qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
3,856
<p>I wrote a component that displays a filename, a thumbnail and has a button to load/play the file. The component is databound to a repeater. How can I make it so that the button event fires to the main application and tells it which file to play?</p>
[ { "answer_id": 3852, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "<p>Can you do it as a subselect, something like</p>\n\n<pre><code>SELECT * FROM (\n SELECT A,B,C FROM table WHERE field...
2008/08/06
[ "https://Stackoverflow.com/questions/3856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
I wrote a component that displays a filename, a thumbnail and has a button to load/play the file. The component is databound to a repeater. How can I make it so that the button event fires to the main application and tells it which file to play?
Maybe you should try including a fourth column, stating the table it came from, and then order and group by it: ``` SELECT A,B,C, "query 1" as origin FROM table WHERE field LIKE 'query%' UNION SELECT A,B,C, "query 2" as origin FROM table WHERE field LIKE '%query' UNION SELECT A,B,C, "query 3" as origin FROM table WHERE field LIKE '%query%' GROUP BY origin, B ORDER BY origin, B ASC LIMIT 5 ```
3,894
<p>Given the constraint of only using T-Sql in Sql Server 2005, is there a better way to remove the decimal point from a money datatype than a conversion to a varchar (here implicitly) and then a replace of the decimal point?</p> <p>Here is what I have currently.</p> <pre><code>SELECT REPLACE(1.23, '.', ''), REPLACE(19.99, '.', '') </code></pre> <p>Which returns the desired 123 and 1999, but I was wondering if there was a better way. Any thoughts?</p>
[ { "answer_id": 3897, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": true, "text": "<p>Multiply by 100 and then convert to an int.</p>\n" }, { "answer_id": 3899, "author": "Curt Hagenlocher", "a...
2008/08/06
[ "https://Stackoverflow.com/questions/3894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76/" ]
Given the constraint of only using T-Sql in Sql Server 2005, is there a better way to remove the decimal point from a money datatype than a conversion to a varchar (here implicitly) and then a replace of the decimal point? Here is what I have currently. ``` SELECT REPLACE(1.23, '.', ''), REPLACE(19.99, '.', '') ``` Which returns the desired 123 and 1999, but I was wondering if there was a better way. Any thoughts?
Multiply by 100 and then convert to an int.
3,903
<p>Since the WMI class Win32_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system.</p> <pre><code>private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } } </code></pre> <p>It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method?</p> <p><strong>Edit</strong>: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.</p>
[ { "answer_id": 3909, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 1, "selected": false, "text": "<p>Looking into the registry is perfectly valid, so long as you can be sure that the user of the application will always have...
2008/08/06
[ "https://Stackoverflow.com/questions/3903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/560/" ]
Since the WMI class Win32\_OperatingSystem only includes OSArchitecture in Windows Vista, I quickly wrote up a method using the registry to try and determine whether or not the current system is a 32 or 64bit system. ``` private Boolean is64BitOperatingSystem() { RegistryKey localEnvironment = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment"); String processorArchitecture = (String) localEnvironment.GetValue("PROCESSOR_ARCHITECTURE"); if (processorArchitecture.Equals("x86")) { return false; } else { return true; } } ``` It's worked out pretty well for us so far, but I'm not sure how much I like looking through the registry. Is this a pretty standard practice or is there a better method? **Edit**: Wow, that code looks a lot prettier in the preview. I'll consider linking to a pastebin or something, next time.
Take a look at Raymond Chens solution: [How to detect programmatically whether you are running on 64-bit Windows](http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx) and here's the PINVOKE for .NET: [IsWow64Process (kernel32)](http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y) **Update:** I'd take issue with checking for 'x86'. Who's to say what intel's or AMD's next 32 bit processor may be designated as. The probability is low but it is a risk. You should ask the OS to determine this via the correct API's, not by querying what could be a OS version/platform specific value that may be considered opaque to the outside world. Ask yourself the questions, 1 - is the registry entry concerned properly documented by MS, 2 - If it is do they provide a definitive list of possible values that is guaranteed to permit you as a developer to make the informed decision between whether you are running 32 bit or 64 bit. If the answer is no, then call the API's, yeah it's a but more long winded but it is documented and definitive.
3,976
<p>I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . </p> <p>When i do this everything seems to be hunky-dory:</p> <pre><code>stty -f /dev/cu.usbserial speed 9600 baud; lflags: -icanon -isig -iexten -echo iflags: -icrnl -ixon -ixany -imaxbel -brkint oflags: -opost -onlcr -oxtabs cflags: cs8 -parenb </code></pre> <p>Everything also works when I use the <a href="http://www.versiontracker.com/dyn/moreinfo/macosx/24024" rel="noreferrer">serial port tool</a> to talk to it.</p> <p>If I run this piece of code while the above mentioned serial port tool, everthing also works. But as soon as I disconnect the tool the connection gets lost. </p> <pre><code>#!/usr/bin/python import serial ser = serial.Serial('/dev/cu.usbserial', 9600, timeout=10) ser.write("&lt;ID01&gt;&lt;PA&gt; \r\n") read_chars = ser.read(20) print read_chars ser.close() </code></pre> <p>So the question is, what magicks do I need to perform to start talking to the serial port without the serial port tool? Is that a permissions problem? Also, what's the difference between /dev/cu.usbserial and /dev/tty.usbserial?</p> <hr> <p>Nope, no serial numbers. The thing is, the problem persists even with sudo-running the python script, and the only thing that makes it go through if I open the connection in the gui tool that I mentioned.</p>
[ { "answer_id": 4128, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<p>have you tried watching the traffic between the GUI and the serial port to see if there is some kind of special command be...
2008/08/06
[ "https://Stackoverflow.com/questions/3976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
I have a Prolite LED sign that I like to set up to show scrolling search queries from a apache logs and other fun statistics. The problem is, my G5 does not have a serial port, so I have to use a usb to serial dongle. It shows up as /dev/cu.usbserial and /dev/tty.usbserial . When i do this everything seems to be hunky-dory: ``` stty -f /dev/cu.usbserial speed 9600 baud; lflags: -icanon -isig -iexten -echo iflags: -icrnl -ixon -ixany -imaxbel -brkint oflags: -opost -onlcr -oxtabs cflags: cs8 -parenb ``` Everything also works when I use the [serial port tool](http://www.versiontracker.com/dyn/moreinfo/macosx/24024) to talk to it. If I run this piece of code while the above mentioned serial port tool, everthing also works. But as soon as I disconnect the tool the connection gets lost. ``` #!/usr/bin/python import serial ser = serial.Serial('/dev/cu.usbserial', 9600, timeout=10) ser.write("<ID01><PA> \r\n") read_chars = ser.read(20) print read_chars ser.close() ``` So the question is, what magicks do I need to perform to start talking to the serial port without the serial port tool? Is that a permissions problem? Also, what's the difference between /dev/cu.usbserial and /dev/tty.usbserial? --- Nope, no serial numbers. The thing is, the problem persists even with sudo-running the python script, and the only thing that makes it go through if I open the connection in the gui tool that I mentioned.
`/dev/cu.xxxxx` is the "callout" device, it's what you use when you establish a connection to the serial device and start talking to it. `/dev/tty.xxxxx` is the "dialin" device, used for monitoring a port for incoming calls for e.g. a fax listener.
4,046
<p>I'm trying to convince my providers to use ANT instead of Rational Application Development so anyone can recompile, recheck, redeploy the solution anyplace, anytime, anyhow. :P</p> <p>I started a build.xml for a project that generates a JAR file but stopped there and I need real examples to compare notes. My good friends! I don't have anyone close to chat about this! </p> <p>This is my <a href="http://pastebin.ca/1094382" rel="noreferrer">build.xml</a> so far. </p> <p><i>(*) I edited my question based in the <a href="https://stackoverflow.com/questions/4046/can-someone-give-me-a-working-example-of-a-buildxml-for-an-ear-that-deploys-in-#4298">suggestion</a> of to use pastebin.ca</i></p>
[ { "answer_id": 4902, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 5, "selected": true, "text": "<p>My Environment: Fedora 8; WAS 6.1 (as installed with Rational Application Developer 7)</p>\n\n<p>The documentation is very po...
2008/08/06
[ "https://Stackoverflow.com/questions/4046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/527/" ]
I'm trying to convince my providers to use ANT instead of Rational Application Development so anyone can recompile, recheck, redeploy the solution anyplace, anytime, anyhow. :P I started a build.xml for a project that generates a JAR file but stopped there and I need real examples to compare notes. My good friends! I don't have anyone close to chat about this! This is my [build.xml](http://pastebin.ca/1094382) so far. *(\*) I edited my question based in the [suggestion](https://stackoverflow.com/questions/4046/can-someone-give-me-a-working-example-of-a-buildxml-for-an-ear-that-deploys-in-#4298) of to use pastebin.ca*
My Environment: Fedora 8; WAS 6.1 (as installed with Rational Application Developer 7) The documentation is very poor in this area and there is a dearth of practical examples. **Using the WebSphere Application Server (WAS) Ant tasks** To run as described here, you need to run them from your server **profile** bin directory using the **ws\_ant.sh** or **ws\_ant.bat** commands. ``` <?xml version="1.0"?> <project name="project" default="wasListApps" basedir="."> <description> Script for listing installed apps. Example run from: /opt/IBM/SDP70/runtimes/base_v61/profiles/AppSrv01/bin </description> <property name="was_home" value="/opt/IBM/SDP70/runtimes/base_v61/"> </property> <path id="was.runtime"> <fileset dir="${was_home}/lib"> <include name="**/*.jar" /> </fileset> <fileset dir="${was_home}/plugins"> <include name="**/*.jar" /> </fileset> </path> <property name="was_cp" value="${toString:was.runtime}"></property> <property environment="env"></property> <target name="wasListApps"> <taskdef name="wsListApp" classname="com.ibm.websphere.ant.tasks.ListApplications" classpath="${was_cp}"> </taskdef> <wsListApp wasHome="${was_home}" /> </target> </project> ``` Command: ``` ./ws_ant.sh -buildfile ~/IBM/rationalsdp7.0/workspace/mywebappDeploy/applist.xml ``` **A Deployment Script** ``` <?xml version="1.0"?> <project name="project" default="default" basedir="."> <description> Build/Deploy an EAR to WebSphere Application Server 6.1 </description> <property name="was_home" value="/opt/IBM/SDP70/runtimes/base_v61/" /> <path id="was.runtime"> <fileset dir="${was_home}/lib"> <include name="**/*.jar" /> </fileset> <fileset dir="${was_home}/plugins"> <include name="**/*.jar" /> </fileset> </path> <property name="was_cp" value="${toString:was.runtime}" /> <property environment="env" /> <property name="ear" value="${env.HOME}/IBM/rationalsdp7.0/workspace/mywebappDeploy/mywebappEAR.ear" /> <target name="default" depends="deployEar"> </target> <target name="generateWar" depends="compileWarClasses"> <jar destfile="mywebapp.war"> <fileset dir="../mywebapp/WebContent"> </fileset> </jar> </target> <target name="compileWarClasses"> <echo message="was_cp=${was_cp}" /> <javac srcdir="../mywebapp/src" destdir="../mywebapp/WebContent/WEB-INF/classes" classpath="${was_cp}"> </javac> </target> <target name="generateEar" depends="generateWar"> <mkdir dir="./earbin/META-INF"/> <move file="mywebapp.war" todir="./earbin" /> <copy file="../mywebappEAR/META-INF/application.xml" todir="./earbin/META-INF" /> <jar destfile="${ear}"> <fileset dir="./earbin" /> </jar> </target> <!-- http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.ibm.websphere.javadoc.doc/public_html/api/com/ibm/websphere/ant/tasks/package-summary.html --> <target name="deployEar" depends="generateEar"> <taskdef name="wsInstallApp" classname="com.ibm.websphere.ant.tasks.InstallApplication" classpath="${was_cp}"/> <wsInstallApp ear="${ear}" failonerror="true" debug="true" taskname="" washome="${was_home}" /> </target> </project> ``` Notes: * You can only run this once! You cannot install if the app name is in use - see other tasks like **wsUninstallApp** * It probably won't start the app either * You need to run this on the server and the script is quite fragile **Alternatives** I would probably use Java Management Extensions (JMX). You could write a file-upload servlet that accepts an EAR and uses the deployment MBeans to deploy the EAR on the server. You would just POST the file over HTTP. This would avoid any WAS API dependencies on your dev/build machine and could be independent of any one project.
4,051
<p>In <code>C</code> can I <strong>pass a multidimensional array</strong> to a function <strong>as a single argument</strong> when I don't know what the dimensions of the array are going to be?</p> <p>Besides, my multidimensional array may contain types other than strings.</p>
[ { "answer_id": 4192, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 6, "selected": true, "text": "<p>You can do this with any data type. Simply make it a pointer-to-pointer:</p>\n\n<pre><code>typedef struct {\n int myint;\n ...
2008/08/06
[ "https://Stackoverflow.com/questions/4051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
In `C` can I **pass a multidimensional array** to a function **as a single argument** when I don't know what the dimensions of the array are going to be? Besides, my multidimensional array may contain types other than strings.
You can do this with any data type. Simply make it a pointer-to-pointer: ``` typedef struct { int myint; char* mystring; } data; data** array; ``` But don't forget you still have to malloc the variable, and it does get a bit complex: ``` //initialize int x,y,w,h; w = 10; //width of array h = 20; //height of array //malloc the 'y' dimension array = malloc(sizeof(data*) * h); //iterate over 'y' dimension for(y=0;y<h;y++){ //malloc the 'x' dimension array[y] = malloc(sizeof(data) * w); //iterate over the 'x' dimension for(x=0;x<w;x++){ //malloc the string in the data structure array[y][x].mystring = malloc(50); //50 chars //initialize array[y][x].myint = 6; strcpy(array[y][x].mystring, "w00t"); } } ``` The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should [check the return of malloc()](http://www.google.com/search?q=check+malloc+return).) Now let's say you want to pass this to a function. You can still use the double pointer, because you probably want to do manipulations on the data structure, not the pointer to pointers of data structures: ``` int whatsMyInt(data** arrayPtr, int x, int y){ return arrayPtr[y][x].myint; } ``` Call this function with: ``` printf("My int is %d.\n", whatsMyInt(array, 2, 4)); ``` Output: ``` My int is 6. ```
4,052
<p>I am trying to enable Full-text indexing in SQL Server 2005 Express. I am running this on my laptop with Vista Ultimate.</p> <p>I understand that the standard version of SQL Server Express does not have full-text indexing. I have already downloaded and installed "Microsoft SQL Server 2005 Express Edition with Advanced Services Service Pack 2" (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=5B5528B9-13E1-4DB9-A3FC-82116D598C3D&amp;displaylang=en" rel="noreferrer">download</a>).</p> <p>I have also ensured that both the "SQL Server (instance)" and "SQL Server FullText Search (instance)" services are running on the same account which is "Network Service".</p> <p>I have also selected the option to "Use full-text indexing" in the Database Properties > Files area.</p> <p>I can run the sql query "SELECT fulltextserviceproperty('IsFulltextInstalled');" and return 1.</p> <p>The problem I am having is that when I have my table open in design view and select "Manage FullText Index"; the full-text index window displays the message... </p> <blockquote> <p>"Creation of the full-text index is not available. Check that you have the correct permissions or that full-text catalogs are defined."</p> </blockquote> <p>Any ideas on what to check or where to go next?</p>
[ { "answer_id": 4139, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 5, "selected": true, "text": "<pre><code>sp_fulltext_database 'enable'\n\nCREATE FULLTEXT CATALOG [myFullText]\nWITH ACCENT_SENSITIVITY = ON\n\nCREATE FULLTEXT I...
2008/08/06
[ "https://Stackoverflow.com/questions/4052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ]
I am trying to enable Full-text indexing in SQL Server 2005 Express. I am running this on my laptop with Vista Ultimate. I understand that the standard version of SQL Server Express does not have full-text indexing. I have already downloaded and installed "Microsoft SQL Server 2005 Express Edition with Advanced Services Service Pack 2" ([download](http://www.microsoft.com/downloads/details.aspx?FamilyID=5B5528B9-13E1-4DB9-A3FC-82116D598C3D&displaylang=en)). I have also ensured that both the "SQL Server (instance)" and "SQL Server FullText Search (instance)" services are running on the same account which is "Network Service". I have also selected the option to "Use full-text indexing" in the Database Properties > Files area. I can run the sql query "SELECT fulltextserviceproperty('IsFulltextInstalled');" and return 1. The problem I am having is that when I have my table open in design view and select "Manage FullText Index"; the full-text index window displays the message... > > "Creation of the full-text index is not available. Check that you have the correct permissions or that full-text catalogs are defined." > > > Any ideas on what to check or where to go next?
``` sp_fulltext_database 'enable' CREATE FULLTEXT CATALOG [myFullText] WITH ACCENT_SENSITIVITY = ON CREATE FULLTEXT INDEX ON [dbo].[tblName] KEY INDEX [PK_something] ON [myFullText] WITH CHANGE_TRACKING AUTO ALTER FULLTEXT INDEX ON [dbo].[otherTable] ADD ([Text]) ALTER FULLTEXT INDEX ON [dbo].[teyOtherTable] ENABLE ```
4,072
<p>I just did a merge using something like:</p> <pre><code>svn merge -r 67212:67213 https://my.svn.repository/trunk . </code></pre> <p>I only had 2 files, one of which is a simple <code>ChangeLog</code>. Rather than just merging my <code>ChangeLog</code> changes, it actually pulled mine plus some previous ones that were not in the destination <code>ChangeLog</code>. I noticed there was a conflict when I executed --dry-run, so I updated <code>ChangeLog</code>, and there was still a conflict (and I saw the conflict when I did the actual merge).</p> <p>I then later diffed on the file I was merging from:</p> <pre><code>svn diff -r 67212:67213 ChangeLog </code></pre> <p>And I see just the changes I had made, so I know that extra changes didn't get in there somehow. </p> <p>This makes me worried that merge is not actually just taking what I changed, which is what I would have expected. Can anybody explain what happened?</p> <p>UPDATE: In response to NilObject:</p> <p>So, I have 2 files changed, only ChangeLog is relevant, the other merged fine. When I go to my regular trunk checkout, I do the diff command above and see:</p> <pre><code>Index: ChangeLog =================================================================== --- ChangeLog (revision 67212) +++ ChangeLog (revision 67213) @@ -1,3 +1,7 @@ +2008-08-06 Mike Stone &lt;myemail&gt; + + * changed_file: Details. + 2008-08-06 Someone Else &lt;their_email&gt; * theirChanges: Details. </code></pre> <p>After my merge of the previous changes, the diff of ChangeLog looks like this:</p> <pre><code>Index: ChangeLog =================================================================== --- ChangeLog (revision 67215) +++ ChangeLog (working copy) @@ -1,3 +1,14 @@ +&lt;&lt;&lt;&lt;&lt;&lt;&lt; .working +======= +2008-08-06 Mike Stone &lt;myemail&gt; + + * changed_file: Details. + +2008-08-06 Someone Else &lt;their_email&gt; + + * theirChanges: Details. + +&gt;&gt;&gt;&gt;&gt;&gt;&gt; .merge-right.r67213 2008-08-05 Someone Else2 &lt;their2_email&gt; * olderChange: Details. </code></pre> <p>Note that the entry that was incorrectly pulled in was not in the file I am merging it to, but yet it was not one of my changes and shouldn't have been merged anyways. It was easy to fix (remove the extra lines that weren't part of my changes), but it still makes me worry about merging automatically in <code>SVN</code>.</p>
[ { "answer_id": 4104, "author": "Ecton", "author_id": 457, "author_profile": "https://Stackoverflow.com/users/457", "pm_score": 0, "selected": false, "text": "<p>There's not really enough information to go on here.</p>\n\n<pre><code>svn merge -r 67212:67213 https://my.svn.repository/trunk...
2008/08/06
[ "https://Stackoverflow.com/questions/4072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I just did a merge using something like: ``` svn merge -r 67212:67213 https://my.svn.repository/trunk . ``` I only had 2 files, one of which is a simple `ChangeLog`. Rather than just merging my `ChangeLog` changes, it actually pulled mine plus some previous ones that were not in the destination `ChangeLog`. I noticed there was a conflict when I executed --dry-run, so I updated `ChangeLog`, and there was still a conflict (and I saw the conflict when I did the actual merge). I then later diffed on the file I was merging from: ``` svn diff -r 67212:67213 ChangeLog ``` And I see just the changes I had made, so I know that extra changes didn't get in there somehow. This makes me worried that merge is not actually just taking what I changed, which is what I would have expected. Can anybody explain what happened? UPDATE: In response to NilObject: So, I have 2 files changed, only ChangeLog is relevant, the other merged fine. When I go to my regular trunk checkout, I do the diff command above and see: ``` Index: ChangeLog =================================================================== --- ChangeLog (revision 67212) +++ ChangeLog (revision 67213) @@ -1,3 +1,7 @@ +2008-08-06 Mike Stone <myemail> + + * changed_file: Details. + 2008-08-06 Someone Else <their_email> * theirChanges: Details. ``` After my merge of the previous changes, the diff of ChangeLog looks like this: ``` Index: ChangeLog =================================================================== --- ChangeLog (revision 67215) +++ ChangeLog (working copy) @@ -1,3 +1,14 @@ +<<<<<<< .working +======= +2008-08-06 Mike Stone <myemail> + + * changed_file: Details. + +2008-08-06 Someone Else <their_email> + + * theirChanges: Details. + +>>>>>>> .merge-right.r67213 2008-08-05 Someone Else2 <their2_email> * olderChange: Details. ``` Note that the entry that was incorrectly pulled in was not in the file I am merging it to, but yet it was not one of my changes and shouldn't have been merged anyways. It was easy to fix (remove the extra lines that weren't part of my changes), but it still makes me worry about merging automatically in `SVN`.
This only happens with conflicts - basically svn tried to merge the change in, but (roughly speaking) saw the change as: Add ``` 2008-08-06 Mike Stone <myemail> * changed_file: Details. ``` before ``` 2008-08-06 Someone Else <their_email> ``` And it couldn't find the Someone Else line while doing the merge, so chucked that bit in for context when putting in the conflict. If it was a non-conflicting merge only the changes you expected would have been applied.
4,080
<p>What code analysis tools do you use on your Java projects?</p> <p>I am interested in all kinds</p> <ul> <li>static code analysis tools (FindBugs, PMD, and any others)</li> <li>code coverage tools (Cobertura, Emma, and any others)</li> <li>any other instrumentation-based tools </li> <li>anything else, if I'm missing something</li> </ul> <p>If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools. </p> <p>If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting.</p>
[ { "answer_id": 4166, "author": "ggasp", "author_id": 527, "author_profile": "https://Stackoverflow.com/users/527", "pm_score": 1, "selected": false, "text": "<p>We use FindBugs and JDepend integrated with Ant. We use JUnit but we're not using any coverage tool. </p>\n\n<p>I'm not using i...
2008/08/06
[ "https://Stackoverflow.com/questions/4080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/235/" ]
What code analysis tools do you use on your Java projects? I am interested in all kinds * static code analysis tools (FindBugs, PMD, and any others) * code coverage tools (Cobertura, Emma, and any others) * any other instrumentation-based tools * anything else, if I'm missing something If applicable, also state what build tools you use and how well these tools integrate with both your IDEs and build tools. If a tool is only available a specific way (as an IDE plugin, or, say, a build tool plugin) that information is also worth noting.
For static analysis tools I often use CPD, [PMD](http://pmd.sourceforge.net), [FindBugs](http://findbugs.sourceforge.net), and [Checkstyle](http://checkstyle.sourceforge.net). CPD is the PMD "Copy/Paste Detector" tool. I was using PMD for a little while before I noticed the ["Finding Duplicated Code" link](http://pmd.sourceforge.net/cpd.html) on the [PMD web page](http://pmd.sourceforge.net). I'd like to point out that these tools can sometimes be extended beyond their "out-of-the-box" set of rules. And not just because they're open source so that you can rewrite them. Some of these tools come with applications or "hooks" that allow them to be extended. For example, PMD comes with the ["designer" tool](http://pmd.sourceforge.net/howtowritearule.html) that allows you to create new rules. Also, Checkstyle has the [DescendantToken](http://checkstyle.sourceforge.net/config_misc.html#DescendantToken) check that has properties that allow for substantial customization. I integrate these tools with [an Ant-based build](http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/scm/common.xml?view=markup). You can follow the link to see my commented configuration. In addition to the simple integration into the build, I find it helpful to configure the tools to be somewhat "integrated" in a couple of other ways. Namely, report generation and warning suppression uniformity. I'd like to add these aspects to this discussion (which should probably have the "static-analysis" tag also): how are folks configuring these tools to create a "unified" solution? (I've asked this question separately [here](https://stackoverflow.com/questions/79918/configuring-static-analysis-tools-for-uniformity)) First, for warning reports, I transform the output so that each warning has the simple format: ``` /absolute-path/filename:line-number:column-number: warning(tool-name): message ``` This is often called the "Emacs format," but even if you aren't using Emacs, it's a reasonable format for homogenizing reports. For example: ``` /project/src/com/example/Foo.java:425:9: warning(Checkstyle):Missing a Javadoc comment. ``` My warning format transformations are done by my Ant script with Ant [filterchains](http://ant.apache.org/manual/Types/filterchain.html). The second "integration" that I do is for warning suppression. By default, each tool supports comments or an annotation (or both) that you can place in your code to silence a warning that you want to ignore. But these various warning suppression requests do not have a consistent look which seems somewhat silly. When you're suppressing a warning, you're suppressing a warning, so why not always write "`SuppressWarning`?" For example, PMD's default configuration suppresses warning generation on lines of code with the string "`NOPMD`" in a comment. Also, PMD supports Java's `@SuppressWarnings` annotation. I configure PMD to use comments containing "`SuppressWarning(PMD.`" instead of `NOPMD` so that PMD suppressions look alike. I fill in the particular rule that is violated when using the comment style suppression: ``` // SuppressWarnings(PMD.PreserveStackTrace) justification: (false positive) exceptions are chained ``` Only the "`SuppressWarnings(PMD.`" part is significant for a comment, but it is consistent with PMD's support for the `@SuppressWarning` annotation which does recognize individual rule violations by name: ``` @SuppressWarnings("PMD.CompareObjectsWithEquals") // justification: identity comparision intended ``` Similarly, Checkstyle suppresses warning generation between pairs of comments (no annotation support is provided). By default, comments to turn Checkstyle off and on contain the strings `CHECKSTYLE:OFF` and `CHECKSTYLE:ON`, respectively. Changing this configuration (with Checkstyle's "SuppressionCommentFilter") to use the strings "`BEGIN SuppressWarnings(CheckStyle.`" and "`END SuppressWarnings(CheckStyle.`" makes the controls look more like PMD: ``` // BEGIN SuppressWarnings(Checkstyle.HiddenField) justification: "Effective Java," 2nd ed., Bloch, Item 2 // END SuppressWarnings(Checkstyle.HiddenField) ``` With Checkstyle comments, the particular check violation (`HiddenField`) *is* significant because each check has its own "`BEGIN/END`" comment pair. FindBugs also supports warning generation suppression with a `@SuppressWarnings` annotation, so no further configuration is required to achieve some level of uniformity with other tools. Unfortunately, Findbugs has to support a custom `@SuppressWarnings` annotation because the built-in Java `@SuppressWarnings` annotation has a `SOURCE` retention policy which is not strong enough to retain the annotation in the class file where FindBugs needs it. I fully qualify FindBugs warnings suppressions to avoid clashing with Java's `@SuppressWarnings` annotation: ``` @edu.umd.cs.findbugs.annotations.SuppressWarnings("UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") ``` These techniques makes things look reasonably consistent across tools. Note that having each warning suppression contain the string "`SuppressWarnings`" makes it easy to run a simple search to find all instances for all tools over an entire code base.
4,138
<p>What is the best SVN Ignore Pattern should TortoiseSVN have for a VB.NET solution?</p>
[ { "answer_id": 4140, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 5, "selected": true, "text": "<p>this is what I use for C# w/resharper, should work just the same with vb.net:</p>\n\n<pre><code>build deploy */bin */bin/* ...
2008/08/06
[ "https://Stackoverflow.com/questions/4138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
What is the best SVN Ignore Pattern should TortoiseSVN have for a VB.NET solution?
this is what I use for C# w/resharper, should work just the same with vb.net: ``` build deploy */bin */bin/* obj *.dll *.pdb *.user *.suo _ReSharper* *.resharper* bin ```
4,149
<p>I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.</p> <p>I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then? </p> <p>My intuition is currently pushing me towards BufferedStreams. Is this the way to go?</p>
[ { "answer_id": 4188, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 1, "selected": false, "text": "<p>Not Java per-se, but you may run into issues where you have written something to a file, but it hasn't been actuall...
2008/08/06
[ "https://Stackoverflow.com/questions/4149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/488/" ]
I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time. I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then? My intuition is currently pushing me towards BufferedStreams. Is this the way to go?
Could not get the example to work using `FileChannel.read(ByteBuffer)` because it isn't a blocking read. Did however get the code below to work: ``` boolean running = true; BufferedInputStream reader = new BufferedInputStream(new FileInputStream( "out.txt" ) ); public void run() { while( running ) { if( reader.available() > 0 ) { System.out.print( (char)reader.read() ); } else { try { sleep( 500 ); } catch( InterruptedException ex ) { running = false; } } } } ``` Of course the same thing would work as a timer instead of a thread, but I leave that up to the programmer. I'm still looking for a better way, but this works for me for now. Oh, and I'll caveat this with: I'm using 1.4.2. Yes I know I'm in the stone ages still.
4,168
<p>I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?</p>
[ { "answer_id": 4177, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 1, "selected": false, "text": "<p>I would expect tools that need this simply walk the tree in a depth-first manner and when they hit a leaf, just process ...
2008/08/07
[ "https://Stackoverflow.com/questions/4168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/588/" ]
I'm looking for a simple algorithm to 'serialize' a directed graph. In particular I've got a set of files with interdependencies on their execution order, and I want to find the correct order at compile time. I know it must be a fairly common thing to do - compilers do it all the time - but my google-fu has been weak today. What's the 'go-to' algorithm for this?
[Topological Sort](http://en.wikipedia.org/wiki/Topological_sorting) (From Wikipedia): > > In graph theory, a topological sort or > topological ordering of a directed > acyclic graph (DAG) is a linear > ordering of its nodes in which each > node comes before all nodes to which > it has outbound edges. Every DAG has > one or more topological sorts. > > > Pseudo code: ``` L ← Empty list where we put the sorted elements Q ← Set of all nodes with no incoming edges while Q is non-empty do remove a node n from Q insert n into L for each node m with an edge e from n to m do remove edge e from the graph if m has no other incoming edges then insert m into Q if graph has edges then output error message (graph has a cycle) else output message (proposed topologically sorted order: L) ```
4,170
<p>I need to learn ADO.NET to build applications based on MS Office. I have read a good deal about ADO.NET in the MSDN Library, but everything seems rather messy to me.</p> <p>What are the basics one must figure out when using ADO.NET? I think a few key words will suffice to let me organize my learning.</p>
[ { "answer_id": 4204, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 4, "selected": true, "text": "<p>There are three key components (assuming ur using SQL server):</p>\n\n<ul>\n<li><code>SQLConnection</code></li>\n<li><code>S...
2008/08/07
[ "https://Stackoverflow.com/questions/4170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to learn ADO.NET to build applications based on MS Office. I have read a good deal about ADO.NET in the MSDN Library, but everything seems rather messy to me. What are the basics one must figure out when using ADO.NET? I think a few key words will suffice to let me organize my learning.
There are three key components (assuming ur using SQL server): * `SQLConnection` * `SqlCommand` * `SqlDataReader` (if you're using something else, replace `Sql` with "Something", like `MySqlConnection`, `OracleCommand`) Everything else is just built on top of that. **Example 1:** ``` using (SqlConnection connection = new SqlConnection("CONNECTION STRING")) using (SqlCommand command = new SqlCommand()) { command.commandText = "SELECT Name FROM Users WHERE Status = @OnlineStatus"; command.Connection = connection; command.Parameters.Add("@OnlineStatus", SqlDbType.Int).Value = 1; //replace with enum connection.Open(); using (SqlDataReader dr = command.ExecuteReader)) { List<string> onlineUsers = new List<string>(); while (dr.Read()) { onlineUsers.Add(dr.GetString(0)); } } } ``` **Example 2:** ``` using (SqlConnection connection = new SqlConnection("CONNECTION STRING")) using (SqlCommand command = new SqlCommand()) { command.commandText = "DELETE FROM Users where Email = @Email"; command.Connection = connection; command.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = "user@host.com"; connection.Open(); command.ExecuteNonQuery(); } ```
4,208
<p>Is there a Windows equivalent of the Unix command, <em>nice</em>?</p> <p>I'm specifically looking for something I can use at the command line, and <strong>not</strong> the "Set Priority" menu from the task manager.</p> <p>My attempts at finding this on Google have been thwarted by those who can't come up with better adjectives.</p>
[ { "answer_id": 4262, "author": "ggasp", "author_id": 527, "author_profile": "https://Stackoverflow.com/users/527", "pm_score": 3, "selected": false, "text": "<p>Maybe you want to consider using <a href=\"http://www.donationcoder.com/Software/Mouser/proctamer/index.html\" rel=\"noreferrer...
2008/08/07
[ "https://Stackoverflow.com/questions/4208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55/" ]
Is there a Windows equivalent of the Unix command, *nice*? I'm specifically looking for something I can use at the command line, and **not** the "Set Priority" menu from the task manager. My attempts at finding this on Google have been thwarted by those who can't come up with better adjectives.
If you want to set priority when launching a process you could use the built-in [START](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/start) command: ```batch START ["title"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED] [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL] [/WAIT] [/B] [command/program] [parameters] ``` Use the low through belownormal options to set priority of the launched command/program. Seems like the most straightforward solution. No downloads or script writing. The other solutions probably work on already running procs though.
4,221
<p>I'd like to use a <code>LinqDataSource</code> control on a page and limit the amount of records returned. I know if I use code behind I could do something like this:</p> <pre><code>IEnumerable&lt;int&gt; values = Enumerable.Range(0, 10); IEnumerable&lt;int&gt; take3 = values.Take(3); </code></pre> <p>Does anyone know if something like this is possible with a <code>LinqDataSource</code> control?</p> <p><strong>[Update]</strong></p> <p>I'm going to use the <code>LinqDataSource</code> with the <code>ListView</code> control, <em>not</em> a GridView or Repeater. The <code>LinqDataSource</code> wizard does not provide the ability to limit the number of records return. The Advanced options only allow you to enabled deletes, inserts, and updates.</p>
[ { "answer_id": 4231, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 2, "selected": false, "text": "<p>I know that if you use a paging repeater or gridview with the linqdatasource it will automatically optimize the number of resu...
2008/08/07
[ "https://Stackoverflow.com/questions/4221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/519/" ]
I'd like to use a `LinqDataSource` control on a page and limit the amount of records returned. I know if I use code behind I could do something like this: ``` IEnumerable<int> values = Enumerable.Range(0, 10); IEnumerable<int> take3 = values.Take(3); ``` Does anyone know if something like this is possible with a `LinqDataSource` control? **[Update]** I'm going to use the `LinqDataSource` with the `ListView` control, *not* a GridView or Repeater. The `LinqDataSource` wizard does not provide the ability to limit the number of records return. The Advanced options only allow you to enabled deletes, inserts, and updates.
I had this same issue. The way I got round this was to use the Selecting event on the LinqDataSource and return the result manually. e.g. ``` protected void lnqRecentOrder_Selecting(object sender, LinqDataSourceSelectEventArgs e) { DataClassesDataContext dx = new DataClassesDataContext(); e.Result = (from o in dx.Orders where o.CustomerID == Int32.Parse(Request.QueryString["CustomerID"]) select o).Take(5); } ```
4,227
<p>I'm using a <code>Dictionary&lt;string, int&gt;</code> where the <code>int</code> is a count of the key.</p> <p>Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt:</p> <pre><code>int LastCount = mydict[mydict.keys[mydict.keys.Count]]; </code></pre> <p>does not work, because <code>Dictionary.Keys</code> does not implement a []-indexer.</p> <p>I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a <code>Stack&lt;MyStruct&gt;</code>, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?</p>
[ { "answer_id": 4252, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 3, "selected": false, "text": "<p>You could always do this:</p>\n\n<pre><code>string[] temp = new string[mydict.count];\nmydict.Keys.CopyTo(temp, 0)\nint LastC...
2008/08/07
[ "https://Stackoverflow.com/questions/4227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I'm using a `Dictionary<string, int>` where the `int` is a count of the key. Now, I need to access the last-inserted Key inside the Dictionary, but I do not know the name of it. The obvious attempt: ``` int LastCount = mydict[mydict.keys[mydict.keys.Count]]; ``` does not work, because `Dictionary.Keys` does not implement a []-indexer. I just wonder if there is any similar class? I thought about using a Stack, but that only stores a string. I could now create my own struct and then use a `Stack<MyStruct>`, but I wonder if there is another alternative, essentially a Dictionary that implements an []-indexer on the Keys?
As @Falanwe points out in a comment, doing something like this is ***incorrect***: ``` int LastCount = mydict.Keys.ElementAt(mydict.Count -1); ``` You **should not** depend on the order of keys in a Dictionary. If you need ordering, you should use an [OrderedDictionary](https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary), as suggested in this [answer](https://stackoverflow.com/a/5540/1724702). The other answers on this page are interesting as well.
4,242
<p>I want to convert a primitive to a string, and I tried:</p> <pre><code>myInt.toString(); </code></pre> <p>This fails with the error:</p> <pre><code>int cannot be dereferenced </code></pre> <p>Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point). So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that.</p> <p>Furthermore, I believe C# allows such a call, unless I remember incorrectly. Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?</p>
[ { "answer_id": 4247, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 7, "selected": true, "text": "<p>Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it....
2008/08/07
[ "https://Stackoverflow.com/questions/4242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I want to convert a primitive to a string, and I tried: ``` myInt.toString(); ``` This fails with the error: ``` int cannot be dereferenced ``` Now, I get that primitives are not reference types (ie, not an Object) and so cannot have methods. However, Java 5 introduced autoboxing and unboxing (a la C#... which I never liked in C#, but that's beside the point). So with autoboxing, I would expect the above to convert myInt to an Integer and then call toString() on that. Furthermore, I believe C# allows such a call, unless I remember incorrectly. Is this just an unfortunate shortcoming of Java's autoboxing/unboxing specification, or is there a good reason for this?
Java autoboxing/unboxing doesn't go to the extent to allow you to dereference a primitive, so your compiler prevents it. Your compiler still knows `myInt` as a primitive. There's a paper about this issue at [jcp.org](http://jcp.org/aboutJava/communityprocess/jsr/tiger/autoboxing.html). Autoboxing is mainly useful during assignment or parameter passing -- allowing you to pass a primitive as an object (or vice versa), or assign a primitive to an object (or vice versa). So unfortunately, you would have to do it like this: (kudos Patrick, I switched to your way) ``` Integer.toString(myInt); ```
4,246
<p>What is the best method for executing FTP commands from a SQL Server stored procedure? we currently use something like this:</p> <pre><code>EXEC master..xp_cmdshell 'ftp -n -s:d:\ftp\ftpscript.xmt 172.1.1.1' </code></pre> <p>The problem is that the command seems to succeed even if the FTP ended in error. Also, the use of <code>xp_cmdshell</code> requires special permissions and may leave room for security issues.</p>
[ { "answer_id": 4271, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "<p>If you're running SQL 2005 you could do this in a CLR integration assembly and use the FTP classes in the System.Net namespace to ...
2008/08/07
[ "https://Stackoverflow.com/questions/4246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/162/" ]
What is the best method for executing FTP commands from a SQL Server stored procedure? we currently use something like this: ``` EXEC master..xp_cmdshell 'ftp -n -s:d:\ftp\ftpscript.xmt 172.1.1.1' ``` The problem is that the command seems to succeed even if the FTP ended in error. Also, the use of `xp_cmdshell` requires special permissions and may leave room for security issues.
If you're running SQL 2005 you could do this in a CLR integration assembly and use the FTP classes in the System.Net namespace to build a simple FTP client. You'd benefit from being able to trap and handle exceptions and reduce the security risk of having to use xp\_cmdshell. Just some thoughts.
4,287
<p>I have a process in erlang that is supposed to do something immediately after spawn, then send the result back to the parent when it is finished. How do I figure out the PID of the process that spawned it?</p>
[ { "answer_id": 4304, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 5, "selected": true, "text": "<p>You should pass self() to the child as one of the arguments to the entry function.</p>\n\n<pre><code>spawn_link(?MODULE, ...
2008/08/07
[ "https://Stackoverflow.com/questions/4287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/121/" ]
I have a process in erlang that is supposed to do something immediately after spawn, then send the result back to the parent when it is finished. How do I figure out the PID of the process that spawned it?
You should pass self() to the child as one of the arguments to the entry function. ``` spawn_link(?MODULE, child, [self()]). ```
4,306
<p>I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation. </p> <p>In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array). </p> <p>A sparse array allows the user to store a small number of values, and assume all undefined records to be a preset value. Since it is not physically possibly to store all values in memory, I need to store only the few non-zero elements. This could be several million entries.</p> <p>Speed is a huge priority, and I would also like to dynamically choose the number of variables in the class at runtime.</p> <p>I currently work on a system that uses a binary search tree (b-tree) to store entries. Does anyone know of a better system?</p>
[ { "answer_id": 4311, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 6, "selected": true, "text": "<p>For C++, a map works well. Several million objects won't be a problem. 10 million items took about 4.4 seconds and abo...
2008/08/07
[ "https://Stackoverflow.com/questions/4306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ]
I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation. In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array). A sparse array allows the user to store a small number of values, and assume all undefined records to be a preset value. Since it is not physically possibly to store all values in memory, I need to store only the few non-zero elements. This could be several million entries. Speed is a huge priority, and I would also like to dynamically choose the number of variables in the class at runtime. I currently work on a system that uses a binary search tree (b-tree) to store entries. Does anyone know of a better system?
For C++, a map works well. Several million objects won't be a problem. 10 million items took about 4.4 seconds and about 57 meg on my computer. My test application is as follows: ``` #include <stdio.h> #include <stdlib.h> #include <map> class triple { public: int x; int y; int z; bool operator<(const triple &other) const { if (x < other.x) return true; if (other.x < x) return false; if (y < other.y) return true; if (other.y < y) return false; return z < other.z; } }; int main(int, char**) { std::map<triple,int> data; triple point; int i; for (i = 0; i < 10000000; ++i) { point.x = rand(); point.y = rand(); point.z = rand(); //printf("%d %d %d %d\n", i, point.x, point.y, point.z); data[point] = i; } return 0; } ``` Now to dynamically choose the number of variables, the easiest solution is to represent **index as a string**, and then use string as a key for the map. For instance, an item located at [23][55] can be represented via "23,55" string. We can also extend this solution for higher dimensions; such as for three dimensions an arbitrary index will look like "34,45,56". A simple implementation of this technique is as follows: ``` std::map data<string,int> data; char ix[100]; sprintf(ix, "%d,%d", x, y); // 2 vars data[ix] = i; sprintf(ix, "%d,%d,%d", x, y, z); // 3 vars data[ix] = i; ```
4,369
<p>I have a directory structure like the following;</p> <blockquote> <p>script.php</p> <p>inc/include1.php<br/> inc/include2.php</p> <p>objects/object1.php<br/> objects/object2.php</p> <p>soap/soap.php</p> </blockquote> <p>Now, I use those objects in both <code>script.php</code> and <code>/soap/soap.php</code>, I could move them, but I want the directory structure like that for a specific reason. When executing <code>script.php</code> the include path is <code>inc/include.php</code> and when executing <code>/soap/soap.php</code> it's <code>../inc</code>, absolute paths work, <code>/mnt/webdev/[project name]/inc/include1.php...</code> But it's an ugly solution if I ever want to move the directory to a different location.</p> <p>So is there a way to use relative paths, or a way to programmatically generate the <code>"/mnt/webdev/[project name]/"</code>?</p>
[ { "answer_id": 4378, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 3, "selected": false, "text": "<p>You could define a constant with the path to the root directory of your project, and then put that at the beginning of the pat...
2008/08/07
[ "https://Stackoverflow.com/questions/4369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264/" ]
I have a directory structure like the following; > > script.php > > > inc/include1.php > > inc/include2.php > > > objects/object1.php > > objects/object2.php > > > soap/soap.php > > > Now, I use those objects in both `script.php` and `/soap/soap.php`, I could move them, but I want the directory structure like that for a specific reason. When executing `script.php` the include path is `inc/include.php` and when executing `/soap/soap.php` it's `../inc`, absolute paths work, `/mnt/webdev/[project name]/inc/include1.php...` But it's an ugly solution if I ever want to move the directory to a different location. So is there a way to use relative paths, or a way to programmatically generate the `"/mnt/webdev/[project name]/"`?
This should work ``` $root = realpath($_SERVER["DOCUMENT_ROOT"]); include "$root/inc/include1.php"; ``` --- **Edit:** added imporvement by [aussieviking](https://stackoverflow.com/questions/4369/include-files-requiring-an-absolute-path#4388)
4,371
<p>I lost my MySQL username and password. How do I retrieve it?</p>
[ { "answer_id": 4376, "author": "Xenph Yan", "author_id": 264, "author_profile": "https://Stackoverflow.com/users/264", "pm_score": 9, "selected": true, "text": "<blockquote>\n<p>Stop the MySQL process.</p>\n<p>Start the MySQL process with the --skip-grant-tables option.</p>\n<p>Start the...
2008/08/07
[ "https://Stackoverflow.com/questions/4371", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
I lost my MySQL username and password. How do I retrieve it?
> > Stop the MySQL process. > > > Start the MySQL process with the --skip-grant-tables option. > > > Start the MySQL console client with the -u root option. > > > List all the users; ``` SELECT * FROM mysql.user; ``` Reset password; ``` UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]'; ``` --- But **DO NOT FORGET** to > > Stop the MySQL process > > > Start the MySQL Process normally (i.e. without the --skip-grant-tables option) > > > when you are finished. Otherwise, your database's security could be compromised.
4,393
<p>How can I drop all tables whose names begin with a given string? </p> <p>I think this can be done with some dynamic SQL and the <code>INFORMATION_SCHEMA</code> tables.</p>
[ { "answer_id": 4394, "author": "Xenph Yan", "author_id": 264, "author_profile": "https://Stackoverflow.com/users/264", "pm_score": 7, "selected": false, "text": "<pre><code>SELECT 'DROP TABLE \"' + TABLE_NAME + '\"' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n</...
2008/08/07
[ "https://Stackoverflow.com/questions/4393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
How can I drop all tables whose names begin with a given string? I think this can be done with some dynamic SQL and the `INFORMATION_SCHEMA` tables.
You may need to modify the query to include the owner if there's more than one in the database. ```sql DECLARE @cmd varchar(4000) DECLARE cmds CURSOR FOR SELECT 'drop table [' + Table_Name + ']' FROM INFORMATION_SCHEMA.TABLES WHERE Table_Name LIKE 'prefix%' OPEN cmds WHILE 1 = 1 BEGIN FETCH cmds INTO @cmd IF @@fetch_status != 0 BREAK EXEC(@cmd) END CLOSE cmds; DEALLOCATE cmds ``` This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run. I know that if I were going to do this against a production database, I'd be as careful as possible. **Edit** Code sample fixed.
4,416
<p>I am walking through the MS Press Windows Workflow Step-by-Step book and in chapter 8 it mentions a tool with the filename "wca.exe". This is supposed to be able to generate workflow communication helper classes based on an interface you provide it. I can't find that file. I thought it would be in the latest .NET 3.5 SDK, but I just downloaded and fully installed, and it's not there. Also, some MSDN forum posts had links posted that just go to 404s. So, where can I find wca.exe?</p>
[ { "answer_id": 4394, "author": "Xenph Yan", "author_id": 264, "author_profile": "https://Stackoverflow.com/users/264", "pm_score": 7, "selected": false, "text": "<pre><code>SELECT 'DROP TABLE \"' + TABLE_NAME + '\"' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n</...
2008/08/07
[ "https://Stackoverflow.com/questions/4416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ]
I am walking through the MS Press Windows Workflow Step-by-Step book and in chapter 8 it mentions a tool with the filename "wca.exe". This is supposed to be able to generate workflow communication helper classes based on an interface you provide it. I can't find that file. I thought it would be in the latest .NET 3.5 SDK, but I just downloaded and fully installed, and it's not there. Also, some MSDN forum posts had links posted that just go to 404s. So, where can I find wca.exe?
You may need to modify the query to include the owner if there's more than one in the database. ```sql DECLARE @cmd varchar(4000) DECLARE cmds CURSOR FOR SELECT 'drop table [' + Table_Name + ']' FROM INFORMATION_SCHEMA.TABLES WHERE Table_Name LIKE 'prefix%' OPEN cmds WHILE 1 = 1 BEGIN FETCH cmds INTO @cmd IF @@fetch_status != 0 BREAK EXEC(@cmd) END CLOSE cmds; DEALLOCATE cmds ``` This is cleaner than using a two-step approach of generate script plus run. But one advantage of the script generation is that it gives you the chance to review the entirety of what's going to be run before it's actually run. I know that if I were going to do this against a production database, I'd be as careful as possible. **Edit** Code sample fixed.
4,418
<p>The firewall I'm behind is running Microsoft ISA server in NTLM-only mode. Hash anyone have success getting their Ruby gems to install/update via Ruby SSPI gem or other method?</p> <p>... or am I just being lazy?</p> <p>Note: rubysspi-1.2.4 does not work.</p> <p>This also works for "igem", part of the IronRuby project</p>
[ { "answer_id": 4420, "author": "Jarin Udom", "author_id": 574, "author_profile": "https://Stackoverflow.com/users/574", "pm_score": 3, "selected": false, "text": "<p>A workaround is to install <a href=\"http://web.archive.org/web/20060913093359/http://apserver.sourceforge.net:80/\" rel=\...
2008/08/07
[ "https://Stackoverflow.com/questions/4418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/307/" ]
The firewall I'm behind is running Microsoft ISA server in NTLM-only mode. Hash anyone have success getting their Ruby gems to install/update via Ruby SSPI gem or other method? ... or am I just being lazy? Note: rubysspi-1.2.4 does not work. This also works for "igem", part of the IronRuby project
I wasn't able to get mine working from the command-line switch but I have been able to do it just by setting my `HTTP_PROXY` environment variable. (Note that case seems to be important). I have a batch file that has a line like this in it: ``` SET HTTP_PROXY=http://%USER%:%PASSWORD%@%SERVER%:%PORT% ``` I set the four referenced variables before I get to this line obviously. As an example if my username is "wolfbyte", my password is "secret" and my proxy is called "pigsy" and operates on port 8080: ``` SET HTTP_PROXY=http://wolfbyte:secret@pigsy:8080 ``` You might want to be careful how you manage that because it stores your password in plain text in the machine's session but I don't think it should be too much of an issue.
4,432
<p>Typical way of creating a <a href="http://en.wikipedia.org/wiki/Comma-separated_values" rel="noreferrer">CSV</a> string (pseudocode):</p> <ol> <li>Create a CSV container object (like a StringBuilder in C#).</li> <li>Loop through the strings you want to add appending a comma after each one.</li> <li>After the loop, remove that last superfluous comma.</li> </ol> <p>Code sample:</p> <pre><code>public string ReturnAsCSV(ContactList contactList) { StringBuilder sb = new StringBuilder(); foreach (Contact c in contactList) { sb.Append(c.Name + ","); } sb.Remove(sb.Length - 1, 1); //sb.Replace(",", "", sb.Length - 1, 1) return sb.ToString(); } </code></pre> <p>I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence?</p> <p>I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?</p>
[ { "answer_id": 4437, "author": "Chris Farmer", "author_id": 404, "author_profile": "https://Stackoverflow.com/users/404", "pm_score": 2, "selected": false, "text": "<p>You could instead add the comma as the first thing inside your foreach.</p>\n\n<p><code>if (sb.Length &gt; 0) sb.Append(...
2008/08/07
[ "https://Stackoverflow.com/questions/4432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/202/" ]
Typical way of creating a [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) string (pseudocode): 1. Create a CSV container object (like a StringBuilder in C#). 2. Loop through the strings you want to add appending a comma after each one. 3. After the loop, remove that last superfluous comma. Code sample: ``` public string ReturnAsCSV(ContactList contactList) { StringBuilder sb = new StringBuilder(); foreach (Contact c in contactList) { sb.Append(c.Name + ","); } sb.Remove(sb.Length - 1, 1); //sb.Replace(",", "", sb.Length - 1, 1) return sb.ToString(); } ``` I like the idea of adding the comma by checking if the container is empty, but doesn't that mean more processing as it needs to check the length of the string on each occurrence? I feel that there should be an easier/cleaner/more efficient way of removing that last comma. Any ideas?
You could use [LINQ to Objects](http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_Objects): ``` string [] strings = contactList.Select(c => c.Name).ToArray(); string csv = string.Join(",", strings); ``` Obviously that could all be done in one line, but it's a bit clearer on two.
4,506
<p>I'm writing a resource handling method where I control access to various files, and I'd like to be able to make use of the browser's cache. My question is two-fold:</p> <ol> <li><p>Which are the definitive HTTP headers that I need to check in order to know for sure whether I should send a 304 response, and what am I looking for when I do check them?</p></li> <li><p>Additionally, are there any headers that I need to send when I initially send the file (like 'Last-Modified') as a 200 response?</p></li> </ol> <p>Some psuedo-code would probably be the most useful answer.</p> <hr> <p>What about the cache-control header? Can the various possible values of that affect what you send to the client (namely max-age) or should only if-modified-since be obeyed?</p>
[ { "answer_id": 4509, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 2, "selected": false, "text": "<p>You should send a 304 if the client has explicitly stated that it may already have the page in its cache. This is called a c...
2008/08/07
[ "https://Stackoverflow.com/questions/4506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
I'm writing a resource handling method where I control access to various files, and I'd like to be able to make use of the browser's cache. My question is two-fold: 1. Which are the definitive HTTP headers that I need to check in order to know for sure whether I should send a 304 response, and what am I looking for when I do check them? 2. Additionally, are there any headers that I need to send when I initially send the file (like 'Last-Modified') as a 200 response? Some psuedo-code would probably be the most useful answer. --- What about the cache-control header? Can the various possible values of that affect what you send to the client (namely max-age) or should only if-modified-since be obeyed?
Here's how I implemented it. The code has been working for a bit more than a year and with multiple browsers, so I think it's pretty reliable. This is based on [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html) and by observing what and when the various browsers were sending. Here's the pseudocode: ``` server_etag = gen_etag_for_this_file(myfile) etag_from_browser = get_header("Etag") if etag_from_browser does not exist: etag_from_browser = get_header("If-None-Match") if the browser has quoted the etag: strip the quotes (e.g. "foo" --> foo) set server_etag into http header if etag_from_browser matches server_etag send 304 return code to browser ``` Here's a snippet of my server logic that handles this. ``` /* the client should set either Etag or If-None-Match */ /* some clients quote the parm, strip quotes if so */ mketag(etag, &sb); etagin = apr_table_get(r->headers_in, "Etag"); if (etagin == NULL) etagin = apr_table_get(r->headers_in, "If-None-Match"); if (etag != NULL && etag[0] == '"') { int sl; sl = strlen(etag); memmove(etag, etag+1, sl+1); etag[sl-2] = 0; logit(2,"etag=:%s:",etag); } ... apr_table_add(r->headers_out, "ETag", etag); ... if (etagin != NULL && strcmp(etagin, etag) == 0) { /* if the etag matches, we return a 304 */ rc = HTTP_NOT_MODIFIED; } ``` If you want some help with etag generation post another question and I'll dig out some code that does that as well. HTH!
4,533
<p>How do I generate an ETag HTTP header for a resource file?</p>
[ { "answer_id": 4540, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": true, "text": "<p>An etag is an arbitrary string that the server sends to the client that the client will send back to the server the next...
2008/08/07
[ "https://Stackoverflow.com/questions/4533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/192/" ]
How do I generate an ETag HTTP header for a resource file?
An etag is an arbitrary string that the server sends to the client that the client will send back to the server the next time the file is requested. The etag should be computable on the server based on the file. Sort of like a checksum, but you might not want to checksum every file sending it out. ``` server client <------------- request file foo file foo etag: "xyz" --------> <------------- request file foo etag: "xyz" (what the server just sent) (the etag is the same, so the server can send a 304) ``` I built up a string in the format "datestamp-file size-file inode number". So, if a file is changed on the server after it has been served out to the client, the newly regenerated etag won't match if the client re-requests it. ```c char *mketag(char *s, struct stat *sb) { sprintf(s, "%d-%d-%d", sb->st_mtime, sb->st_size, sb->st_ino); return s; } ```
4,544
<p>I'm trying to create a bookmarklet for posting del.icio.us bookmarks to a separate account.</p> <p>I tested it from the command line like:</p> <pre><code>wget -O - --no-check-certificate \ "https://seconduser:thepassword@api.del.icio.us/v1/posts/add?url=http://seet.dk&amp;description=test" </code></pre> <p>This works great.</p> <p>I then wanted to create a bookmarklet in my firefox. I googled and found bits and pieces and ended up with:</p> <pre><code>javascript:void( open('https://seconduser:password@api.del.icio.us/v1/posts/add?url=' +encodeURIComponent(location.href) +'&amp;description='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=500,height=250' ) ); </code></pre> <p>But all that happens is that I get this from del.icio.us:</p> <pre><code>&lt;?xml version="1.0" standalone="yes"?&gt; &lt;result code="access denied" /&gt; &lt;!-- fe04.api.del.ac4.yahoo.net uncompressed/chunked Thu Aug 7 02:02:54 PDT 2008 --&gt; </code></pre> <p>If I then go to the address bar and press enter, it changes to:</p> <pre><code>&lt;?xml version='1.0' standalone='yes'?&gt; &lt;result code="done" /&gt; &lt;!-- fe02.api.del.ac4.yahoo.net uncompressed/chunked Thu Aug 7 02:07:45 PDT 2008 --&gt; </code></pre> <p>Any ideas how to get it to work directly from the bookmarks?</p>
[ { "answer_id": 4546, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 1, "selected": false, "text": "<p>Does calling the method twice work?</p>\n\n<p>Seems to me that your authentication is being approved after the content arr...
2008/08/07
[ "https://Stackoverflow.com/questions/4544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86/" ]
I'm trying to create a bookmarklet for posting del.icio.us bookmarks to a separate account. I tested it from the command line like: ``` wget -O - --no-check-certificate \ "https://seconduser:thepassword@api.del.icio.us/v1/posts/add?url=http://seet.dk&description=test" ``` This works great. I then wanted to create a bookmarklet in my firefox. I googled and found bits and pieces and ended up with: ``` javascript:void( open('https://seconduser:password@api.del.icio.us/v1/posts/add?url=' +encodeURIComponent(location.href) +'&description='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=500,height=250' ) ); ``` But all that happens is that I get this from del.icio.us: ``` <?xml version="1.0" standalone="yes"?> <result code="access denied" /> <!-- fe04.api.del.ac4.yahoo.net uncompressed/chunked Thu Aug 7 02:02:54 PDT 2008 --> ``` If I then go to the address bar and press enter, it changes to: ``` <?xml version='1.0' standalone='yes'?> <result code="done" /> <!-- fe02.api.del.ac4.yahoo.net uncompressed/chunked Thu Aug 7 02:07:45 PDT 2008 --> ``` Any ideas how to get it to work directly from the bookmarks?
Can you sniff the traffic to find what's actually being sent? Is it sending any auth data at all and it's incorrect or being presented in a form the server doesn't like, or is it never being sent by firefox at all?
4,582
<p>I've implemented an image/video transformation technique called discrete cosine transform. This technique is used in MPEG video encoding. I based my algorithm on the ideas presented at the following URL:</p> <p><a href="http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html" rel="noreferrer"><a href="http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html" rel="noreferrer">http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html</a></a></p> <p>Now I can transform an 8x8 section of a black and white image, such as:</p> <pre> 0140 0124 0124 0132 0130 0139 0102 0088 0140 0123 0126 0132 0134 0134 0088 0117 0143 0126 0126 0133 0134 0138 0081 0082 0148 0126 0128 0136 0137 0134 0079 0130 0147 0128 0126 0137 0138 0145 0132 0144 0147 0131 0123 0138 0137 0140 0145 0137 0142 0135 0122 0137 0140 0138 0143 0112 0140 0138 0125 0137 0140 0140 0148 0143 </pre> <p>Into this an image with all the important information at the top right. The transformed block looks like this:</p> <pre> 1041 0039 -023 0044 0027 0000 0021 -019 -050 0044 -029 0000 0009 -014 0032 -010 0000 0000 0000 0000 -018 0010 -017 0000 0014 -019 0010 0000 0000 0016 -012 0000 0010 -010 0000 0000 0000 0000 0000 0000 -016 0021 -014 0010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 -010 0013 -014 0010 0000 0000 </pre> <p>Now, I need to know how can I take advantage of this transformation? I'd like to detect other 8x8 blocks in the same image ( or another image ) that represent a good match.</p> <p>Also, What does this transformation give me? Why is the information stored in the top right of the converted image important?</p>
[ { "answer_id": 4584, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>If I remember correctly, this matrix allows you to save the data to a file with compression.</p>\n\n<p>If you read f...
2008/08/07
[ "https://Stackoverflow.com/questions/4582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/609/" ]
I've implemented an image/video transformation technique called discrete cosine transform. This technique is used in MPEG video encoding. I based my algorithm on the ideas presented at the following URL: [<http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html>](http://vsr.informatik.tu-chemnitz.de/~jan/MPEG/HTML/mpeg_tech.html) Now I can transform an 8x8 section of a black and white image, such as: ``` 0140 0124 0124 0132 0130 0139 0102 0088 0140 0123 0126 0132 0134 0134 0088 0117 0143 0126 0126 0133 0134 0138 0081 0082 0148 0126 0128 0136 0137 0134 0079 0130 0147 0128 0126 0137 0138 0145 0132 0144 0147 0131 0123 0138 0137 0140 0145 0137 0142 0135 0122 0137 0140 0138 0143 0112 0140 0138 0125 0137 0140 0140 0148 0143 ``` Into this an image with all the important information at the top right. The transformed block looks like this: ``` 1041 0039 -023 0044 0027 0000 0021 -019 -050 0044 -029 0000 0009 -014 0032 -010 0000 0000 0000 0000 -018 0010 -017 0000 0014 -019 0010 0000 0000 0016 -012 0000 0010 -010 0000 0000 0000 0000 0000 0000 -016 0021 -014 0010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 -010 0013 -014 0010 0000 0000 ``` Now, I need to know how can I take advantage of this transformation? I'd like to detect other 8x8 blocks in the same image ( or another image ) that represent a good match. Also, What does this transformation give me? Why is the information stored in the top right of the converted image important?
The result of a DCT is a transformation of the original source into the frequency domain. The top left entry stores the "amplitude" the "base" frequency and frequency increases both along the horizontal and vertical axes. The outcome of the DCT is usually a collection of amplitudes at the more usual lower frequencies (the top left quadrant) and less entries at the higher frequencies. As lassevk mentioned, it is usual to just zero out these higher frequencies as they typically constitute very minor parts of the source. However, this does result in loss of information. To complete the compression it is usual to use a lossless compression over the DCT'd source. This is where the compression comes in as all those runs of zeros get packed down to almost nothing. One possible advantage of using the DCT to find similar regions is that you can do a first pass match on low frequency values (top-left corner). This reduces the number of values you need to match against. If you find matches of low frequency values, you can increase into comparing the higher frequencies. Hope this helps
4,610
<p>How is it possible to make prototype methods in C#.Net?</p> <p>In JavaScript, I can do the following to create a trim method for the string object:</p> <pre><code>String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } </code></pre> <p>How can I go about doing this in C#.Net?</p>
[ { "answer_id": 4614, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 0, "selected": false, "text": "<p>You need to create an extension method, which requires .NET 3.5. The method needs to be static, in a static class. The ...
2008/08/07
[ "https://Stackoverflow.com/questions/4610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How is it possible to make prototype methods in C#.Net? In JavaScript, I can do the following to create a trim method for the string object: ``` String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } ``` How can I go about doing this in C#.Net?
You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class. You can, however, in C# 3.0, use extension methods, which *look* like new methods, but are compile-time magic. To do this for your code: ``` public static class StringExtensions { public static String trim(this String s) { return s.Trim(); } } ``` To use it: ``` String s = " Test "; s = s.trim(); ``` This looks like a new method, but will compile the exact same way as this code: ``` String s = " Test "; s = StringExtensions.trim(s); ``` What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?
4,612
<p>Is <em>CompileAssemblyFromDom</em> faster than <em>CompileAssemblyFromSource</em>?</p> <p>It <em>should</em> be as it presumably bypasses the compiler front-end.</p>
[ { "answer_id": 4659, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>I've tried finding the ultimate compiler call earlier and I gave up. There's quite a number of layers of interfaces ...
2008/08/07
[ "https://Stackoverflow.com/questions/4612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/608/" ]
Is *CompileAssemblyFromDom* faster than *CompileAssemblyFromSource*? It *should* be as it presumably bypasses the compiler front-end.
CompileAssemblyFromDom compiles to a .cs file which is then run through the normal C# compiler. Example: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.CSharp; using System.CodeDom; using System.IO; using System.CodeDom.Compiler; using System.Reflection; namespace CodeDomQuestion { class Program { private static void Main(string[] args) { Program p = new Program(); p.dotest("C:\\fs.exe"); } public void dotest(string outputname) { CSharpCodeProvider cscProvider = new CSharpCodeProvider(); CompilerParameters cp = new CompilerParameters(); cp.MainClass = null; cp.GenerateExecutable = true; cp.OutputAssembly = outputname; CodeNamespace ns = new CodeNamespace("StackOverflowd"); CodeTypeDeclaration type = new CodeTypeDeclaration(); type.IsClass = true; type.Name = "MainClass"; type.TypeAttributes = TypeAttributes.Public; ns.Types.Add(type); CodeMemberMethod cmm = new CodeMemberMethod(); cmm.Attributes = MemberAttributes.Static; cmm.Name = "Main"; cmm.Statements.Add(new CodeSnippetExpression("System.Console.WriteLine('f'zxcvv)")); type.Members.Add(cmm); CodeCompileUnit ccu = new CodeCompileUnit(); ccu.Namespaces.Add(ns); CompilerResults results = cscProvider.CompileAssemblyFromDom(cp, ccu); foreach (CompilerError err in results.Errors) Console.WriteLine(err.ErrorText + " - " + err.FileName + ":" + err.Line); Console.WriteLine(); } } } ``` which shows errors in a (now nonexistent) temp file: > > ) expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17 > > > ; expected - c:\Documents and Settings\jacob\Local Settings\Temp\x59n9yb-.0.cs:17 > > > Invalid expression term ')' - c:\Documents and Settings\jacob\Local Settings\Tem p\x59n9yb-.0.cs:17 > > > So I guess the answer is "no"
4,622
<p>What is the <strong>complete</strong> and correct syntax for the SQL Case expression?</p>
[ { "answer_id": 4626, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 7, "selected": true, "text": "<p>The <strong>complete</strong> syntax depends on the database engine you're working with:</p>\n\n<p>For SQL Server:</p...
2008/08/07
[ "https://Stackoverflow.com/questions/4622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
What is the **complete** and correct syntax for the SQL Case expression?
The **complete** syntax depends on the database engine you're working with: For SQL Server: ``` CASE case-expression WHEN when-expression-1 THEN value-1 [ WHEN when-expression-n THEN value-n ... ] [ ELSE else-value ] END ``` or: ``` CASE WHEN boolean-when-expression-1 THEN value-1 [ WHEN boolean-when-expression-n THEN value-n ... ] [ ELSE else-value ] END ``` expressions, etc: ``` case-expression - something that produces a value when-expression-x - something that is compared against the case-expression value-1 - the result of the CASE statement if: the when-expression == case-expression OR the boolean-when-expression == TRUE boolean-when-exp.. - something that produces a TRUE/FALSE answer ``` Link: [CASE (Transact-SQL)](http://msdn.microsoft.com/en-us/library/ms181765.aspx) Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and **the first one that matches is used**. **Note**: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be *NULL*.
4,629
<p>I can do an <code>eval("something()");</code> to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?</p> <p>An example of what I am trying to do is: I have an integer variable (say <code>i</code>) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc. Now, I want to perform some operations on the " Property<em>i</em> " property depending on the value of <code>i</code>. </p> <p>This is really simple with Javascript. Is there any way to do this with C#?</p>
[ { "answer_id": 4633, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 2, "selected": false, "text": "<p>You can use reflection to get the property and invoke it. Something like this:</p>\n\n<pre><code>object result = theObj...
2008/08/07
[ "https://Stackoverflow.com/questions/4629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384/" ]
I can do an `eval("something()");` to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#? An example of what I am trying to do is: I have an integer variable (say `i`) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc. Now, I want to perform some operations on the " Property*i* " property depending on the value of `i`. This is really simple with Javascript. Is there any way to do this with C#?
**DISCLAIMER:** This answer was written back in 2008. The landscape has changed drastically since then. Look at the other answers on this page, especially the one detailing `Microsoft.CodeAnalysis.CSharp.Scripting`. Rest of answer will be left as it was originally posted but is no longer accurate. --- Unfortunately, C# isn't a dynamic language like that. What you can do, however, is to create a C# source code file, full with class and everything, and run it through the CodeDom provider for C# and compile it into an assembly, and then execute it. This forum post on MSDN contains an answer with some example code down the page somewhat: [create a anonymous method from a string?](https://social.msdn.microsoft.com/Forums/vstudio/en-US/6a783cc4-bb54-4fec-b504-f9b1ed786b54/create-a-anonymous-method-from-a-string) I would hardly say this is a very good solution, but it is possible anyway. What kind of code are you going to expect in that string? If it is a minor subset of valid code, for instance just math expressions, it might be that other alternatives exists. --- **Edit**: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here. If you split the string by the ; first, to get individual properties, you can use the following code to get a PropertyInfo object for a particular property for a class, and then use that object to manipulate a particular object. ``` String propName = "Text"; PropertyInfo pi = someObject.GetType().GetProperty(propName); pi.SetValue(someObject, "New Value", new Object[0]); ``` Link: [PropertyInfo.SetValue Method](https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue)
4,661
<p>I have more than one OpenID as I have tried out numerous. As people take up OpenID different suppliers are going to emerge I may want to switch provinders. As all IDs are me, and all are authenticated against the same email address, shouldn't I be able to log into stack overflow with any of them and be able to hit the same account?</p>
[ { "answer_id": 4777, "author": "Otto", "author_id": 519, "author_profile": "https://Stackoverflow.com/users/519", "pm_score": 6, "selected": true, "text": "<p>I think each site that implements OpenID would have to build their software to allow multiple entries for your OpenID credentials...
2008/08/07
[ "https://Stackoverflow.com/questions/4661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/274/" ]
I have more than one OpenID as I have tried out numerous. As people take up OpenID different suppliers are going to emerge I may want to switch provinders. As all IDs are me, and all are authenticated against the same email address, shouldn't I be able to log into stack overflow with any of them and be able to hit the same account?
I think each site that implements OpenID would have to build their software to allow multiple entries for your OpenID credentials. However, just because a site doesn't allow you to create multiple entries doesn't mean you can't swap out OpenID suppliers. How to turn your blog into an OpenID ------------------------------------ STEP 1: Get an OpenID. There a lots of servers and services out there you can use. I use <http://www.myopenid.com> STEP 2: Add these two lines to your blog's main template in-between the `<HEAD></HEAD>` tags at the top of your template. Most all blog engines support editing your template so this should be an easy and very possible thing to do. Example: ``` <link rel="openid.server" href="http://www.myopenid.com/server" /> <link rel="openid.delegate" href=http://YOURUSERNAME.myopenid.com/ /> ``` This will let you use your domain/blog as your OpenID. Credits to [Scott Hanselman](http://www.hanselman.com/blog/TheWeeklySourceCode25OpenIDEdition.aspx) and [Simon Willison](http://simonwillison.net/2006/Dec/19/openid/) for these simple instructions. Switch Your Supplier -------------------- Now that your OpenID points to your blog, you can update your link rel href's to point to a new supplier and all the places that you've tied your blog's OpenID will use the new supplier.
4,677
<p>The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Although I know how to code the singleton pattern in C++ and Java, I was wondering if anyone know how to implement it in Ruby?</p>
[ { "answer_id": 4686, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 3, "selected": false, "text": "<p>Use the singleton module:</p>\n\n<pre><code>class Clazz\n include Singleton\nend\n</code></pre>\n\n<p>See <a href=\"http:...
2008/08/07
[ "https://Stackoverflow.com/questions/4677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
The singleton pattern is a design pattern that is used to restrict instantiation of a class to one object instance. Although I know how to code the singleton pattern in C++ and Java, I was wondering if anyone know how to implement it in Ruby?
Actually, the above answer was not completely correct. ``` require 'singleton' class Example include Singleton end ``` You also need to include the require 'singleton' statement.
4,738
<p>I'm developing a data access component that will be used in a website that contains a mix of classic ASP and ASP.NET pages, and need a good way to manage its configuration settings.</p> <p>I'd like to use a custom <code>ConfigurationSection</code>, and for the ASP.NET pages this works great. But when the component is called via COM interop from a classic ASP page, the component isn't running in the context of an ASP.NET request and therefore has no knowledge of web.config.</p> <p>Is there a way to tell the <code>ConfigurationManager</code> to just load the configuration from an arbitrary path (e.g. <code>..\web.config</code> if my assembly is in the <code>/bin</code> folder)? If there is then I'm thinking my component can fall back to that if the default <code>ConfigurationManager.GetSection</code> returns <code>null</code> for my custom section.</p> <p>Any other approaches to this would be welcome!</p>
[ { "answer_id": 4746, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 8, "selected": true, "text": "<p>Try this:</p>\n\n<pre><code>System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Pa...
2008/08/07
[ "https://Stackoverflow.com/questions/4738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205/" ]
I'm developing a data access component that will be used in a website that contains a mix of classic ASP and ASP.NET pages, and need a good way to manage its configuration settings. I'd like to use a custom `ConfigurationSection`, and for the ASP.NET pages this works great. But when the component is called via COM interop from a classic ASP page, the component isn't running in the context of an ASP.NET request and therefore has no knowledge of web.config. Is there a way to tell the `ConfigurationManager` to just load the configuration from an arbitrary path (e.g. `..\web.config` if my assembly is in the `/bin` folder)? If there is then I'm thinking my component can fall back to that if the default `ConfigurationManager.GetSection` returns `null` for my custom section. Any other approaches to this would be welcome!
Try this: ``` System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath); //Path to your config file System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap); ```
4,752
<p>We've been having some issues with a SharePoint instance in a test environment. Thankfully this is not production ;) The problems started when the disk with the SQL Server databases and search index ran out of space. Following this, the search service would not run and search settings in the SSP were not accessible. Reclaiming the disk space did not resolve the issue. So rather than restoring the VM, we decided to try to fix the issue.</p> <p>We created a new SSP and changed the association of all services to the new SSP. The old SSP and it's databases were then deleted. Search results for PDF files are no longer appearing, but the search works fine otherwise. MySites also works OK.</p> <p>Following the implementation of this change, these problems occur:</p> <blockquote> <p>1) An audit failure message started appearing in the application event log, for 'DOMAIN\SPMOSSSvc' which is the MOSS farm account.</p> </blockquote> <pre><code>Event Type: Failure Audit Event Source: MSSQLSERVER Event Category: (4) Event ID: 18456 Date: 8/5/2008 Time: 3:55:19 PM User: DOMAIN\SPMOSSSvc Computer: dastest01 Description: Login failed for user 'DOMAIN\SPMOSSSvc'. [CLIENT: &lt;local machine&gt;] </code></pre> <blockquote> <p>2) SQL Server profiler is showing queries from SharePoint that reference the old (deleted) SSP database.</p> </blockquote> <p>So...</p> <ul> <li>Where would these references to DOMAIN\SPMOSSSvc and the old SSP database exist?</li> <li>Is there a way to 'completely' remove the SSP from the server, and re-create? The option to delete was not available (greyed out) when a single SSP is in place.</li> </ul>
[ { "answer_id": 5475, "author": "Daniel O", "author_id": 697, "author_profile": "https://Stackoverflow.com/users/697", "pm_score": 1, "selected": false, "text": "<p>Have you tried removing the SSP using the command line? I found this worked once when we had a broken an SSP and just wanted...
2008/08/07
[ "https://Stackoverflow.com/questions/4752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
We've been having some issues with a SharePoint instance in a test environment. Thankfully this is not production ;) The problems started when the disk with the SQL Server databases and search index ran out of space. Following this, the search service would not run and search settings in the SSP were not accessible. Reclaiming the disk space did not resolve the issue. So rather than restoring the VM, we decided to try to fix the issue. We created a new SSP and changed the association of all services to the new SSP. The old SSP and it's databases were then deleted. Search results for PDF files are no longer appearing, but the search works fine otherwise. MySites also works OK. Following the implementation of this change, these problems occur: > > 1) An audit failure message started appearing in the application event log, for 'DOMAIN\SPMOSSSvc' which is the MOSS farm account. > > > ``` Event Type: Failure Audit Event Source: MSSQLSERVER Event Category: (4) Event ID: 18456 Date: 8/5/2008 Time: 3:55:19 PM User: DOMAIN\SPMOSSSvc Computer: dastest01 Description: Login failed for user 'DOMAIN\SPMOSSSvc'. [CLIENT: <local machine>] ``` > > 2) SQL Server profiler is showing queries from SharePoint that reference the old > (deleted) SSP database. > > > So... * Where would these references to DOMAIN\SPMOSSSvc and the old SSP database exist? * Is there a way to 'completely' remove the SSP from the server, and re-create? The option to delete was not available (greyed out) when a single SSP is in place.
As Daniel McPherson said, this is caused when SSPs are deleted but the associated job are not and attempt to communicate with the deleted database. If the SSP database has been deleted or a problem occurred when deleting an SSP, the job may not be deleted. When the job attempts to run, it will fail since the database no longer exists. Follow the steps Daniel mentioned: 1. Go to SQL Server Management Studio 2. Disable the job called SSPNAME\_JobDeleteExpiredSessions, right click and choose Disable Job.
4,816
<p>How do you resolve a domain name to an IP address with .NET/C#?</p>
[ { "answer_id": 4821, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 5, "selected": true, "text": "<pre><code>using System.Net;\n\nforeach (IPAddress address in Dns.GetHostAddresses(\"www.google.com\"))\n{\n Console.WriteL...
2008/08/07
[ "https://Stackoverflow.com/questions/4816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/390/" ]
How do you resolve a domain name to an IP address with .NET/C#?
``` using System.Net; foreach (IPAddress address in Dns.GetHostAddresses("www.google.com")) { Console.WriteLine(address.ToString()); } ```
4,824
<p>Is there a C library function that will return the index of a character in a string?</p> <p>So far, all I've found are functions like strstr that will return the found char *, not it's location in the original string.</p>
[ { "answer_id": 4829, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 0, "selected": false, "text": "<p>If you are not totally tied to pure C and can use string.h there is strchr()\n<a href=\"http://www.cplusplus.com/reference...
2008/08/07
[ "https://Stackoverflow.com/questions/4824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/75/" ]
Is there a C library function that will return the index of a character in a string? So far, all I've found are functions like strstr that will return the found char \*, not it's location in the original string.
I think that > > size\_t strcspn ( const char \* str1, const char \* str2 ); > > > is what you want. Here is an example pulled from [here](http://www.cplusplus.com/reference/clibrary/cstring/strcspn.html): ``` /* strcspn example */ #include <stdio.h> #include <string.h> int main () { char str[] = "fcba73"; char keys[] = "1234567890"; int i; i = strcspn (str,keys); printf ("The first number in str is at position %d.\n",i+1); return 0; } ```
4,839
<p>My dream IDE does full code hints, explains and completes PHP, Javascript, HTML and CSS. I know it exists!</p> <p>so far, <a href="http://www.zend.com/en/products/studio/features" rel="noreferrer">Zend studio 6</a>, under the Eclipse IDE does a great job at hinting PHP, some Javascript and HTML, any way I can expand this?</p> <p>edit: a bit more information: right now, using zend-6 under eclipse, i type in</p> <pre><code>&lt;?php p //(a single letter "p") </code></pre> <p>and I get a hint tooltip with all the available php functions that begin with "p" (phpinfo(), parse_ini_file(), parse_str(), etc...), each with its own explanation: phpinfo()->"outputs lots of PHP information", the same applies for regular HTML (no explanations however).</p> <p>However, I get nothing when I do:</p> <pre><code>&lt;style&gt; b /* (a single letter "b") */ </code></pre> <p>I'd love it if I could get, from that "b" suggestions for "border", "bottom", etc. The same applies for Javascript.</p> <p>Any ideas?</p>
[ { "answer_id": 4852, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 0, "selected": false, "text": "<p>The default CSS and HTML editors for Eclipse are really good. The default javascript editor does an OK job, but ...
2008/08/07
[ "https://Stackoverflow.com/questions/4839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ]
My dream IDE does full code hints, explains and completes PHP, Javascript, HTML and CSS. I know it exists! so far, [Zend studio 6](http://www.zend.com/en/products/studio/features), under the Eclipse IDE does a great job at hinting PHP, some Javascript and HTML, any way I can expand this? edit: a bit more information: right now, using zend-6 under eclipse, i type in ``` <?php p //(a single letter "p") ``` and I get a hint tooltip with all the available php functions that begin with "p" (phpinfo(), parse\_ini\_file(), parse\_str(), etc...), each with its own explanation: phpinfo()->"outputs lots of PHP information", the same applies for regular HTML (no explanations however). However, I get nothing when I do: ``` <style> b /* (a single letter "b") */ ``` I'd love it if I could get, from that "b" suggestions for "border", "bottom", etc. The same applies for Javascript. Any ideas?
I think the JavaScript and CSS need to be in separate files for this to work. Example of CSS autocomplete in Eclipse: Starting to type `border` > > ![css example in eclipse](https://i.stack.imgur.com/h4Sj9.png) > > > Then setting thickness > > ![autocompleting border thickness](https://i.stack.imgur.com/mmaEe.png) > > > Then choosing the color > > ![autocompleting border color](https://i.stack.imgur.com/Up41q.png) > > > Chose red, and it added the ; for me > > ![alt text](https://i.stack.imgur.com/Up41q.png) > > > Works pretty good IMHO.
4,850
<p>I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys.</p> <p>Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers(<strong><kbd>ALT</kbd>+<kbd>CTRL</kbd>+<kbd>SHIFT</kbd></strong>). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to.</p> <p>Does anyone have any ideas or suggestions on where I should go with this?</p>
[ { "answer_id": 5026, "author": "Tokabi", "author_id": 315, "author_profile": "https://Stackoverflow.com/users/315", "pm_score": 5, "selected": true, "text": "<p>Within your overridden ProcessCmdKey how are you determining which key has been pressed?</p>\n\n<p>The value of keyData (the se...
2008/08/07
[ "https://Stackoverflow.com/questions/4850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41/" ]
I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys. Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers(**`ALT`+`CTRL`+`SHIFT`**). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to. Does anyone have any ideas or suggestions on where I should go with this?
Within your overridden ProcessCmdKey how are you determining which key has been pressed? The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181. You can extract the modifiers and the key pressed by ANDing with appropriate enum values: ``` protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { bool shiftPressed = (keyData & Keys.Shift) != 0; Keys unmodifiedKey = (keyData & Keys.KeyCode); // rest of code goes here } ```
4,860
<p>We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details.</p> <p>Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs?</p>
[ { "answer_id": 5026, "author": "Tokabi", "author_id": 315, "author_profile": "https://Stackoverflow.com/users/315", "pm_score": 5, "selected": true, "text": "<p>Within your overridden ProcessCmdKey how are you determining which key has been pressed?</p>\n\n<p>The value of keyData (the se...
2008/08/07
[ "https://Stackoverflow.com/questions/4860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/661/" ]
We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details. Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs?
Within your overridden ProcessCmdKey how are you determining which key has been pressed? The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181. You can extract the modifiers and the key pressed by ANDing with appropriate enum values: ``` protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { bool shiftPressed = (keyData & Keys.Shift) != 0; Keys unmodifiedKey = (keyData & Keys.KeyCode); // rest of code goes here } ```
4,870
<p>I'm writing a Telnet client of sorts in C# and part of what I have to parse are ANSI/VT100 escape sequences, specifically, just those used for colour and formatting (detailed <a href="http://www.termsys.demon.co.uk/vtansi.htm#colors" rel="noreferrer">here</a>).</p> <p>One method I have is one to find all the codes and remove them, so I can render the text without any formatting if needed:</p> <pre><code> public static string StripStringFormating(string formattedString) { if (rTest.IsMatch(formattedString)) return rTest.Replace(formattedString, string.Empty); else return formattedString; } </code></pre> <p>I'm new to regular expressions and I was suggested to use this:</p> <pre><code>static Regex rText = new Regex(@"\e\[[\d;]+m", RegexOptions.Compiled);</code></pre> <p>However, this failed if the escape code was incomplete due to an error on the server. So then this was suggested, but my friend warned it might be slower (this one also matches another condition (z) that I might come across later):</p> <pre><code>static Regex rTest = new Regex(@"(\e(\[([\d;]*[mz]?))?)?", RegexOptions.Compiled);</code></pre> <p>This not only worked, but was in fact faster to and reduced the impact on my text rendering. Can someone explain to a regexp newbie, why? :)</p>
[ { "answer_id": 4883, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 1, "selected": false, "text": "<p>Without doing detailed analysis, I'd guess that it's faster because of the question marks. These allow the regular expression ...
2008/08/07
[ "https://Stackoverflow.com/questions/4870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
I'm writing a Telnet client of sorts in C# and part of what I have to parse are ANSI/VT100 escape sequences, specifically, just those used for colour and formatting (detailed [here](http://www.termsys.demon.co.uk/vtansi.htm#colors)). One method I have is one to find all the codes and remove them, so I can render the text without any formatting if needed: ``` public static string StripStringFormating(string formattedString) { if (rTest.IsMatch(formattedString)) return rTest.Replace(formattedString, string.Empty); else return formattedString; } ``` I'm new to regular expressions and I was suggested to use this: ``` static Regex rText = new Regex(@"\e\[[\d;]+m", RegexOptions.Compiled); ``` However, this failed if the escape code was incomplete due to an error on the server. So then this was suggested, but my friend warned it might be slower (this one also matches another condition (z) that I might come across later): ``` static Regex rTest = new Regex(@"(\e(\[([\d;]*[mz]?))?)?", RegexOptions.Compiled); ``` This not only worked, but was in fact faster to and reduced the impact on my text rendering. Can someone explain to a regexp newbie, why? :)
The reason why #1 is slower is that [\d;]+ is a greedy quantifier. Using +? or \*? is going to do lazy quantifing. See [MSDN - Quantifiers](http://msdn.microsoft.com/en-us/library/3206d374(VS.80).aspx) for more info. You may want to try: ``` "(\e\[(\d{1,2};)*?[mz]?)?" ``` That may be faster for you.
4,884
<p>I have a custom built ajax [div] based dynamic dropdown. </p> <p>I have an [input] box which; <code>onkeyup</code>, runs an Ajax search which returns results in <code>div</code>s and are drawn back in using <code>innerHTML</code>. These <code>div</code>s all have highlights <code>onmouseover</code> so, a typical successful search yields the following structure (pardon the semi-code):</p> <pre><code>[input] [div id=results] //this gets overwritten contantly by my AJAX function [div id=result1 onmouseover=highlight onclick=input.value=result1] [div id=result2 onmouseover=highlight onclick=input.value=result2] [div id=result2 onmouseover=highlight onclick=input.value=result2] [/div] </code></pre> <p>It works.</p> <p>However, I'm missing the important functions behind regular HTML elements. I can't keyboard down or up between "options".</p> <p>I know javascript handles keyboard events but; I haven't been able to find a good guide. (Of course, the follow-up question will end up being: can I use <code>&lt;ENTER&gt;</code> to trigger that <code>onclick</code> event?)</p>
[ { "answer_id": 4897, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 1, "selected": false, "text": "<p>Off the top of my head, I would think that you'd need to maintain some form of a data structure in the JavaScript that reflects the...
2008/08/07
[ "https://Stackoverflow.com/questions/4884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/547/" ]
I have a custom built ajax [div] based dynamic dropdown. I have an [input] box which; `onkeyup`, runs an Ajax search which returns results in `div`s and are drawn back in using `innerHTML`. These `div`s all have highlights `onmouseover` so, a typical successful search yields the following structure (pardon the semi-code): ``` [input] [div id=results] //this gets overwritten contantly by my AJAX function [div id=result1 onmouseover=highlight onclick=input.value=result1] [div id=result2 onmouseover=highlight onclick=input.value=result2] [div id=result2 onmouseover=highlight onclick=input.value=result2] [/div] ``` It works. However, I'm missing the important functions behind regular HTML elements. I can't keyboard down or up between "options". I know javascript handles keyboard events but; I haven't been able to find a good guide. (Of course, the follow-up question will end up being: can I use `<ENTER>` to trigger that `onclick` event?)
What you need to do is attach event listeners to the `div` with `id="results"`. You can do this by adding `onkeyup`, `onkeydown`, etc. attributes to the `div` when you create it or you can attach these using JavaScript. My recommendation would be that you use an AJAX library like [YUI](http://developer.yahoo.com/yui/), [jQuery](http://jquery.com/), [Prototype](http://www.prototypejs.org/), etc. for two reasons: 1. It sounds like you are trying to create an [Auto Complete](http://developer.yahoo.com/ypatterns/pattern.php?pattern=autocomplete) control which is something most AJAX libaries should provide. If you can use an existing component you'll save yourself a lot of time. 2. Even if you don't want to use the control provided by a library, all libraries provide event libraries that help to hide the differences between the event APIs provided by different browsers. [Forget addEvent, use Yahoo!’s Event Utility](http://www.dustindiaz.com/yahoo-event-utility/) provides a good summary of what an event library should provide for you. I'm pretty sure that the event libraries provided by jQuery, Prototype, et. al. provide similar features. If that article goes over your head have a look at [this documentation](http://developer.yahoo.com/yui/event/index.html) first and then re-read the original article (I found the article made much more sense after I'd used the event library). A couple of other things: * Using JavaScript gives you much more control than writing `onkeyup` etc. attributes into your HTML. Unless you want to do something *really simple* I would use JavaScript. * If you write your own code to handle keyboard events a [good key code reference](http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx) is really handy.
4,922
<p>I saw this in <a href="https://stackoverflow.com/a/4384/697449">an answer to another question</a>, in reference to shortcomings of the Java spec:</p> <blockquote> <p>There are more shortcomings and this is a subtle topic. Check <a href="http://kiranthakkar.blogspot.com/2007/05/method-overloading-with-new-features-of.html" rel="noreferrer">this</a> out:</p> <pre><code>public class methodOverloading{ public static void hello(Integer x){ System.out.println(&quot;Integer&quot;); } public static void hello(long x){ System.out.println(&quot;long&quot;); } public static void main(String[] args){ int i = 5; hello(i); } } </code></pre> <p>Here &quot;long&quot; would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all!</p> </blockquote> <p><em>Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely?</em></p> <p>On my initial scanning, I would agree with the statement that the output would be &quot;long&quot; on the basis of <code>i</code> being declared as a primitive and not an object. However, if you changed</p> <pre><code>hello(long x) </code></pre> <p>to</p> <pre><code>hello(Long x) </code></pre> <p>the output would print &quot;Integer&quot;</p> <p>What's really going on here? I know nothing about the compilers/bytecode interpreters for java...</p>
[ { "answer_id": 4932, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "<p>Yes it is, try it out in a test. You will see \"long\" printed. It is widening because Java will choose to widen the int...
2008/08/07
[ "https://Stackoverflow.com/questions/4922", "https://Stackoverflow.com", "https://Stackoverflow.com/users/670/" ]
I saw this in [an answer to another question](https://stackoverflow.com/a/4384/697449), in reference to shortcomings of the Java spec: > > There are more shortcomings and this is a subtle topic. Check [this](http://kiranthakkar.blogspot.com/2007/05/method-overloading-with-new-features-of.html) out: > > > > ``` > public class methodOverloading{ > public static void hello(Integer x){ > System.out.println("Integer"); > } > > public static void hello(long x){ > System.out.println("long"); > } > > public static void main(String[] args){ > int i = 5; > hello(i); > } > } > > ``` > > Here "long" would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all! > > > *Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely?* On my initial scanning, I would agree with the statement that the output would be "long" on the basis of `i` being declared as a primitive and not an object. However, if you changed ``` hello(long x) ``` to ``` hello(Long x) ``` the output would print "Integer" What's really going on here? I know nothing about the compilers/bytecode interpreters for java...
In the first case, you have a widening conversion happening. This can be see when runinng the "javap" utility program (included w/ the JDK), on the compiled class: ``` public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: i2l 4: invokestatic #6; //Method hello:(J)V 7: return } ``` Clearly, you see the I2L, which is the mnemonic for the widening Integer-To-Long bytecode instruction. See reference [here](http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html). And in the other case, replacing the "long x" with the object "Long x" signature, you'll have this code in the main method: ``` public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: invokestatic #6; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 6: invokestatic #7; //Method hello:(Ljava/lang/Integer;)V 9: return } ``` So you see the compiler has created the instruction Integer.valueOf(int), to box the primitive inside the wrapper.
4,954
<p>I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something. </p> <p>For what do you use regular expressions?</p> <p>P.S. sorry for my bad english</p>
[ { "answer_id": 4959, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>A regular expression (regex or regexp for short) is a special text string for describing a search pattern....
2008/08/07
[ "https://Stackoverflow.com/questions/4954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/518/" ]
I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something. For what do you use regular expressions? P.S. sorry for my bad english
Consider an example in Ruby: ``` puts "Matched!" unless /\d{3}-\d{4}/.match("555-1234").nil? puts "Didn't match!" if /\d{3}-\d{4}/.match("Not phone number").nil? ``` The "/\d{3}-\d{4}/" is the regular expression, and as you can see it is a VERY concise way of finding a match in a string. Furthermore, using groups you can extract information, as such: ``` match = /([^@]*)@(.*)/.match("myaddress@domain.com") name = match[1] domain = match[2] ``` Here, the parenthesis in the regular expression mark a capturing group, so you can see exactly WHAT the data is that you matched, so you can do further processing. This is just the tip of the iceberg... there are many many different things you can do in a regular expression that makes processing text REALLY easy.
4,973
<p>I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background color. The content in the right side is almost always going to be smaller than that on the left. I would like the div on the right to always be tall enough to reach the separator for the row below it. How can I make my background color fill that space?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.rightfloat { color: red; background-color: #BBBBBB; float: right; width: 200px; } .left { font-size: 20pt; } .separator { clear: both; width: 100%; border-top: 1px solid black; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="separator"&gt; &lt;div class="rightfloat"&gt; Some really short content. &lt;/div&gt; &lt;div class="left"&gt; Some really really really really really really really really really really big content &lt;/div&gt; &lt;/div&gt; &lt;div class="separator"&gt; &lt;div class="rightfloat"&gt; Some more short content. &lt;/div&gt; &lt;div class="left"&gt; Some really really really really really really really really really really big content &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p>Edit: I agree that this example is very table-like and an actual table would be a fine choice. But my "real" page will eventually be less table-like, and I'd just like to first master this task!</p> <p>Also, for some reason, when I create/edit my posts in IE7, the code shows up correctly in the preview view, but when I actually post the message, the formatting gets removed. Editing my post in Firefox 2 seems to have worked, FWIW.</p> <hr> <p>Another edit: Yeah, I unaccepted GateKiller's answer. It does indeed work nicely on my simple page, but not in my actual heavier page. I'll investigate some of the links y'all have pointed me to.</p>
[ { "answer_id": 4979, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 2, "selected": false, "text": "<p>I had the same problem on my site (<a href=\"http://woarl.com\" rel=\"nofollow noreferrer\">shameless plug</a>).</p>\...
2008/08/07
[ "https://Stackoverflow.com/questions/4973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/404/" ]
I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background color. The content in the right side is almost always going to be smaller than that on the left. I would like the div on the right to always be tall enough to reach the separator for the row below it. How can I make my background color fill that space? ```css .rightfloat { color: red; background-color: #BBBBBB; float: right; width: 200px; } .left { font-size: 20pt; } .separator { clear: both; width: 100%; border-top: 1px solid black; } ``` ```html <div class="separator"> <div class="rightfloat"> Some really short content. </div> <div class="left"> Some really really really really really really really really really really big content </div> </div> <div class="separator"> <div class="rightfloat"> Some more short content. </div> <div class="left"> Some really really really really really really really really really really big content </div> </div> ``` --- Edit: I agree that this example is very table-like and an actual table would be a fine choice. But my "real" page will eventually be less table-like, and I'd just like to first master this task! Also, for some reason, when I create/edit my posts in IE7, the code shows up correctly in the preview view, but when I actually post the message, the formatting gets removed. Editing my post in Firefox 2 seems to have worked, FWIW. --- Another edit: Yeah, I unaccepted GateKiller's answer. It does indeed work nicely on my simple page, but not in my actual heavier page. I'll investigate some of the links y'all have pointed me to.
Ahem... > > The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page. > > > Actually, 100% height will not work in most design situations - this may be short but it is not a good answer. Google "any column longest" layouts. The best way is to put the left and right cols inside a wrapper `div`, float the left and right cols and then float the wrapper - this makes it stretch to the height of the inner containers - then set background image on the outer wrapper. But watch for any horizontal margins on the floated elements in case you get the IE "double margin float bug".
5,017
<p>I have written an AIR Application that downloads videos and documents from a server. The videos play inside of the application, but I would like the user to be able to open the documents in their native applications.</p> <p>I am looking for a way to prompt the user to Open / Save As on a local file stored in the Application Storage Directory. I have tried using the FileReference + URLRequest classes but this throws an exception that it needs a remote url.</p> <p>My last resort is just copying the file to their desktop : \</p>
[ { "answer_id": 5266, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 3, "selected": true, "text": "<p>Only way I could figure out how to do it without just moving the file and telling the user was to pass it off to the browser.</p>\...
2008/08/07
[ "https://Stackoverflow.com/questions/5017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26/" ]
I have written an AIR Application that downloads videos and documents from a server. The videos play inside of the application, but I would like the user to be able to open the documents in their native applications. I am looking for a way to prompt the user to Open / Save As on a local file stored in the Application Storage Directory. I have tried using the FileReference + URLRequest classes but this throws an exception that it needs a remote url. My last resort is just copying the file to their desktop : \
Only way I could figure out how to do it without just moving the file and telling the user was to pass it off to the browser. ``` navigateToURL(new URLRequest(File.applicationStorageDirectory.nativePath + "/courses/" + fileName)); ```
5,071
<p>I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running "<code>cvs add</code>" only adds the contents of the current directory, and using "<code>cvs import</code>" didn't look like the right thing either since it's still all code I'm producing (this howto claimed import is for <a href="http://www.thathost.com/wincvs-howto/cvsdoc/cvs_16.html#SEC136" rel="noreferrer">3rd party sources</a>)</p> <p>Do you guys know any way to recursively add everything in a given directory to the current CVS project (or if SVN or git makes this notably easier)?</p>
[ { "answer_id": 5076, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "<p>SVN definitely makes this trivial task, using a GUI like Tortoise is even easier, however.</p>\n\n<p>This might be a good...
2008/08/07
[ "https://Stackoverflow.com/questions/5071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running "`cvs add`" only adds the contents of the current directory, and using "`cvs import`" didn't look like the right thing either since it's still all code I'm producing (this howto claimed import is for [3rd party sources](http://www.thathost.com/wincvs-howto/cvsdoc/cvs_16.html#SEC136)) Do you guys know any way to recursively add everything in a given directory to the current CVS project (or if SVN or git makes this notably easier)?
Ah, spaces. This will work with spaces: ``` find . -type f -print0| xargs -0 cvs add ```
5,118
<p>I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look.</p> <p>I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations?</p> <p>I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement:</p> <pre><code>&lt;link href=&quot;Style/&lt;% GetCssRoot() %&gt;.css&quot; rel=&quot;stylesheet&quot; type=&quot;text/css&quot; /&gt; &lt;!--[if lte IE 8]&gt; &lt;link type=&quot;text/css&quot; href=&quot;Style/&lt;% GetCssRoot() %&gt;-ie8.css&quot; rel=&quot;stylesheet&quot; /&gt; &lt;![endif]--&gt; &lt;!--[if lte IE 7]&gt; &lt;link type=&quot;text/css&quot; href=&quot;Style/&lt;% GetCssRoot() %&gt;-ie7.css&quot; rel=&quot;stylesheet&quot; /&gt; &lt;![endif]--&gt; &lt;!--[if lte IE 6]&gt; &lt;link type=&quot;text/css&quot; href=&quot;Style/&lt;% GetCssRoot() %&gt;-ie6.css&quot; rel=&quot;stylesheet&quot; /&gt; &lt;![endif]--&gt; </code></pre>
[ { "answer_id": 5151, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 2, "selected": false, "text": "<p>I would suggest storing the stylesheet selection in the session so you don't have to rely on the querystring key being presen...
2008/08/07
[ "https://Stackoverflow.com/questions/5118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5/" ]
I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look. I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations? I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement: ``` <link href="Style/<% GetCssRoot() %>.css" rel="stylesheet" type="text/css" /> <!--[if lte IE 8]> <link type="text/css" href="Style/<% GetCssRoot() %>-ie8.css" rel="stylesheet" /> <![endif]--> <!--[if lte IE 7]> <link type="text/css" href="Style/<% GetCssRoot() %>-ie7.css" rel="stylesheet" /> <![endif]--> <!--[if lte IE 6]> <link type="text/css" href="Style/<% GetCssRoot() %>-ie6.css" rel="stylesheet" /> <![endif]--> ```
In Asp.net 3.5, you should be able to set up the Link tag in the header as a server tag. Then in the codebehind you can set the href property for the link element, based on a cookie value, querystring, date, etc. In your aspx file: ``` <head> <link id="linkStyles" rel="stylesheet" type="text/css" runat="server" /> </head> ``` And in the Code behind: ``` protected void Page_Load(object sender, EventArgs e) { string stylesheetAddress = // logic to determine stylesheet linkStyles.Href = stylesheetAddress; } ```
5,134
<p>What is the best approach to write <strong>hooks</strong> for <strong>Subversion</strong> in <strong>Windows</strong>? As far as I know, only executable files can be used. So what is the best choice? </p> <ul> <li>Plain batch files (very limited but perhaps OK for very simple solutions)</li> <li>Dedicated compiled executable applications (sledgehammer to crack a nutshell?)</li> <li>Some other hybrid choice (like a batch file running a Powershell script)</li> </ul>
[ { "answer_id": 5144, "author": "Tanerax", "author_id": 567, "author_profile": "https://Stackoverflow.com/users/567", "pm_score": 1, "selected": false, "text": "<p>Depending on the complexity, each situation is different, If I am just simply moving files around, I'll write a quick batch f...
2008/08/07
[ "https://Stackoverflow.com/questions/5134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/563/" ]
What is the best approach to write **hooks** for **Subversion** in **Windows**? As far as I know, only executable files can be used. So what is the best choice? * Plain batch files (very limited but perhaps OK for very simple solutions) * Dedicated compiled executable applications (sledgehammer to crack a nutshell?) * Some other hybrid choice (like a batch file running a Powershell script)
I’ve just spent several days procrastinating about exactly this question. There are third party products available and plenty of PERL and Python scripts but I wanted something simple and a language I was familiar with so ended up just writing hooks in a C# console app. It’s very straight forward: ``` public void Main(string[] args) { string repositories = args[0]; string transaction = args[1]; var processStartInfo = new ProcessStartInfo { FileName = "svnlook.exe", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, Arguments = String.Format("log -t \"{0}\" \"{1}\"", transaction, repositories) }; var p = Process.Start(processStartInfo); var s = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if (s == string.Empty) { Console.Error.WriteLine("Message must be provided"); Environment.Exit(1); } Environment.Exit(0); } ``` You can then invoke this on pre commit by adding a pre-commit.cmd file to the hooks folder of the repo with the following line: ``` [path]\PreCommit.exe %1 %2 ``` You may consider this overkill but ultimately it’s only a few minutes of coding. What’s more, you get the advantage of the .NET language suite which IMHO is far preferable to the alternatives. I’ll expand my hooks out significantly and write appropriate tests against them as well – bit hard to do this with a DOS batch file! BTW, the code has been adapted from [this post](http://irwinj.blogspot.com/2008/04/simple-subversion-trigger.html).
5,142
<p>I created a view on a machine using the <em>substring</em> function from Firebird, and it worked. When I copied the database to a different machine, the view was broken. This is the way I used it:</p> <pre><code>SELECT SUBSTRING(field FROM 5 FOR 15) FROM table; </code></pre> <p>And this is the output on the machine that does not accept the function:</p> <pre><code>token unknown: FROM </code></pre> <p>Both computers have this configuration:</p> <ul> <li><em>IB Expert</em> version 2.5.0.42 to run the queries and deal with the database.</li> <li><em>Firebird</em> version 1.5 as server to database.</li> <li><em>BDE Administration</em> version 5.01 installed, with <em>Interbase</em> 4.0 drivers.</li> </ul> <p>Any ideas about why it's behaving differently on these machines?</p>
[ { "answer_id": 5148, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>Different engine versions?</p>\n\n<p>Have you tried naming that expression in the result?</p>\n\n<pre><code>SELECT S...
2008/08/07
[ "https://Stackoverflow.com/questions/5142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/431/" ]
I created a view on a machine using the *substring* function from Firebird, and it worked. When I copied the database to a different machine, the view was broken. This is the way I used it: ``` SELECT SUBSTRING(field FROM 5 FOR 15) FROM table; ``` And this is the output on the machine that does not accept the function: ``` token unknown: FROM ``` Both computers have this configuration: * *IB Expert* version 2.5.0.42 to run the queries and deal with the database. * *Firebird* version 1.5 as server to database. * *BDE Administration* version 5.01 installed, with *Interbase* 4.0 drivers. Any ideas about why it's behaving differently on these machines?
1. Make sure Firebird engine is 1.5 and there's no InterBase server running on this same box on the port you expected Firebird 1.5. 2. Make sure you don't have any UDF called 'substring' registered inside this DB so that Firebird is expecting different parameters.
5,179
<p>ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain.</p> <p>An <code>HttpWebRequest</code> works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post.</p> <p>So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code?</p>
[ { "answer_id": 5185, "author": "Mike Powell", "author_id": 205, "author_profile": "https://Stackoverflow.com/users/205", "pm_score": 2, "selected": false, "text": "<p>If you're using ASP.NET 2.0, you can do this with <a href=\"http://msdn.microsoft.com/en-us/library/ms178139.aspx\" rel=\...
2008/08/07
[ "https://Stackoverflow.com/questions/5179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111/" ]
ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain. An `HttpWebRequest` works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post. So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code?
Here's how I solved this problem today. I started from [this article](http://www.c-sharpcorner.com/UploadFile/desaijm/ASP.NetPostURL11282005005516AM/ASP.NetPostURL.aspx) on C# Corner, but found the example - while technically sound - a little incomplete. Everything he said was right, but I needed to hit a few external sites to piece this together to work exactly as I wanted. It didn't help that the user was not technically submitting a form at all; they were clicking a link to go to our support center, but to log them in an http post had to be made to the support center's site. This solution involves using `HttpContext.Current.Response.Write()` to write the data for the form, then using a bit of Javascript on the `<body onload="">` method to submit the form to the proper URL. When the user clicks on the Support Center link, the following method is called to write the response and redirect the user: ``` public static void PassthroughAuthentication() { System.Web.HttpContext.Current.Response.Write("<body onload=document.forms[0].submit();window.location=\"Home.aspx\";>"); System.Web.HttpContext.Current.Response.Write("<form name=\"Form\" target=_blank method=post action=\"https://external-url.com/security.asp\">"); System.Web.HttpContext.Current.Response.Write(string.Format("<input type=hidden name=\"cFName\" value=\"{0}\">", "Username")); System.Web.HttpContext.Current.Response.Write("</form>"); System.Web.HttpContext.Current.Response.Write("</body>"); } ``` The key to this method is in that onload bit of Javascript, which , when the body of the page loads, submits the form and then redirects the user back to my own Home page. The reason for that bit of hoodoo is that I'm launching the external site in a new window, but don't want the user to resubmit the hidden form if they refresh the page. Plus that hidden form pushed the page down a few pixels which got on my nerves. I'd be very interested in any cleaner ideas anyone has on this one. Eric Sipple
5,188
<p>I have a web reference for our report server embedded in our application. The server that the reports live on could change though, and I'd like to be able to change it "on the fly" if necessary.</p> <p>I know I've done this before, but can't seem to remember how. Thanks for your help.</p> <p>I've manually driven around this for the time being. It's not a big deal to set the URL in the code, but I'd like to figure out what the "proper" way of doing this in VS 2008 is. Could anyone provide any further insights? Thanks!</p> <hr> <p>In <strong>VS2008</strong> when I change the URL Behavior property to Dynamic I get the following code auto-generated in the Reference class.</p> <p>Can I override this setting (MySettings) in the web.config? I guess I don't know how the settings stuff works.</p> <pre><code>Public Sub New() MyBase.New Me.Url = Global.My.MySettings.Default.Namespace_Reference_ServiceName If (Me.IsLocalFileSystemWebService(Me.Url) = true) Then Me.UseDefaultCredentials = true Me.useDefaultCredentialsSetExplicitly = false Else Me.useDefaultCredentialsSetExplicitly = true End If End Sub </code></pre> <p><em>EDIT</em></p> <p>So this stuff has changed a bit since VS03 (which was probably the last VS version I used to do this).</p> <p>According to: <a href="http://msdn.microsoft.com/en-us/library/a65txexh.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/a65txexh.aspx</a> it looks like I have a settings object on which I can set the property programatically, but that I would need to provide the logic to retrieve that URL from the web.config.</p> <p>Is this the new standard way of doing this in VS2008, or am I missing something?</p> <p><em>EDIT #2</em></p> <p>Anyone have any ideas here? I drove around it in my application and just put the URL in my web.config myself and read it out. But I'm not happy with that because it still feels like I'm missing something.</p>
[ { "answer_id": 5192, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 3, "selected": true, "text": "<p>In the properties window change the \"behavior\" to Dynamic.</p>\n\n<p>See: <a href=\"http://www.codeproject.com/KB/XML/wsdldy...
2008/08/07
[ "https://Stackoverflow.com/questions/5188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/326/" ]
I have a web reference for our report server embedded in our application. The server that the reports live on could change though, and I'd like to be able to change it "on the fly" if necessary. I know I've done this before, but can't seem to remember how. Thanks for your help. I've manually driven around this for the time being. It's not a big deal to set the URL in the code, but I'd like to figure out what the "proper" way of doing this in VS 2008 is. Could anyone provide any further insights? Thanks! --- In **VS2008** when I change the URL Behavior property to Dynamic I get the following code auto-generated in the Reference class. Can I override this setting (MySettings) in the web.config? I guess I don't know how the settings stuff works. ``` Public Sub New() MyBase.New Me.Url = Global.My.MySettings.Default.Namespace_Reference_ServiceName If (Me.IsLocalFileSystemWebService(Me.Url) = true) Then Me.UseDefaultCredentials = true Me.useDefaultCredentialsSetExplicitly = false Else Me.useDefaultCredentialsSetExplicitly = true End If End Sub ``` *EDIT* So this stuff has changed a bit since VS03 (which was probably the last VS version I used to do this). According to: <http://msdn.microsoft.com/en-us/library/a65txexh.aspx> it looks like I have a settings object on which I can set the property programatically, but that I would need to provide the logic to retrieve that URL from the web.config. Is this the new standard way of doing this in VS2008, or am I missing something? *EDIT #2* Anyone have any ideas here? I drove around it in my application and just put the URL in my web.config myself and read it out. But I'm not happy with that because it still feels like I'm missing something.
In the properties window change the "behavior" to Dynamic. See: <http://www.codeproject.com/KB/XML/wsdldynamicurl.aspx>
5,194
<p>I am prototyping some C# 3 collection filters and came across this. I have a collection of products:</p> <pre><code>public class MyProduct { public string Name { get; set; } public Double Price { get; set; } public string Description { get; set; } } var MyProducts = new List&lt;MyProduct&gt; { new MyProduct { Name = "Surfboard", Price = 144.99, Description = "Most important thing you will ever own." }, new MyProduct { Name = "Leash", Price = 29.28, Description = "Keep important things close to you." } , new MyProduct { Name = "Sun Screen", Price = 15.88, Description = "1000 SPF! Who Could ask for more?" } }; </code></pre> <p>Now if I use LINQ to filter it works as expected:</p> <pre><code>var d = (from mp in MyProducts where mp.Price &lt; 50d select mp); </code></pre> <p>And if I use the Where extension method combined with a Lambda the filter works as well:</p> <pre><code>var f = MyProducts.Where(mp =&gt; mp.Price &lt; 50d).ToList(); </code></pre> <p><strong>Question:</strong> What is the difference, and why use one over the other?</p>
[ { "answer_id": 5199, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": true, "text": "<p>LINQ turns into method calls like the code you have.</p>\n\n<p>In other words, there should be no difference.</p>\n\n...
2008/08/07
[ "https://Stackoverflow.com/questions/5194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/439/" ]
I am prototyping some C# 3 collection filters and came across this. I have a collection of products: ``` public class MyProduct { public string Name { get; set; } public Double Price { get; set; } public string Description { get; set; } } var MyProducts = new List<MyProduct> { new MyProduct { Name = "Surfboard", Price = 144.99, Description = "Most important thing you will ever own." }, new MyProduct { Name = "Leash", Price = 29.28, Description = "Keep important things close to you." } , new MyProduct { Name = "Sun Screen", Price = 15.88, Description = "1000 SPF! Who Could ask for more?" } }; ``` Now if I use LINQ to filter it works as expected: ``` var d = (from mp in MyProducts where mp.Price < 50d select mp); ``` And if I use the Where extension method combined with a Lambda the filter works as well: ``` var f = MyProducts.Where(mp => mp.Price < 50d).ToList(); ``` **Question:** What is the difference, and why use one over the other?
LINQ turns into method calls like the code you have. In other words, there should be no difference. However, in your two pieces of code you are not calling .ToList in the first, so the first piece of code will produce an enumerable data source, but if you call .ToList on it, the two should be the same.
5,223
<p>I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?</p> <pre><code>const myObject = new Object(); myObject[&quot;firstname&quot;] = &quot;Gareth&quot;; myObject[&quot;lastname&quot;] = &quot;Simpson&quot;; myObject[&quot;age&quot;] = 21; </code></pre>
[ { "answer_id": 5232, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 5, "selected": false, "text": "<p>I'm not a JavaScript expert, but it looks like you would have to loop through the elements and count them since Object doesn't h...
2008/08/07
[ "https://Stackoverflow.com/questions/5223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/147/" ]
I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? ``` const myObject = new Object(); myObject["firstname"] = "Gareth"; myObject["lastname"] = "Simpson"; myObject["age"] = 21; ```
Updated answer -------------- **Here's an update as of 2016 and [widespread deployment of ES5](http://kangax.github.io/compat-table/es5/) and beyond.** For IE9+ and all other modern ES5+ capable browsers, you can use [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) so the above code just becomes: ``` var size = Object.keys(myObj).length; ``` This doesn't have to modify any existing prototype since `Object.keys()` is now built-in. **Edit**: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them. Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites. `Object.keys` or `Object.getOwnPropertyNames` does not work for symbolic properties. To return them you need to use `Object.getOwnPropertySymbols`. ```js var person = { [Symbol('name')]: 'John Doe', [Symbol('age')]: 33, "occupation": "Programmer" }; const propOwn = Object.getOwnPropertyNames(person); console.log(propOwn.length); // 1 let propSymb = Object.getOwnPropertySymbols(person); console.log(propSymb.length); // 2 ``` Older answer ------------ The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be: ```js Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // Get the size of an object const myObj = {} var size = Object.size(myObj); ``` There's a sort of convention in JavaScript that you [don't add things to Object.prototype](https://stackoverflow.com/questions/10757455/object-prototype-is-verboten), because it can break enumerations in various libraries. Adding methods to Object is usually safe, though. ---
5,260
<p>I have a situation where I want to add hours to a date and have the new date wrap around the work-day. I cobbled up a function to determine this new date, but want to make sure that I'm not forgetting anything.</p> <p>The hours to be added is called "delay". It could easily be a parameter to the function instead.</p> <p>Please post any suggestions. [VB.NET Warning]</p> <pre><code>Private Function GetDateRequired() As Date ''// A decimal representation of the current hour Dim hours As Decimal = Decimal.Parse(Date.Now.Hour) + (Decimal.Parse(Date.Now.Minute) / 60.0) Dim delay As Decimal = 3.0 ''// delay in hours Dim endOfDay As Decimal = 12.0 + 5.0 ''// end of day, in hours Dim startOfDay As Decimal = 8.0 ''// start of day, in hours Dim newHour As Integer Dim newMinute As Integer Dim dateRequired As Date = Now Dim delta As Decimal = hours + delay ''// Wrap around to the next day, if necessary If delta &gt; endOfDay Then delta = delta - endOfDay dateRequired = dateRequired.AddDays(1) newHour = Integer.Parse(Decimal.Truncate(delta)) newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60)) newHour = startOfDay + newHour Else newHour = Integer.Parse(Decimal.Truncate(delta)) newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60)) End If dateRequired = New Date(dateRequired.Year, dateRequired.Month, dateRequired.Day, newHour, newMinute, 0) Return dateRequired End Sub </code></pre> <p><strong>Note</strong>: This will probably not work if delay is more than 9 hours long. It should never change from 3, through.</p> <p>EDIT: The goal is find the date and time that you get as a result of adding several hours to the current time. This is used to determine a default value for a due date of a submission. I want to add 3 hours to the current time to get the due date time. However, I don't want due dates that go beyond 5pm on the current day. So, I tried to have the hours split between (today, up to 5pm) and (tomorrow, from 8am on), such that adding 3 hours to 4pm would give you 19am, because 1 hour is added to the end of today and 2 hours are added to the beginning of tomorrow.</p>
[ { "answer_id": 5303, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>You should probably write some automated tests for each condition you can think of, and then just start brainstorming more...
2008/08/07
[ "https://Stackoverflow.com/questions/5260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/106/" ]
I have a situation where I want to add hours to a date and have the new date wrap around the work-day. I cobbled up a function to determine this new date, but want to make sure that I'm not forgetting anything. The hours to be added is called "delay". It could easily be a parameter to the function instead. Please post any suggestions. [VB.NET Warning] ``` Private Function GetDateRequired() As Date ''// A decimal representation of the current hour Dim hours As Decimal = Decimal.Parse(Date.Now.Hour) + (Decimal.Parse(Date.Now.Minute) / 60.0) Dim delay As Decimal = 3.0 ''// delay in hours Dim endOfDay As Decimal = 12.0 + 5.0 ''// end of day, in hours Dim startOfDay As Decimal = 8.0 ''// start of day, in hours Dim newHour As Integer Dim newMinute As Integer Dim dateRequired As Date = Now Dim delta As Decimal = hours + delay ''// Wrap around to the next day, if necessary If delta > endOfDay Then delta = delta - endOfDay dateRequired = dateRequired.AddDays(1) newHour = Integer.Parse(Decimal.Truncate(delta)) newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60)) newHour = startOfDay + newHour Else newHour = Integer.Parse(Decimal.Truncate(delta)) newMinute = Integer.Parse(Decimal.Truncate((delta - newHour) * 60)) End If dateRequired = New Date(dateRequired.Year, dateRequired.Month, dateRequired.Day, newHour, newMinute, 0) Return dateRequired End Sub ``` **Note**: This will probably not work if delay is more than 9 hours long. It should never change from 3, through. EDIT: The goal is find the date and time that you get as a result of adding several hours to the current time. This is used to determine a default value for a due date of a submission. I want to add 3 hours to the current time to get the due date time. However, I don't want due dates that go beyond 5pm on the current day. So, I tried to have the hours split between (today, up to 5pm) and (tomorrow, from 8am on), such that adding 3 hours to 4pm would give you 19am, because 1 hour is added to the end of today and 2 hours are added to the beginning of tomorrow.
You should probably write some automated tests for each condition you can think of, and then just start brainstorming more, writing the tests as you think of them. This way, you can see for sure it will work, and will continue to work if you make further changes. Look up Test Driven Development if you like the results.
5,263
<p>I have a self-referential Role table that represents a tree structure </p> <pre><code>ID [INT] AUTO INCREMENT Name [VARCHAR] ParentID [INT] </code></pre> <p>I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of existing rows. If I make a child row, then make a child of that child, then Update, the temporary ID value generated by the DataTable is going into the ParentID column. I have the following data relation set:</p> <pre><code>dataset.Relations.Add(New DataRelation("RoleToRole",RoleTable.Columns("ID"), RoleTable.Columns("ParentID"))) </code></pre> <p>And when I make new child rows in the DataTable I call the SetParentRow method</p> <pre><code>newRow.SetParentRow(parentRow) </code></pre> <p>Is there something special I have to do to get the ID generation to propagate recursively when I call Update on the DataAdapter?</p>
[ { "answer_id": 5497, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "<p>Does it make any difference if you go</p>\n\n<pre><code>newRow.SetParentRow(parentRow, RoleTable.Relations(\"RoleToRole\"))\n<...
2008/08/07
[ "https://Stackoverflow.com/questions/5263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173/" ]
I have a self-referential Role table that represents a tree structure ``` ID [INT] AUTO INCREMENT Name [VARCHAR] ParentID [INT] ``` I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of existing rows. If I make a child row, then make a child of that child, then Update, the temporary ID value generated by the DataTable is going into the ParentID column. I have the following data relation set: ``` dataset.Relations.Add(New DataRelation("RoleToRole",RoleTable.Columns("ID"), RoleTable.Columns("ParentID"))) ``` And when I make new child rows in the DataTable I call the SetParentRow method ``` newRow.SetParentRow(parentRow) ``` Is there something special I have to do to get the ID generation to propagate recursively when I call Update on the DataAdapter?
I don't know ADO.net in particular, but most ORMs won't automatically insert the ID of a new record in a relationship. You'll have to resort to the 2-step process: 1. build and save parent 2. build and save child with relationship to parent The reason that this is difficult for ORMs is because you might have circular dependencies, and it wouldn't know which object it needed to create an ID for first. Some ORMs are smart enough to figure out those relationships where there are no such circular dependencies, but most aren't.
5,269
<p>In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement?</p> <p>Example:</p> <pre><code>DataTable myDt = new DataTable(); if (myDt != null &amp;&amp; myDt.Rows.Count &gt; 0) { //do some stuff with myDt } </code></pre> <p>Which statement does the runtime evaluate first - </p> <pre><code>myDt != null </code></pre> <p>or:</p> <pre><code>myDt.Rows.Count &gt; 0 </code></pre> <p>?</p> <p>Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved?</p> <hr> <blockquote> <p>&amp; is known as a logical bitwise operator and will always evaluate all the sub-expressions</p> </blockquote> <p>What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"?</p>
[ { "answer_id": 5272, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 2, "selected": false, "text": "<p>The left one, then stops if it is null.</p>\n\n<p>Edit: In vb.net it will evaluate both and possibly throw an error, unless you u...
2008/08/07
[ "https://Stackoverflow.com/questions/5269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement? Example: ``` DataTable myDt = new DataTable(); if (myDt != null && myDt.Rows.Count > 0) { //do some stuff with myDt } ``` Which statement does the runtime evaluate first - ``` myDt != null ``` or: ``` myDt.Rows.Count > 0 ``` ? Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved? --- > > & is known as a logical bitwise operator and will always evaluate all the sub-expressions > > > What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"?
C# : Left to right, and processing stops if a non-match (evaluates to false) is found.
5,323
<p>It seems like every time I try to create a pure CSS layout it takes me much longer than if I'd use a table or two. Getting three columns to be equal lengths with different amounts of data seems to require particular fancy hacks, especially when dealing with cross-browser issues.</p> <p>My Question:</p> <p>Who are these few tables going to hurt? </p> <p>Tables seem to work particularly well on tabular data &mdash; why are they so reviled in this day and age?</p> <p>Google.com has a table in its source code, so do many other sites (<em>stackoverflow.com does not by the way</em>).</p>
[ { "answer_id": 5331, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 3, "selected": false, "text": "<p>I'm of the thought that CSS layout with as few tables as possible is cleaner and better, but I agree that sometimes you just g...
2008/08/07
[ "https://Stackoverflow.com/questions/5323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/556/" ]
It seems like every time I try to create a pure CSS layout it takes me much longer than if I'd use a table or two. Getting three columns to be equal lengths with different amounts of data seems to require particular fancy hacks, especially when dealing with cross-browser issues. My Question: Who are these few tables going to hurt? Tables seem to work particularly well on tabular data — why are they so reviled in this day and age? Google.com has a table in its source code, so do many other sites (*stackoverflow.com does not by the way*).
Since this is stack**overflow**, I'll give you my *programmer's answer* semantics 101 First take a look at this code and think about what's wrong here... ``` class car { int wheels = 4; string engine; } car mybike = new car(); mybike.wheels = 2; mybike.engine = null; ``` The problem, of course, is that a bike is not a car. The car class is an inappropriate class for the bike instance. The code is error-free, but is semantically incorrect. It reflects poorly on the programmer. semantics 102 Now apply this to document markup. If your document needs to present tabular data, then the appropriate tag would be `<table>`. If you place navigation into a table however, then you're misusing the intended purpose of the `<table>` element. In the second case, you're not presenting tabular data -- you're (mis)using the `<table>` element to achieve a presentational goal. conclusion Whom does this hurt? No one. Who benefits if you use semantic markup? You -- and your professional reputation. Now go and do the right thing.
5,328
<p>So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that?</p> <p>My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException.</p> <p>So, what I want to do is effectively this:</p> <pre><code>public class MyClassMock extends MyClass { public MyClassMock() { try { super(0); } catch (Exception e) { throw new RuntimeException(e); } } // Mocked methods } </code></pre> <p>But Java complains that super isn't the first statement.</p> <p>My workaround:</p> <pre><code>public class MyClassMock extends MyClass { public static MyClassMock construct() { try { return new MyClassMock(); } catch (Exception e) { throw new RuntimeException(e); } } public MyClassMock() throws Exception { super(0); } // Mocked methods } </code></pre> <p>Is this the best workaround? Why doesn't Java let me do the former?</p> <hr> <p>My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways.</p> <p>I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.</p>
[ { "answer_id": 5351, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": true, "text": "<p>Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your c...
2008/08/07
[ "https://Stackoverflow.com/questions/5328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that? My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException. So, what I want to do is effectively this: ``` public class MyClassMock extends MyClass { public MyClassMock() { try { super(0); } catch (Exception e) { throw new RuntimeException(e); } } // Mocked methods } ``` But Java complains that super isn't the first statement. My workaround: ``` public class MyClassMock extends MyClass { public static MyClassMock construct() { try { return new MyClassMock(); } catch (Exception e) { throw new RuntimeException(e); } } public MyClassMock() throws Exception { super(0); } // Mocked methods } ``` Is this the best workaround? Why doesn't Java let me do the former? --- My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways. I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.
Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases. In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do *unsafe* things if one knows how to deal with them. In C# .NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this: ``` public ClassName(...) : base(...) ``` in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.
5,374
<p>I would have thought this would be an easy one to Google, but I've been unsucessful.</p> <p>I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute.</p> <p>Example:</p> <pre><code>&lt;xsl:variable name="myId" select="@id" /&gt; &lt;xsl value-of select="//Root/Some/Other/Path/Where[@id='{@myId}']/@Name /&gt; </code></pre> <p>That does not work. If I replace the {@myId} with the value that is in the variable then it does find the right node, but doign it this way produces nothing. I'm sure I'm missing something, or perhaps there is a different way to do it.</p> <p>The context is that there is related data under different top-level nodes that share the same id value so I need to get the related nodes in my template.</p>
[ { "answer_id": 5469, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 5, "selected": true, "text": "<p>Ok, I finally figured it out. Silly problem really, I simply needed to leave out the quotes and the braces. One of those t...
2008/08/07
[ "https://Stackoverflow.com/questions/5374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/312/" ]
I would have thought this would be an easy one to Google, but I've been unsucessful. I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute. Example: ``` <xsl:variable name="myId" select="@id" /> <xsl value-of select="//Root/Some/Other/Path/Where[@id='{@myId}']/@Name /> ``` That does not work. If I replace the {@myId} with the value that is in the variable then it does find the right node, but doign it this way produces nothing. I'm sure I'm missing something, or perhaps there is a different way to do it. The context is that there is related data under different top-level nodes that share the same id value so I need to get the related nodes in my template.
Ok, I finally figured it out. Silly problem really, I simply needed to leave out the quotes and the braces. One of those times when I *thought* that I'd already tried that. :D Oh, and I mistyped @myId in the first example, the code was actually $myId. ``` <xsl:variable name="myId" select="@id" /> <xsl value-of select="//Root/Some/Other/Path/Where[@id=$myId]/@Name" /> ```
5,415
<p>I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?</p>
[ { "answer_id": 73281, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 8, "selected": true, "text": "<pre><code>&gt;&gt;&gt; import struct\n&gt;&gt;&gt; struct.pack('f', 3.141592654)\nb'\\xdb\\x0fI@'\n&gt;&gt;&gt; struct.unpack('f...
2008/08/07
[ "https://Stackoverflow.com/questions/5415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
``` >>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@' ```
5,419
<p>When I try to print a Unicode string in a Windows console, I get an error .</p> <p><code>UnicodeEncodeError: 'charmap' codec can't encode character ....</code></p> <p>I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a <code>?</code> instead of failing in this situation?</p> <p><strong>Edit:</strong> I'm using Python 2.5.</p> <hr /> <p><strong>Note:</strong> @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!!</p> <p><a href="https://stackoverflow.com/a/32176732/610569">@JFSebastian answer</a> is more relevant as of today (6 Jan 2016).</p>
[ { "answer_id": 5430, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 6, "selected": true, "text": "<p><strong>Note:</strong> This answer is sort of outdated (from 2008). Please use the solution below with care!!</p>\n\n...
2008/08/07
[ "https://Stackoverflow.com/questions/5419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207/" ]
When I try to print a Unicode string in a Windows console, I get an error . `UnicodeEncodeError: 'charmap' codec can't encode character ....` I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this? Is there any way I can make Python automatically print a `?` instead of failing in this situation? **Edit:** I'm using Python 2.5. --- **Note:** @LasseV.Karlsen answer with the checkmark is sort of outdated (from 2008). Please use the solutions/answers/suggestions below with care!! [@JFSebastian answer](https://stackoverflow.com/a/32176732/610569) is more relevant as of today (6 Jan 2016).
**Note:** This answer is sort of outdated (from 2008). Please use the solution below with care!! --- Here is a page that details the problem and a solution (search the page for the text *Wrapping sys.stdout into an instance*): [PrintFails - Python Wiki](http://wiki.python.org/moin/PrintFails) Here's a code excerpt from that page: ``` $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 <type 'unicode'> 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None <type 'unicode'> 2 Б Б ``` There's some more information on that page, well worth a read.
5,425
<p>I have a page that is generated which inserts an HTML comment near the top of the page. Inside the comment is a *nix-style command.</p> <pre><code>&lt;!-- command --option value --option2 value2 --option3 --&gt; </code></pre> <p>This comment breaks the page completely. What is wrong with the comment to cause this to happen, and why is this the case?</p>
[ { "answer_id": 5441, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 6, "selected": true, "text": "<p>Comments in the <a href=\"http://www.w3.org/TR/REC-xml/#sec-comments\" rel=\"noreferrer\">XML Spec from the w3.org</a> :</p>\...
2008/08/07
[ "https://Stackoverflow.com/questions/5425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/219/" ]
I have a page that is generated which inserts an HTML comment near the top of the page. Inside the comment is a \*nix-style command. ``` <!-- command --option value --option2 value2 --option3 --> ``` This comment breaks the page completely. What is wrong with the comment to cause this to happen, and why is this the case?
Comments in the [XML Spec from the w3.org](http://www.w3.org/TR/REC-xml/#sec-comments) : > > For compatibility, the string "--" > (double-hyphen) MUST NOT occur within > comments. > > >
5,428
<p>Is it worth learning the convention or is it a bane to readability and maintainability?</p>
[ { "answer_id": 5439, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 7, "selected": true, "text": "<p>Considering that most people that use <em>Hungarian Notation</em> is following the misunderstood version of it, I'd s...
2008/08/07
[ "https://Stackoverflow.com/questions/5428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/659/" ]
Is it worth learning the convention or is it a bane to readability and maintainability?
Considering that most people that use *Hungarian Notation* is following the misunderstood version of it, I'd say it's pretty pointless. If you want to use the original definition of it, it might make more sense, but other than that it is mostly syntactic sugar. If you read the [Wikipedia article](http://en.wikipedia.org/wiki/Hungarian_notation) on the subject, you'll find two conflicting notations, *Systems Hungarian Notation* and *Apps Hungarian Notation*. The original, good, definition is the *Apps Hungarian Notation*, but most people use the *Systems Hungarian Notation*. As an example of the two, consider prefixing variables with l for length, a for area and v for volume. With such notation, the following expression makes sense: ``` int vBox = aBottom * lVerticalSide; ``` but this doesn't: ``` int aBottom = lSide1; ``` If you're mixing the prefixes, they're to be considered part of the equation, and volume = area \* length is fine for a box, but copying a length value into an area variable should raise some red flags. Unfortunately, the other notation is less useful, where people prefix the variable names with the type of the value, like this: ``` int iLength; int iVolume; int iArea; ``` some people use n for number, or i for integer, f for float, s for string etc. The original prefix was meant to be used to spot problems in equations, but has somehow devolved into making the code slightly easier to read since you don't have to go look for the variable declaration. With todays smart editors where you can simply hover over any variable to find the full type, and not just an abbreviation for it, this type of hungarian notation has lost a lot of its meaning. But, you should make up your own mind. All I can say is that I don't use either. --- **Edit** Just to add a short notice, while I don't use *Hungarian Notation*, I do use a prefix, and it's the underscore. I prefix all private fields of classes with a \_ and otherwise spell their names as I would a property, titlecase with the first letter uppercase.
5,459
<p>This is how I wanted to do it which would work in PHP 5.3.0+</p> <pre><code>&lt;?php class MyClass { const CONSTANT = 'Const var'; } $classname = 'MyClass'; echo $classname::CONSTANT; // As of PHP 5.3.0 ?&gt; </code></pre> <p>But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?</p>
[ { "answer_id": 5472, "author": "Juan", "author_id": 550, "author_profile": "https://Stackoverflow.com/users/550", "pm_score": -1, "selected": false, "text": "<p>If you absolutly need to access a constant like that, you can do this:</p>\n\n<pre><code>&lt;?php\nclass MyClass\n{\n co...
2008/08/07
[ "https://Stackoverflow.com/questions/5459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
This is how I wanted to do it which would work in PHP 5.3.0+ ``` <?php class MyClass { const CONSTANT = 'Const var'; } $classname = 'MyClass'; echo $classname::CONSTANT; // As of PHP 5.3.0 ?> ``` But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?
You can accomplish this without using [`eval`](http://php.net/manual/en/function.eval.php) in pre-5.3 code. Just use the [`constant`](http://php.net/manual/en/function.constant.php) function: ``` <?php class MyClass { const CONSTANT = 'Const var'; } $classname = 'MyClass'; echo constant("$classname::CONSTANT"); ?> ```
5,473
<p>Is it possible to undo the changes caused by the following command? If so, how?</p> <pre><code>git reset --hard HEAD~1 </code></pre>
[ { "answer_id": 6636, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 9, "selected": false, "text": "<p>What you want to do is to specify the sha1 of the commit you want to restore to. You can get the sha1 by examining the refl...
2008/08/07
[ "https://Stackoverflow.com/questions/5473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ]
Is it possible to undo the changes caused by the following command? If so, how? ``` git reset --hard HEAD~1 ```
Pat Notz is correct. You can get the commit back so long as it's been within a few days. git only garbage collects after about a month or so unless you explicitly tell it to remove newer blobs. ``` $ git init Initialized empty Git repository in .git/ $ echo "testing reset" > file1 $ git add file1 $ git commit -m 'added file1' Created initial commit 1a75c1d: added file1 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file1 $ echo "added new file" > file2 $ git add file2 $ git commit -m 'added file2' Created commit f6e5064: added file2 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file2 $ git reset --hard HEAD^ HEAD is now at 1a75c1d... added file1 $ cat file2 cat: file2: No such file or directory $ git reflog 1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEAD f6e5064... HEAD@{1}: commit: added file2 $ git reset --hard f6e5064 HEAD is now at f6e5064... added file2 $ cat file2 added new file ``` You can see in the example that the file2 was removed as a result of the hard reset, but was put back in place when I reset via the reflog.
5,482
<p>The ASP.NET AJAX <strong>ModalPopupExtender</strong> has <code>OnCancelScript</code> and <code>OnOkScript</code> properties, but it doesn't seem to have an <code>OnShowScript</code> property. I'd like to specify a javascript function to run each time the popup is shown.</p> <p>In past situations, I set the <code>TargetControlID</code> to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code.</p> <p>Anyone know of a way to do this?</p> <p>BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown</p>
[ { "answer_id": 5488, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 2, "selected": false, "text": "<p>If you are using a button or hyperlink or something to trigger the popup to show, could you also add an additional handler to ...
2008/08/07
[ "https://Stackoverflow.com/questions/5482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/698/" ]
The ASP.NET AJAX **ModalPopupExtender** has `OnCancelScript` and `OnOkScript` properties, but it doesn't seem to have an `OnShowScript` property. I'd like to specify a javascript function to run each time the popup is shown. In past situations, I set the `TargetControlID` to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code. Anyone know of a way to do this? BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown
hmmm... I'm *pretty sure* that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page\_load ``` function pageLoad() { var popup = $find('ModalPopupClientID'); popup.add_shown(SetFocus); } function SetFocus() { $get('TriggerClientId').focus(); } ``` i'm not sure tho if this will help you with calling it from the server side tho
5,511
<p>How are you handling the entry of numeric values in WPF applications?</p> <p>Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly.</p> <p>Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control?</p> <pre><code>private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e) { bool isNumPadNumeric = (e.Key &gt;= Key.NumPad0 &amp;&amp; e.Key &lt;= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key &gt;= Key.D0 &amp;&amp; e.Key &lt;= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) &amp;&amp; Keyboard.Modifiers != ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers != ModifierKeys.None &amp;&amp; Keyboard.Modifiers != ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled = !isControl &amp;&amp; !isNumeric &amp;&amp; !isNumPadNumeric; } </code></pre>
[ { "answer_id": 6174, "author": "tags2k", "author_id": 192, "author_profile": "https://Stackoverflow.com/users/192", "pm_score": 1, "selected": false, "text": "<p>Call me crazy, but why not put plus and minus buttons at either side of the TextBox control and simply prevent the TextBox fro...
2008/08/08
[ "https://Stackoverflow.com/questions/5511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
How are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control? ``` private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e) { bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers != ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers != ModifierKeys.None && Keyboard.Modifiers != ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled = !isControl && !isNumeric && !isNumPadNumeric; } ```
How about: ``` protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { e.Handled = !AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e); } private bool AreAllValidNumericChars(string str) { foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true; } ```
5,611
<p>I know that just using <code>rand()</code> is predictable, if you know what you're doing, and have access to the server.</p> <p>I have a project that is <strong>highly</strong> dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can generate a <em>better</em> random number.</p> <p>I used this to do a little test:</p> <pre><code>$i = 0; while($i &lt; 10000){ $rand = rand(0, 100); if(!isset($array[$rand])){ $array[$rand] = 1; } else { $array[$rand]++; } sort($array); $i++; } </code></pre> <p>I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated.</p>
[ { "answer_id": 5679, "author": "Justin Yost", "author_id": 657, "author_profile": "https://Stackoverflow.com/users/657", "pm_score": 1, "selected": false, "text": "<p>Variation on @KG, using the milliseconds since EPOCH as the seed for rand?</p>\n" }, { "answer_id": 5820, "au...
2008/08/08
[ "https://Stackoverflow.com/questions/5611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
I know that just using `rand()` is predictable, if you know what you're doing, and have access to the server. I have a project that is **highly** dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can generate a *better* random number. I used this to do a little test: ``` $i = 0; while($i < 10000){ $rand = rand(0, 100); if(!isset($array[$rand])){ $array[$rand] = 1; } else { $array[$rand]++; } sort($array); $i++; } ``` I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated.
Adding, multiplying, or truncating a poor random source will give you a poor random result. See [Introduction to Randomness and Random Numbers](http://random.org/randomness/) for an explanation. You're right about PHP rand() function. See the second figure on [Statistical Analysis](http://random.org/analysis/) for a striking illustration. (The first figure is striking, but it's been drawn by Scott Adams, not plotted with rand()). One solution is to use a true random generator such as [random.org](http://random.org/integers/). Another, if you're on Linux/BSD/etc. is to use [/dev/random](http://en.wikipedia.org/wiki/Urandom). If the randomness is mission critical, you will have to use a [hardware random generator](http://en.wikipedia.org/wiki/Hardware_random_number_generator).
5,694
<p>I got this error today when trying to open a Visual Studio 2008 <strong>project</strong> in Visual Studio 2005:</p> <blockquote> <p>The imported project "C:\Microsoft.CSharp.targets" was not found.</p> </blockquote>
[ { "answer_id": 5695, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 8, "selected": true, "text": "<p>Open your csproj file in notepad (or notepad++)\nFind the line: </p>\n\n<pre><code>&lt;Import Project=\"$(MSBuildToolsPath)\\Mi...
2008/08/08
[ "https://Stackoverflow.com/questions/5694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
I got this error today when trying to open a Visual Studio 2008 **project** in Visual Studio 2005: > > The imported project "C:\Microsoft.CSharp.targets" was not found. > > >
Open your csproj file in notepad (or notepad++) Find the line: ``` <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> ``` and change it to ``` <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> ```
5,727
<p>Why are pointers such a leading factor of confusion for many new, and even old, college level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?</p> <p>What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios.</p>
[ { "answer_id": 5728, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 5, "selected": false, "text": "<blockquote>\n <p>Why are pointers such a leading factor of confusion for many new, and even old, college level students in the C/...
2008/08/08
[ "https://Stackoverflow.com/questions/5727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/568/" ]
Why are pointers such a leading factor of confusion for many new, and even old, college level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level? What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill like scenarios.
Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block. I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained. I've added some Delphi code down below, and some comments where appropriate. I chose Delphi since my other main programming language, C#, does not exhibit things like memory leaks in the same way. If you only wish to learn the high-level concept of pointers, then you should ignore the parts labelled "Memory layout" in the explanation below. They are intended to give examples of what memory could look like after operations, but they are more low-level in nature. However, in order to accurately explain how buffer overruns really work, it was important that I added these diagrams. *Disclaimer: For all intents and purposes, this explanation and the example memory layouts are vastly simplified. There's more overhead and a lot more details you would need to know if you need to deal with memory on a low-level basis. However, for the intents of explaining memory and pointers, it is accurate enough.* --- Let's assume the THouse class used below looks like this: ``` type THouse = class private FName : array[0..9] of Char; public constructor Create(name: PChar); end; ``` When you initialize the house object, the name given to the constructor is copied into the private field FName. There is a reason it is defined as a fixed-size array. In memory, there will be some overhead associated with the house allocation, I'll illustrate this below like this: ``` ---[ttttNNNNNNNNNN]--- ^ ^ | | | +- the FName array | +- overhead ``` The "tttt" area is overhead, there will typically be more of this for various types of runtimes and languages, like 8 or 12 bytes. It is imperative that whatever values are stored in this area never gets changed by anything other than the memory allocator or the core system routines, or you risk crashing the program. --- **Allocate memory** Get an entrepreneur to build your house, and give you the address to the house. In contrast to the real world, memory allocation cannot be told where to allocate, but will find a suitable spot with enough room, and report back the address to the allocated memory. In other words, the entrepreneur will choose the spot. ``` THouse.Create('My house'); ``` Memory layout: ``` ---[ttttNNNNNNNNNN]--- 1234My house ``` --- **Keep a variable with the address** Write the address to your new house down on a piece of paper. This paper will serve as your reference to your house. Without this piece of paper, you're lost, and cannot find the house, unless you're already in it. ``` var h: THouse; begin h := THouse.Create('My house'); ... ``` Memory layout: ``` h v ---[ttttNNNNNNNNNN]--- 1234My house ``` --- **Copy pointer value** Just write the address on a new piece of paper. You now have two pieces of paper that will get you to the same house, not two separate houses. Any attempts to follow the address from one paper and rearrange the furniture at that house will make it seem that *the other house* has been modified in the same manner, unless you can explicitly detect that it's actually just one house. *Note* This is usually the concept that I have the most problem explaining to people, two pointers does not mean two objects or memory blocks. ``` var h1, h2: THouse; begin h1 := THouse.Create('My house'); h2 := h1; // copies the address, not the house ... ``` ``` h1 v ---[ttttNNNNNNNNNN]--- 1234My house ^ h2 ``` --- **Freeing the memory** Demolish the house. You can then later on reuse the paper for a new address if you so wish, or clear it to forget the address to the house that no longer exists. ``` var h: THouse; begin h := THouse.Create('My house'); ... h.Free; h := nil; ``` Here I first construct the house, and get hold of its address. Then I do something to the house (use it, the ... code, left as an exercise for the reader), and then I free it. Lastly I clear the address from my variable. Memory layout: ``` h <--+ v +- before free ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after free ---------------------- | (note, memory might still xx34My house <--+ contain some data) ``` --- **Dangling pointers** You tell your entrepreneur to destroy the house, but you forget to erase the address from your piece of paper. When later on you look at the piece of paper, you've forgotten that the house is no longer there, and goes to visit it, with failed results (see also the part about an invalid reference below). ``` var h: THouse; begin h := THouse.Create('My house'); ... h.Free; ... // forgot to clear h here h.OpenFrontDoor; // will most likely fail ``` Using `h` after the call to `.Free` *might* work, but that is just pure luck. Most likely it will fail, at a customers place, in the middle of a critical operation. ``` h <--+ v +- before free ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h <--+ v +- after free ---------------------- | xx34My house <--+ ``` As you can see, h still points to the remnants of the data in memory, but since it might not be complete, using it as before might fail. --- **Memory leak** You lose the piece of paper and cannot find the house. The house is still standing somewhere though, and when you later on want to construct a new house, you cannot reuse that spot. ``` var h: THouse; begin h := THouse.Create('My house'); h := THouse.Create('My house'); // uh-oh, what happened to our first house? ... h.Free; h := nil; ``` Here we overwrote the contents of the `h` variable with the address of a new house, but the old one is still standing... somewhere. After this code, there is no way to reach that house, and it will be left standing. In other words, the allocated memory will stay allocated until the application closes, at which point the operating system will tear it down. Memory layout after first allocation: ``` h v ---[ttttNNNNNNNNNN]--- 1234My house ``` Memory layout after second allocation: ``` h v ---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house ``` A more common way to get this method is just to forget to free something, instead of overwriting it as above. In Delphi terms, this will occur with the following method: ``` procedure OpenTheFrontDoorOfANewHouse; var h: THouse; begin h := THouse.Create('My house'); h.OpenFrontDoor; // uh-oh, no .Free here, where does the address go? end; ``` After this method has executed, there's no place in our variables that the address to the house exists, but the house is still out there. Memory layout: ``` h <--+ v +- before losing pointer ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after losing pointer ---[ttttNNNNNNNNNN]--- | 1234My house <--+ ``` As you can see, the old data is left intact in memory, and will not be reused by the memory allocator. The allocator keeps track of which areas of memory has been used, and will not reuse them unless you free it. --- **Freeing the memory but keeping a (now invalid) reference** Demolish the house, erase one of the pieces of paper but you also have another piece of paper with the old address on it, when you go to the address, you won't find a house, but you might find something that resembles the ruins of one. Perhaps you will even find a house, but it is not the house you were originally given the address to, and thus any attempts to use it as though it belongs to you might fail horribly. Sometimes you might even find that a neighbouring address has a rather big house set up on it that occupies three address (Main Street 1-3), and your address goes to the middle of the house. Any attempts to treat that part of the large 3-address house as a single small house might also fail horribly. ``` var h1, h2: THouse; begin h1 := THouse.Create('My house'); h2 := h1; // copies the address, not the house ... h1.Free; h1 := nil; h2.OpenFrontDoor; // uh-oh, what happened to our house? ``` Here the house was torn down, through the reference in `h1`, and while `h1` was cleared as well, `h2` still has the old, out-of-date, address. Access to the house that is no longer standing might or might not work. This is a variation of the dangling pointer above. See its memory layout. --- **Buffer overrun** You move more stuff into the house than you can possibly fit, spilling into the neighbours house or yard. When the owner of that neighbouring house later on comes home, he'll find all sorts of things he'll consider his own. This is the reason I chose a fixed-size array. To set the stage, assume that the second house we allocate will, for some reason, be placed before the first one in memory. In other words, the second house will have a lower address than the first one. Also, they're allocated right next to each other. Thus, this code: ``` var h1, h2: THouse; begin h1 := THouse.Create('My house'); h2 := THouse.Create('My other house somewhere'); ^-----------------------^ longer than 10 characters 0123456789 <-- 10 characters ``` Memory layout after first allocation: ``` h1 v -----------------------[ttttNNNNNNNNNN] 5678My house ``` Memory layout after second allocation: ``` h2 h1 v v ---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN] 1234My other house somewhereouse ^---+--^ | +- overwritten ``` The part that will most often cause crash is when you overwrite important parts of the data you stored that really should not be randomly changed. For instance it might not be a problem that parts of the name of the h1-house was changed, in terms of crashing the program, but overwriting the overhead of the object will most likely crash when you try to use the broken object, as will overwriting links that is stored to other objects in the object. --- **Linked lists** When you follow an address on a piece of paper, you get to a house, and at that house there is another piece of paper with a new address on it, for the next house in the chain, and so on. ``` var h1, h2: THouse; begin h1 := THouse.Create('Home'); h2 := THouse.Create('Cabin'); h1.NextHouse := h2; ``` Here we create a link from our home house to our cabin. We can follow the chain until a house has no `NextHouse` reference, which means it's the last one. To visit all our houses, we could use the following code: ``` var h1, h2: THouse; h: THouse; begin h1 := THouse.Create('Home'); h2 := THouse.Create('Cabin'); h1.NextHouse := h2; ... h := h1; while h <> nil do begin h.LockAllDoors; h.CloseAllWindows; h := h.NextHouse; end; ``` Memory layout (added NextHouse as a link in the object, noted with the four LLLL's in the below diagram): ``` h1 h2 v v ---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home + 5678Cabin + | ^ | +--------+ * (no link) ``` --- **In basic terms, what is a memory address?** A memory address is in basic terms just a number. If you think of memory as a big array of bytes, the very first byte has the address 0, the next one the address 1 and so on upwards. This is simplified, but good enough. So this memory layout: ``` h1 h2 v v ---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house ``` Might have these two address (the leftmost - is address 0): * h1 = 4 * h2 = 23 Which means that our linked list above might actuall look like this: ``` h1 (=4) h2 (=28) v v ---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home 0028 5678Cabin 0000 | ^ | +--------+ * (no link) ``` It is typical to store an address that "points nowhere" as a zero-address. --- **In basic terms, what is a pointer?** A pointer is just a variable holding a memory address. You can typically ask the programming language to give you its number, but most programming languages and runtimes tries to hide the fact that there is a number beneath, just because the number itself does not really hold any meaning to you. It is best to think of a pointer as a black box, ie. you don't really know or care about how it is actually implemented, just as long as it works.
5,821
<p>How do I escape the underscore character?</p> <p>I am writing something like the following where clause and want to be able to find actual entries with _d at the end.</p> <pre><code>Where Username Like '%_d' </code></pre>
[ { "answer_id": 5822, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 10, "selected": true, "text": "<p><a href=\"https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-ver15#usin...
2008/08/08
[ "https://Stackoverflow.com/questions/5821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
How do I escape the underscore character? I am writing something like the following where clause and want to be able to find actual entries with \_d at the end. ``` Where Username Like '%_d' ```
[T-SQL Reference for LIKE](https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql?view=sql-server-ver15#using-wildcard-characters-as-literals): > > You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters. > > > For your case: ``` ... LIKE '%[_]d' ```
5,846
<p>How do I turn the following 2 queries into 1 query</p> <pre><code>$sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db-&gt;sql_query($sql); $level = (int) $db-&gt;sql_fetchfield('level'); $db-&gt;sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db-&gt;sql_query($sql); $db-&gt;sql_freeresult($result); </code></pre> <p>I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query.</p> <p>Edit: <code>$id</code> has already been forced to be an integer, thus no escaping is needed this time.</p>
[ { "answer_id": 5848, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 6, "selected": true, "text": "<p>I get downmodded for this?</p>\n\n<pre><code>$sql = \"UPDATE skills SET level = level+1 WHERE id = $id\";\n$result = $db-&gt;sql_...
2008/08/08
[ "https://Stackoverflow.com/questions/5846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
How do I turn the following 2 queries into 1 query ``` $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db->sql_query($sql); $level = (int) $db->sql_fetchfield('level'); $db->sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db->sql_query($sql); $db->sql_freeresult($result); ``` I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query. Edit: `$id` has already been forced to be an integer, thus no escaping is needed this time.
I get downmodded for this? ``` $sql = "UPDATE skills SET level = level+1 WHERE id = $id"; $result = $db->sql_query($sql); $db->sql_freeresult($result); ``` In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL. In the general case, you should not use NULL to represent zero. Incrementing NULL *should* give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use ``` $sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id"; ``` ...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include ``` level INT DEFAULT '0' NOT NULL ``` in case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL.
5,857
<p>I have a page upon which a user can choose up to many different paragraphs. When the link is clicked (or button), an email will open up and put all those paragraphs into the body of the email, address it, and fill in the subject. However, the text can be too long for a mailto link.</p> <p>Any way around this?</p> <hr> <p>We were thinking about having an SP from the SQL Server do it but the user needs a nice way of 'seeing' the email before they blast 50 executive level employees with items that shouldn't be sent...and of course there's the whole thing about doing IT for IT rather than doing software programming. 80(</p> <p>When you build stuff for IT, it doesn't (some say shouldn't) have to be pretty just functional. In other words, this isn't the dogfood we wake it's just the dog food we have to eat.</p> <hr> <p>We started talking about it and decided that the 'mail form' would give us exactly what we are looking for.</p> <ol> <li>A very different look to let the user know that the gun is loaded and aimed.</li> <li>The ability to change/add text to the email.</li> <li>Send a copy to themselves or not.</li> <li>Can be coded quickly.</li> </ol>
[ { "answer_id": 5860, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": true, "text": "<p>By putting the data into a form, I was able to make the body around 1800 characters long before the form stopped work...
2008/08/08
[ "https://Stackoverflow.com/questions/5857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I have a page upon which a user can choose up to many different paragraphs. When the link is clicked (or button), an email will open up and put all those paragraphs into the body of the email, address it, and fill in the subject. However, the text can be too long for a mailto link. Any way around this? --- We were thinking about having an SP from the SQL Server do it but the user needs a nice way of 'seeing' the email before they blast 50 executive level employees with items that shouldn't be sent...and of course there's the whole thing about doing IT for IT rather than doing software programming. 80( When you build stuff for IT, it doesn't (some say shouldn't) have to be pretty just functional. In other words, this isn't the dogfood we wake it's just the dog food we have to eat. --- We started talking about it and decided that the 'mail form' would give us exactly what we are looking for. 1. A very different look to let the user know that the gun is loaded and aimed. 2. The ability to change/add text to the email. 3. Send a copy to themselves or not. 4. Can be coded quickly.
By putting the data into a form, I was able to make the body around 1800 characters long before the form stopped working. The code looked like this: ``` <form action="mailto:youremail@domain.com"> <input type="hidden" name="Subject" value="Email subject"> <input type="hidden" name="Body" value="Email body"> <input type="submit"> </form> ``` --- **Edit**: The best way to send emails from a web application is of course to do just that, send it directly from the web application, instead of relying on the users mailprogram. As you've discovered, the protocol for sending information to that program is limited, but with a server-based solution you would of course not have those limitations.
5,863
<p>I'm just getting into creating some WCF services, but I have a requirement to make them backward compatible for legacy (.NET 1.1 and 2.0) client applications. </p> <p>I've managed to get the services to run correctly for 3.0 and greater clients, but when I publish the services using a basicHttpBinding endpoint (which I believe is required for the compatibility I need), the service refactors my method signatures. e.g.</p> <pre><code>public bool MethodToReturnTrue(string seedValue); </code></pre> <p>appears to the client apps as</p> <pre><code>public void MethodToReturnTrue(string seedValue, out bool result, out bool MethodToReturnTrueResultSpecified); </code></pre> <p>I've tried every configuration parameter I can think of in the app.config for my self-hosting console app, but I can't seem to make this function as expected. I suppose this might lead to the fact that my expectations are flawed, but I'd be surprised that a WCF service is incapable of handling a bool return type to a down-level client.</p> <p>My current app.config looks like this.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;system.serviceModel&gt; &lt;services&gt; &lt;service behaviorConfiguration="MyServiceTypeBehaviors" Name="MyCompany.Services.CentreService.CentreService"&gt; &lt;clear /&gt; &lt;endpoint address="http://localhost:8080/CSMEX" binding="basicHttpBinding" bindingConfiguration="" contract="IMetadataExchange" /&gt; &lt;endpoint address="http://localhost:8080/CentreService" binding="basicHttpBinding" bindingName="Compatible" name="basicEndpoint" contract="MyCompany.Services.CentreService.ICentreService" /&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyServiceTypeBehaviors" &gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; &lt;/configuration&gt; </code></pre> <p>Can anyone advise, please?</p>
[ { "answer_id": 6997, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 2, "selected": false, "text": "<p>Ah, this is killing me! I did this at work about 3 months ago, and now I can't remember all the details.</p>\n\n<p>I do...
2008/08/08
[ "https://Stackoverflow.com/questions/5863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/377/" ]
I'm just getting into creating some WCF services, but I have a requirement to make them backward compatible for legacy (.NET 1.1 and 2.0) client applications. I've managed to get the services to run correctly for 3.0 and greater clients, but when I publish the services using a basicHttpBinding endpoint (which I believe is required for the compatibility I need), the service refactors my method signatures. e.g. ``` public bool MethodToReturnTrue(string seedValue); ``` appears to the client apps as ``` public void MethodToReturnTrue(string seedValue, out bool result, out bool MethodToReturnTrueResultSpecified); ``` I've tried every configuration parameter I can think of in the app.config for my self-hosting console app, but I can't seem to make this function as expected. I suppose this might lead to the fact that my expectations are flawed, but I'd be surprised that a WCF service is incapable of handling a bool return type to a down-level client. My current app.config looks like this. ``` <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.serviceModel> <services> <service behaviorConfiguration="MyServiceTypeBehaviors" Name="MyCompany.Services.CentreService.CentreService"> <clear /> <endpoint address="http://localhost:8080/CSMEX" binding="basicHttpBinding" bindingConfiguration="" contract="IMetadataExchange" /> <endpoint address="http://localhost:8080/CentreService" binding="basicHttpBinding" bindingName="Compatible" name="basicEndpoint" contract="MyCompany.Services.CentreService.ICentreService" /> </service> </services> <behaviors> <serviceBehaviors> <behavior name="MyServiceTypeBehaviors" > <serviceMetadata httpGetEnabled="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> </configuration> ``` Can anyone advise, please?
OK, we needed to resolve this issue in the short term, and so we came up with the idea of a "interop", or compatibility layer. Baiscally, all we did was added a traditional ASMX web service to the project, and called the WCF service from that using native WCF calls. We were then able to return the appropriate types back to the client applications without a significant amount of re-factoring work. I know it was a hacky solution, but it was the best option we had with such a large legacy code-base. And the added bonus is that it actually works surprisingly well. :)
5,876
<p>I use <a href="http://www.thekelleys.org.uk/dnsmasq/doc.html" rel="nofollow noreferrer">dnsmasq</a> to resolve DNS queries on my home network. Unfortunately, if a domain name is not known, it will append my own domain name to the request which means that I always end up viewing my own site in a browser.</p> <p>For example, if I enter <a href="http://dlksfhoiahdsfiuhsdf.com" rel="nofollow noreferrer">http://dlksfhoiahdsfiuhsdf.com</a> in a browser, I end up viewing my own site with that URL. If I try something like:</p> <pre><code>host dlksfhoiahdsfiuhsdf.com </code></pre> <p>Instead of the expected:</p> <pre><code>Host dlksfhoiahdsfiuhsdf.com not found: 3(NXDOMAIN) </code></pre> <p>I get this:</p> <pre><code>dlksfhoiahdsfiuhsdf.com.mydomainname.com has address W.X.Y.Z. </code></pre> <p>Clearly, dnsmasq is appending my domain name to impossible name requests in an effort to resolve them, but I'd rather see the not found error instead.</p> <p>I've tried playing with the <em>expand-hosts</em> and <em>domain</em> configuration settings, but to no avail. Is there anything else I can try?</p>
[ { "answer_id": 5912, "author": "saint_groceon", "author_id": 59, "author_profile": "https://Stackoverflow.com/users/59", "pm_score": 0, "selected": false, "text": "<p>I tried removing <em>domain-needed</em> from my own configuration to replicate your issue and it did not produce this beh...
2008/08/08
[ "https://Stackoverflow.com/questions/5876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ]
I use [dnsmasq](http://www.thekelleys.org.uk/dnsmasq/doc.html) to resolve DNS queries on my home network. Unfortunately, if a domain name is not known, it will append my own domain name to the request which means that I always end up viewing my own site in a browser. For example, if I enter <http://dlksfhoiahdsfiuhsdf.com> in a browser, I end up viewing my own site with that URL. If I try something like: ``` host dlksfhoiahdsfiuhsdf.com ``` Instead of the expected: ``` Host dlksfhoiahdsfiuhsdf.com not found: 3(NXDOMAIN) ``` I get this: ``` dlksfhoiahdsfiuhsdf.com.mydomainname.com has address W.X.Y.Z. ``` Clearly, dnsmasq is appending my domain name to impossible name requests in an effort to resolve them, but I'd rather see the not found error instead. I've tried playing with the *expand-hosts* and *domain* configuration settings, but to no avail. Is there anything else I can try?
try querying with a trailing dot to explicitly set the root: ``` host dlksfhoiahdsfiuhsdf.com. ```
5,909
<p>I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server?</p> <pre><code>import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the .TXT / .ZIP files fnames = re.findall('^.*&lt;a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE) for fname in fnames: print fname, "..." f = urllib.urlopen(url + "/" + fname) #### Here I want to check the filesize to download or not #### file = f.read() f.close() f = open (fname, "w") f.write (file) f.close() </code></pre> <hr> <p>@Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. </p> <p>Examples:</p> <pre><code>Local Size Server Size 2.223.533 2.115.516 664.603 662.121 </code></pre> <p>It has anything to do with the CR/LF conversion?</p>
[ { "answer_id": 5927, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 3, "selected": false, "text": "<p>The size of the file is sent as the Content-Length header. Here is how to get it with urllib:</p>\n\n<pre><code>...
2008/08/08
[ "https://Stackoverflow.com/questions/5909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? ``` import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the .TXT / .ZIP files fnames = re.findall('^.*<a href="(\w+(?:\.txt|.zip)?)".*$', html, re.MULTILINE) for fname in fnames: print fname, "..." f = urllib.urlopen(url + "/" + fname) #### Here I want to check the filesize to download or not #### file = f.read() f.close() f = open (fname, "w") f.write (file) f.close() ``` --- @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: ``` Local Size Server Size 2.223.533 2.115.516 664.603 662.121 ``` It has anything to do with the CR/LF conversion?
I have reproduced what you are seeing: ``` import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "r") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "w") f.write(site.read()) site.close() f.close() f = open("out.txt", "r") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size ``` Outputs this: ``` opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16861 ``` What am I doing wrong here? Is os.stat().st\_size not returning the correct size? --- Edit: OK, I figured out what the problem was: ``` import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "rb") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "wb") f.write(site.read()) site.close() f.close() f = open("out.txt", "rb") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size ``` this outputs: ``` $ python test.py opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16535 ``` Make sure you are opening both files for binary read/write. ``` // open for binary write open(filename, "wb") // open for binary read open(filename, "rb") ```
5,913
<p>This gets the value of whatever is selected in my dropdown menu.</p> <pre><code>document.getElementById('newSkill').value </code></pre> <p>I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at <a href="http://w3schools.com/" rel="noreferrer">W3Schools</a> but that didn't have the answer, does anybody here know?</p> <p>For those not sure, here's the HTML for a drop down box.</p> <pre><code>&lt;select name="newSkill" id="newSkill"&gt; &lt;option value="1"&gt;A skill&lt;/option&gt; &lt;option value="2"&gt;Another skill&lt;/option&gt; &lt;option value="3"&gt;Yet another skill&lt;/option&gt; &lt;/select&gt; </code></pre>
[ { "answer_id": 5921, "author": "Brian Childress", "author_id": 721, "author_profile": "https://Stackoverflow.com/users/721", "pm_score": 1, "selected": false, "text": "<p>Does this get the correct answer? </p>\n\n<pre><code>document.getElementById(\"newSkill\").innerHTML\n</code></pre>\n...
2008/08/08
[ "https://Stackoverflow.com/questions/5913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
This gets the value of whatever is selected in my dropdown menu. ``` document.getElementById('newSkill').value ``` I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at [W3Schools](http://w3schools.com/) but that didn't have the answer, does anybody here know? For those not sure, here's the HTML for a drop down box. ``` <select name="newSkill" id="newSkill"> <option value="1">A skill</option> <option value="2">Another skill</option> <option value="3">Yet another skill</option> </select> ```
Based on your example HTML code, here's one way to get the displayed text of the currently selected option: ``` var skillsSelect = document.getElementById("newSkill"); var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text; ```
5,916
<p>For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)</p>
[ { "answer_id": 5923, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 2, "selected": false, "text": "<p>I use <a href=\"http://macromates.com/\" rel=\"nofollow noreferrer\">Textmate</a> (Mac only) which has Code folding a...
2008/08/08
[ "https://Stackoverflow.com/questions/5916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/396/" ]
For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)
9 out of 10 times, code folding means that you have failed to use the [SoC principle](http://en.wikipedia.org/wiki/Separation_of_concerns) for what its worth. I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up. It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method. Whenever you can, pull some code out of the main class, and into a helper or factory class. ``` foreach (var item in Items) { //.. 100 lines of validation and data logic.. } ``` is not as readable as ``` foreach (var item in Items) { if (ValidatorClass.Validate(item)) RepositoryClass.Update(item); } ``` My $0.02 anyways.
5,949
<p>I've always preferred to use long integers as primary keys in databases, for simplicity and (assumed) speed. But when using a <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" rel="noreferrer">REST</a> or Rails-like URL scheme for object instances, I'd then end up with URLs like this:</p> <pre><code>http://example.com/user/783 </code></pre> <p>And then the assumption is that there are also users with IDs of 782, 781, ..., 2, and 1. Assuming that the web app in question is secure enough to prevent people entering other numbers to view other users without authorization, a simple sequentially-assigned surrogate key also "leaks" the total number of instances (older than this one), in this case users, which might be privileged information. (For instance, I am user #726 in stackoverflow.)</p> <p>Would a <a href="http://en.wikipedia.org/wiki/Uuid" rel="noreferrer">UUID</a>/GUID be a better solution? Then I could set up URLs like this:</p> <pre><code>http://example.com/user/035a46e0-6550-11dd-ad8b-0800200c9a66 </code></pre> <p>Not exactly succinct, but there's less implied information about users on display. Sure, it smacks of "security through obscurity" which is no substitute for proper security, but it seems at least a little more secure.</p> <p>Is that benefit worth the cost and complexity of implementing UUIDs for web-addressable object instances? I think that I'd still want to use integer columns as database PKs just to speed up joins.</p> <p>There's also the question of in-database representation of UUIDs. I know MySQL stores them as 36-character strings. Postgres seems to have a more efficient internal representation (128 bits?) but I haven't tried it myself. Anyone have any experience with this?</p> <hr> <p>Update: for those who asked about just using the user name in the URL (e.g., <a href="http://example.com/user/yukondude" rel="noreferrer">http://example.com/user/yukondude</a>), that works fine for object instances with names that are unique, but what about the zillions of web app objects that can really only be identified by number? Orders, transactions, invoices, duplicate image names, stackoverflow questions, ...</p>
[ { "answer_id": 5958, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "<p>I work with a student management system which uses UUID's in the form of an integer. They have a table which hold the next...
2008/08/08
[ "https://Stackoverflow.com/questions/5949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ]
I've always preferred to use long integers as primary keys in databases, for simplicity and (assumed) speed. But when using a [REST](http://en.wikipedia.org/wiki/Representational_State_Transfer) or Rails-like URL scheme for object instances, I'd then end up with URLs like this: ``` http://example.com/user/783 ``` And then the assumption is that there are also users with IDs of 782, 781, ..., 2, and 1. Assuming that the web app in question is secure enough to prevent people entering other numbers to view other users without authorization, a simple sequentially-assigned surrogate key also "leaks" the total number of instances (older than this one), in this case users, which might be privileged information. (For instance, I am user #726 in stackoverflow.) Would a [UUID](http://en.wikipedia.org/wiki/Uuid)/GUID be a better solution? Then I could set up URLs like this: ``` http://example.com/user/035a46e0-6550-11dd-ad8b-0800200c9a66 ``` Not exactly succinct, but there's less implied information about users on display. Sure, it smacks of "security through obscurity" which is no substitute for proper security, but it seems at least a little more secure. Is that benefit worth the cost and complexity of implementing UUIDs for web-addressable object instances? I think that I'd still want to use integer columns as database PKs just to speed up joins. There's also the question of in-database representation of UUIDs. I know MySQL stores them as 36-character strings. Postgres seems to have a more efficient internal representation (128 bits?) but I haven't tried it myself. Anyone have any experience with this? --- Update: for those who asked about just using the user name in the URL (e.g., <http://example.com/user/yukondude>), that works fine for object instances with names that are unique, but what about the zillions of web app objects that can really only be identified by number? Orders, transactions, invoices, duplicate image names, stackoverflow questions, ...
I can't say about the web side of your question. But uuids are great for n-tier applications. PK generation can be decentralized: each client generates it's own pk without risk of collision. And the speed difference is generally small. Make sure your database supports an efficient storage datatype (16 bytes, 128 bits). At the very least you can encode the uuid string in base64 and use char(22). I've used them extensively with Firebird and do recommend.
5,966
<p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py" rel="noreferrer">here</a>.</p> <p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p> <pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1 </code></pre> <p>What is the "best" way to abstract this data within the <code>Tvdb()</code> class?</p> <p>I originally used a extended <code>Dict()</code> that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p> <p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p> <p>This worked okay, but there was no easy way of checking if <code>x[3][24]</code> was supposed to exist or not (so I couldn't raise the season_not_found exception).</p> <p>Currently it's using four classes: <code>ShowContainer</code>, <code>Show</code>, <code>Season</code> and <code>Episode</code>. Each one is a very basic dict, which I can easily add extra functionality in (the <code>search()</code> function on <code>Show()</code> for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code>.</p> <p>This works mostly fine, I can check in Shows if it has that season in it's <code>self.data</code> dict, if not, <code>raise season_not_found</code>. I can also check in <code>Season()</code> if it has that episode and so on.</p> <p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <code>__getitem__</code> and <code>__setitem__</code> functions, it's easy to accidentally recursively call <code>__getitem__</code> (so I'm not sure if extending the <code>Dict</code> class will cause problems).</p> <p>The other slight problem is adding data into the dict is a lot more work than the old <code>Dict</code> method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See <code>_setItem</code> and <code>_setData</code>. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly... Elegant.</p> <p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the <code>ShowContainer</code>/etc classes with <code>Dict</code> cause problems?</p>
[ { "answer_id": 6125, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 2, "selected": false, "text": "<p>Why not use SQLite? There is good support in Python and you can write SQL queries to get the data out. Here is t...
2008/08/08
[ "https://Stackoverflow.com/questions/5966", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
Basically, I've written an API to www.thetvdb.com in Python. The current code can be found [here](http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py). It grabs data from the API as requested, and has to store the data somehow, and make it available by doing: ``` print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1 ``` What is the "best" way to abstract this data within the `Tvdb()` class? I originally used a extended `Dict()` that automatically created sub-dicts (so you could do `x[1][2][3][4] = "something"` without having to do `if x[1].has_key(2): x[1][2] = []` and so on) Then I just stored the data by doing `self.data[show_id][season_number][episode_number][attribute_name] = "something"` This worked okay, but there was no easy way of checking if `x[3][24]` was supposed to exist or not (so I couldn't raise the season\_not\_found exception). Currently it's using four classes: `ShowContainer`, `Show`, `Season` and `Episode`. Each one is a very basic dict, which I can easily add extra functionality in (the `search()` function on `Show()` for example). Each has a `__setitem__`, `__getitem_` and `has_key`. This works mostly fine, I can check in Shows if it has that season in it's `self.data` dict, if not, `raise season_not_found`. I can also check in `Season()` if it has that episode and so on. The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the `__getitem__` and `__setitem__` functions, it's easy to accidentally recursively call `__getitem__` (so I'm not sure if extending the `Dict` class will cause problems). The other slight problem is adding data into the dict is a lot more work than the old `Dict` method (which was `self.data[seas_no][ep_no]['attribute'] = 'something'`). See `_setItem` and `_setData`. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly... Elegant. I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the `ShowContainer`/etc classes with `Dict` cause problems?
OK, what you need is `classobj` from new module. That would allow you to construct exception classes dynamically (`classobj` takes a string as an argument for the class name). ``` import new myexc=new.classobj("ExcName",(Exception,),{}) i=myexc("This is the exc msg!") raise i ``` this gives you: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> __main__.ExcName: This is the exc msg! ``` remember that you can always get the class name through: ``` self.__class__.__name__ ``` So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception. P.S. - you can also raise strings, but this is deprecated. ``` raise(self.__class__.__name__+"Exception") ```
5,982
<p>Does anyone know why when using BindingUtils on the selectedItem property of a ComboBox you get the following warning? Any ideas how to resolve the issue?</p> <p>The binding still works properly, but it would be nice to get rid of the warning.</p> <pre><code>warning: multiple describeType entries for 'selectedItem' on type 'mx.controls::ComboBox': &lt;accessor name="selectedItem" access="readwrite" type="Object" declaredBy="mx.controls::ComboBase"&gt; &lt;metadata name="Bindable"&gt; &lt;arg key="" value="valueCommit"/&gt; &lt;/metadata&gt; </code></pre>
[ { "answer_id": 14237, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 0, "selected": false, "text": "<p>Here is the code. It is basically a copy of BindingUtils.bindProperty that is setup for a ComboBox so that both the combo...
2008/08/08
[ "https://Stackoverflow.com/questions/5982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22/" ]
Does anyone know why when using BindingUtils on the selectedItem property of a ComboBox you get the following warning? Any ideas how to resolve the issue? The binding still works properly, but it would be nice to get rid of the warning. ``` warning: multiple describeType entries for 'selectedItem' on type 'mx.controls::ComboBox': <accessor name="selectedItem" access="readwrite" type="Object" declaredBy="mx.controls::ComboBase"> <metadata name="Bindable"> <arg key="" value="valueCommit"/> </metadata> ```
It is better to override the property in question and declare it final.
6,007
<p>How do I make <a href="http://logging.apache.org/log4net/index.html" rel="noreferrer">Log4net</a> only log Info level logs? Is that even possible? Can you only set a threshold? </p> <p>This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info?</p> <pre class="lang-xml prettyprint-override"><code>&lt;logger name="BrokerCollection.Model.XmlDocumentCreationTask"&gt; &lt;appender-ref ref="SubmissionAppender"/&gt; &lt;level value="Info" /&gt; &lt;/logger&gt; </code></pre>
[ { "answer_id": 10383, "author": "Brandon Wood", "author_id": 423, "author_profile": "https://Stackoverflow.com/users/423", "pm_score": 8, "selected": true, "text": "<p>Within the definition of the appender, I believe you can do something like this:</p>\n\n<pre class=\"lang-xml prettyprin...
2008/08/08
[ "https://Stackoverflow.com/questions/6007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
How do I make [Log4net](http://logging.apache.org/log4net/index.html) only log Info level logs? Is that even possible? Can you only set a threshold? This is what I have, and it logs Info and above as I would expect. Is there anything i can do to make it only log info? ```xml <logger name="BrokerCollection.Model.XmlDocumentCreationTask"> <appender-ref ref="SubmissionAppender"/> <level value="Info" /> </logger> ```
Within the definition of the appender, I believe you can do something like this: ```xml <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender"> <filter type="log4net.Filter.LevelRangeFilter"> <param name="LevelMin" value="INFO"/> <param name="LevelMax" value="INFO"/> </filter> ... </appender> ```
6,076
<p>I am building a server control that will search our db and return results. The server control is contains an ASP:Panel. I have set the default button on the panel equal to my button id and have set the form default button equal to my button id.</p> <p>On the Panel:</p> <pre><code> MyPanel.DefaultButton = SearchButton.ID</code></pre> <p>On the Control:</p> <pre><code>Me.Page.Form.DefaultButton = SearchButton.UniqueID </code></pre> <p>Works fine in IE &amp; Safari I can type a search term and hit the enter key and it searches fine. If I do it in Firefox I get an alert box saying &quot;Object reference not set to an instance of an a object.</p> <p>Anyone run across this before?</p>
[ { "answer_id": 6096, "author": "Otto", "author_id": 519, "author_profile": "https://Stackoverflow.com/users/519", "pm_score": 2, "selected": false, "text": "<p>Is SearchButton a LinkButton? If so, the javascript that is written to the browser doesn't work properly.</p>\n\n<p>Here is a g...
2008/08/08
[ "https://Stackoverflow.com/questions/6076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225/" ]
I am building a server control that will search our db and return results. The server control is contains an ASP:Panel. I have set the default button on the panel equal to my button id and have set the form default button equal to my button id. On the Panel: ``` MyPanel.DefaultButton = SearchButton.ID ``` On the Control: ``` Me.Page.Form.DefaultButton = SearchButton.UniqueID ``` Works fine in IE & Safari I can type a search term and hit the enter key and it searches fine. If I do it in Firefox I get an alert box saying "Object reference not set to an instance of an a object. Anyone run across this before?
Ends up this resolved my issue: ``` SearchButton.UseSubmitBehavior = False ```
6,110
<p>I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations.</p> <p>For example, here are some records that describe the same customer:</p> <p><strong>Location Table</strong></p> <pre><code> ID Location_Name 1 TownShop#1 2 Town Shop - Loc 2 3 The Town Shop 4 TTS - Someplace 5 Town Shop,the 3 6 Toen Shop4 </code></pre> <p>My goal is to make it look like:</p> <p><strong>Location Table</strong></p> <pre><code> ID Company_ID Location_Name 1 1 Town Shop#1 2 1 Town Shop - Loc 2 3 1 The Town Shop 4 1 TTS - Someplace 5 1 Town Shop,the 3 6 1 Toen Shop4 </code></pre> <p><strong>Company Table</strong></p> <pre><code> Company_ID Company_Name 1 The Town Shop </code></pre> <p>There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations.</p> <p>Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand.</p> <p>Any suggestions on how I can approach this is appreciated.</p> <p><strong>@Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row.</strong></p> <p><strong>@yukondude, Your step 4 is the heart of my question.</strong></p>
[ { "answer_id": 6119, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "<p>I've had to do this before. The only real way to do it is to manually match up the various locations. Use your database's conso...
2008/08/08
[ "https://Stackoverflow.com/questions/6110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/754/" ]
I've been handed a table with about 18000 rows. Each record describes the location of one customer. The issue is, that when the person created the table, they did not add a field for "Company Name", only "Location Name," and one company can have many locations. For example, here are some records that describe the same customer: **Location Table** ``` ID Location_Name 1 TownShop#1 2 Town Shop - Loc 2 3 The Town Shop 4 TTS - Someplace 5 Town Shop,the 3 6 Toen Shop4 ``` My goal is to make it look like: **Location Table** ``` ID Company_ID Location_Name 1 1 Town Shop#1 2 1 Town Shop - Loc 2 3 1 The Town Shop 4 1 TTS - Someplace 5 1 Town Shop,the 3 6 1 Toen Shop4 ``` **Company Table** ``` Company_ID Company_Name 1 The Town Shop ``` There is no "Company" table, I will have to generate the Company Name list from the most descriptive or best Location Name that represents the multiple locations. Currently I am thinking I need to generate a list of Location Names that are similar, and then and go through that list by hand. Any suggestions on how I can approach this is appreciated. **@Neall, Thank you for your statement, but unfortunately, each location name is distinct, there are no duplicate location names, only similar. So in the results from your statement "repcount" is 1 in each row.** **@yukondude, Your step 4 is the heart of my question.**
Please update the question, do you have a list of CompanyNames available to you? I ask because you maybe able to use Levenshtein algo to find a relationship between your list of CompanyNames and LocationNames. --- **Update** > > There is not a list of Company Names, I will have to generate the company name from the most descriptive or best Location Name that represents the multiple locations. > > > Okay... try this: 1. Build a list of candidate CompanyNames by finding LocationNames made up of mostly or all alphabetic characters. You can use [regular expressions](http://us2.php.net/manual/en/book.pcre.php) for this. Store this list in a separate table. 2. Sort that list alphabetically and (manually) determine which entries should be CompanyNames. 3. Compare each CompanyName to each LocationName and come up with a match score (use [Levenshtein](http://us2.php.net/manual/en/function.levenshtein.php) or some other string matching algo). Store the result in a separate table. 4. Set a threshold score such that any MatchScore < Threshold will not be considered a match for a given CompanyName. 5. Manually vet through the LocationNames by CompanyName | LocationName | MatchScore, and figure out which ones actually match. Ordering by MatchScore should make the process less painful. The whole purpose of the above actions is to automate parts and limit the scope of your problem. It's far from perfect, but will hopefully save you the trouble of going through 18K records by hand.
6,126
<p>It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life.</p> <p>Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem?</p> <p>Example, all on one line:</p> <pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true &amp;&amp; var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true) { </code></pre> <p>Example, multi-line:</p> <pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true &amp;&amp; var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true) { </code></pre> <p>Example-nested:</p> <pre><code>if (var1 = true &amp;&amp; var2 = true &amp;&amp; var2 = true &amp;&amp; var3 = true) { if (var4 = true &amp;&amp; var5 = true &amp;&amp; var6 = true) { </code></pre>
[ { "answer_id": 6131, "author": "abyx", "author_id": 573, "author_profile": "https://Stackoverflow.com/users/573", "pm_score": 3, "selected": false, "text": "<p>First, I'd remove all the <code>== true</code> parts, that would make it 50% shorter ;)</p>\n\n<p>When I have big condition I se...
2008/08/08
[ "https://Stackoverflow.com/questions/6126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
It's something that's bugged me in every language I've used, I have an if statement but the conditional part has so many checks that I have to split it over multiple lines, use a nested if statement or just accept that it's ugly and move on with my life. Are there any other methods that you've found that might be of use to me and anybody else that's hit the same problem? Example, all on one line: ``` if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { ``` Example, multi-line: ``` if (var1 = true && var2 = true && var2 = true && var3 = true && var4 = true && var5 = true && var6 = true) { ``` Example-nested: ``` if (var1 = true && var2 = true && var2 = true && var3 = true) { if (var4 = true && var5 = true && var6 = true) { ```
Separate the condition in several booleans and then use a master boolean as the condition. ``` bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); bool isVisible = isOpaque && isDrawable && ! isHidden; if(isVisible) { // ... } ``` Better yet: ``` public bool IsVisible { get { bool isOpaque = object.Alpha == 1.0f; bool isDrawable = object.CanDraw && object.Layer == currentLayer; bool isHidden = hideList.Find(object); return isOpaque && isDrawable && ! isHidden; } } void Draw() { if(IsVisible) { // ... } } ``` Make sure you give your variables name that actualy indicate intention rather than function. This will greatly help the developer maintaining your code... it could be YOU!
6,134
<p>I have a problem with some zombie-like processes on a certain server that need to be killed every now and then. How can I best identify the ones that have run for longer than an hour or so?</p>
[ { "answer_id": 6141, "author": "abyx", "author_id": 573, "author_profile": "https://Stackoverflow.com/users/573", "pm_score": 0, "selected": false, "text": "<p>Using ps is the right way. I've already done something similar before but don't have the source handy.\nGenerally - ps has an op...
2008/08/08
[ "https://Stackoverflow.com/questions/6134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ]
I have a problem with some zombie-like processes on a certain server that need to be killed every now and then. How can I best identify the ones that have run for longer than an hour or so?
If they just need to be killed: ``` if [[ "$(uname)" = "Linux" ]];then killall --older-than 1h someprocessname;fi ``` If you want to see what it's matching ``` if [[ "$(uname)" = "Linux" ]];then killall -i --older-than 1h someprocessname;fi ``` The `-i` flag will prompt you with yes/no for each process match.
6,155
<p>What kinds of hook scripts are people using for Subversion? Just general ideas but code would be great too!</p>
[ { "answer_id": 6165, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 0, "selected": false, "text": "<p>The most common one I think is to allow people to change revision comments after comitting. </p>\n\n<p>You need to enable...
2008/08/08
[ "https://Stackoverflow.com/questions/6155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ]
What kinds of hook scripts are people using for Subversion? Just general ideas but code would be great too!
I am using the `pre-revprop-change` hook that allows me to actually go back and edit comments and such information after the commit has been performed. This is very useful if there is missing/erroneous information in the commit comments. Here I post a `pre-revprop-change.bat` batch file for Windows NT or later. You can certainly enhance it with more modifications. You can also derive a `post-revprop-change.cmd` from it to back up the old `snv:log` somewhere or just to append it to the new log. The only tricky part was to be able to actually parse the stdin from the batch file. This is done here with the `FIND.EXE` command. The other thing is that I have had reports from other users of issues with the use of the `/b` with the `exit` command. You may just need to remove that `/b` in your specific application if error cases do not behave well. ``` @ECHO OFF set repos=%1 set rev=%2 set user=%3 set propname=%4 set action=%5 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Only allow changes to svn:log. The author, date and other revision :: properties cannot be changed :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if /I not '%propname%'=='svn:log' goto ERROR_PROPNAME :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Only allow modifications to svn:log (no addition/overwrite or deletion) :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if /I not '%action%'=='M' goto ERROR_ACTION :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Make sure that the new svn:log message contains some text. :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: set bIsEmpty=true for /f "tokens=*" %%g in ('find /V ""') do ( set bIsEmpty=false ) if '%bIsEmpty%'=='true' goto ERROR_EMPTY goto :eof :ERROR_EMPTY echo Empty svn:log properties are not allowed. >&2 goto ERROR_EXIT :ERROR_PROPNAME echo Only changes to svn:log revision properties are allowed. >&2 goto ERROR_EXIT :ERROR_ACTION echo Only modifications to svn:log revision properties are allowed. >&2 goto ERROR_EXIT :ERROR_EXIT exit /b 1 ```
6,173
<p>I'm looking for a .NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link. </p> <p>And a side question:</p> <p>Is there <strong>one regex to rule them all</strong>? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability)</p>
[ { "answer_id": 6177, "author": "Vagmi Mudumbai", "author_id": 617, "author_profile": "https://Stackoverflow.com/users/617", "pm_score": 1, "selected": false, "text": "<p>Look at the URI specification. That could help you a lot. And as far as performance goes, you can pretty much extract ...
2008/08/08
[ "https://Stackoverflow.com/questions/6173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/322/" ]
I'm looking for a .NET regular expression extract all the URLs from a webpage but haven't found one to be comprehensive enough to cover all the different ways you can specify a link. And a side question: Is there **one regex to rule them all**? Or am I better off using a series of less complicated regular expressions and just using mutliple passes against the raw HTML? (Speed vs. Maintainability)
``` ((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+) ``` I took this from [regexlib.com](http://regexlib.com/Search.aspx?k=URL) [editor's note: the {1} has no real function in this regex; [see this post](https://stackoverflow.com/questions/13470/question-about-specific-regular-expression)]
6,184
<p>When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread.</p> <p>The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.</p>
[ { "answer_id": 6189, "author": "Simon Gillbee", "author_id": 756, "author_profile": "https://Stackoverflow.com/users/756", "pm_score": 4, "selected": false, "text": "<p>Here are the salient points:</p>\n\n<ol>\n<li>You can't make UI control calls from a different thread than the one they...
2008/08/08
[ "https://Stackoverflow.com/questions/6184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/756/" ]
When you subscribe to an event on an object from within a form, you are essentially handing over control of your callback method to the event source. You have no idea whether that event source will choose to trigger the event on a different thread. The problem is that when the callback is invoked, you cannot assume that you can make update controls on your form because sometimes those controls will throw an exception if the event callback was called on a thread different than the thread the form was run on.
To simplify Simon's code a bit, you could use the built in generic Action delegate. It saves peppering your code with a bunch of delegate types you don't really need. Also, in .NET 3.5 they added a params parameter to the Invoke method so you don't have to define a temporary array. ``` void SomethingHappened(object sender, EventArgs ea) { if (InvokeRequired) { Invoke(new Action<object, EventArgs>(SomethingHappened), sender, ea); return; } textBox1.Text = "Something happened"; } ```
6,326
<p>I have the following html.erb code that I'm looking to move to Haml:</p> <pre><code>&lt;span class="&lt;%= item.dashboardstatus.cssclass %&gt;" &gt;&lt;%= item.dashboardstatus.status %&gt;&lt;/span&gt; </code></pre> <p>What it does is associate the CSS class of the currently assigned status to the span.</p> <p>How is this done in Haml? I'm sure I'm missing something really simple.</p>
[ { "answer_id": 6355, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 5, "selected": true, "text": "<p>Not sure. Maybe:</p>\n\n<pre><code>%span{:class =&gt; item.dashboardstatus.cssclass }= item.dashboardstatus.status\...
2008/08/08
[ "https://Stackoverflow.com/questions/6326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/722/" ]
I have the following html.erb code that I'm looking to move to Haml: ``` <span class="<%= item.dashboardstatus.cssclass %>" ><%= item.dashboardstatus.status %></span> ``` What it does is associate the CSS class of the currently assigned status to the span. How is this done in Haml? I'm sure I'm missing something really simple.
Not sure. Maybe: ``` %span{:class => item.dashboardstatus.cssclass }= item.dashboardstatus.status ```
6,340
<p>I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly :p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas?</p> <pre><code>CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; </code></pre> <p><em>Edited to remove double primary key definition...</em></p> <hr> <p>Yeah, unfortunately that didn't fix it though. Now I'm getting:</p> <blockquote> <p>Can't create table './<em>REMOVED MY DB NAME</em>/SHIPPING_GRID.frm' (errno: 150)</p> </blockquote> <p>Doing a phpinfo() tells me this for mysql:</p> <blockquote> <p>Client API version 5.0.45</p> </blockquote> <p>Yes, the VENDOR.no is type int(6).</p>
[ { "answer_id": 6349, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 5, "selected": true, "text": "<p>You defined the primary key twice. Try:</p>\n\n<pre><code>CREATE TABLE SHIPPING_GRID( \n id INT NOT NULL AUTO_I...
2008/08/08
[ "https://Stackoverflow.com/questions/6340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58/" ]
I've got a table that is supposed to track days and costs for shipping product from one vendor to another. We (brilliantly :p) stored both the shipping vendors (FedEx, UPS) with the product handling vendors (Think... Dunder Mifflin) in a "VENDOR" table. So, I have three columns in my SHIPPING\_DETAILS table that all reference VENDOR.no. For some reason MySQL isn't letting me define all three as foreign keys. Any ideas? ``` CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; ``` *Edited to remove double primary key definition...* --- Yeah, unfortunately that didn't fix it though. Now I'm getting: > > Can't create table > './*REMOVED MY DB NAME*/SHIPPING\_GRID.frm' > (errno: 150) > > > Doing a phpinfo() tells me this for mysql: > > Client API version 5.0.45 > > > Yes, the VENDOR.no is type int(6).
You defined the primary key twice. Try: ``` CREATE TABLE SHIPPING_GRID( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', INDEX (shipping_vendor_no), INDEX (start_vendor_no), INDEX (end_vendor_no), FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) ) TYPE = INNODB; ``` The VENDOR primary key must be INT(6), and both tables must be of type InnoDB.
6,369
<p>So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause:</p> <pre><code>CREATE PROCEDURE getSomething @keyList varchar(4096) AS SELECT * FROM mytbl WHERE name IN (@keyList) </code></pre> <p>How do I call my stored proc with more than 1 value in the list? So far I've tried </p> <pre><code>exec getSomething 'John' -- works but only 1 value exec getSomething 'John','Tom' -- doesn't work - expects two variables exec getSomething "'John','Tom'" -- doesn't work - doesn't find anything exec getSomething '"John","Tom"' -- doesn't work - doesn't find anything exec getSomething '\'John\',\'Tom\'' -- doesn't work - syntax error </code></pre> <p><strong>EDIT:</strong> I actually found this <a href="http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm" rel="noreferrer">page</a> that has a great reference of the various ways to pas an array to a sproc</p>
[ { "answer_id": 6377, "author": "Brian Childress", "author_id": 721, "author_profile": "https://Stackoverflow.com/users/721", "pm_score": 0, "selected": false, "text": "<p>Do you need to use a comma separated list? The last couple of years, I've been taking this type of idea and passing i...
2008/08/08
[ "https://Stackoverflow.com/questions/6369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/779/" ]
So I have a Sybase stored proc that takes 1 parameter that's a comma separated list of strings and runs a query with in in an IN() clause: ``` CREATE PROCEDURE getSomething @keyList varchar(4096) AS SELECT * FROM mytbl WHERE name IN (@keyList) ``` How do I call my stored proc with more than 1 value in the list? So far I've tried ``` exec getSomething 'John' -- works but only 1 value exec getSomething 'John','Tom' -- doesn't work - expects two variables exec getSomething "'John','Tom'" -- doesn't work - doesn't find anything exec getSomething '"John","Tom"' -- doesn't work - doesn't find anything exec getSomething '\'John\',\'Tom\'' -- doesn't work - syntax error ``` **EDIT:** I actually found this [page](http://vyaskn.tripod.com/passing_arrays_to_stored_procedures.htm) that has a great reference of the various ways to pas an array to a sproc
If you're using Sybase 12.5 or earlier then you can't use functions. A workaround might be to populate a temporary table with the values and read them from there.
6,373
<p>There are two popular closure styles in javascript. The first I call <em>anonymous constructor</em>:</p> <pre><code>new function() { var code... } </code></pre> <p>and the <em>inline executed function</em>:</p> <pre><code>(function() { var code... })(); </code></pre> <p>are there differences in behaviour between those two? Is one "better" over the other?</p>
[ { "answer_id": 6387, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 3, "selected": false, "text": "<p>@Lance: the first one is also executing. Compare it with a named constructor:</p>\n\n<pre><code>function Blah() {\n alert('b...
2008/08/08
[ "https://Stackoverflow.com/questions/6373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
There are two popular closure styles in javascript. The first I call *anonymous constructor*: ``` new function() { var code... } ``` and the *inline executed function*: ``` (function() { var code... })(); ``` are there differences in behaviour between those two? Is one "better" over the other?
Both cases will execute the function, the only real difference is what the return value of the expression may be, and what the value of "this" will be inside the function. Basically behaviour of ``` new expression ``` Is effectively equivalent to ``` var tempObject = {}; var result = expression.call(tempObject); if (result is not an object) result = tempObject; ``` Although of course tempObject and result are transient values you can never see (they're implementation details in the interpreter), and there is no JS mechanism to do the "is not an object" check. Broadly speaking the "new function() { .. }" method will be slower due to the need to create the this object for the constructor. That said this should be not be a real difference as object allocation is not slow, and you shouldn't be using such code in hot code (due to the cost of creating the function object and associated closure). Edit: one thing i realised that i missed from this is that the `tempObject` will get `expression`s prototype, eg. (before the `expression.call`) `tempObject.__proto__ = expression.prototype`
6,392
<p>I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to:</p> <pre><code>sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] </code></pre> <p>Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's <a href="http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getDisplayName()" rel="noreferrer">display name</a>, and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon.</p> <p>Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration.</p> <hr> <p>Ok, here's an update. A coworker suggested I update JAVA_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden).</p> <p>However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround.</p> <hr> <p>I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution.</p>
[ { "answer_id": 6496, "author": "Jason Day", "author_id": 737, "author_profile": "https://Stackoverflow.com/users/737", "pm_score": 6, "selected": true, "text": "<p>It's a \"quirk\" in the way the JVM looks up the zoneinfo file. See <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?b...
2008/08/08
[ "https://Stackoverflow.com/questions/6392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I am running a Tomcat application, and I need to display some time values. Unfortunately, the time is coming up an hour off. I looked into it and discovered that my default TimeZone is being set to: ``` sun.util.calendar.ZoneInfo[id="GMT-08:00", offset=-28800000, dstSavings=0, useDaylight=false, transitions=0, lastRule=null] ``` Rather than the Pacific time zone. This is further indicated when I try to print the default time zone's [display name](http://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html#getDisplayName()), and it comes up "GMT-08:00", which seems to indicate to me that it is not correctly set to the US Pacific time zone. I am running on Ubuntu Hardy Heron, upgraded from Gutsy Gibbon. Is there a configuration file I can update to tell the JRE to use Pacific with all the associated daylight savings time information? The time on my machine shows correctly, so it doesn't seem to be an OS-wide misconfiguration. --- Ok, here's an update. A coworker suggested I update JAVA\_OPTS in my /etc/profile to include "-Duser.timezone=US/Pacific", which worked (I also saw CATALINA\_OPTS, which I updated as well). Actually, I just exported the change into the variables rather than use the new /etc/profile (a reboot later will pick up the changes and I will be golden). However, I still think there is a better solution... there should be a configuration for Java somewhere that says what timezone it is using, or how it is grabbing the timezone. If someone knows such a setting, that would be awesome, but for now this is a decent workaround. --- I am using 1.5, and it is most definitely a DST problem. As you can see, the time zone is set to not use daylight savings. My belief is it is generically set to -8 offset rather than the specific Pacific timezone. Since the generic -8 offset has no daylight savings info, it's of course not using it, but the question is, where do I tell Java to use Pacific time zone when it starts up? I'm NOT looking for a programmatic solution, it should be a configuration solution.
It's a "quirk" in the way the JVM looks up the zoneinfo file. See [Bug ID 6456628](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6456628). The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work: ``` # sudo cp /etc/localtime /etc/localtime.dist # sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime ``` I haven't had any problems with the symlink approach. Edit: Added "sudo" to the commands.
6,406
<p>Is it possible to access an element on a Master page from the page loaded within the <code>ContentPlaceHolder</code> for the master?</p> <p>I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The <code>ListView</code> currently does not update it's values until the cache is reloaded. We have found that just re-running the <code>ListView.DataBind()</code> will update a listview's contents. We have not been able to run the <code>ListView.DataBind()</code> on a page that uses the Master page. </p> <p>Below is a sample of what I wanted to do but a compiler error says </p> <blockquote> <p>"PeopleListView does not exist in the current context"</p> </blockquote> <p>GIS.master - Where ListView resides</p> <pre><code>...&lt;asp:ListView ID="PeopleListView"... </code></pre> <p>GISInput_People.aspx - Uses GIS.master as it's master page</p> <p>GISInput_People.aspx.cs</p> <pre><code>AddNewPerson() { // Add person to table .... // Update Person List PeopleListView.DataBind(); ... } </code></pre> <p>What would be the best way to resolve an issue like this in C# .Net?</p>
[ { "answer_id": 6411, "author": "Brandon Wood", "author_id": 423, "author_profile": "https://Stackoverflow.com/users/423", "pm_score": -1, "selected": false, "text": "<p>Assuming your master page was named MyMaster:</p>\n\n<pre><code>(Master as MyMaster).PeopleListView.DataBind();\n</code...
2008/08/08
[ "https://Stackoverflow.com/questions/6406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/576/" ]
Is it possible to access an element on a Master page from the page loaded within the `ContentPlaceHolder` for the master? I have a ListView that lists people's names in a navigation area on the Master page. I would like to update the ListView after a person has been added to the table that the ListView is data bound to. The `ListView` currently does not update it's values until the cache is reloaded. We have found that just re-running the `ListView.DataBind()` will update a listview's contents. We have not been able to run the `ListView.DataBind()` on a page that uses the Master page. Below is a sample of what I wanted to do but a compiler error says > > "PeopleListView does not exist in the current context" > > > GIS.master - Where ListView resides ``` ...<asp:ListView ID="PeopleListView"... ``` GISInput\_People.aspx - Uses GIS.master as it's master page GISInput\_People.aspx.cs ``` AddNewPerson() { // Add person to table .... // Update Person List PeopleListView.DataBind(); ... } ``` What would be the best way to resolve an issue like this in C# .Net?
I believe you *could* do this by using this.Master.FindControl or something similar, but you probably shouldn't - it requires the content page to know too much about the structure of the master page. I would suggest another method, such as firing an event in the content area that the master could listen for and re-bind when fired.
6,414
<p>In a C# (feel free to answer for other languages) loop, what's the difference between <code>break</code> and <code>continue</code> as a means to leave the structure of the loop, and go to the next iteration?</p> <p>Example:</p> <pre><code>foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference between this and continue ? //continue; } } </code></pre>
[ { "answer_id": 6415, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 5, "selected": false, "text": "<p><code>break</code> would stop the <code>foreach</code> loop completely, <code>continue</code> would skip to the next <code>Da...
2008/08/08
[ "https://Stackoverflow.com/questions/6414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
In a C# (feel free to answer for other languages) loop, what's the difference between `break` and `continue` as a means to leave the structure of the loop, and go to the next iteration? Example: ``` foreach (DataRow row in myTable.Rows) { if (someConditionEvalsToTrue) { break; //what's the difference between this and continue ? //continue; } } ```
`break` will exit the loop completely, `continue` will just **skip** the current iteration. For example: ``` for (int i = 0; i < 10; i++) { if (i == 0) { break; } DoSomeThingWith(i); } ``` The break will cause the loop to exit on the first iteration - `DoSomeThingWith` will never be executed. This here: ``` for (int i = 0; i < 10; i++) { if(i == 0) { continue; } DoSomeThingWith(i); } ``` Will not execute `DoSomeThingWith` for `i = 0`, but the loop will **continue** and `DoSomeThingWith` will be executed for `i = 1` to `i = 9`.