qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
342,990 | <p>How can I create an instance of the Java console inside of a GUI panel?</p>
| [
{
"answer_id": 343007,
"author": "Lawrence Dol",
"author_id": 8946,
"author_profile": "https://Stackoverflow.com/users/8946",
"pm_score": 6,
"selected": false,
"text": "PrintStream con=new PrintStream(new TextAreaOutputStream(...));\nSystem.setOut(con);\nSystem.setErr(con);\n run() import java.awt.*;\nimport java.io.*;\nimport java.util.*;\nimport java.util.regex.*;\nimport java.util.List;\nimport javax.swing.*;\n\npublic class TextAreaOutputStream\nextends OutputStream\n{\n\n// *************************************************************************************************\n// INSTANCE PROPERTIES\n// *************************************************************************************************\n\nprivate byte[] oneByte; // array for write(int val);\nprivate Appender appender; // most recent action\n\n// *************************************************************************************************\n// INSTANCE CONSTRUCTORS/INIT/CLOSE/FINALIZE\n// *************************************************************************************************\n\npublic TextAreaOutputStream(JTextArea txtara) {\n this(txtara,1000);\n }\n\npublic TextAreaOutputStream(JTextArea txtara, int maxlin) {\n this(txtara,maxlin,null);\n }\n\npublic TextAreaOutputStream(JTextArea txtara, int maxlin, Pattern rmvptn) {\n if(maxlin<1) { throw new IllegalArgumentException(\"TextAreaOutputStream maximum lines must be positive (value=\"+maxlin+\")\"); }\n oneByte=new byte[1];\n appender=new Appender(txtara,maxlin,rmvptn);\n }\n\n// *************************************************************************************************\n// INSTANCE METHODS - ACCESSORS\n// *************************************************************************************************\n\n/** Clear the current console text area. */\npublic synchronized void clear() {\n if(appender!=null) { appender.clear(); }\n }\n\n// *************************************************************************************************\n// INSTANCE METHODS - OUTPUT STREAM IMPLEMENTATION\n// *************************************************************************************************\n\npublic synchronized void close() {\n appender=null;\n }\n\npublic synchronized void flush() {\n }\n\npublic synchronized void write(int val) {\n oneByte[0]=(byte)val;\n write(oneByte,0,1);\n }\n\npublic synchronized void write(byte[] ba) {\n write(ba,0,ba.length);\n }\n\npublic synchronized void write(byte[] ba,int str,int len) {\n if(appender!=null) { appender.append(bytesToString(ba,str,len)); }\n }\n\n// *************************************************************************************************\n// INSTANCE METHODS - UTILITY\n// *************************************************************************************************\n\n@edu.umd.cs.findbugs.annotations.SuppressWarnings(\"DM_DEFAULT_ENCODING\")\nstatic private String bytesToString(byte[] ba, int str, int len) {\n try { return new String(ba,str,len,\"UTF-8\"); } catch(UnsupportedEncodingException thr) { return new String(ba,str,len); } // all JVMs are required to support UTF-8\n }\n\n// *************************************************************************************************\n// STATIC NESTED CLASSES\n// *************************************************************************************************\n\n static class Appender\n implements Runnable\n {\n private final StringBuilder line = new StringBuilder(1000); // current line being assembled\n private final List<String> lines = new ArrayList<String>(); // lines waiting to be appended\n private final LinkedList<Integer> lengths = new LinkedList<Integer>(); // lengths of each line within text area\n\n private final JTextArea textArea;\n private final int maxLines; // maximum lines allowed in text area\n private final Pattern rmvPattern;\n\n private boolean clear;\n private boolean queue;\n private boolean wrapped;\n\n Appender(JTextArea txtara, int maxlin, Pattern rmvptn) {\n textArea = txtara;\n maxLines = maxlin;\n rmvPattern = rmvptn;\n\n clear = false;\n queue = true;\n wrapped = false;\n }\n\n synchronized void append(String val) {\n boolean eol = val.endsWith(EOL1) || val.endsWith(EOL2);\n\n line.append(val);\n while(line.length()>LINE_MAX) {\n emitLine(line.substring(0,LINE_MAX)+EOL1);\n line.replace(0,LINE_MAX,\"[>>] \");\n }\n if(eol) {\n emitLine(line.toString());\n line.setLength(0);\n }\n }\n\n private void emitLine(String lin) {\n if(lines.size()>10_000) {\n lines.clear();\n lines.add(\"<console-overflowed>\\n\");\n }\n else {\n if(rmvPattern!=null) { lin = rmvPattern.matcher(lin).replaceAll(\"\"); }\n lines.add(lin);\n }\n if(queue) {\n queue=false;\n EventQueue.invokeLater(this);\n }\n }\n\n synchronized void clear() {\n clear = true;\n if(queue) { queue = false; EventQueue.invokeLater(this); }\n wrapped = false;\n }\n\n // MUST BE THE ONLY METHOD THAT TOUCHES textArea!\n public synchronized void run() {\n int don = 0;\n\n if(clear) {\n lengths . clear();\n lines . clear();\n textArea . setText(\"\");\n clear = false;\n }\n\n for(String lin: lines) {\n don += 1;\n lengths.addLast(lin.length());\n if(lengths.size()>=maxLines) { textArea.replaceRange(\"\",0,lengths.removeFirst()); }\n textArea.append(lin);\n if(don>=100) { break; }\n }\n if(don==lines.size()) {\n lines.clear();\n queue = true;\n }\n else {\n lines.subList(0,don).clear();\n EventQueue.invokeLater(this);\n }\n }\n\n static private final String EOL1 = \"\\n\";\n static private final String EOL2 = System.getProperty(\"line.separator\",EOL1);\n static private final int LINE_MAX = 1000;\n}\n"
},
{
"answer_id": 343084,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": false,
"text": "import javax.swing.*;\nimport java.awt.*;\nimport java.awt.event.*;\nimport java.io.*;\n\npublic class Main{\n public static void main( String [] args ) throws InterruptedException {\n JFrame frame = new JFrame();\n frame.add( new JLabel(\" Outout\" ), BorderLayout.NORTH );\n\n JTextArea ta = new JTextArea();\n TextAreaOutputStream taos = new TextAreaOutputStream( ta, 60 );\n PrintStream ps = new PrintStream( taos );\n System.setOut( ps );\n System.setErr( ps );\n\n\n frame.add( new JScrollPane( ta ) );\n\n frame.pack();\n frame.setVisible( true );\n frame.setSize(800,600);\n\n for( int i = 0 ; i < 100 ; i++ ) {\n System.out.println( i );\n Thread.sleep( 500 );\n }\n }\n}\n"
},
{
"answer_id": 12938749,
"author": "Derive McNeill",
"author_id": 1753832,
"author_profile": "https://Stackoverflow.com/users/1753832",
"pm_score": 2,
"selected": false,
"text": "import java.io.IOException;\nimport java.io.OutputStream;\nimport java.util.ArrayList;\n\nimport javax.swing.JTextArea;\n\n/**\n * Represents a console viewable through a <code>JTextArea</code>.\n * \n * <p>\n * Implementation:\n * <code>\n * System.setOut(new PrintStream(new Console( ... )));\n * </code>\n * </p>\n * \n * @author Derive McNeill\n *\n */\npublic class Console extends OutputStream {\n\n /**\n * Represents the data written to the stream.\n */\n ArrayList <Byte> data = new ArrayList <Byte> ();\n\n /**\n * Represents the text area that will be showing the written data.\n */\n private JTextArea output;\n\n /**\n * Creates a console context.\n * @param output\n * The text area to output the consoles text.\n */\n public Console(JTextArea output) {\n this.output = output;\n }\n\n /**\n * Called when data has been written to the console.\n */\n private void fireDataWritten() {\n\n // First we loop through our written data counting the lines.\n int lines = 0;\n for (int i = 0; i < data.size(); i++) {\n byte b = data.get(i);\n\n // Specifically we look for 10 which represents \"\\n\".\n if (b == 10) {\n lines++;\n }\n\n // If the line count exceeds 250 we remove older lines.\n if (lines >= 250) {\n data = (ArrayList<Byte>) data.subList(i, data.size());\n }\n }\n\n // We then create a string builder to append our text data.\n StringBuilder bldr = new StringBuilder();\n\n // We loop through the text data appending it to the string builder.\n for (byte b : data) {\n bldr.append((char) b);\n }\n\n // Finally we set the outputs text to our built string.\n output.setText(bldr.toString());\n }\n\n @Override\n public void write(int i) throws IOException {\n\n // Append the piece of data to our array of data.\n data.add((byte) i);\n\n // Indicate that data has just been written.\n fireDataWritten();\n }\n\n}\n"
},
{
"answer_id": 13321464,
"author": "snipsnipsnip",
"author_id": 188256,
"author_profile": "https://Stackoverflow.com/users/188256",
"pm_score": 2,
"selected": false,
"text": "private void redirectConsoleTo(final JTextArea textarea) {\n PrintStream out = new PrintStream(new ByteArrayOutputStream() {\n public synchronized void flush() throws IOException {\n textarea.setText(toString());\n }\n }, true);\n\n System.setErr(out);\n System.setOut(out);\n}\n private void redirectConsoleWithClearButton(final JTextArea textarea, JButton clearButton) {\n final ByteArrayOutputStream bytes = new ByteArrayOutputStream() {\n public synchronized void flush() throws IOException {\n textarea.setText(toString());\n }\n };\n\n clearButton.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e) {\n bytes.reset();\n }\n });\n\n PrintStream out = new PrintStream(bytes, true);\n\n System.setErr(out);\n System.setOut(out);\n}\n"
},
{
"answer_id": 27737289,
"author": "Stephan",
"author_id": 363573,
"author_profile": "https://Stackoverflow.com/users/363573",
"pm_score": 1,
"selected": false,
"text": "JTextarea JLabel JTextarea import java.awt.EventQueue;\nimport java.io.OutputStream;\nimport java.io.UnsupportedEncodingException;\nimport java.util.ArrayList;\nimport java.util.LinkedList;\nimport java.util.List;\nimport java.util.concurrent.locks.Lock;\nimport java.util.concurrent.locks.ReentrantLock;\n\nimport javax.swing.JComponent;\n\npublic class JComponentOutputStream extends OutputStream {\n\n // *************************************************************************************************\n // INSTANCE MEMBERS\n // *************************************************************************************************\n\n private byte[] oneByte; // array for write(int val);\n private Appender appender; // most recent action\n\n private Lock jcosLock = new ReentrantLock();\n\n public JComponentOutputStream(JComponent txtara, JComponentHandler handler) {\n this(txtara, 1000, handler);\n }\n\n public JComponentOutputStream(JComponent txtara, int maxlin, JComponentHandler handler) {\n if (maxlin < 1) {\n throw new IllegalArgumentException(\"JComponentOutputStream maximum lines must be positive (value=\" + maxlin + \")\");\n }\n oneByte = new byte[1];\n appender = new Appender(txtara, maxlin, handler);\n }\n\n /** Clear the current console text area. */\n public void clear() {\n jcosLock.lock();\n try {\n if (appender != null) {\n appender.clear();\n }\n } finally {\n jcosLock.unlock();\n }\n }\n\n public void close() {\n jcosLock.lock();\n try {\n appender = null;\n } finally {\n jcosLock.unlock();\n }\n }\n\n public void flush() {\n // sstosLock.lock();\n // try {\n // // TODO: Add necessary code here...\n // } finally {\n // sstosLock.unlock();\n // }\n }\n\n public void write(int val) {\n jcosLock.lock();\n try {\n oneByte[0] = (byte) val;\n write(oneByte, 0, 1);\n } finally {\n jcosLock.unlock();\n }\n }\n\n public void write(byte[] ba) {\n jcosLock.lock();\n try {\n write(ba, 0, ba.length);\n } finally {\n jcosLock.unlock();\n }\n }\n\n public void write(byte[] ba, int str, int len) {\n jcosLock.lock();\n try {\n if (appender != null) {\n appender.append(bytesToString(ba, str, len));\n }\n } finally {\n jcosLock.unlock();\n }\n }\n\n static private String bytesToString(byte[] ba, int str, int len) {\n try {\n return new String(ba, str, len, \"UTF-8\");\n } catch (UnsupportedEncodingException thr) {\n return new String(ba, str, len);\n } // all JVMs are required to support UTF-8\n }\n\n // *************************************************************************************************\n // STATIC MEMBERS\n // *************************************************************************************************\n\n static class Appender implements Runnable {\n private final JComponent swingComponent;\n private final int maxLines; // maximum lines allowed in text area\n private final LinkedList<Integer> lengths; // length of lines within\n // text area\n private final List<String> values; // values waiting to be appended\n\n private int curLength; // length of current line\n private boolean clear;\n private boolean queue;\n\n private Lock appenderLock;\n\n private JComponentHandler handler;\n\n Appender(JComponent cpt, int maxlin, JComponentHandler hndlr) {\n appenderLock = new ReentrantLock();\n\n swingComponent = cpt;\n maxLines = maxlin;\n lengths = new LinkedList<Integer>();\n values = new ArrayList<String>();\n\n curLength = 0;\n clear = false;\n queue = true;\n\n handler = hndlr;\n }\n\n void append(String val) {\n appenderLock.lock();\n try {\n values.add(val);\n if (queue) {\n queue = false;\n EventQueue.invokeLater(this);\n }\n } finally {\n appenderLock.unlock();\n }\n }\n\n void clear() {\n appenderLock.lock();\n try {\n\n clear = true;\n curLength = 0;\n lengths.clear();\n values.clear();\n if (queue) {\n queue = false;\n EventQueue.invokeLater(this);\n }\n } finally {\n appenderLock.unlock();\n }\n }\n\n // MUST BE THE ONLY METHOD THAT TOUCHES the JComponent!\n public void run() {\n appenderLock.lock();\n try {\n if (clear) {\n handler.setText(swingComponent, \"\");\n }\n for (String val : values) {\n curLength += val.length();\n if (val.endsWith(EOL1) || val.endsWith(EOL2)) {\n if (lengths.size() >= maxLines) {\n handler.replaceRange(swingComponent, \"\", 0, lengths.removeFirst());\n }\n lengths.addLast(curLength);\n curLength = 0;\n }\n handler.append(swingComponent, val);\n }\n\n values.clear();\n clear = false;\n queue = true;\n } finally {\n appenderLock.unlock();\n }\n }\n\n static private final String EOL1 = \"\\n\";\n static private final String EOL2 = System.getProperty(\"line.separator\", EOL1);\n }\n\n public interface JComponentHandler {\n void setText(JComponent swingComponent, String text);\n\n void replaceRange(JComponent swingComponent, String text, int start, int end);\n\n void append(JComponent swingComponent, String text);\n }\n\n} /* END PUBLIC CLASS */\n JLabel console = new JLabel();\nJComponentOutputStream consoleOutputStream = new JComponentOutputStream(console, new JComponentHandler() {\n private StringBuilder sb = new StringBuilder();\n\n @Override\n public void setText(JComponent swingComponent, String text) {\n sb.delete(0, sb.length());\n append(swingComponent, text);\n }\n\n @Override\n public void replaceRange(JComponent swingComponent, String text, int start, int end) {\n sb.replace(start, end, text);\n redrawTextOf(swingComponent);\n }\n\n @Override\n public void append(JComponent swingComponent, String text) {\n sb.append(text);\n redrawTextOf(swingComponent);\n }\n\n private void redrawTextOf(JComponent swingComponent) {\n ((JLabel)swingComponent).setText(\"<html><pre>\" + sb.toString() + \"</pre></html>\");\n }\n});\n\nPrintStream con = new PrintStream(consoleOutputStream);\nSystem.setOut(con);\nSystem.setErr(con); \n\n// Optional: add a scrollpane around the console for having scrolling bars\nJScrollPane sp = new JScrollPane( //\n console, //\n ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, //\n ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED //\n);\nmyPanel.add(sp);\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
342,994 | <p>How do I download a file from the internet in a Flex based AIR application. </p>
<p>I tried using a file with url set to the address, but I got a file does not exist error when I tried to save it. And it is really hard to google for help on this issue.</p>
| [
{
"answer_id": 343587,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 0,
"selected": false,
"text": "flash.net.URLRequest"
},
{
"answer_id": 414226,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 3,
"selected": false,
"text": "downloadFile: function (url, fileName) {\n var urlStream = new air.URLStream();\n var request = new air.URLRequest(url);\n var fileStream = new air.FileStream();\n // write 50k from the urlstream to the filestream, unless\n // the writeAll flag is true, when you write everything in the buffer\n function writeFile(writeAll) {\n if (urlStream.bytesAvailable > 51200 || writeAll) {\n alert(\"got some\");\n var dataBuffer = new air.ByteArray();\n urlStream.readBytes(dataBuffer, 0, urlStream.bytesAvailable);\n fileStream.writeBytes(dataBuffer, 0, dataBuffer.length);\n }\n // do clean up:\n if (writeAll) {\n alert(\"done\");\n fileStream.close();\n urlStream.close();\n // set up the next download\n setTimeout(this.downloadNextFile.bind(this), 0);\n }\n }\n\n urlStream.addEventListener(air.Event.COMPLETE, writeFile.bind(this, true));\n urlStream.addEventListener(air.ProgressEvent.PROGRESS, writeFile.bind(this, false));\n\n var file = air.File.desktopDirectory.resolvePath(fileName);\n fileStream.openAsync(file, air.FileMode.WRITE);\n\n urlStream.load(request);\n\n}\n"
},
{
"answer_id": 1805477,
"author": "AlexH",
"author_id": 40397,
"author_profile": "https://Stackoverflow.com/users/40397",
"pm_score": 4,
"selected": false,
"text": "var downloader = new FileDownloader(\"url\", \"Local/Path\"); downloader.load() package com.alex{\nimport flash.filesystem.File;\nimport flash.filesystem.FileMode;\nimport flash.filesystem.FileStream;\nimport flash.net.URLRequest;\nimport flash.net.URLStream;\nimport flash.utils.ByteArray;\n\npublic class FileDownloader\n{\n\n // Class to download files from the internet\n\n // Function called every time data arrives\n // called with an argument of how much has been downloaded\n public var onProgress :Function = function(t:uint):void{};\n public var onComplete :Function = function():void{};\n public var remotePath :String = \"\";\n public var localFile :File = null; \n\n private var stream :URLStream;\n private var fileAccess :FileStream;\n\n public function FileDownloader( remotePath :String = \"\" , localFile :File = null ) {\n\n this.remotePath = remotePath;\n this.localFile = localFile;\n }\n\n public function load() :void {\n if( !stream || !stream.connected ) {\n stream = new URLStream();\n fileAccess = new FileStream();\n\n var requester :URLRequest = new URLRequest( remotePath );\n var currentPosition :uint = 0;\n var downloadCompleteFlag :Boolean = false;\n\n // Function to call oncomplete, once the download finishes and\n // all data has been written to disc \n fileAccess.addEventListener( \"outputProgress\", function ( result ) :void {\n if( result.bytesPending == 0 && downloadCompleteFlag ) {\n\n stream.close();\n fileAccess.close();\n onComplete();\n }\n });\n\n fileAccess.openAsync( localFile, FileMode.WRITE );\n\n stream.addEventListener( \"progress\" , function () :void {\n\n var bytes :ByteArray = new ByteArray();\n var thisStart :uint = currentPosition;\n currentPosition += stream.bytesAvailable;\n // ^^ Makes sure that asyncronicity does not break anything\n\n stream.readBytes( bytes, thisStart );\n fileAccess.writeBytes( bytes, thisStart );\n\n onProgress( currentPosition ); \n });\n\n stream.addEventListener( \"complete\", function () :void {\n downloadCompleteFlag = true;\n });\n\n stream.load( requester );\n\n } else {\n // Do something unspeakable\n }\n }\n}}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/342994",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40397/"
] |
343,014 | <p>I have a custom error page set up for my application:</p>
<pre><code><customErrors mode="On" defaultRedirect="~/errors/GeneralError.aspx"
/>
</code></pre>
<p>In Global.asax, Application_Error(), the following code works to get the exception details:</p>
<pre><code> Exception ex = Server.GetLastError();
if (ex != null)
{
if (ex.GetBaseException() != null)
ex = ex.GetBaseException();
}
</code></pre>
<p>By the time I get to my error page (~/errors/GeneralError.aspx.cs), Server.GetLastError() is null</p>
<p>Is there any way I can get the exception details on the Error Page, rather than in Global.asax.cs ?</p>
<p>ASP.NET 3.5 on Vista/IIS7</p>
| [
{
"answer_id": 343056,
"author": "nailitdown",
"author_id": 40934,
"author_profile": "https://Stackoverflow.com/users/40934",
"pm_score": 8,
"selected": true,
"text": "customErrors <customErrors mode=\"RemoteOnly\" defaultRedirect=\"~/errors/GeneralError.aspx\" redirectMode=\"ResponseRewrite\" />\n ResponseRewrite"
},
{
"answer_id": 344871,
"author": "rlb.usa",
"author_id": 449902,
"author_profile": "https://Stackoverflow.com/users/449902",
"pm_score": 4,
"selected": false,
"text": " void Application_Error(object sender, EventArgs e) \n{\n // Code that runs when an unhandled error occurs\n Exception ex = Server.GetLastError();\n Application[\"TheException\"] = ex; //store the error for later\n Server.ClearError(); //clear the error so we can continue onwards\n Response.Redirect(\"~/myErrorPage.aspx\"); //direct user to error page\n}\n <system.web>\n <customErrors mode=\"RemoteOnly\" defaultRedirect=\"~/myErrorPage.aspx\">\n </customErrors>\n </system.web>\n protected void Page_Load(object sender, EventArgs e)\n{\n\n // ... do stuff ...\n //we caught an exception in our Global.asax, do stuff with it.\n Exception caughtException = (Exception)Application[\"TheException\"];\n //... do stuff ...\n}\n"
},
{
"answer_id": 780314,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "Server.Transfer(\"~/ErrorPage.aspx\"); Application_Error() Page_Load() Exception exception = Server.GetLastError().GetBaseException(); Server.Transfer()"
},
{
"answer_id": 7586126,
"author": "user825345",
"author_id": 825345,
"author_profile": "https://Stackoverflow.com/users/825345",
"pm_score": 3,
"selected": false,
"text": "void Application_Error(object sender, EventArgs e)\n {\n // Code that runs when an unhandled error occurs\n\n //direct user to error page \n Server.Transfer(\"~/ErrorPages/Oops.aspx\"); \n }\n protected void Page_Load(object sender, EventArgs e)\n {\n if (!IsPostBack)\n LoadError(Server.GetLastError()); \n }\n\n protected void LoadError(Exception objError)\n {\n if (objError != null)\n {\n StringBuilder lasterror = new StringBuilder();\n\n if (objError.Message != null)\n {\n lasterror.AppendLine(\"Message:\");\n lasterror.AppendLine(objError.Message);\n lasterror.AppendLine();\n }\n\n if (objError.InnerException != null)\n {\n lasterror.AppendLine(\"InnerException:\");\n lasterror.AppendLine(objError.InnerException.ToString());\n lasterror.AppendLine();\n }\n\n if (objError.Source != null)\n {\n lasterror.AppendLine(\"Source:\");\n lasterror.AppendLine(objError.Source);\n lasterror.AppendLine();\n }\n\n if (objError.StackTrace != null)\n {\n lasterror.AppendLine(\"StackTrace:\");\n lasterror.AppendLine(objError.StackTrace);\n lasterror.AppendLine();\n }\n\n ViewState.Add(\"LastError\", lasterror.ToString());\n }\n }\n\n protected void btnReportError_Click(object sender, EventArgs e)\n {\n SendEmail();\n }\n\n public void SendEmail()\n {\n try\n {\n MailMessage msg = new MailMessage(\"webteam\", \"webteam\");\n StringBuilder body = new StringBuilder();\n\n body.AppendLine(\"An unexcepted error has occurred.\");\n body.AppendLine();\n\n body.AppendLine(ViewState[\"LastError\"].ToString());\n\n msg.Subject = \"Error\";\n msg.Body = body.ToString();\n msg.IsBodyHtml = false;\n\n SmtpClient smtp = new SmtpClient(\"exchangeserver\");\n smtp.Send(msg);\n }\n\n catch (Exception ex)\n {\n lblException.Text = ex.Message;\n }\n }\n"
},
{
"answer_id": 41164924,
"author": "Bao",
"author_id": 7302142,
"author_profile": "https://Stackoverflow.com/users/7302142",
"pm_score": 2,
"selected": false,
"text": "Server.Transfer() or Response.Redirect() <customErrors defaultRedirect=\"errorHandler.aspx\" mode=\"On\" />\n void Application_Error(object sender, EventArgs e)\n {\n if(Context.IsCustomErrorEnabled)\n { \n Exception ex = Server.GetLastError();\n Application[\"TheException\"] = ex; //store the error for later\n }\n }\n protected void Page_Load(object sender, EventArgs e)\n { \n string htmlErrorMessage = string.Empty ;\n Exception ex = (Exception)Application[\"TheException\"];\n string yourSessionValue = HttpContext.Current.Session[\"YourSessionId\"].ToString();\n\n //continue with ex to get htmlErrorMessage \n if(ex.GetHtmlErrorMessage() != null){ \n htmlErrorMessage = ex.GetHtmlErrorMessage();\n } \n // continue your code\n }\n"
},
{
"answer_id": 41786763,
"author": "M.R.T",
"author_id": 6778726,
"author_profile": "https://Stackoverflow.com/users/6778726",
"pm_score": 2,
"selected": false,
"text": "~\\Global.asax void Application_Error(object sender, EventArgs e)\n{\n FTools.LogException();\n Response.Redirect(\"/Error\");\n}\n ~\\Controllers ErrorController.cs using System.Web.Mvc;\n\nnamespace MVC_WebApp.Controllers\n{\n public class ErrorController : Controller\n {\n // GET: Error\n public ActionResult Index()\n {\n return View(\"Error\");\n }\n }\n}\n ~\\Models FunctionTools.cs using System;\nusing System.Web;\n\nnamespace MVC_WebApp.Models\n{\n public static class FTools\n {\n private static string _error;\n private static bool _isError;\n\n public static string GetLastError\n {\n get\n {\n string cashe = _error;\n HttpContext.Current.Server.ClearError();\n _error = null;\n _isError = false;\n return cashe;\n }\n }\n public static bool ThereIsError => _isError;\n\n public static void LogException()\n {\n Exception exc = HttpContext.Current.Server.GetLastError();\n if (exc == null) return;\n string errLog = \"\";\n errLog += \"**********\" + DateTime.Now + \"**********\\n\";\n if (exc.InnerException != null)\n {\n errLog += \"Inner Exception Type: \";\n errLog += exc.InnerException.GetType() + \"\\n\";\n errLog += \"Inner Exception: \";\n errLog += exc.InnerException.Message + \"\\n\";\n errLog += \"Inner Source: \";\n errLog += exc.InnerException.Source + \"\\n\";\n if (exc.InnerException.StackTrace != null)\n {\n errLog += \"\\nInner Stack Trace: \" + \"\\n\";\n errLog += exc.InnerException.StackTrace + \"\\n\";\n }\n }\n errLog += \"Exception Type: \";\n errLog += exc.GetType().ToString() + \"\\n\";\n errLog += \"Exception: \" + exc.Message + \"\\n\";\n errLog += \"\\nStack Trace: \" + \"\\n\";\n if (exc.StackTrace != null)\n {\n errLog += exc.StackTrace + \"\\n\";\n }\n _error = errLog;\n _isError = true;\n }\n }\n}\n ~\\Views Error ~\\Views\\Error Error.cshtml @using MVC_WebApp.Models\n@{\n ViewBag.Title = \"Error\";\n if (FTools.ThereIsError == false)\n {\n if (Server.GetLastError() != null)\n {\n FTools.LogException();\n }\n }\n if (FTools.ThereIsError == false)\n {\n <br />\n <h1>No Problem!</h1>\n }\n else\n {\n string log = FTools.GetLastError;\n <div>@Html.Raw(log.Replace(\"\\n\", \"<br />\"))</div>\n }\n}\n localhost/Error"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40934/"
] |
343,035 | <p>I have a program that writes to a FILE *cgiOut and just after it has written to the stream, I need to fork and run a background process. The trouble is that after the fork, the FILE * stream seems to flush out sometimes and I get duplicated output (after the fork, all open files are closed which I guess causes the buffers to be flushed). How can I avoid this? I don't want to close the file in the master process as it is opened in a library and it is a socket or pipe I think.</p>
| [
{
"answer_id": 343066,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 4,
"selected": true,
"text": "cgiOut fork() fflush() fork() setvbuf()"
},
{
"answer_id": 343067,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 0,
"selected": false,
"text": "fflush(file)"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343035",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20889/"
] |
343,039 | <p>I need to retrieve the browser and OS through php coding.</p>
<p>I had used <code>$_SERVER['HTTP_USER_AGENT']</code>, but its shows the following </p>
<pre><code>Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; IEMB3)
</code></pre>
<p>How can I separate the browser and OS from the above received value?</p>
<p>Please guide me..</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 343057,
"author": "lfx",
"author_id": 43164,
"author_profile": "https://Stackoverflow.com/users/43164",
"pm_score": -1,
"selected": false,
"text": "<?php\n$ex=explode(' ',$_SERVER['HTTP_USER_AGENT']);\necho 'OS: '.$ex[4].' '.$ex[5].' '.$ex[6].'/n'; \necho 'Browser: '.$ex[0]; \n?> \n"
},
{
"answer_id": 343071,
"author": "user37125",
"author_id": 37125,
"author_profile": "https://Stackoverflow.com/users/37125",
"pm_score": 2,
"selected": false,
"text": "require('Browscap.php');\n$browscap = new Browscap('/path/to/cache');\nvar_dump($browscap->getBrowser());\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38172/"
] |
343,061 | <p>I have the need/desire to learn to program against Win32 in C++. I am a little confused as to what Win32 even is, as I have no experience on the platform. </p>
<p>What would you recommend to get me started programming and debugging C++ programs on Win32?</p>
| [
{
"answer_id": 343106,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 6,
"selected": false,
"text": "do_something.exe do_something printf"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41522/"
] |
343,075 | <p>I want to write my own little chat server in C on a MacOS machine. Now I want to connect to all clients, that are online and let the connection open, to be able to receive and send messages. The problem is that I only know, how to have one socket connection at a time open. So only one client can connect so far and chatting like that is kinda boring ;)</p>
| [
{
"answer_id": 343081,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "select(2) select(2)"
},
{
"answer_id": 343172,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 0,
"selected": false,
"text": "accept() select() poll() select() select()"
},
{
"answer_id": 344454,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "int listen_fd, new_fd;\n\nwhile ((new_fd = accept(listen_fd, NULL, NULL)) != -1) {\n if (fork())\n close(new_fd);\n else\n // handle client connection\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25017/"
] |
343,078 | <p>If have created a custom role within SqlServer which I added to the db__denydatareader and db__denydatawriter roles. I think went through the db and granted exec permission to all neccersary stored procedures. </p>
<p>Everything works fine, calling those sps will run fine. The one exception is a stored procedure which executes dynamic sql by using sp_executesql. This fails saying </p>
<pre><code>The SELECT permission was denied on the object 'listing_counter', database 'Cannla', schema 'dbo'.
</code></pre>
<p>Is there any way to grant the role permission to run this query without giving it select access to the underlying tables?</p>
<p>I guess what I'm wanting to do is grant exec on sys.sp_executesql but only in a certain case.</p>
| [
{
"answer_id": 343090,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 0,
"selected": false,
"text": " [ , [ @datasrc= ] 'data_source' ] \n [ , [ @location= ] 'location' ] \n [ , [ @provstr= ] 'provider_string' ] \n [ , [ @catalog= ] 'catalog' ] \n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
] |
343,085 | <p>In IOC's what does <code>ResolveAll</code> do?? I know that the offical answer is "Resolve all valid components that match this type." Does that mean that it will return any class that implements a given interface?</p>
| [
{
"answer_id": 2726982,
"author": "LukeN",
"author_id": 98313,
"author_profile": "https://Stackoverflow.com/users/98313",
"pm_score": 2,
"selected": false,
"text": "container.RegisterType<IInterface, ActualClassOne>(new ContainerControlledLifetimeManager());\ncontainer.RegisterType<IInterface, ActualClassOne>(\"Singleton\", new ContainerControlledLifetimeManager());\ncontainer.RegisterType<IInterface, ActualClassOne>(\"Trans\", new TransientLifetimeManager());\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30572/"
] |
343,088 | <p>I am writing an Objective-C application which communicates with a USB device. The application writes certain data to the device continuously and displays the status of the write operation in a textView, which is an object of NSTextView. I call the <code>-[NSTextView insertText:]</code> method in the loop when I get the write operation status from the device.</p>
<p>The problem is that the NSTextView doesn't get updated at every call of <code>-insertText:</code>. I get the entire contents of the NSTextView only after the entire loop has been executed.</p>
<p>I didn't see an appropriate refresh or update method for NSTextView class. How can I recieve the status of the operation and update the NSTextView simultaneously?</p>
<pre><code>- (IBAction)notifyContentHasChanged:(NSInteger) block {
NSString *str;
str = [NSString stringWithFormat:@"Block Written Successfully: %d\n", block];
[data insertText:str];
}
- (IBAction)func {
while(USB_SUCCESS(status))
{
printf("\nBlocks Written Successfully: %d",BlockCnt);
[refToSelf notifyContentHasChanged:BlockCnt];
}
}
</code></pre>
<p>Note that the <code>printf</code> on console is updated timely but not the NSTextView.</p>
| [
{
"answer_id": 343135,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "select(2)"
},
{
"answer_id": 16124620,
"author": "Phillip Boushy",
"author_id": 1399529,
"author_profile": "https://Stackoverflow.com/users/1399529",
"pm_score": 1,
"selected": false,
"text": "//Creates the background thread.\ndispatch_queue_t backgroundQueue = dispatch_queue_create(\"Network\", nil);\n //Runs code in background thread.\ndispatch_async(backgroundQueue, ^(void){\n //Code Here.\n});\n //Sends code within the background thread to the main thread.\ndispatch_async(dispatch_get_main_queue(), ^(void){\n //Code Here.\n});\n - (IBAction)notifyContentHasChanged:(NSInteger) block {\n NSString *str;\n str = [NSString stringWithFormat:@\"Block Written Successfully: %d\\n\", block];\n [data insertText:str];\n}\n\n- (IBAction)func {\n dispatch_queue_t backgroundQueue = dispatch_queue_create(\"Network\", nil);\n dispatch_async(backgroundQueue, ^(void){\n while(USB_SUCCESS(status))\n {\n printf(\"\\nBlocks Written Successfully: %d\",BlockCnt);\n dispatch_async(dispatch_get_main_queue(), ^(void){\n [refToSelf notifyContentHasChanged:BlockCnt];\n });\n }\n });\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39270/"
] |
343,100 | <p>I have an assembly. Is there a way to detect which version of .NET was used to build that assembly?</p>
| [
{
"answer_id": 343179,
"author": "Julien Hoarau",
"author_id": 12248,
"author_profile": "https://Stackoverflow.com/users/12248",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Reflection;\n\nclass Module1\n{\n\n public static void CheckReferencedAssemblies(string assemblyPath)\n {\n Assembly a = Assembly.Load(assemblyPath);\n\n foreach (AssemblyName an in a.GetReferencedAssemblies() )\n {\n // Check an.Version for System assemblies\n }\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191/"
] |
343,101 | <p>Let me start off by saying that I know there is probably a much simpler way to do this.
But this is what i have and yes hopefully I can make some improvements and/or simplifications at the end.</p>
<p><strong>Goal as of this moment</strong></p>
<p>To double space the output stored in the <code>$tmp</code> variable below and individually number each line. Doing this should give me each set of executable commands on separate lines.</p>
<p><em>Problem 1</em></p>
<p>I've tried everything that I can think of to double space what's in the variable. Moving the double space command around, and changing the command itself.</p>
<p>To number the files I've tried to modify this code:</p>
<pre><code> sed = filename | sed 'N; s/^/ /; s/ *\(.\{6,\}\)\n/\1 /
</code></pre>
<p>And of course experimented around with awk but no progress..</p>
<p><strong>Not so Long Term Goals</strong></p>
<ul>
<li>To execute these commands one by one and compare the difference in bytes. Or just any general difference. I know at this point I can use the diff command with <code>file1 file2</code> and then save the output in some variable like: <code>"$diffA $diffB"</code> and updating it each time using a loop for the chance that more than 2 files are passed as arguments.</li>
<li>To tell the difference between each command line. And echo something like:</li>
</ul>
<blockquote>
<p>line 1 in file1 is different from line 1 in file2, check it out: "$diffA $diffB"</p>
</blockquote>
<p>Here is what i have so far, its a start:</p>
<pre><code>#!/bin/bash
FILE="$1"
echo "You Entered $FILE"
if [ -f $FILE ]; then
tmp=$(cat $FILE | sed '/./!d' | sed -n '/regex/,/regex/{/regex/d;p}'| sed -n '/---/,+2!p' | sed -n '/#/!p' | sed 's/^[ ]*//' | sed -e\
s/[^:]*:// | sed -n '/regex /!p' | sed -n '/regex /!p' | sed -n '/"regex"/,+1!p' | sed -n '/======/!p' | sed -n '/regex/!p' | sed -n '/regex\
\r/!p' | sed -n '/regex /!p' )
fi
MyVar=$(echo $tmp)
echo "$MyVar | sed G"
FILE2="$2"
if [ -f $FILE2 ]; then
if [ -f $FILE2 ]; then
tmp2=$(cat $FILE2 | sed -n '/regex/,/regex/{/regex\ S/d;p}' |\
sed -n '/#/!p' | sed -e s/[^:]*:// | sed /--------/,+10d)
fi
echo "$tmp2"
</code></pre>
<p>Any help is very much appreciated.</p>
| [
{
"answer_id": 343592,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 1,
"selected": false,
"text": "awk ' { print NF \" \" $0; print \"\"; }'\n ( echo a; echo b) | awk ' { print NR \" \" $0; print \"\"; }'\n 1 a\n\n2 b\n tmp=$(( echo a; echo b) | awk ' { print NR \" \" $0; print \"\"; }')\necho \"$tmp\"\n 1 a 2 b\n tmp=$(mktemp)\nawk ' { print NR \" \" $0; print \"\"; }' $FILE > $tmp\ncat $tmp # Do something with the file\nrm $tmp # Don't forget to clean up after yourself.\n"
},
{
"answer_id": 1851878,
"author": "meingbg",
"author_id": 225353,
"author_profile": "https://Stackoverflow.com/users/225353",
"pm_score": 0,
"selected": false,
"text": "tmp=\"$(echo a; echo b)\"\necho \"$tmp\"\n"
},
{
"answer_id": 8628482,
"author": "potong",
"author_id": 967492,
"author_profile": "https://Stackoverflow.com/users/967492",
"pm_score": 0,
"selected": false,
"text": "a=$(printf \"aaa %d\\n\" {1..5} | sed = | sed 'N;s/\\n//;G')\necho $a\n1aaa 1 2aaa 2 3aaa 3 4aaa 4 5aaa 5\necho \"$a\"\n1aaa 1\n\n2aaa 2\n\n3aaa 3\n\n4aaa 4\n\n5aaa 5\n sed = sed 'N's/\\n//;G' s/\\n// G"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40120/"
] |
343,111 | <p>I am writing a client-side validation function for <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator.aspx" rel="nofollow noreferrer">CustomValidator</a> and I need to check length of entered string. But before, to counteract cheaters a little, I want to remove all leading and trailing spaces from the string. What is the easiest way to do it in this scenario?</p>
<p>Thank you!</p>
| [
{
"answer_id": 343127,
"author": "J Cooper",
"author_id": 38803,
"author_profile": "https://Stackoverflow.com/users/38803",
"pm_score": 2,
"selected": false,
"text": "trim function trim( text ) {\n return (text || \"\").replace( /^\\s+|\\s+$/g, \"\" );\n}\n"
},
{
"answer_id": 343149,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 0,
"selected": false,
"text": "function RequiredFieldValidatorEvaluateIsValid(val) {\n return (ValidatorTrim(ValidatorGetValue(val.controltovalidate)) != \n ValidatorTrim(val.initialvalue))\n}\n function ValidatorTrim(s) {\n var m = s.match(/^\\s*(\\S+(\\s+\\S+)*)\\s*$/);\n return (m == null) ? \"\" : m[1];\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
] |
343,115 | <p>I'm trying to find a way to make a list of everything between <code><a></code> and <code></a></code> tags. So I have a list of links and I want to get the names of the links (not where the links go, but what they're called on the page). Would be really helpful to me.</p>
<p>Currently I have this:</p>
<pre><code>$lines = preg_split("/\r?\n|\r/", $content); // content is the given page
foreach ($lines as $val) {
if (preg_match("/(<A(.*)>)(<\/A>)/", $val, $alink)) {
$newurl = $alink[1];
// put in array of found links
$links[$index] = $newurl;
$index++;
$is_href = true;
}
}
</code></pre>
| [
{
"answer_id": 343174,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<a\\b[^>]*>(.*?)</a> // match group one will contain the link text\n"
},
{
"answer_id": 343233,
"author": "Jørn Jensen",
"author_id": 34585,
"author_profile": "https://Stackoverflow.com/users/34585",
"pm_score": 0,
"selected": false,
"text": "m!<a .*?>(.*?)</a>!i\n"
},
{
"answer_id": 343279,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 2,
"selected": false,
"text": "<a\\s*(.*)\\>(.*)</a>\n\n<a href=\"http://www.stackoverflow.com\">Go to stackoverflow.com</a>\n"
},
{
"answer_id": 17044488,
"author": "Avram Cosmin",
"author_id": 903224,
"author_profile": "https://Stackoverflow.com/users/903224",
"pm_score": 0,
"selected": false,
"text": "$pattern = '#<a[^>]*>([^<]*)<\\/a>#';\n$subject = '<a href=\"#\">Link 1</a> <a href=\"#\">Link 3</a> <a href=\"#\">Link 3</a>';\npreg_match_all($pattern, $subject, $matches);\nprint_r($matches[1]);\n $pattern = '#<a[^>]*>(.*?)<\\/a>#';\n$subject = '<a href=\"#\">2 > 1</a> <a href=\"#\">1 < 2</a>';\npreg_match_all($pattern, $subject, $matches);\n Array (\n [0] => Link 1\n [1] => Link 3\n [2] => Link 3\n)\n"
},
{
"answer_id": 17280701,
"author": "Juan José Brown",
"author_id": 1390440,
"author_profile": "https://Stackoverflow.com/users/1390440",
"pm_score": 0,
"selected": false,
"text": "'<a.*?>(.*?)</a>'\n ['sign up', 'log in', 'careers 2.0']\n <span id=\"hlinks-nav\"><a href=\"/users/login?returnurl=%2fquestions%2f343115%2fregexp-for-finding-everything-between-a-and-a-tags\">sign up</a><span class=\"lsep\">|</span><a href=\"/users/login?returnurl=%2fquestions%2f343115%2fregexp-for-finding-everything-between-a-and-a-tags\">log in</a><span class=\"lsep\">|</span><a href=\"http://careers.stackoverflow.com\">careers 2.0</a><span class=\"lsep\">|</span></span>\n"
},
{
"answer_id": 58295919,
"author": "Emma",
"author_id": 6553328,
"author_profile": "https://Stackoverflow.com/users/6553328",
"pm_score": 0,
"selected": false,
"text": "[\"'] i s <a\\s.*?['\"]\\s*>((?:(?!<\\/a>).)*)<\\/a>\n $re = '/<a\\s.*?[\\'\"]\\s*>((?:(?!<\\/a>).)*)<\\/a>/si';\n$str = '<a href=\"https://google.com\"\ntitle=\"some title\"\ndata-key=\"{\\'key\\':\\'adf0a8dfq<>*1$4%\\' >\n\nsome context in here <>\n\nsome context in there <>\n\n</a>\n\n<A href=\"https://google.com\"\ntitle=\"some title\"\ndata-key=\"{\\'key\\':\\'adf0a8dfq<>*1$4%\\'>\n\nsome context in here\n\nsome context in there\n\n</A>';\n\npreg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);\n\nvar_dump($matches);\n"
},
{
"answer_id": 58313334,
"author": "mickmackusa",
"author_id": 2943403,
"author_profile": "https://Stackoverflow.com/users/2943403",
"pm_score": 1,
"selected": false,
"text": "$html = <<<HTML\n<a href=\"#\">hello</a> <abbr href=\"#\">FYI</abbr> <a title=\"goodbye\">later</a>\n<a href=https://example.com>no quoted attributes</a>\n<A href=\"https://example.com\"\ntitle=\"some title\"\ndata-key=\"{\\'key\\':\\'adf0a8dfq<>*1$4%\\'\">a link with data attribute</A>\nand\nthis is <a title=\"hello\">not a hyperlink</a> but simply an anchor tag\nHTML;\n\n$dom = new DOMDocument; \n$dom->loadHTML($html);\n$xpath = new DOMXPath($dom);\n$linkText = [];\nforeach ($xpath->evaluate(\"//a[@href]\") as $node) {\n $linkText[] = $node->nodeValue;\n}\nvar_export($linkText);\n array (\n 0 => 'hello',\n 1 => 'no quoted attributes',\n 2 => 'a link with data attribute',\n) \n href $doc = new DOMDocument();\n$doc->loadHTML($html);\n$aTags = [];\nforeach ($doc->getElementsByTagName('a') as $a) {\n $aTags[] = $a->nodeValue;\n}\nvar_export($aTags);\n array (\n 0 => 'hello',\n 1 => 'later',\n 2 => 'no quoted attributes',\n 3 => 'a link with data attribute',\n 4 => 'not a hyperlink',\n)\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43510/"
] |
343,133 | <p>My problem is that I want a grid that is populated with a set of times spent on tasks. It needs to have the days of the week at the top (these would preferably be fixed - i.e. Sun, Mon... Sat) and task names down the left column. The contents of the grid will have the individual hours spent for that day on that task.</p>
<p>What would the best approach to take to achieve this? Option one would be to try and put it all in SQL statements in the database. Option two is a collection of LINQ queries that pull raw data from a Tasks and TimeEntries and structure it correctly. Option three is to use LINQ and pull the results into a class (or collection), which is then bound to the control (probably a gridview).</p>
<p>How would you do this?</p>
| [
{
"answer_id": 343142,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 1,
"selected": false,
"text": "ResultSet TimeSheetModel"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15609/"
] |
343,138 | <p>I'm running a project on a Postgres database and need to retrieve the comments on columns within the DB to be used as table headings and such. I have seen that there are a couple of built in functions (<a href="http://www.postgresql.org/docs/9.1/static/catalog-pg-description.html" rel="noreferrer">pg_description</a> and <a href="http://www.postgresql.org/docs/9.1/static/functions-info.html" rel="noreferrer">col_description</a>) but i haven't been able to find examples on how to use them and playing around with them has proved pretty futile.</p>
<p>So I was wondering if any has been able to do this before and if so, how?</p>
| [
{
"answer_id": 343152,
"author": "mat",
"author_id": 42083,
"author_profile": "https://Stackoverflow.com/users/42083",
"pm_score": 4,
"selected": false,
"text": "mat=> SELECT c.oid FROM pg_catalog.pg_class c WHERE c.relname = 'customers';\n oid \n-------\n 23208\n(1 row)\n mat=> select pg_catalog.obj_description(23208);\n obj_description \n-------------------\n Customers\n(1 row)\n mat=> select pg_catalog.col_description(23208,4);\n col_description \n-----------------------------------------\n Customer codes, CHS, FACTPOST, POWER...\n(1 row)\n psql \\dt+ \\d+ customers -E"
},
{
"answer_id": 351019,
"author": "dland",
"author_id": 18625,
"author_profile": "https://Stackoverflow.com/users/18625",
"pm_score": 1,
"selected": false,
"text": "select\n a.attname as \"colname\"\n ,a.attrelid as \"tableoid\"\n ,a.attnum as \"columnoid\"\nfrom\n pg_catalog.pg_attribute a\n inner join pg_catalog.pg_class c on a.attrelid = c.oid\nwhere\n c.relname = 'mytable' -- better to use a placeholder\n and a.attnum > 0\n and a.attisdropped is false\n and pg_catalog.pg_table_is_visible(c.oid)\norder by a.attnum\n"
},
{
"answer_id": 1088772,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "select cols.column_name,\n(select pg_catalog.obj_description(oid) from pg_catalog.pg_class c where c.relname=cols.table_name) as table_comment\n,(select pg_catalog.col_description(oid,cols.ordinal_position::int) from pg_catalog.pg_class c where c.relname=cols.table_name) as column_comment\nfrom information_schema.columns cols\nwhere cols.table_catalog='postbooks' and cols.table_name='apapply'\n"
},
{
"answer_id": 1173538,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "\nCREATE OR REPLACE VIEW our_tables AS \n SELECT c.oid, n.nspname AS schemaname, c.relname AS tablename, d.description,\n pg_get_userbyid(c.relowner) AS tableowner, t.spcname AS \"tablespace\", \n c.relhasindex AS hasindexes, c.relhasrules AS hasrules, c.reltriggers > 0 AS hastriggers\n FROM pg_class c\n LEFT JOIN pg_namespace n ON n.oid = c.relnamespace\n LEFT JOIN pg_tablespace t ON t.oid = c.reltablespace\n LEFT JOIN pg_description d ON c.oid = d.objoid\n WHERE c.relkind = 'r'::\"char\";\n\nALTER TABLE our_tables OWNER TO postgres;\nGRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES, TRIGGER ON TABLE our_tables TO postgres;\nGRANT SELECT ON TABLE our_tables TO public;\n\n SELECT tablename, description FROM our_tables WHERE schemaname = 'public'"
},
{
"answer_id": 4946306,
"author": "user609896",
"author_id": 609896,
"author_profile": "https://Stackoverflow.com/users/609896",
"pm_score": 6,
"selected": false,
"text": "select\n c.table_schema,\n c.table_name,\n c.column_name,\n pgd.description\nfrom pg_catalog.pg_statio_all_tables as st\ninner join pg_catalog.pg_description pgd on (\n pgd.objoid = st.relid\n)\ninner join information_schema.columns c on (\n pgd.objsubid = c.ordinal_position and\n c.table_schema = st.schemaname and\n c.table_name = st.relname\n);\n"
},
{
"answer_id": 12779829,
"author": "Peter Krauss",
"author_id": 287948,
"author_profile": "https://Stackoverflow.com/users/287948",
"pm_score": 2,
"selected": false,
"text": "SELECT obj_description('schemaName.tableName'::regclass, 'pg_class'); (tname||'.'||schema)::regclass obj_description CREATE FUNCTION obj_description(\n p_rname text, p_schema text DEFAULT NULL, \n p_catalname text DEFAULT 'pg_class'\n ) RETURNS text AS $f$\n SELECT obj_description((CASE \n WHEN strpos($1, '.')>0 OR $2 IS NULL OR $2='' THEN $1\n ELSE $2||'.'||$1\n END)::regclass, $3);\n $f$ LANGUAGE SQL IMMUTABLE;\n -- USAGE: obj_description('mytable') \n -- SELECT obj_description('s.t'); \n -- PS: obj_description('s.t', 'otherschema') is a syntax error, \n -- but not generates exception: returns the same as ('s.t') \n rname"
},
{
"answer_id": 22547588,
"author": "Marcio Mazzucato",
"author_id": 999820,
"author_profile": "https://Stackoverflow.com/users/999820",
"pm_score": 4,
"selected": false,
"text": "SELECT\n cols.column_name, (\n SELECT\n pg_catalog.col_description(c.oid, cols.ordinal_position::int)\n FROM\n pg_catalog.pg_class c\n WHERE\n c.oid = (SELECT ('\"' || cols.table_name || '\"')::regclass::oid)\n AND c.relname = cols.table_name\n ) AS column_comment\nFROM\n information_schema.columns cols\nWHERE\n cols.table_catalog = 'your_database'\n AND cols.table_name = 'your_table'\n AND cols.table_schema = 'your_schema';\n"
},
{
"answer_id": 28848797,
"author": "T.Z.",
"author_id": 2415119,
"author_profile": "https://Stackoverflow.com/users/2415119",
"pm_score": 4,
"selected": false,
"text": "SELECT \n obj_description(format('%s.%s',isc.table_schema,isc.table_name)::regclass::oid, 'pg_class') as table_description,\n pg_catalog.col_description(format('%s.%s',isc.table_schema,isc.table_name)::regclass::oid,isc.ordinal_position) as column_description\nFROM\n information_schema.columns isc\n"
},
{
"answer_id": 32717774,
"author": "amxy",
"author_id": 4004410,
"author_profile": "https://Stackoverflow.com/users/4004410",
"pm_score": 1,
"selected": false,
"text": "SELECT pg_tables.tablename, pg_attribute.attname AS field, \n format_type(pg_attribute.atttypid, NULL) AS \"type\", \n pg_attribute.atttypmod AS len,\n (SELECT col_description(pg_attribute.attrelid, \n pg_attribute.attnum)) AS comment, \n CASE pg_attribute.attnotnull \n WHEN false THEN 1 ELSE 0 \n END AS \"notnull\", \n pg_constraint.conname AS \"key\", pc2.conname AS ckey, \n (SELECT pg_attrdef.adsrc FROM pg_attrdef \n WHERE pg_attrdef.adrelid = pg_class.oid \n AND pg_attrdef.adnum = pg_attribute.attnum) AS def \nFROM pg_tables, pg_class \nJOIN pg_attribute ON pg_class.oid = pg_attribute.attrelid \n AND pg_attribute.attnum > 0 \nLEFT JOIN pg_constraint ON pg_constraint.contype = 'p'::\"char\" \n AND pg_constraint.conrelid = pg_class.oid AND\n (pg_attribute.attnum = ANY (pg_constraint.conkey)) \nLEFT JOIN pg_constraint AS pc2 ON pc2.contype = 'f'::\"char\" \n AND pc2.conrelid = pg_class.oid \n AND (pg_attribute.attnum = ANY (pc2.conkey)) \nWHERE pg_class.relname = pg_tables.tablename \n-- AND pg_tables.tableowner = \"current_user\"() \n AND pg_attribute.atttypid <> 0::oid \n AND tablename='your_table' \nORDER BY field ASC\n"
},
{
"answer_id": 46891613,
"author": "James Roscoe",
"author_id": 196276,
"author_profile": "https://Stackoverflow.com/users/196276",
"pm_score": 2,
"selected": false,
"text": "select c.relname table_name, pg_catalog.obj_description(c.oid) as comment from pg_catalog.pg_class c where c.relname = 'table_name';\n SELECT c.column_name, pgd.description FROM pg_catalog.pg_statio_all_tables as st inner join pg_catalog.pg_description pgd on (pgd.objoid=st.relid) inner join information_schema.columns c on (pgd.objsubid=c.ordinal_position and c.table_schema=st.schemaname and c.table_name=st.relname and c.table_name = 'table_name' and c.table_schema = 'public');\n"
},
{
"answer_id": 49984930,
"author": "DatabaseShouter",
"author_id": 9540123,
"author_profile": "https://Stackoverflow.com/users/9540123",
"pm_score": 3,
"selected": false,
"text": "select c.table_schema, st.relname as TableName, c.column_name, \npgd.description\nfrom pg_catalog.pg_statio_all_tables as st\ninner join information_schema.columns c\non c.table_schema = st.schemaname\nand c.table_name = st.relname\nleft join pg_catalog.pg_description pgd\non pgd.objoid=st.relid\nand pgd.objsubid=c.ordinal_position\nwhere st.relname = 'YourTableName';\n"
},
{
"answer_id": 62654305,
"author": "DevonDahon",
"author_id": 931247,
"author_profile": "https://Stackoverflow.com/users/931247",
"pm_score": 2,
"selected": false,
"text": "comments \\d+ my_table\n"
},
{
"answer_id": 65425141,
"author": "Nicolas Janel",
"author_id": 279326,
"author_profile": "https://Stackoverflow.com/users/279326",
"pm_score": 0,
"selected": false,
"text": "SELECT\n cols.table_name,\n cols.column_name, (\n SELECT\n pg_catalog.col_description(c.oid, cols.ordinal_position::int)\n FROM\n pg_catalog.pg_class c\n WHERE\n c.oid = (SELECT ('\"' || cols.table_name || '\"')::regclass::oid)\n AND c.relname = cols.table_name\n) AS column_comment\nFROM\n information_schema.columns cols\nWHERE\n cols.table_name IN (SELECT cols.table_name FROM information_schema.columns)\n AND cols.table_catalog = 'your_database_name'\n AND cols.table_schema = 'your_schema_name';\n"
},
{
"answer_id": 69968028,
"author": "Fogo Fortitude",
"author_id": 7870146,
"author_profile": "https://Stackoverflow.com/users/7870146",
"pm_score": 0,
"selected": false,
"text": "SELECT \npg_tables.schemaname,\npg_tables.TABLENAME,\npg_attribute.attname AS field,\nformat_type(pg_attribute.atttypid, NULL) AS \"type\",\npg_attribute.atttypmod AS len,\n(\nSELECT col_description(pg_attribute.attrelid, pg_attribute.attnum)) AS COMMENT,\nCASE pg_attribute.attnotnull\n WHEN FALSE THEN 1\n ELSE 0\nEND AS \"notnull\",\npg_constraint.conname AS \"key\", pc2.conname AS ckey,\n(\nSELECT pg_attrdef.adsrc\nFROM pg_attrdef\nWHERE pg_attrdef.adrelid = pg_class.oid\n AND pg_attrdef.adnum = pg_attribute.attnum) AS def\nFROM pg_tables, pg_class\nJOIN pg_attribute\n ON pg_class.oid = pg_attribute.attrelid\n AND pg_attribute.attnum > 0\nLEFT JOIN pg_constraint\n ON pg_constraint.contype = 'p'::\"char\"\n AND pg_constraint.conrelid = pg_class.oid\n AND\n(pg_attribute.attnum = ANY (pg_constraint.conkey))\nLEFT JOIN pg_constraint AS pc2\n ON pc2.contype = 'f'::\"char\"\n AND pc2.conrelid = pg_class.oid\n AND (pg_attribute.attnum = ANY (pc2.conkey))\nWHERE pg_class.relname = pg_tables.TABLENAME\nAND pg_tables.schemaname IN ('op', 'im', 'cs','usr','li')\n-- AND pg_tables.tableowner = \"current_user\"()\n AND pg_attribute.atttypid <> 0::oid\n ---AND TABLENAME='your_table'\nORDER BY pg_tables.schemaname,\npg_tables.TABLENAME ASC;\n"
},
{
"answer_id": 72114851,
"author": "rodrigo",
"author_id": 19034389,
"author_profile": "https://Stackoverflow.com/users/19034389",
"pm_score": 0,
"selected": false,
"text": "SELECT \n relname table_name,\n obj_description(oid) table_description,\n column_name,\n pgd.description column_description\nFROM pg_class\nINNER JOIN\n information_schema.columns\n ON table_name = pg_class.relname\nLEFT JOIN \n pg_catalog.pg_description pgd\n ON pgd.objsubid = ordinal_position\nWHERE \n relname = 'your_table_name'\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343138",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,145 | <p>I've created two functions to load expanded views of a month in the archive section of my blog when it's link is clicked:</p>
<pre><code>// Load open view of a month in the Archive section
function loadMonth(date) {
// Remove other open month
removeMonth();
// Hide opening month's link
// Define variable to hold month anchor tag
var monthLink = document.getElementById(date);
monthLink.style.display = "none"; // Hide month anchor
// Define new open month node and its attributes
var openMonth = document.createElement("div");
openMonth.setAttribute("id", "openMonth");
openMonth.innerHTML = "Testing one, two, three.";
// Insert open month
// Define a variable to hold the archive Div node
var archive = document.getElementById("archive");
// Insert the open month in the archive node before it's link
archive.insertBefore(openMonth,monthLink);
return;
}
// Close full view of a month and replace with respective link
function removeMonth() {
// Define global function vars
var archive = document.getElementById("archive"); // Define a var to hold the archive Div node
var openMonth = document.getElementById("openMonth"); // Define var to hold the open month Div node
// Get date of full view month for replacement anchor tag where ID = date
var month = openMonth.getElementsByTagName("span")[0].innerHTML; // Define var to hold the name of the open month
var date = (new Date(month + " 15, 2008").getMonth() + 1); // Define var to hold the numerical equivalent of the month
var year = archive.getElementsByTagName("h3")[0].innerHTML.split(" "); // Define var to hold the year being displayed in the archive
date = year[1] + "" + date; // Change date var to string and insert year
// Remove the open month
archive.removeChild(openMonth);
// Show Link for that month
document.getElementById(date).className = "big"; // Fixes display error when anchor has class firstLink
document.getElementById(date).style.display = "inline"; // Returns link from display "none" state
return;
}
</code></pre>
<p>The functions work when run on the original static content, but when a second link is clicked in the archive, they do nothing. I am wondering if maybe because the elements that were created by my functions cannot be called by document.getElementById. Perhaps a different method of accessing those nodes should be used, or maybe replacing "document" with something that works on javascript created elements too?</p>
<p>Any advice would be greatly appreciated. Thanks.</p>
| [
{
"answer_id": 343155,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "openMonth.id = \"openMonth\";\n getElementById() insertBefore() setAttribute() .id function test()\n{\n // create element, set ID\n var p = document.createElement(\"P\");\n p.innerHTML = \"Look ma, this is a new paragraph!\";\n p.id = \"newParagraph\";\n\n // make element part of the DOM\n document.getElementsByTagName(\"BODY\")[0].appendChild(p);\n\n // get element by ID\n var test = document.getElementById(\"newParagraph\");\n alert(test.innerHTML);\n}\n"
},
{
"answer_id": 343180,
"author": "Ryan Cook",
"author_id": 43029,
"author_profile": "https://Stackoverflow.com/users/43029",
"pm_score": 3,
"selected": true,
"text": "document.getElementById var month = openMonth.getElementsByTagName(\"span\")[0].innerHTML;\n openMonth.getElementsByTagName(\"span\")"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29297/"
] |
343,164 | <p><code>IntToStr()</code> function returns string which is Unicode now. I want to convert to <code>AnsiString</code>.
Can I use <code>AnsiString(IntToStr(I))</code> safely?</p>
| [
{
"answer_id": 343168,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "IntToAnsiString function IntToAnsiStr(X: Integer; Width: Integer = 0): AnsiString;\nbegin\n Str(X: Width, Result);\nend;\n"
},
{
"answer_id": 344086,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 1,
"selected": false,
"text": "UnicodeString IntToStr AnsiString '0' '9' AnsiString"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42065/"
] |
343,182 | <p>Can anyone help me to convert a C# .NET program to PowerShell cmdlet? I am very new to this area. Please help me to get out of this checkpoint!</p>
<p>Regards,</p>
<p>Arun</p>
| [
{
"answer_id": 343199,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 4,
"selected": false,
"text": "[Cmdlet(VerbsCommon.Get, \"Double\")]\npublic class GetDouble : Cmdlet\n{\n [Parameter]\n public int SomeInput { get; set; }\n\n protected override void ProcessRecord()\n {\n WriteObject(SomeInput * 2);\n }\n}\n [RunInstaller(true)]\npublic class MySnapin : PSSnapIn\n{\n public override string Name { get { return \"MyCommandlets\"; } }\n public override string Vendor { get { return \"MyCompany\"; } }\n public override string Description { get { return \"Does unnecessary aritmetic.\"; } }\n}\n Installutil /i myassembly.dll\n Add-PsSnapin MyCommandlets\n"
},
{
"answer_id": 362178,
"author": "user45618",
"author_id": 45618,
"author_profile": "https://Stackoverflow.com/users/45618",
"pm_score": 2,
"selected": false,
"text": "pssnapin getproc"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/201406/"
] |
343,192 | <p>I have a textbox with an onchange event. Why does this event not fire when the user uses the autocomplete feature to populate the textbox?</p>
<p>I am working with Internet Explorer. Is there a standard and relatively simple solution to workaround this problem, without me having to disable the autocomplete feature?</p>
| [
{
"answer_id": 343215,
"author": "Tom Jelen",
"author_id": 28399,
"author_profile": "https://Stackoverflow.com/users/28399",
"pm_score": 5,
"selected": true,
"text": "onpropertychange"
},
{
"answer_id": 343218,
"author": "Tim C",
"author_id": 7585,
"author_profile": "https://Stackoverflow.com/users/7585",
"pm_score": 4,
"selected": false,
"text": "<input type=\"text\" name=\"txtTest\" value=\"\" onfocus=\"this.originalvalue=this.value\" onblur=\"if (this.value != this.originalvalue) alert('Test has changed')\"/>\n"
},
{
"answer_id": 1880859,
"author": "Big Briyan",
"author_id": 228799,
"author_profile": "https://Stackoverflow.com/users/228799",
"pm_score": 2,
"selected": false,
"text": "'Turn off Auto complete \n'(it needs to fire the text change event)\n txtYourTextBox.Attributes.Add(\"AutoComplete\", \"off\")\n input form <input type=text autocomplete=off>\n <form autocomplete=off>\n"
},
{
"answer_id": 8249622,
"author": "David Hammond",
"author_id": 331541,
"author_profile": "https://Stackoverflow.com/users/331541",
"pm_score": 3,
"selected": false,
"text": "$(\"input[type=text]\").bind(\"focus change\",function(){\n this.previousvalue = this.value;\n}).blur(function(){\n if (this.previousvalue != this.value){\n $(this).change();\n }\n})\n $(\"input[type=text]\").blur(function(){\n $(this).change();\n})\n"
},
{
"answer_id": 23161969,
"author": "bluebinary",
"author_id": 1914455,
"author_profile": "https://Stackoverflow.com/users/1914455",
"pm_score": 1,
"selected": false,
"text": "$(\"input:text[id=text_field_id]\").bind(\"focus change keyup blur\", function(event) {\n// handle text change here...\n});\n blur \"input:text[id=text_field_id]\" id text_field_id id"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41766/"
] |
343,200 | <p>I need to extract the icon from a windows shortcut (.lnk) file (or find the icon file, if it's just pointed to by the shortcut).</p>
<p>I'm not asking about extracting icons from exe's, dll's, etc. The shortcut in question is created when I run a installation program. And the icon displayed by the shortcut is not contained in the .exe that the shortcut points to. Presumably the icon is embedded in the .lnk file, or the .lnk file contains a pointer to where this icon lives. But none of the utilities I've found work address this -- they all just go to the .exe.</p>
<p>Many thanks!</p>
| [
{
"answer_id": 343208,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": true,
"text": "Path2Link := 'C:\\Stuff\\TBear S Saver.lnk';\nSHGetFileInfo(PChar(Path2Link), 0, ShInfo1, SizeOf(TSHFILEINFO),\n SHGFI_ICON);\n// this ShInfo1.hIcon will have the Icon Handle for the Link Icon with\n// the small ShortCut arrow added}\n [DllImport(\"shell32.dll\")]\npublic static extern IntPtr SHGetFileInfo(\n string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, \n uint cbSizeFileInfo, uint uFlags);\n Func _ShellGetAssocIcon(Const $szFile,Const $IconFlags = 0)\n Local $tFileInfo = DllStructCreate($tagSHFILEINFO)\n If @error Then\n Return SetError(1,@extended,0)\n EndIf\n\n Local $Ret = DllCall(\"shell32.dll\",\"int\",\"SHGetFileInfo\",\"str\",$szFile,\"dword\",0, _\n \"ptr\",DllStructGetPtr($tFileInfo),\"uint\",DllStructGetSize($tFileInfo),\"uint\",BitOr($SHGFI_ICON,$IconFlags))\n MsgBox(0,0,@error)\n Return DllStructGetData($tFileInfo,\"hIcon\")\nEndFunc\n"
},
{
"answer_id": 13574990,
"author": "Robbie",
"author_id": 1854951,
"author_profile": "https://Stackoverflow.com/users/1854951",
"pm_score": 3,
"selected": false,
"text": "String lnkPath = @\"C:\\Users\\PriceR\\Desktop\\Microsoft Word 2010.lnk\";\n//--- run microsoft word\nvar shl = new Shell32.Shell(); // Move this to class scope\nlnkPath = System.IO.Path.GetFullPath(lnkPath);\nvar dir = shl.NameSpace(System.IO.Path.GetDirectoryName(lnkPath));\nvar itm = dir.Items().Item(System.IO.Path.GetFileName(lnkPath));\nvar lnk = (Shell32.ShellLinkObject)itm.GetLink;\n//lnk.GetIconLocation(out strIcon);\nString strIcon;\nlnk.GetIconLocation(out strIcon);\nIcon awIcon = Icon.ExtractAssociatedIcon(strIcon);\nthis.button1.Text = \"\";\nthis.button1.Image = awIcon.ToBitmap();\n"
},
{
"answer_id": 41455025,
"author": "Remon Ramy",
"author_id": 4636813,
"author_profile": "https://Stackoverflow.com/users/4636813",
"pm_score": 1,
"selected": false,
"text": "using IWshRuntimeLibrary; Image ShortcutIcon = System.Drawing.Icon.ExtractAssociatedIcon(((IWshShortcut)new WshShell().CreateShortcut(File)).TargetPath).ToBitmap();\n Icon ShortcutIcon = System.Drawing.Icon.ExtractAssociatedIcon(((IWshShortcut)new WshShell().CreateShortcut(File)).TargetPath);\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343200",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,204 | <p>I've been working on getting a 2.5 module ported to 3.0, mostly for my own education, when I've gotten stuck. The class "Builder" has as its init:</p>
<pre><code>def __init__(self, **options):
self._verifyOptions(options)
self._options = options
self._initDigest()
self._initBuildNames()
self._methods = []
</code></pre>
<p></p>
<p>But the error occurs at:</p>
<pre><code>def _initDigest(self):
import os, sys, hashlib
digester = hashlib.md5()
digester.update(self._options.get('code'))
self._digest = digester.hexdigest()
</code></pre>
<p>which has as its traceback:</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#5>", line 5, in <module>
""", language="Cee")
File "C:\Python30\lib\site-packages\PyInline\__init__.py", line 31, in build
b = m.Builder(**args)
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 17, in __init__
self._initDigest()
File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 27, in _initDigest
digester.update(self._options.get('code'))
TypeError: object supporting the buffer API required
</code></pre>
<p>I've run it through 2to3, but it isn't picking up on it. As far as I can tell, the update function is expecting the argument to be in the form of bytes/buffer, but I've tried several different methods to convert it and haven't succeeded.</p>
<p>As always, any assistance would be greatly appreciated. :)</p>
| [
{
"answer_id": 343228,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "encoded"
},
{
"answer_id": 343284,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": true,
"text": "digester.update(self._options.get('code'))\n digester.update(self._options.get('code').encode(\"utf-8\"))\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39851/"
] |
343,210 | <p>I found the <a href="http://www.cgal.org/" rel="nofollow noreferrer">Computational Geometry Algorithms Library</a> in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the links are dead! What happened to it? Where can I get it now?</p>
| [
{
"answer_id": 69006755,
"author": "A. Hendry",
"author_id": 8748308,
"author_profile": "https://Stackoverflow.com/users/8748308",
"pm_score": 1,
"selected": false,
"text": "pip install -i https://test.pypi.org/simple/ cgal\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2653/"
] |
343,211 | <p>Is it possible to assign a blank string (i.e. "") as a Default Value in the Entity Framework's EDMX designer? The only technique I've found is to edit the edmx file manually using a text editor</p>
| [
{
"answer_id": 866437,
"author": "Davy8",
"author_id": 23822,
"author_profile": "https://Stackoverflow.com/users/23822",
"pm_score": 2,
"selected": false,
"text": "_privateFieldName = string.Empty;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1131/"
] |
343,219 | <p>I am doing something like this:</p>
<pre><code>#include <signal.h>
class myClass {
public:
void myFunction ()
{
signal(SIGIO,myHandler);
}
void myHandler (int signum)
{
/**
* Handling code
*/
}
}
</code></pre>
<p>I am working on Ubuntu, using gcc. </p>
<p>But it won't compile. It is complaining with:</p>
<blockquote>
<p>error: the argument with type <code>void (MyClass::)(int)</code> doesn't agree with <code>void (*) (int)</code></p>
</blockquote>
<p>Any clues? Or maybe it is just that I cannot use a signal inside classes? Are signals only allowed in C? </p>
<p>The error message is an approximate translation because my compiler is not in English.</p>
| [
{
"answer_id": 343253,
"author": "Jørn Jensen",
"author_id": 34585,
"author_profile": "https://Stackoverflow.com/users/34585",
"pm_score": 4,
"selected": false,
"text": "class myClass {\n void myFunction () \n {\n signal(SIGIO, myClass::myHandler);\n }\n\n static void myHandler (int signum)\n {\n // blabla\n }\n};\n"
},
{
"answer_id": 344495,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 7,
"selected": true,
"text": "void (myClass::*)(int) myHandler class myClass \n{\n public:\n void myFunction () \n {\n signal(SIGIO, myClass::myHandler);\n }\n\n static void myHandler (int signum)\n {\n // handling code\n }\n};\n class myClass \n{\n public:\n void myFunction () \n {\n signal(SIGIO, myClass::static_myHandler);\n }\n\n void myHandler (int signum)\n {\n // handling code\n }\n\n static void static_myHandler(int signum)\n {\n instance.myHandler(signum);\n }\n\n private:\n static myClass instance;\n};\n class myClass\n{\n public:\n void myFunction () // registers a handler\n {\n instances.push_back(this);\n }\n\n void myHandler (int signum)\n {\n // handling code\n }\n\n static void callHandlers (int signum) // calls the handlers\n {\n std::for_each(instances.begin(), \n instances.end(), \n std::bind2nd(std::mem_fun(&myClass::myHandler), signum));\n }\n private:\n static std::vector<myClass *> instances;\n};\n signal(SIGIO, myClass::callHandlers);\n"
},
{
"answer_id": 32757577,
"author": "gekomad",
"author_id": 4264914,
"author_profile": "https://Stackoverflow.com/users/4264914",
"pm_score": 2,
"selected": false,
"text": "#include <signal.h>\n\nclass myClass {\n\n private:\n static myClass* me;\n\n public:\n myClass(){ me=this; }\n\n void myFunction (){\n signal(SIGIO,myClass::myHandler);\n }\n\n void my_method(){ }\n\n static void myHandler (int signum){\n me->my_method();\n }\n}\n"
},
{
"answer_id": 49646471,
"author": "Michael Firth",
"author_id": 4523777,
"author_profile": "https://Stackoverflow.com/users/4523777",
"pm_score": 1,
"selected": false,
"text": "myClass"
},
{
"answer_id": 67642186,
"author": "Abolfazl Abbasi",
"author_id": 9472193,
"author_profile": "https://Stackoverflow.com/users/9472193",
"pm_score": 0,
"selected": false,
"text": " static MyClass &getInstance() {\n static MyClass instance;\n return instance;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366094/"
] |
343,271 | <p>I have a simple program print barcodes. The label format is in a preloaded form.
The value the barcode is passed by a parameter as follow.</p>
<pre><code>^XA
^XFR:FORM.ZPL
^FN999^FDH654321+Y0001+OABC+^FS
^PQ2,0,1,N
</code></pre>
<p>And it print two barcodes</p>
<pre><code>H654321+Y0001+OABC+
H654321+Y0001+OABC+
</code></pre>
<p>What I want is the middle part as a serial number, and it will print barcodes like this</p>
<pre><code>H654321+Y0001+OABC+
H654321+Y0002+OABC+
</code></pre>
<p>I have tried the ^SN and ^SF</p>
<pre><code>^FN999^FDH654321+Y0001+OABC+^SF%%%%%%%%%dddd%%%%%%,1%%%%%%^FS
</code></pre>
<p>But it was not success, two copies are the same. How can I do it in ZPL-II?</p>
| [
{
"answer_id": 24886344,
"author": "Paul",
"author_id": 3864410,
"author_profile": "https://Stackoverflow.com/users/3864410",
"pm_score": 0,
"selected": false,
"text": "^PQ2,0,1,N ^PQ2,0,0,N"
},
{
"answer_id": 28647163,
"author": "Vladis",
"author_id": 4397756,
"author_profile": "https://Stackoverflow.com/users/4397756",
"pm_score": 1,
"selected": false,
"text": "^XA\n^LH10,40\n^BCN,150,Y,N,N^FD^SNH654321+Y0001+OABC+,1,Y^FS\n^PQ2,0,1,Y\n^XZ\n"
},
{
"answer_id": 69289356,
"author": "Oscar Balderas",
"author_id": 7054490,
"author_profile": "https://Stackoverflow.com/users/7054490",
"pm_score": -1,
"selected": false,
"text": "% ^FN999^FDH654321+Y0001+OABC+^SF%%%%%%%%%dddd%%%%%%,1%%%%%%^FS %%%%%%= 1000000 ^FN999^FDH654321+Y0001+OABC+^SF%%%%%%%%%dddd%%%%%%,1000000^FS"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343271",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40214/"
] |
343,275 | <p>I'm using ganymede but I can't find the option to change mirror for the update sites. Is there a way to change this? </p>
| [
{
"answer_id": 349026,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "eclipsec -verbose -application org.eclipse.equinox.p2.metadata.repository.mirrorApplication \n-source http://www.someurl.com/ -destination file:x:/local/path/to/mirror\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20300/"
] |
343,277 | <p>I'm working on a canvas app embedded in a page. I have it so you can zoom into the drawing with the mousewheel but unfortunately this scrolls the page as it is part of an article.</p>
<p>Is it possible to prevent mousewheel scrolling on the window when I'm mousewheeling on a dom element?!</p>
| [
{
"answer_id": 22712226,
"author": "Josh Harrison",
"author_id": 940252,
"author_profile": "https://Stackoverflow.com/users/940252",
"pm_score": 0,
"selected": false,
"text": "// disable all scrolling:\n$(window).disablescroll();\n\n// enable scrolling again:\n$(window).disablescroll(\"undo\");\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,282 | <p>In the following, I'd like to alter the CSS such that the <code>right-sibling</code> is <em>truly</em> centered in the <code>container</code> div. (Edit: without using absolute positioning). </p>
<pre><code><html>
<head>
<style type='text/css'>
#container {
width: 500px;
}
#left-sibling {
float: left;
}
#right-sibling {
text-align: center;
}
</style>
</head>
<body>
<div id='container'>
<div id='left-sibling'>Spam</div>
<div id='right-sibling'>Eggs</div>
</div>
</body>
</html>
</code></pre>
<p>In its current implementation, the right sibling's centering is affected by the left sibling -- you can see this by adding <code>display: none</code> to the <code>left-sibling</code>'s style.</p>
<p>(Note: I'd like to avoid modifying the HTML structure because, as I understand it, the whole point of CSS is to decouple the tag structure from the presentation logic, and this doesn't seem like a really crazy request for CSS to handle.)</p>
<p>TIA.</p>
| [
{
"answer_id": 343289,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "float: left; #left-sibling position: absolute;"
},
{
"answer_id": 343302,
"author": "Mark Bell",
"author_id": 43140,
"author_profile": "https://Stackoverflow.com/users/43140",
"pm_score": 1,
"selected": false,
"text": "border: solid 1px #000; \n"
},
{
"answer_id": 343321,
"author": "MadViking",
"author_id": 40073,
"author_profile": "https://Stackoverflow.com/users/40073",
"pm_score": 1,
"selected": false,
"text": "#left-sibling { float: left; width:100px; border:1px Solid Blue; }\n#right-sibling { text-align: center; width:100px; border:1px Solid Red; }\n <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n #container { width: 500px; position:relative; border:1px Solid Black; }\n#left-sibling { float:left; position:absolute; top:0px; left:0px; width:100px; border:1px Solid Blue; }\n#right-sibling { width:100px; position:relative; margin-left:auto; margin-right:auto; border:1px Solid Red; }\n"
},
{
"answer_id": 343361,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 2,
"selected": false,
"text": "<html>\n <head>\n <style type='text/css'>\n #container {\n width: 500px;\n }\n #left-sibling {\n float: left;\n width:50px;\n }\n #right-sibling {\n text-align: center;\n padding-right:50px;\n }\n </style>\n </head>\n <body>\n <div id='container'>\n <div id='left-sibling'>Spam</div>\n <div id='right-sibling'>Eggs</div>\n </div>\n </body>\n</html>\n"
},
{
"answer_id": 343585,
"author": "rohancragg",
"author_id": 5351,
"author_profile": "https://Stackoverflow.com/users/5351",
"pm_score": 4,
"selected": true,
"text": "<html>\n <head>\n <style type='text/css'> \n #container {\n width: 500px;\n padding-left:50px;\n padding-right:50px; \n } \n #left-sibling {\n border: solid 1px #000;\n float: left;\n width:50px;\n margin-left:-50px; \n } \n #right-sibling {\n border: solid 1px #000;\n text-align: center;\n\n }\n #container2 {\n width: 500px; \n } \n</style>\n </head>\n <body>\n <div id='container'> \n <div id='left-sibling'>Spam</div>\n <div id='right-sibling'>Eggs<br />Eggs<br />Eggs<br /></div>\n </div>\n <div id='container'> \n <div id='left-sibling' style=\"display:none;\">Spam</div> \n <div id='right-sibling'>Eggs<br />Eggs<br />Eggs<br /></div>\n </div>\n <div id='container2'> \n <div id='right-sibling'>Eggs<br />Eggs<br />Eggs<br /></div>\n </div>\n </body>\n</html>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343282",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
343,288 | <p>I'm building a framework and want developers who build with it to have the ability to allow parts of it to both share data with other sites and allow other sites to add/edit/delete data.</p>
<p>For example, if someone makes a site that has book reviews, authors, quotes, code examples, comments, etc. the developer could make e.g. "book reviews" read-only for other sites and "comments" readable by other sites and writable by certain sites/users. The idea is to use the framework to build applications that can easily be interconnected with other applications.</p>
<p>I envision enabling all interaction with the site via POST and GET which would look something like this:</p>
<ul>
<li><strong>/books.php?category=ruby</strong> (returns an XML collection of books about ruby)</li>
<li><strong>/books.php?id=23</strong> (returns the XML for a specific book)</li>
<li><strong>/books.php?action=add&title=AdvancedRuby&description=....&securityId=923847203487</strong></li>
<li><strong>/books.php?action=delete&id=342&securityId=923847203487</strong></li>
</ul>
<p>Other applications could also "discover and consume" what a certain site has to offer by doing this:</p>
<ul>
<li><strong>/discover.php</strong> (returns XML of all public classes and actions available)</li>
</ul>
<p>Really this is all I need to enable the framework to be a way for developers to quickly create loosely connected sites.</p>
<p><strong>What I want to know is, before I begin implementing this, are there significant/interesting parts of REST that I do not yet understand which I should be building into the framework</strong>, e.g.:</p>
<ul>
<li>REST requires GET, POST, PUT and DELETE. Why would I ever need "PUT" and "DELETE"? Am I locking myself out from taking advantage of some standard if I dont' use these?</li>
<li>My "discover.php" file functions similarly to a WSDL file in web services. I am surprised in descriptions of REST there seems to be no standardized way of discovering the services that a RESTful service offers, or is there?</li>
<li>If a client website tries to e.g. add a book to a server website and does not get any "success" response back, it would simply try again until it got a response. The server website would simply not add the same book twice. This is my understanding of data integrity in REST, is there more to it than this?</li>
<li><p>eventually I want to have multiple sites that have the same rich classes e.g. "BookReview" so that a client site would be able to execute code such as this:</p>
<p><strong>$bookReview = new BookReview("<a href="http://www.example.com/books.php?id=23" rel="nofollow noreferrer">http://www.example.com/books.php?id=23</a>");
$book->informAuthor("a comment about your book review was posted on our site...");</strong></p></li>
</ul>
<p>and the server site would send an e-mail off to the author of that review.
Is this type of type interaction a component of the RESTful philosophy or is REST simply the exchange of data via XML, JSON?</p>
| [
{
"answer_id": 1081681,
"author": "pbreitenbach",
"author_id": 42048,
"author_profile": "https://Stackoverflow.com/users/42048",
"pm_score": 2,
"selected": false,
"text": "GET /search?type=books&category=ruby\n GET /books/23 (or /books/23.xml)\n POST /books\ntitle=AdvancedRuby&description=A+great+book...\n DELETE /books/342\n POST /books/342\nstatus=Deleted\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
343,299 | <p>What is the fastest way to do Bulk insert to Oracle using .NET? I need to transfer about 160K records using .NET to Oracle. Currently, I'm using insert statement and execute it 160K times.It takes about 25 minutes to complete. The source data is stored in a DataTable, as a result of query from another database (MySQL), </p>
<p>Is there any better way to do this?</p>
<p><strong>EDIT</strong> : I'm currently using System.Data.OracleClient, but willing to accept solutions using another provider (ODP.NET, DevArt, etc..)</p>
| [
{
"answer_id": 343398,
"author": "Theo",
"author_id": 43402,
"author_profile": "https://Stackoverflow.com/users/43402",
"pm_score": 4,
"selected": false,
"text": "for (int n = 0; n < 100000; n ++)\n{\n mycommand.CommandText = String.Format(\"INSERT INTO [MyTable] ([MyId]) VALUES({0})\", n + 1);\n mycommand.ExecuteNonQuery();\n}\n OracleParameter myparam = new OracleParameter();\nmycommand.CommandText = \"INSERT INTO [MyTable] ([MyId]) VALUES(?)\";\nmycommand.Parameters.Add(myparam);\n \nfor (int n = 0; n < 100000; n ++)\n{\n myparam.Value = n + 1;\n mycommand.ExecuteNonQuery();\n}\n"
},
{
"answer_id": 2110117,
"author": "Neil",
"author_id": 148593,
"author_profile": "https://Stackoverflow.com/users/148593",
"pm_score": 2,
"selected": false,
"text": "String commandString = \"INSERT INTO Users (Name, Desk, UpdateTime) VALUES (:Name, :Desk, :UpdateTime)\";\nusing (OracleCommand command = new OracleCommand(commandString, _connection, _transaction))\n{\n command.Parameters.Add(\"Name\", OracleType.VarChar, 50).Value = strategy;\n command.Parameters.Add(\"Desk\", OracleType.VarChar, 50).Value = deskName ?? OracleString.Null;\n command.Parameters.Add(\"UpdateTime\", OracleType.DateTime).Value = updated;\n command.ExecuteNonQuery();\n}\n"
},
{
"answer_id": 4918808,
"author": "bernd_k",
"author_id": 522317,
"author_profile": "https://Stackoverflow.com/users/522317",
"pm_score": 1,
"selected": false,
"text": "if ($ora_dll -eq $null)\n{\n \"Load Oracle dll\"\n $ora_dll = [System.Reflection.Assembly]::LoadWithPartialName(\"Oracle.DataAccess\") \n $ora_dll\n}\n\n# sql-server or Oracle source example is sql-server\n$ConnectionString =\"server=localhost;database=myDatabase;trusted_connection=yes;Provider=SQLNCLI10;\"\n\n# Oracle destination\n$oraClientConnString = \"Data Source=myTNS;User ID=myUser;Password=myPassword\"\n\n$tableName = \"mytable\"\n$sql = \"select * from $tableName\"\n\n$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($ConnectionString)\n$OLEDBConn.open()\n$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)\n$readcmd.CommandTimeout = '300'\n$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)\n$dt = New-Object system.Data.datatable\n[void]$da.fill($dt)\n$OLEDBConn.close()\n#Write-Output $dt\n\nif ($dt)\n{\n try\n {\n $bulkCopy = new-object (\"Oracle.DataAccess.Client.OracleBulkCopy\") $oraClientConnString\n $bulkCopy.DestinationTableName = $tableName\n $bulkCopy.BatchSize = 5000\n $bulkCopy.BulkCopyTimeout = 10000\n $bulkCopy.WriteToServer($dt)\n $bulkcopy.close()\n $bulkcopy.Dispose()\n }\n catch\n {\n $ex = $_.Exception\n Write-Error \"Write-DataTable$($connectionName):$ex.Message\"\n continue\n }\n}\n"
},
{
"answer_id": 24413040,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 2,
"selected": false,
"text": "create table jkl_test (id number(9));\n using Oracle.DataAccess.Client;\n\nnamespace OracleArrayInsertExample\n{\n class Program\n {\n static void Main(string[] args)\n {\n // Open a connection using ODP.Net\n var connection = new OracleConnection(\"Data Source=YourDatabase; Password=YourPassword; User Id=YourUser\");\n connection.Open();\n\n // Create an insert command\n var command = connection.CreateCommand();\n command.CommandText = \"insert into jkl_test values (:ids)\";\n\n // Set up the parameter and provide values\n var param = new OracleParameter(\"ids\", OracleDbType.Int32);\n param.Value = new int[] { 22, 55, 7, 33, 11 };\n\n // This is critical to the process; in order for the command to \n // recognize and bind arrays, an array bind count must be specified.\n // Set it to the length of the array.\n command.ArrayBindCount = 5;\n command.Parameters.Add(param);\n command.ExecuteNonQuery();\n }\n }\n}\n"
},
{
"answer_id": 40234289,
"author": "6opuc",
"author_id": 225344,
"author_profile": "https://Stackoverflow.com/users/225344",
"pm_score": 2,
"selected": false,
"text": "var bulkWriter = new OracleDbBulkWriter();\n bulkWriter.Write(\n connection,\n \"BULK_WRITE_TEST\",\n Enumerable.Range(1, 10000).Select(v => new TestData { Id = v, StringValue=v.ToString() }).ToList());\n public class OracleDbBulkWriter : IDbBulkWriter\n{\n public void Write<T>(IDbConnection connection, string targetTableName, IList<T> data, IList<ColumnToPropertyMapping> mappings = null)\n {\n if (connection == null)\n {\n throw new ArgumentNullException(nameof(connection));\n }\n if (string.IsNullOrEmpty(targetTableName))\n {\n throw new ArgumentNullException(nameof(targetTableName));\n }\n if (data == null)\n {\n throw new ArgumentNullException(nameof(data));\n }\n if (mappings == null)\n {\n mappings = GetGenericMappings<T>();\n }\n\n mappings = GetUniqueMappings<T>(mappings);\n Dictionary<string, Array> parameterValues = InitializeParameterValues<T>(mappings, data.Count);\n FillParameterValues(parameterValues, data);\n\n using (var command = CreateCommand(connection, targetTableName, mappings, parameterValues))\n {\n command.ExecuteNonQuery();\n }\n }\n\n private static IDbCommand CreateCommand(IDbConnection connection, string targetTableName, IList<ColumnToPropertyMapping> mappings, Dictionary<string, Array> parameterValues)\n {\n var command = (OracleCommandWrapper)connection.CreateCommand();\n command.ArrayBindCount = parameterValues.First().Value.Length;\n\n foreach(var mapping in mappings)\n {\n var parameter = command.CreateParameter();\n parameter.ParameterName = mapping.Column;\n parameter.Value = parameterValues[mapping.Property];\n\n command.Parameters.Add(parameter);\n }\n\n command.CommandText = $@\"insert into {targetTableName} ({string.Join(\",\", mappings.Select(m => m.Column))}) values ({string.Join(\",\", mappings.Select(m => $\":{m.Column}\")) })\";\n return command;\n }\n\n private IList<ColumnToPropertyMapping> GetGenericMappings<T>()\n {\n var accessor = TypeAccessor.Create(typeof(T));\n\n var mappings = accessor.GetMembers()\n .Select(m => new ColumnToPropertyMapping(m.Name, m.Name))\n .ToList();\n\n return mappings;\n }\n\n private static IList<ColumnToPropertyMapping> GetUniqueMappings<T>(IList<ColumnToPropertyMapping> mappings)\n {\n var accessor = TypeAccessor.Create(typeof(T));\n var members = new HashSet<string>(accessor.GetMembers().Select(m => m.Name));\n\n mappings = mappings\n .Where(m => m != null && members.Contains(m.Property))\n .GroupBy(m => m.Column)\n .Select(g => g.First())\n .ToList();\n return mappings;\n }\n\n private static Dictionary<string, Array> InitializeParameterValues<T>(IList<ColumnToPropertyMapping> mappings, int numberOfRows)\n {\n var values = new Dictionary<string, Array>(mappings.Count);\n var accessor = TypeAccessor.Create(typeof(T));\n var members = accessor.GetMembers().ToDictionary(m => m.Name);\n\n foreach(var mapping in mappings)\n {\n var member = members[mapping.Property];\n\n values[mapping.Property] = Array.CreateInstance(member.Type, numberOfRows);\n }\n\n return values;\n }\n\n private static void FillParameterValues<T>(Dictionary<string, Array> parameterValues, IList<T> data)\n {\n var accessor = TypeAccessor.Create(typeof(T));\n for (var rowNumber = 0; rowNumber < data.Count; rowNumber++)\n {\n var row = data[rowNumber];\n foreach (var pair in parameterValues)\n {\n Array parameterValue = pair.Value;\n var propertyValue = accessor[row, pair.Key];\n parameterValue.SetValue(propertyValue, rowNumber);\n }\n }\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343299",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10629/"
] |
343,313 | <p>Sorry for the slightly rubbish title. I could not think how to describe this one better.</p>
<p>I am trying to implement the Google Friend Connect members gadget on my site, (just got into the scheme and want to put it in without a major redesign, at least for testing sake).</p>
<p>My problem is as follows:</p>
<p>I have a container div that has a width of 90% of the main page (body). Inside this I am floating a div to the right and setting its width to 300px and putting the google gadget inside it. What I would like is to be able to have a div fill 95% of the space remaining to the left of the google gadget div. </p>
<p>I don't know if it is possible to be able to mix px and % with divs and widths. </p>
<p>I hope this makes sense.</p>
<p>Thanks</p>
| [
{
"answer_id": 45336531,
"author": "Reggie Pinkham",
"author_id": 2927114,
"author_profile": "https://Stackoverflow.com/users/2927114",
"pm_score": 2,
"selected": false,
"text": ".main {\n display: flex;\n width: 90%;\n}\n.col1 {\n flex-grow: 1;\n}\n.col2 {\n width: 300px;\n margin-left: 5%;\n} <div class=\"main\">\n <div class=\"col1\" style=\"background: #518cf3;\">Left column</div>\n <div class=\"col2\" style=\"background: #94d0bb;\">Right column</div>\n</div>"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6486/"
] |
343,346 | <p>I'm trying to get the label of some network resources mapped as drives. When I use DriveInfo.GetDrives(), local volumes have the VolumeLabel filled parameter as expected, but in network drives it is an empty string. How can I get those labels?</p>
| [
{
"answer_id": 45336531,
"author": "Reggie Pinkham",
"author_id": 2927114,
"author_profile": "https://Stackoverflow.com/users/2927114",
"pm_score": 2,
"selected": false,
"text": ".main {\n display: flex;\n width: 90%;\n}\n.col1 {\n flex-grow: 1;\n}\n.col2 {\n width: 300px;\n margin-left: 5%;\n} <div class=\"main\">\n <div class=\"col1\" style=\"background: #518cf3;\">Left column</div>\n <div class=\"col2\" style=\"background: #94d0bb;\">Right column</div>\n</div>"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40996/"
] |
343,356 | <p>I'm developing a web application that is targeted at IE and during testing would like to log in as a number of different users and test their interactions with each other.</p>
<p>At present I have to log in and out to switch users; Opening another window just overrides the cookies/session.</p>
<p>Is there any way to get IE to run completely seperate; I can run firefox or chrome and get another session but the app isn't supported in these browsers.</p>
| [
{
"answer_id": 343360,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 3,
"selected": true,
"text": "runas /user:domain\\account iexplore.exe\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24525/"
] |
343,362 | <p>I have a web application (ASP.net 2.0) that has a database (SQL Server) at the background. I'm considering ways how to handle database concurrency if two users insert the same data to the same table at the same time. Are there any way to handle this case? Thanks in advance.</p>
<p>Jimmy</p>
| [
{
"answer_id": 343399,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 2,
"selected": false,
"text": "INSERT INSERT TIMESTAMP command.CommandText = @\"\n UPDATE tbl\n SET LastName = @LastName, FirstName = @FirstName\n WHERE ID = @ID AND Timestamp = @Timestamp\n \";\n\nint rowCount = command.ExecuteNonQuery();\nif (rowCount != 1)\n throw new DBConcurrencyException();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,366 | <p>If I am storing the Subversion user names and passwords for repository access in a text file in the <code>conf</code> folder, what is the maximum length of the passwords I can use? That is to say, how long can the secrets in the following file be?</p>
<pre><code>[users]
harry = harryssecret
sally = sallyssecret
</code></pre>
| [
{
"answer_id": 343441,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 3,
"selected": true,
"text": "svnserve"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39722/"
] |
343,368 | <p>I am getting this linker error.</p>
<blockquote>
<p><strong>mfcs80.lib(dllmodul.obj) : error LNK2005: _DllMain@12 already defined in MSVCRT.lib(dllmain.obj)</strong></p>
</blockquote>
<p>Please tell me the correct way of eliminating this bug. I read solution on microsoft support site about this bug but it didnt helped much.</p>
<p>I am using VS 2005 with Platform SDK</p>
| [
{
"answer_id": 16124492,
"author": "izogfif",
"author_id": 156973,
"author_profile": "https://Stackoverflow.com/users/156973",
"pm_score": 2,
"selected": false,
"text": "Solution Explorer Properties Linker mfcs71ud.lib Additional Dependencies"
},
{
"answer_id": 19930430,
"author": "Constantin",
"author_id": 531840,
"author_profile": "https://Stackoverflow.com/users/531840",
"pm_score": 6,
"selected": false,
"text": "extern \"C\" { int _afxForceUSRDLL; } \n DllMain DllMain"
},
{
"answer_id": 25389904,
"author": "joan",
"author_id": 3957464,
"author_profile": "https://Stackoverflow.com/users/3957464",
"pm_score": 2,
"selected": false,
"text": "_USRDLL"
},
{
"answer_id": 27919572,
"author": "Carsten",
"author_id": 1254352,
"author_profile": "https://Stackoverflow.com/users/1254352",
"pm_score": 2,
"selected": false,
"text": "Yc/Yu ClCompile ClInclude dllmain.cpp CompileAsManaged false PrecompiledHeader MyLib.cpp DllCanUnloadNow MyLib_i.c dllmain.cpp stdafx.cpp PrecompiledHeader Create xdlldata.c dllmain.cpp dllmain.h MyLib_i.h Resource.h stdafx.h targetver.h xdlldata.h"
},
{
"answer_id": 33029765,
"author": "Avishek Bose",
"author_id": 5425917,
"author_profile": "https://Stackoverflow.com/users/5425917",
"pm_score": 2,
"selected": false,
"text": "mfc80ud.lib mfcs80ud.lib Additional Dependancies Project Properties -> Linker Tab -> Input of Visual Studio"
},
{
"answer_id": 34054747,
"author": "mgruber4",
"author_id": 2480144,
"author_profile": "https://Stackoverflow.com/users/2480144",
"pm_score": 2,
"selected": false,
"text": "#undef _USRDLL afx.h"
},
{
"answer_id": 63223209,
"author": "dmedine",
"author_id": 4525932,
"author_profile": "https://Stackoverflow.com/users/4525932",
"pm_score": 1,
"selected": false,
"text": "foo.dll foo.def DoFoo bar.dll bar.def DoFoo"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38038/"
] |
343,383 | <p>I have this code:</p>
<pre><code>if (file.exists()) {
Document doc = builder.parse(file);
NodeList list = doc.getElementsByTagName("property");
System.out.println("XML Elements: ");
for (int ii = 0; ii < list.getLength(); ii++) {
</code></pre>
<p>line 2 gives following exception</p>
<pre>
E:\workspace\test\testDomain\src\com\test\ins\nxg\maps\Right.hbm.xml
...***java.net.SocketException: Operation timed out: connect:could be due to invalid address
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:372)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:233)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:220)
</pre>
| [
{
"answer_id": 354740,
"author": "kevindaub",
"author_id": 27669,
"author_profile": "https://Stackoverflow.com/users/27669",
"pm_score": 0,
"selected": false,
"text": "DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();\nDocumentBuilder db = dbf.newDocumentBuilder();\nDocument doc = db.parse(file);\n"
},
{
"answer_id": 25876930,
"author": "Kemin Zhou",
"author_id": 2407363,
"author_profile": "https://Stackoverflow.com/users/2407363",
"pm_score": 1,
"selected": false,
"text": "<?xml version=\"1.0\"?> <!DOCTYPE GBSet PUBLIC \"-//NCBI//NCBI GBSeq/EN\" http://www.ncbi.nlm.nih.gov/dtd/NCBI_GBSeq.dtd\"> ... more to come\n <!-- ============================================\n ::DATATOOL:: Generated from \"gbseq.asn\"\n ::DATATOOL:: by application DATATOOL version 1.5.0\n ::DATATOOL:: on 06/06/2006 23:03:48\n ============================================ -->\n\n<!-- NCBI_GBSeq.dtd\nThis file is built from a series of basic modules.\nThe actual ELEMENT and ENTITY declarations are in the modules.\nThis file is used to put them together.\n-->\n\n<!ENTITY % NCBI_Entity_module PUBLIC \"-//NCBI//NCBI Entity Module//EN\" \n\"NCBI_Entity.mod.dtd\"> %NCBI_Entity_module;\n\n<!ENTITY % NCBI_GBSeq_module PUBLIC \"-//NCBI//NCBI GBSeq Module//EN\" \"NCBI_GBSeq.mod.dtd\"> %NCBI_GBSeq_module;\n <!DOCTYPE GBSet PUBLIC \"-//NCBI//NCBI GBSeq/EN\" \"http://www.ncbi.nlm.nih.gov/dtd/NCBI_GBSeq.dtd\">\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,396 | <p>When we run a update query we get prompt saying that 'these many records are going to be updated. do you want to continue' is it possible to capture the value in the prompt message to a variable i.e the number of records going to be updated.</p>
| [
{
"answer_id": 343752,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": true,
"text": "Dim db As Database\nSet db=CurrentDB\ndb.Execute \"Some SQL here\"\ndb.RecordsAffected\n"
},
{
"answer_id": 343765,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 2,
"selected": false,
"text": "RecordsAffected Function RowsChanged(updateQuery As String) As Long\n Dim qry As QueryDef\n\n Set qry = CurrentDb.QueryDefs(updateQuery)\n qry.Execute\n\n RowsChanged = qry.RecordsAffected\nEnd Function\n Dim numRows as long\nnumRows = RowsChanged(\"UpdateQuery\")\n"
},
{
"answer_id": 348453,
"author": "David-W-Fenton",
"author_id": 9787,
"author_profile": "https://Stackoverflow.com/users/9787",
"pm_score": 2,
"selected": false,
"text": " Function RowsChanged(updateQuery As String) As Long\n Dim qry As QueryDef\n\n Set qry = CurrentDb.QueryDefs(updateQuery)\n qry.Execute\n\n RowsChanged = qry.RecordsAffected\n End Function\n Public Function SQLRun(strSQL As String) As Long\n On Error GoTo errHandler\n Static db As DAO.Database\n\n If db Is Nothing Then \n Set db = CurrentDB\n End If\n db.Execute strSQL, dbFailOnError\n SQLRun = db.RecordsAffected\n\n exitRoutine:\n Exit Function\n\n errHandler:\n MsgBox Err.Number & \": \" & Err.Description, vbExclamation, \"Error in SQLRun()\"\n Resume exitRoutine\n End Function\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
343,402 | <p>I'm currently busy implementing a filter of sorts for which I need to generate an INNER JOIN clausse for every "tag" to filter on.</p>
<p>The problem is that after a whole bunch of SQL, I have a table that contains all the information I need to make my selection, but I need it again for every generated INNER JOIN</p>
<p>This basically looks like:</p>
<pre><code>SELECT
*
FROM search
INNER JOIN search f1 ON f1.baseID = search.baseID AND f1.condition = condition1
INNER JOIN search f2 ON f2.baseID = search.baseID AND f2.condition = condition2
...
INNER JOIN search fN ON fN.baseID = search.baseID AND fN.condition = conditionN
</code></pre>
<p>This works but I would much prefer the "search" table to be temporary (it can be several orders of magnitude smaller if it isn't a normal table) but that gives me a very annoying error: <code>Can't reopen table</code></p>
<p>Some research leads me to <a href="http://bugs.mysql.com/bug.php?id=10327" rel="noreferrer">this bug report</a> but the folks over at MySQL don't seem to care that such a basic feature (using a table more than once) does not work with temporary tables. I'm running into a lot of scalability problems with this issue.</p>
<p>Is there any viable workaround that does not require me to manage potentially lots of temporary but very real tables or make me maintain a huge table with all the data in it?</p>
<p>Kind regards, Kris</p>
<p>[additional]</p>
<p>The GROUP_CONCAT answer does not work in my situation because my conditions are multiple columns in specific order, it would make ORs out of what I need to be ANDs. However, It did help me solve an earlier problem so now the table, temp or not, is no longer required. We were just thinking too generic for our problem. The entire application of filters has now been brought back from around a minute to well under a quarter of a second.</p>
| [
{
"answer_id": 347300,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 6,
"selected": false,
"text": "TEMPORARY SELECT f1.baseID, GROUP_CONCAT(f1.condition)\nFROM search f1\nWHERE f1.condition IN (<condition1>, <condition2>, ... <conditionN>)\nGROUP BY f1.baseID\nHAVING COUNT(*) = <N>;\n"
},
{
"answer_id": 23441101,
"author": "beeks",
"author_id": 2624707,
"author_profile": "https://Stackoverflow.com/users/2624707",
"pm_score": 3,
"selected": false,
"text": "select concat('ReviewLatency', CONNECTION_ID()) into @tablename;\n\n#Drop \"temporary\" table if it exists\nset @dsql=concat('drop table if exists ', @tablename, ';');\nPREPARE QUERY1 FROM @dsql;\nEXECUTE QUERY1;\nDEALLOCATE PREPARE QUERY1;\n\n#Due to MySQL bug not allowing multiple queries in DSQL, we have to break it up...\n#Also due to MySQL bug, you cannot join a temporary table to itself,\n#so we create a real table, but append the SPID to it for uniqueness.\nset @dsql=concat('\ncreate table ', @tablename, ' (\n `EventUID` int(11) not null,\n `EventTimestamp` datetime not null,\n `HasAudit` bit not null,\n `GroupName` varchar(255) not null,\n `UserID` int(11) not null,\n `EventAuditUID` int(11) null,\n `ReviewerName` varchar(255) null,\n index `tmp_', @tablename, '_EventUID` (`EventUID` asc),\n index `tmp_', @tablename, '_EventAuditUID` (`EventAuditUID` asc),\n index `tmp_', @tablename, '_EventUID_EventTimestamp` (`EventUID`, `EventTimestamp`)\n) ENGINE=MEMORY;');\nPREPARE QUERY2 FROM @dsql;\nEXECUTE QUERY2;\nDEALLOCATE PREPARE QUERY2;\n\n#Insert into the \"temporary\" table\nset @dsql=concat('\ninsert into ', @tablename, ' \nselect e.EventUID, e.EventTimestamp, e.HasAudit, gn.GroupName, epi.UserID, eai.EventUID as `EventAuditUID`\n , concat(concat(concat(max(concat('' '', ui.UserPropertyValue)), '' (''), ut.UserName), '')'') as `ReviewerName`\nfrom EventCore e\n inner join EventParticipantInformation epi on e.EventUID = epi.EventUID and epi.TypeClass=''FROM''\n inner join UserGroupRelation ugr on epi.UserID = ugr.UserID and e.EventTimestamp between ugr.EffectiveStartDate and ugr.EffectiveEndDate \n inner join GroupNames gn on ugr.GroupID = gn.GroupID\n left outer join EventAuditInformation eai on e.EventUID = eai.EventUID\n left outer join UserTable ut on eai.UserID = ut.UserID\n left outer join UserInformation ui on eai.UserID = ui.UserID and ui.UserProperty=-10\n where e.EventTimestamp between @StartDate and @EndDate\n and e.SenderSID = @FirmID\n group by e.EventUID;');\nPREPARE QUERY3 FROM @dsql;\nEXECUTE QUERY3;\nDEALLOCATE PREPARE QUERY3;\n\n#Generate the actual query to return results. \nset @dsql=concat('\nselect rl1.GroupName as `Group`, coalesce(max(rl1.ReviewerName), '''') as `Reviewer(s)`, count(distinct rl1.EventUID) as `Total Events`\n , (count(distinct rl1.EventUID) - count(distinct rl1.EventAuditUID)) as `Unreviewed Events`\n , round(((count(distinct rl1.EventUID) - count(distinct rl1.EventAuditUID)) / count(distinct rl1.EventUID)) * 100, 1) as `% Unreviewed`\n , date_format(min(rl2.EventTimestamp), ''%W, %b %c %Y %r'') as `Oldest Unreviewed`\n , count(distinct rl3.EventUID) as `<=7 Days Unreviewed`\n , count(distinct rl4.EventUID) as `8-14 Days Unreviewed`\n , count(distinct rl5.EventUID) as `>14 Days Unreviewed`\nfrom ', @tablename, ' rl1\nleft outer join ', @tablename, ' rl2 on rl1.EventUID = rl2.EventUID and rl2.EventAuditUID is null\nleft outer join ', @tablename, ' rl3 on rl1.EventUID = rl3.EventUID and rl3.EventAuditUID is null and rl1.EventTimestamp > DATE_SUB(NOW(), INTERVAL 7 DAY) \nleft outer join ', @tablename, ' rl4 on rl1.EventUID = rl4.EventUID and rl4.EventAuditUID is null and rl1.EventTimestamp between DATE_SUB(NOW(), INTERVAL 7 DAY) and DATE_SUB(NOW(), INTERVAL 14 DAY)\nleft outer join ', @tablename, ' rl5 on rl1.EventUID = rl5.EventUID and rl5.EventAuditUID is null and rl1.EventTimestamp < DATE_SUB(NOW(), INTERVAL 14 DAY)\ngroup by rl1.GroupName\norder by ((count(distinct rl1.EventUID) - count(distinct rl1.EventAuditUID)) / count(distinct rl1.EventUID)) * 100 desc\n;');\nPREPARE QUERY4 FROM @dsql;\nEXECUTE QUERY4;\nDEALLOCATE PREPARE QUERY4;\n\n#Drop \"temporary\" table\nset @dsql = concat('drop table if exists ', @tablename, ';');\nPREPARE QUERY5 FROM @dsql;\nEXECUTE QUERY5;\nDEALLOCATE PREPARE QUERY5;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18565/"
] |
343,422 | <p>How can i make the inner table to overlap the parent div with 5 px while resizing?</p>
<p>my current solution:</p>
<pre><code><div id="crop">
<table style="width:105%; height:105%;">
//table cells
</table>
</div>
</code></pre>
<p>problem is that it gets smaller when resizing... </p>
<p>how can I make it constantly overlap with 5px;</p>
| [
{
"answer_id": 343498,
"author": "chriscena",
"author_id": 32671,
"author_profile": "https://Stackoverflow.com/users/32671",
"pm_score": 0,
"selected": false,
"text": "table {\nposition: relative;\ntop: 5px;\nleft: 5px;\nmargin-top: -5px;\nmargin-left: -5px;\n}\n <style type=\"text/css\">\n#container {\nbackground-color: red; //color added for illustration\n}\n\n#data {\nbackground-color: blue; //color added for illustration\nposition: relative;\ntop: 5px;\nleft: 5px;\nmargin-top: -5px;\nmargin-left: -5px;\n}\n</style>\n\n<!-- ... -->\n\n<div id=\"container\">\nsome text to make the div visible at the top\n<table id=\"data\">\n<!-- rows -->\n</table>\n</div>\n"
},
{
"answer_id": 343502,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "table div table div div position:absolute"
},
{
"answer_id": 344152,
"author": "BlackMael",
"author_id": 19377,
"author_profile": "https://Stackoverflow.com/users/19377",
"pm_score": 2,
"selected": true,
"text": "<html>\n <head>\n <style type=\"text/css\">\n #outer {\n position: relative;\n border: solid 1px blue;\n height: 100px;\n }\n #inner {\n position: absolute;\n border: solid 1px red;\n top: -5px;\n left: -5px;\n bottom: -5px;\n right: -5px;\n }\n </style>\n <!--[if IE]>\n <style type=\"text/css\">\n #inner {\n border: solid 1px green;\n height: 108px;\n width: expression(document.getElementById(\"outer\").clientWidth + 10);\n }\n </style>\n <![endif]-->\n </head>\n <body>\n <table width=\"100%\">\n <colgroup>\n <col />\n <col width=\"100\" />\n <col width=\"200\" />\n </colgroup>\n <tr>\n <td>\n <div id=\"outer\">\n <div id=\"inner\">\n <table border=\"1\">\n <tr><td>A</td><td>B</td></tr>\n <tr><td>C</td><td>D</td></tr>\n </table>\n </div>\n </div>\n </td>\n <td>Alpha</td>\n <td>Beta</td>\n </tr>\n <tr>\n <td>One</td>\n <td>Two</td>\n <td>Three</td>\n </tr>\n </table>\n </body>\n</html>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,435 | <h3>ANSWER:</h3>
<p>If you ever see these lines and are mistified like I was, here's what they mean.</p>
<p><code>Thread[AWT-EventQueue-0] (Suspended (exception NullPointerException))</code></p>
<p><code>EventDispatchTread.run() line: not available [local variables unavailable]</code></p>
<p>It's not that the variables are unavailable because they are lurking behind a shroud of mystery in a library somewhere dank. No no, they just went out of scope! It's still your fault, you still have to find the null, and no you can't blame the library. Important lesson!</p>
<h3>QUESTION:</h3>
<p>One of the most frustrating things for me, as a beginner is libraries! It's a love/hate relationship: On the one hand they let me do things I wouldn't normally understand how to do with the code that I do understand, on the other hand because I don't completely understand them, they sometimes throw a wrench in code that is otherwise working fine! It's because I don't understand the errors that can occur when using these libraries, because I didn't write them, and because eclipse doesn't give me a great deal to go with when one of imports starts acting up...</p>
<p>So here's the problem: I've been working with java.awt.event to handle a bunch of JButtons on the screen for this and that. I get an error when I use one of the buttons I've made. The error is:</p>
<p><code>Thread[AWT-EventQueue-0] (Suspended (exception NullPointerException))</code></p>
<p><code>EventDispatchTread.run() line: not available [local variables unavailable]</code></p>
<p>What does this mean? What could be causing it? I'm embarrassed to post code, but if you can stand to try to decipher my terrible style, here is the method that seems to cause this error to be thrown.</p>
<pre><code>public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
String name;
code...
if(cmd.equals("Play")) {
name = field.getText();
card = getCard(name);
if(card != null) {
if(rules.zoneHasCard(card, rules.hand)) {
display.updateStatusMessage(rules.play(card));
field.setText("");
display.updateHand(rules.zoneList("hand"));
display.updateDiscard(rules.zoneList("Discard")); // This is the error here! The discard Zone was empty!
}
else {
field.setText("You do not have " + card.getName());
field.selectAll();
}
}
else {
field.setText("That cardname is unused");
field.selectAll();
}
}
}
</code></pre>
| [
{
"answer_id": 343530,
"author": "Steve McLeod",
"author_id": 2959,
"author_profile": "https://Stackoverflow.com/users/2959",
"pm_score": 3,
"selected": true,
"text": "public void actionPerformed(ActionEvent e) {\n String cmd = e.getActionCommand();\n String name;\n\n// more code...\n}\n System.out.println(\"field = \" + field);\nSystem.out.println(\"rules = \" + rules);\nSystem.out.println(\"display = \" + display);\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29182/"
] |
343,457 | <p>--Edit with more bgnd information--</p>
<p>A (black box) COM object returns me a string.
A 2nd COM object expects this same string as byte[] as input and returns a byte[] with the processed data.
This will be fed to a browser as downloadable, non-human-readable file that will be loaded in a client side stand-alone application.</p>
<p>so I get the string inputString from the 1st COM and convert it into a byte[] as follows</p>
<pre><code>BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, inputString);
obj = ms.ToArray();
</code></pre>
<p>I feed it to the 2nd COM and read it back out.
The result gets written to the browser.</p>
<pre><code>Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment; filename="test.dat");
Response.BinaryWrite(obj);
</code></pre>
<p>The error occurs in the 2nd COm because the formatting is incorrect.
I went to check the original string and that was perfectly fine. I then pumped the result from the 1st com directly to the browser and watched what came out. It appeared that somewhere along the road extra unreadable characters are added. What are these characters, what are they used for and how can I prevent them from making my 2nd COM grind to a halt?</p>
<p>The unreadable characters are of this kind:</p>
<p>NUL/SOH/NUL/NUL/NUL/FF/FF/FF/FF/SOH/NUL/NUL/NUL etc</p>
<p>Any ideas?</p>
<p><strong>--Answer--</strong><br>
Use </p>
<pre><code>System.Text.Encoding.UTF8.GetBytes(theString)
</code></pre>
<p>rather then</p>
<pre><code>BinaryFormatter.Serialize()
</code></pre>
| [
{
"answer_id": 343477,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": " ÿÿÿÿ AIronScheme, Version=1.0.0.0, Culture=neutral, Public\n byte[] buffer = Encoding.Default.GetBytes(formulaXml);\nResponse.BinaryWrite(buffer);\n"
},
{
"answer_id": 343496,
"author": "Miral",
"author_id": 43534,
"author_profile": "https://Stackoverflow.com/users/43534",
"pm_score": 1,
"selected": false,
"text": "BinaryFormatter BinaryFormatter Encoding.GetBytes"
},
{
"answer_id": 343552,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": true,
"text": "\"<foo>\""
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
343,466 | <p>Does dot net have an interface like IEnumerable with a count property? I know about interfaces such as IList and ICollection which do offer a Count property but it seems like these interfaces were designed for mutable data structures first and use as a read only interface seems like an afterthought - the presence of an IsReadOnly field and mutators throwing exceptions when this property is true is IMO ample evidence for this.</p>
<p>For the time being I am using a custom interface called IReadOnlyCollection (see my own answer to this post) but I would be glad to know of other alternative approaches.</p>
| [
{
"answer_id": 343478,
"author": "Ruben Bartelink",
"author_id": 11635,
"author_profile": "https://Stackoverflow.com/users/11635",
"pm_score": 5,
"selected": true,
"text": "using System.Linq;\n\nclass X\n{\n void Y(IEnumerable<int> collection)\n {\n int itemCount = collection.Count();\n }\n}\n"
},
{
"answer_id": 343486,
"author": "Miral",
"author_id": 43534,
"author_profile": "https://Stackoverflow.com/users/43534",
"pm_score": 1,
"selected": false,
"text": "IList ICollection void ICollection<DataType>.Add(DataType item)\n{\n throw new NotSupportedException();\n}\n\npublic DataType this[int index]\n{\n get { return InnerList[index]; }\n}\n\nDataType IList<DataType>.this[int index]\n{\n get { return this[index]; }\n set { throw new NotSupportedException(); }\n}\n"
},
{
"answer_id": 343506,
"author": "Sandeep Datta",
"author_id": 39648,
"author_profile": "https://Stackoverflow.com/users/39648",
"pm_score": 2,
"selected": false,
"text": "interface IReadOnlyCollection<T> : IEnumerable<T>\n{\n int Count { get; }\n}\n\n//This can now be not misused by downcasting to List\n//The wrapper can also be used with lists since IList inherits from ICollection\npublic class CollectionWrapper<T> : IReadOnlyCollection<T>\n{\n\n public CollectionWrapper(ICollection<T> collection)\n {\n _collection = collection;\n }\n\n public int Count\n {\n get\n {\n return _collection.Count;\n }\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n return (IEnumerator<T>)_collection.GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return (IEnumerator)((IEnumerable)_collection).GetEnumerator();\n }\n\n ////////Private data///////\n ICollection<T> _collection;\n}\n\n\nclass Program\n{\n static void Main(string[] args)\n {\n List<int> list = new List<int>();\n\n list.Add(1);\n list.Add(2);\n list.Add(3);\n list.Add(4);\n\n CollectionWrapper<int> collection = new CollectionWrapper<int>(list);\n\n Console.WriteLine(\"Count:{0}\", collection.Count);\n foreach (var x in collection)\n {\n Console.WriteLine(x);\n }\n\n foreach (var x in (IEnumerable)collection)\n {\n Console.WriteLine(x);\n }\n }\n}\n"
},
{
"answer_id": 343538,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "ReadOnlyCollection<T> IList<T>"
},
{
"answer_id": 343803,
"author": "Justin Van Patten",
"author_id": 43620,
"author_profile": "https://Stackoverflow.com/users/43620",
"pm_score": 0,
"selected": false,
"text": "class Program {\n static void Main(string[] args) {\n List<int> list = new List<int>();\n list.Add(1);\n list.Add(2);\n list.Add(3);\n list.Add(4);\n\n ReadOnlyCollection<int> collection = new ReadOnlyCollection<int>(list);\n Console.WriteLine(\"Count:{0}\", collection.Count);\n foreach (var x in collection) {\n Console.WriteLine(x);\n }\n foreach (var x in (IEnumerable)collection) {\n Console.WriteLine(x);\n }\n }\n}\n"
},
{
"answer_id": 10885747,
"author": "svick",
"author_id": 41071,
"author_profile": "https://Stackoverflow.com/users/41071",
"pm_score": 4,
"selected": false,
"text": "IReadOnlyCollection<T> IReadOnlyList<T> IReadOnlyCollection<T> IEnumerable<T> Count IReadOnlyList<T>"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39648/"
] |
343,468 | <p>To do DataBinding of the <code>Document</code> in a WPF <code>RichtextBox</code>, I saw 2 solutions so far, which are to derive from the <code>RichtextBox</code> and add a <code>DependencyProperty</code>, and also the solution with a "proxy".</p>
<p>Neither the first or the second are satisfactory. Does somebody know another solution, or instead, a commercial RTF control which is capable of <strong>DataBinding</strong>? The normal <code>TextBox</code> is not an alternative, since we need text formatting.</p>
<p>Any idea?</p>
| [
{
"answer_id": 343888,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 3,
"selected": false,
"text": " public FlowDocument Document\n {\n get { return (FlowDocument)GetValue(DocumentProperty); }\n set { SetValue(DocumentProperty, value); }\n }\n\n public static readonly DependencyProperty DocumentProperty =\n DependencyProperty.Register(\"Document\", typeof(FlowDocument), typeof(RichTextBoxControl), new PropertyMetadata(OnDocumentChanged));\n\n private static void OnDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n {\n RichTextBoxControl control = (RichTextBoxControl) d;\n FlowDocument document = e.NewValue as FlowDocument;\n if (document == null)\n {\n control.RTB.Document = new FlowDocument(); //Document is not amused by null :)\n }\n else\n {\n control.RTB.Document = document;\n }\n }\n"
},
{
"answer_id": 345275,
"author": "Szymon Rozga",
"author_id": 7583,
"author_profile": "https://Stackoverflow.com/users/7583",
"pm_score": 4,
"selected": false,
"text": "DependencyProperty RichTextBox Document RichTextBox FlowDocument Document FlowDocument DependencyProperty FlowDocument FlowDocument RichTextBox INotifyPropertyChanged DependencyProperty RichTextBox FlowDocument DependencyProperty DependencyObject class HasDocument : DependencyObject\n{\n public static readonly DependencyProperty DocumentProperty =\n DependencyProperty.Register(\"Document\", \n typeof(FlowDocument), \n typeof(HasDocument), \n new PropertyMetadata(new PropertyChangedCallback(DocumentChanged)));\n\n private static void DocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)\n {\n Debug.WriteLine(\"Document has changed\");\n }\n\n public FlowDocument Document\n {\n get { return GetValue(DocumentProperty) as FlowDocument; }\n set { SetValue(DocumentProperty, value); }\n }\n}\n Window <Window x:Class=\"samples.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Flow Document Binding\" Height=\"300\" Width=\"300\"\n >\n <Grid>\n <RichTextBox Name=\"richTextBox\" />\n </Grid>\n</Window>\n Window HasDocument HasDocument hasDocument;\n hasDocument = new HasDocument();\n\nInitializeComponent();\n\nBinding b = new Binding(\"Document\");\nb.Source = richTextBox;\nb.Mode = BindingMode.OneWay;\nBindingOperations.SetBinding(hasDocument, HasDocument.DocumentProperty, b);\n HasDocument FrameworkElement Document HasDocument Document FlowDocument d = new FlowDocument();\nParagraph g = new Paragraph();\nRun a = new Run();\na.Text = \"I showed this using a binding\";\ng.Inlines.Add(a);\nd.Blocks.Add(g);\n\nhasDocument.Document = d;\n"
},
{
"answer_id": 2641774,
"author": "Ray Burns",
"author_id": 199245,
"author_profile": "https://Stackoverflow.com/users/199245",
"pm_score": 8,
"selected": true,
"text": "DocumentXaml DocumentRTF RichTextBox Autobiography <TextBox Text=\"{Binding FirstName}\" />\n<TextBox Text=\"{Binding LastName}\" />\n<RichTextBox local:RichTextBoxHelper.DocumentXaml=\"{Binding Autobiography}\" />\n RichTextBox FlowDocument FlowDocument using System.IO;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\npublic class RichTextBoxHelper : DependencyObject\n{\n public static string GetDocumentXaml(DependencyObject obj)\n {\n return (string)obj.GetValue(DocumentXamlProperty);\n }\n\n public static void SetDocumentXaml(DependencyObject obj, string value)\n {\n obj.SetValue(DocumentXamlProperty, value);\n }\n\n public static readonly DependencyProperty DocumentXamlProperty =\n DependencyProperty.RegisterAttached(\n \"DocumentXaml\",\n typeof(string),\n typeof(RichTextBoxHelper),\n new FrameworkPropertyMetadata\n {\n BindsTwoWayByDefault = true,\n PropertyChangedCallback = (obj, e) =>\n {\n var richTextBox = (RichTextBox)obj;\n\n // Parse the XAML to a document (or use XamlReader.Parse())\n var xaml = GetDocumentXaml(richTextBox);\n var doc = new FlowDocument();\n var range = new TextRange(doc.ContentStart, doc.ContentEnd);\n\n range.Load(new MemoryStream(Encoding.UTF8.GetBytes(xaml)),\n DataFormats.Xaml);\n\n // Set the document\n richTextBox.Document = doc;\n\n // When the document changes update the source\n range.Changed += (obj2, e2) =>\n {\n if (richTextBox.Document == doc)\n {\n MemoryStream buffer = new MemoryStream();\n range.Save(buffer, DataFormats.Xaml);\n SetDocumentXaml(richTextBox,\n Encoding.UTF8.GetString(buffer.ToArray()));\n }\n };\n }\n });\n}\n byte[] string"
},
{
"answer_id": 2989277,
"author": "Krzysztof",
"author_id": 360374,
"author_profile": "https://Stackoverflow.com/users/360374",
"pm_score": 4,
"selected": false,
"text": "public class RichTextBoxHelper : DependencyObject\n{\n private static HashSet<Thread> _recursionProtection = new HashSet<Thread>();\n\n public static string GetDocumentXaml(DependencyObject obj)\n {\n return (string)obj.GetValue(DocumentXamlProperty);\n }\n\n public static void SetDocumentXaml(DependencyObject obj, string value)\n {\n _recursionProtection.Add(Thread.CurrentThread);\n obj.SetValue(DocumentXamlProperty, value);\n _recursionProtection.Remove(Thread.CurrentThread);\n }\n\n public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(\n \"DocumentXaml\", \n typeof(string), \n typeof(RichTextBoxHelper), \n new FrameworkPropertyMetadata(\n \"\", \n FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,\n (obj, e) => {\n if (_recursionProtection.Contains(Thread.CurrentThread))\n return;\n\n var richTextBox = (RichTextBox)obj;\n\n // Parse the XAML to a document (or use XamlReader.Parse())\n\n try\n {\n var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));\n var doc = (FlowDocument)XamlReader.Load(stream);\n\n // Set the document\n richTextBox.Document = doc;\n }\n catch (Exception)\n {\n richTextBox.Document = new FlowDocument();\n }\n\n // When the document changes update the source\n richTextBox.TextChanged += (obj2, e2) =>\n {\n RichTextBox richTextBox2 = obj2 as RichTextBox;\n if (richTextBox2 != null)\n {\n SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));\n }\n };\n }\n )\n );\n}\n"
},
{
"answer_id": 3659817,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 1,
"selected": false,
"text": "Public Class RichTextBoxHelper\nInherits DependencyObject\n\nPrivate Shared _recursionProtection As New HashSet(Of System.Threading.Thread)()\n\nPublic Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As String\n Return DirectCast(depObj.GetValue(DocumentXamlProperty), String)\nEnd Function\n\nPublic Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As String)\n _recursionProtection.Add(System.Threading.Thread.CurrentThread)\n depObj.SetValue(DocumentXamlProperty, value)\n _recursionProtection.Remove(System.Threading.Thread.CurrentThread)\nEnd Sub\n\nPublic Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached(\"DocumentXaml\", GetType(String), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata(\"\", FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e)\n RegisterIt(depObj, e)\n End Sub))\n\nPrivate Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)\n If _recursionProtection.Contains(System.Threading.Thread.CurrentThread) Then\n Return\n End If\n Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox)\n Try\n rtb.Document = Markup.XamlReader.Parse(GetDocumentXaml(rtb))\n Catch\n rtb.Document = New FlowDocument()\n End Try\n ' When the document changes update the source\n AddHandler rtb.TextChanged, AddressOf TextChanged\nEnd Sub\n\nPrivate Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)\n Dim rtb As RichTextBox = TryCast(sender, RichTextBox)\n If rtb IsNot Nothing Then\n SetDocumentXaml(sender, Markup.XamlWriter.Save(rtb.Document))\n End If\nEnd Sub\n"
},
{
"answer_id": 3675460,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 0,
"selected": false,
"text": " ' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary\n' Loading document here because Loaded is the last available event to create a document\nPrivate Sub Rtb_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n ' only good place to initialize RichTextBox.Document with DependencyProperty\n Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)\n Try\n rtb.Document = RichTextBoxHelper.GetDocumentXaml(rtb)\n Catch ex As Exception\n Debug.WriteLine(\"Rtb_Loaded: Message:\" & ex.Message)\n End Try\nEnd Sub\n\n' Loaded and Unloaded events seems to be the only way to initialize a control created from a Resource Dictionary\n' Free document being held by RichTextBox.Document by assigning New FlowDocument to RichTextBox.Document. Otherwise we'll see an of \"Document belongs to another RichTextBox\"\nPrivate Sub Rtb_Unloaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n Dim rtb As RichTextBox = DirectCast(sender, RichTextBox)\n Dim fd As New FlowDocument\n RichTextBoxHelper.SetDocumentXaml(rtb, fd)\n Try\n rtb.Document = fd\n Catch ex As Exception\n Debug.WriteLine(\"PoemDocument.PoemDocumentView.PoemRtb_Unloaded: Message:\" & ex.Message)\n End Try\nEnd Sub\n\nPublic Class RichTextBoxHelper\n Inherits DependencyObject\n\n Public Shared Function GetDocumentXaml(ByVal depObj As DependencyObject) As FlowDocument\n Return depObj.GetValue(DocumentXamlProperty)\n End Function\n\n Public Shared Sub SetDocumentXaml(ByVal depObj As DependencyObject, ByVal value As FlowDocument)\n depObj.SetValue(DocumentXamlProperty, value)\n End Sub\n\n Public Shared ReadOnly DocumentXamlProperty As DependencyProperty = DependencyProperty.RegisterAttached(\"DocumentXaml\", GetType(FlowDocument), GetType(RichTextBoxHelper), New FrameworkPropertyMetadata(Nothing, FrameworkPropertyMetadataOptions.AffectsRender Or FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, Sub(depObj, e)\n RegisterIt(depObj, e)\n End Sub))\n\n\n Private Shared Sub RegisterIt(ByVal depObj As System.Windows.DependencyObject, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)\n Dim rtb As RichTextBox = DirectCast(depObj, RichTextBox)\n If rtb.IsLoaded Then\n RemoveHandler rtb.TextChanged, AddressOf TextChanged\n Try\n rtb.Document = GetDocumentXaml(rtb)\n Catch ex As Exception\n Debug.WriteLine(\"RichTextBoxHelper.RegisterIt: ex:\" & ex.Message)\n rtb.Document = New FlowDocument()\n End Try\n AddHandler rtb.TextChanged, AddressOf TextChanged\n Else\n Debug.WriteLine(\"RichTextBoxHelper: Unloaded control ignored:\" & rtb.Name)\n End If\n End Sub\n\n ' When a RichTextBox Document changes, update the DependencyProperty so they're in sync.\n Private Shared Sub TextChanged(ByVal sender As Object, ByVal e As TextChangedEventArgs)\n Dim rtb As RichTextBox = TryCast(sender, RichTextBox)\n If rtb IsNot Nothing Then\n SetDocumentXaml(sender, rtb.Document)\n End If\n End Sub\n\nEnd Class\n"
},
{
"answer_id": 25948442,
"author": "djack109",
"author_id": 985197,
"author_profile": "https://Stackoverflow.com/users/985197",
"pm_score": 0,
"selected": false,
"text": "<RichTextBox>\n <FlowDocument>\n <Paragraph>\n <Run Text=\"{Binding Mytextbinding}\"/>\n </Paragraph>\n </FlowDocument>\n</RichTextBox>\n"
},
{
"answer_id": 47054534,
"author": "FakeCaleb",
"author_id": 6721384,
"author_profile": "https://Stackoverflow.com/users/6721384",
"pm_score": 4,
"selected": false,
"text": " <RichTextBox>\n <FlowDocument PageHeight=\"180\">\n <Paragraph>\n <Run Text=\"{Binding Text, Mode=TwoWay}\"/>\n </Paragraph>\n </FlowDocument>\n </RichTextBox>\n Text"
},
{
"answer_id": 48909764,
"author": "Ajeeb.K.P",
"author_id": 3001007,
"author_profile": "https://Stackoverflow.com/users/3001007",
"pm_score": 3,
"selected": false,
"text": "_recursionProtection Guid public class RichTextBoxHelper : DependencyObject\n {\n private static List<Guid> _recursionProtection = new List<Guid>();\n\n public static string GetDocumentXaml(DependencyObject obj)\n {\n return (string)obj.GetValue(DocumentXamlProperty);\n }\n\n public static void SetDocumentXaml(DependencyObject obj, string value)\n {\n var fw1 = (FrameworkElement)obj;\n if (fw1.Tag == null || (Guid)fw1.Tag == Guid.Empty)\n fw1.Tag = Guid.NewGuid();\n _recursionProtection.Add((Guid)fw1.Tag);\n obj.SetValue(DocumentXamlProperty, value);\n _recursionProtection.Remove((Guid)fw1.Tag);\n }\n\n public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(\n \"DocumentXaml\",\n typeof(string),\n typeof(RichTextBoxHelper),\n new FrameworkPropertyMetadata(\n \"\",\n FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,\n (obj, e) =>\n {\n var richTextBox = (RichTextBox)obj;\n if (richTextBox.Tag != null && _recursionProtection.Contains((Guid)richTextBox.Tag))\n return;\n\n\n // Parse the XAML to a document (or use XamlReader.Parse())\n\n try\n {\n string docXaml = GetDocumentXaml(richTextBox);\n var stream = new MemoryStream(Encoding.UTF8.GetBytes(docXaml));\n FlowDocument doc;\n if (!string.IsNullOrEmpty(docXaml))\n {\n doc = (FlowDocument)XamlReader.Load(stream);\n }\n else\n {\n doc = new FlowDocument();\n }\n\n // Set the document\n richTextBox.Document = doc;\n }\n catch (Exception)\n {\n richTextBox.Document = new FlowDocument();\n }\n\n // When the document changes update the source\n richTextBox.TextChanged += (obj2, e2) =>\n {\n RichTextBox richTextBox2 = obj2 as RichTextBox;\n if (richTextBox2 != null)\n {\n SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));\n }\n };\n }\n )\n );\n }\n <RichTextBox local:RichTextBoxHelper.DocumentXaml=\"{Binding Autobiography}\" />\n"
},
{
"answer_id": 66459117,
"author": "Vladdy",
"author_id": 5238704,
"author_profile": "https://Stackoverflow.com/users/5238704",
"pm_score": 2,
"selected": false,
"text": " TestText = @\"<FlowDocument xmlns=\"\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\"><Paragraph><Bold>Hello World!</Bold></Paragraph></FlowDocument>\";\n <RichTextBox local:RichTextBoxHelper.DocumentXaml=\"{Binding TestText}\"/>\n public class RichTextBoxHelper : DependencyObject\n{\n public static string GetDocumentXaml(DependencyObject obj) { return (string) obj.GetValue(DocumentXamlProperty); }\n\n public static void SetDocumentXaml(DependencyObject obj,\n string value)\n {\n obj.SetValue(DocumentXamlProperty, value);\n }\n\n public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached\n (\n \"DocumentXaml\",\n typeof(string),\n typeof(RichTextBoxHelper),\n new FrameworkPropertyMetadata\n {\n BindsTwoWayByDefault = true,\n PropertyChangedCallback = (obj,\n e) =>\n {\n var richTextBox = (RichTextBox) obj;\n var xaml = GetDocumentXaml(richTextBox);\n Stream sm = new MemoryStream(Encoding.UTF8.GetBytes(xaml));\n richTextBox.Document = (FlowDocument) XamlReader.Load(sm);\n sm.Close();\n }\n }\n );\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41407/"
] |
343,476 | <p>I'm using the Win32 <code>CreateProcess</code> function to perform a call to an external executable. The executable returns a string.</p>
<p>Is there a way I can capture and interrogate the returned string after calling the executable? Failing that, I might have to write out the string to a file in the executable and read that in the calling program after the call has finished. That seems lame though.</p>
| [
{
"answer_id": 343489,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 1,
"selected": false,
"text": "var\n fMapping : THandle;\n pMapData : Pointer;\n\nfMapping := CreateFileMapping($FFFFFFFF, nil, PAGE_READWRITE,\n 0, MAPFILESIZE, pchar('MAP NAME GOES HERE'));\n\nPMapData := MapViewOfFile(fMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0);\n if PMapData <> nil then\n UnMapViewOfFile(PMapData);\nif fMapping <> 0 then\n CloseHandle(fMapping);\n"
},
{
"answer_id": 343564,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 2,
"selected": false,
"text": "yourprog.exe > results.txt\n results.txt"
},
{
"answer_id": 343610,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 4,
"selected": true,
"text": "function CreateDOSProcessRedirected(const CommandLine, InputFile, OutputFile: string): Boolean;\nvar\n StartupInfo: TStartupInfo;\n ProcessInfo: TProcessInformation;\n SecAtrrs: TSecurityAttributes;\n hInputFile, hOutputFile: THandle;\nbegin\n Result := False;\n hInputFile := CreateFile(PChar(InputFile), GENERIC_READ, FILE_SHARE_READ,\n CreateInheritable(SecAtrrs), OPEN_EXISTING, FILE_ATTRIBUTE_TEMPORARY, 0);\n if hInputFile <> INVALID_HANDLE_VALUE then\n begin\n hOutputFile := CreateFile(PChar(OutPutFile), GENERIC_READ or GENERIC_WRITE,\n FILE_SHARE_READ, CreateInheritable(SecAtrrs), CREATE_ALWAYS,\n FILE_ATTRIBUTE_TEMPORARY, 0);\n if hOutputFile <> INVALID_HANDLE_VALUE then\n begin\n FillChar(StartupInfo, SizeOf(StartupInfo), #0);\n StartupInfo.cb := SizeOf(StartupInfo);\n StartupInfo.dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;\n StartupInfo.wShowWindow := SW_HIDE;\n StartupInfo.hStdOutput := hOutputFile;\n StartupInfo.hStdInput := hInputFile;\n Result := CreateProcess(nil, PChar(CommandLine), nil, nil, True,\n CREATE_NEW_CONSOLE or NORMAL_PRIORITY_CLASS, nil, nil, StartupInfo,\n ProcessInfo);\n if Result then\n begin\n WaitForSingleObject(ProcessInfo.hProcess, INFINITE);\n CloseHandle(ProcessInfo.hProcess);\n CloseHandle(ProcessInfo.hThread);\n end;\n CloseHandle(hOutputFile);\n end;\n CloseHandle(hInputFile);\n end;\nend;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7703/"
] |
343,491 | <p>Here's some code I saw once. Can you see what's wrong with it?</p>
<p>[updated]</p>
<pre><code>public class ResourceManager1
{
private final String mutex = "";
Object resource = null;
public Object getResource()
{
synchronized (mutex)
{
if (resource == null)
{
resource = new Object();
}
}
return resource;
}
}
public class ResourceManager2
{
private final String mutex = "";
Object resource = null;
public Object getResource()
{
synchronized (mutex)
{
if (resource == null)
{
resource = new Object();
}
}
return resource;
}
}
</code></pre>
| [
{
"answer_id": 343507,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "private final"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17641/"
] |
343,517 | <p>I want to use git to allow me to work on several features in a module I'm writing concurrently. I'm currently using SVN, with only one workspace, so I just have the workspace on my PYTHONPATH. I'm realizing this is less than ideal, so I was wondering if anyone could suggest a more 'proper' way of doing this.</p>
<p>Let me elaborate with a hypothetical situation:
I say I have a module 'eggs', with sub-modules 'foo' and 'bar'. Components in 'bar' use code in foo, so eggs/bar/a.py may 'import eggs.foo'. </p>
<p>Say that 'eggs' is in a git repository. I want to try out some changes to 'foo', so I copy it. The problem is that 'import eggs.foo' in eggs/bar finds the original repository in the PYTHONPATH, so it ends up using the old 'foo' instead of my modified one. </p>
<p>How do I set myself up such that each copy of the module uses its own associated 'foo'? Thanks.</p>
<p>edit- Thanks for the pointer to relative imports. I've read up on it and I can see how to apply it. One problem I'd have with using it is that I've built up a fairly large codebase, and I haven't been too neat about it so most modules have a quick 'self-test' under <code>if __name__ == '__main__':</code>, which from what I've read does not play with relative imports: </p>
<ul>
<li><p><a href="http://mail.python.org/pipermail/python-list/2006-October/408945.html" rel="nofollow noreferrer">http://mail.python.org/pipermail/python-list/2006-October/408945.html</a></p></li>
<li><p><a href="http://www.velocityreviews.com/forums/t502905-relative-import-broken.html" rel="nofollow noreferrer">http://www.velocityreviews.com/forums/t502905-relative-import-broken.html</a></p></li>
</ul>
<p>The other solution I've been able to google up is to deliberately manipulate sys.path, which seems like an even worse hack. Are there any other possibilities?</p>
<p>edit - Thanks for the suggestions. I'd originally misunderstood git branches, so as pointed out branches are exactly what I want. Nonetheless, I hadn't heard of relative imports before so thanks for that as well. I've learnt something new and may incorporate its use.</p>
| [
{
"answer_id": 343534,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "eggs/\n __init__.py\n foo.py\n bar.py\n\n# foo.py\nfrom __future__ import absolute_import\nfrom . import bar\n eggs.foo eggs.bar.a git $ git status\n# On branch master\nnothing to commit (working directory clean)\n $ git checkout -b experimental\nSwitched to a new branch \"experimental\"\n $ git commit -a\n $ git checkout master\nSwitched to branch \"master\"\n $ git commit -a\n $ git merge experimental\n"
},
{
"answer_id": 343614,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "eggs.bar.a eggs.foo eggs eggs.foo eggs.foo eggs.foo eggs.quux PYTHONPATH"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37984/"
] |
343,518 | <p>Inside a windows batch file I'd like to figure out what the fully qualified path name of this batch file is.</p>
<p>I have tried <code>%0</code> but this does only gave me the typed command (e.g. just the file name without path or extension).</p>
| [
{
"answer_id": 343531,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": 3,
"selected": false,
"text": "%CD% %~dp0 c:\\folder c:\\otherfolder %CD% C:\\otherfolder %~dp0 c:\\folder"
},
{
"answer_id": 343823,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 6,
"selected": true,
"text": "echo %~f0\n for /? cmd"
},
{
"answer_id": 343846,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 5,
"selected": false,
"text": "/E:ON Enable command extensions (see below)\n/E:OFF Disable command extensions (see below)\n for /? cmd In addition, substitution of FOR variable references has been enhanced.\nYou can now use the following optional syntax:\n\n %~I - expands %I removing any surrounding quotes (\")\n %~fI - expands %I to a fully qualified path name\n %~dI - expands %I to a drive letter only\n %~pI - expands %I to a path only\n %~nI - expands %I to a file name only\n %~xI - expands %I to a file extension only\n %~sI - expanded path contains short names only\n %~aI - expands %I to file attributes of file\n %~tI - expands %I to date/time of file\n %~zI - expands %I to size of file\n %~$PATH:I - searches the directories listed in the PATH\n environment variable and expands %I to the\n fully qualified name of the first one found.\n If the environment variable name is not\n defined or the file is not found by the\n search, then this modifier expands to the\n empty string\n\nThe modifiers can be combined to get compound results:\n\n %~dpI - expands %I to a drive letter and path only\n %~nxI - expands %I to a file name and extension only\n %~fsI - expands %I to a full path name with short names only\n %~dp$PATH:I - searches the directories listed in the PATH\n environment variable for %I and expands to the\n drive letter and path of the first one found.\n %~ftzaI - expands %I to a DIR like output line\n\nIn the above examples %I and PATH can be replaced by other valid\nvalues. The %~ syntax is terminated by a valid FOR variable name.\nPicking upper case variable names like %I makes it more readable and\navoids confusion with the modifiers, which are not case sensitive.\n"
},
{
"answer_id": 343957,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 1,
"selected": false,
"text": "%~f0\n %~dpnx0\n"
},
{
"answer_id": 41449724,
"author": "Robert Cody",
"author_id": 7370757,
"author_profile": "https://Stackoverflow.com/users/7370757",
"pm_score": 0,
"selected": false,
"text": "FIRST.BAT call second.bat %0 parameter-a parameter-b\n SECOND.BAT echo The name of this called script should be \"SECOND\", proof: %~n0\necho The 1st parameter passed should be \"FIRST\", proof: %1\nshift\necho The name of the calling script should be \"FIRST\", proof: %~n0\necho The 1st parameter should be \"parameter-a\", proof: %1\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343518",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25782/"
] |
343,521 | <p>Using TeamCity, I'm trying to get a (TestAutomationFX) test that requires an STA thread to run .</p>
<p>It works via a custom app.config that configures NUnit 2.4.x (8) (as referred to by Gishu, thanks, described at <a href="http://madcoderspeak.blogspot.com/2008/12/getting-nunit-to-go-all-sta.html" rel="nofollow noreferrer">http://madcoderspeak.blogspot.com/2008/12/getting-nunit-to-go-all-sta.html</a>)</p>
<p>It works via:</p>
<pre><code>/// <summary>
/// Via Peter Provost / http://www.hedgate.net/articles/2007/01/08/instantiating-a-wpf-control-from-an-nunit-test/
/// </summary>
public static class CrossThreadTestRunner // To be replaced with (RequiresSTA) from NUnit 2.5
{
public static void RunInSTA(Action userDelegate)
{
Exception lastException = null;
Thread thread = new Thread(delegate()
{
try
{
userDelegate();
}
catch (Exception e)
{
lastException = e;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (lastException != null)
ThrowExceptionPreservingStack(lastException);
}
[ReflectionPermission(SecurityAction.Demand)]
static void ThrowExceptionPreservingStack(Exception exception)
{
FieldInfo remoteStackTraceString = typeof(Exception).GetField(
"_remoteStackTraceString",
BindingFlags.Instance | BindingFlags.NonPublic);
remoteStackTraceString.SetValue(exception, exception.StackTrace + Environment.NewLine);
throw exception;
}
}
</code></pre>
<p>I'm hoping to use something built in. So NUnit 2.5.0.8322 (Beta 1)'s RequiresSTAAttribute seems ideal. It works standalone, but not via TeamCity, even when I attempt to force the issue via:</p>
<pre><code><NUnit Assemblies="Test\bin\$(Configuration)\Test.exe" NUnitVersion="NUnit-2.5.0" />
</code></pre>
<p>The docs say the runner supports 2.5.0 alpha 4? (<a href="http://www.jetbrains.net/confluence/display/TCD4/NUnit+for+MSBuild" rel="nofollow noreferrer">http://www.jetbrains.net/confluence/display/TCD4/NUnit+for+MSBuild</a>)</p>
<p>Probably answering my own question, 2.5.0 Aplha 4 doesnt have RequiresSTAAttribute, hence the runner is not honouring my Attribute...</p>
| [
{
"answer_id": 343589,
"author": "Ruben Bartelink",
"author_id": 11635,
"author_profile": "https://Stackoverflow.com/users/11635",
"pm_score": 0,
"selected": false,
"text": " private void ForceSTAIfNecessary(ThreadStart threadStart)\n {\n if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)\n threadStart();\n else\n CrossThreadTestRunner.RunInSTA(threadStart);\n }\n\n [Test]\n public void TestRunApp()\n {\n ForceSTAIfNecessary(TestRunAppSTA);\n }\n\n public void TestRunAppSTA()\n {\n Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA));\n ...\n }\n [RequiresSTA]\n public void TestRunAppSTA()\n {\n Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA));\n ...\n }\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11635/"
] |
343,528 | <p>I'm looking for a <em>SimpleGrepSedPerlOrPythonOneLiner</em> that outputs all quotations in a text.</p>
<hr>
<p>Example 1:</p>
<pre><code>echo “HAL,” noted Frank, “said that everything was going extremely well.” | SimpleGrepSedPerlOrPythonOneLiner
</code></pre>
<p>stdout:</p>
<pre><code>"HAL,"
"said that everything was going extremely well.”
</code></pre>
<hr>
<p>Example 2:</p>
<pre><code>cat MicrosoftWindowsXPEula.txt | SimpleGrepSedPerlOrPythonOneLiner
</code></pre>
<p>stdout:</p>
<pre><code>"EULA"
"Software"
"Workstation Computer"
"Device"
"DRM"
</code></pre>
<p>etc.</p>
<p>(<a href="http://www.microsoft.com/windowsxp/eula/home.mspx" rel="nofollow noreferrer">link to the corresponding text</a>).</p>
| [
{
"answer_id": 343555,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "grep -o \"\\\"[^\\\"]*\\\"\"\n \" \""
},
{
"answer_id": 343559,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "$ echo \\\"HAL,\\\" noted Frank, \\\"said that everything was going extremely well\\\" \n | perl -n -e 'while (m/(\".*?\")/g) { print $1.\"\\n\"; }'\n\"HAL,\"\n\"said that everything was going extremely well\"\n\n$ cat eula.txt| perl -n -e 'while (m/(\".*?\")/g) { print $1.\"\\n\"; }'\n\"EULA\"\n\"online\"\n\"Software\"\n\"Workstation Computer\"\n\"Device\"\n\"multiplexing\"\n\"DRM\"\n\"Secure Content\"\n\"DRM Software\"\n\"Secure Content Owners\"\n\"DRM Upgrades\"\n\"WMFSDK\"\n\"Not For Resale\"\n\"NFR,\"\n\"Academic Edition\"\n\"AE,\"\n\"Qualified Educational User.\"\n\"Exclusion of Incidental, Consequential and Certain Other Damages\"\n\"Restricted Rights\"\n\"Exclusion des dommages accessoires, indirects et de certains autres dommages\"\n\"Consumer rights\"\n"
},
{
"answer_id": 343845,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 4,
"selected": true,
"text": "perl -ne 'print \"$_\\n\" foreach /\"((?>[^\"\\\\]|\\\\+[^\"]|\\\\(?:\\\\\\\\)*\")*)\"/g;'\n my $re = qr{\n \" # Begin it with literal quote\n ( \n (?> # prevent backtracking once the alternation has been\n # satisfied. It either agrees or it does not. This expression\n # only needs one direction, or we fail out of the branch\n\n [^\"\\\\] # a character that is not a dquote or a backslash\n | \\\\+ # OR if a backslash, then any number of backslashes followed by \n [^\"] # something that is not a quote\n | \\\\ # OR again a backslash\n (?>\\\\\\\\)* # followed by any number of *pairs* of backslashes (as units)\n \" # and a quote\n )* # any number of *set* qualifying phrases\n ) # all batched up together\n \" # Ended by a literal quote\n}x;\n /\"([^\"]*)\"/ \n"
},
{
"answer_id": 2552391,
"author": "SergioAraujo",
"author_id": 2571881,
"author_profile": "https://Stackoverflow.com/users/2571881",
"pm_score": 0,
"selected": false,
"text": "grep -o '\"[^\"]*\"' file\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4085/"
] |
343,533 | <p>I am trying to build a function grapher,</p>
<p>The user enters xmin, xmax, ymin, ymax, function.
I got the x, y for all points.</p>
<p>Now i want to translate this initial referential to a Canvas starting at 0,0 up to
250,250.</p>
<p>Is there a short way or should i just check </p>
<pre><code>if x < 0
new x = (x - xmin) * (250 / (xmax - xmin)) ?
</code></pre>
<p>etc ..</p>
<p>Also this basic approach does not optimise sampling.
For example if my function f(x) = 5 i dont need to sample the xrange in 500 points,
i only need two points. I could do some heuristic checks.</p>
<p>But for a function like sin(2/x) i need more sampling around x (-1,1) how would you aproach such a thing ?</p>
<p>Thanks</p>
| [
{
"answer_id": 343771,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 0,
"selected": false,
"text": "(canvas_x, canvas_y) -> (maths_x, maths_y)\n(maths_x, maths_y) -> (canvas_x, canvas_y)\n\nmaths_x -> maths_y\n maths_x = maths_x_from_canvas_x(canvas_x, min_maths_x, max_maths_x)\nmaths_y = maths_y_from_maths_x(maths_x) # this is the function to be plotted.\ncanvas_y = canvas_y_from_maths_y(maths_y, min_maths_y, max_maths_y)\n\nif (canvas_y not out of bounds) plot(canvas_x, canvas_y)\n y = 5"
},
{
"answer_id": 344620,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 1,
"selected": false,
"text": "for (int xcanvas = 0; xcanvas <= 250; i++) {\n double x = ((xmax - xmin) * xcanvas / 250.0) + xmin;\n double y = f(x);\n\n int ycanvas = 250 * (y - ymin) / (ymax - ymin) + .5;\n\n // Plot (xcanvas, ycanvas)\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32032/"
] |
343,553 | <p>I am not a Delphi programmer, but I I got an old Delphi 7 application that I need to fix and it is using ADO.</p>
<p>The database table (MS Accesss) contains +100,000 rows and when I set the ADOTable.Active=true it starts to load the entire table into RAM and that takes a lot of memory and time.</p>
<p>How can I prevent ADO to load the entire table? I tried to set the MaxRecords but it does not help.</p>
<p>Basically all we do is att program startup:</p>
<pre><code>// Connect to database
DataModule.MyADOConnection.Connected:=true;
DataModule.MeasurementsADOTable.MaxRecords:=1;
// Open datatables
DataModule.MeasurementsADOTable.Active:=true;
</code></pre>
<p>After setting Active=true it starts to load the entire measurements into RAM and it takes TIME!</p>
<p>We are using the MSDASQL.1 provider. Perhaps it does not support the MaxRecords property?</p>
<p>How do I add some limiting query into this data object to only "load TOP 1 * from Measurements" ?</p>
| [
{
"answer_id": 356686,
"author": "Fabricio Araujo",
"author_id": 10300,
"author_profile": "https://Stackoverflow.com/users/10300",
"pm_score": 3,
"selected": false,
"text": "procedure ConfigCDSFromAdoQuery(p_ADOQ: TADOQuery; p_CDS: TClientDataset; p_Prov: TDatasetProvider);\nbegin\n If p_ADOQ.Active then p_ADOQ.Close;\n p_ADOQ.CursorLocation := clServer;\n p_ADOQ.CursorType := ctOpenForwardOnly;\n p_Prov.Dataset := p_ADOQ;\n p_CDS.SetProvider(p_Prov);\n p_CDS.PacketRecords := 100;\n p_CDS.Open; \nend ;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38165/"
] |
343,556 | <p>I have 10 websites on an IP. I would like to share the IP among all the websites.How do I achieve this without having to run these websites on different port numbers?</p>
| [
{
"answer_id": 356686,
"author": "Fabricio Araujo",
"author_id": 10300,
"author_profile": "https://Stackoverflow.com/users/10300",
"pm_score": 3,
"selected": false,
"text": "procedure ConfigCDSFromAdoQuery(p_ADOQ: TADOQuery; p_CDS: TClientDataset; p_Prov: TDatasetProvider);\nbegin\n If p_ADOQ.Active then p_ADOQ.Close;\n p_ADOQ.CursorLocation := clServer;\n p_ADOQ.CursorType := ctOpenForwardOnly;\n p_Prov.Dataset := p_ADOQ;\n p_CDS.SetProvider(p_Prov);\n p_CDS.PacketRecords := 100;\n p_CDS.Open; \nend ;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39312/"
] |
343,557 | <p>Is there a way to distinguish if a script was invoked from the command line or by the web server? </p>
<p>(<strong>See <a href="https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s">What is the canonical way to determine commandline vs. http execution of a PHP script?</a> for best answer</strong> and more detailed discussion - didn't find that one before posting)</p>
<hr>
<p>I have a (non-production) server with Apache 2.2.10 and PHP 5.2.6. On it, in a web-accessible directory is my PHP script, <code>maintenance_tasks.php</code>. I would like to invoke this script from the command line or through a HTTP request (by opening in a browser). Is there some variable that allows me to reliably determine how script is invoked?</p>
<p>(I already tackled the issues of different views for each type of invocation and HTTP response timeout, just looking for a way of telling the two invocation types apart)</p>
<p>I'll be trying different things and add my findings below.</p>
<p><strong>Duplicate:</strong> <a href="https://stackoverflow.com/questions/173851/what-is-the-canonical-way-to-determine-commandline-vs-http-execution-of-a-php-s">What is the canonical way to determine commandline vs. http execution of a PHP script?</a></p>
| [
{
"answer_id": 343569,
"author": "Nuramon",
"author_id": 43583,
"author_profile": "https://Stackoverflow.com/users/43583",
"pm_score": 8,
"selected": true,
"text": "define(\"CLI\", !isset($_SERVER['HTTP_USER_AGENT']));\n php_sapi_name() == 'cli' PHP_SAPI == 'cli'"
},
{
"answer_id": 343580,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 2,
"selected": false,
"text": "$_SERVER $_SERVER['argc'] <?php\nif (isset($_SERVER['argc'])) {\n define('CLI', true);\n} else {\n define('CLI', false);\n}\n $_SERVER['HTTP_*']"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19746/"
] |
343,561 | <p>I want to achieve going to the parent element then to the prev element get the atrribute id of the element which has class: classname.</p>
<pre><code><div>
<span><span id="190" class="classname">blabla</span></span>
<span><a href="#" class="button">blabla</a></span>
</div>
</code></pre>
<p>Pseudo code:</p>
<pre><code>$('.button').click(function(){
console.log($(this).parent().prev().$(".classname").attr("id"));
});
</code></pre>
<p>Do I have to use a find here or is there another way?</p>
| [
{
"answer_id": 343582,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 0,
"selected": false,
"text": "find"
},
{
"answer_id": 343601,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "$(this).parent().prev().children( '.classname' ).attr( 'id' );\n"
},
{
"answer_id": 345478,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 0,
"selected": false,
"text": "alert($(this).parents(\"div\").find(\".classname\").attr( 'id' ));\n alert($(this).parents(\"div\").find(\"span span\").attr( 'id' ));\n"
},
{
"answer_id": 5643897,
"author": "ianace",
"author_id": 572270,
"author_profile": "https://Stackoverflow.com/users/572270",
"pm_score": 0,
"selected": false,
"text": "<div> find $(this).parent().prev().children( '.classname' ).attr( 'id' );\n"
},
{
"answer_id": 9414517,
"author": "alexg",
"author_id": 1223744,
"author_profile": "https://Stackoverflow.com/users/1223744",
"pm_score": 0,
"selected": false,
"text": "$('.button').click(function(){\n console.log( $('.classname', $(this).parent() ).attr('id') );\n});\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,562 | <p>I need some SQL to update a record in a database if it exists and insert it when it does not, looking around there looks to be several solutions for this, but I don't know what are the correct/ accepted ways to do this.</p>
<p>I would ideally like it to work on both Firebird 2 and MySQL 5 as the update will need to be ran against both databases, and it would be simpler if the same SQL ran on both, if it worked on more database that would be a plus.</p>
<p>Speed and reliability also factor in, reliability over speed in this case but it will potentially be used to update 1000's of records in quick succession (over different tables).</p>
<p>any subjections?</p>
| [
{
"answer_id": 343579,
"author": "xahtep",
"author_id": 42184,
"author_profile": "https://Stackoverflow.com/users/42184",
"pm_score": 1,
"selected": false,
"text": "REPLACE"
},
{
"answer_id": 343591,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 0,
"selected": false,
"text": "{ VALUES | VALUE} \n\n({expr | DEFAULT},...),(...),...\n"
},
{
"answer_id": 343603,
"author": "Smokey Bacon Esq.",
"author_id": 43595,
"author_profile": "https://Stackoverflow.com/users/43595",
"pm_score": 3,
"selected": true,
"text": "BEGIN TRANSACTION\nIF EXISTS (SELECT * FROM the_table WHERE pk = 'whatever')\n UPDATE the_table SET data = 'stuff' WHERE pk = 'whatever'\nELSE\n INSERT INTO the_table (pk, data) VALUES ('whatever', 'stuff')\nCOMMIT\n INSERT INTO the_table (pk, data) VALUES ('whatever', 'stuff')\n\nUPDATE the_table SET data = 'stuff' WHERE pk = 'whatever'\n"
},
{
"answer_id": 343645,
"author": "charlesbridge",
"author_id": 22738,
"author_profile": "https://Stackoverflow.com/users/22738",
"pm_score": 0,
"selected": false,
"text": "INSERT INTO table () VALUES () ON DUPLICATE KEY UPDATE key"
},
{
"answer_id": 1179896,
"author": "Marco",
"author_id": 138137,
"author_profile": "https://Stackoverflow.com/users/138137",
"pm_score": 2,
"selected": false,
"text": "insert into table (id, a, b, c) values (:id, :a, :b, :c)\nwhen SQLCODE -803 \ndo\nbegin\n update table set a = :a, b = :b, c = :c where id = :id;\nend;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2098/"
] |
343,584 | <p>How do I get whole and fractional parts from double in JSP/Java ? If the value is 3.25 then I want to get <code>fractional =.25</code>, <code>whole = 3</code></p>
<p>How can we do this in Java?</p>
| [
{
"answer_id": 343598,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 3,
"selected": false,
"text": "long bits = Double.doubleToLongBits(3.25);\n\nboolean isNegative = (bits & 0x8000000000000000L) != 0; \nlong exponent = (bits & 0x7ff0000000000000L) >> 52;\nlong mantissa = bits & 0x000fffffffffffffL;\n"
},
{
"answer_id": 343602,
"author": "Dan Vinton",
"author_id": 21849,
"author_profile": "https://Stackoverflow.com/users/21849",
"pm_score": 7,
"selected": false,
"text": "double value = 3.25;\ndouble fractionalPart = value % 1;\ndouble integralPart = value - fractionalPart;\n"
},
{
"answer_id": 343621,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 2,
"selected": false,
"text": "exponent = int(log(n))\nmantissa = n / 10^exponent\n exponent = int(n)\nmantissa = n - exponent\n"
},
{
"answer_id": 343629,
"author": "Pete Kirkham",
"author_id": 1527,
"author_profile": "https://Stackoverflow.com/users/1527",
"pm_score": 3,
"selected": false,
"text": "value = sign * (1 + mantissa) * pow(2, exponent)\n integral = Math.floor(x)\nfractional = x - Math.floor(x)\n (floor(-3.5) == -4.0)"
},
{
"answer_id": 343643,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 8,
"selected": true,
"text": "double num;\nlong iPart;\ndouble fPart;\n\n// Get user input\nnum = 2.3d;\niPart = (long) num;\nfPart = num - iPart;\nSystem.out.println(\"Integer part = \" + iPart);\nSystem.out.println(\"Fractional part = \" + fPart);\n Integer part = 2\nFractional part = 0.2999999999999998\n"
},
{
"answer_id": 721061,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "public class MyMain2 {\n public static void main(String[] args) {\n double myDub;\n myDub=1234.5678;\n long myLong;\n myLong=(int)myDub;\n myDub=(myDub%1)*10000;\n int myInt=(int)myDub;\n System.out.println(myLong + \"\\n\" + myInt);\n }\n}\n"
},
{
"answer_id": 2257643,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 5,
"selected": false,
"text": "/WEB-INF/lib <fmt:formatNumber> maxFractionDigits maxIntegerDigits <%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\" %>\n\n<%\n // Just for quick prototyping. Don't do this in real! Use servlet/javabean.\n double d = 3.25;\n request.setAttribute(\"d\", d);\n%>\n\n<!doctype html>\n<html lang=\"en\">\n <head>\n <title>SO question 343584</title>\n </head>\n <body>\n <p>Whole: <fmt:formatNumber value=\"${d}\" maxFractionDigits=\"0\" />\n <p>Fraction: <fmt:formatNumber value=\"${d}\" maxIntegerDigits=\"0\" />\n </body>\n</html>\n"
},
{
"answer_id": 2416532,
"author": "Roland Illig",
"author_id": 225757,
"author_profile": "https://Stackoverflow.com/users/225757",
"pm_score": 0,
"selected": false,
"text": "fmt:formatNumber <%@ taglib uri=\"http://java.sun.com/jsp/jstl/core\" prefix=\"c\" %>\n<%@ taglib uri=\"http://java.sun.com/jsp/jstl/functions\" prefix=\"fn\" %>\n\n<%\n double[] numbers = { 0.0, 3.25, 3.75, 3.5, 2.5, -1.5, -2.5 };\n pageContext.setAttribute(\"numbers\", numbers);\n%>\n\n<html>\n <body>\n <ul>\n <c:forEach var=\"n\" items=\"${numbers}\">\n <li>${n} = ${fn:substringBefore(n, \".\")} + ${n - fn:substringBefore(n, \".\")}</li>\n </c:forEach>\n </ul>\n </body>\n</html>\n"
},
{
"answer_id": 18517555,
"author": "OnePunchMan",
"author_id": 2508414,
"author_profile": "https://Stackoverflow.com/users/2508414",
"pm_score": 2,
"selected": false,
"text": "double num, temp=0;\ndouble frac,j=1;\n\nnum=1034.235;\n// FOR THE FRACTION PART\ndo{\nj=j*10;\ntemp= num*j;\n}while((temp%10)!=0); \n\nj=j/10;\ntemp=(int)num;\nfrac=(num*j)-(temp*j);\n\nSystem.out.println(\"Double number= \"+num); \nSystem.out.println(\"Whole part= \"+(int)num+\" fraction part= \"+(int)frac);\n"
},
{
"answer_id": 19284357,
"author": "QED",
"author_id": 1224741,
"author_profile": "https://Stackoverflow.com/users/1224741",
"pm_score": 3,
"selected": false,
"text": "float fp = ip % 1.0f;\n"
},
{
"answer_id": 25678502,
"author": "benofben",
"author_id": 3362306,
"author_profile": "https://Stackoverflow.com/users/3362306",
"pm_score": 0,
"selected": false,
"text": "double x=123.456;\ndouble fractionalPart = x-Math.floor(x);\ndouble wholePart = Math.floor(x);\n"
},
{
"answer_id": 31877346,
"author": "user1817835",
"author_id": 1817835,
"author_profile": "https://Stackoverflow.com/users/1817835",
"pm_score": 0,
"selected": false,
"text": " double num;\n double iPart;\n double fPart;\n\n // Get user input\n num = -0.35d;\n iPart = (long) num;\n //Correct numbers between -0.0 and -1.0\n iPart = (num<=-0.0000001 && num>-1.0)? -iPart : iPart ;\n fPart = Math.abs(num - iPart);\n System.out.println(String.format(\"Integer part = %01.0f\",iPart));\n System.out.println(String.format(\"Fractional part = %01.04f\",fPart));\n Integer part = -0\nFractional part = 0,3500\n"
},
{
"answer_id": 33360625,
"author": "Stephan",
"author_id": 363573,
"author_profile": "https://Stackoverflow.com/users/363573",
"pm_score": 0,
"selected": false,
"text": "Math.floorDiv int floorDiv(4, 3) == 1\nfloorDiv(-4, 3) == -2\n / (4 / 3) == 1\n(-4 / 3) == -1\n"
},
{
"answer_id": 34415841,
"author": "Endery",
"author_id": 2305034,
"author_profile": "https://Stackoverflow.com/users/2305034",
"pm_score": 0,
"selected": false,
"text": " double value = 3.25;\n BigDecimal wholeValue = BigDecimal.valueOf(value).setScale(0, BigDecimal.ROUND_DOWN);\n double fractionalValue = value - wholeValue.doubleValue();\n"
},
{
"answer_id": 39315178,
"author": "Mohamed Sabirulla",
"author_id": 1896545,
"author_profile": "https://Stackoverflow.com/users/1896545",
"pm_score": 0,
"selected": false,
"text": "String value = \"3.06\";\n\nif(!value.isEmpty()){\n if(value.contains(\".\")){ \n String block = value.substring(0,value.indexOf(\".\"));\n System.out.println(block);\n }else{\n System.out.println(value);\n }\n}\n"
},
{
"answer_id": 40188113,
"author": "roybraym",
"author_id": 2967057,
"author_profile": "https://Stackoverflow.com/users/2967057",
"pm_score": 1,
"selected": false,
"text": "Integer x,y,intPart;\nBigDecimal bd,bdInt,bdDec;\nbd = new BigDecimal(\"2.39999999999999\");\nintPart = bd.intValue();\nbdInt = new BigDecimal(intPart);\nbdDec = bd.subtract(bdInt);\nSystem.out.println(\"Number : \" + bd);\nSystem.out.println(\"Whole number part : \" + bdInt);\nSystem.out.println(\"Decimal number part : \" + bdDec);\n"
},
{
"answer_id": 61424077,
"author": "w__",
"author_id": 9677624,
"author_profile": "https://Stackoverflow.com/users/9677624",
"pm_score": 0,
"selected": false,
"text": "// target float point number\ndouble d = 3.025;\n\n// transfer the number to string\nDecimalFormat df = new DecimalFormat();\ndf.setDecimalSeparatorAlwaysShown(false);\nString format = df.format(d);\n\n// split the number into two fragments\nint dotIndex = format.indexOf(\".\");\nint iPart = Integer.parseInt(format.substring(0, dotIndex)); // output: 3\ndouble fPart = Double.parseDouble(format.substring(dotIndex)); // output: 0.025\n"
},
{
"answer_id": 62478596,
"author": "Omar Elashry",
"author_id": 8383660,
"author_profile": "https://Stackoverflow.com/users/8383660",
"pm_score": 0,
"selected": false,
"text": "double d = 11.38;\n\nBigDecimal bigD = BigDecimal.valueOf(d);\nint intPart = bigD.intValue();\ndouble fractionalPart = bigD.subtract(BigDecimal.valueOf(intPart)).doubleValue();\n\nSystem.out.println(intPart); // 11\nSystem.out.println(fractionalPart ); //0.38\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28557/"
] |
343,605 | <p>I'm interested in hearing what technique(s) you're using to validate the internal state of an object during an operation that, from it's own point of view, only can fail because of bad internal state or invariant breach.</p>
<p>My primary focus is on C++, since in C# the official and prevalent way is to throw an exception, and in C++ there's not just one <em>single</em> way to do this (ok, not really in C# either, I know that).</p>
<p>Note that I'm <strong>not</strong> talking about function parameter validation, but more like class invariant integrity checks.</p>
<p>For instance, let's say we want a <code>Printer</code> object to <code>Queue</code> a print job asynchronously. To the user of <code>Printer</code>, that operation can only succeed, because an asynchronous queue result with arrive at another time. So, there's no relevant error code to convey to the caller.</p>
<p>But to the <code>Printer</code> object, this operation can fail if the internal state is bad, i.e., the class invariant is broken, which basically means: a bug. This condition is not necessarily of any interest to the user of the <code>Printer</code> object.</p>
<p>Personally, I tend to mix three styles of internal state validation and I can't really decide which one's the best, if any, only which one is absolutely the worst. I'd like to hear your views on these and also that you share any of your own experiences and thoughts on this matter.</p>
<p>The first style I use - better fail in a controllable way than corrupt data:</p>
<pre><code>void Printer::Queue(const PrintJob& job)
{
// Validate the state in both release and debug builds.
// Never proceed with the queuing in a bad state.
if(!IsValidState())
{
throw InvalidOperationException();
}
// Continue with queuing, parameter checking, etc.
// Internal state is guaranteed to be good.
}
</code></pre>
<p>The second style I use - better crash uncontrollable than corrupt data:</p>
<pre><code>void Printer::Queue(const PrintJob& job)
{
// Validate the state in debug builds only.
// Break into the debugger in debug builds.
// Always proceed with the queuing, also in a bad state.
DebugAssert(IsValidState());
// Continue with queuing, parameter checking, etc.
// Generally, behavior is now undefined, because of bad internal state.
// But, specifically, this often means an access violation when
// a NULL pointer is dereferenced, or something similar, and that crash will
// generate a dump file that can be used to find the error cause during
// testing before shipping the product.
}
</code></pre>
<p>The third style I use - better silently and defensively bail out than corrupt data:</p>
<pre><code>void Printer::Queue(const PrintJob& job)
{
// Validate the state in both release and debug builds.
// Break into the debugger in debug builds.
// Never proceed with the queuing in a bad state.
// This object will likely never again succeed in queuing anything.
if(!IsValidState())
{
DebugBreak();
return;
}
// Continue with defenestration.
// Internal state is guaranteed to be good.
}
</code></pre>
<p>My comments to the styles:</p>
<ol>
<li>I think I prefer the second style, where the failure isn't hidden, provided that an access violation actually causes a crash.</li>
<li>If it's not a NULL pointer involved in the invariant, then I tend to lean towards the first style.</li>
<li>I really dislike the third style, since it will hide lots of bugs, but I know people that prefers it in production code, because it creates the illusion of a robust software that doesn't crash (features will just stop to function, as in the queuing on the broken <code>Printer</code> object). </li>
</ol>
<p>Do you prefer any of these or do you have other ways of achieving this?</p>
| [
{
"answer_id": 343628,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "template method class Printer {\npublic:\n // checks invariant, and calls the actual queuing\n void Queue(const PrintJob&);\nprivate:\n virtual void DoQueue(const PringJob&);\n};\n\n\nvoid Printer::Queue(const PrintJob& job) // not virtual\n{\n // Validate the state in both release and debug builds.\n // Never proceed with the queuing in a bad state.\n if(!IsValidState()) {\n throw std::logic_error(\"Printer not ready\");\n }\n\n // call virtual method DoQueue which does the job\n DoQueue(job);\n}\n\nvoid Printer::DoQueue(const PrintJob& job) // virtual\n{\n // Do the actual Queuing. State is guaranteed to be valid.\n}\n Queue DoQueue assert(CheckInvariant()); std::logic_error"
},
{
"answer_id": 343640,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 3,
"selected": true,
"text": "DebugBreak"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6345/"
] |
343,609 | <p>I have two or three i18n files in my struts application. I am able to switch between these by setting the <code>Global.LOCALE_KEY</code> variable in the session.</p>
<p>Is there a way to set a default locale for the application (probably in the struts-config.xml file, I guess) ? Is the session the only place to set the locale ?</p>
<p>Sure, I could intercept the call to the first page and set the variable in the session, but that's more cumbersome.</p>
| [
{
"answer_id": 343641,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 2,
"selected": false,
"text": "<context-param>\n <param-name>LOCALE</param-name>\n <param-value>en-GB</param-value>\n</context-param>\n java.util.Enumeration<String> setout = servletContext.getInitParameterNames();\nwhile (setout.hasMoreElements()) {\n String paramName = setout.nextElement();\n configProperties.put(paramName, servletContext.getInitParameter(paramName));\n}\n"
},
{
"answer_id": 349367,
"author": "Leonel",
"author_id": 15649,
"author_profile": "https://Stackoverflow.com/users/15649",
"pm_score": 0,
"selected": false,
"text": "import javax.servlet.ServletContext;\nimport javax.servlet.ServletContextEvent;\nimport javax.servlet.ServletContextListener;\n\npublic class AppContextListener implements ServletContextListener {\n @Override\n public void contextDestroyed(ServletContextEvent event) { /* empty. */ }\n\n @Override\n public void contextInitialized(ServletContextEvent event) {\n /*\n * Default locale\n */\n ServletContext sc = event.getServletContext();\n sc.setAttribute(org.apache.struts.Globals.LOCALE_KEY, \"pt_BR\");\n }\n} \n"
},
{
"answer_id": 367134,
"author": "Eduard Wirch",
"author_id": 17428,
"author_profile": "https://Stackoverflow.com/users/17428",
"pm_score": 0,
"selected": false,
"text": "Texts_en_GB.properties\nTexts_pt_BR.properties\nTexts.propertiers ( <-- this one will be selected when no resources for requested language could be found)\n mode <message-resources key=\"Texts\" parameter=\"com.mycompany.Texts\" null=\"false\"/>\n Texts.properties Texts.properties Texts_de.properties <message-resources key=\"Texts\" parameter=\"com.mycompany.Texts\" null=\"false\">\n <set-property key=\"mode\" value=\"JSTL\" />\n</message-resources>\n"
},
{
"answer_id": 36878772,
"author": "Unknown",
"author_id": 3850392,
"author_profile": "https://Stackoverflow.com/users/3850392",
"pm_score": 1,
"selected": false,
"text": "package com.mycompany.web.session;\nimport javax.servlet.http.HttpSessionEvent;\nimport javax.servlet.http.HttpSessionListener;\nimport org.apache.struts.Globals;\n\npublic class LocaleController implements HttpSessionListener {\n\n private static Locale defaultLocale = locale.ENGLISH;\n\n @Override\n public void sessionCreated(HttpSessionEvent event) {\n event.getSession().setAttribute(Globals.LOCALE_KEY, defaultLocale);\n }\n\n @Override\n public void sessionDestroyed(HttpSessionEvent event) {\n }\n}\n <listener>\n <listener-class>com.mycompany.web.session.LocaleController</listener-class>\n</listener>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15649/"
] |
343,622 | <p>I would like to be able to submit a form in an <strong>HTML source (string)</strong>. In other words I need at least the ability to generate POST parameters <strong>from a string containing HTML source of the form</strong>. This is needed in unit tests for a Django project. I would like a solution that possibly;</p>
<ul>
<li>Uses only standard Python library and Django.</li>
<li>Allows parameter generation from a specific form if there is more than one form present.</li>
<li>Allows me to change the values before submission.</li>
</ul>
<p>A solution that returns a (Django) form instance from a given form class is best. Because it would allow me to use validation. Ideally it would consume the source (which is a string), a form class, and optionally a form name and return the instance as it was before rendering.</p>
<p>NOTE: I am aware this is not an easy task, and probably the gains would hardly justify the effort needed. But I am just curious about how this can be done, in a practical and reliable way. If possible.</p>
| [
{
"answer_id": 343639,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "class Test_HTML_Change_User( django.test.TestCase ):\n fixtures = [ 'auth.json', 'someApp.json' ]\n def test_chg_user_1( self ):\n self.client.login( username='this', password='this' )\n response= self.client.get( \"/support/html/user/2/change/\" )\n self.assertEquals( 200, response.status_code )\n self.assertTemplateUsed( response, \"someApp/user.html\")\n\ndef test_chg_user( self ):\n self.client.login( username='this', password='this' )\n # The truly fussy would redo the test_chg_user_1 test here\n response= self.client.post(\n \"/support/html/user/2/change/\",\n {'web_services': 'P',\n 'username':'olduser',\n 'first_name':'asdf',\n 'last_name':'asdf',\n 'email':'asdf@asdf.com',\n 'password1':'passw0rd',\n 'password2':'passw0rd',} )\n self.assertRedirects(response, \"/support/html/user/2/\" )\n response= self.client.get( \"/support/html/user/2/\" )\n self.assertContains( response, \"<h2>Users: Details for\", status_code=200 )\n self.assertContains( response, \"olduser\" )\n self.assertTemplateUsed( response, \"someApp/user_detail.html\")\n"
},
{
"answer_id": 343794,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "method action input select name id value select option value"
},
{
"answer_id": 345334,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 3,
"selected": true,
"text": "GET POST Context Context forms.Form /form/ {'myform': forms.Form()} from django.test.client import Client\nc = Client()\n\n# request the web page:\nresponse = c.get('/form/')\n\n# get the Form object:\nform = response.context['myform']\n\nform_data = form.cleaned_data\nmy_form_data = {} # put your filled-out data in here...\nform_data.update(my_form_data)\n\n# submit the form back to the web page:\nnew_form = forms.Form(form_data)\nif new_form.is_valid():\n c.post('/form/', new_form.cleaned_data)\n Form"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42188/"
] |
343,638 | <p>I'm looking for some information on Routing in MVC with C#. I'm currently very aware of the basics of routing in MVC, but what i'm looking for is somewhat difficult to find. </p>
<p>Effectively, what I want to find is a way of defining a single route that takes a single parameter.</p>
<p>The common examples I have found online is all based around the example</p>
<pre><code>routes.MapRoute(
"Default",
"{controller}.mvc/{action}/{id}"
new { controller = "Default", action="Index", id=""});
</code></pre>
<p>By mapping this route, you can map to any action in any controller, but if you want to pass anything into the action, the method parameter must be called "id". I want to find a way around this if it's possible, so that I don't have to constantly specify routes just to use a different parameter name in my actions.</p>
<p>Has anyone any ideas, or found a way around this?</p>
| [
{
"answer_id": 343681,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 1,
"selected": true,
"text": "routes.MapRoute(\n \"Default\",\n \"{controller}.mvc/{action}/{param1}/{param2}/{param3}\"\n new { controller = \"Default\", action=\"Index\", param1=\"\", param2=\"\", param3=\"\"});\n"
},
{
"answer_id": 345272,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 3,
"selected": false,
"text": "~/mycontroller/myaction/?foobar=123\n public ActionResult MyAction(int? foobar)\n"
},
{
"answer_id": 11062947,
"author": "Tom",
"author_id": 1330984,
"author_profile": "https://Stackoverflow.com/users/1330984",
"pm_score": 2,
"selected": false,
"text": "http://blah/foo.axd/foo/bar/baz/bing"
},
{
"answer_id": 15393937,
"author": "Curtis",
"author_id": 981187,
"author_profile": "https://Stackoverflow.com/users/981187",
"pm_score": 3,
"selected": false,
"text": "public ActionResult MyView([FromUri(Name = \"id\")] string parameterThatMapsToId)\n{\n // do stuff\n}\n routes.MapRoute(\n \"Default\",\n \"{controller}.mvc/{action}/{id}\"\n new { controller = \"Default\", action=\"Index\", id=\"\"});\n"
},
{
"answer_id": 43396077,
"author": "toddmo",
"author_id": 1045881,
"author_profile": "https://Stackoverflow.com/users/1045881",
"pm_score": 0,
"selected": false,
"text": "FromUri Route [Route(\"~/Policy/PriorAddressDelete/{sequence}\")]\npublic ActionResult PriorAddressDelete(int sequence)\n{\n Policy.RemoveScheduledPriorAddressItem(sequence);\n return RedirectToAction(\"Information\", new { id = Policy.Id });\n}\n routeconfig routes.MapMvcAttributeRoutes();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343638",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20749/"
] |
343,642 | <p>Where I work, people don't like to write specs. (Boy, does anyone?) So they don't do it, unless forced by their bosses. If they are forced to write them, they make them as short as possible. (By the way, <em>they</em> also includes <em>me</em>.)</p>
<p>This results in specifications like</p>
<ul>
<li>This software logs the time between event A and B to the event log</li>
<li>Name and path of parameter X are set in a configuration file in ini format.</li>
<li>The software is active without a user needing to log on to the computer (implementation as a Windows service)</li>
</ul>
<p>This example is taken from a very small project, and it worked out pretty well, But I don't think that it will suffice for anything more complex. I did not specify OS/hardware requirements because this is in-house development and we have company or department standards covering those. </p>
<p>So my question is:
<em>What do you consider the absolute minimum level of detail in a functional specification for any non-trivial software?</em></p>
| [
{
"answer_id": 343681,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 1,
"selected": true,
"text": "routes.MapRoute(\n \"Default\",\n \"{controller}.mvc/{action}/{param1}/{param2}/{param3}\"\n new { controller = \"Default\", action=\"Index\", param1=\"\", param2=\"\", param3=\"\"});\n"
},
{
"answer_id": 345272,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 3,
"selected": false,
"text": "~/mycontroller/myaction/?foobar=123\n public ActionResult MyAction(int? foobar)\n"
},
{
"answer_id": 11062947,
"author": "Tom",
"author_id": 1330984,
"author_profile": "https://Stackoverflow.com/users/1330984",
"pm_score": 2,
"selected": false,
"text": "http://blah/foo.axd/foo/bar/baz/bing"
},
{
"answer_id": 15393937,
"author": "Curtis",
"author_id": 981187,
"author_profile": "https://Stackoverflow.com/users/981187",
"pm_score": 3,
"selected": false,
"text": "public ActionResult MyView([FromUri(Name = \"id\")] string parameterThatMapsToId)\n{\n // do stuff\n}\n routes.MapRoute(\n \"Default\",\n \"{controller}.mvc/{action}/{id}\"\n new { controller = \"Default\", action=\"Index\", id=\"\"});\n"
},
{
"answer_id": 43396077,
"author": "toddmo",
"author_id": 1045881,
"author_profile": "https://Stackoverflow.com/users/1045881",
"pm_score": 0,
"selected": false,
"text": "FromUri Route [Route(\"~/Policy/PriorAddressDelete/{sequence}\")]\npublic ActionResult PriorAddressDelete(int sequence)\n{\n Policy.RemoveScheduledPriorAddressItem(sequence);\n return RedirectToAction(\"Information\", new { id = Policy.Id });\n}\n routeconfig routes.MapMvcAttributeRoutes();\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22114/"
] |
343,646 | <p>How can I ignore directories or folders in Git using msysgit on Windows?</p>
| [
{
"answer_id": 343734,
"author": "stew",
"author_id": 43613,
"author_profile": "https://Stackoverflow.com/users/43613",
"pm_score": 12,
"selected": true,
"text": ".gitignore dir_to_ignore/\n"
},
{
"answer_id": 343890,
"author": "sf.",
"author_id": 43603,
"author_profile": "https://Stackoverflow.com/users/43603",
"pm_score": 6,
"selected": false,
"text": "."
},
{
"answer_id": 2518239,
"author": "Mahes",
"author_id": 301960,
"author_profile": "https://Stackoverflow.com/users/301960",
"pm_score": 6,
"selected": false,
"text": ".gitignore .gitignore ren \"New Text Document.txt\" .gitignore\n *.txt"
},
{
"answer_id": 3308265,
"author": "brainwavedave",
"author_id": 313810,
"author_profile": "https://Stackoverflow.com/users/313810",
"pm_score": 8,
"selected": false,
"text": ".gitignore .gitignore.txt .gitignore.txt .gitignore"
},
{
"answer_id": 4955747,
"author": "Si3",
"author_id": 611160,
"author_profile": "https://Stackoverflow.com/users/611160",
"pm_score": 4,
"selected": false,
"text": "\\.git\\info .gitignore"
},
{
"answer_id": 9300157,
"author": "Jason",
"author_id": 524511,
"author_profile": "https://Stackoverflow.com/users/524511",
"pm_score": 3,
"selected": false,
"text": ".gitignore $GIT_DIR/info/exclude $GIT_DIR $GIT_DIR .git"
},
{
"answer_id": 10396461,
"author": "Vairis",
"author_id": 1353248,
"author_profile": "https://Stackoverflow.com/users/1353248",
"pm_score": 7,
"selected": false,
"text": ".gitignore .git .gitignore. ~/.gitignore_global git config --global core.excludesfile ~/.gitignore_global git rm --cached filename .git/info/exclude"
},
{
"answer_id": 11259916,
"author": "Mark Longair",
"author_id": 223092,
"author_profile": "https://Stackoverflow.com/users/223092",
"pm_score": 3,
"selected": false,
"text": "a-cache/foo\na-cache/index.html\nb-cache/bar\nb-cache/foo\nb-cache/index.html\n.gitignore\n .gitignore git status $ git status\n# On branch master\n# Untracked files:\n# (use \"git add <file>...\" to include in what will be committed)\n#\n# .gitignore\n# a-cache/\n# b-cache/\n index.html index.html git add *cache/index.html\ngit commit -m \"Adding index.html files to the cache directories\"\n git status $ git status\n# On branch master\n# Untracked files:\n# (use \"git add <file>...\" to include in what will be committed)\n#\n# .gitignore\nnothing added to commit but untracked files present (use \"git add\" to track)\n .gitignore"
},
{
"answer_id": 11260163,
"author": "sensorario",
"author_id": 1420625,
"author_profile": "https://Stackoverflow.com/users/1420625",
"pm_score": 5,
"selected": false,
"text": ".gitignore $ git add path/to/folder/.gitignore\n The following paths are ignored by one of your .gitignore files:\npath/to/folder/.gitignore\nUse -f if you really want to add them.\nfatal: no files added\n $ git add path/to/folder/.gitignore -f\n"
},
{
"answer_id": 21092884,
"author": "wortwart",
"author_id": 2733244,
"author_profile": "https://Stackoverflow.com/users/2733244",
"pm_score": 5,
"selected": false,
"text": "my file.txt my\\ file.txt / \\"
},
{
"answer_id": 28346487,
"author": "calraiden",
"author_id": 2923872,
"author_profile": "https://Stackoverflow.com/users/2923872",
"pm_score": 5,
"selected": false,
"text": "*\n!.gitignore\n"
},
{
"answer_id": 37846411,
"author": "J-Dizzle",
"author_id": 3159066,
"author_profile": "https://Stackoverflow.com/users/3159066",
"pm_score": 6,
"selected": false,
"text": "/root/\n .gitignore\n /dirA/\n someFile1.txt\n someFile2.txt\n /dirB/\n .gitignore\n someFile3.txt\n someFile4.txt\n"
},
{
"answer_id": 48836801,
"author": "Eat at Joes",
"author_id": 614825,
"author_profile": "https://Stackoverflow.com/users/614825",
"pm_score": 5,
"selected": false,
"text": "** **/build/output/Debug/\n"
},
{
"answer_id": 49660849,
"author": "Xedret",
"author_id": 2288252,
"author_profile": "https://Stackoverflow.com/users/2288252",
"pm_score": 4,
"selected": false,
"text": "# git ls-files --others --exclude-from=.git/info/exclude\n# Lines that start with '#' are comments.\n# For a project mostly in C, the following would be a good set of\n# exclude patterns (uncomment them if you want to use them):\n# *.[oa]\n# *~\nassets/\ncompiled/\n"
},
{
"answer_id": 51061514,
"author": "fvolodimir",
"author_id": 4779365,
"author_profile": "https://Stackoverflow.com/users/4779365",
"pm_score": 3,
"selected": false,
"text": "touch .gitignore\n echo > .gitignore\n .gitignore .gitignore"
},
{
"answer_id": 51840174,
"author": "Olusola Omosola",
"author_id": 8434246,
"author_profile": "https://Stackoverflow.com/users/8434246",
"pm_score": 3,
"selected": false,
"text": "echo Flower_Data_Folder >> .gitignore\n data.txt echo data.txt >> .gitignore\n echo \"Data/passwords.txt\" >> .gitignore. \n"
},
{
"answer_id": 60179144,
"author": "DINA TAKLIT",
"author_id": 9039646,
"author_profile": "https://Stackoverflow.com/users/9039646",
"pm_score": 1,
"selected": false,
"text": ".gitignore frontend/node_modules\n"
},
{
"answer_id": 65372848,
"author": "ACB_prgm",
"author_id": 13354853,
"author_profile": "https://Stackoverflow.com/users/13354853",
"pm_score": 1,
"selected": false,
"text": "touch .gitignore\nnano .gitignore\n ls -a"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343646",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43603/"
] |
343,652 | <p>I have been working on Flex for last couple of months and as this was the first time I had to actually do Flex I ended up underestimating the project tasks which resulted in a delay. So how does one estimate the project timings when working on a new technology?</p>
| [
{
"answer_id": 343718,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 0,
"selected": false,
"text": "New Project Time = Project Time * 1.5\n"
},
{
"answer_id": 344144,
"author": "Jeremiah",
"author_id": 34183,
"author_profile": "https://Stackoverflow.com/users/34183",
"pm_score": 3,
"selected": true,
"text": "long GetManHoursForProject()\n{\n long Count_of_Function_Points = GetFunctionPointCountFromAnalyticalPhaseOfSDLC();\n double Average_Complexity = 1; // .8 for easy, 1 for normal, 1.2 for hard\n long Programming_Language = 130; // for C++ (higher level languages have higher values)\n\n\n double Man_Months = Count_of_Function_Points * Programming_Language * Average_Complexity;\n\n\n long Man_Hours = Man_Months * 20 * 8; // 20 days per month, 8 hours per day\n\n return Man_Hours;\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20301/"
] |
343,654 | <p>I am looking to refactor a c# method into a c function in an attempt to gain some speed, and then call the c dll in c# to allow my program to use the functionality.</p>
<p>Currently the c# method takes a list of integers and returns a list of lists of integers. The method calculated the power set of the integers so an input of 3 ints would produce the following output (at this stage the values of the ints is not important as it is used as an internal weighting value)</p>
<pre><code>1
2
3
1,2
1,3
2,3
1,2,3
</code></pre>
<p>Where each line represents a list of integers. The output indicates the index (with an offset of 1) of the first list, not the value. So 1,2 indicates that the element at index 0 and 1 are an element of the power set.</p>
<p>I am unfamiliar with c, so what are my best options for data structures that will allow the c# to access the returned data?</p>
<p>Thanks in advance</p>
<p><strong>Update</strong></p>
<p>Thank you all for your comments so far. Here is a bit of a background to the nature of the problem.</p>
<p>The iterative method for calculating the power set of a set is fairly straight forward. Two loops and a bit of bit manipulation is all there is to it really. It just get called..a lot (in fact billions of times if the size of the set is big enough).</p>
<p>My thoughs around using c (c++ as people have pointed out) are that it gives more scope for performance tuning. A direct port may not offer any increase, but it opens the way for more involved methods to get a bit more speed out of it. Even a small increase per iteration would equate to a measurable increase.</p>
<p>My idea was to port a direct version and then work to increase it. And then refactor it over time (with help from everyone here at SO).</p>
<p><strong>Update 2</strong></p>
<p>Another fair point from jalf, I dont have to use list or equivelent. If there is a better way then I am open to suggestions. The only reason for the list was that each set of results is not the same size.</p>
<p><strong>The code so far...</strong></p>
<pre><code>public List<List<int>> powerset(List<int> currentGroupList)
{
_currentGroupList = currentGroupList;
int max;
int count;
//Count the objects in the group
count = _currentGroupList.Count;
max = (int)Math.Pow(2, count);
//outer loop
for (int i = 0; i < max; i++)
{
_currentSet = new List<int>();
//inner loop
for (int j = 0; j < count; j++)
{
if ((i & (1 << j)) == 0)
{
_currentSetList.Add(_currentGroupList.ElementAt(j));
}
}
outputList.Add(_currentSetList);
}
return outputList;
}
</code></pre>
<p>As you can see, not a lot to it. It just goes round and round a lot!</p>
<p>I accept that the creating and building of lists may not be the most efficient way, but I need some way of providing the results back in a manageable way.</p>
<p><strong>Update 2</strong></p>
<p>Thanks for all the input and implementation work. Just to clarify a couple of points raised: I dont need the output to be in 'natural order', and also I am not that interested in the empty set being returned. </p>
<p>hughdbrown's implementation is intesting but i think that i will need to store the results (or at least a subset of them) at some point. It sounds like memory limitiations will apply long before running time becomes a real issue.
Partly because of this, I think I can get away with using bytes instead of integers, giving more potential storage.</p>
<p>The question really is then: Have we reached the maximum speed for this calcualtion in C#? Does the option of unmanaged code provide any more scope. I know in many respects the answer is futile, as even if we havled the time to run, it would only allow an extra values in the original set.</p>
| [
{
"answer_id": 343668,
"author": "Smokey Bacon Esq.",
"author_id": 43595,
"author_profile": "https://Stackoverflow.com/users/43595",
"pm_score": 1,
"selected": false,
"text": "list"
},
{
"answer_id": 343683,
"author": "Giovanni Galbo",
"author_id": 4050,
"author_profile": "https://Stackoverflow.com/users/4050",
"pm_score": 3,
"selected": false,
"text": "#include \"stdafx.h\"\n\nusing namespace System;\n\nSystem::Collections::Generic::List<int> ^MyAlgorithm(System::Collections::Generic::List<int> ^sourceList);\n\n\nint main(array<System::String ^> ^args)\n{\n System::Collections::Generic::List<int> ^intList = gcnew System::Collections::Generic::List<int>();\n\n intList->Add(1);\n intList->Add(2);\n intList->Add(3);\n intList->Add(4);\n intList->Add(5);\n\n Console::WriteLine(\"Before Call\");\n for each(int i in intList)\n {\n Console::WriteLine(i);\n }\n\n System::Collections::Generic::List<int> ^modifiedList = MyAlgorithm(intList);\n\n Console::WriteLine(\"After Call\");\n for each(int i in modifiedList)\n {\n Console::WriteLine(i);\n }\n}\n\n\nSystem::Collections::Generic::List<int> ^MyAlgorithm(System::Collections::Generic::List<int> ^sourceList)\n{\n int* nativeInts = new int[sourceList->Count];\n\n int nativeIntArraySize = sourceList->Count;\n\n //Managed to Native\n for(int i=0; i<sourceList->Count; i++)\n {\n nativeInts[i] = sourceList[i];\n }\n\n //Do Something to native ints\n for(int i=0; i<nativeIntArraySize; i++)\n {\n nativeInts[i]++;\n }\n\n\n //Native to Managed\n System::Collections::Generic::List<int> ^returnList = gcnew System::Collections::Generic::List<int>();\n for(int i=0; i<nativeIntArraySize; i++)\n {\n returnList->Add(nativeInts[i]);\n }\n\n\n return returnList;\n}\n"
},
{
"answer_id": 347060,
"author": "hughdbrown",
"author_id": 10293,
"author_profile": "https://Stackoverflow.com/users/10293",
"pm_score": 2,
"selected": false,
"text": "static class PowerSet<T>\n{\n static long[] mask = { 1L << 0, 1L << 1, 1L << 2, 1L << 3, \n 1L << 4, 1L << 5, 1L << 6, 1L << 7, \n 1L << 8, 1L << 9, 1L << 10, 1L << 11, \n 1L << 12, 1L << 13, 1L << 14, 1L << 15, \n 1L << 16, 1L << 17, 1L << 18, 1L << 19, \n 1L << 20, 1L << 21, 1L << 22, 1L << 23, \n 1L << 24, 1L << 25, 1L << 26, 1L << 27, \n 1L << 28, 1L << 29, 1L << 30, 1L << 31};\n static public IEnumerable<IList<T>> powerset(T[] currentGroupList)\n {\n int count = currentGroupList.Length;\n long max = 1L << count;\n for (long iter = 0; iter < max; iter++)\n {\n T[] list = new T[count];\n int k = 0, m = -1;\n for (long i = iter; i != 0; i &= (i - 1))\n {\n while ((mask[++m] & i) == 0)\n ;\n list[k++] = currentGroupList[m];\n }\n yield return list;\n }\n }\n}\n static void Main(string[] args)\n {\n int[] intList = { 1, 2, 3, 4 };\n foreach (IList<int> set in PowerSet<int>.powerset(intList))\n {\n foreach (int i in set)\n Console.Write(\"{0} \", i);\n Console.WriteLine();\n }\n }\n"
},
{
"answer_id": 347086,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 2,
"selected": false,
"text": "for /* \n * Made it static, because it shouldn't really use or modify state data.\n * Making it static also saves a tiny bit of call time, because it doesn't\n * have to receive an extra \"this\" pointer. Also, accessing a local\n * parameter is a tiny bit faster than accessing a class member, because\n * dereferencing the \"this\" pointer is not free.\n * \n * Made it generic so that the same code can handle sets of any type.\n */\nstatic IList<IList<T>> PowerSet<T>(IList<T> set){\n if(set == null)\n throw new ArgumentNullException(\"set\");\n\n /*\n * Caveat:\n * If set.Count > 30, this function pukes all over itself without so\n * much as wiping up afterwards. Even for 30 elements, though, the\n * result set is about 68 GB (if \"set\" is comprised of ints). 24 or\n * 25 elements is a practical limit for current hardware.\n */\n int setSize = set.Count;\n int subsetCount = 1 << setSize; // MUCH faster than (int)Math.Pow(2, setSize)\n T[][] rtn = new T[subsetCount][];\n /* \n * We don't really need dynamic list allocation. We can calculate\n * in advance the number of subsets (\"subsetCount\" above), and\n * the size of each subset (0 through setSize). The performance\n * of List<> is pretty horrible when the initial size is not\n * guessed well.\n */\n\n int subsetIndex = 0;\n for(int subsetSize = 0; subsetSize <= setSize; subsetSize++){\n /*\n * The \"indices\" array below is part of how we implement the\n * \"natural\" ordering of the subsets. For a subset of size 3,\n * for example, we initialize the indices array with {0, 1, 2};\n * Later, we'll increment each index until we reach setSize,\n * then carry over to the next index. So, assuming a set size\n * of 5, the second iteration will have indices {0, 1, 3}, the\n * third will have {0, 1, 4}, and the fifth will involve a carry,\n * so we'll have {0, 2, 3}.\n */\n int[] indices = new int[subsetSize];\n for(int i = 1; i < subsetSize; i++)\n indices[i] = i;\n\n /*\n * Now we'll iterate over all the subsets we need to make for the\n * current subset size. The number of subsets of a given size\n * is easily determined with combination (nCr). In other words,\n * if I have 5 items in my set and I want all subsets of size 3,\n * I need 5-pick-3, or 5C3 = 5! / 3!(5 - 3)! = 10.\n */\n for(int i = Combination(setSize, subsetSize); i > 0; i--){\n /*\n * Copy the items from the input set according to the\n * indices we've already set up. Alternatively, if you\n * just wanted the indices in your output, you could\n * just dup the index array here (but make sure you dup!\n * Otherwise the setup step at the bottom of this for\n * loop will mess up your output list! You'll also want\n * to change the function's return type to\n * IList<IList<int>> in that case.\n */\n T[] subset = new T[subsetSize];\n for(int j = 0; j < subsetSize; j++)\n subset[j] = set[indices[j]];\n\n /* Add the subset to the return */\n rtn[subsetIndex++] = subset;\n\n /*\n * Set up indices for next subset. This looks a lot\n * messier than it is. It simply increments the\n * right-most index until it overflows, then carries\n * over left as far as it needs to. I've made the\n * logic as fast as I could, which is why it's hairy-\n * looking. Note that the inner for loop won't\n * actually run as long as a carry isn't required,\n * and will run at most once in any case. The outer\n * loop will go through as few iterations as required.\n * \n * You may notice that this logic doesn't check the\n * end case (when the left-most digit overflows). It\n * doesn't need to, since the loop up above won't\n * execute again in that case, anyway. There's no\n * reason to waste time checking that here.\n */\n for(int j = subsetSize - 1; j >= 0; j--)\n if(++indices[j] <= setSize - subsetSize + j){\n for(int k = j + 1; k < subsetSize; k++)\n indices[k] = indices[k - 1] + 1;\n break;\n }\n }\n }\n return rtn;\n}\n\nstatic int Combination(int n, int r){\n if(r == 0 || r == n)\n return 1;\n\n /*\n * The formula for combination is:\n *\n * n!\n * ----------\n * r!(n - r)!\n *\n * We'll actually use a slightly modified version here. The above\n * formula forces us to calculate (n - r)! twice. Instead, we only\n * multiply for the numerator the factors of n! that aren't canceled\n * out by (n - r)! in the denominator.\n */\n\n /*\n * nCr == nC(n - r)\n * We can use this fact to reduce the number of multiplications we\n * perform, as well as the incidence of overflow, where r > n / 2\n */\n if(r > n / 2) /* We DO want integer truncation here (7 / 2 = 3) */\n r = n - r;\n\n /*\n * I originally used all integer math below, with some complicated\n * logic and another function to handle cases where the intermediate\n * results overflowed a 32-bit int. It was pretty ugly. In later\n * testing, I found that the more generalized double-precision\n * floating-point approach was actually *faster*, so there was no\n * need for the ugly code. But if you want to see a giant WTF, look\n * at the edit history for this post!\n */\n\n double denominator = Factorial(r);\n double numerator = n;\n while(--r > 0)\n numerator *= --n;\n\n return (int)(numerator / denominator + 0.1/* Deal with rounding errors. */);\n}\n\n/*\n * The archetypical factorial implementation is recursive, and is perhaps\n * the most often used demonstration of recursion in text books and other\n * materials. It's unfortunate, however, that few texts point out that\n * it's nearly as simple to write an iterative factorial function that\n * will perform better (although tail-end recursion, if implemented by\n * the compiler, will help to close the gap).\n */\nstatic double Factorial(int x){\n /*\n * An all-purpose factorial function would handle negative numbers\n * correctly - the result should be Sign(x) * Factorial(Abs(x)) -\n * but since we don't need that functionality, we're better off\n * saving the few extra clock cycles it would take.\n */\n\n /*\n * I originally used all integer math below, but found that the\n * double-precision floating-point version is not only more\n * general, but also *faster*!\n */\n\n if(x < 2)\n return 1;\n\n double rtn = x;\n while(--x > 1)\n rtn *= x;\n\n return rtn;\n}\n"
},
{
"answer_id": 347746,
"author": "hughdbrown",
"author_id": 10293,
"author_profile": "https://Stackoverflow.com/users/10293",
"pm_score": 0,
"selected": false,
"text": " static long Combination(long n, long r)\n {\n r = (r > n - r) ? (n - r) : r;\n if (r == 0)\n return 1;\n long result = 1;\n long k = 1;\n while (r-- > 0)\n {\n result *= n--;\n result /= k++;\n }\n\n return result;\n }\n"
},
{
"answer_id": 349919,
"author": "hughdbrown",
"author_id": 10293,
"author_profile": "https://Stackoverflow.com/users/10293",
"pm_score": 4,
"selected": true,
"text": "static class PowerSet4<T>\n{\n static public IEnumerable<IList<T>> powerset(T[] currentGroupList)\n {\n int count = currentGroupList.Length;\n Dictionary<long, T> powerToIndex = new Dictionary<long, T>();\n long mask = 1L;\n for (int i = 0; i < count; i++)\n {\n powerToIndex[mask] = currentGroupList[i];\n mask <<= 1;\n }\n\n Dictionary<long, T> result = new Dictionary<long, T>();\n yield return result.Values.ToArray();\n\n long max = 1L << count;\n for (long i = 1L; i < max; i++)\n {\n long key = i & -i;\n if (result.ContainsKey(key))\n result.Remove(key);\n else\n result[key] = powerToIndex[key];\n yield return result.Values.ToArray();\n }\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21197/"
] |
343,667 | <p>I want to determine whether two different child nodes within an XML document are equal or not. Two nodes should be considered equal if they have the same set of attributes and child notes and all child notes are equal, too (i.e. the whole sub tree should be equal).</p>
<p>The input document might be very large (up to 60MB, more than a 100000 nodes to compare) and performance is an issue. </p>
<p>What would be an efficient way to check for the equality of two nodes?</p>
<p><strong>Example:</strong></p>
<pre><code><w:p>
<w:pPr>
<w:spacing w:after="120"/>
</w:pPr>
<w:r>
<w:t>Hello</w:t>
</w:r>
</w:p>
<w:p>
<w:pPr>
<w:spacing w:after="240"/>
</w:pPr>
<w:r>
<w:t>World</w:t>
</w:r>
</w:p>
</code></pre>
<p>This XML snippet describes paragraphs in an OpenXML document. The algorithm would be used to determine whether a document contains a paragraph (w:p node) with the same properties (w:pPr node) as another paragraph earlier in the document.</p>
<p>One idea I have would be to store the nodes' outer XML in a hash set (Normally I would have to get a canonical string representation first where attributes and child notes are sorted always in the same way, but I can expect my nodes already to be in such a form).</p>
<p>Another idea would be to create an XmlNode object for each node and write a comparer which compares all attributes and child nodes.</p>
<p>My environment is C# (.Net 2.0); any feedback and further ideas are very welcome. Maybe somebody even has already a good solution?</p>
<p>EDIT: Microsoft's XmlDiff API can actually do that but I was wondering whether there would be a more lightweight approach. XmlDiff seems to always produce a diffgram and to always produce a canonical node representation first, both things which I don't need.</p>
<p>EDIT2: I finally implemented my own XmlNodeEqualityComparer based on the suggestion made here. Thanks a lot!!!!</p>
<p>Thanks,
divo</p>
| [
{
"answer_id": 343784,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<w:pPr> <w:p> // string format is really irrelevant, so this is just a bogus example\n'!w:keep-with-next@value=\"true\"!w:spacing@w:before=\"10\"@w:after=\"120\"'\n <w:p>"
},
{
"answer_id": 343917,
"author": "Dave R.",
"author_id": 42841,
"author_profile": "https://Stackoverflow.com/users/42841",
"pm_score": 5,
"selected": true,
"text": "XNodeEqualityComparer GetHashCode XNodeEqualityComparer comparer = new XNodeEqualityComparer();\nXDocument doc = XDocument.Load(\"XmlFile1.xml\");\nDictionary<int, XNode> nodeDictionary = new Dictionary<int, XNode>();\n\nforeach (XNode node in doc.Elements(\"doc\").Elements(\"node\"))\n{\n int hash = comparer.GetHashCode(node);\n if (nodeDictionary.ContainsKey(hash))\n {\n // A duplicate has been found. Execute your logic here\n // ...\n }\n else\n {\n nodeDictionary.Add(hash, node);\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<doc>\n <node att=\"A\">Blah</node>\n <node att=\"A\">Blah</node>\n <node att=\"B\">\n <inner>Innertext</inner>\n </node>\n <node>Blah</node>\n <node att=\"B\">\n <inner>Different</inner>\n </node>\n</doc>\n nodeDictionary Dictionary ContainsKey XNodeEqualityComparer GetHashCode"
},
{
"answer_id": 344157,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 2,
"selected": false,
"text": "static int HashXElement(XElement elem)\n{\n int hash = 23;\n\n foreach (XAttribute attrib in elem.Attributes())\n {\n int attribHash = 23;\n attribHash = attribHash * 37 + attrib.Name.GetHashCode();\n attribHash = attribHash * 37 + attrib.Value.GetHashCode();\n hash = hash ^ attribHash;\n }\n\n foreach(XElement subElem in elem.Descendants())\n {\n hash = hash * 37 + XmlHash(subElem);\n }\n\n hash = hash * 37 + elem.Value.GetHashCode();\n\n return hash;\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40347/"
] |
343,669 | <p>Got a quick question. Does anyone know how to let JAXB (marshall) render boolean fields as 1 and 0 instead of printing out "true" and "false"?</p>
| [
{
"answer_id": 344111,
"author": "Luc Touraille",
"author_id": 20984,
"author_profile": "https://Stackoverflow.com/users/20984",
"pm_score": 3,
"selected": false,
"text": "<javaType> parseMethod printMethod public boolean myParseBool(String s)\n{\n return s.equals(\"1\");\n}\n\npublic String myPrintBool(boolean b)\n{\n return b ? \"1\" : \"0\";\n}\n"
},
{
"answer_id": 1633006,
"author": "mtpettyp",
"author_id": 98632,
"author_profile": "https://Stackoverflow.com/users/98632",
"pm_score": 5,
"selected": false,
"text": "import javax.xml.bind.annotation.adapters.XmlAdapter;\n\npublic class BooleanAdapter extends XmlAdapter<Integer, Boolean>\n{\n @Override\n public Boolean unmarshal( Integer s )\n {\n return s == null ? null : s == 1;\n }\n\n @Override\n public Integer marshal( Boolean c )\n {\n return c == null ? null : c ? 1 : 0;\n }\n}\n @XmlElement( name = \"enabled\" )\n@XmlJavaTypeAdapter( BooleanAdapter.class )\npublic Boolean getEnabled()\n{\n return enabled;\n}\n"
},
{
"answer_id": 8502409,
"author": "Aim Mistaken",
"author_id": 1097468,
"author_profile": "https://Stackoverflow.com/users/1097468",
"pm_score": 3,
"selected": false,
"text": "<plugin>\n<groupId>org.jvnet.jaxb2.maven2</groupId>\n<artifactId>maven-jaxb2-plugin</artifactId>\n<executions>\n <execution>\n <phase>generate-sources</phase>\n <goals>\n <goal>generate</goal>\n </goals>\n </execution>\n</executions>\n<configuration>\n <generateDirectory>src/main/generated</generateDirectory>\n <extension>true</extension>\n <removeOldOutput>true</removeOldOutput>\n</configuration>\n <?xml version=\"1.0\" ?>\n<bindings xmlns=\"http://java.sun.com/xml/ns/jaxb\" \n version=\"2.1\" \n xmlns:kml=\"http://www.opengis.net/kml/2.2\"\n xmlns:xjc=\"http://java.sun.com/xml/ns/jaxb/xjc\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <globalBindings>\n <xjc:simple/>\n <xjc:javaType name=\"java.lang.Boolean\" \n xmlType=\"xsd:boolean\" \n adapter=\"path.to.my.JaxbBooleanAdapter\"/>\n </globalBindings>\n ...\n ...\n</bindings>\n package path.to.my;\n\nimport javax.xml.bind.annotation.adapters.XmlAdapter;\n\n/**\n * Utility class to correctly render the xml types used in JAXB.\n */\npublic class JaxbBooleanAdapter extends XmlAdapter<String, Boolean>\n{\n @Override\n public Boolean unmarshal(String v) throws Exception\n {\n if (\"1\".equals(v))\n {\n return true;\n }\n return false;\n }\n\n @Override\n public String marshal(Boolean v) throws Exception\n {\n if (v == null)\n {\n return null;\n }\n if (v)\n {\n return \"1\";\n }\n return \"0\";\n }\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343669",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20298/"
] |
343,675 | <p>I'm using SVN right now, and I've used CVS and VSS in the past. SVN is the current favourite in my books, but I've been hearing a lot about git. Of the people that have used git, what are the pros and cons from your experience?</p>
| [
{
"answer_id": 343691,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "git add"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15852/"
] |
343,690 | <p>Is it possible to use Flex 3 component/code inside Flash (cs4) SWF file ?</p>
<p>I know its possible in the opposite direction.</p>
| [
{
"answer_id": 343726,
"author": "hasseg",
"author_id": 4111,
"author_profile": "https://Stackoverflow.com/users/4111",
"pm_score": 1,
"selected": false,
"text": "swc /frameworks/libs /frameworks/projects/framework/src"
},
{
"answer_id": 4345057,
"author": "Tamlyn",
"author_id": 132208,
"author_profile": "https://Stackoverflow.com/users/132208",
"pm_score": 0,
"selected": false,
"text": "-keep-generated-actionscript spark.components.Application"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20979/"
] |
343,695 | <p>I need a combobox in an Windows MFC application that has a search feature. It should work so that if you start typing something that matches one or more items in the list, the combobox should drop-down and display those items. Kinda like popular ajax-based search boxes on the web</p>
<p>Do you
- know of any control that provides this functionality?
- have a link to information on how to create such functionality myself?
- have ideas on how to do this that you could share?</p>
| [
{
"answer_id": 343738,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 0,
"selected": false,
"text": "CBN_EDITCHANGE CComboBox::FindString() CComboBox::SetCurSel()"
},
{
"answer_id": 350538,
"author": "Serge Wautier",
"author_id": 12379,
"author_profile": "https://Stackoverflow.com/users/12379",
"pm_score": -1,
"selected": false,
"text": "CEdit *pEdit = (CEdit *)pComboBox->GetWindow(GW_CHILD);\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37268/"
] |
343,711 | <p>I'm SSHing into a remote server on the command line, and trying to copy a directory onto my local machine with the <code>scp</code> command. However, the remote server returns this "usage" message:</p>
<pre><code>[Stewart:console/ebooks/discostat] jmm% scp -p ./styles/
usage: scp [-1246BCEpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
[-l limit] [-o ssh_option] [-P port] [-S program]
[[user@]host1:]file1 [...] [[user@]host2:]file2
[Stewart:console/ebooks/discostat] jmm%
</code></pre>
<p>I'd like to be able to transfer files in both directions. From what I read, I thought the above command would work for downloading, and <code>scp -p [localpath] [remotepath]</code> for uploading? </p>
| [
{
"answer_id": 343720,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 4,
"selected": false,
"text": "scp [from] [to] scp -p server:serverpath localpath"
},
{
"answer_id": 343723,
"author": "lemnisca",
"author_id": 43463,
"author_profile": "https://Stackoverflow.com/users/43463",
"pm_score": 10,
"selected": false,
"text": "scp scp ./styles/ ./styles/ # download: remote -> local\nscp user@remote_host:remote_file local_file \n local_file # upload: local -> remote\nscp local_file user@remote_host:remote_file\n -r scp cp user@remote_host:file"
},
{
"answer_id": 343739,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 7,
"selected": false,
"text": "# copy from local machine to remote machine\nscp localfile user@host:/path/to/whereyouwant/thefile\n # copy from remote machine to local machine\nscp user@host:/path/to/remotefile localfile\n"
},
{
"answer_id": 343822,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 5,
"selected": false,
"text": "scp -pr user@remoteserver:whatever .\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,717 | <p>I raised a request over at Microsoft Connect regarding the formatting of dates ("<a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=327261" rel="nofollow noreferrer">DateTime Formatting should caluclate the correct suffix for the day</a>"). Basically I wanted to have a formatting string code for adding the suffix to the day number. So "1 Jan" would be formatted "1st Jan" and "2 Jan" formatted "2nd Jan" etc.</p>
<p>This is quite easy to do for the English case however Microsoft have rejected the idea on the grounds that it would be too hard to internationalise.</p>
<p>I was just wondering if people agree that it is reasonable for Microsoft to make life harder for English programmers writing solely for an English market, just because they can’t cater for the Non-English market?</p>
<p><strong>Edit:</strong> Ok, I accept the argument that it is there framework to do what they want with. I was asking more out of an ideological sense. Also remember that there is an easy fallback for Non-English cultures which is to add nothing, which makes people no worse off than they are now.</p>
<p><strong>Edit 2:</strong> For me this is more than an hours work. I need to support code that looks something like this:</p>
<pre><code> DateTime minDate = new DateTime(2003, 12, 10);
string errorMessage = ValidationMessageResource.DateTooEarly;
Console.WriteLine(String.Format(errorMessage, minDate));
</code></pre>
<p>I have no control over the resource file's contents and the resource string is often something like this "The date should not be before {0:D}". To do this I would need to implement my own IFormatProvider class which would have to support all the different formatting strings Microsoft's formatter accepts. Microsoft doesn’t seem to have given an easy way to extend their formatter through inheritance.</p>
| [
{
"answer_id": 344077,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "%x %o %O %o"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20553/"
] |
343,728 | <p>Apache XMLBeans can be used to generate Java classes and interfaces from XML Schema Definition files (XSD). It also generates Enums based on StringEnumAbstractBase and StringEnumAbstractBase.Table to represent domain values. They are handy for entering only valid values. However, I want to get all those values to generate a JCombobox, a JTable or a html table. </p>
<p>Is there a XMLBeans API call to get all Enum values from a generated class?
Is the only choice available some sort of Java reflection?</p>
<p>Thanks</p>
| [
{
"answer_id": 344064,
"author": "Nick Holt",
"author_id": 41423,
"author_profile": "https://Stackoverflow.com/users/41423",
"pm_score": 3,
"selected": true,
"text": "for (int i = 1; i <= MyEnum.Enum.table.lastInt(); i++) \n{\n System.out.println(MyEnum.Enum.forInt(i));\n}\n"
},
{
"answer_id": 1358453,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "public static List<String> getEnumValueList(XmlString xmlString){\n List<String> values = new ArrayList<String>();\n SchemaStringEnumEntry valArr[] = xmlString.schemaType().getStringEnumEntries();\n for(SchemaStringEnumEntry val : valArr){\n values.add(val.getString());\n }\n return values;\n}\n getEnumValueList(ModelType.Factory.newInstance());\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24165/"
] |
343,732 | <p>In our app, we currently live with the legacy of a decision to store all engineering data in our database in SI.</p>
<p>I worry that we may run the risk of not having sufficient precision and accuracy in our database or in .NET numeric types. I am also worried that we may see artifacts of floating-point maths (although that is probably a question all to itself). </p>
<p>For example, the source data may have been a pressure quantity expressed (and read in from some 3rd party service) in Psi (pounds per square inch). The engineers will have chosen this unit of measure because (for the quantity being expressed) this will tend to give easily-digested, human-readable numbers without requiring scientific notation.</p>
<p>When we 'standardise' the number, i.e. when we convert this quantity for our own persistence, we might convert it to Pa (Pascals) which will require either multiplying or dividing the number by some other potentially large number.</p>
<p>We often end up storing very large or very small numbers, and worse - we might do further calculations on these numbers.</p>
<p>At present we use ORACLE float and System.Double.</p>
<p>What do people think of this?</p>
<p><strong>UPDATE</strong></p>
<p>Further research has unearthed <a href="http://blogs.msdn.com/andrewkennedy/archive/2008/08/20/units-of-measure-in-f-part-one-introducing-units.aspx" rel="nofollow noreferrer">Units of Measure support</a> in the forthcoming F# language (in CTP as I write).</p>
<p>It seems we'll be able to have F# understand user input such as:</p>
<pre><code>9.81<n/s^2> // an acceleration
</code></pre>
<p>We'll also be able to create our own derived units and unit systems.</p>
<p><a href="https://i.stack.imgur.com/xMfVf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xMfVf.png" alt="creating a derived unit for Newtons in F#"></a><br>
<sub>(source: <a href="http://blogs.msdn.com/blogfiles/andrewkennedy/WindowsLiveWriter/UnitsofMeasureinFPartOneIntroducingUnits_A131/image_thumb_11.png" rel="nofollow noreferrer">msdn.com</a>)</sub> </p>
| [
{
"answer_id": 343751,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 4,
"selected": true,
"text": "NUMERIC(p,s)"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343732",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5351/"
] |
343,744 | <p>Is it possible to close parent window in Firefox 2.0 using JavaScript. I have a parent page which opens another window, i need to close the parent window after say 10 seconds.
I have tried Firefox tweaks "dom.allow_scripts_to_close_windows", tried delay but nothing seems to work.</p>
<p>Any help will be really appreciated.</p>
<p>Thanks</p>
| [
{
"answer_id": 343774,
"author": "user37125",
"author_id": 37125,
"author_profile": "https://Stackoverflow.com/users/37125",
"pm_score": 3,
"selected": true,
"text": "opener.close()\n opener.opener = top; // or whatever, as long as opener.opener has a value;\nopener.close()\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21195/"
] |
343,753 | <p>I have a mysql database which as one of the fields contains a html description. This description is not in my control, and is obtained and inserted automatically. An example of one of these descriptions is here:</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22492" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22492</a></p>
<p>The data is originally exported from an access database, and seems to remain intact. An example of the exported data is here:</p>
<p><a href="http://www.yousendit.com/transfer.php?action=batch_download&batch_id=TTZtWmdsT01kMnVGa1E9PQ" rel="nofollow noreferrer">http://www.yousendit.com/transfer.php?action=batch_download&batch_id=TTZtWmdsT01kMnVGa1E9PQ</a></p>
<p>I am trying to output the variable containing the html description into a popupwindow, to display it as is. The code I am trying to use to do this is here:</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22498" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22498</a></p>
<p>However it produces the following html code:</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22462" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22462</a></p>
<p>There is an unclosed style tag which prevents the rest of the page from displaying, and the popup winbdow from opening. I have narrowed this down to a php problem as far as I can tell, because the data seems fine in mysql.</p>
<p>edit:</p>
<p>I just attempted to select only article_Desc from the database with this code:</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22494" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22494</a></p>
<p>Which produced this as a result:</p>
<p><a href="http://www.nomorepasting.com/getpaste.php?pasteid=22496" rel="nofollow noreferrer">http://www.nomorepasting.com/getpaste.php?pasteid=22496</a></p>
<p>edit2:</p>
<p>There seem to be a problem with the countrycode variable containing the style tag. When I remove this, the picture is displayed and the popupwindow is created, only with html results much like the last link I pasted. The data seems correct in the database, so what could be causing this problem?</p>
| [
{
"answer_id": 343778,
"author": "OIS",
"author_id": 36175,
"author_profile": "https://Stackoverflow.com/users/36175",
"pm_score": 2,
"selected": false,
"text": "child1.document.write(' . json_encode($row2[\"ARTICLE_DESC\"]) . ');\n child1.document.write(\"\");\n $sql=\"SELECT * FROM Auctions WHERE ARTICLE_NO ='$pk'\";\n$sql2=\"SELECT ARTICLE_DESC FROM Auctions WHERE ARTICLE_NO ='$pk'\";\n $query = \"SELECT article_desc FROM Auctions WHERE ARTICLE_NO ='220288560247'\";\n json_encode($row['article_desc'])\n str_replace(array(\"\\n\", \"\\r\", \"\\t\"), array('', '', ''), $row['article_desc']);\n <!-- text -->\n <!-- +++++++++++++++++++++++++ Bitte ändern Sie im eigenen Interesse nichts an diesem Code! ++++++++++++++++++++++++ -->\n<!-- +++++++++++++++++++++++++ Das kann massive Fehldarstellungen ihrer Auktion zur Folge haben! +++++++++++++++++++ -->\n<!-- +++++++++++++++++++++++++ ++++++++++++++++++++++++++ Ihr Supreme Team +++++++++++++++++++++++++++++++++++++++++ -->\n"
},
{
"answer_id": 343858,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 2,
"selected": true,
"text": "String1\nString2\nStri,ng3\n String1,String2,Stri,ng3 \"String1\", \"String2\", \"Stri,ng3\" String1\nString\"2\n \"String1\", \"String\\\"2\"\n FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\\\'\n \\n \\\\n \\r \\\\r"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
343,764 | <p>So I've just recently made the step from ad hoc debugging with <code>dump</code>, <code>print_r</code> and <code>echo</code> to some more sophisticated methods and I'm having a struggle. </p>
<p>I work with Zend Framework, Aptana and Zend Debugger.</p>
<p>At this moment I'm trying to debug a custom controller and whatever I try I don't get to my breakpoint which I understand since there is authentication in between and using the menu.</p>
<p><strong>Questions</strong>:</p>
<ol>
<li>How can I make my application break at the point of authentication, login in the browser, navigate to a certain uri and then continue debugging?</li>
<li>What are good places to set breakpoints in Zend Framework with MVC?</li>
</ol>
| [
{
"answer_id": 343906,
"author": "Jay",
"author_id": 41690,
"author_profile": "https://Stackoverflow.com/users/41690",
"pm_score": 1,
"selected": false,
"text": "define('MODE_DEBUG', 1);\n if($obj->myLoginMethod() || constant('MODE_DEBUG') == 1){\n\n}\n define('MODE_DEBUG', (false !== strpos($_SERVER['HTTP_HOST'], 'dev.mysite.com') ? 1 : 0));\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11995/"
] |
343,769 | <p>We use a number of diffrent web services in our company, wiki(moinmoin), bugtracker (internally), requestracker (customer connection), subversion. Is there a way to parse the wikipages so that if I write "... in Bug1234 you could ..." Bug1234 woud be renderd as a link to <code>http://mybugtracker/bug1234</code></p>
| [
{
"answer_id": 1932862,
"author": "meduz",
"author_id": 234547,
"author_profile": "https://Stackoverflow.com/users/234547",
"pm_score": 0,
"selected": false,
"text": "data/intermap.txt wpen http://en.wikipedia.org/wiki/\n [[wpen:MoinMoin]] http://en.wikipedia.org/wiki/MoinMoin wpfr http://fr.wikipedia.org/wiki/\nwpde http://de.wikipedia.org/wiki/\n data/intermap.txt tracker http://mybugtracker/\n [[tracker:bug1234]]"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42580/"
] |
343,790 | <p>I am trying to play the Asterisk system sound from a C# program with</p>
<pre><code>System.Media.SystemSounds.Asterisk.Play();
</code></pre>
<p>but no sound plays. My system does have a sound set up for Asterisk and other programs (not written by me) cause various system sounds to play.</p>
<p>Can anyone suggest any possible reasons for this?</p>
| [
{
"answer_id": 344130,
"author": "ng5000",
"author_id": 36860,
"author_profile": "https://Stackoverflow.com/users/36860",
"pm_score": 1,
"selected": false,
"text": "[DllImport(\"user32.dll\", CharSet=CharSet.Auto, ExactSpelling=true)]\ninternal static extern bool MessageBeep(int type);\n"
},
{
"answer_id": 37687414,
"author": "teynon",
"author_id": 697477,
"author_profile": "https://Stackoverflow.com/users/697477",
"pm_score": 0,
"selected": false,
"text": "Restart"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535/"
] |
343,811 | <p>I'm trying to click on a link using jquery. There only appears to be a click event that replicates "onclick" (i.e user input). Is it possible to use jquery to actually click a link?</p>
| [
{
"answer_id": 344186,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 6,
"selected": true,
"text": "$(\"a[0]\") \n $(\"a:first\") \n $(\"a\").eq(0). \n $(\"table[1]/tr[1]/td[1]/a\").trigger('click'); \n $(\"table\").eq(1).children(\"tr\").eq(1).children('td').eq(1).children('a').click();\n document.location = $(\"table\").eq(1).children(\"tr\").eq(1).children('td').eq(1).children('a').attr('href');\n $(\"table:eq(1) > tr:eq(1) > td:eq(1) > a\").click();\n document.location = $(\"table\").eq(0).children(\"tr\").eq(0).children('td').eq(0).children('a').eq(0).attr('href');\n"
},
{
"answer_id": 350153,
"author": "Andreas Grech",
"author_id": 44084,
"author_profile": "https://Stackoverflow.com/users/44084",
"pm_score": 0,
"selected": false,
"text": "$(\"table:first\").find(\"tr:first\").find(\"td:first\").find(\"a:first\").click();\n"
},
{
"answer_id": 443786,
"author": "bang",
"author_id": 611084,
"author_profile": "https://Stackoverflow.com/users/611084",
"pm_score": 2,
"selected": false,
"text": "$(\"table:first\").find(\"tr:first\").find(\"td:first\").find(\"a:first\")[0].click();\n"
},
{
"answer_id": 1677847,
"author": "ElHaix",
"author_id": 172359,
"author_profile": "https://Stackoverflow.com/users/172359",
"pm_score": 2,
"selected": false,
"text": " $(document).ready(function() {\n $(\"#horizontalSlideButton\").trigger('click');\n }); \n"
},
{
"answer_id": 2731125,
"author": "Bojanglez",
"author_id": 328061,
"author_profile": "https://Stackoverflow.com/users/328061",
"pm_score": 2,
"selected": false,
"text": "var event = document.createEvent(\"HTMLEvents\");\nevent.initEvent(\"click\", true, true);\ndocument.getElementById('myID').dispatchEvent(event); \n"
},
{
"answer_id": 6844477,
"author": "Eric",
"author_id": 749657,
"author_profile": "https://Stackoverflow.com/users/749657",
"pm_score": 0,
"selected": false,
"text": " $(document).ready(function() {\n $(\".myclass\").live('click', function(){//do something});\n\n});\n $(document).ready(function() {\n $(\"#myid\").live('click', function(){//do something});\n\n});\n <span class=\"link\"><a href=\"javascript:void(0);\" target=\"_new\">my link/a></span>\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43626/"
] |
343,841 | <p>How to configure Tomcat 5.5 to authenticate against Win2003 Activedirectory(LDAP)</p>
<p>What changes are needed to default tomcat configuration, at least server.xml needs to be changed somehow to have IP of Win2003 server?</p>
| [
{
"answer_id": 356370,
"author": "Jerome Delattre",
"author_id": 27762,
"author_profile": "https://Stackoverflow.com/users/27762",
"pm_score": 3,
"selected": true,
"text": " <Realm\n className=\"org.apache.catalina.realm.JNDIRealm\"\n debug=\"99\"\n connectionURL=\"ldap://your-activedirectory-server:389\"\n connectionName=\"a user with read access to AD (optional if anonymous access is permitted)\"\n connectionPassword=\"password\"\n referrals=\"follow\"\n userBase=\"where to look for users, for instance: DC=mycompany,DC=com\"\n userSearch=\"(sAMAccountName={0})\"\n userSubtree=\"true\"\n roleBase=\"where to look for groups, for instance: DC=mycompany,DC=com\"\n roleName=\"cn\"\n roleSearch=\"(member={0})\"\n roleSubtree=\"true\"/>\n"
},
{
"answer_id": 10622152,
"author": "der",
"author_id": 1399074,
"author_profile": "https://Stackoverflow.com/users/1399074",
"pm_score": 0,
"selected": false,
"text": "seen below:-- emailAddress=mail\n\nUser Property Names Mapping : userId=sAMAccountName,name=cn,emailAddress=displayName\n displayName"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20979/"
] |
343,852 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/295579/fastest-way-to-determine-if-an-integers-square-root-is-an-integer">Fastest way to determine if an integer's square root is an integer</a> </p>
</blockquote>
<p>What's a way to see if a number is a <a href="http://en.wikipedia.org/wiki/Square_number" rel="noreferrer">perfect square</a>?
</p>
<pre class="lang-cs prettyprint-override"><code>bool IsPerfectSquare(long input)
{
// TODO
}
</code></pre>
<p>I'm using C# but this is language agnostic.</p>
<p>Bonus points for clarity and simplicity (this isn't meant to be code-golf).</p>
<hr>
<p><strong>Edit:</strong> This got much more complex than I expected! It turns out the problems with double precision manifest themselves a couple ways. First, Math.Sqrt takes a double which can't precisely hold a long (thanks Jon). </p>
<p>Second, a double's precision will lose small values ( .000...00001) when you have a huge, near perfect square. e.g., my implementation failed this test for Math.Pow(10,18)+1 (mine reported true).</p>
| [
{
"answer_id": 343862,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "bool IsPerfectSquare(long input)\n{\n long closestRoot = (long) Math.Sqrt(input);\n return input == closestRoot * closestRoot;\n}\n bool IsPerfectSquare(long input)\n{\n double root = Math.Sqrt(input);\n\n long rootBits = BitConverter.DoubleToInt64Bits(root);\n long lowerBound = (long) BitConverter.Int64BitsToDouble(rootBits-1);\n long upperBound = (long) BitConverter.Int64BitsToDouble(rootBits+1);\n\n for (long candidate = lowerBound; candidate <= upperBound; candidate++)\n {\n if (candidate * candidate == input)\n {\n return true;\n }\n }\n return false;\n}\n"
},
{
"answer_id": 343864,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 4,
"selected": false,
"text": "bool IsPerfectSquare(long input)\n{\n long SquareRoot = (long) Math.Sqrt(input);\n return ((SquareRoot * SquareRoot) == input);\n}\n"
},
{
"answer_id": 343876,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 3,
"selected": false,
"text": "(defun perfect-square-p (n)\n (= (expt (isqrt n) 2)\n n))\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29/"
] |
343,865 | <p>I have a bunch of files with coordinates in UTM form. For each coordinate I have easting, northing and zone. I need to convert this to LatLng for use with Google Map API to show the information in a map.</p>
<p>I have found some online calculators that does this, but no actual code or libraries. <a href="http://trac.osgeo.org/proj4js/" rel="noreferrer">http://trac.osgeo.org/proj4js/</a> is a projection library for Javascript, but looking at the demo it doesn't include UTM projection.</p>
<p>I am still pretty fresh to the entire GIS domain, so what I want is something ala:</p>
<pre><code>(lat,lng) = transform(easting, northing, zone)
</code></pre>
| [
{
"answer_id": 344083,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 6,
"selected": true,
"text": "import math\n\ndef utmToLatLng(zone, easting, northing, northernHemisphere=True):\n if not northernHemisphere:\n northing = 10000000 - northing\n\n a = 6378137\n e = 0.081819191\n e1sq = 0.006739497\n k0 = 0.9996\n\n arc = northing / k0\n mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0))\n\n ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0)))\n\n ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0\n\n cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32\n cc = 151 * math.pow(ei, 3) / 96\n cd = 1097 * math.pow(ei, 4) / 512\n phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)\n\n n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))\n\n r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0))\n fact1 = n0 * math.tan(phi1) / r0\n\n _a1 = 500000 - easting\n dd0 = _a1 / (n0 * k0)\n fact2 = dd0 * dd0 / 2\n\n t0 = math.pow(math.tan(phi1), 2)\n Q0 = e1sq * math.pow(math.cos(phi1), 2)\n fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24\n\n fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720\n\n lof1 = _a1 / (n0 * k0)\n lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0\n lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120\n _a2 = (lof1 - lof2 + lof3) / math.cos(phi1)\n _a3 = _a2 * 180 / math.pi\n\n latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi\n\n if not northernHemisphere:\n latitude = -latitude\n\n longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3\n\n return (latitude, longitude)\n easting*x+zone*y"
},
{
"answer_id": 6734087,
"author": "TreyA",
"author_id": 817828,
"author_profile": "https://Stackoverflow.com/users/817828",
"pm_score": 1,
"selected": false,
"text": "////////////////////////////////////////////////////////////////////////////////////////////\n//\n// ToLL - function to compute Latitude and Longitude given UTM Northing and Easting in meters\n//\n// Description:\n// This member function converts input north and east coordinates\n// to the corresponding Northing and Easting values relative to the defined\n// UTM zone. Refer to the reference in this file's header.\n//\n// Parameters:\n// north - (i) Northing (meters)\n// east - (i) Easting (meters)\n// utmZone - (i) UTM Zone of the North and East parameters\n// lat - (o) Latitude in degrees \n// lon - (o) Longitude in degrees\n//\nfunction ToLL(north,east,utmZone)\n{ \n // This is the lambda knot value in the reference\n var LngOrigin = DegToRad(utmZone * 6 - 183)\n\n // The following set of class constants define characteristics of the\n // ellipsoid, as defined my the WGS84 datum. These values need to be\n // changed if a different dataum is used. \n\n var FalseNorth = 0. // South or North?\n //if (lat < 0.) FalseNorth = 10000000. // South or North?\n //else FalseNorth = 0. \n\n var Ecc = 0.081819190842622 // Eccentricity\n var EccSq = Ecc * Ecc\n var Ecc2Sq = EccSq / (1. - EccSq)\n var Ecc2 = Math.sqrt(Ecc2Sq) // Secondary eccentricity\n var E1 = ( 1 - Math.sqrt(1-EccSq) ) / ( 1 + Math.sqrt(1-EccSq) )\n var E12 = E1 * E1\n var E13 = E12 * E1\n var E14 = E13 * E1\n\n var SemiMajor = 6378137.0 // Ellipsoidal semi-major axis (Meters)\n var FalseEast = 500000.0 // UTM East bias (Meters)\n var ScaleFactor = 0.9996 // Scale at natural origin\n\n // Calculate the Cassini projection parameters\n\n var M1 = (north - FalseNorth) / ScaleFactor\n var Mu1 = M1 / ( SemiMajor * (1 - EccSq/4.0 - 3.0*EccSq*EccSq/64.0 -\n 5.0*EccSq*EccSq*EccSq/256.0) )\n\n var Phi1 = Mu1 + (3.0*E1/2.0 - 27.0*E13/32.0) * Math.sin(2.0*Mu1)\n + (21.0*E12/16.0 - 55.0*E14/32.0) * Math.sin(4.0*Mu1)\n + (151.0*E13/96.0) * Math.sin(6.0*Mu1)\n + (1097.0*E14/512.0) * Math.sin(8.0*Mu1)\n\n var sin2phi1 = Math.sin(Phi1) * Math.sin(Phi1)\n var Rho1 = (SemiMajor * (1.0-EccSq) ) / Math.pow(1.0-EccSq*sin2phi1,1.5)\n var Nu1 = SemiMajor / Math.sqrt(1.0-EccSq*sin2phi1)\n\n // Compute parameters as defined in the POSC specification. T, C and D\n\n var T1 = Math.tan(Phi1) * Math.tan(Phi1)\n var T12 = T1 * T1\n var C1 = Ecc2Sq * Math.cos(Phi1) * Math.cos(Phi1)\n var C12 = C1 * C1\n var D = (east - FalseEast) / (ScaleFactor * Nu1)\n var D2 = D * D\n var D3 = D2 * D\n var D4 = D3 * D\n var D5 = D4 * D\n var D6 = D5 * D\n\n // Compute the Latitude and Longitude and convert to degrees\n var lat = Phi1 - Nu1*Math.tan(Phi1)/Rho1 *\n ( D2/2.0 - (5.0 + 3.0*T1 + 10.0*C1 - 4.0*C12 - 9.0*Ecc2Sq)*D4/24.0\n + (61.0 + 90.0*T1 + 298.0*C1 + 45.0*T12 - 252.0*Ecc2Sq - 3.0*C12)*D6/720.0 )\n\n lat = RadToDeg(lat)\n\n var lon = LngOrigin + \n ( D - (1.0 + 2.0*T1 + C1)*D3/6.0\n + (5.0 - 2.0*C1 + 28.0*T1 - 3.0*C12 + 8.0*Ecc2Sq + 24.0*T12)*D5/120.0) / Math.cos(Phi1)\n\n lon = RadToDeg(lon)\n\n // Create a object to store the calculated Latitude and Longitude values\n var sendLatLon = new PC_LatLon(lat,lon)\n\n // Returns a PC_LatLon object\n return sendLatLon\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n//\n// RadToDeg - function that inputs a value in radians and returns a value in degrees\n//\nfunction RadToDeg(value)\n{\n return ( value * 180.0 / Math.PI )\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n//\n// PC_LatLon - this psuedo class is used to store lat/lon values computed by the ToLL \n// function.\n//\nfunction PC_LatLon(inLat,inLon)\n{\n this.lat = inLat // Store Latitude in decimal degrees\n this.lon = inLon // Store Longitude in decimal degrees\n}\n"
},
{
"answer_id": 10239676,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 3,
"selected": false,
"text": "import osr\n\ndef transform_utm_to_wgs84(easting, northing, zone):\n utm_coordinate_system = osr.SpatialReference()\n utm_coordinate_system.SetWellKnownGeogCS(\"WGS84\") # Set geographic coordinate system to handle lat/lon\n is_northern = northing > 0 \n utm_coordinate_system.SetUTM(zone, is_northern)\n\n wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system \n\n # create transform component\n utm_to_wgs84_transform = osr.CoordinateTransformation(utm_coordinate_system, wgs84_coordinate_system) # (<from>, <to>)\n return utm_to_wgs84_transform.TransformPoint(easting, northing, 0) # returns lon, lat, altitude\n def transform_wgs84_to_utm(lon, lat): \n def get_utm_zone(longitude):\n return (int(1+(longitude+180.0)/6.0))\n\n def is_northern(latitude):\n \"\"\"\n Determines if given latitude is a northern for UTM\n \"\"\"\n if (latitude < 0.0):\n return 0\n else:\n return 1\n\n utm_coordinate_system = osr.SpatialReference()\n utm_coordinate_system.SetWellKnownGeogCS(\"WGS84\") # Set geographic coordinate system to handle lat/lon \n utm_coordinate_system.SetUTM(get_utm_zone(lon), is_northern(lat))\n\n wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system \n\n # create transform component\n wgs84_to_utm_transform = osr.CoordinateTransformation(wgs84_coordinate_system, utm_coordinate_system) # (<from>, <to>)\n return wgs84_to_utm_transform.TransformPoint(lon, lat, 0) # returns easting, northing, altitude \n Point() from django.contrib.gis.geos import Point\nutm2epsg = {\"54N\": 3185, ...}\np = Point(lon, lat, srid=4326) # 4326 = WGS84 epsg code\np.transform(utm2epsg[\"54N\"])\n"
},
{
"answer_id": 18621253,
"author": "Richard",
"author_id": 752843,
"author_profile": "https://Stackoverflow.com/users/752843",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head>\n <script src=\"proj4.js\"></script>\n\n <script>\n var utm = \"+proj=utm +zone=32\";\n var wgs84 = \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\";\n console.log(proj4(utm,wgs84,[539884, 4942158]));\n </script>\n</head>\n<body>\n\n</body>\n</html>\n [9.502832656648073, 44.631671014204365] \n"
},
{
"answer_id": 27388998,
"author": "sandino",
"author_id": 441515,
"author_profile": "https://Stackoverflow.com/users/441515",
"pm_score": 3,
"selected": false,
"text": "function utmToLatLng(zone, easting, northing, northernHemisphere){\n if (!northernHemisphere){\n northing = 10000000 - northing;\n }\n\n var a = 6378137;\n var e = 0.081819191;\n var e1sq = 0.006739497;\n var k0 = 0.9996;\n\n var arc = northing / k0;\n var mu = arc / (a * (1 - Math.pow(e, 2) / 4.0 - 3 * Math.pow(e, 4) / 64.0 - 5 * Math.pow(e, 6) / 256.0));\n\n var ei = (1 - Math.pow((1 - e * e), (1 / 2.0))) / (1 + Math.pow((1 - e * e), (1 / 2.0)));\n\n var ca = 3 * ei / 2 - 27 * Math.pow(ei, 3) / 32.0;\n\n var cb = 21 * Math.pow(ei, 2) / 16 - 55 * Math.pow(ei, 4) / 32;\n var cc = 151 * Math.pow(ei, 3) / 96;\n var cd = 1097 * Math.pow(ei, 4) / 512;\n var phi1 = mu + ca * Math.sin(2 * mu) + cb * Math.sin(4 * mu) + cc * Math.sin(6 * mu) + cd * Math.sin(8 * mu);\n\n var n0 = a / Math.pow((1 - Math.pow((e * Math.sin(phi1)), 2)), (1 / 2.0));\n\n var r0 = a * (1 - e * e) / Math.pow((1 - Math.pow((e * Math.sin(phi1)), 2)), (3 / 2.0));\n var fact1 = n0 * Math.tan(phi1) / r0;\n\n var _a1 = 500000 - easting;\n var dd0 = _a1 / (n0 * k0);\n var fact2 = dd0 * dd0 / 2;\n\n var t0 = Math.pow(Math.tan(phi1), 2);\n var Q0 = e1sq * Math.pow(Math.cos(phi1), 2);\n var fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * Math.pow(dd0, 4) / 24;\n\n var fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * Math.pow(dd0, 6) / 720;\n\n var lof1 = _a1 / (n0 * k0);\n var lof2 = (1 + 2 * t0 + Q0) * Math.pow(dd0, 3) / 6.0;\n var lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * Math.pow(Q0, 2) + 8 * e1sq + 24 * Math.pow(t0, 2)) * Math.pow(dd0, 5) / 120;\n var _a2 = (lof1 - lof2 + lof3) / Math.cos(phi1);\n var _a3 = _a2 * 180 / Math.PI;\n\n var latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / Math.PI;\n\n if (!northernHemisphere){\n latitude = -latitude;\n }\n\n var longitude = ((zone > 0) && (6 * zone - 183.0) || 3.0) - _a3;\n\n var obj = {\n latitude : latitude,\n longitude: longitude\n };\n\n\n return obj;\n }\n"
},
{
"answer_id": 51968448,
"author": "miln40",
"author_id": 1729547,
"author_profile": "https://Stackoverflow.com/users/1729547",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\ndef utmToLatLng(zone, easting, northing, northernHemisphere=True):\n if not northernHemisphere:\n northing = 10000000 - northing\n\na = 6378137\ne = 0.081819191\ne1sq = 0.006739497\nk0 = 0.9996\n\narc = northing / k0\nmu = arc / (a * (1 - np.power(e, 2) / 4.0 - 3 * np.power(e, 4) / 64.0 - 5 * np.power(e, 6) / 256.0))\n\nei = (1 - np.power((1 - e * e), (1 / 2.0))) / (1 + np.power((1 - e * e), (1 / 2.0)))\n\nca = 3 * ei / 2 - 27 * np.power(ei, 3) / 32.0\n\ncb = 21 * np.power(ei, 2) / 16 - 55 * np.power(ei, 4) / 32\ncc = 151 * np.power(ei, 3) / 96\ncd = 1097 * np.power(ei, 4) / 512\nphi1 = mu + ca * np.sin(2 * mu) + cb * np.sin(4 * mu) + cc * np.sin(6 * mu) + cd * np.sin(8 * mu)\n\nn0 = a / np.power((1 - np.power((e * np.sin(phi1)), 2)), (1 / 2.0))\n\nr0 = a * (1 - e * e) / np.power((1 - np.power((e * np.sin(phi1)), 2)), (3 / 2.0))\nfact1 = n0 * np.tan(phi1) / r0\n\n_a1 = 500000 - easting\ndd0 = _a1 / (n0 * k0)\nfact2 = dd0 * dd0 / 2\n\nt0 = np.power(np.tan(phi1), 2)\nQ0 = e1sq * np.power(np.cos(phi1), 2)\nfact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * np.power(dd0, 4) / 24\n\nfact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * np.power(dd0, 6) / 720\n\nlof1 = _a1 / (n0 * k0)\nlof2 = (1 + 2 * t0 + Q0) * np.power(dd0, 3) / 6.0\nlof3 = (5 - 2 * Q0 + 28 * t0 - 3 * np.power(Q0, 2) + 8 * e1sq + 24 * np.power(t0, 2)) * np.power(dd0, 5) / 120\n_a2 = (lof1 - lof2 + lof3) / np.cos(phi1)\n_a3 = _a2 * 180 / np.pi\n\nlatitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / np.pi\n\nif not northernHemisphere:\n latitude = -latitude\n\nlongitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3\n\nreturn (latitude, longitude)\n df['LAT'], df['LON']=utmToLatLng(31, df['X'], df['Y'], northernHemisphere=True)\n"
},
{
"answer_id": 70036872,
"author": "Roar Grønmo",
"author_id": 4475206,
"author_profile": "https://Stackoverflow.com/users/4475206",
"pm_score": 0,
"selected": false,
"text": "\nfun utmToLatLng2(\n north:Double?,\n east:Double?,\n zone:Long,\n northernHemisphere: Boolean\n):LatLng?{\n\n if((north==null)||(east == null)) return null\n\n val lngOrigin = Math.toRadians(zone*6.0 - 183.0)\n val falseNorth = if(northernHemisphere) 0.toDouble() else 10000000.toDouble()\n\n val ecc = 0.081819190842622\n val eccSq = ecc*ecc\n val ecc2Sq = eccSq / (1.0 - eccSq)\n //var ecc2 = sqrt(ecc2Sq) //not in use ?\n val e1 = (1.0 - sqrt(1.0-eccSq))/(1.0 + sqrt(1-eccSq))\n val e12 = e1*e1\n val e13 = e12*e1\n val e14 = e13*e1\n\n val semiMajor = 6378137.0\n val falseEast = 500000.0\n val scaleFactor = 0.9996\n\n //Cassini\n\n val m1 = (north - falseNorth) / scaleFactor\n val mu1 = m1 / (semiMajor * (1.0 - eccSq/4.0 - 3.0*eccSq*eccSq/64.0 - 5.0*eccSq*eccSq*eccSq/256.0))\n\n val phi1 = mu1 +\n (3.0 * e1 / 2.0 - 27.0 * e13 / 32.0) * sin(2.0 * mu1) +\n (21.0 * e12 / 16.0 - 55.0 * e14 / 32.0) * sin(4.0 * mu1) +\n (151.0 * e13 / 96.0) * sin(6.0 * mu1) +\n (1097.0 * e14 / 512.0) * sin( 8.0 * mu1)\n\n val sin2phi1 = sin(phi1) * sin(phi1)\n val rho1 = (semiMajor * (1.0-eccSq)) / (1.0 - eccSq * sin2phi1).pow(1.5)\n val nu1 = semiMajor / sqrt(1.0-eccSq*sin2phi1)\n\n //POSC\n\n val t1 = tan(phi1)*tan(phi1)\n val t12 = t1*t1\n val c1 = ecc2Sq*cos(phi1)*cos(phi1)\n val c12 = c1*c1\n val d = (east - falseEast) / (scaleFactor*nu1)\n val d2 = d*d\n val d3 = d2*d\n val d4 = d3*d\n val d5 = d4*d\n val d6 = d5*d\n\n //Compute lat & lon convert to degree\n\n var lat =\n phi1 - nu1 * tan(phi1)/rho1 *\n (d2/2.0 - (5.0 + 3.0*t1 + 10*c1 - 4.0*c12 -9.0*ecc2Sq) * d4/24.0 +\n (61.0 + 90.0*t1 +298.0*c1 + 45.0*t12 -252*ecc2Sq - 3.0*c12) * d6/720.0)\n\n lat = Math.toDegrees(lat)\n\n var lon =\n lngOrigin +\n (d - (1.0 + 2.0*t1 + c1)*d3/6.0 +\n (5.0 - 2.0*c1 + 28.0*t1 - 3.0*c12 + 8.0*ecc2Sq + 24.0*t12)*d5/120.0) / cos(phi1)\n\n lon = Math.toDegrees(lon)\n\n return LatLng(lat,lon)\n\n\n}\n\n\n\n"
},
{
"answer_id": 70309354,
"author": "Bernat",
"author_id": 5924929,
"author_profile": "https://Stackoverflow.com/users/5924929",
"pm_score": 2,
"selected": false,
"text": ">>> utm.from_latlon(51.2, 7.5)\n (395201.3103811303, 5673135.241182375, 32, 'U')\n (EASTING, NORTHING, ZONE_NUMBER, ZONE_LETTER) >>> utm.from_latlon(np.array([51.2, 49.0]), np.array([7.5, 8.4]))\n (array([395201.31038113, 456114.59586214]), array([5673135.24118237, 5427629.20426126]), 32, 'U')\n >>> utm.to_latlon(340000, 5710000, 32, 'U')\n (51.51852098408468, 6.693872395145327)\n utm.to_latlon(EASTING, NORTHING, ZONE_NUMBER, ZONE_LETTER)"
},
{
"answer_id": 71313053,
"author": "Bernardo Costa",
"author_id": 9720343,
"author_profile": "https://Stackoverflow.com/users/9720343",
"pm_score": 0,
"selected": false,
"text": "from pyproj import Transformer, CRS\ncrs = CRS.from_epsg(25833) # put your desired EPSG code here\nlatlon2utm = Transformer.from_crs(crs.geodetic_crs, crs)\nlats = [58.969, 59.911] # latitudes of two Norwegian cities\nlons = [5.732, 10.750] # longitudes of two Norwegian cities\neastings, northings = latlon2utm.transform(lats, lons)\n utm2latlon = Transformer.from_crs(crs, crs.geodetic_crs)\nlatitudes, longitudes = utm2latlon.transform(eastings, northings)\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343865",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3355/"
] |
343,866 | <p>More and more applications need different representations of similar objects, e.g., when crossing the wire with web services or when mapping to the database. When you are working with a domain model you probably need one kind of objects in your business layer/domain model (small, lots of behaviour) and another when crossing process or network boundaries (big, only data) or when talking to the database (e.g., LINQ to SQL only supports 1-to-1 mapping between DB tables and generated/mapped objects).</p>
<p>This means you have to write a lot of code performing the rote task of translating/mapping similar objects to eachother. Surely there must be some kind of framework or tool to help you do this? Or is manual coding the only way to really be in control? We have investigated using reflection and XML/attribute mapping to solve this ourselves but it quickly gets fairly complicated, e.g., mapping subobjects and lists or several primitives on one object to a subobject on the other object.</p>
<p>We are using C# on .NET 3.5.</p>
| [
{
"answer_id": 344083,
"author": "Staale",
"author_id": 3355,
"author_profile": "https://Stackoverflow.com/users/3355",
"pm_score": 6,
"selected": true,
"text": "import math\n\ndef utmToLatLng(zone, easting, northing, northernHemisphere=True):\n if not northernHemisphere:\n northing = 10000000 - northing\n\n a = 6378137\n e = 0.081819191\n e1sq = 0.006739497\n k0 = 0.9996\n\n arc = northing / k0\n mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0))\n\n ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0)))\n\n ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0\n\n cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32\n cc = 151 * math.pow(ei, 3) / 96\n cd = 1097 * math.pow(ei, 4) / 512\n phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)\n\n n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))\n\n r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0))\n fact1 = n0 * math.tan(phi1) / r0\n\n _a1 = 500000 - easting\n dd0 = _a1 / (n0 * k0)\n fact2 = dd0 * dd0 / 2\n\n t0 = math.pow(math.tan(phi1), 2)\n Q0 = e1sq * math.pow(math.cos(phi1), 2)\n fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24\n\n fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720\n\n lof1 = _a1 / (n0 * k0)\n lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0\n lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120\n _a2 = (lof1 - lof2 + lof3) / math.cos(phi1)\n _a3 = _a2 * 180 / math.pi\n\n latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi\n\n if not northernHemisphere:\n latitude = -latitude\n\n longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3\n\n return (latitude, longitude)\n easting*x+zone*y"
},
{
"answer_id": 6734087,
"author": "TreyA",
"author_id": 817828,
"author_profile": "https://Stackoverflow.com/users/817828",
"pm_score": 1,
"selected": false,
"text": "////////////////////////////////////////////////////////////////////////////////////////////\n//\n// ToLL - function to compute Latitude and Longitude given UTM Northing and Easting in meters\n//\n// Description:\n// This member function converts input north and east coordinates\n// to the corresponding Northing and Easting values relative to the defined\n// UTM zone. Refer to the reference in this file's header.\n//\n// Parameters:\n// north - (i) Northing (meters)\n// east - (i) Easting (meters)\n// utmZone - (i) UTM Zone of the North and East parameters\n// lat - (o) Latitude in degrees \n// lon - (o) Longitude in degrees\n//\nfunction ToLL(north,east,utmZone)\n{ \n // This is the lambda knot value in the reference\n var LngOrigin = DegToRad(utmZone * 6 - 183)\n\n // The following set of class constants define characteristics of the\n // ellipsoid, as defined my the WGS84 datum. These values need to be\n // changed if a different dataum is used. \n\n var FalseNorth = 0. // South or North?\n //if (lat < 0.) FalseNorth = 10000000. // South or North?\n //else FalseNorth = 0. \n\n var Ecc = 0.081819190842622 // Eccentricity\n var EccSq = Ecc * Ecc\n var Ecc2Sq = EccSq / (1. - EccSq)\n var Ecc2 = Math.sqrt(Ecc2Sq) // Secondary eccentricity\n var E1 = ( 1 - Math.sqrt(1-EccSq) ) / ( 1 + Math.sqrt(1-EccSq) )\n var E12 = E1 * E1\n var E13 = E12 * E1\n var E14 = E13 * E1\n\n var SemiMajor = 6378137.0 // Ellipsoidal semi-major axis (Meters)\n var FalseEast = 500000.0 // UTM East bias (Meters)\n var ScaleFactor = 0.9996 // Scale at natural origin\n\n // Calculate the Cassini projection parameters\n\n var M1 = (north - FalseNorth) / ScaleFactor\n var Mu1 = M1 / ( SemiMajor * (1 - EccSq/4.0 - 3.0*EccSq*EccSq/64.0 -\n 5.0*EccSq*EccSq*EccSq/256.0) )\n\n var Phi1 = Mu1 + (3.0*E1/2.0 - 27.0*E13/32.0) * Math.sin(2.0*Mu1)\n + (21.0*E12/16.0 - 55.0*E14/32.0) * Math.sin(4.0*Mu1)\n + (151.0*E13/96.0) * Math.sin(6.0*Mu1)\n + (1097.0*E14/512.0) * Math.sin(8.0*Mu1)\n\n var sin2phi1 = Math.sin(Phi1) * Math.sin(Phi1)\n var Rho1 = (SemiMajor * (1.0-EccSq) ) / Math.pow(1.0-EccSq*sin2phi1,1.5)\n var Nu1 = SemiMajor / Math.sqrt(1.0-EccSq*sin2phi1)\n\n // Compute parameters as defined in the POSC specification. T, C and D\n\n var T1 = Math.tan(Phi1) * Math.tan(Phi1)\n var T12 = T1 * T1\n var C1 = Ecc2Sq * Math.cos(Phi1) * Math.cos(Phi1)\n var C12 = C1 * C1\n var D = (east - FalseEast) / (ScaleFactor * Nu1)\n var D2 = D * D\n var D3 = D2 * D\n var D4 = D3 * D\n var D5 = D4 * D\n var D6 = D5 * D\n\n // Compute the Latitude and Longitude and convert to degrees\n var lat = Phi1 - Nu1*Math.tan(Phi1)/Rho1 *\n ( D2/2.0 - (5.0 + 3.0*T1 + 10.0*C1 - 4.0*C12 - 9.0*Ecc2Sq)*D4/24.0\n + (61.0 + 90.0*T1 + 298.0*C1 + 45.0*T12 - 252.0*Ecc2Sq - 3.0*C12)*D6/720.0 )\n\n lat = RadToDeg(lat)\n\n var lon = LngOrigin + \n ( D - (1.0 + 2.0*T1 + C1)*D3/6.0\n + (5.0 - 2.0*C1 + 28.0*T1 - 3.0*C12 + 8.0*Ecc2Sq + 24.0*T12)*D5/120.0) / Math.cos(Phi1)\n\n lon = RadToDeg(lon)\n\n // Create a object to store the calculated Latitude and Longitude values\n var sendLatLon = new PC_LatLon(lat,lon)\n\n // Returns a PC_LatLon object\n return sendLatLon\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n//\n// RadToDeg - function that inputs a value in radians and returns a value in degrees\n//\nfunction RadToDeg(value)\n{\n return ( value * 180.0 / Math.PI )\n}\n\n////////////////////////////////////////////////////////////////////////////////////////////\n//\n// PC_LatLon - this psuedo class is used to store lat/lon values computed by the ToLL \n// function.\n//\nfunction PC_LatLon(inLat,inLon)\n{\n this.lat = inLat // Store Latitude in decimal degrees\n this.lon = inLon // Store Longitude in decimal degrees\n}\n"
},
{
"answer_id": 10239676,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 3,
"selected": false,
"text": "import osr\n\ndef transform_utm_to_wgs84(easting, northing, zone):\n utm_coordinate_system = osr.SpatialReference()\n utm_coordinate_system.SetWellKnownGeogCS(\"WGS84\") # Set geographic coordinate system to handle lat/lon\n is_northern = northing > 0 \n utm_coordinate_system.SetUTM(zone, is_northern)\n\n wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system \n\n # create transform component\n utm_to_wgs84_transform = osr.CoordinateTransformation(utm_coordinate_system, wgs84_coordinate_system) # (<from>, <to>)\n return utm_to_wgs84_transform.TransformPoint(easting, northing, 0) # returns lon, lat, altitude\n def transform_wgs84_to_utm(lon, lat): \n def get_utm_zone(longitude):\n return (int(1+(longitude+180.0)/6.0))\n\n def is_northern(latitude):\n \"\"\"\n Determines if given latitude is a northern for UTM\n \"\"\"\n if (latitude < 0.0):\n return 0\n else:\n return 1\n\n utm_coordinate_system = osr.SpatialReference()\n utm_coordinate_system.SetWellKnownGeogCS(\"WGS84\") # Set geographic coordinate system to handle lat/lon \n utm_coordinate_system.SetUTM(get_utm_zone(lon), is_northern(lat))\n\n wgs84_coordinate_system = utm_coordinate_system.CloneGeogCS() # Clone ONLY the geographic coordinate system \n\n # create transform component\n wgs84_to_utm_transform = osr.CoordinateTransformation(wgs84_coordinate_system, utm_coordinate_system) # (<from>, <to>)\n return wgs84_to_utm_transform.TransformPoint(lon, lat, 0) # returns easting, northing, altitude \n Point() from django.contrib.gis.geos import Point\nutm2epsg = {\"54N\": 3185, ...}\np = Point(lon, lat, srid=4326) # 4326 = WGS84 epsg code\np.transform(utm2epsg[\"54N\"])\n"
},
{
"answer_id": 18621253,
"author": "Richard",
"author_id": 752843,
"author_profile": "https://Stackoverflow.com/users/752843",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head>\n <script src=\"proj4.js\"></script>\n\n <script>\n var utm = \"+proj=utm +zone=32\";\n var wgs84 = \"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs\";\n console.log(proj4(utm,wgs84,[539884, 4942158]));\n </script>\n</head>\n<body>\n\n</body>\n</html>\n [9.502832656648073, 44.631671014204365] \n"
},
{
"answer_id": 27388998,
"author": "sandino",
"author_id": 441515,
"author_profile": "https://Stackoverflow.com/users/441515",
"pm_score": 3,
"selected": false,
"text": "function utmToLatLng(zone, easting, northing, northernHemisphere){\n if (!northernHemisphere){\n northing = 10000000 - northing;\n }\n\n var a = 6378137;\n var e = 0.081819191;\n var e1sq = 0.006739497;\n var k0 = 0.9996;\n\n var arc = northing / k0;\n var mu = arc / (a * (1 - Math.pow(e, 2) / 4.0 - 3 * Math.pow(e, 4) / 64.0 - 5 * Math.pow(e, 6) / 256.0));\n\n var ei = (1 - Math.pow((1 - e * e), (1 / 2.0))) / (1 + Math.pow((1 - e * e), (1 / 2.0)));\n\n var ca = 3 * ei / 2 - 27 * Math.pow(ei, 3) / 32.0;\n\n var cb = 21 * Math.pow(ei, 2) / 16 - 55 * Math.pow(ei, 4) / 32;\n var cc = 151 * Math.pow(ei, 3) / 96;\n var cd = 1097 * Math.pow(ei, 4) / 512;\n var phi1 = mu + ca * Math.sin(2 * mu) + cb * Math.sin(4 * mu) + cc * Math.sin(6 * mu) + cd * Math.sin(8 * mu);\n\n var n0 = a / Math.pow((1 - Math.pow((e * Math.sin(phi1)), 2)), (1 / 2.0));\n\n var r0 = a * (1 - e * e) / Math.pow((1 - Math.pow((e * Math.sin(phi1)), 2)), (3 / 2.0));\n var fact1 = n0 * Math.tan(phi1) / r0;\n\n var _a1 = 500000 - easting;\n var dd0 = _a1 / (n0 * k0);\n var fact2 = dd0 * dd0 / 2;\n\n var t0 = Math.pow(Math.tan(phi1), 2);\n var Q0 = e1sq * Math.pow(Math.cos(phi1), 2);\n var fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * Math.pow(dd0, 4) / 24;\n\n var fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * Math.pow(dd0, 6) / 720;\n\n var lof1 = _a1 / (n0 * k0);\n var lof2 = (1 + 2 * t0 + Q0) * Math.pow(dd0, 3) / 6.0;\n var lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * Math.pow(Q0, 2) + 8 * e1sq + 24 * Math.pow(t0, 2)) * Math.pow(dd0, 5) / 120;\n var _a2 = (lof1 - lof2 + lof3) / Math.cos(phi1);\n var _a3 = _a2 * 180 / Math.PI;\n\n var latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / Math.PI;\n\n if (!northernHemisphere){\n latitude = -latitude;\n }\n\n var longitude = ((zone > 0) && (6 * zone - 183.0) || 3.0) - _a3;\n\n var obj = {\n latitude : latitude,\n longitude: longitude\n };\n\n\n return obj;\n }\n"
},
{
"answer_id": 51968448,
"author": "miln40",
"author_id": 1729547,
"author_profile": "https://Stackoverflow.com/users/1729547",
"pm_score": 0,
"selected": false,
"text": "import numpy as np\n\ndef utmToLatLng(zone, easting, northing, northernHemisphere=True):\n if not northernHemisphere:\n northing = 10000000 - northing\n\na = 6378137\ne = 0.081819191\ne1sq = 0.006739497\nk0 = 0.9996\n\narc = northing / k0\nmu = arc / (a * (1 - np.power(e, 2) / 4.0 - 3 * np.power(e, 4) / 64.0 - 5 * np.power(e, 6) / 256.0))\n\nei = (1 - np.power((1 - e * e), (1 / 2.0))) / (1 + np.power((1 - e * e), (1 / 2.0)))\n\nca = 3 * ei / 2 - 27 * np.power(ei, 3) / 32.0\n\ncb = 21 * np.power(ei, 2) / 16 - 55 * np.power(ei, 4) / 32\ncc = 151 * np.power(ei, 3) / 96\ncd = 1097 * np.power(ei, 4) / 512\nphi1 = mu + ca * np.sin(2 * mu) + cb * np.sin(4 * mu) + cc * np.sin(6 * mu) + cd * np.sin(8 * mu)\n\nn0 = a / np.power((1 - np.power((e * np.sin(phi1)), 2)), (1 / 2.0))\n\nr0 = a * (1 - e * e) / np.power((1 - np.power((e * np.sin(phi1)), 2)), (3 / 2.0))\nfact1 = n0 * np.tan(phi1) / r0\n\n_a1 = 500000 - easting\ndd0 = _a1 / (n0 * k0)\nfact2 = dd0 * dd0 / 2\n\nt0 = np.power(np.tan(phi1), 2)\nQ0 = e1sq * np.power(np.cos(phi1), 2)\nfact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * np.power(dd0, 4) / 24\n\nfact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * np.power(dd0, 6) / 720\n\nlof1 = _a1 / (n0 * k0)\nlof2 = (1 + 2 * t0 + Q0) * np.power(dd0, 3) / 6.0\nlof3 = (5 - 2 * Q0 + 28 * t0 - 3 * np.power(Q0, 2) + 8 * e1sq + 24 * np.power(t0, 2)) * np.power(dd0, 5) / 120\n_a2 = (lof1 - lof2 + lof3) / np.cos(phi1)\n_a3 = _a2 * 180 / np.pi\n\nlatitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / np.pi\n\nif not northernHemisphere:\n latitude = -latitude\n\nlongitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3\n\nreturn (latitude, longitude)\n df['LAT'], df['LON']=utmToLatLng(31, df['X'], df['Y'], northernHemisphere=True)\n"
},
{
"answer_id": 70036872,
"author": "Roar Grønmo",
"author_id": 4475206,
"author_profile": "https://Stackoverflow.com/users/4475206",
"pm_score": 0,
"selected": false,
"text": "\nfun utmToLatLng2(\n north:Double?,\n east:Double?,\n zone:Long,\n northernHemisphere: Boolean\n):LatLng?{\n\n if((north==null)||(east == null)) return null\n\n val lngOrigin = Math.toRadians(zone*6.0 - 183.0)\n val falseNorth = if(northernHemisphere) 0.toDouble() else 10000000.toDouble()\n\n val ecc = 0.081819190842622\n val eccSq = ecc*ecc\n val ecc2Sq = eccSq / (1.0 - eccSq)\n //var ecc2 = sqrt(ecc2Sq) //not in use ?\n val e1 = (1.0 - sqrt(1.0-eccSq))/(1.0 + sqrt(1-eccSq))\n val e12 = e1*e1\n val e13 = e12*e1\n val e14 = e13*e1\n\n val semiMajor = 6378137.0\n val falseEast = 500000.0\n val scaleFactor = 0.9996\n\n //Cassini\n\n val m1 = (north - falseNorth) / scaleFactor\n val mu1 = m1 / (semiMajor * (1.0 - eccSq/4.0 - 3.0*eccSq*eccSq/64.0 - 5.0*eccSq*eccSq*eccSq/256.0))\n\n val phi1 = mu1 +\n (3.0 * e1 / 2.0 - 27.0 * e13 / 32.0) * sin(2.0 * mu1) +\n (21.0 * e12 / 16.0 - 55.0 * e14 / 32.0) * sin(4.0 * mu1) +\n (151.0 * e13 / 96.0) * sin(6.0 * mu1) +\n (1097.0 * e14 / 512.0) * sin( 8.0 * mu1)\n\n val sin2phi1 = sin(phi1) * sin(phi1)\n val rho1 = (semiMajor * (1.0-eccSq)) / (1.0 - eccSq * sin2phi1).pow(1.5)\n val nu1 = semiMajor / sqrt(1.0-eccSq*sin2phi1)\n\n //POSC\n\n val t1 = tan(phi1)*tan(phi1)\n val t12 = t1*t1\n val c1 = ecc2Sq*cos(phi1)*cos(phi1)\n val c12 = c1*c1\n val d = (east - falseEast) / (scaleFactor*nu1)\n val d2 = d*d\n val d3 = d2*d\n val d4 = d3*d\n val d5 = d4*d\n val d6 = d5*d\n\n //Compute lat & lon convert to degree\n\n var lat =\n phi1 - nu1 * tan(phi1)/rho1 *\n (d2/2.0 - (5.0 + 3.0*t1 + 10*c1 - 4.0*c12 -9.0*ecc2Sq) * d4/24.0 +\n (61.0 + 90.0*t1 +298.0*c1 + 45.0*t12 -252*ecc2Sq - 3.0*c12) * d6/720.0)\n\n lat = Math.toDegrees(lat)\n\n var lon =\n lngOrigin +\n (d - (1.0 + 2.0*t1 + c1)*d3/6.0 +\n (5.0 - 2.0*c1 + 28.0*t1 - 3.0*c12 + 8.0*ecc2Sq + 24.0*t12)*d5/120.0) / cos(phi1)\n\n lon = Math.toDegrees(lon)\n\n return LatLng(lat,lon)\n\n\n}\n\n\n\n"
},
{
"answer_id": 70309354,
"author": "Bernat",
"author_id": 5924929,
"author_profile": "https://Stackoverflow.com/users/5924929",
"pm_score": 2,
"selected": false,
"text": ">>> utm.from_latlon(51.2, 7.5)\n (395201.3103811303, 5673135.241182375, 32, 'U')\n (EASTING, NORTHING, ZONE_NUMBER, ZONE_LETTER) >>> utm.from_latlon(np.array([51.2, 49.0]), np.array([7.5, 8.4]))\n (array([395201.31038113, 456114.59586214]), array([5673135.24118237, 5427629.20426126]), 32, 'U')\n >>> utm.to_latlon(340000, 5710000, 32, 'U')\n (51.51852098408468, 6.693872395145327)\n utm.to_latlon(EASTING, NORTHING, ZONE_NUMBER, ZONE_LETTER)"
},
{
"answer_id": 71313053,
"author": "Bernardo Costa",
"author_id": 9720343,
"author_profile": "https://Stackoverflow.com/users/9720343",
"pm_score": 0,
"selected": false,
"text": "from pyproj import Transformer, CRS\ncrs = CRS.from_epsg(25833) # put your desired EPSG code here\nlatlon2utm = Transformer.from_crs(crs.geodetic_crs, crs)\nlats = [58.969, 59.911] # latitudes of two Norwegian cities\nlons = [5.732, 10.750] # longitudes of two Norwegian cities\neastings, northings = latlon2utm.transform(lats, lons)\n utm2latlon = Transformer.from_crs(crs, crs.geodetic_crs)\nlatitudes, longitudes = utm2latlon.transform(eastings, northings)\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,878 | <p>Currently I'm doing something like this in markup </p>
<pre><code><input type="text" ONKEYPRESS="InputNumeric(event);" id="txtNumber" />
</code></pre>
<p>But I want to use the jQuery bind method instead for all the obvious reasons.</p>
<pre><code>jQuery(function($)
{
$("#txtNumber").bind("keyup", InputNumeric(event));
});
</code></pre>
<p>But when I try the above I get the below error </p>
<p>"event is not defined"</p>
<p>What should this syntax look like?</p>
<p><strong>EDIT</strong></p>
<p>The actual solution I got working is shown below.</p>
<pre><code>$("#txtPriority").keypress(function (e) { InputInteger(e); });
</code></pre>
| [
{
"answer_id": 343913,
"author": "matthewk",
"author_id": 42905,
"author_profile": "https://Stackoverflow.com/users/42905",
"pm_score": 3,
"selected": true,
"text": "jQuery(function($)\n{\n $(\"#txtNumber\").bind(\"keyup\", function(event) {InputNumeric(event);});\n});\n"
},
{
"answer_id": 343923,
"author": "kamal.gs",
"author_id": 43605,
"author_profile": "https://Stackoverflow.com/users/43605",
"pm_score": 2,
"selected": false,
"text": "\n $(\"#txtNumber\").bind(\"keyup\",InputNumeric);\n"
},
{
"answer_id": 344185,
"author": "roborourke",
"author_id": 42147,
"author_profile": "https://Stackoverflow.com/users/42147",
"pm_score": 2,
"selected": false,
"text": "$(\"#txtNumber\").bind(\"keyup\",InputNumeric);\n\nfunction InputNumeric(event){\n $(event.target).dosomething(); // is the same as\n $(this).dosomething();\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701/"
] |
343,899 | <p>I have read lots of information about page caching and partial page caching in a MVC application. However, I would like to know how you would cache data.</p>
<p>In my scenario I will be using LINQ to Entities (entity framework). On the first call to GetNames (or whatever the method is) I want to grab the data from the database. I want to save the results in cache and on the second call to use the cached version if it exists.</p>
<p>Can anyone show an example of how this would work, where this should be implemented (model?) and if it would work.</p>
<p>I have seen this done in traditional ASP.NET apps , typically for very static data.</p>
| [
{
"answer_id": 343935,
"author": "terjetyl",
"author_id": 29519,
"author_profile": "https://Stackoverflow.com/users/29519",
"pm_score": 7,
"selected": true,
"text": "System.Web System.Web.Caching.Cache public string[] GetNames()\n {\n string[] names = Cache[\"names\"] as string[];\n if(names == null) //not in cache\n {\n names = DB.GetNames();\n Cache[\"names\"] = names;\n }\n return names;\n }\n"
},
{
"answer_id": 349111,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 9,
"selected": false,
"text": "using System.Runtime.Caching; \n\npublic class InMemoryCache: ICacheService\n{\n public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class\n {\n T item = MemoryCache.Default.Get(cacheKey) as T;\n if (item == null)\n {\n item = getItemCallback();\n MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));\n }\n return item;\n }\n}\n\ninterface ICacheService\n{\n T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;\n}\n cacheProvider.GetOrSet(\"cache key\", (delegate method if cache is empty));\n var products=cacheService.GetOrSet(\"catalog.products\", ()=>productRepository.GetAll())\n"
},
{
"answer_id": 353527,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": -1,
"selected": false,
"text": "[OutputCache(Duration=10)]\n"
},
{
"answer_id": 1098893,
"author": "Oli",
"author_id": 15296,
"author_profile": "https://Stackoverflow.com/users/15296",
"pm_score": 5,
"selected": false,
"text": "public string[] GetNames()\n{ \n var noms = Cache[\"names\"];\n if(noms == null) \n { \n noms = DB.GetNames();\n Cache[\"names\"] = noms; \n }\n\n return ((string[])noms);\n}\n"
},
{
"answer_id": 20801643,
"author": "Berezh",
"author_id": 721704,
"author_profile": "https://Stackoverflow.com/users/721704",
"pm_score": 1,
"selected": false,
"text": "public class Cacher<TValue>\n where TValue : class\n{\n #region Properties\n private Func<TValue> _init;\n public string Key { get; private set; }\n public TValue Value\n {\n get\n {\n var item = HttpRuntime.Cache.Get(Key) as TValue;\n if (item == null)\n {\n item = _init();\n HttpContext.Current.Cache.Insert(Key, item);\n }\n return item;\n }\n }\n #endregion\n\n #region Constructor\n public Cacher(string key, Func<TValue> init)\n {\n Key = key;\n _init = init;\n }\n #endregion\n\n #region Methods\n public void Refresh()\n {\n HttpRuntime.Cache.Remove(Key);\n }\n #endregion\n}\n public static class Caches\n{\n static Caches()\n {\n Languages = new Cacher<IEnumerable<Language>>(\"Languages\", () =>\n {\n using (var context = new WordsContext())\n {\n return context.Languages.ToList();\n }\n });\n }\n public static Cacher<IEnumerable<Language>> Languages { get; private set; }\n}\n"
},
{
"answer_id": 28397271,
"author": "smdrager",
"author_id": 356550,
"author_profile": "https://Stackoverflow.com/users/356550",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Runtime.Caching;\n\npublic class InMemoryCache : ICacheService\n{\n public TValue Get<TValue>(string cacheKey, int durationInMinutes, Func<TValue> getItemCallback) where TValue : class\n {\n TValue item = MemoryCache.Default.Get(cacheKey) as TValue;\n if (item == null)\n {\n item = getItemCallback();\n MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));\n }\n return item;\n }\n\n public TValue Get<TValue, TId>(string cacheKeyFormat, TId id, int durationInMinutes, Func<TId, TValue> getItemCallback) where TValue : class\n {\n string cacheKey = string.Format(cacheKeyFormat, id);\n TValue item = MemoryCache.Default.Get(cacheKey) as TValue;\n if (item == null)\n {\n item = getItemCallback(id);\n MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(durationInMinutes));\n }\n return item;\n }\n}\n\ninterface ICacheService\n{\n TValue Get<TValue>(string cacheKey, Func<TValue> getItemCallback) where TValue : class;\n TValue Get<TValue, TId>(string cacheKeyFormat, TId id, Func<TId, TValue> getItemCallback) where TValue : class;\n}\n Product product = cache.Get(\"product_{0}\", productId, 10, productData.getProductById);\n IEnumerable<Categories> categories = cache.Get(\"categories\", 20, categoryData.getCategories);\n"
},
{
"answer_id": 32017090,
"author": "DShook",
"author_id": 370,
"author_profile": "https://Stackoverflow.com/users/370",
"pm_score": 2,
"selected": false,
"text": "public interface ICache\n{\n T GetOrSet<T>(Func<T> getItemCallback, object dependsOn, TimeSpan duration) where T : class;\n}\n using System;\nusing System.Reflection;\nusing System.Runtime.Caching;\nusing Newtonsoft.Json;\n\npublic class InMemoryCache : ICache\n{\n private static readonly object CacheLockObject = new object();\n\n public T GetOrSet<T>(Func<T> getItemCallback, object dependsOn, TimeSpan duration) where T : class\n {\n string cacheKey = GetCacheKey(getItemCallback, dependsOn);\n T item = MemoryCache.Default.Get(cacheKey) as T;\n if (item == null)\n {\n lock (CacheLockObject)\n {\n item = getItemCallback();\n MemoryCache.Default.Add(cacheKey, item, DateTime.Now.Add(duration));\n }\n }\n return item;\n }\n\n private string GetCacheKey<T>(Func<T> itemCallback, object dependsOn) where T: class\n {\n var serializedDependants = JsonConvert.SerializeObject(dependsOn);\n var methodType = itemCallback.GetType();\n return methodType.FullName + serializedDependants;\n }\n}\n var order = _cache.GetOrSet(\n () => _session.Set<Order>().SingleOrDefault(o => o.Id == orderId)\n , new { id = orderId }\n , new TimeSpan(0, 10, 0)\n);\n"
},
{
"answer_id": 33536971,
"author": "GeraGamo",
"author_id": 3678414,
"author_profile": "https://Stackoverflow.com/users/3678414",
"pm_score": 0,
"selected": false,
"text": " public class GPDataDictionary\n{\n private Dictionary<string, object> configDictionary = new Dictionary<string, object>();\n\n /// <summary>\n /// Configuration values dictionary\n /// </summary>\n public Dictionary<string, object> ConfigDictionary\n {\n get { return configDictionary; }\n }\n\n private static GPDataDictionary instance;\n public static GPDataDictionary Instance\n {\n get\n {\n if (instance == null)\n {\n instance = new GPDataDictionary();\n }\n return instance;\n }\n }\n\n // private constructor\n private GPDataDictionary() { }\n\n} // singleton\n"
},
{
"answer_id": 34264765,
"author": "juFo",
"author_id": 187650,
"author_profile": "https://Stackoverflow.com/users/187650",
"pm_score": 5,
"selected": false,
"text": "System.Runtime.Caching using System.Runtime.Caching; public string[] GetNames()\n{ \n var noms = System.Runtime.Caching.MemoryCache.Default[\"names\"];\n if(noms == null) \n { \n noms = DB.GetNames();\n System.Runtime.Caching.MemoryCache.Default[\"names\"] = noms; \n }\n\n return ((string[])noms);\n}\n"
},
{
"answer_id": 37566623,
"author": "Chau",
"author_id": 6409178,
"author_profile": "https://Stackoverflow.com/users/6409178",
"pm_score": 2,
"selected": false,
"text": "public sealed class CacheManager\n{\n private static volatile CacheManager instance;\n private static object syncRoot = new Object();\n private ObjectCache cache = null;\n private CacheItemPolicy defaultCacheItemPolicy = null;\n\n private CacheEntryRemovedCallback callback = null;\n private bool allowCache = true;\n\n private CacheManager()\n {\n cache = MemoryCache.Default;\n callback = new CacheEntryRemovedCallback(this.CachedItemRemovedCallback);\n\n defaultCacheItemPolicy = new CacheItemPolicy();\n defaultCacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(1.0);\n defaultCacheItemPolicy.RemovedCallback = callback;\n allowCache = StringUtils.Str2Bool(ConfigurationManager.AppSettings[\"AllowCache\"]); ;\n }\n public static CacheManager Instance\n {\n get\n {\n if (instance == null)\n {\n lock (syncRoot)\n {\n if (instance == null)\n {\n instance = new CacheManager();\n }\n }\n }\n\n return instance;\n }\n }\n\n public IEnumerable GetCache(String Key)\n {\n if (Key == null || !allowCache)\n {\n return null;\n }\n\n try\n {\n String Key_ = Key;\n if (cache.Contains(Key_))\n {\n return (IEnumerable)cache.Get(Key_);\n }\n else\n {\n return null;\n }\n }\n catch (Exception)\n {\n return null;\n }\n }\n\n public void ClearCache(string key)\n {\n AddCache(key, null);\n }\n\n public bool AddCache(String Key, IEnumerable data, CacheItemPolicy cacheItemPolicy = null)\n {\n if (!allowCache) return true;\n try\n {\n if (Key == null)\n {\n return false;\n }\n\n if (cacheItemPolicy == null)\n {\n cacheItemPolicy = defaultCacheItemPolicy;\n }\n\n String Key_ = Key;\n\n lock (Key_)\n {\n return cache.Add(Key_, data, cacheItemPolicy);\n }\n }\n catch (Exception)\n {\n return false;\n }\n }\n\n private void CachedItemRemovedCallback(CacheEntryRemovedArguments arguments)\n {\n String strLog = String.Concat(\"Reason: \", arguments.RemovedReason.ToString(), \" | Key-Name: \", arguments.CacheItem.Key, \" | Value-Object: \", arguments.CacheItem.Value.ToString());\n LogManager.Instance.Info(strLog);\n }\n}\n"
},
{
"answer_id": 48964526,
"author": "Md. Akhtar Uzzaman",
"author_id": 2489273,
"author_profile": "https://Stackoverflow.com/users/2489273",
"pm_score": 0,
"selected": false,
"text": "HttpContext.Current.Cache.Insert(\"subjectlist\", subjectlist);\n"
},
{
"answer_id": 50400638,
"author": "user3776645",
"author_id": 3776645,
"author_profile": "https://Stackoverflow.com/users/3776645",
"pm_score": 3,
"selected": false,
"text": "public string GetInfo()\n{\n string name = string.Empty;\n if(System.Web.HttpContext.Current.Cache[\"KeyName\"] == null)\n {\n name = GetNameMethod();\n System.Web.HttpContext.Current.Cache.Add(\"KeyName\", name, null, DateTime.Noew.AddMinutes(5), Cache.NoSlidingExpiration, CacheitemPriority.AboveNormal, null);\n }\n else\n {\n name = System.Web.HttpContext.Current.Cache[\"KeyName\"] as string;\n }\n\n return name;\n\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42434/"
] |
343,900 | <p>I have a table with playerhandles, like this:</p>
<pre><code>1 - [N] Laka
2 - [N] James
3 - nor | Brian
4 - nor | John
5 - Player 2
6 - Spectator
7 - [N] Joe
</code></pre>
<p>From there I wanna select all players where the first n-chars match, but I don't know the pattern, only that it's the first n-chars. In the above example I wan't it to return rows 1,2,3,4 and 7.</p>
<p>Is this possible and not too expensive to do in MySQL? </p>
| [
{
"answer_id": 343982,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 3,
"selected": true,
"text": "select name from players p1 where exists (\n select 1 from players p2 where \n p2.name like CONCAT( SUBSTRING(p1.name, 1, 3), '%') \n and p1.name <> p2.name )\n"
},
{
"answer_id": 344035,
"author": "foxy",
"author_id": 30119,
"author_profile": "https://Stackoverflow.com/users/30119",
"pm_score": 3,
"selected": false,
"text": "Select *\nFROM players\nWHERE Left(name, 3) in (\n SELECT Left(name, 3)\n FROM players\n GROUP BY Left(name, 3)\n HAVING (Count(*) > 1)\n);\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33232/"
] |
343,902 | <p>I have a table in a ORACLE 10g database with a column "<code>kzCode NUMBER(1)</code>".</p>
<p>If I try to map this with Hibernate annotations in JBOSS Server WebApp like this:</p>
<pre><code>@Column(nullable=false)
private Integer kzCode;
</code></pre>
<p>I got an error: </p>
<pre><code>org.hibernate.HibernateException: Wrong column type: kzCode, expected: integer
</code></pre>
<p>I also tried </p>
<pre><code>@Column(nullable=false) private BigInteger kzCode;
</code></pre>
<p>error: </p>
<pre><code>org.hibernate.HibernateException: Wrong column type: kzCode, expected:numeric(19,2)
</code></pre>
<p>I don't really know, what Java type to take.</p>
| [
{
"answer_id": 343922,
"author": "Paul Croarkin",
"author_id": 18995,
"author_profile": "https://Stackoverflow.com/users/18995",
"pm_score": 0,
"selected": false,
"text": "@Column(nullable=false)\nprivate Boolean kzCode;\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,921 | <p>I am writing a batch script which I wish to open a file and then change the second line of it. I want to find the string "cat" and replace it with a value that I have SET i.e. %var% . I only want this to happen on the second line (or for the first 3 times). How would you go about doing this?</p>
| [
{
"answer_id": 343955,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": -1,
"selected": false,
"text": "@echo off\nsetlocal enabledelayedexpansion\n\nset file=c:\\file.txt\nset output=output.txt\nset maxlines=5000\n\nset count=0\n\nfor /F \"tokens=* usebackq\" %%G in (\"%file%\") do (\n if !count!==%maxlines% goto :eof\n\n set line=%%G\n set line=!line:*000000000000=--FOUND--!\n if \"!line:~0,9!\"==\"--FOUND--\" (\n echo %%G>>\"%output%\"\n set /a count+=1\n )\n)\n"
},
{
"answer_id": 344132,
"author": "Dennis C",
"author_id": 40214,
"author_profile": "https://Stackoverflow.com/users/40214",
"pm_score": 2,
"selected": true,
"text": "@echo OFF\nSETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION\nSET filename=%1\nset LINENO=0 \nfor /F \"delims=\" %%l in (%filename%) do (\n SET /A LINENO=!LINENO!+1\n IF \"!LINENO!\"==\"2\" ( call echo %%l ) ELSE ( echo %%l )\n)\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343921",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
343,946 | <p>I want to change the font I am using in a CEikLabel on S60 device</p>
<p>I believe I can do the following</p>
<pre><code>const CFont* aPlainFont = LatinPlain12();
aLabel->SetFont(aPlainFont);
</code></pre>
<p>where LatinPlain12 is one from this list..</p>
<pre><code>Albi12
Alp13
Alpi13
Albi13
alp17
Alb17b
albi17b
alpi17
Aco13
Aco21
Acalc21
LatinBold12
LatinBold13
LatinBold17
LatinBold19
LatinPlain12
Acb14
Acb30
Acp5
</code></pre>
<p>However, who can help me find out which ones from this list are fixed width.. Thanks :)</p>
| [
{
"answer_id": 373970,
"author": "KevinD",
"author_id": 26497,
"author_profile": "https://Stackoverflow.com/users/26497",
"pm_score": 1,
"selected": true,
"text": "const CFont* myFont; \n// Initialize your font\n// ....\nTBool isProportional = (myFont->FontSpecInTwips().iTypeface.Attributes() & TTypeFace::EProportional);\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
343,947 | <p>What communication is going on between Eclipse and my application server (JBoss) when I run the server from within Eclipse in debugging mode? How does this work?</p>
| [
{
"answer_id": 34278857,
"author": "Pritam Banerjee",
"author_id": 1475228,
"author_profile": "https://Stackoverflow.com/users/1475228",
"pm_score": 0,
"selected": false,
"text": " agentlib:libname[=options] format.\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18103/"
] |
343,954 | <p>I've got a service that has a very slow memory leak. If I analyze the .NET CLR Loading counters, I see that the <em>Current Classes Loaded</em> counter is constantly increasing and matches <em>Total Classes Loaded</em> counter at all times. This gives me the impression that the memory leak is related to resources not being freed (This is just a guess).</p>
<p>The service creates new appDomains each time it performs a task (plug-in architecture).</p>
<p>I need to figure out the class names so I can narrow down the cause of the leak. I'm not very proficient with WinDbg, but I was wondering if anyone could walk me through the steps to enumerate these <em>Loaded</em> classes.</p>
<p>I do have the source code so I can obtain the symbol files if necessary. Thanks in advance for any help!</p>
| [
{
"answer_id": 343981,
"author": "Andrew Rollings",
"author_id": 40410,
"author_profile": "https://Stackoverflow.com/users/40410",
"pm_score": 2,
"selected": false,
"text": "AppDomain AppDomain AppDomain"
},
{
"answer_id": 344265,
"author": "Page",
"author_id": 2657,
"author_profile": "https://Stackoverflow.com/users/2657",
"pm_score": 0,
"selected": false,
"text": "AppDomainSetup ads = new AppDomainSetup();\nads.ApplicationName = \"RemoteAgentLib\";\nads.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;\nads.PrivateBinPath = AppDomain.CurrentDomain.BaseDirectory;\nads.ShadowCopyDirectories = AppDomain.CurrentDomain.BaseDirectory;\nads.ShadowCopyFiles = \"true\";\n\nm_domain = AppDomain.CreateDomain(\"RemoteTaskRunner\", null, ads);\n RemoteTaskRunner taskRunner = m_domain.CreateInstanceAndUnwrap(\n Assembly.GetExecutingAssembly().FullName,\n typeof (RemoteTaskRunner).FullName) as RemoteTaskRunner;\ntaskRunner.LoadTask(taskInfo.Assembly, taskInfo.Type);\n [Serializable]\ninternal class RemoteTaskRunner : MarshalByRefObject\n{\n private ITask m_task;\n\n public RemoteTaskRunner()\n {\n }\n\n internal void LoadTask(string assembly, string type)\n {\n // This assembly should load in the secondary appDomain.\n Assembly taskAssembly = AppDomain.CurrentDomain.Load(assembly);\n m_task = taskAssembly.CreateInstance(type) as ITask;\n }\n\n internal void RunTask(string taskConfig)\n {\n // This method should run in the secondary appDomain.\n m_task.RunTask(taskConfig, m_logger);\n }\n...\n...\n taskRunner.RunTask(taskInfo.TaskConfig);\n AppDomain.Unload(m_domain);\n"
},
{
"answer_id": 344508,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 2,
"selected": false,
"text": "foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n{\n Console.WriteLine(assembly.FullName);\n}\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2657/"
] |
343,963 | <p>I need to store large amounts of data on-disk in approximately 1k blocks. I will be accessing these objects in a way that is hard to predict, but where patterns probably exist.</p>
<p>Is there an algorithm or heuristic I can use that will rearrange the objects on disk based on my access patterns to try to maximize sequential access, and thus minimize disk seek time?</p>
| [
{
"answer_id": 344108,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "memcpy()"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16050/"
] |
343,968 | <p>I have a 1GB file containing pairs of string and long.
What's the best way of reading it into a Dictionary, and how much memory would you say it requires?</p>
<p>File has 62 million rows.
I've managed to read it using 5.5GB of ram.</p>
<p>Say 22 bytes overhead per Dictionary entry, that's 1.5GB.
long is 8 bytes, that's 500MB.
Average string length is 15 chars, each char 2 bytes, that's 2GB.
Total is about 4GB, where does the extra 1.5 GB go to?</p>
<p>The initial Dictionary allocation takes 256MB.
I've noticed that each 10 million rows I read, consume about 580MB, which fits quite nicely with the above calculation, but somewhere around the 6000th line, memory usage grows from 260MB to 1.7GB, that's my missing 1.5GB, where does it go?</p>
<p>Thanks.</p>
| [
{
"answer_id": 343986,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "Dictionary<string,long> dictionary = new Dictionary<string,long>();\nusing (TextReader reader = File.OpenText(filename))\n{\n string line;\n while ((line = reader.ReadLine()) != null)\n {\n string[] bits = line.Split('=');\n // Error checking would go here\n long value = long.Parse(bits[1]);\n dictionary[bits[0]] = value;\n }\n}\n"
},
{
"answer_id": 347694,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 0,
"selected": false,
"text": "[key2][value2...][key1][value1..][key3][value3....]\n [value1..][value2...][value3....]\n [key1][value1-offset]\n[key2][value2-offset]\n[key3][value3-offset]\n key->value-offset key(N) key(N) value(N)-offset value(N+1)-offset"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19956/"
] |
343,983 | <p>The bossman wants to know how to delete a user in Sharepoint. We've got him convinced that deleting a user is too difficult because of traces of that user through the system, so now he wants to be able to change the username to all Xs or somesuch. I've poked around the DB and found a couple of UserInfo tables, one in <code>SharePoint_AdminContent_<guid></code> db and another in SharedServices. Is there a better way to change usernames? Am I on the wrong track?</p>
<p>Thanks. </p>
| [
{
"answer_id": 344039,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 2,
"selected": false,
"text": "stsadm -o migrateuser"
},
{
"answer_id": 344311,
"author": "Alex Angas",
"author_id": 6651,
"author_profile": "https://Stackoverflow.com/users/6651",
"pm_score": 2,
"selected": false,
"text": "stsadm -o deleteuser"
},
{
"answer_id": 378852,
"author": "Nathan DeWitt",
"author_id": 1753,
"author_profile": "https://Stackoverflow.com/users/1753",
"pm_score": 1,
"selected": true,
"text": "stsadm -o deleteuser"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16162/"
] |
343,989 | <p>I'm using Turbo Delphi 2006.</p>
<p>The DLL will be called from within Excel as part of a VBA/DLL combination. </p>
<p>The first part of the problem is trying to find out how to pass to the DLL a reference to the current Excel session. Most other code I've seen was that it launched a separate instance of Excel apart from the one you're in.</p>
<p>I've seen some C++ code that creates an instance of <code>IDispatch</code> and then passes something in to a method of the IDispatch object, but not knowing much C++.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 345452,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 4,
"selected": true,
"text": "IDTExtensibility2 Application OnConnection IDTExtensibility2"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
] |
343,991 | <p>I use VS6 and ATL with CServiceModule to implement a custom windows service. In case of a fatal error service should shut itself down. Since CServiceModule is available via _Module variable in all files I thought of something like this to cause CServiceModule::Run to stop pumping messages and shut itself down</p>
<pre><code>PostThreadMessage(_Module.dwThreadID, WM_QUIT, 0, 0);
</code></pre>
<p>Is this correct or you have better idea ?</p>
| [
{
"answer_id": 345452,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 4,
"selected": true,
"text": "IDTExtensibility2 Application OnConnection IDTExtensibility2"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/501/"
] |
343,995 | <p>I'm rewriting a PHP web site in ASP.NET MVC. I'd like to maintain the same user base but the passwords are hashed using the PHP crypt() function. I need the same function in .Net so that I can hash a password on login and check it against the hashed password in the user database.</p>
<p>crypt in this case is using the CRYPT_MD5 implementation - the hashes all start with $1$</p>
<p>I've tried Phalanger but it doesn't have an MD5 implementation of the crypt function.</p>
<p>Does anyone know of one in .Net? The C# example of crypt() on CodeProject uses DES, not MD5.</p>
<p>I've tried the following code in C#, with different permutations of salt+password, password+salt and salt with and without $1$ prefix and $ suffix. None gives same result as PHP:</p>
<pre><code>static void Main(string[] args)
{
const string salt = "somesalt";
const string password = "fubar";
const string plaintextString = password + salt;
byte[] plaintext = GetBytes(plaintextString);
var md5 = MD5.Create("MD5");
byte[] hash = md5.ComputeHash(plaintext);
string s = System.Convert.ToBase64String(hash);
Console.WriteLine("Hash of " + password + " is " + s);
Console.ReadKey();
}
private static byte[] GetBytes(string s)
{
var result = new byte[s.Length];
for (int i = 0; i < s.Length; i++)
result[i] = (byte)s[i];
return result;
}
</code></pre>
| [
{
"answer_id": 344023,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 2,
"selected": false,
"text": "System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, format) $1$"
},
{
"answer_id": 344133,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 1,
"selected": false,
"text": "CRYPT_MD5 $1$"
},
{
"answer_id": 3332130,
"author": "bstoney",
"author_id": 70716,
"author_profile": "https://Stackoverflow.com/users/70716",
"pm_score": 0,
"selected": false,
"text": "[DllImport( \"php5ts.dll\", EntryPoint = \"crypt\", CharSet = CharSet.Ansi )]\nprivate static extern string crypt( string str, string salt );\n"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/343995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43649/"
] |
344,012 | <p><strong>UPDATE:</strong>
Obviously, you'd want to do this using templates or a base class rather than macros. Unfortunately for various reasons I can't use templates, or a base class.</p>
<hr/>
<p>At the moment I am using a macro to define a bunch of fields and methods on various classes, like this:</p>
<pre><code>class Example
{
// Use FIELDS_AND_METHODS macro to define some methods and fields
FIELDS_AND_METHODS(Example)
};
</code></pre>
<p><code>FIELDS_AND_METHODS</code> is a multi-line macro that uses stringizing and token-pasting operators.</p>
<p>I would like to replace this with the following kind of thing</p>
<pre><code>class Example
{
// Include FieldsNMethods.h, with TYPE_NAME preprocessor symbol
// defined, to achieve the same result as the macro.
#define TYPE_NAME Example
#include "FieldsNMethods.h"
};
</code></pre>
<p>Here I #define the name of the class (previously the parameter to the macro), and the <code>FieldsNMethods.h</code> file contains the content of the original macro. However, because I'm #including I can step into the code at runtime, when debugging.</p>
<p>However I am having trouble 'stringizing' and 'token pasting' the <code>TYPE_NAME</code> preprocessor symbol in the <code>FieldsNMethods.h</code> file.</p>
<p>For example, I want to define the destructor of the class in <code>FieldsNMethods.h</code>, so this would need to use the value of <code>TYPE_NAME</code> as below:</p>
<pre><code>~TYPE_NAME()
{
//...
}
</code></pre>
<p>But with <code>TYPE_NAME</code> replaced by its value.</p>
<p>Is what I'm attempting possible? I can't use the stringizing and token-pasting operators directly, because I'm not in a macro definition.</p>
| [
{
"answer_id": 344029,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 4,
"selected": true,
"text": "class Example<class T>\n{\n ...class definition...\n};\n #define PASTE_NAME(x, y) PASTE_TOKENS(x, y)\n#define PASTE_TOKENS(x, y) x ## y\n\n#define TYPE_NAME Example\nint PASTE_NAME(TYPE_NAME, _function_suffix)(void) { ... }\n class Example\n{\n // Use FIELDS_AND_METHODS macro to define some methods and fields\n FIELDS_AND_METHODS(Example)\n};\n class Example\n{\n // Include FieldsNMethods.h, with TYPE_NAME preprocessor symbol\n // defined, to achieve the same result as the macro.\n #define TYPE_NAME Example\n #include \"FieldsNMethods.h\"\n};\n FIELDS_AND_METHODS(type) #define FIELDS_AND_METHODS(type) \\\n type *next; \\\n type() : next(0) { } \\\n type * type ## _next() { return next; }\n #ifndef TYPE_NAME\n#error TYPE_NAME not defined\n#endif\n#define FNM_PASTE_NAME(x, y) FNM_PASTE_TOKENS(x, y)\n#define FNM_PASTE_TOKENS(x, y) x ## y\n\nTYPE_NAME *next;\nTYPE_NAME() : next(0) { }\nTYPE_NAME * FNM_PASTE_NAME(TYPE_NAME, _next)() { return next; }\n\n#undef FNM_PASTE_NAME\n#undef FNM_PASTE_TOKENS\n FNM_ #define TYPE_NAME Example\nclass TYPE_NAME\n{\n // Include FieldsNMethods.h, with TYPE_NAME preprocessor symbol\n // defined, to achieve the same result as the macro.\n #include \"FieldsNMethods.h\"\n};\n"
},
{
"answer_id": 344106,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 2,
"selected": false,
"text": "#define MAKE_STR_X( _v ) # _v\n#define MAKE_STR( _v ) MAKE_STR_X( _v )\n\nchar *method() { return MAKE_STR( TYPE_NAME ); }\n"
},
{
"answer_id": 344224,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "#define STRINGIZE(x) STRINGIZE2(x)\n#define STRINGIZE2(x) #x\n\n#define TOKENPASTE(x, y) TOKENPASTE2(x, y)\n#define TOKENPASTE2(x, y) x ## y\n #define A B, #define B C, #define C D, STRINGIZE(A)"
}
] | 2008/12/05 | [
"https://Stackoverflow.com/questions/344012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25457/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.