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 LIKE 'query%'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query'\n UNION\n SELECT A,B,C FROM table WHERE field LIKE '%query%'\n) ORDER BY B ASC LIMIT 5\n</code></pre>\n" }, { "answer_id": 3853, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 0, "selected": false, "text": "<p>If there isn't a sort that makes sense to order them you desire, don't union the results together - just return 3 separate recordsets, and deal with them accordingly in your data tier.</p>\n" }, { "answer_id": 3854, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 3, "selected": false, "text": "<p>Add an additional column with hard-coded values that you will use to sort the overall resultset, like so:</p>\n\n<pre><code>SELECT A,B,C,1 as [order] FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C,2 as [order] FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C,3 as [order] FROM table WHERE field LIKE '%query%'\nGROUP BY B ORDER BY [order] ASC, B ASC LIMIT 5\n</code></pre>\n" }, { "answer_id": 3860, "author": "Mario Marinato", "author_id": 431, "author_profile": "https://Stackoverflow.com/users/431", "pm_score": 5, "selected": true, "text": "<p>Maybe you should try including a fourth column, stating the table it came from, and then order and group by it:</p>\n\n<pre><code>SELECT A,B,C, \"query 1\" as origin FROM table WHERE field LIKE 'query%'\nUNION\nSELECT A,B,C, \"query 2\" as origin FROM table WHERE field LIKE '%query'\nUNION\nSELECT A,B,C, \"query 3\" as origin FROM table WHERE field LIKE '%query%'\nGROUP BY origin, B ORDER BY origin, B ASC LIMIT 5\n</code></pre>\n" }, { "answer_id": 3876, "author": "mauriciopastrana", "author_id": 547, "author_profile": "https://Stackoverflow.com/users/547", "pm_score": 0, "selected": false, "text": "<p>I eventually (looking at all suggestions) came to this solution, its a bit of a compromise between what I need and time.</p>\n\n<pre><code>SELECT * FROM \n (SELECT A, B, C, \"1\" FROM table WHERE B LIKE 'query%' LIMIT 3\n UNION\n SELECT A, B, C, \"2\" FROM table WHERE B LIKE '%query%' LIMIT 5)\nAS RS\nGROUP BY B\nORDER BY 1 DESC\n</code></pre>\n\n<p>it delivers 5 results total, sorts from the fourth \"column\" and gives me what I need; a natural result set (its coming over AJAX), and a wildcard result set following right after.</p>\n\n<p>:)</p>\n\n<p>/mp</p>\n" }, { "answer_id": 3902, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 1, "selected": false, "text": "<p>SELECT distinct a,b,c FROM (\n SELECT A,B,C,1 as o FROM table WHERE field LIKE 'query%'\n UNION\n SELECT A,B,C,2 as o FROM table WHERE field LIKE '%query'\n UNION\n SELECT A,B,C,3 as o FROM table WHERE field LIKE '%query%'\n )\n ORDER BY o ASC LIMIT 5</p>\n\n<p>Would be my way of doing it. I dont know how that scales.</p>\n\n<p>I don't understand the</p>\n\n<pre><code>GROUP BY B ORDER BY B ASC LIMIT 5\n</code></pre>\n\n<p>Does it apply only to the last SELECT in the union? </p>\n\n<p>Does mysql actually allow you to group by a column and still not do aggregates on the other columns?</p>\n\n<p>EDIT: aaahh. I see that mysql actually does. Its a special version of DISTINCT(b) or something. I wouldnt want to try to be an expert on that area :)</p>\n" }, { "answer_id": 84974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>There are two varients of UNION. </p>\n\n<pre><code>'UNION' and 'UNION ALL'\n</code></pre>\n\n<p>In most cases what you really want to say is UNION ALL as it does not do duplicate elimination (Think <code>SELECT DISTINCT</code>) between sets which can result in quite a bit of savings in terms of execution time.</p>\n\n<p>Others have suggested multiple result sets which is a workable solution however I would caution against this in time sensitive applications or applications connected over WANs as doing so can result in significantly more round trips on the wire between server and client.</p>\n" }, { "answer_id": 56214651, "author": "harsha reddy", "author_id": 11315515, "author_profile": "https://Stackoverflow.com/users/11315515", "pm_score": 0, "selected": false, "text": "<p>I don't understand why the need of union for taking the data from single table</p>\n\n<pre><code>SELECT A, B, C \nFROM table \nWHERE field LIKE 'query%' \n OR field LIKE '%query' \n OR field LIKE '%query%'\nGROUP BY B \nORDER BY B ASC LIMIT 5\n</code></pre>\n" } ]
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", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 0, "selected": false, "text": "<p>Could you be a little more specific about the use case? Removing the decimal point from the representation is a little unusual given that you'll lose all information about the scale. Are you assuming that there will always be two digits? If so, you could simplify multiply by 100 and then round before converting to a string.</p>\n" }, { "answer_id": 3974, "author": "Lance Fisher", "author_id": 571, "author_profile": "https://Stackoverflow.com/users/571", "pm_score": 0, "selected": false, "text": "<p>Keep in mind that the money data type can have up to 4 digits past the decimal. Values with more than two digits might not work as expected for either your original solution or the x100 trick.</p>\n" }, { "answer_id": 5944, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "<p>You should never ever use the money datatype to store monetary values. If you do any calculations you will get truncated results. Run the following to see what I mean</p>\n\n<pre><code>DECLARE\n@mon1 MONEY,\n@mon2 MONEY,\n@mon3 MONEY,\n@mon4 MONEY,\n@num1 DECIMAL(19,4),\n@num2 DECIMAL(19,4),\n@num3 DECIMAL(19,4),\n@num4 DECIMAL(19,4)\n\nSELECT\n@mon1 = 100, @mon2 = 339, @mon3 = 10000,\n@num1 = 100, @num2 = 339, @num3 = 10000\n\nSET @mon4 = @mon1/@mon2*@mon3\nSET @num4 = @num1/@num2*@num3\n\nSELECT @mon4 AS moneyresult,\n@num4 AS numericresult\n</code></pre>\n\n<p>Output:\n2949.0000 2949.8525</p>\n" }, { "answer_id": 886375, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Here is the magic:</p>\n\n<pre><code>DataFormatString=\"{0:c0}\n</code></pre>\n\n<p>This will remove the decimal places.</p>\n" } ]
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 access to what you need.</p>\n" }, { "answer_id": 3911, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "<p>Take a look at Raymond Chens solution:</p>\n\n<p><a href=\"http://blogs.msdn.com/oldnewthing/archive/2005/02/01/364563.aspx\" rel=\"nofollow noreferrer\">How to detect programmatically whether you are running on 64-bit Windows</a></p>\n\n<p>and here's the PINVOKE for .NET:</p>\n\n<p><a href=\"http://www.pinvoke.net/default.aspx/kernel32/IsWow64Process.html?diff=y\" rel=\"nofollow noreferrer\">IsWow64Process (kernel32)</a></p>\n\n<p><strong>Update:</strong> 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. </p>\n" }, { "answer_id": 3919, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 1, "selected": false, "text": "<p>The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size.</p>\n\n<p>EDIT: Doh! This will tell you whether or not the current process is 64-bit, not the OS as a whole. Sorry!</p>\n" }, { "answer_id": 3922, "author": "Jeremy Privett", "author_id": 560, "author_profile": "https://Stackoverflow.com/users/560", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>The easiest way to test for 64-bit under .NET is to check the value of IntPtr.Size.</p>\n</blockquote>\n\n<p>I believe the value of IntPtr.Size is 4 for a 32bit app that's running under WOW, isn't it?</p>\n\n<p><strong>Edit</strong>: @Edit: Yeah. :)</p>\n" } ]
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 being sent across? Also just curious, Python is sending ASCII and not UTF-8 or something else right? The reason I ask is because I noticed your quote changes for the strings and in some languages that actually is the difference between ASCII and UTF-8.</p>\n" }, { "answer_id": 4162, "author": "Lily Ballard", "author_id": 582, "author_profile": "https://Stackoverflow.com/users/582", "pm_score": 3, "selected": false, "text": "<p><code>/dev/cu.xxxxx</code> is the \"callout\" device, it's what you use when you establish a connection to the serial device and start talking to it. <code>/dev/tty.xxxxx</code> is the \"dialin\" device, used for monitoring a port for incoming calls for e.g. a fax listener.</p>\n" } ]
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 poor in this area and there is a dearth of practical examples.</p>\n\n<p><strong>Using the WebSphere Application Server (WAS) Ant tasks</strong></p>\n\n<p>To run as described here, you need to run them from your server <strong>profile</strong> bin directory using the <strong>ws_ant.sh</strong> or <strong>ws_ant.bat</strong> commands.</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;project name=\"project\" default=\"wasListApps\" basedir=\".\"&gt;\n &lt;description&gt;\n Script for listing installed apps.\n Example run from:\n /opt/IBM/SDP70/runtimes/base_v61/profiles/AppSrv01/bin\n &lt;/description&gt;\n\n &lt;property name=\"was_home\"\n value=\"/opt/IBM/SDP70/runtimes/base_v61/\"&gt;\n &lt;/property&gt;\n &lt;path id=\"was.runtime\"&gt;\n &lt;fileset dir=\"${was_home}/lib\"&gt;\n &lt;include name=\"**/*.jar\" /&gt;\n &lt;/fileset&gt;\n &lt;fileset dir=\"${was_home}/plugins\"&gt;\n &lt;include name=\"**/*.jar\" /&gt;\n &lt;/fileset&gt;\n &lt;/path&gt;\n &lt;property name=\"was_cp\" value=\"${toString:was.runtime}\"&gt;&lt;/property&gt;\n &lt;property environment=\"env\"&gt;&lt;/property&gt;\n\n &lt;target name=\"wasListApps\"&gt;\n &lt;taskdef name=\"wsListApp\"\n classname=\"com.ibm.websphere.ant.tasks.ListApplications\"\n classpath=\"${was_cp}\"&gt;\n &lt;/taskdef&gt;\n &lt;wsListApp wasHome=\"${was_home}\" /&gt;\n &lt;/target&gt;\n\n&lt;/project&gt;\n</code></pre>\n\n<p>Command:</p>\n\n<pre><code>./ws_ant.sh -buildfile ~/IBM/rationalsdp7.0/workspace/mywebappDeploy/applist.xml\n</code></pre>\n\n<p><strong>A Deployment Script</strong></p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;project name=\"project\" default=\"default\" basedir=\".\"&gt;\n&lt;description&gt;\nBuild/Deploy an EAR to WebSphere Application Server 6.1\n&lt;/description&gt;\n\n &lt;property name=\"was_home\" value=\"/opt/IBM/SDP70/runtimes/base_v61/\" /&gt;\n &lt;path id=\"was.runtime\"&gt;\n &lt;fileset dir=\"${was_home}/lib\"&gt;\n &lt;include name=\"**/*.jar\" /&gt;\n &lt;/fileset&gt;\n &lt;fileset dir=\"${was_home}/plugins\"&gt;\n &lt;include name=\"**/*.jar\" /&gt;\n &lt;/fileset&gt;\n &lt;/path&gt;\n &lt;property name=\"was_cp\" value=\"${toString:was.runtime}\" /&gt;\n &lt;property environment=\"env\" /&gt;\n &lt;property name=\"ear\" value=\"${env.HOME}/IBM/rationalsdp7.0/workspace/mywebappDeploy/mywebappEAR.ear\" /&gt;\n\n &lt;target name=\"default\" depends=\"deployEar\"&gt;\n &lt;/target&gt;\n\n &lt;target name=\"generateWar\" depends=\"compileWarClasses\"&gt;\n &lt;jar destfile=\"mywebapp.war\"&gt;\n &lt;fileset dir=\"../mywebapp/WebContent\"&gt;\n &lt;/fileset&gt;\n &lt;/jar&gt;\n &lt;/target&gt;\n\n &lt;target name=\"compileWarClasses\"&gt;\n &lt;echo message=\"was_cp=${was_cp}\" /&gt;\n &lt;javac srcdir=\"../mywebapp/src\" destdir=\"../mywebapp/WebContent/WEB-INF/classes\" classpath=\"${was_cp}\"&gt;\n &lt;/javac&gt;\n &lt;/target&gt;\n\n &lt;target name=\"generateEar\" depends=\"generateWar\"&gt;\n &lt;mkdir dir=\"./earbin/META-INF\"/&gt;\n &lt;move file=\"mywebapp.war\" todir=\"./earbin\" /&gt;\n &lt;copy file=\"../mywebappEAR/META-INF/application.xml\" todir=\"./earbin/META-INF\" /&gt;\n &lt;jar destfile=\"${ear}\"&gt;\n &lt;fileset dir=\"./earbin\" /&gt;\n &lt;/jar&gt;\n &lt;/target&gt;\n\n &lt;!-- 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 --&gt;\n &lt;target name=\"deployEar\" depends=\"generateEar\"&gt;\n &lt;taskdef name=\"wsInstallApp\" classname=\"com.ibm.websphere.ant.tasks.InstallApplication\" classpath=\"${was_cp}\"/&gt;\n &lt;wsInstallApp ear=\"${ear}\" \n failonerror=\"true\" \n debug=\"true\" \n taskname=\"\"\n washome=\"${was_home}\" /&gt;\n &lt;/target&gt;\n\n&lt;/project&gt;\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>You can only run this once! You cannot install if the app name is in use - see other tasks like <strong>wsUninstallApp</strong></li>\n<li>It probably won't start the app either</li>\n<li>You need to run this on the server and the script is quite fragile</li>\n</ul>\n\n<p><strong>Alternatives</strong></p>\n\n<p>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.</p>\n" }, { "answer_id": 14796, "author": "accreativos", "author_id": 1713, "author_profile": "https://Stackoverflow.com/users/1713", "pm_score": 3, "selected": false, "text": "<p>a good start point, could be this <a href=\"http://jira.codehaus.org/browse/MOJO-392\" rel=\"noreferrer\">maven pluggin</a>, not for use it, or maybe yes, but this maven is build over ant task. If you see WAS5+Plugin+Mojo.zip\\src\\main\\scripts\\was5.build.xml</p>\n\n<p>Or as said \"McDowell\", you can use \"WebSphere Application Server (WAS) Ant tasks\" but directly as ANT task.</p>\n\n<pre><code>&lt;path id=\"classpath\"&gt;\n &lt;fileset file=\"com.ibm.websphere.v61_6.1.100.ws_runtime.jar\"/&gt;\n&lt;/path&gt;\n\n&lt;taskdef name=\"wsStartApp\" classname=\"com.ibm.websphere.ant.tasks.StartApplication\" classpathref=\"classpath\" /&gt;\n&lt;taskdef name=\"wsStopApp\" classname=\"com.ibm.websphere.ant.tasks.StopApplication\" classpathref=\"classpath\" /&gt;\n&lt;taskdef name=\"wsInstallApp\" classname=\"com.ibm.websphere.ant.tasks.InstallApplication\" classpathref=\"classpath\" /&gt;\n&lt;taskdef name=\"wsUninstallApp\" classname=\"com.ibm.websphere.ant.tasks.UninstallApplication\" classpathref=\"classpath\" /&gt;\n\n&lt;target name=\"startWebApp1\" depends=\"installEar\"&gt;\n &lt;wsStartApp wasHome=\"${wasHome.dir}\" \n application=\"${remoteAppName}\" \n server=\"${clusterServerName}\" \n conntype=\"${remoteProdConnType}\" \n host=\"${remoteProdHostName}\" \n port=\"${remoteProdPort}\" \n user=\"${remoteProdUserId}\" \n password=\"${remoteProdPassword}\" /&gt;\n&lt;/target&gt;\n\n&lt;target name=\"stopWebApp1\" depends=\"prepare\"&gt;\n &lt;wsStopApp wasHome=\"${wasHome.dir}\"\n application=\"${remoteAppName}\"\n server=\"${clusterServerName}\"\n conntype=\"${remoteConnType}\"\n host=\"${remoteHostName}\"\n port=\"${remotePort}\"\n user=\"${remoteUserId}\"\n password=\"${remotePassword}\"/&gt;\n&lt;/target&gt;\n\n&lt;target name=\"uninstallEar\" depends=\"stopWebApp1\"&gt;\n &lt;wsUninstallApp wasHome=\"${wasHome.dir}\"\n application=\"${remoteAppName}\"\n options=\"-cell uatNetwork -cluster DOL\"\n conntype=\"${remoteConnType}\"\n host=\"${remoteHostName}\"\n port=\"${remoteDmgrPort}\"\n user=\"${remoteUserId}\"\n password=\"${remotePassword}\"/&gt;\n&lt;/target&gt;\n\n&lt;target name=\"installEar\" depends=\"prepare\"&gt;\n &lt;wsInstallApp ear=\"${existingEar.dir}/${existingEar}\" \n wasHome=\"${wasHome.dir}\" \n options=\"${install_app_options}\"\n conntype=\"${remoteConnType}\" \n host=\"${remoteHostName}\" \n port=\"${remoteDmgrPort}\" \n user=\"${remoteUserId}\" \n password=\"${remotePassword}\" /&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p>Another useful link could be <a href=\"http://www.theserverside.com/news/thread.tss?thread_id=32285\" rel=\"noreferrer\">this</a>.</p>\n" }, { "answer_id": 113687, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you just want to play around why not use the netbeans IDE to generate your ear files. If you create an enterprise project it will automatically generate the ant files for you. Good for prototyping and just getting started :-)</p>\n\n<p>There is even a was plugin which allows automated deployment however this seems very shakey!</p>\n" }, { "answer_id": 141442, "author": "fnCzar", "author_id": 15053, "author_profile": "https://Stackoverflow.com/users/15053", "pm_score": 3, "selected": false, "text": "<p>Here is some of the same functionality if you don't have the WAS ant tasks available or don't want to run was_ant.bat. This relies on wsadmin.bat existing in the path.</p>\n\n<p></p>\n\n<pre><code>&lt;property name=\"websphere.home.dir\" value=\"${env.WS6_HOME}\" /&gt;\n&lt;property name=\"was.server.name\" value=\"server1\" /&gt;\n&lt;property name=\"wsadmin.base.command\" value=\"wsadmin.bat\" /&gt;\n\n&lt;property name=\"ws.list.command\" value=\"$AdminApp list\" /&gt;\n&lt;property name=\"ws.install.command\" value=\"$AdminApp install\" /&gt;\n&lt;property name=\"ws.uninstall.command\" value=\"$AdminApp uninstall\" /&gt;\n&lt;property name=\"ws.save.command\" value=\"$AdminConfig save\" /&gt;\n&lt;property name=\"ws.setManager.command\" value=\"set appManager [$AdminControl queryNames cell=${env.COMPUTERNAME}Node01Cell,node=${env.COMPUTERNAME}Node01,type=ApplicationManager,process=${was.server.name},*]\" /&gt;\n&lt;property name=\"ws.startapp.command\" value=\"$AdminControl invoke $appManager startApplication\" /&gt;\n&lt;property name=\"ws.stopapp.command\" value=\"$AdminControl invoke $appManager stopApplication\" /&gt;\n\n&lt;property name=\"ws.conn.type\" value=\"SOAP\" /&gt;\n&lt;property name=\"ws.host.name\" value=\"localhost\" /&gt;\n&lt;property name=\"ws.port.name\" value=\"8880\" /&gt;\n&lt;property name=\"ws.user.name\" value=\"username\" /&gt;\n&lt;property name=\"ws.password.name\" value=\"password\" /&gt;\n\n&lt;property name=\"app.deployed.name\" value=\"${artifact.filename}\" /&gt;\n&lt;property name=\"app.contextroot.name\" value=\"/${artifact.filename}\" /&gt;\n\n&lt;target name=\"websphere-list-applications\"&gt;\n &lt;exec dir=\"${websphere.home.dir}/bin\" executable=\"${wsadmin.base.command}\" output=\"waslist.txt\" logError=\"true\"&gt;\n &lt;arg line=\"-conntype ${ws.conn.type}\" /&gt;\n &lt;arg line=\"-host ${ws.host.name}\" /&gt;\n &lt;arg line=\"-port ${ws.port.name}\" /&gt;\n &lt;arg line=\"-username ${ws.user.name}\" /&gt;\n &lt;arg line=\"-password ${ws.password.name}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.list.command}\" /&gt;\n &lt;/exec&gt;\n&lt;/target&gt;\n\n&lt;target name=\"websphere-install-application\" depends=\"websphere-uninstall-application\"&gt;\n &lt;exec executable=\"${websphere.home.dir}/bin/${wsadmin.base.command}\" logError=\"true\" outputproperty=\"websphere.install.output\" failonerror=\"true\"&gt;\n &lt;arg line=\"-conntype ${ws.conn.type}\" /&gt;\n &lt;arg line=\"-host ${ws.host.name}\" /&gt;\n &lt;arg line=\"-port ${ws.port.name}\" /&gt;\n &lt;arg line=\"-username ${ws.user.name}\" /&gt;\n &lt;arg line=\"-password ${ws.password.name}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.install.command} ${dist.dir}/${artifact.filename}.war {-appname ${app.deployed.name} -server ${was.server.name} -contextroot ${app.contextroot.name}}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.save.command}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.setManager.command}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.startapp.command} ${app.deployed.name}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.save.command}\" /&gt;\n &lt;/exec&gt;\n &lt;echo message=\"${websphere.install.output}\" /&gt;\n&lt;/target&gt;\n\n&lt;target name=\"websphere-uninstall-application\"&gt;\n &lt;exec executable=\"${websphere.home.dir}/bin/${wsadmin.base.command}\" logError=\"true\" outputproperty=\"websphere.uninstall.output\" failonerror=\"false\"&gt;\n &lt;arg line=\"-conntype ${ws.conn.type}\" /&gt;\n &lt;arg line=\"-host ${ws.host.name}\" /&gt;\n &lt;arg line=\"-port ${ws.port.name}\" /&gt;\n &lt;arg line=\"-username ${ws.user.name}\" /&gt;\n &lt;arg line=\"-password ${ws.password.name}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.setManager.command}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.stopapp.command} ${app.deployed.name}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.save.command}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.uninstall.command} ${app.deployed.name}\" /&gt;\n &lt;arg line=\"-c\" /&gt;\n &lt;arg value=\"${ws.save.command}\" /&gt;\n &lt;/exec&gt;\n &lt;echo message=\"${websphere.uninstall.output}\" /&gt;\n&lt;/target&gt;\n</code></pre>\n\n<p></p>\n" } ]
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 char* mystring;\n} data;\n\ndata** array;\n</code></pre>\n\n<p>But don't forget you still have to malloc the variable, and it does get a bit complex:</p>\n\n<pre><code>//initialize\nint x,y,w,h;\nw = 10; //width of array\nh = 20; //height of array\n\n//malloc the 'y' dimension\narray = malloc(sizeof(data*) * h);\n\n//iterate over 'y' dimension\nfor(y=0;y&lt;h;y++){\n //malloc the 'x' dimension\n array[y] = malloc(sizeof(data) * w);\n\n //iterate over the 'x' dimension\n for(x=0;x&lt;w;x++){\n //malloc the string in the data structure\n array[y][x].mystring = malloc(50); //50 chars\n\n //initialize\n array[y][x].myint = 6;\n strcpy(array[y][x].mystring, \"w00t\");\n }\n}\n</code></pre>\n\n<p>The code to deallocate the structure looks similar - don't forget to call free() on everything you malloced! (Also, in robust applications you should <a href=\"http://www.google.com/search?q=check+malloc+return\" rel=\"noreferrer\">check the return of malloc()</a>.)</p>\n\n<p>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:</p>\n\n<pre><code>int whatsMyInt(data** arrayPtr, int x, int y){\n return arrayPtr[y][x].myint;\n}\n</code></pre>\n\n<p>Call this function with:</p>\n\n<pre><code>printf(\"My int is %d.\\n\", whatsMyInt(array, 2, 4));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>My int is 6.\n</code></pre>\n" }, { "answer_id": 1916200, "author": "John Bode", "author_id": 134554, "author_profile": "https://Stackoverflow.com/users/134554", "pm_score": 5, "selected": false, "text": "<p>Pass an explicit pointer to the first element with the array dimensions as separate parameters. For example, to handle arbitrarily sized 2-d arrays of int:</p>\n\n<pre><code>void func_2d(int *p, size_t M, size_t N)\n{\n size_t i, j;\n ...\n p[i*N+j] = ...;\n}\n</code></pre>\n\n<p>which would be called as</p>\n\n<pre><code>...\nint arr1[10][20];\nint arr2[5][80];\n...\nfunc_2d(&amp;arr1[0][0], 10, 20);\nfunc_2d(&amp;arr2[0][0], 5, 80);\n</code></pre>\n\n<p>Same principle applies for higher-dimension arrays:</p>\n\n<pre><code>func_3d(int *p, size_t X, size_t Y, size_t Z)\n{\n size_t i, j, k;\n ...\n p[i*Y*Z+j*Z+k] = ...;\n ...\n}\n...\narr2[10][20][30];\n...\nfunc_3d(&amp;arr[0][0][0], 10, 20, 30);\n</code></pre>\n" }, { "answer_id": 8712577, "author": "Pedro", "author_id": 1127866, "author_profile": "https://Stackoverflow.com/users/1127866", "pm_score": -1, "selected": false, "text": "<pre><code>int matmax(int **p, int dim) // p- matrix , dim- dimension of the matrix \n{\n return p[0][0]; \n}\n\nint main()\n{\n int *u[5]; // will be a 5x5 matrix\n\n for(int i = 0; i &lt; 5; i++)\n u[i] = new int[5];\n\n u[0][0] = 1; // initialize u[0][0] - not mandatory\n\n // put data in u[][]\n\n printf(\"%d\", matmax(u, 0)); //call to function\n getche(); // just to see the result\n}\n</code></pre>\n" }, { "answer_id": 24623778, "author": "rslemos", "author_id": 1535706, "author_profile": "https://Stackoverflow.com/users/1535706", "pm_score": 5, "selected": false, "text": "<p>You can declare your function as:</p>\n\n<pre><code>f(int size, int data[][size]) {...}\n</code></pre>\n\n<p>The compiler will then do all pointer arithmetic for you.</p>\n\n<p>Note that the dimensions sizes must appear <strong>before</strong> the array itself.</p>\n\n<p>GNU C allows for argument declaration forwarding (in case you really need to pass dimensions after the array):</p>\n\n<pre><code>f(int size; int data[][size], int size) {...}\n</code></pre>\n\n<p>The first dimension, although you can pass as argument too, is useless for the C compiler (even for sizeof operator, when applied over array passed as argument will always treat is as a pointer to first element).</p>\n" }, { "answer_id": 59321586, "author": "Andrew Henle", "author_id": 4756299, "author_profile": "https://Stackoverflow.com/users/4756299", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>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?</p>\n</blockquote>\n\n<p><strong>No</strong></p>\n\n<p>If by \"single argument\" you mean passing just the array without passing the array dimensions, no you can't. At least not for true multidimensional arrays.</p>\n\n<p>You can put the dimension[s] into a structure along with the array and claim you're passing a \"single argument\", but that's really just packing multiple values into a single container and calling that container \"one argument\".</p>\n\n<p>You can pass an array of known type and number of dimensions but unknown size by passing the dimensions themselves and the array like this:</p>\n\n<pre><code>void print2dIntArray( size_t x, size_t y, int array[ x ][ y ] )\n{\n for ( size_t ii = 0, ii &lt; x; ii++ )\n {\n char *sep = \"\";\n for ( size_t jj = 0; jj &lt; y; jj++ )\n {\n printf( \"%s%d\", sep, array[ ii ][ jj ] );\n sep = \", \";\n }\n printf( \"\\n\" );\n }\n}\n</code></pre>\n\n<p>You would call that function like this:</p>\n\n<pre><code>int a[ 4 ][ 5 ];\nint b[ 255 ][ 16 ];\n\n...\n\nprint2dIntArray( 4, 5, a );\n\n....\n\nprintt2dIntArray( 255, 16, b );\n</code></pre>\n\n<p>Similarly, a 3-dimensional array of, for example, a <code>struct pixel</code>:</p>\n\n<pre><code>void print3dPixelArray( size_t x, size_t y, size_t z, struct pixel pixelArray[ x ][ y ][ z ] )\n{\n ...\n}\n</code></pre>\n\n<p>or a 1-dimensional <code>double</code> array:</p>\n\n<pre><code>void print1dDoubleArray( size_t x, double doubleArray[ x ] )\n{\n ...\n}\n</code></pre>\n\n<p><strong>BUT...</strong></p>\n\n<p>However, it can be possible to pass \"arrays of pointers to arrays of pointers to ... an array of type <code>X</code>\" constructs that are often mislabeled as a \"multidimensional array\" as a single argument as long as the base type <code>X</code> has an sentinel value that can be used to indicate the end of the final, lowest-level single-dimensional array of type <code>X</code>.</p>\n\n<p>For example, the <code>char **argv</code> value passed to <code>main()</code> is a pointer to an array of pointers to <code>char</code>. The initial array of <code>char *</code> pointers ends with a <code>NULL</code> sentinel value, while each <code>char</code> array referenced by the array of <code>char *</code> pointers ends with a <code>NUL</code> character value of <code>'\\0'</code>.</p>\n\n<p>For example, if you can use <code>NAN</code> as a sentinel value because actual data won't <strong>ever</strong> be a <code>NAN</code>, you could print a <code>double **</code> like this:</p>\n\n<pre><code>void printDoubles( double **notAnArray )\n{\n while ( *notAnArray )\n {\n char *sep = \"\";\n for ( size_t ii = 0; ( *notAnArray )[ ii ] != NAN; ii++ )\n {\n printf( \"%s%f\", sep, ( *notAnArray )[ ii ] );\n sep = \", \";\n }\n\n notAnArray++;\n }\n}\n</code></pre>\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 INDEX ON [dbo].[tblName] KEY INDEX [PK_something] ON [myFullText] WITH CHANGE_TRACKING AUTO\nALTER FULLTEXT INDEX ON [dbo].[otherTable] ADD ([Text])\nALTER FULLTEXT INDEX ON [dbo].[teyOtherTable] ENABLE\n</code></pre>\n" }, { "answer_id": 4717, "author": "Eddie", "author_id": 576, "author_profile": "https://Stackoverflow.com/users/576", "pm_score": 2, "selected": false, "text": "<p>All I needed to get full-text indexing to work was the...</p>\n\n<blockquote>\n <p>CREATE FULLTEXT CATALOG [myFullText] WITH ACCENT_SENSITIVITY = ON</p>\n</blockquote>\n\n<p>After that I could run a CREATE FULLTEXT INDEX query or use the Manage FullText Index in MSSQL Management Studio.</p>\n" }, { "answer_id": 12140569, "author": "Nikhil Chavan", "author_id": 1627443, "author_profile": "https://Stackoverflow.com/users/1627443", "pm_score": 1, "selected": false, "text": "<p>Use sql server management studio.</p>\n\n<p>Login as admin to your windows account.</p>\n\n<p>Then select database and right click on database in sql server management studio and select Define Full Text Index and you are guided throughout the process by management studio.</p>\n" } ]
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 .\n</code></pre>\n\n<p>will merge any files changed in the revision 67212 in the folder /trunk on the repository and merge them into your current working directory. If you do:</p>\n\n<pre><code>svn log -r 67212\n</code></pre>\n\n<p>What files does it show changed? Merge will only pull changes from the first argument, and apply them to the second. It does not upload back to the server in the first argument.</p>\n\n<p>If this doesn't answer your question, could you post more details as to what exactly is happening?</p>\n" }, { "answer_id": 13738, "author": "Cebjyre", "author_id": 1612, "author_profile": "https://Stackoverflow.com/users/1612", "pm_score": 3, "selected": true, "text": "<p>This only happens with conflicts - basically svn tried to merge the change in, but (roughly speaking) saw the change as:</p>\n\n<p>Add</p>\n\n<pre><code>2008-08-06 Mike Stone &lt;myemail&gt;\n\n* changed_file: Details.\n</code></pre>\n\n<p>before</p>\n\n<pre><code>2008-08-06 Someone Else &lt;their_email&gt;\n</code></pre>\n\n<p>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.</p>\n" } ]
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 it integrated to Rational Application Developer (the IDE I'm using to develop J2EE applications) because I like how neat it looks when you run javac in the Windows console. :P</p>\n" }, { "answer_id": 4492, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://checkstyle.sourceforge.net/\" rel=\"noreferrer\">Checkstyle</a> is another one I've used at a previous company... it's mainly for style checking, but it can do some static analysis too. Also, <a href=\"http://www.atlassian.com/software/clover/\" rel=\"noreferrer\">Clover</a> for code coverage, though be aware it is not a free tool.</p>\n" }, { "answer_id": 4493, "author": "dlinsin", "author_id": 198, "author_profile": "https://Stackoverflow.com/users/198", "pm_score": 2, "selected": false, "text": "<p>We are using FindBugs and Checkstyle as well as Clover for Code Coverage. </p>\n\n<p>I think it's important to have some kind of static analysis, supporting your development. Unfortunately it's still not widely spread that these tools are important.</p>\n" }, { "answer_id": 6022, "author": "Joshua McKinnon", "author_id": 235, "author_profile": "https://Stackoverflow.com/users/235", "pm_score": 0, "selected": false, "text": "<p>I am looking for many answers to learn about new tools and consolidate this knowledge in a one question/thread, so I doubt there will be 1 true answer to this question.</p>\n\n<p>My answer to my own question is that we use:</p>\n\n<ul>\n<li>Findbugs to look for common errors bad/coding - run from maven, and also integrates easily into Eclipse</li>\n<li>Cobertura for our coverage reports - run from maven</li>\n</ul>\n\n<p>Hudson also has a task-scanner plugin that will display a count of your TODO and FIXMEs, as well as show where they are in the source files.</p>\n\n<p>All are integrated with Maven 1.x in our case and tied into Hudson, which runs our builds on check-in as well as extra things nightly and weekly. Hudson trend graphs our JUnit tests, coverage, findbugs, as well as open tasks. There is also a Hudson plugin that reports and graphs our compile warnings. We also have several performance tests with their own graphs of performance and memory use over time using the Hudson plots plugin as well.</p>\n" }, { "answer_id": 13277, "author": "Brian Laframboise", "author_id": 1557, "author_profile": "https://Stackoverflow.com/users/1557", "pm_score": 4, "selected": false, "text": "<p>All of the following we use and integrate easiy in both our Maven 2.x builds and Eclipse/RAD 7:</p>\n\n<ul>\n<li>Testing - JUnit/TestNG</li>\n<li>Code analysis - FindBugs, PMD</li>\n<li>Code coverage - Clover</li>\n</ul>\n\n<p>In addition, in our Maven builds we have:</p>\n\n<ul>\n<li>JDepend</li>\n<li>Tag checker (TODO, FIXME, etc)</li>\n</ul>\n\n<p>Furthermore, if you're using Maven 2.x, CodeHaus has a collection of handy Maven plugins in their <a href=\"http://mojo.codehaus.org/plugins.html\" rel=\"noreferrer\">Mojo project</a>.</p>\n\n<p>Note: Clover has out-of-the-box integration with the Bamboo CI server (since they're both Atlassian products). There are also Bamboo plugins for FindBugs, PMD, and CheckStyle but, as noted, the free Hudson CI server has those too.</p>\n" }, { "answer_id": 79845, "author": "Greg Mattes", "author_id": 13940, "author_profile": "https://Stackoverflow.com/users/13940", "pm_score": 7, "selected": true, "text": "<p>For static analysis tools I often use CPD, <a href=\"http://pmd.sourceforge.net\" rel=\"noreferrer\">PMD</a>, <a href=\"http://findbugs.sourceforge.net\" rel=\"noreferrer\">FindBugs</a>, and <a href=\"http://checkstyle.sourceforge.net\" rel=\"noreferrer\">Checkstyle</a>.</p>\n\n<p><p>CPD is the PMD \"Copy/Paste Detector\" tool. I was using PMD for a little while before I noticed the <a href=\"http://pmd.sourceforge.net/cpd.html\" rel=\"noreferrer\">\"Finding Duplicated Code\" link</a> on the <a href=\"http://pmd.sourceforge.net\" rel=\"noreferrer\">PMD web page</a>.</p>\n\n<p><p>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 <a href=\"http://pmd.sourceforge.net/howtowritearule.html\" rel=\"noreferrer\">\"designer\" tool</a> that allows you to create new rules. Also, Checkstyle has the <a href=\"http://checkstyle.sourceforge.net/config_misc.html#DescendantToken\" rel=\"noreferrer\">DescendantToken</a> check that has properties that allow for substantial customization.</p>\n\n<p><p>I integrate these tools with <a href=\"http://virtualteamtls.svn.sourceforge.net/viewvc/virtualteamtls/trunk/scm/common.xml?view=markup\" rel=\"noreferrer\">an Ant-based build</a>. You can follow the link to see my commented configuration.</p>\n\n<p><p>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 <a href=\"https://stackoverflow.com/questions/79918/configuring-static-analysis-tools-for-uniformity\">here</a>)</p>\n\n<p><p>First, for warning reports, I transform the output so that each warning has the simple format:</p>\n\n<pre><code>/absolute-path/filename:line-number:column-number: warning(tool-name): message</code></pre>\n\n<p><p>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:</p>\n\n<pre><code>/project/src/com/example/Foo.java:425:9: warning(Checkstyle):Missing a Javadoc comment.</code></pre>\n\n<p><p>My warning format transformations are done by my Ant script with Ant <a href=\"http://ant.apache.org/manual/Types/filterchain.html\" rel=\"noreferrer\">filterchains</a>.</p>\n\n<p><p>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 \"<code>SuppressWarning</code>?\"</p>\n\n<p><p>For example, PMD's default configuration suppresses warning generation on lines of code with the string \"<code>NOPMD</code>\" in a comment. Also, PMD supports Java's <code>@SuppressWarnings</code> annotation. I configure PMD to use comments containing \"<code>SuppressWarning(PMD.</code>\" instead of <code>NOPMD</code> so that PMD suppressions look alike. I fill in the particular rule that is violated when using the comment style suppression:</p>\n\n<pre><code>// SuppressWarnings(PMD.PreserveStackTrace) justification: (false positive) exceptions are chained</code></pre>\n\n<p><p>Only the \"<code>SuppressWarnings(PMD.</code>\" part is significant for a comment, but it is consistent with PMD's support for the <code>@SuppressWarning</code> annotation which does recognize individual rule violations by name:</p>\n\n<pre><code>@SuppressWarnings(\"PMD.CompareObjectsWithEquals\") // justification: identity comparision intended</code></pre>\n\n<p><p>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 <code>CHECKSTYLE:OFF</code> and <code>CHECKSTYLE:ON</code>, respectively. Changing this configuration (with Checkstyle's \"SuppressionCommentFilter\") to use the strings \"<code>BEGIN&nbsp;SuppressWarnings(CheckStyle.</code>\" and \"<code>END&nbsp;SuppressWarnings(CheckStyle.</code>\" makes the controls look more like PMD:</p>\n\n<pre>\n<code>// BEGIN SuppressWarnings(Checkstyle.HiddenField) justification: \"Effective Java,\" 2nd ed., Bloch, Item 2</code>\n<code>// END SuppressWarnings(Checkstyle.HiddenField)</code>\n</pre>\n\n<p><p>With Checkstyle comments, the particular check violation (<code>HiddenField</code>) <em>is</em> significant because each check has its own \"<code>BEGIN/END</code>\" comment pair.</p>\n\n<p><p>FindBugs also supports warning generation suppression with a <code>@SuppressWarnings</code> annotation, so no further configuration is required to achieve some level of uniformity with other tools. Unfortunately, Findbugs has to support a custom <code>@SuppressWarnings</code> annotation because the built-in Java <code>@SuppressWarnings</code> annotation has a <code>SOURCE</code> 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 <code>@SuppressWarnings</code> annotation:</p>\n\n<pre><code>@edu.umd.cs.findbugs.annotations.SuppressWarnings(\"UWF&#95;FIELD&#95;NOT&#95;INITIALIZED&#95;IN&#95;CONSTRUCTOR\")</code></pre>\n\n<p><p>These techniques makes things look reasonably consistent across tools. Note that having each warning suppression contain the string \"<code>SuppressWarnings</code>\" makes it easy to run a simple search to find all instances for all tools over an entire code base.</p>\n" }, { "answer_id": 80009, "author": "Randyaa", "author_id": 9518, "author_profile": "https://Stackoverflow.com/users/9518", "pm_score": 1, "selected": false, "text": "<p>I've had good luck with Cobertura. It's a code coverage tool which can be executed via your ant script as part of your normal build and can be integrated into Hudson.</p>\n" }, { "answer_id": 83955, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 3, "selected": false, "text": "<p>I use the static analysis built into IntelliJ IDEA. Perfect integration.</p>\n\n<p>I use the code coverage built into Intellij IDEA (based on EMMA). Again, perfect integration.</p>\n\n<p>This integrated solution is reliable, powerful, and easy-to-use compared to piecing together tools from various vendors.</p>\n" }, { "answer_id": 84013, "author": "vaske", "author_id": 16039, "author_profile": "https://Stackoverflow.com/users/16039", "pm_score": 1, "selected": false, "text": "<p>Our team use PMD and Cobertura, actually our projects are maven projects and there is very simple to include plug ins for code analysis. The real question would be for specific project which analysis you need to use, my opinion is that it's you couldn't use the same plugins for each project.</p>\n" }, { "answer_id": 247984, "author": "Ken Liu", "author_id": 25688, "author_profile": "https://Stackoverflow.com/users/25688", "pm_score": 4, "selected": false, "text": "<p>I use a combination of Cobertura, Checkstyle, (Ecl)Emma and Findbugs.</p>\n\n<p><a href=\"http://www.eclemma.org/\" rel=\"noreferrer\">EclEmma</a> is an <em>awesome</em> Eclipse plugin that shows the code coverage by coloring the java source in the editor (<a href=\"http://www.eclemma.org/images/screen.png\" rel=\"noreferrer\">screenshot</a>) - the coverage is generated by running a JUnit test. This is really useful when you are trying to figure out which lines are covered in a particular class, or if you want to see just which lines are covered by a single test. This is much more user friendly and useful than generating a report and then looking through the report to see which classes have low coverage.</p>\n\n<p>The Checkstyle and Findbugs Eclipse plugins are also useful, they generate warnings in the editor as you type.</p>\n\n<p>Maven2 has report plugins that work with the above tools to generate reports at build time. We use this to get overall project reports, which are more useful when you want aggregate numbers. These are generated by our CI builds, which run using <a href=\"http://continuum.apache.org/\" rel=\"noreferrer\">Continuum</a>.</p>\n" }, { "answer_id": 3594285, "author": "OneCent", "author_id": 434162, "author_profile": "https://Stackoverflow.com/users/434162", "pm_score": 1, "selected": false, "text": "<p>in our project we use Sonar in front of checkstyle, pmd.... together with the CI (Bamboo, Hudson) we get also a nice history of our source quality and what directing we go. I do like Sonar, because you one central tool in the CI Stack that does it for you, and you can easy customize the rules for each project.</p>\n" }, { "answer_id": 7453067, "author": "Jeffrey Lee", "author_id": 844555, "author_profile": "https://Stackoverflow.com/users/844555", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.headwaysoftware.com/\" rel=\"nofollow\">Structure 101</a> is good at code analysis and finding the cyclic package dependencies.</p>\n" } ]
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/* obj *.dll *.pdb *.user *.suo _ReSharper* *.resharper* bin\n</code></pre>\n" }, { "answer_id": 27708, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 2, "selected": false, "text": "<p>I always add Thumbs.db in as well, because I hate having those files versioned. Probably more of an issue for web developers </p>\n" } ]
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 actually written yet - it might be in a cache somewhere, and reading from the same file may not actually give you the new information.</p>\n\n<p>Short version - use flush() or whatever the relevant system call is to ensure that your data is actually written to the file.</p>\n\n<p>Note I am not talking about the OS level disk cache - if your data gets into here, it should appear in a read() after this point. It may be that the language itself caches writes, waiting until a buffer fills up or file is flushed/closed.</p>\n" }, { "answer_id": 4206, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 0, "selected": false, "text": "<p>I've never tried it, but you should write a test case to see if reading from a stream after you have hit the end will work, regardless of if there is more data written to the file.</p>\n\n<p>Is there a reason you can't use a piped input/output stream? Is the data being written and read from the same application (if so, you have the data, why do you need to read from the file)?</p>\n\n<p>Otherwise, maybe read till end of file, then monitor for changes and seek to where you left off and continue... though watch out for race conditions.</p>\n" }, { "answer_id": 4498, "author": "Anthony Cramp", "author_id": 488, "author_profile": "https://Stackoverflow.com/users/488", "pm_score": 2, "selected": false, "text": "<p>The answer seems to be \"no\" ... and \"yes\". There seems to be no real way to know if a file is open for writing by another application. So, reading from such a file will just progress until content is exhausted. I took Mike's advice and wrote some test code:</p>\n\n<p>Writer.java writes a string to file and then waits for the user to hit enter before writing another line to file. The idea being that it could be started up, then a reader can be started to see how it copes with the \"partial\" file. The reader I wrote is in Reader.java.</p>\n\n<p><strong>Writer.java</strong></p>\n\n<pre><code>public class Writer extends Object\n{\n Writer () {\n\n }\n\n public static String[] strings = \n {\n \"Hello World\", \n \"Goodbye World\"\n };\n\n public static void main(String[] args) \n throws java.io.IOException {\n\n java.io.PrintWriter pw =\n new java.io.PrintWriter(new java.io.FileOutputStream(\"out.txt\"), true);\n\n for(String s : strings) {\n pw.println(s);\n System.in.read();\n }\n\n pw.close();\n }\n}\n</code></pre>\n\n<p><strong>Reader.java</strong></p>\n\n<pre><code>public class Reader extends Object\n{\n Reader () {\n\n }\n\n public static void main(String[] args) \n throws Exception {\n\n java.io.FileInputStream in = new java.io.FileInputStream(\"out.txt\");\n\n java.nio.channels.FileChannel fc = in.getChannel();\n java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(10);\n\n while(fc.read(bb) &gt;= 0) {\n bb.flip();\n while(bb.hasRemaining()) {\n System.out.println((char)bb.get());\n }\n bb.clear();\n }\n\n System.exit(0);\n }\n}\n</code></pre>\n\n<p>No guarantees that this code is best practice.</p>\n\n<p>This leaves the option suggested by Mike of periodically checking if there is new data to be read from the file. This then requires user intervention to close the file reader when it is determined that the reading is completed. Or, the reader needs to be made aware the content of the file and be able to determine and end of write condition. If the content were XML, the end of document could be used to signal this.</p>\n" }, { "answer_id": 38133, "author": "Frederic Morin", "author_id": 4064, "author_profile": "https://Stackoverflow.com/users/4064", "pm_score": 3, "selected": false, "text": "<p>You might also take a look at java channel for locking a part of a file.</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html</a></p>\n\n<p>This function of the <code>FileChannel</code> might be a start</p>\n\n<pre><code>lock(long position, long size, boolean shared) \n</code></pre>\n\n<p>An invocation of this method will block until the region can be locked</p>\n" }, { "answer_id": 154588, "author": "Joseph Gordon", "author_id": 1741, "author_profile": "https://Stackoverflow.com/users/1741", "pm_score": 7, "selected": true, "text": "<p>Could not get the example to work using <code>FileChannel.read(ByteBuffer)</code> because it isn't a blocking read. Did however get the code below to work:</p>\n\n<pre><code>boolean running = true;\nBufferedInputStream reader = new BufferedInputStream(new FileInputStream( \"out.txt\" ) );\n\npublic void run() {\n while( running ) {\n if( reader.available() &gt; 0 ) {\n System.out.print( (char)reader.read() );\n }\n else {\n try {\n sleep( 500 );\n }\n catch( InterruptedException ex ) {\n running = false;\n }\n }\n }\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>Oh, and I'll caveat this with: I'm using 1.4.2. Yes I know I'm in the stone ages still.</p>\n" }, { "answer_id": 28818516, "author": "Rodrigo Menezes", "author_id": 1255493, "author_profile": "https://Stackoverflow.com/users/1255493", "pm_score": 2, "selected": false, "text": "<p>There are a Open Source Java Graphic Tail that does this.</p>\n\n<p><a href=\"https://stackoverflow.com/a/559146/1255493\">https://stackoverflow.com/a/559146/1255493</a></p>\n\n<pre><code>public void run() {\n try {\n while (_running) {\n Thread.sleep(_updateInterval);\n long len = _file.length();\n if (len &lt; _filePointer) {\n // Log must have been jibbled or deleted.\n this.appendMessage(\"Log file was reset. Restarting logging from start of file.\");\n _filePointer = len;\n }\n else if (len &gt; _filePointer) {\n // File must have had something added to it!\n RandomAccessFile raf = new RandomAccessFile(_file, \"r\");\n raf.seek(_filePointer);\n String line = null;\n while ((line = raf.readLine()) != null) {\n this.appendLine(line);\n }\n _filePointer = raf.getFilePointer();\n raf.close();\n }\n }\n }\n catch (Exception e) {\n this.appendMessage(\"Fatal error reading log file, log tailing has stopped.\");\n }\n // dispose();\n}\n</code></pre>\n" }, { "answer_id": 32783641, "author": "ToYonos", "author_id": 2003986, "author_profile": "https://Stackoverflow.com/users/2003986", "pm_score": 3, "selected": false, "text": "<p>I totally agree with <a href=\"https://stackoverflow.com/a/10803105/2003986\">Joshua's response</a>, <a href=\"https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/input/Tailer.html\" rel=\"nofollow noreferrer\">Tailer</a> is fit for the job in this situation. Here is an example :</p>\n\n<p>It writes a line every 150 ms in a file, while reading this very same file every 2500 ms</p>\n\n<pre><code>public class TailerTest\n{\n public static void main(String[] args)\n {\n File f = new File(\"/tmp/test.txt\");\n MyListener listener = new MyListener();\n Tailer.create(f, listener, 2500);\n\n try\n {\n FileOutputStream fos = new FileOutputStream(f);\n int i = 0;\n while (i &lt; 200)\n {\n fos.write((\"test\" + ++i + \"\\n\").getBytes());\n Thread.sleep(150);\n }\n fos.close();\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }\n\n private static class MyListener extends TailerListenerAdapter\n {\n @Override\n public void handle(String line)\n {\n System.out.println(line);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 32851944, "author": "tiger.spring", "author_id": 4042626, "author_profile": "https://Stackoverflow.com/users/4042626", "pm_score": 4, "selected": false, "text": "<p>If you want to read a file while it is being written and only read the new content then following will help you achieve the same.</p>\n\n<p>To run this program you will launch it from command prompt/terminal window and pass the file name to read. It will read the file unless you kill the program.</p>\n\n<p>java FileReader c:\\myfile.txt</p>\n\n<p>As you type a line of text save it from notepad and you will see the text printed in the console.</p>\n\n<pre><code>public class FileReader {\n\n public static void main(String args[]) throws Exception {\n if(args.length&gt;0){\n File file = new File(args[0]);\n System.out.println(file.getAbsolutePath());\n if(file.exists() &amp;&amp; file.canRead()){\n long fileLength = file.length();\n readFile(file,0L);\n while(true){\n\n if(fileLength&lt;file.length()){\n readFile(file,fileLength);\n fileLength=file.length();\n }\n }\n }\n }else{\n System.out.println(\"no file to read\");\n }\n }\n\n public static void readFile(File file,Long fileLength) throws IOException {\n String line = null;\n\n BufferedReader in = new BufferedReader(new java.io.FileReader(file));\n in.skip(fileLength);\n while((line = in.readLine()) != null)\n {\n System.out.println(line);\n }\n in.close();\n }\n}\n</code></pre>\n" }, { "answer_id": 34576387, "author": "bebbo", "author_id": 1412279, "author_profile": "https://Stackoverflow.com/users/1412279", "pm_score": 2, "selected": false, "text": "<p>You can't read a file which is opened from another process using FileInputStream, FileReader or RandomAccessFile.</p>\n\n<p>But using FileChannel directly will work:</p>\n\n<pre><code>private static byte[] readSharedFile(File file) throws IOException {\n byte buffer[] = new byte[(int) file.length()];\n final FileChannel fc = FileChannel.open(file.toPath(), EnumSet.of(StandardOpenOption.READ));\n final ByteBuffer dst = ByteBuffer.wrap(buffer);\n fc.read(dst);\n fc.close();\n return buffer;\n}\n</code></pre>\n" } ]
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 it (e.g. compile) and remove it from the graph (or mark it as processed, and treat nodes with all leaves processed as leaves).</p>\n\n<p>As long as it's a DAG, this simple stack-based walk should be trivial.</p>\n" }, { "answer_id": 4185, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 1, "selected": false, "text": "<p>I've come up with a fairly naive recursive algorithm (pseudocode):</p>\n\n<pre><code>Map&lt;Object, List&lt;Object&gt;&gt; source; // map of each object to its dependency list\nList&lt;Object&gt; dest; // destination list\n\nfunction resolve(a):\n if (dest.contains(a)) return;\n foreach (b in source[a]):\n resolve(b);\n dest.add(a);\n\nforeach (a in source):\n resolve(a);\n</code></pre>\n\n<p>The biggest problem with this is that it has no ability to detect cyclic dependencies - it can go into infinite recursion (ie stack overflow ;-p). The only way around that that I can see would be to flip the recursive algorithm into an interative one with a manual stack, and manually check the stack for repeated elements.</p>\n\n<p>Anyone have something better?</p>\n" }, { "answer_id": 4577, "author": "Andrew Peters", "author_id": 608, "author_profile": "https://Stackoverflow.com/users/608", "pm_score": 7, "selected": true, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Topological_sorting\" rel=\"noreferrer\">Topological Sort</a> (From Wikipedia):</p>\n\n<blockquote>\n <p>In graph theory, a topological sort or\n topological ordering of a directed\n acyclic graph (DAG) is a linear\n ordering of its nodes in which each\n node comes before all nodes to which\n it has outbound edges. Every DAG has\n one or more topological sorts.</p>\n</blockquote>\n\n<p>Pseudo code:</p>\n\n<pre><code>L ← Empty list where we put the sorted elements\nQ ← Set of all nodes with no incoming edges\nwhile Q is non-empty do\n remove a node n from Q\n insert n into L\n for each node m with an edge e from n to m do\n remove edge e from the graph\n if m has no other incoming edges then\n insert m into Q\nif graph has edges then\n output error message (graph has a cycle)\nelse \n output message (proposed topologically sorted order: L)\n</code></pre>\n" }, { "answer_id": 473219, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>If the graph contains cycles, how can there exist allowed execution orders for your files?\nIt seems to me that if the graph contains cycles, then you have no solution, and this\nis reported correctly by the above algorithm.</p>\n" } ]
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>SqlCommand</code></li>\n<li><code>SqlDataReader</code></li>\n</ul>\n\n<p>(if you're using something else, replace <code>Sql</code> with \"Something\", like <code>MySqlConnection</code>, <code>OracleCommand</code>)</p>\n\n<p>Everything else is just built on top of that.</p>\n\n<p><strong>Example 1:</strong></p>\n\n<pre><code>using (SqlConnection connection = new SqlConnection(\"CONNECTION STRING\"))\nusing (SqlCommand command = new SqlCommand())\n{\n command.commandText = \"SELECT Name FROM Users WHERE Status = @OnlineStatus\";\n command.Connection = connection;\n command.Parameters.Add(\"@OnlineStatus\", SqlDbType.Int).Value = 1; //replace with enum\n connection.Open();\n\n using (SqlDataReader dr = command.ExecuteReader))\n {\n List&lt;string&gt; onlineUsers = new List&lt;string&gt;();\n\n while (dr.Read())\n {\n onlineUsers.Add(dr.GetString(0));\n }\n }\n}\n</code></pre>\n\n<p><strong>Example 2:</strong></p>\n\n<pre><code>using (SqlConnection connection = new SqlConnection(\"CONNECTION STRING\"))\nusing (SqlCommand command = new SqlCommand())\n{\n command.commandText = \"DELETE FROM Users where Email = @Email\";\n command.Connection = connection;\n command.Parameters.Add(\"@Email\", SqlDbType.VarChar, 100).Value = \"[email protected]\";\n connection.Open();\n command.ExecuteNonQuery();\n}\n</code></pre>\n" }, { "answer_id": 14218, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>Another way of getting a command object is to call <code>connection.CreateCommand()</code>. </p>\n\n<p>That way you shouldn't have to set the <code>Connection</code> property on the command object. </p>\n" } ]
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 = "[email protected]"; 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\">ProcessTamer</a> that \"automatize\" the process of downgrading or upgrading process priority based in your settings. </p>\n\n<p>I've been using it for two years. It's very simple but really effective!</p>\n" }, { "answer_id": 4302, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 3, "selected": false, "text": "<p>If you use <a href=\"http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx\" rel=\"noreferrer\">PowerShell</a>, you could write a script that let you change the priority of a process. I found the following PowerShell function on the <a href=\"http://monadblog.blogspot.com/2006/03/msh-how-to-change-processs-priority.html\" rel=\"noreferrer\">Monad blog</a>:</p>\n\n<pre><code>function set-ProcessPriority { \n param($processName = $(throw \"Enter process name\"), $priority = \"Normal\")\n\n get-process -processname $processname | foreach { $_.PriorityClass = $priority }\n write-host \"`\"$($processName)`\"'s priority is set to `\"$($priority)`\"\"\n}\n</code></pre>\n\n<p>From the PowerShell prompt, you would do something line:</p>\n\n<pre><code>set-ProcessPriority SomeProcessName \"High\"\n</code></pre>\n" }, { "answer_id": 4332, "author": "Stephen Pellicer", "author_id": 360, "author_profile": "https://Stackoverflow.com/users/360", "pm_score": 7, "selected": true, "text": "<p>If you want to set priority when launching a process you could use the built-in <a href=\"https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/start\" rel=\"noreferrer\">START</a> command:</p>\n\n<pre class=\"lang-batch prettyprint-override\"><code>START [\"title\"] [/Dpath] [/I] [/MIN] [/MAX] [/SEPARATE | /SHARED]\n [/LOW | /NORMAL | /HIGH | /REALTIME | /ABOVENORMAL | /BELOWNORMAL]\n [/WAIT] [/B] [command/program] [parameters]\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 675056, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>from <a href=\"http://techtasks.com/code/viewbookcode/567\" rel=\"noreferrer\">http://techtasks.com/code/viewbookcode/567</a></p>\n\n<pre><code># This code sets the priority of a process\n\n# ---------------------------------------------------------------\n# Adapted from VBScript code contained in the book:\n# \"Windows Server Cookbook\" by Robbie Allen\n# ISBN: 0-596-00633-0\n# ---------------------------------------------------------------\n\nuse Win32::OLE;\n$Win32::OLE::Warn = 3;\n\nuse constant NORMAL =&gt; 32;\nuse constant IDLE =&gt; 64;\nuse constant HIGH_PRIORITY =&gt; 128;\nuse constant REALTIME =&gt; 256;\nuse constant BELOW_NORMAL =&gt; 16384;\nuse constant ABOVE_NORMAL =&gt; 32768;\n\n# ------ SCRIPT CONFIGURATION ------\n$strComputer = '.';\n$intPID = 2880; # set this to the PID of the target process\n$intPriority = ABOVE_NORMAL; # Set this to one of the constants above\n# ------ END CONFIGURATION ---------\n\nprint \"Process PID: $intPID\\n\";\n\n$objWMIProcess = Win32::OLE-&gt;GetObject('winmgmts:\\\\\\\\' . $strComputer . '\\\\root\\\\cimv2:Win32_Process.Handle=\\'' . $intPID . '\\'');\n\nprint 'Process name: ' . $objWMIProcess-&gt;Name, \"\\n\";\n\n$intRC = $objWMIProcess-&gt;SetPriority($intPriority);\n\nif ($intRC == 0) {\n print \"Successfully set priority.\\n\";\n}\nelse {\n print 'Could not set priority. Error code: ' . $intRC, \"\\n\";\n}\n</code></pre>\n" } ]
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 results returned, but I'm also pretty sure in the datasource wizard you can go to advanced options and limit it to </p>\n\n<pre><code>SELECT TOP 3 FROM \n</code></pre>\n\n<p>which should allow you to do what you need</p>\n" }, { "answer_id": 27327, "author": "Portman", "author_id": 1690, "author_profile": "https://Stackoverflow.com/users/1690", "pm_score": 4, "selected": false, "text": "<p><strong>Yes</strong> and <strong>No</strong>.</p>\n\n<p><strong>No</strong>, you cannot limit the results within the LinqDataSource control. Because Linq uses deferred execution, the expectation is that the presentation control will do the recordset limits.</p>\n\n<p><strong>Yes</strong>, you can do this with a ListView control. The trick is to use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.datapager\" rel=\"nofollow noreferrer\">DataPager</a> control within the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.listview.layouttemplate\" rel=\"nofollow noreferrer\">LayoutTemplate</a>, like so:</p>\n\n<pre><code>&lt;LayoutTemplate&gt;\n &lt;div id=\"itemPlaceholder\" runat=\"server\" /&gt;\n &lt;asp:DataPager ID=\"DataPager1\" runat=\"server\" PageSize=\"3\"&gt;\n &lt;/asp:DataPager&gt; \n&lt;/LayoutTemplate&gt;\n</code></pre>\n\n<p>Normally, you would include controls inside the DataPager like first, last, next, and previous. But if you just make it empty, then you will only see the three results that you desire.</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 62158, "author": "Ollie", "author_id": 4453, "author_profile": "https://Stackoverflow.com/users/4453", "pm_score": 5, "selected": false, "text": "<p>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.</p>\n\n<p>e.g.</p>\n\n<pre><code>protected void lnqRecentOrder_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n DataClassesDataContext dx = new DataClassesDataContext();\n e.Result = (from o in dx.Orders\n where o.CustomerID == Int32.Parse(Request.QueryString[\"CustomerID\"])\n select o).Take(5);\n}\n</code></pre>\n" }, { "answer_id": 62196, "author": "Daniel O", "author_id": 697, "author_profile": "https://Stackoverflow.com/users/697", "pm_score": 2, "selected": false, "text": "<p>You could base your Linq query on a stored proc that only returns x number of rows using a TOP statement. Remember just because you can do all your DB code in Linq doesn't mean you should. Plus, you can tell Linq to use the same return type for the stored proc as the normal table, so all your binding will still work, and the return results will be the same type</p>\n" }, { "answer_id": 5330890, "author": "10gler", "author_id": 663178, "author_profile": "https://Stackoverflow.com/users/663178", "pm_score": 2, "selected": false, "text": "<p>You can put event Selecting of LinqDataSource:</p>\n\n<pre><code>protected void ldsLastEntries_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n e.Arguments.MaximumRows = 10;\n}\n</code></pre>\n" }, { "answer_id": 13048430, "author": "Abd-elhameed Quraim", "author_id": 1771068, "author_profile": "https://Stackoverflow.com/users/1771068", "pm_score": 3, "selected": false, "text": "<pre><code>protected void DocsData_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{\n e.Arguments.MaximumRows = 5;\n}\n</code></pre>\n" } ]
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 LastCount = mydict[temp[mydict.count - 1]]\n</code></pre>\n\n<p>But I wouldn't recommend it. There's no guarantee that the last inserted key will be at the end of the array. The ordering for Keys <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys\" rel=\"nofollow noreferrer\">on MSDN</a> is unspecified, and subject to change. In my very brief test, it does seem to be in order of insertion, but you'd be better off building in proper bookkeeping like a stack--as you suggest (though I don't see the need of a struct based on your other statements)--or single variable cache if you just need to know the latest key.</p>\n" }, { "answer_id": 4255, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 2, "selected": false, "text": "<p>I don't know if this would work because I'm pretty sure that the keys aren't stored in the order they are added, but you could cast the KeysCollection to a List and then get the last key in the list... but it would be worth having a look.</p>\n\n<p>The only other thing I can think of is to store the keys in a lookup list and add the keys to the list before you add them to the dictionary... it's not pretty tho.</p>\n" }, { "answer_id": 4258, "author": "Juan", "author_id": 550, "author_profile": "https://Stackoverflow.com/users/550", "pm_score": 3, "selected": false, "text": "<p>I think you can do something like this, the syntax might be wrong, havent used C# in a while\nTo get the last item</p>\n\n<pre><code>Dictionary&lt;string, int&gt;.KeyCollection keys = mydict.keys;\nstring lastKey = keys.Last();\n</code></pre>\n\n<p>or use Max instead of Last to get the max value, I dont know which one fits your code better.</p>\n" }, { "answer_id": 4315, "author": "Stephen Pellicer", "author_id": 360, "author_profile": "https://Stackoverflow.com/users/360", "pm_score": 2, "selected": false, "text": "<p>I agree with the second part of Patrick's answer. Even if in some tests it seems to keep insertion order, the documentation (and normal behavior for dictionaries and hashes) explicitly states the ordering is unspecified.</p>\n\n<p>You're just asking for trouble depending on the ordering of the keys. Add your own bookkeeping (as Patrick said, just a single variable for the last added key) to be sure. Also, don't be tempted by all the methods such as Last and Max on the dictionary as those are probably in relation to the key comparator (I'm not sure about that).</p>\n" }, { "answer_id": 4319, "author": "Jeremy Privett", "author_id": 560, "author_profile": "https://Stackoverflow.com/users/560", "pm_score": 2, "selected": false, "text": "<p>The way you worded the question leads me to believe that the int in the Dictionary contains the item's \"position\" on the Dictionary. Judging from the assertion that the keys aren't stored in the order that they're added, if this is correct, that would mean that keys.Count (or .Count - 1, if you're using zero-based) should still always be the number of the last-entered key?</p>\n\n<p>If that's correct, is there any reason you can't instead use Dictionary&lt;int, string&gt; so that you can use mydict[ mydict.Keys.Count ]?</p>\n" }, { "answer_id": 4589, "author": "Calanus", "author_id": 445, "author_profile": "https://Stackoverflow.com/users/445", "pm_score": 3, "selected": false, "text": "<p>Why don't you just extend the dictionary class to add in a last key inserted property. Something like the following maybe?</p>\n\n<pre><code>public class ExtendedDictionary : Dictionary&lt;string, int&gt;\n{\n private int lastKeyInserted = -1;\n\n public int LastKeyInserted\n {\n get { return lastKeyInserted; }\n set { lastKeyInserted = value; }\n }\n\n public void AddNew(string s, int i)\n {\n lastKeyInserted = i;\n\n base.Add(s, i);\n }\n}\n</code></pre>\n" }, { "answer_id": 5540, "author": "Andrew Peters", "author_id": 608, "author_profile": "https://Stackoverflow.com/users/608", "pm_score": 6, "selected": false, "text": "<p>You can use an <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary\" rel=\"nofollow noreferrer\">OrderedDictionary</a>.</p>\n\n<blockquote>\n <p>Represents a collection of key/value\n pairs that are accessible by the key\n or index.</p>\n</blockquote>\n" }, { "answer_id": 756286, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>A Dictionary is a Hash Table, so you have no idea the order of insertion!</p>\n\n<p>If you want to know the last inserted key I would suggest extending the Dictionary to include a LastKeyInserted value.</p>\n\n<p>E.g.:</p>\n\n<pre><code>public MyDictionary&lt;K, T&gt; : IDictionary&lt;K, T&gt;\n{\n private IDictionary&lt;K, T&gt; _InnerDictionary;\n\n public K LastInsertedKey { get; set; }\n\n public MyDictionary()\n {\n _InnerDictionary = new Dictionary&lt;K, T&gt;();\n }\n\n #region Implementation of IDictionary\n\n public void Add(KeyValuePair&lt;K, T&gt; item)\n {\n _InnerDictionary.Add(item);\n LastInsertedKey = item.Key;\n\n }\n\n public void Add(K key, T value)\n {\n _InnerDictionary.Add(key, value);\n LastInsertedKey = key;\n }\n\n .... rest of IDictionary methods\n\n #endregion\n\n}\n</code></pre>\n\n<p>You will run into problems however when you use <code>.Remove()</code> so to overcome this you will have to keep an ordered list of the keys inserted.</p>\n" }, { "answer_id": 2619931, "author": "Glenn Slayden", "author_id": 147511, "author_profile": "https://Stackoverflow.com/users/147511", "pm_score": 2, "selected": false, "text": "<p>In case you decide to use dangerous code that is subject to breakage, this extension function will fetch a key from a <code>Dictionary&lt;K,V&gt;</code> according to its internal indexing (which for Mono and .NET currently appears to be in the same order as you get by enumerating the <code>Keys</code> property).</p>\n\n<p>It is much preferable to use Linq: <code>dict.Keys.ElementAt(i)</code>, but that function will iterate O(N); the following is O(1) but with a reflection performance penalty.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Reflection;\n\npublic static class Extensions\n{\n public static TKey KeyByIndex&lt;TKey,TValue&gt;(this Dictionary&lt;TKey, TValue&gt; dict, int idx)\n {\n Type type = typeof(Dictionary&lt;TKey, TValue&gt;);\n FieldInfo info = type.GetField(\"entries\", BindingFlags.NonPublic | BindingFlags.Instance);\n if (info != null)\n {\n // .NET\n Object element = ((Array)info.GetValue(dict)).GetValue(idx);\n return (TKey)element.GetType().GetField(\"key\", BindingFlags.Public | BindingFlags.Instance).GetValue(element);\n }\n // Mono:\n info = type.GetField(\"keySlots\", BindingFlags.NonPublic | BindingFlags.Instance);\n return (TKey)((Array)info.GetValue(dict)).GetValue(idx);\n }\n};\n</code></pre>\n" }, { "answer_id": 4735712, "author": "Vitor Hugo", "author_id": 581486, "author_profile": "https://Stackoverflow.com/users/581486", "pm_score": 9, "selected": true, "text": "<p>As @Falanwe points out in a comment, doing something like this is <strong><em>incorrect</em></strong>:</p>\n\n<pre><code>int LastCount = mydict.Keys.ElementAt(mydict.Count -1);\n</code></pre>\n\n<p>You <strong>should not</strong> depend on the order of keys in a Dictionary. If you need ordering, you should use an <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.specialized.ordereddictionary\" rel=\"noreferrer\">OrderedDictionary</a>, as suggested in this <a href=\"https://stackoverflow.com/a/5540/1724702\">answer</a>. The other answers on this page are interesting as well.</p>\n" }, { "answer_id": 6755798, "author": "Daniel Ballinger", "author_id": 54026, "author_profile": "https://Stackoverflow.com/users/54026", "pm_score": 2, "selected": false, "text": "<p>One alternative would be a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.keyedcollection-2\" rel=\"nofollow noreferrer\">KeyedCollection</a> if the key is embedded in the value.</p>\n\n<p>Just create a basic implementation in a sealed class to use.</p>\n\n<p>So to replace <code>Dictionary&lt;string, int&gt;</code> (which isn't a very good example as there isn't a clear key for a int).</p>\n\n<pre><code>private sealed class IntDictionary : KeyedCollection&lt;string, int&gt;\n{\n protected override string GetKeyForItem(int item)\n {\n // The example works better when the value contains the key. It falls down a bit for a dictionary of ints.\n return item.ToString();\n }\n}\n\nKeyedCollection&lt;string, int&gt; intCollection = new ClassThatContainsSealedImplementation.IntDictionary();\n\nintCollection.Add(7);\n\nint valueByIndex = intCollection[0];\n</code></pre>\n" }, { "answer_id": 6759645, "author": "takrl", "author_id": 520044, "author_profile": "https://Stackoverflow.com/users/520044", "pm_score": 2, "selected": false, "text": "<p>To expand on Daniels post and his comments regarding the key, since the key is embedded within the value anyway, you could resort to using a <code>KeyValuePair&lt;TKey, TValue&gt;</code> as the value. The main reasoning for this is that, in general, the Key isn't necessarily directly derivable from the value.</p>\n\n<p>Then it'd look like this:</p>\n\n<pre><code>public sealed class CustomDictionary&lt;TKey, TValue&gt;\n : KeyedCollection&lt;TKey, KeyValuePair&lt;TKey, TValue&gt;&gt;\n{\n protected override TKey GetKeyForItem(KeyValuePair&lt;TKey, TValue&gt; item)\n {\n return item.Key;\n }\n}\n</code></pre>\n\n<p>To use this as in the previous example, you'd do:</p>\n\n<pre><code>CustomDictionary&lt;string, int&gt; custDict = new CustomDictionary&lt;string, int&gt;();\n\ncustDict.Add(new KeyValuePair&lt;string, int&gt;(\"key\", 7));\n\nint valueByIndex = custDict[0].Value;\nint valueByKey = custDict[\"key\"].Value;\nstring keyByIndex = custDict[0].Key;\n</code></pre>\n" }, { "answer_id": 29263349, "author": "Sharunas Bielskis", "author_id": 4403269, "author_profile": "https://Stackoverflow.com/users/4403269", "pm_score": 2, "selected": false, "text": "<p>You can also use SortedList and its Generic counterpart. These two classes and in Andrew Peters answer mentioned OrderedDictionary are dictionary classes in which items can be accessed by index (position) as well as by key. How to use these classes you can find: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.sortedlist\" rel=\"nofollow noreferrer\">SortedList Class</a> , <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.sortedlist-2\" rel=\"nofollow noreferrer\">SortedList Generic Class</a> .</p>\n" }, { "answer_id": 36462499, "author": "espaciomore", "author_id": 2743497, "author_profile": "https://Stackoverflow.com/users/2743497", "pm_score": 2, "selected": false, "text": "<p>A dictionary may not be very intuitive for using index for reference but, you can have similar operations with an array of <strong>KeyValuePair</strong>:</p>\n\n<p>ex.\n<code>KeyValuePair&lt;string, string&gt;[] filters;</code></p>\n" }, { "answer_id": 40397023, "author": "quicktrick", "author_id": 6123485, "author_profile": "https://Stackoverflow.com/users/6123485", "pm_score": 1, "selected": false, "text": "<p>Visual Studio's <a href=\"https://visualstudio.uservoice.com/forums/121579-visual-studio-2015/suggestions/16494583-generic-ordereddictionary\" rel=\"nofollow noreferrer\">UserVoice</a> gives a link to <a href=\"https://github.com/mattmc3/dotmore/blob/master/dotmore/Collections/Generic/OrderedDictionary.cs\" rel=\"nofollow noreferrer\">generic OrderedDictionary implementation</a> by dotmore.</p>\n\n<p>But if you only need to get key/value pairs by index and don't need to get values by keys, you may use one simple trick. Declare some generic class (I called it ListArray) as follows:</p>\n\n<pre><code>class ListArray&lt;T&gt; : List&lt;T[]&gt; { }\n</code></pre>\n\n<p>You may also declare it with constructors:</p>\n\n<pre><code>class ListArray&lt;T&gt; : List&lt;T[]&gt;\n{\n public ListArray() : base() { }\n public ListArray(int capacity) : base(capacity) { }\n}\n</code></pre>\n\n<p>For example, you read some key/value pairs from a file and just want to store them in the order they were read so to get them later by index:</p>\n\n<pre><code>ListArray&lt;string&gt; settingsRead = new ListArray&lt;string&gt;();\nusing (var sr = new StreamReader(myFile))\n{\n string line;\n while ((line = sr.ReadLine()) != null)\n {\n string[] keyValueStrings = line.Split(separator);\n for (int i = 0; i &lt; keyValueStrings.Length; i++)\n keyValueStrings[i] = keyValueStrings[i].Trim();\n settingsRead.Add(keyValueStrings);\n }\n}\n// Later you get your key/value strings simply by index\nstring[] myKeyValueStrings = settingsRead[index];\n</code></pre>\n\n<p>As you may have noticed, you can have not necessarily just pairs of key/value in your ListArray. The item arrays may be of any length, like in jagged array.</p>\n" } ]
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. Your compiler still knows <code>myInt</code> as a primitive. There's a paper about this issue at <a href=\"http://jcp.org/aboutJava/communityprocess/jsr/tiger/autoboxing.html\" rel=\"noreferrer\">jcp.org</a>.</p>\n\n<p>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).</p>\n\n<p>So unfortunately, you would have to do it like this: (kudos Patrick, I switched to your way)</p>\n\n<pre><code>Integer.toString(myInt);\n</code></pre>\n" }, { "answer_id": 4256, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 5, "selected": false, "text": "<p>Ditto on what Justin said, but you should do this instead:</p>\n\n<pre><code>Integer.toString(myInt);\n</code></pre>\n\n<p>It saves an allocation or two and is more readable.</p>\n" }, { "answer_id": 4384, "author": "dlinsin", "author_id": 198, "author_profile": "https://Stackoverflow.com/users/198", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>seems like a shortcoming of the\n specification to me</p>\n</blockquote>\n\n<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>\n\n<pre><code>public class methodOverloading{\n public static void hello(Integer x){\n System.out.println(\"Integer\");\n }\n\n public static void hello(long x){\n System.out.println(\"long\");\n }\n\n public static void main(String[] args){\n int i = 5;\n hello(i);\n }\n}\n</code></pre>\n\n<p>Here \"long\" would be printed (haven't checked it myself), because the compiler choses widening over autoboxing. Be careful when using autoboxing or don't use it at all!</p>\n" }, { "answer_id": 7083, "author": "SaM", "author_id": 883, "author_profile": "https://Stackoverflow.com/users/883", "pm_score": 4, "selected": false, "text": "<p>One other way to do it is to use:</p>\n\n<pre><code>String.valueOf(myInt);\n</code></pre>\n\n<p>This method is overloaded for every primitive type and <code>Object</code>. This way you don't even have to think about the type you're using. Implementations of the method will call the appropriate method of the given type for you, e.g. <code>Integer.toString(myInt)</code>.</p>\n\n<p>See <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/String.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/lang/String.html</a>.</p>\n" }, { "answer_id": 55352, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>In C#, integers are neither reference types nor do they have to be boxed in order for <em>ToString()</em> to be called. They <strong>are</strong> considered objects in the Framework (as a ValueType, so they have value semantics), however. In the CLR, methods on primitives are called by \"indirectly\" loading them onto the stack (ldind).</p>\n" }, { "answer_id": 128153, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 3, "selected": false, "text": "<p>The valid syntax closest to your example is</p>\n\n<pre><code>((Integer) myInt).toString();\n</code></pre>\n\n<p>When the compiler finishes, that's equivalent to</p>\n\n<pre><code>Integer.valueOf(myInt).toString();\n</code></pre>\n\n<p>However, this doesn't perform as well as the conventional usage, <code>String.valueOf(myInt)</code>, because, except in special cases, it creates a new Integer instance, then immediately throws it away, resulting in more unnecessary garbage. (A small range of integers are cached, and access by an array access.) Perhaps language designers wanted to discourage this usage for performance reasons.</p>\n\n<p>Edit: I'd appreciate it if the downvoter(s) would comment about why this is not helpful.</p>\n" }, { "answer_id": 2123426, "author": "Dan Rosenstark", "author_id": 8047, "author_profile": "https://Stackoverflow.com/users/8047", "pm_score": 2, "selected": false, "text": "<p>As everyone has pointed out, autoboxing lets you simplify some code, but you cannot pretend that primitives are complex types.</p>\n\n<p>Also interesting: <a href=\"http://gafter.blogspot.com/2008/01/is-java-dying.html\" rel=\"nofollow noreferrer\">\"autoboxing is a compiler-level hack\"</a> in Java. Autoboxing is basically a strange kludge added onto Java. Check out <a href=\"http://bexhuff.com/2006/11/java-1-5-autoboxing-wackyness\" rel=\"nofollow noreferrer\">this post</a> for more details about how strange it is.</p>\n" }, { "answer_id": 21469629, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 2, "selected": false, "text": "<p>It would be helpful if Java defined certain static methods to operate on primitive types and built into the compiler some syntactic sugar so that</p>\n\n<pre><code>5.asInteger\n</code></pre>\n\n<p>would be equivalent to</p>\n\n<pre><code>some.magic.stuff.Integer.asInteger(5);\n</code></pre>\n\n<p>I don't think such a feature would cause incompatibility with any code that compiles under the current rules, and it would help reduce syntactic clutter in many cases. If Java were to autobox primitives that were dereferenced, people might assume that it was mapping the dereferencing syntax to static method calls (which is effectively what happens in .NET), and thus that operations written in that form were no more costly than would be the equivalent static method invocations. Adding a new language feature that would encourage people to write bad code (e.g. auto-boxing dereferenced primitives) doesn't seem like a good idea, though allowing dereferencing-style methods might be.</p>\n" } ]
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 build a simple FTP client.</p>\n\n<p>You'd benefit from being able to trap and handle exceptions and reduce the security risk of having to use xp_cmdshell.</p>\n\n<p>Just some thoughts.</p>\n" }, { "answer_id": 4299, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 2, "selected": false, "text": "<p>If you need to do FTP from within the database, then I would go with a .NET assembly as Kevin suggested. That would provide the most control over the process, plus you would be able to log meaningful error messages to a table for reporting.</p>\n\n<p>Another option would be to write a command line app that read the database for commands to run. You could then define a scheduled task to call that command line app every minutes or whatever the polling period needed to be. That would be more secure than enabling CLR support in the database server.</p>\n" }, { "answer_id": 7607, "author": "BTB", "author_id": 961, "author_profile": "https://Stackoverflow.com/users/961", "pm_score": 2, "selected": false, "text": "<p>Another possibility is to use DTS or Integration Services (DTS for SQL Server 7 or 2000, SSIS for 2005 or higher). Both are from Microsoft, included in the Sql Server installation (in Standard edition at least) and have an FTP task and are designed for import/export jobs from Sql Server.</p>\n" } ]
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, child, [self()]).\n</code></pre>\n" }, { "answer_id": 4374, "author": "Greg Case", "author_id": 462, "author_profile": "https://Stackoverflow.com/users/462", "pm_score": 0, "selected": false, "text": "<p>You can use the BIF register to give the spawning / parent process a name (an atom) then refer back to the registered name from other processes.</p>\n\n<blockquote>\n <p>FUNC() -></p>\n \n <blockquote>\n <p>%% Do something<br>\n %% Then send message to parent<br>\n parent ! MESSAGE.</p>\n </blockquote>\n \n <p>...</p>\n \n <p>register(parent, self()),<br>\n spawn(MODULE, FUNC, [ARGS]).</p>\n</blockquote>\n\n<p>See <a href=\"http://www.erlang.org/doc/getting_started/conc_prog.html#3.3\" rel=\"nofollow noreferrer\">Getting Started With Erlang §3.3</a> and <a href=\"http://www.erlang.org/doc/reference_manual/processes.html#10.3\" rel=\"nofollow noreferrer\">The Erlang Reference Manual §10.3</a>.</p>\n" }, { "answer_id": 73002, "author": "user12462", "author_id": 12462, "author_profile": "https://Stackoverflow.com/users/12462", "pm_score": 2, "selected": false, "text": "<p>@Eridius' answer is the preferred way to do it. Requiring a process to register a name may have unintended side-effects such as increasing the visibility of the process not to mention the hassle of coming up with unique names when you have lots of processes.</p>\n" }, { "answer_id": 1261457, "author": "rvirding", "author_id": 77617, "author_profile": "https://Stackoverflow.com/users/77617", "pm_score": 2, "selected": false, "text": "<p>The best way is definitely to pass it as an argument to the function called to start the child process. If you are spawning funs, which generally is a Good Thing to do, be careful of doing:</p>\n\n<pre><code>spawn_link(fun () -&gt; child(self()) end)\n</code></pre>\n\n<p>which will NOT do as you intended. (Hint: when is self() called)</p>\n\n<p>Generally you should avoid registering a process, i.e. giving it a global name, unless you really want it to be globally known. Spawning a fun means that you don't have to export the spawned function as you should generally avoid exporting functions that aren't meant to be called from other modules.</p>\n" } ]
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 about 57 meg on my computer.</p>\n\n<p>My test application is as follows:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;map&gt;\n\nclass triple {\npublic:\n int x;\n int y;\n int z;\n bool operator&lt;(const triple &amp;other) const {\n if (x &lt; other.x) return true;\n if (other.x &lt; x) return false;\n if (y &lt; other.y) return true;\n if (other.y &lt; y) return false;\n return z &lt; other.z;\n }\n};\n\nint main(int, char**)\n{\n std::map&lt;triple,int&gt; data;\n triple point;\n int i;\n\n for (i = 0; i &lt; 10000000; ++i) {\n point.x = rand();\n point.y = rand();\n point.z = rand();\n //printf(\"%d %d %d %d\\n\", i, point.x, point.y, point.z);\n data[point] = i;\n }\n return 0;\n}\n</code></pre>\n\n<p>Now to dynamically choose the number of variables, the easiest solution is to represent <strong>index as a string</strong>, 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:</p>\n\n<pre><code>std::map data&lt;string,int&gt; data;\nchar ix[100];\n\nsprintf(ix, \"%d,%d\", x, y); // 2 vars\ndata[ix] = i;\n\nsprintf(ix, \"%d,%d,%d\", x, y, z); // 3 vars\ndata[ix] = i;\n</code></pre>\n" }, { "answer_id": 4354, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "<p>Hash tables have a fast insertion and look up. You could write a simple hash function since you know you'd be dealing with only integer pairs as the keys.</p>\n" }, { "answer_id": 5722, "author": "JSN", "author_id": 108465, "author_profile": "https://Stackoverflow.com/users/108465", "pm_score": 1, "selected": false, "text": "<p>The best way to implement sparse matrices is to not to implement them - atleast not on your own. I would suggest to BLAS (which I think is a part of LAPACK) which can handle really huge matrices.</p>\n" }, { "answer_id": 17051, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 2, "selected": false, "text": "<p>Small detail in the index comparison. You need to do a lexicographical compare, otherwise:</p>\n\n<pre><code>a= (1, 2, 1); b= (2, 1, 2);\n(a&lt;b) == (b&lt;a) is true, but b!=a\n</code></pre>\n\n<p>Edit: So the comparison should probably be:</p>\n\n<pre><code>return lhs.x&lt;rhs.x\n ? true \n : lhs.x==rhs.x \n ? lhs.y&lt;rhs.y \n ? true \n : lhs.y==rhs.y\n ? lhs.z&lt;rhs.z\n : false\n : false\n</code></pre>\n" }, { "answer_id": 21450, "author": "Nic Strong", "author_id": 2281, "author_profile": "https://Stackoverflow.com/users/2281", "pm_score": 4, "selected": false, "text": "<p>Boost has a templated implementation of BLAS called uBLAS that contains a sparse matrix.</p>\n\n<p><a href=\"https://www.boost.org/doc/libs/release/libs/numeric/ublas/doc/index.htm\" rel=\"nofollow noreferrer\">https://www.boost.org/doc/libs/release/libs/numeric/ublas/doc/index.htm</a></p>\n" }, { "answer_id": 39052, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 5, "selected": false, "text": "<p>The accepted answer recommends using strings to represent multi-dimensional indices.</p>\n<p>However, constructing strings is needlessly wasteful for this. If the size isn’t known at compile time (and thus <code>std::tuple</code> doesn’t work), <code>std::vector</code> works well as an index, both with hash maps and ordered trees. For <code>std::map</code>, this is almost trivial:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;map&gt;\n\nusing index_type = std::vector&lt;int&gt;;\n\ntemplate &lt;typename T&gt;\nusing sparse_array = std::map&lt;index_type, T&gt;;\n</code></pre>\n<p>For <code>std::unordered_map</code> (or similar hash table-based dictionaries) it’s slightly more work, since <code>std::vector</code> does not specialise <code>std::hash</code>:</p>\n<pre><code>#include &lt;vector&gt;\n#include &lt;unordered_map&gt;\n#include &lt;numeric&gt;\n\nusing index_type = std::vector&lt;int&gt;;\n\nstruct index_hash {\n std::size_t operator()(index_type const&amp; i) const noexcept {\n // Like boost::hash_combine; there might be some caveats, see\n // &lt;https://stackoverflow.com/a/50978188/1968&gt;\n auto const hash_combine = [](auto seed, auto x) {\n return std::hash&lt;int&gt;()(x) + 0x9e3779b9 + (seed &lt;&lt; 6) + (seed &gt;&gt; 2);\n };\n return std::accumulate(i.begin() + 1, i.end(), i[0], hash_combine);\n }\n};\n\ntemplate &lt;typename T&gt;\nusing sparse_array = std::unordered_map&lt;index_type, T, index_hash&gt;;\n</code></pre>\n<p>Either way, the usage is the same:</p>\n<pre><code>int main() {\n using i = index_type;\n\n auto x = sparse_array&lt;int&gt;();\n x[i{1, 2, 3}] = 42;\n x[i{4, 3, 2}] = 23;\n\n std::cout &lt;&lt; x[i{1, 2, 3}] + x[i{4, 3, 2}] &lt;&lt; '\\n'; // 65\n}\n</code></pre>\n" }, { "answer_id": 1484067, "author": "Nicholas Jordan", "author_id": 177505, "author_profile": "https://Stackoverflow.com/users/177505", "pm_score": 0, "selected": false, "text": "<p>Since only values with [a][b][c]...[w][x][y][z] are of consequence, we only store the indice themselves, not the value 1 which is just about everywhere - always the same + no way to hash it. Noting that the curse of dimensionality is present, suggest go with some established tool NIST or Boost, at least read the sources for that to circumvent needless blunder. </p>\n\n<p>If the work needs to capture the temporal dependence distributions and parametric tendencies of unknown data sets, then a Map or B-Tree with uni-valued root is probably not practical. We can store only the indice themselves, hashed if ordering ( sensibility for presentation ) can subordinate to reduction of time domain at run-time, for all 1 values. Since non-zero values other than one are few, an obvious candidate for those is whatever data-structure you can find readily and understand. If the data set is truly vast-universe sized I suggest some sort of sliding window that manages file / disk / persistent-io yourself, moving portions of the data into scope as need be. ( writing code that you can understand ) If you are under commitment to provide actual solution to a working group, failure to do so leaves you at the mercy of consumer grade operating systems that have the sole goal of taking your lunch away from you.</p>\n" }, { "answer_id": 24370334, "author": "eold", "author_id": 395744, "author_profile": "https://Stackoverflow.com/users/395744", "pm_score": 0, "selected": false, "text": "<p>Here is a relatively simple implementation that should provide a reasonable fast lookup (using a hash table) as well as fast iteration over non-zero elements in a row/column.</p>\n\n<pre><code>// Copyright 2014 Leo Osvald\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n#ifndef UTIL_IMMUTABLE_SPARSE_MATRIX_HPP_\n#define UTIL_IMMUTABLE_SPARSE_MATRIX_HPP_\n\n#include &lt;algorithm&gt;\n#include &lt;limits&gt;\n#include &lt;map&gt;\n#include &lt;type_traits&gt;\n#include &lt;unordered_map&gt;\n#include &lt;utility&gt;\n#include &lt;vector&gt;\n\n// A simple time-efficient implementation of an immutable sparse matrix\n// Provides efficient iteration of non-zero elements by rows/cols,\n// e.g. to iterate over a range [row_from, row_to) x [col_from, col_to):\n// for (int row = row_from; row &lt; row_to; ++row) {\n// for (auto col_range = sm.nonzero_col_range(row, col_from, col_to);\n// col_range.first != col_range.second; ++col_range.first) {\n// int col = *col_range.first;\n// // use sm(row, col)\n// ...\n// }\ntemplate&lt;typename T = double, class Coord = int&gt;\nclass SparseMatrix {\n struct PointHasher;\n typedef std::map&lt; Coord, std::vector&lt;Coord&gt; &gt; NonZeroList;\n typedef std::pair&lt;Coord, Coord&gt; Point;\n\n public:\n typedef T ValueType;\n typedef Coord CoordType;\n typedef typename NonZeroList::mapped_type::const_iterator CoordIter;\n typedef std::pair&lt;CoordIter, CoordIter&gt; CoordIterRange;\n\n SparseMatrix() = default;\n\n // Reads a matrix stored in MatrixMarket-like format, i.e.:\n // &lt;num_rows&gt; &lt;num_cols&gt; &lt;num_entries&gt;\n // &lt;row_1&gt; &lt;col_1&gt; &lt;val_1&gt;\n // ...\n // Note: the header (lines starting with '%' are ignored).\n template&lt;class InputStream, size_t max_line_length = 1024&gt;\n void Init(InputStream&amp; is) {\n rows_.clear(), cols_.clear();\n values_.clear();\n\n // skip the header (lines beginning with '%', if any)\n decltype(is.tellg()) offset = 0;\n for (char buf[max_line_length + 1];\n is.getline(buf, sizeof(buf)) &amp;&amp; buf[0] == '%'; )\n offset = is.tellg();\n is.seekg(offset);\n\n size_t n;\n is &gt;&gt; row_count_ &gt;&gt; col_count_ &gt;&gt; n;\n values_.reserve(n);\n while (n--) {\n Coord row, col;\n typename std::remove_cv&lt;T&gt;::type val;\n is &gt;&gt; row &gt;&gt; col &gt;&gt; val;\n values_[Point(--row, --col)] = val;\n rows_[col].push_back(row);\n cols_[row].push_back(col);\n }\n SortAndShrink(rows_);\n SortAndShrink(cols_);\n }\n\n const T&amp; operator()(const Coord&amp; row, const Coord&amp; col) const {\n static const T kZero = T();\n auto it = values_.find(Point(row, col));\n if (it != values_.end())\n return it-&gt;second;\n return kZero;\n }\n\n CoordIterRange\n nonzero_col_range(Coord row, Coord col_from, Coord col_to) const {\n CoordIterRange r;\n GetRange(cols_, row, col_from, col_to, &amp;r);\n return r;\n }\n\n CoordIterRange\n nonzero_row_range(Coord col, Coord row_from, Coord row_to) const {\n CoordIterRange r;\n GetRange(rows_, col, row_from, row_to, &amp;r);\n return r;\n }\n\n Coord row_count() const { return row_count_; }\n Coord col_count() const { return col_count_; }\n size_t nonzero_count() const { return values_.size(); }\n size_t element_count() const { return size_t(row_count_) * col_count_; }\n\n private:\n typedef std::unordered_map&lt;Point,\n typename std::remove_cv&lt;T&gt;::type,\n PointHasher&gt; ValueMap;\n\n struct PointHasher {\n size_t operator()(const Point&amp; p) const {\n return p.first &lt;&lt; (std::numeric_limits&lt;Coord&gt;::digits &gt;&gt; 1) ^ p.second;\n }\n };\n\n static void SortAndShrink(NonZeroList&amp; list) {\n for (auto&amp; it : list) {\n auto&amp; indices = it.second;\n indices.shrink_to_fit();\n std::sort(indices.begin(), indices.end());\n }\n\n // insert a sentinel vector to handle the case of all zeroes\n if (list.empty())\n list.emplace(Coord(), std::vector&lt;Coord&gt;(Coord()));\n }\n\n static void GetRange(const NonZeroList&amp; list, Coord i, Coord from, Coord to,\n CoordIterRange* r) {\n auto lr = list.equal_range(i);\n if (lr.first == lr.second) {\n r-&gt;first = r-&gt;second = list.begin()-&gt;second.end();\n return;\n }\n\n auto begin = lr.first-&gt;second.begin(), end = lr.first-&gt;second.end();\n r-&gt;first = lower_bound(begin, end, from);\n r-&gt;second = lower_bound(r-&gt;first, end, to);\n }\n\n ValueMap values_;\n NonZeroList rows_, cols_;\n Coord row_count_, col_count_;\n};\n\n#endif /* UTIL_IMMUTABLE_SPARSE_MATRIX_HPP_ */\n</code></pre>\n\n<p>For simplicity, it's <code>immutable</code>, but you can can make it mutable; be sure to change <code>std::vector</code> to <code>std::set</code> if you want a reasonable efficient \"insertions\" (changing a zero to a non-zero).</p>\n" }, { "answer_id": 27696214, "author": "Emile Cormier", "author_id": 245265, "author_profile": "https://Stackoverflow.com/users/245265", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://eigen.tuxfamily.org/\" rel=\"noreferrer\">Eigen</a> is a C++ linear algebra library that has an <a href=\"http://eigen.tuxfamily.org/dox/group__SparseQuickRefPage.html\" rel=\"noreferrer\">implementation</a> of a sparse matrix. It even supports matrix operations and solvers (LU factorization etc) that are optimized for sparse matrices.</p>\n" }, { "answer_id": 39989181, "author": "BenGoldberg", "author_id": 3093194, "author_profile": "https://Stackoverflow.com/users/3093194", "pm_score": 0, "selected": false, "text": "<p>I would suggest doing something like:</p>\n\n<pre><code>typedef std::tuple&lt;int, int, int&gt; coord_t;\ntypedef boost::hash&lt;coord_t&gt; coord_hash_t;\ntypedef std::unordered_map&lt;coord_hash_t, int, c_hash_t&gt; sparse_array_t;\n\nsparse_array_t the_data;\nthe_data[ { x, y, z } ] = 1; /* list-initialization is cool */\n\nfor( const auto&amp; element : the_data ) {\n int xx, yy, zz, val;\n std::tie( std::tie( xx, yy, zz ), val ) = element;\n /* ... */\n}\n</code></pre>\n\n<p>To help keep your data sparse, you might want to write a subclass of <code>unorderd_map</code>, whose iterators automatically skip over (and erase) any items with a value of 0.</p>\n" }, { "answer_id": 41024354, "author": "Validus Oculus", "author_id": 1516116, "author_profile": "https://Stackoverflow.com/users/1516116", "pm_score": 3, "selected": false, "text": "<p>Complete list of solutions can be found in the wikipedia. For convenience, I have quoted relevant sections as follows.</p>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Sparse_matrix#Dictionary_of_keys_.28DOK.29\" rel=\"noreferrer\">https://en.wikipedia.org/wiki/Sparse_matrix#Dictionary_of_keys_.28DOK.29</a></p>\n\n<p><strong>Dictionary of keys (DOK)</strong></p>\n\n<blockquote>\n <p>DOK consists of a dictionary that maps (row, column)-pairs to the\n value of the elements. Elements that are missing from the dictionary\n are taken to be zero. The format is good for incrementally\n constructing a sparse matrix in random order, but poor for iterating\n over non-zero values in lexicographical order. One typically\n constructs a matrix in this format and then converts to another more\n efficient format for processing.[1]</p>\n</blockquote>\n\n<p><strong>List of lists (LIL)</strong></p>\n\n<blockquote>\n <p>LIL stores one list per row, with each entry containing the column\n index and the value. Typically, these entries are kept sorted by\n column index for faster lookup. This is another format good for\n incremental matrix construction.[2]</p>\n</blockquote>\n\n<p><strong>Coordinate list (COO)</strong></p>\n\n<blockquote>\n <p>COO stores a list of (row, column, value) tuples. Ideally, the entries\n are sorted (by row index, then column index) to improve random access\n times. This is another format which is good for incremental matrix\n construction.[3]</p>\n</blockquote>\n\n<p><strong>Compressed sparse row (CSR, CRS or Yale format)</strong></p>\n\n<blockquote>\n <p>The compressed sparse row (CSR) or compressed row storage (CRS) format\n represents a matrix M by three (one-dimensional) arrays, that\n respectively contain nonzero values, the extents of rows, and column\n indices. It is similar to COO, but compresses the row indices, hence\n the name. This format allows fast row access and matrix-vector\n multiplications (Mx).</p>\n</blockquote>\n" } ]
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 path.</p>\n" }, { "answer_id": 4385, "author": "Peter Coulton", "author_id": 117, "author_profile": "https://Stackoverflow.com/users/117", "pm_score": 8, "selected": true, "text": "<p>This should work </p>\n\n<pre><code>$root = realpath($_SERVER[\"DOCUMENT_ROOT\"]);\n\ninclude \"$root/inc/include1.php\";\n</code></pre>\n\n<hr>\n\n<p><strong>Edit:</strong> added imporvement by <a href=\"https://stackoverflow.com/questions/4369/include-files-requiring-an-absolute-path#4388\">aussieviking</a></p>\n" }, { "answer_id": 4388, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 3, "selected": false, "text": "<p>have a look at <a href=\"http://au.php.net/reserved.variables\" rel=\"nofollow noreferrer\">http://au.php.net/reserved.variables</a></p>\n\n<p>I think the variable you are looking for is: <code>$_SERVER[\"DOCUMENT_ROOT\"]</code></p>\n" }, { "answer_id": 4408, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 6, "selected": false, "text": "<p>You can use relative paths. Try <code>__FILE__</code>. This is a PHP constant which always returns the path/filename of the script it is in. So, in <code>soap.php</code>, you could do:</p>\n\n<pre><code>include dirname(__FILE__).'/../inc/include.php';\n</code></pre>\n\n<blockquote>\n <p>The full path and filename of the\n file. If used inside an include, the\n name of the included file is returned.\n Since PHP 4.0.2, <code>__FILE__</code> always\n contains an absolute path with\n symlinks resolved whereas in older\n versions it contained relative path\n under some circumstances.\n <a href=\"http://us2.php.net/constants.predefined\" rel=\"noreferrer\">(source)</a></p>\n</blockquote>\n\n<p>Another solution would be to set an <strong>include path</strong> in your httpd.conf or an .htaccess file.</p>\n" }, { "answer_id": 5187, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 1, "selected": false, "text": "<p>I think the best way is to put your includes in your PHP include path. There are various ways to do this depending on your setup. </p>\n\n<p>Then you can simply refer to </p>\n\n<pre><code>require_once 'inc1.php';\n</code></pre>\n\n<p>from inside any file regardless of where it is whether in your includes or in your web accessible files, or any level of nested subdirectories.</p>\n\n<p>This allows you to have your include files outside the web server root, which is a best practice.</p>\n\n<p>e.g. </p>\n\n<pre><code>site directory\n html (web root)\n your web-accessible files\n includes\n your include files\n</code></pre>\n\n<p>Also, check out __autoload for lazy loading of class files</p>\n\n<p><a href=\"http://www.google.com/search?q=setting+php+include+path\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=setting+php+include+path</a></p>\n\n<p><a href=\"http://www.google.com/search?q=__autoload\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=__autoload</a></p>\n" }, { "answer_id": 6463, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 0, "selected": false, "text": "<blockquote>\n <blockquote>\n <p>@Flubba, does this allow me to have folders inside my include directory? flat include directories give me nightmares. as the whole objects directory should be in the inc directory.</p>\n </blockquote>\n</blockquote>\n\n<p>Oh yes, absolutely. So for example, we use a single layer of subfolders, generally:</p>\n\n<pre><code>require_once('library/string.class.php')\n</code></pre>\n\n<p>You need to be careful with relying on the include path too much in really high traffic sites, because php has to hunt through the current directory and then all the directories on the include path in order to see if your file is there and this can slow things up if you're getting hammered. </p>\n\n<p>So for example if you're doing MVC, you'd put the path to your application directoy in the include path and then specify refer to things in the form</p>\n\n<pre><code>'model/user.class'\n'controllers/front.php'\n</code></pre>\n\n<p>or whatever.</p>\n\n<p>But generally speaking, it just lets you work with really short paths in your PHP that will work from anywhere and it's a lot easier to read than all that realpath document root malarkey. </p>\n\n<p>The benefit of those script-based alternatives others have suggested is they work anywhere, even on shared boxes; setting the include path requires a little more thought and effort but as I mentioned lets you start using __autoload which just the coolest.</p>\n" }, { "answer_id": 53079, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 2, "selected": false, "text": "<p>Another option, related to Kevin's, is use <code>__FILE__</code>, but instead replace the php file name from within it:</p>\n\n<pre><code>&lt;?php\n\n$docRoot = str_replace($_SERVER['SCRIPT_NAME'], '', __FILE__);\nrequire_once($docRoot . '/lib/include.php');\n\n?&gt;\n</code></pre>\n\n<p>I've been using this for a while. The only problem is sometimes you don't have <code>$_SERVER['SCRIPT_NAME']</code>, but sometimes there is another variable similar.</p>\n" }, { "answer_id": 93036, "author": "Sam McAfee", "author_id": 577, "author_profile": "https://Stackoverflow.com/users/577", "pm_score": 3, "selected": false, "text": "<p>Another way to handle this that removes any need for includes at all is to use the <a href=\"http://www.php.net/manual/en/language.oop5.autoload.php\" rel=\"noreferrer\">autoload</a> feature. Including everything your script needs \"Just in Case\" can impede performance. If your includes are all class or interface definitions, and you want to load them only when needed, you can overload the <code>__autoload()</code> function with your own code to find the appropriate class file and load it only when it's called. Here is the example from the manual:</p>\n\n<pre><code>function __autoload($class_name) {\n require_once $class_name . '.php';\n}\n\n$obj = new MyClass1();\n$obj2 = new MyClass2(); \n</code></pre>\n\n<p>As long as you set your include_path variables accordingly, you never need to include a class file again.</p>\n" }, { "answer_id": 9233260, "author": "Thane Gill", "author_id": 1202754, "author_profile": "https://Stackoverflow.com/users/1202754", "pm_score": 2, "selected": false, "text": "<p>I found this to work very well!</p>\n\n<pre><code>function findRoot() { \n return(substr($_SERVER[\"SCRIPT_FILENAME\"], 0, (stripos($_SERVER[\"SCRIPT_FILENAME\"], $_SERVER[\"SCRIPT_NAME\"])+1)));\n}\n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>&lt;?php\n\nfunction findRoot() {\n return(substr($_SERVER[\"SCRIPT_FILENAME\"], 0, (stripos($_SERVER[\"SCRIPT_FILENAME\"], $_SERVER[\"SCRIPT_NAME\"])+1)));\n}\n\ninclude(findRoot() . 'Post.php');\n$posts = getPosts(findRoot() . 'posts_content');\n\ninclude(findRoot() . 'includes/head.php');\n\nfor ($i=(sizeof($posts)-1); 0 &lt;= $i; $i--) {\n $posts[$i]-&gt;displayArticle();\n}\n\ninclude(findRoot() . 'includes/footer.php');\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 29608002, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1)).\"/path/to/file.php\");\n</code></pre>\n\n<p>I use this line of code. It goes back to the \"top\" of the site tree, then goes to the file desired.</p>\n\n<p>For example, let's say i have this file tree:<br></p>\n\n<blockquote>\n <p>domain.com/aaa/index.php<br>\n domain.com/bbb/ccc/ddd/index.php<br>\n domain.com/_resources/functions.php<br></p>\n</blockquote>\n\n<p>I can include the functions.php file from wherever i am, just by copy pasting</p>\n\n<pre><code>require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1)).\"/_resources/functions.php\");\n</code></pre>\n\n<p>If you need to use this code many times, you may create a function that returns the <code>str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))</code> part. Then just insert this function in the first file you include. I have an \"initialize.php\" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named <code>path_back</code>):</p>\n\n<pre><code>require(path_back().\"/_resources/another_php_file.php\");\n</code></pre>\n" }, { "answer_id": 50250763, "author": "yuvraj", "author_id": 9670536, "author_profile": "https://Stackoverflow.com/users/9670536", "pm_score": 0, "selected": false, "text": "<p>If you are going to include specific path in most of the files in your application, create a Global variable to your root folder.</p>\n\n<pre><code>define(\"APPLICATION_PATH\", realpath(dirname(__FILE__) . '/../app'));\nor \ndefine(\"APPLICATION_PATH\", realpath(DIR(__FILE__) . '/../app'));\n</code></pre>\n\n<p>Now this Global variable \"<em>APPLICATION_PATH</em>\" can be used to include all the files instead of calling realpath() everytime you include a new file.</p>\n\n<p>EX: </p>\n\n<pre><code>include(APPLICATION_PATH .\"/config/config.ini\";\n</code></pre>\n\n<p>Hope it helps ;-)</p>\n" } ]
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 MySQL console client with the -u root option.</p>\n</blockquote>\n<p>List all the users;</p>\n<pre><code>SELECT * FROM mysql.user;\n</code></pre>\n<p>Reset password;</p>\n<pre><code>UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';\n</code></pre>\n<hr />\n<p>But <strong>DO NOT FORGET</strong> to</p>\n<blockquote>\n<p>Stop the MySQL process</p>\n<p>Start the MySQL Process normally (i.e. without the --skip-grant-tables option)</p>\n</blockquote>\n<p>when you are finished. Otherwise, your database's security could be compromised.</p>\n" }, { "answer_id": 4403, "author": "jake", "author_id": 389, "author_profile": "https://Stackoverflow.com/users/389", "pm_score": 6, "selected": false, "text": "<p>Unfortunately your user password is irretrievable. It has been hashed with a one way hash which if you don't know is irreversible. I recommend go with Xenph Yan above and just create an new one.</p>\n\n<p>You can also use the following procedure from <a href=\"http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html\" rel=\"noreferrer\">the manual</a> for resetting the password for any MySQL <em>root</em> accounts on Windows: </p>\n\n<ol>\n<li>Log on to your system as Administrator. </li>\n<li>Stop the MySQL server if it is running. For a server that is running as a Windows service, go to\nthe Services manager: </li>\n</ol>\n\n<blockquote>\n <p>Start Menu -> Control Panel -> Administrative Tools -> Services</p>\n</blockquote>\n\n<p>Then find the MySQL service in the list, and stop it. If your server is\nnot running as a service, you may need to use the Task Manager to force it to stop.</p>\n\n<ol start=\"3\">\n<li><p>Create a text file and place the following statements in it. Replace the password with the password that you want to use.</p>\n\n<pre><code>UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';\nFLUSH PRIVILEGES;\n</code></pre>\n\n<p>The <em>UPDATE</em> and <em>FLUSH</em> statements each must be written on a single line. The <em>UPDATE</em> statement resets the password for all existing root accounts, and the <em>FLUSH</em> statement tells the server to reload the grant tables into memory.</p></li>\n<li>Save the file. For this example, the file will be named <em>C:\\mysql-init.txt.</em></li>\n<li><p>Open a console window to get to the command prompt: </p>\n\n<blockquote>\n <p>Start Menu -> Run -> cmd</p>\n</blockquote></li>\n<li><p>Start the MySQL server with the special <em>--init-file</em> option:</p>\n\n<pre><code>C:\\&gt; C:\\mysql\\bin\\mysqld-nt --init-file = C:\\mysql-init.txt\n</code></pre>\n\n<p>If you installed MySQL to a location other than <em>C:\\mysql</em>, adjust the command accordingly.</p>\n\n<p>The server executes the contents of the file named by the <em>--init-file</em> option at startup, changing each <em>root</em> account password.</p>\n\n<p>You can also add the <em>--console</em> option to the command if you want server output to appear in the console window rather than in a log file.</p>\n\n<p>If you installed MySQL using the MySQL Installation Wizard, you may need to specify a <em>--defaults-file</em> option:</p>\n\n<pre><code>C:\\&gt; \"C:\\Program Files\\MySQL\\MySQL Server 5.0\\bin\\mysqld-nt.exe\" --defaults-file=\"C:\\Program Files\\MySQL\\MySQL Server 5.0\\my.ini\" --init-file=C:\\mysql-init.txt\n</code></pre>\n\n<p>The appropriate <em>--defaults-file</em> setting can be found using the Services Manager:</p>\n\n<blockquote>\n <p>Start Menu -> Control Panel -> Administrative Tools -> Services</p>\n</blockquote>\n\n<p>Find the MySQL service in the list, right-click on it, and choose the Properties option. The Path to executable field contains the <em>--defaults-file</em> setting.</p></li>\n<li>After the server has started successfully, delete <em>C:\\mysql-init.txt</em>.</li>\n<li>Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.</li>\n</ol>\n\n<p>You should now be able to connect to MySQL as root using the new password. </p>\n" }, { "answer_id": 8078308, "author": "ThinkingMonkey", "author_id": 858515, "author_profile": "https://Stackoverflow.com/users/858515", "pm_score": 5, "selected": false, "text": "<p>An improvement to the most useful answer here:<br/></p>\n\n<blockquote>\n <p>1] No need to restart the mysql server <br/>\n 2] Security concern for a MySQL server connected to a network<br/></p>\n</blockquote>\n\n<p>There is no need to restart the MySQL server.</p>\n\n<p>use <code>FLUSH PRIVILEGES;</code> after the update mysql.user statement for password change.</p>\n\n<blockquote>\n <p>The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.</p>\n</blockquote>\n\n<p>The <code>--skip-grant-options</code> enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to </p>\n\n<blockquote>\n <p>use <em>--skip-grant-tables</em> in conjunction with <em>--skip-networking</em> to prevent remote clients from connecting. </p>\n</blockquote>\n\n<p>from: reference: <a href=\"http://dev.mysql.com/doc/refman/5.6/en/resetting-permissions.html#resetting-permissions-generic\" rel=\"noreferrer\">resetting-permissions-generic</a></p>\n" }, { "answer_id": 27244876, "author": "Syeful Islam", "author_id": 1468773, "author_profile": "https://Stackoverflow.com/users/1468773", "pm_score": 2, "selected": false, "text": "<p>Login MySql from windows cmd using existing user:</p>\n\n<blockquote>\n <blockquote>\n <p>mysql -u username -p<br>\n Enter password:****</p>\n </blockquote>\n</blockquote>\n\n<p>Then run the following command:</p>\n\n<pre><code>mysql&gt; SELECT * FROM mysql.user;\n</code></pre>\n\n<p>After that copy encrypted md5 password for corresponding user and there are several online password decrypted application available in web. Using this decrypt password and use this for login in next time.\nor update user password using flowing command:</p>\n\n<pre><code>mysql&gt; UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';\n</code></pre>\n\n<p>Then login using the new password and user.</p>\n" }, { "answer_id": 30655524, "author": "shine", "author_id": 4599830, "author_profile": "https://Stackoverflow.com/users/4599830", "pm_score": -1, "selected": false, "text": "<p>Although a strict, logical, computer science'ish interpretation of the op's question would be to require <strong>both</strong> \"How do I retrieve my MySQL username\" <strong>and</strong> \"password\" - I thought It might be useful to someone to also address the <strong>OR</strong> interpretation. In other words ...</p>\n\n<p>1) How do I retrieve my MySQL username?</p>\n\n<p><strong>OR</strong></p>\n\n<p>2) password</p>\n\n<p>This latter condition seems to have been amply addressed already so I won't bother with it. The following is a solution for the case \"How do i retreive my MySQL username\" alone. HIH.</p>\n\n<p>To find your mysql username run the following commands from the mysql shell ...</p>\n\n<p>SELECT User FROM mysql.user;</p>\n\n<p>it will print a table of all mysql users.</p>\n" }, { "answer_id": 33506775, "author": "snemarch", "author_id": 430360, "author_profile": "https://Stackoverflow.com/users/430360", "pm_score": 3, "selected": false, "text": "<p>While you can't directly recover a MySQL password without bruteforcing, there might be another way - if you've used MySQL Workbench to connect to the database, and have saved the credentials to the \"vault\", you're golden.</p>\n\n<p>On Windows, the credentials are stored in <strong>%APPDATA%\\MySQL\\Workbench\\workbench_user_data.dat</strong> - encrypted with <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa380261%28v=vs.85%29.aspx\" rel=\"noreferrer\">CryptProtectData</a> (without any additional entropy). Decrypting is easy peasy:</p>\n\n<pre><code>std::vector&lt;unsigned char&gt; decrypt(BYTE *input, size_t length) {\n DATA_BLOB inblob { length, input };\n DATA_BLOB outblob;\n\n if (!CryptUnprotectData(&amp;inblob, NULL, NULL, NULL, NULL, CRYPTPROTECT_UI_FORBIDDEN, &amp;outblob)) {\n throw std::runtime_error(\"Couldn't decrypt\");\n }\n\n std::vector&lt;unsigned char&gt; output(length);\n memcpy(&amp;output[0], outblob.pbData, outblob.cbData);\n\n return output;\n}\n</code></pre>\n\n<p>Or you can check out this <a href=\"https://www.donationcoder.com/forum/index.php?topic=41860.msg391762#msg391762\" rel=\"noreferrer\">DonationCoder thread</a> for source + executable of a quick-and-dirty implementation.</p>\n" }, { "answer_id": 34945832, "author": "Sajjad Ashraf", "author_id": 1131673, "author_profile": "https://Stackoverflow.com/users/1131673", "pm_score": 3, "selected": false, "text": "<p>If you have root access to the server where mysql is running you should stop the mysql server using this command</p>\n\n<pre><code>sudo service mysql stop\n</code></pre>\n\n<p>Now start mysql using this command</p>\n\n<pre><code>sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &amp;\n</code></pre>\n\n<p>Now you can login to mysql using </p>\n\n<pre><code>sudo mysql\nFLUSH PRIVILEGES;\nSET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');\n</code></pre>\n\n<p>Full instructions can be found here <a href=\"http://www.techmatterz.com/recover-mysql-root-password/\" rel=\"noreferrer\">http://www.techmatterz.com/recover-mysql-root-password/</a></p>\n" }, { "answer_id": 47018488, "author": "samplesize1", "author_id": 3524173, "author_profile": "https://Stackoverflow.com/users/3524173", "pm_score": 0, "selected": false, "text": "<p>IF you happen to have ODBC set up, you can get the password from the ODBC config file. This is in /etc/odbc.ini for Linux and in the Software/ODBC folder in the registry in Windows (there are several - it may take some hunting)</p>\n" }, { "answer_id": 49207760, "author": "S.M.Mousavi", "author_id": 1074799, "author_profile": "https://Stackoverflow.com/users/1074799", "pm_score": 3, "selected": false, "text": "<h2>Do it without down time</h2>\n\n<p>Run following command in the Terminal to connect to the DBMS (you need root access): </p>\n\n<pre><code>sudo mysql -u root -p;\n</code></pre>\n\n<p>run update password of the target user (for my example username is <code>mousavi</code> and it's password must be <code>123456</code>): </p>\n\n<pre><code>UPDATE mysql.user SET authentication_string=PASSWORD('123456') WHERE user='mousavi'; \n</code></pre>\n\n<p>at this point you need to do a flush to apply changes: </p>\n\n<pre><code>FLUSH PRIVILEGES;\n</code></pre>\n\n<p>Done! You did it without any stop or restart mysql service.</p>\n" }, { "answer_id": 58515936, "author": "user12261119", "author_id": 12261119, "author_profile": "https://Stackoverflow.com/users/12261119", "pm_score": 0, "selected": false, "text": "<p>Save the file. For this example, the file will be named C:\\mysql-init.txt.\nit asking administrative permisions for saving the file</p>\n" }, { "answer_id": 72846018, "author": "Raikish", "author_id": 8018902, "author_profile": "https://Stackoverflow.com/users/8018902", "pm_score": 0, "selected": false, "text": "<p><strong>After MySQL 5.7.6 and MariaDB 10.1.20 (currently in 2022) you can:</strong></p>\n<p>Update a mysql user password having access to root user</p>\n<pre><code>ALTER USER 'some_user_name'@'localhost' IDENTIFIED BY 'a_super_secure_password';\n</code></pre>\n<p>Update mysql root user</p>\n<pre><code>ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password by 'mynewpassword';\n</code></pre>\n<p>List all users</p>\n<pre><code>select user from mysql.user;\n</code></pre>\n" } ]
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</code></pre>\n\n<p>This will generate a script.</p>\n\n<p>Adding clause to check existence of table before deleting:</p>\n\n<pre><code>SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n</code></pre>\n" }, { "answer_id": 4400, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/264/xenph-yan\">Xenph Yan</a>'s answer was far cleaner than mine but here is mine all the same.</p>\n\n<pre><code>DECLARE @startStr AS Varchar (20)\nSET @startStr = 'tableName'\n\nDECLARE @startStrLen AS int\nSELECT @startStrLen = LEN(@startStr)\n\nSELECT 'DROP TABLE ' + name FROM sysobjects\nWHERE type = 'U' AND LEFT(name, @startStrLen) = @startStr\n</code></pre>\n\n<p>Just change <code>tableName</code> to the characters that you want to search with.</p>\n" }, { "answer_id": 4401, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "\n\n<p>You may need to modify the query to include the owner if there's more than one in the database.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @cmd varchar(4000)\nDECLARE cmds CURSOR FOR\nSELECT 'drop table [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'prefix%'\n\nOPEN cmds\nWHILE 1 = 1\nBEGIN\n FETCH cmds INTO @cmd\n IF @@fetch_status != 0 BREAK\n EXEC(@cmd)\nEND\nCLOSE cmds;\nDEALLOCATE cmds\n</code></pre>\n\n<p>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.</p>\n\n<p>I know that if I were going to do this against a production database, I'd be as careful as possible.</p>\n\n<p><strong>Edit</strong> Code sample fixed.</p>\n" }, { "answer_id": 189920, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<pre><code>CREATE PROCEDURE usp_GenerateDROP\n @Pattern AS varchar(255)\n ,@PrintQuery AS bit\n ,@ExecQuery AS bit\nAS\nBEGIN\n DECLARE @sql AS varchar(max)\n\n SELECT @sql = COALESCE(@sql, '') + 'DROP TABLE [' + TABLE_NAME + ']' + CHAR(13) + CHAR(10)\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_NAME LIKE @Pattern\n\n IF @PrintQuery = 1 PRINT @sql\n IF @ExecQuery = 1 EXEC (@sql)\nEND\n</code></pre>\n" }, { "answer_id": 17281642, "author": "Shashank", "author_id": 2517289, "author_profile": "https://Stackoverflow.com/users/2517289", "pm_score": 1, "selected": false, "text": "<pre><code>select 'DROP TABLE ' + name from sysobjects\nwhere type = 'U' and sysobjects.name like '%test%'\n</code></pre>\n\n<p>-- Test is the table name</p>\n" }, { "answer_id": 21671836, "author": "Tony O'Hagan", "author_id": 365261, "author_profile": "https://Stackoverflow.com/users/365261", "pm_score": 4, "selected": false, "text": "<p>This will get you the tables in foreign key order and avoid dropping some of the tables created by SQL Server. The <code>t.Ordinal</code> value will slice the tables into dependency layers.</p>\n\n<pre><code>WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS\n(\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n 0 AS Ordinal\n FROM sys.objects AS so\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n\n UNION ALL\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n tt.Ordinal + 1 AS Ordinal\n FROM sys.objects AS so\n INNER JOIN sys.foreign_keys AS f\n ON f.parent_object_id = so.object_id\n AND f.parent_object_id != f.referenced_object_id\n INNER JOIN TablesCTE AS tt\n ON f.referenced_object_id = tt.TableID\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n)\nSELECT DISTINCT t.Ordinal, t.SchemaName, t.TableName, t.TableID\nFROM TablesCTE AS t\n INNER JOIN\n (\n SELECT\n itt.SchemaName AS SchemaName,\n itt.TableName AS TableName,\n itt.TableID AS TableID,\n Max(itt.Ordinal) AS Ordinal\n FROM TablesCTE AS itt\n GROUP BY itt.SchemaName, itt.TableName, itt.TableID\n ) AS tt\n ON t.TableID = tt.TableID\n AND t.Ordinal = tt.Ordinal\nORDER BY t.Ordinal DESC, t.TableName ASC\n</code></pre>\n" }, { "answer_id": 25082268, "author": "RGH", "author_id": 1908292, "author_profile": "https://Stackoverflow.com/users/1908292", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT 'if object_id(''' + TABLE_NAME + ''') is not null begin drop table \"' + TABLE_NAME + '\" end;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n</code></pre>\n" }, { "answer_id": 28533145, "author": "Xaxum", "author_id": 873487, "author_profile": "https://Stackoverflow.com/users/873487", "pm_score": 1, "selected": false, "text": "<p>I had to do a slight derivation on Xenph Yan's answer I suspect because I had tables not in the default schema. </p>\n\n<pre><code>SELECT 'DROP TABLE Databasename.schema.' + TABLE_NAME \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'strmatch%'\n</code></pre>\n" }, { "answer_id": 30372503, "author": "Rosdi Kasim", "author_id": 193634, "author_profile": "https://Stackoverflow.com/users/193634", "pm_score": 3, "selected": false, "text": "<p>On Oracle XE this works:</p>\n\n<pre><code>SELECT 'DROP TABLE \"' || TABLE_NAME || '\";'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n</code></pre>\n\n<p>Or if you want to <strong>remove the constraints and free up space</strong> as well, use this:</p>\n\n<pre><code>SELECT 'DROP TABLE \"' || TABLE_NAME || '\" cascade constraints PURGE;'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n</code></pre>\n\n<p>Which will generate a bunch of <code>DROP TABLE cascade constraints PURGE</code> statements...</p>\n\n<p>For <code>VIEWS</code> use this:</p>\n\n<pre><code>SELECT 'DROP VIEW \"' || VIEW_NAME || '\";'\nFROM USER_VIEWS\nWHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'\n</code></pre>\n" }, { "answer_id": 31668613, "author": "talsibony", "author_id": 1220652, "author_profile": "https://Stackoverflow.com/users/1220652", "pm_score": 3, "selected": false, "text": "<p>I saw this post when I was looking for mysql statement to drop all WordPress tables based on @Xenph Yan here is what I did eventually:</p>\n\n<pre><code>SELECT CONCAT( 'DROP TABLE `', TABLE_NAME, '`;' ) AS query\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE 'wp_%'\n</code></pre>\n\n<p>this will give you the set of drop queries for all tables begins with wp_</p>\n" }, { "answer_id": 36200064, "author": "vencedor", "author_id": 2653457, "author_profile": "https://Stackoverflow.com/users/2653457", "pm_score": 3, "selected": false, "text": "<p>Here is my solution:</p>\n\n<pre><code>SELECT CONCAT('DROP TABLE `', TABLE_NAME,'`;') \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'TABLE_PREFIX_GOES_HERE%';\n</code></pre>\n\n<p>And of course you need to replace <code>TABLE_PREFIX_GOES_HERE</code> with your prefix.</p>\n" }, { "answer_id": 37708151, "author": "mrosiak", "author_id": 3242203, "author_profile": "https://Stackoverflow.com/users/3242203", "pm_score": 3, "selected": false, "text": "<pre><code>EXEC sp_MSforeachtable 'if PARSENAME(\"?\",1) like ''%CertainString%'' DROP TABLE ?'\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>sp_MSforeachtable is undocumented hence not suitable for production because it's behavior may vary depending on MS_SQL version.</p>\n" }, { "answer_id": 39347828, "author": "João Mergulhão", "author_id": 6795613, "author_profile": "https://Stackoverflow.com/users/6795613", "pm_score": 1, "selected": false, "text": "<p>In case of temporary tables, you might want to try </p>\n\n<pre><code>SELECT 'DROP TABLE \"' + t.name + '\"' \nFROM tempdb.sys.tables t\nWHERE t.name LIKE '[prefix]%'\n</code></pre>\n" }, { "answer_id": 57511478, "author": "ASH", "author_id": 5212614, "author_profile": "https://Stackoverflow.com/users/5212614", "pm_score": 2, "selected": false, "text": "<p>This worked for me.</p>\n\n<pre><code>DECLARE @sql NVARCHAR(MAX) = N'';\n\nSELECT @sql += '\nDROP TABLE ' \n + QUOTENAME(s.name)\n + '.' + QUOTENAME(t.name) + ';'\n FROM sys.tables AS t\n INNER JOIN sys.schemas AS s\n ON t.[schema_id] = s.[schema_id] \n WHERE t.name LIKE 'something%';\n\nPRINT @sql;\n-- EXEC sp_executesql @sql;\n</code></pre>\n" }, { "answer_id": 65718571, "author": "Tomasz Wieczorkowski", "author_id": 2355469, "author_profile": "https://Stackoverflow.com/users/2355469", "pm_score": 1, "selected": false, "text": "<p>I would like to post my proposal of the solution which DROP (not just generate and select a drop commands) all tables based on the wildcard (e.g. &quot;table_20210114&quot;) older than particular amount of days.</p>\n<pre><code>DECLARE \n @drop_command NVARCHAR(MAX) = '',\n @system_time date,\n @table_date nvarchar(8),\n @older_than int = 7\n \nSet @system_time = (select getdate() - @older_than)\nSet @table_date = (SELECT CONVERT(char(8), @system_time, 112))\n\nSELECT @drop_command += N'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME([Name]) + ';'\nFROM &lt;your_database_name&gt;.sys.tables\nWHERE [Name] LIKE 'table_%' AND RIGHT([Name],8) &lt; @table_date\n\nSELECT @drop_command\n \nEXEC sp_executesql @drop_command\n</code></pre>\n" }, { "answer_id": 71514887, "author": "Arthur Cam", "author_id": 10475213, "author_profile": "https://Stackoverflow.com/users/10475213", "pm_score": 1, "selected": false, "text": "<p>If your query returns more than one line, you can collect the results and merge them into a query.</p>\n<pre><code>declare @Tables as nvarchar(max) = '[schemaName].['\nselect @Tables =@Tables + TABLE_NAME +'],[schemaName].['\nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_TYPE='BASE TABLE'\nAND TABLE_SCHEMA = 'schemaName'\nAND TABLE_NAME like '%whateverYourQueryIs%'\n\nselect @Tables = Left(@Tables,LEN(@Tables)-13) --trying to remove last &quot;,[schemaName].[&quot; part, so you need to change this 13 with actual lenght \n\n--print @Tables\n\ndeclare @Query as nvarchar(max) = 'Drop table ' +@Tables \n\n--print @Query\n\n\nexec sp_executeSQL @Query\n</code></pre>\n" }, { "answer_id": 73278269, "author": "AliNajafZadeh", "author_id": 16746668, "author_profile": "https://Stackoverflow.com/users/16746668", "pm_score": 0, "selected": false, "text": "<p>Try following code:</p>\n<pre><code>declare @TableLst table(TblNames nvarchar(500))\ninsert into @TableLst (TblNames)\nSELECT 'DROP TABLE [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'yourFilter%'\nWHILE ((select COUNT(*) as CntTables from @TableLst) &gt; 0)\nBEGIN\n declare @ForExecCms nvarchar(500) = (select top(1) TblNames from @TableLst)\n EXEC(@ForExecCms)\n delete from @TableLst where TblNames = @ForExecCms\nEND\n</code></pre>\n<p>This SQL script is executed without using a <strong>cursor</strong>.</p>\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</code></pre>\n\n<p>This will generate a script.</p>\n\n<p>Adding clause to check existence of table before deleting:</p>\n\n<pre><code>SELECT 'IF OBJECT_ID(''' +TABLE_NAME + ''') IS NOT NULL BEGIN DROP TABLE [' + TABLE_NAME + '] END;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n</code></pre>\n" }, { "answer_id": 4400, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/users/264/xenph-yan\">Xenph Yan</a>'s answer was far cleaner than mine but here is mine all the same.</p>\n\n<pre><code>DECLARE @startStr AS Varchar (20)\nSET @startStr = 'tableName'\n\nDECLARE @startStrLen AS int\nSELECT @startStrLen = LEN(@startStr)\n\nSELECT 'DROP TABLE ' + name FROM sysobjects\nWHERE type = 'U' AND LEFT(name, @startStrLen) = @startStr\n</code></pre>\n\n<p>Just change <code>tableName</code> to the characters that you want to search with.</p>\n" }, { "answer_id": 4401, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 8, "selected": true, "text": "\n\n<p>You may need to modify the query to include the owner if there's more than one in the database.</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>DECLARE @cmd varchar(4000)\nDECLARE cmds CURSOR FOR\nSELECT 'drop table [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'prefix%'\n\nOPEN cmds\nWHILE 1 = 1\nBEGIN\n FETCH cmds INTO @cmd\n IF @@fetch_status != 0 BREAK\n EXEC(@cmd)\nEND\nCLOSE cmds;\nDEALLOCATE cmds\n</code></pre>\n\n<p>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.</p>\n\n<p>I know that if I were going to do this against a production database, I'd be as careful as possible.</p>\n\n<p><strong>Edit</strong> Code sample fixed.</p>\n" }, { "answer_id": 189920, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "<pre><code>CREATE PROCEDURE usp_GenerateDROP\n @Pattern AS varchar(255)\n ,@PrintQuery AS bit\n ,@ExecQuery AS bit\nAS\nBEGIN\n DECLARE @sql AS varchar(max)\n\n SELECT @sql = COALESCE(@sql, '') + 'DROP TABLE [' + TABLE_NAME + ']' + CHAR(13) + CHAR(10)\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_NAME LIKE @Pattern\n\n IF @PrintQuery = 1 PRINT @sql\n IF @ExecQuery = 1 EXEC (@sql)\nEND\n</code></pre>\n" }, { "answer_id": 17281642, "author": "Shashank", "author_id": 2517289, "author_profile": "https://Stackoverflow.com/users/2517289", "pm_score": 1, "selected": false, "text": "<pre><code>select 'DROP TABLE ' + name from sysobjects\nwhere type = 'U' and sysobjects.name like '%test%'\n</code></pre>\n\n<p>-- Test is the table name</p>\n" }, { "answer_id": 21671836, "author": "Tony O'Hagan", "author_id": 365261, "author_profile": "https://Stackoverflow.com/users/365261", "pm_score": 4, "selected": false, "text": "<p>This will get you the tables in foreign key order and avoid dropping some of the tables created by SQL Server. The <code>t.Ordinal</code> value will slice the tables into dependency layers.</p>\n\n<pre><code>WITH TablesCTE(SchemaName, TableName, TableID, Ordinal) AS\n(\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n 0 AS Ordinal\n FROM sys.objects AS so\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n\n UNION ALL\n SELECT OBJECT_SCHEMA_NAME(so.object_id) AS SchemaName,\n OBJECT_NAME(so.object_id) AS TableName,\n so.object_id AS TableID,\n tt.Ordinal + 1 AS Ordinal\n FROM sys.objects AS so\n INNER JOIN sys.foreign_keys AS f\n ON f.parent_object_id = so.object_id\n AND f.parent_object_id != f.referenced_object_id\n INNER JOIN TablesCTE AS tt\n ON f.referenced_object_id = tt.TableID\n WHERE so.type = 'U'\n AND so.is_ms_Shipped = 0\n AND OBJECT_NAME(so.object_id)\n LIKE 'MyPrefix%'\n)\nSELECT DISTINCT t.Ordinal, t.SchemaName, t.TableName, t.TableID\nFROM TablesCTE AS t\n INNER JOIN\n (\n SELECT\n itt.SchemaName AS SchemaName,\n itt.TableName AS TableName,\n itt.TableID AS TableID,\n Max(itt.Ordinal) AS Ordinal\n FROM TablesCTE AS itt\n GROUP BY itt.SchemaName, itt.TableName, itt.TableID\n ) AS tt\n ON t.TableID = tt.TableID\n AND t.Ordinal = tt.Ordinal\nORDER BY t.Ordinal DESC, t.TableName ASC\n</code></pre>\n" }, { "answer_id": 25082268, "author": "RGH", "author_id": 1908292, "author_profile": "https://Stackoverflow.com/users/1908292", "pm_score": 1, "selected": false, "text": "<pre><code>SELECT 'if object_id(''' + TABLE_NAME + ''') is not null begin drop table \"' + TABLE_NAME + '\" end;' \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE '[prefix]%'\n</code></pre>\n" }, { "answer_id": 28533145, "author": "Xaxum", "author_id": 873487, "author_profile": "https://Stackoverflow.com/users/873487", "pm_score": 1, "selected": false, "text": "<p>I had to do a slight derivation on Xenph Yan's answer I suspect because I had tables not in the default schema. </p>\n\n<pre><code>SELECT 'DROP TABLE Databasename.schema.' + TABLE_NAME \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'strmatch%'\n</code></pre>\n" }, { "answer_id": 30372503, "author": "Rosdi Kasim", "author_id": 193634, "author_profile": "https://Stackoverflow.com/users/193634", "pm_score": 3, "selected": false, "text": "<p>On Oracle XE this works:</p>\n\n<pre><code>SELECT 'DROP TABLE \"' || TABLE_NAME || '\";'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n</code></pre>\n\n<p>Or if you want to <strong>remove the constraints and free up space</strong> as well, use this:</p>\n\n<pre><code>SELECT 'DROP TABLE \"' || TABLE_NAME || '\" cascade constraints PURGE;'\nFROM USER_TABLES\nWHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'\n</code></pre>\n\n<p>Which will generate a bunch of <code>DROP TABLE cascade constraints PURGE</code> statements...</p>\n\n<p>For <code>VIEWS</code> use this:</p>\n\n<pre><code>SELECT 'DROP VIEW \"' || VIEW_NAME || '\";'\nFROM USER_VIEWS\nWHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'\n</code></pre>\n" }, { "answer_id": 31668613, "author": "talsibony", "author_id": 1220652, "author_profile": "https://Stackoverflow.com/users/1220652", "pm_score": 3, "selected": false, "text": "<p>I saw this post when I was looking for mysql statement to drop all WordPress tables based on @Xenph Yan here is what I did eventually:</p>\n\n<pre><code>SELECT CONCAT( 'DROP TABLE `', TABLE_NAME, '`;' ) AS query\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_NAME LIKE 'wp_%'\n</code></pre>\n\n<p>this will give you the set of drop queries for all tables begins with wp_</p>\n" }, { "answer_id": 36200064, "author": "vencedor", "author_id": 2653457, "author_profile": "https://Stackoverflow.com/users/2653457", "pm_score": 3, "selected": false, "text": "<p>Here is my solution:</p>\n\n<pre><code>SELECT CONCAT('DROP TABLE `', TABLE_NAME,'`;') \nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_NAME LIKE 'TABLE_PREFIX_GOES_HERE%';\n</code></pre>\n\n<p>And of course you need to replace <code>TABLE_PREFIX_GOES_HERE</code> with your prefix.</p>\n" }, { "answer_id": 37708151, "author": "mrosiak", "author_id": 3242203, "author_profile": "https://Stackoverflow.com/users/3242203", "pm_score": 3, "selected": false, "text": "<pre><code>EXEC sp_MSforeachtable 'if PARSENAME(\"?\",1) like ''%CertainString%'' DROP TABLE ?'\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>sp_MSforeachtable is undocumented hence not suitable for production because it's behavior may vary depending on MS_SQL version.</p>\n" }, { "answer_id": 39347828, "author": "João Mergulhão", "author_id": 6795613, "author_profile": "https://Stackoverflow.com/users/6795613", "pm_score": 1, "selected": false, "text": "<p>In case of temporary tables, you might want to try </p>\n\n<pre><code>SELECT 'DROP TABLE \"' + t.name + '\"' \nFROM tempdb.sys.tables t\nWHERE t.name LIKE '[prefix]%'\n</code></pre>\n" }, { "answer_id": 57511478, "author": "ASH", "author_id": 5212614, "author_profile": "https://Stackoverflow.com/users/5212614", "pm_score": 2, "selected": false, "text": "<p>This worked for me.</p>\n\n<pre><code>DECLARE @sql NVARCHAR(MAX) = N'';\n\nSELECT @sql += '\nDROP TABLE ' \n + QUOTENAME(s.name)\n + '.' + QUOTENAME(t.name) + ';'\n FROM sys.tables AS t\n INNER JOIN sys.schemas AS s\n ON t.[schema_id] = s.[schema_id] \n WHERE t.name LIKE 'something%';\n\nPRINT @sql;\n-- EXEC sp_executesql @sql;\n</code></pre>\n" }, { "answer_id": 65718571, "author": "Tomasz Wieczorkowski", "author_id": 2355469, "author_profile": "https://Stackoverflow.com/users/2355469", "pm_score": 1, "selected": false, "text": "<p>I would like to post my proposal of the solution which DROP (not just generate and select a drop commands) all tables based on the wildcard (e.g. &quot;table_20210114&quot;) older than particular amount of days.</p>\n<pre><code>DECLARE \n @drop_command NVARCHAR(MAX) = '',\n @system_time date,\n @table_date nvarchar(8),\n @older_than int = 7\n \nSet @system_time = (select getdate() - @older_than)\nSet @table_date = (SELECT CONVERT(char(8), @system_time, 112))\n\nSELECT @drop_command += N'DROP TABLE ' + QUOTENAME(SCHEMA_NAME(schema_id)) + '.' + QUOTENAME([Name]) + ';'\nFROM &lt;your_database_name&gt;.sys.tables\nWHERE [Name] LIKE 'table_%' AND RIGHT([Name],8) &lt; @table_date\n\nSELECT @drop_command\n \nEXEC sp_executesql @drop_command\n</code></pre>\n" }, { "answer_id": 71514887, "author": "Arthur Cam", "author_id": 10475213, "author_profile": "https://Stackoverflow.com/users/10475213", "pm_score": 1, "selected": false, "text": "<p>If your query returns more than one line, you can collect the results and merge them into a query.</p>\n<pre><code>declare @Tables as nvarchar(max) = '[schemaName].['\nselect @Tables =@Tables + TABLE_NAME +'],[schemaName].['\nFROM INFORMATION_SCHEMA.TABLES \nWHERE TABLE_TYPE='BASE TABLE'\nAND TABLE_SCHEMA = 'schemaName'\nAND TABLE_NAME like '%whateverYourQueryIs%'\n\nselect @Tables = Left(@Tables,LEN(@Tables)-13) --trying to remove last &quot;,[schemaName].[&quot; part, so you need to change this 13 with actual lenght \n\n--print @Tables\n\ndeclare @Query as nvarchar(max) = 'Drop table ' +@Tables \n\n--print @Query\n\n\nexec sp_executeSQL @Query\n</code></pre>\n" }, { "answer_id": 73278269, "author": "AliNajafZadeh", "author_id": 16746668, "author_profile": "https://Stackoverflow.com/users/16746668", "pm_score": 0, "selected": false, "text": "<p>Try following code:</p>\n<pre><code>declare @TableLst table(TblNames nvarchar(500))\ninsert into @TableLst (TblNames)\nSELECT 'DROP TABLE [' + Table_Name + ']'\nFROM INFORMATION_SCHEMA.TABLES\nWHERE Table_Name LIKE 'yourFilter%'\nWHILE ((select COUNT(*) as CntTables from @TableLst) &gt; 0)\nBEGIN\n declare @ForExecCms nvarchar(500) = (select top(1) TblNames from @TableLst)\n EXEC(@ForExecCms)\n delete from @TableLst where TblNames = @ForExecCms\nEND\n</code></pre>\n<p>This SQL script is executed without using a <strong>cursor</strong>.</p>\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=\"nofollow noreferrer\">http://web.archive.org/web/20060913093359/http://apserver.sourceforge.net:80/</a> on your local machine, configure it and run gems through this proxy.</p>\n\n<ul>\n<li>Install: Just download apserver 097 (and not the experimental 098!) and unpack.</li>\n<li>Configure: Edit the server.cfg file and put the values for your MS proxy in <code>PARENT_PROXY</code> and <code>PARENT_PROXY_PORT</code>. Enter the values for DOMAIN and USER. Leave PASSWORD blank (nothing after the colon) – you will be prompted when launching it.</li>\n<li>Run apserver: <code>cd aps097; python main.py</code></li>\n<li>Run Gems: <code>gem install—http-proxy http://localhost:5865/ library</code></li>\n</ul>\n" }, { "answer_id": 4431, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 9, "selected": true, "text": "<p>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 <code>HTTP_PROXY</code> environment variable. (Note that case seems to be important). I have a batch file that has a line like this in it:</p>\n\n<pre><code>SET HTTP_PROXY=http://%USER%:%PASSWORD%@%SERVER%:%PORT%\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>SET HTTP_PROXY=http://wolfbyte:secret@pigsy:8080\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 37161, "author": "Jason Navarrete", "author_id": 3920, "author_profile": "https://Stackoverflow.com/users/3920", "pm_score": 6, "selected": false, "text": "<p>I've been using cntlm (<a href=\"http://cntlm.sourceforge.net/\" rel=\"noreferrer\">http://cntlm.sourceforge.net/</a>) at work. Configuration is very similar to ntlmaps.</p>\n\n<ul>\n<li>gem install --http-proxy <a href=\"http://localhost:3128\" rel=\"noreferrer\">http://localhost:3128</a> _name_of_gem_</li>\n</ul>\n\n<p>Works great, and also allows me to connect my Ubuntu box to the ISA proxy.</p>\n\n<p>Check out <a href=\"http://cntlm.wiki.sourceforge.net/\" rel=\"noreferrer\">http://cntlm.wiki.sourceforge.net/</a> for more information</p>\n" }, { "answer_id": 629605, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Posts abound regarding this topic, and to help others save hours of trying different solutions, here is the final result of my hours of tinkering.</p>\n\n<p>The three solutions around the internet at the moment are:\nrubysspi\napserver\ncntlm</p>\n\n<p>rubysspi only works from a Windows machine, AFAIK, as it relies on the Win32Api library. So if you are on a Windows box trying to run through a proxy, this is the solution for you. If you are on a Linux distro, you're out of luck.</p>\n\n<p>apserver seems to be a dead project. The link listed in the posts I've seen lead to 404 page on sourceforge. I search for \"apserver\" on sourceforge returns nothing.</p>\n\n<p>The sourceforge link for cntlm that I've seen redirects to <a href=\"http://cntlm.awk.cz/\" rel=\"noreferrer\">http://cntlm.awk.cz/</a>, but that times out. A search on sourceforge turns up this link, which does work: <a href=\"http://sourceforge.net/projects/cntlm/\" rel=\"noreferrer\">http://sourceforge.net/projects/cntlm/</a></p>\n\n<p>After downloading and configuring cntlm I have managed to install a gem through the proxy, so this seems to be the best solution for Linux distros.</p>\n" }, { "answer_id": 4187271, "author": "Peter Moresi", "author_id": 426602, "author_profile": "https://Stackoverflow.com/users/426602", "pm_score": 8, "selected": false, "text": "<p>For the Windows OS, I used Fiddler to work around the issue.</p>\n\n<ol>\n<li>Install/Run Fiddler from www.fiddler2.com</li>\n<li><p>Run gem:</p>\n\n<pre><code>$ gem install --http-proxy http://localhost:8888 $gem_name\n</code></pre></li>\n</ol>\n" }, { "answer_id": 7315150, "author": "Christian F", "author_id": 722711, "author_profile": "https://Stackoverflow.com/users/722711", "pm_score": 3, "selected": false, "text": "<p>I tried all the above solutions, however none of them worked. If you're on linux/macOS i highly suggest using tsocks over an ssh tunnel. What you need in order to get this setup working is a machine where you can log in via ssh, and in addition to that a programm called tsocks installed. </p>\n\n<p>The idea here is to create a dynamic tunnel via SSH (a socks5 proxy). We then configure tsocks to use this tunnel and to start our applications, in this case:</p>\n\n<pre><code>tsocks gem install ...\n</code></pre>\n\n<p>or to account for rails 3.0:</p>\n\n<pre><code>tsocks bundle install\n</code></pre>\n\n<p>A more detailed guide can be found under:</p>\n\n<p><a href=\"http://blog.byscripts.info/2011/04/bypass-a-proxy-with-ssh-tunnel-and-tsocks-under-ubuntu/\">http://blog.byscripts.info/2011/04/bypass-a-proxy-with-ssh-tunnel-and-tsocks-under-ubuntu/</a></p>\n\n<p>Despite being written for Ubuntu the procedure should be applicable for all Unix based machines. An alternative to tsocks for Windows is FreeCap (<a href=\"http://www.freecap.ru/eng/\">http://www.freecap.ru/eng/</a>). A viable SSH client on windows is called putty.</p>\n" }, { "answer_id": 8006225, "author": "moonpatrol", "author_id": 465598, "author_profile": "https://Stackoverflow.com/users/465598", "pm_score": 2, "selected": false, "text": "<p>rubysspi-1.3.1 worked for me on Windows 7, using the instructions from this page:</p>\n\n<p><a href=\"http://www.stuartellis.eu/articles/installing-ruby/\" rel=\"nofollow\">http://www.stuartellis.eu/articles/installing-ruby/</a></p>\n" }, { "answer_id": 9382152, "author": "Benjamin Wootton", "author_id": 247573, "author_profile": "https://Stackoverflow.com/users/247573", "pm_score": 4, "selected": false, "text": "<p>If you are having problems getting authenticated through your proxy, be sure to set the environment variables in exactly the format below: </p>\n\n<pre><code>set HTTP_PROXY=some.proxy.com\nset HTTP_PROXY_USER=user\nset HTTP_PROXY_PASS=password\n</code></pre>\n\n<p>The <code>user:password@</code> syntax doesn't seem to work and there are also some badly named environment variables floating around on Stack Overflow and various forum posts. </p>\n\n<p>Also be aware that it can take a while for your gems to start downloading. At first I thought it wasn't working but with a bit of patience they started downloading as expected.</p>\n" }, { "answer_id": 9866308, "author": "SethRocker", "author_id": 439133, "author_profile": "https://Stackoverflow.com/users/439133", "pm_score": 7, "selected": false, "text": "<p>This totally worked:</p>\n\n<pre><code>gem install --http-proxy http://COMPANY.PROXY.ADDRESS $gem_name\n</code></pre>\n" }, { "answer_id": 11769049, "author": "kfox", "author_id": 575027, "author_profile": "https://Stackoverflow.com/users/575027", "pm_score": 5, "selected": false, "text": "<p>I tried some of these solutions, and none of them worked. I finally found a solution that works for me:</p>\n\n<pre><code>gem install -p http://proxy_ip:proxy_port rails\n</code></pre>\n\n<p>using the <code>-p</code> parameter to pass the proxy. I'm using Gem version 1.9.1.</p>\n" }, { "answer_id": 13563827, "author": "Zander", "author_id": 91359, "author_profile": "https://Stackoverflow.com/users/91359", "pm_score": 2, "selected": false, "text": "<p>I am working behind a proxy and just installed SASS by downloading directly from <a href=\"http://rubygems.org\" rel=\"nofollow\">http://rubygems.org</a>.</p>\n\n<p>I then ran <code>sudo gem install [path/to/downloaded/gem/file]</code>. I cannot say this will work for all gems, but it may help some people.</p>\n" }, { "answer_id": 19596410, "author": "Saikrishna Rao", "author_id": 1128212, "author_profile": "https://Stackoverflow.com/users/1128212", "pm_score": 2, "selected": false, "text": "<p>If you are on a *nix system, use this:</p>\n\n<pre><code>export http_proxy=http://${proxy.host}:${port}\nexport https_proxy=http://${proxy.host}:${port}\n</code></pre>\n\n<p>and then try:</p>\n\n<pre><code>gem install ${gem_name}\n</code></pre>\n" }, { "answer_id": 22957276, "author": "HomTom", "author_id": 2931433, "author_profile": "https://Stackoverflow.com/users/2931433", "pm_score": 4, "selected": false, "text": "<p>This solved my problem perfectly:</p>\n\n<pre><code>gem install -p http://proxy_ip:proxy_port compass\n</code></pre>\n\n<p>You might need to add your user name and password to it:</p>\n\n<pre><code>gem install -p http://[username]:[password]@proxy_ip:proxy_port compass\n</code></pre>\n" }, { "answer_id": 23693898, "author": "testworks", "author_id": 3509508, "author_profile": "https://Stackoverflow.com/users/3509508", "pm_score": 1, "selected": false, "text": "<p>Rather than editing batch files (which you may have to do for other Ruby gems, e.g. Bundler), it's probably better to do this once, and do it properly.</p>\n\n<p>On Windows, behind my corporate proxy, all I had to do was add the <code>HTTP_PROXY</code> environment variable to my system.</p>\n\n<ol>\n<li>Start -> right click Computer -> Properties</li>\n<li>Choose \"Advanced System Settings\"</li>\n<li>Click Advanced -> Environment Variables</li>\n<li>Create a new System variable named \"<code>HTTP_PROXY</code>\", and set the Value to your proxy server</li>\n<li>Reboot or log out and back in again</li>\n</ol>\n\n<p>Depending on your authentication requirements, the <code>HTTP_PROXY</code> value can be as simple as:</p>\n\n<pre><code>http://proxy-server-name\n</code></pre>\n\n<p>Or more complex as others have pointed out</p>\n\n<pre><code>http://username:password@proxy-server-name:port-number\n</code></pre>\n" }, { "answer_id": 24087006, "author": "Qi Luo", "author_id": 2514803, "author_profile": "https://Stackoverflow.com/users/2514803", "pm_score": 1, "selected": false, "text": "<p>If you want to use SOCKS5 proxy, you may try rubygems-socksproxy <a href=\"https://github.com/gussan/rubygems-socksproxy\" rel=\"nofollow\">https://github.com/gussan/rubygems-socksproxy</a>.</p>\n\n<p>It works for me on OSX 10.9.3.</p>\n" }, { "answer_id": 25244434, "author": "ArNumb", "author_id": 2818659, "author_profile": "https://Stackoverflow.com/users/2818659", "pm_score": 1, "selected": false, "text": "<p>If behind a proxy, you can navigate to <a href=\"http://rubygems.org/gems/rubygems-update\" rel=\"nofollow\">Ruby downloads</a>, click on Download, which will download the specified update ( or Gem ) to a desired location.</p>\n\n<p>Next, via Ruby command line, navigate to the downloaded location by using : <code>pushd [directory]</code> </p>\n\n<p>eg : <code>pushd D:\\Setups</code> </p>\n\n<p>then run the following command: <code>gem install [update name] --local</code></p>\n\n<p>eg: <code>gem install rubygems-update --local</code>.</p>\n\n<p>Tested on Windows 7 with Ruby update version 2.4.1.</p>\n\n<p>To check use following command : <code>ruby -v</code> </p>\n" }, { "answer_id": 27921249, "author": "Pedro García Vigil", "author_id": 4449057, "author_profile": "https://Stackoverflow.com/users/4449057", "pm_score": 2, "selected": false, "text": "<p>This worked for me in a Windows box:</p>\n\n<pre><code>set HTTP_PROXY=http://server:port\nset HTTP_PROXY_USER=username\nset HTTP_PROXY_PASS=userparssword\nset HTTPS_PROXY=http://server:port\nset HTTPS_PROXY_USER=username\nset HTTPS_PROXY_PASS=userpassword\n</code></pre>\n\n<p>I have a batch file with these lines that I use to set environment values when I need it.</p>\n\n<p>The trick, in my case, was <code>HTTPS_PROXY</code> sets. Without them, I always got a 407 proxy authentication error.</p>\n" }, { "answer_id": 34412185, "author": "lukapiske", "author_id": 511366, "author_profile": "https://Stackoverflow.com/users/511366", "pm_score": 4, "selected": false, "text": "<p>Create a .gemrc file (either in /etc/gemrc or ~/.gemrc or for example with chef gem in /opt/chef/embedded/etc/gemrc) containing:</p>\n\n<pre><code>http_proxy: http://proxy:3128\n</code></pre>\n\n<p>Then you can <code>gem install</code> as usual. </p>\n" }, { "answer_id": 56637216, "author": "Shantonu", "author_id": 1564801, "author_profile": "https://Stackoverflow.com/users/1564801", "pm_score": 3, "selected": false, "text": "<p>Quick answer : Add proxy configuration with parameter for both install/update</p>\n\n<pre><code>gem install --http-proxy http://host:port/ package_name\n\ngem update --http-proxy http://host:port/ package_name\n</code></pre>\n" }, { "answer_id": 61013775, "author": "Mike Campbell", "author_id": 1520714, "author_profile": "https://Stackoverflow.com/users/1520714", "pm_score": 0, "selected": false, "text": "<p>for anyone tunnelling with SSH; you can create a version of the <code>gem</code> command that uses SOCKS proxy:</p>\n\n<ol>\n<li>Install <code>socksify</code> with <code>gem install socksify</code> (you'll need to be able to do this step without proxy, at least)</li>\n<li><p>Copy your existing gem exe</p>\n\n<pre><code>cp $(command which gem) /usr/local/bin/proxy_gem\n</code></pre></li>\n<li><p>Open it in your favourite editor and add this at the top (after the shebang)</p>\n\n<pre><code>require 'socksify'\n\nif ENV['SOCKS_PROXY']\n require 'socksify'\n host, port = ENV['SOCKS_PROXY'].split(':')\n TCPSocket.socks_server = host || 'localhost'\n TCPSocket.socks_port = port.to_i || 1080\nend\n</code></pre></li>\n<li><p>Set up your tunnel</p>\n\n<pre><code>ssh -D 8123 -f -C -q -N user@proxy\n</code></pre></li>\n<li><p>Run your gem command with proxy_gem</p>\n\n<pre><code>SOCKS_PROXY=localhost:8123 proxy_gem push mygem\n</code></pre></li>\n</ol>\n" } ]
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(\",\");</code></p>\n" }, { "answer_id": 4438, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 0, "selected": false, "text": "<p>How about tracking whether you are on the first item, and only add a comma <em>before</em> the item if it is not the first one.</p>\n\n<pre><code>public string ReturnAsCSV(ContactList contactList)\n{\n StringBuilder sb = new StringBuilder();\n bool isFirst = true;\n\n foreach (Contact c in contactList) {\n if (!isFirst) { \n // Only add comma before item if it is not the first item\n sb.Append(\",\"); \n } else {\n isFirst = false;\n }\n\n sb.Append(c.Name);\n }\n\n return sb.ToString();\n}\n</code></pre>\n" }, { "answer_id": 4441, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 5, "selected": true, "text": "<p>You could use <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_Objects\" rel=\"noreferrer\">LINQ to Objects</a>:</p>\n\n<pre><code>string [] strings = contactList.Select(c =&gt; c.Name).ToArray();\nstring csv = string.Join(\",\", strings);\n</code></pre>\n\n<p>Obviously that could all be done in one line, but it's a bit clearer on two.</p>\n" }, { "answer_id": 4461, "author": "Xenph Yan", "author_id": 264, "author_profile": "https://Stackoverflow.com/users/264", "pm_score": 1, "selected": false, "text": "<blockquote>\n <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>\n</blockquote>\n\n<p>You're prematurely optimizing, the performance hit would be negligible.</p>\n" }, { "answer_id": 4502, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 2, "selected": false, "text": "<p>You could also make an array of <strong>c.Name</strong> data and use <strong>String.Join</strong> method to create your line.</p>\n\n<pre><code>public string ReturnAsCSV(ContactList contactList)\n{\n List&lt;String&gt; tmpList = new List&lt;string&gt;();\n\n foreach (Contact c in contactList)\n {\n tmpList.Add(c.Name);\n }\n\n return String.Join(\",\", tmpList.ToArray());\n}\n</code></pre>\n\n<p>This might not be as performant as the <strong>StringBuilder</strong> approach, but it definitely looks cleaner.</p>\n\n<p>Also, you might want to consider using <strong>.CurrentCulture.TextInfo.ListSeparator</strong> instead of a hard-coded comma -- If your output is going to be imported into other applications, you might have problems with it. ListSeparator may be different across different cultures, and MS Excel at the very least, honors this setting. So:</p>\n\n<pre><code>return String.Join(\n System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator,\n tmpList.ToArray());\n</code></pre>\n" }, { "answer_id": 4518, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>How about some trimming?</p>\n\n<pre><code>public string ReturnAsCSV(ContactList contactList)\n{\n StringBuilder sb = new StringBuilder();\n\n foreach (Contact c in contactList)\n {\n sb.Append(c.Name + \",\");\n }\n\n return sb.ToString().Trim(',');\n}\n</code></pre>\n" }, { "answer_id": 4592, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 1, "selected": false, "text": "<p>Just a thought, but remember to handle comma's and quotation marks (\") in the field values, otherwise your CSV file may break the consumers reader.</p>\n" }, { "answer_id": 4611, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "<p>Don't forget our old friend \"for\". It's not as nice-looking as foreach but it has the advantage of being able to start at the second element.</p>\n\n<pre><code>public string ReturnAsCSV(ContactList contactList)\n{\n if (contactList == null || contactList.Count == 0)\n return string.Empty;\n\n StringBuilder sb = new StringBuilder(contactList[0].Name);\n\n for (int i = 1; i &lt; contactList.Count; i++)\n {\n sb.Append(\",\");\n sb.Append(contactList[i].Name);\n }\n\n return sb.ToString();\n}\n</code></pre>\n\n<p>You could also wrap the second Append in an \"if\" that tests whether the Name property contains a double-quote or a comma, and if so, escape them appropriately.</p>\n" }, { "answer_id": 6724, "author": "dbkk", "author_id": 838, "author_profile": "https://Stackoverflow.com/users/838", "pm_score": 3, "selected": false, "text": "<p>Your code not really compliant with <a href=\"http://www.creativyst.com/Doc/Articles/CSV/CSV01.htm\" rel=\"nofollow noreferrer\">full CSV format</a>. If you are just generating CSV from data that has no commas, leading/trailing spaces, tabs, newlines or quotes, it should be fine. However, in most real-world data-exchange scenarios, you do need the full imlementation. </p>\n\n<p>For generation to proper CSV, you can use this:</p>\n\n<pre><code>public static String EncodeCsvLine(params String[] fields)\n{\n StringBuilder line = new StringBuilder();\n\n for (int i = 0; i &lt; fields.Length; i++)\n {\n if (i &gt; 0)\n {\n line.Append(DelimiterChar);\n }\n\n String csvField = EncodeCsvField(fields[i]);\n line.Append(csvField);\n }\n\n return line.ToString();\n}\n\nstatic String EncodeCsvField(String field)\n{\n StringBuilder sb = new StringBuilder();\n sb.Append(field);\n\n // Some fields with special characters must be embedded in double quotes\n bool embedInQuotes = false;\n\n // Embed in quotes to preserve leading/tralining whitespace\n if (sb.Length &gt; 0 &amp;&amp; \n (sb[0] == ' ' || \n sb[0] == '\\t' ||\n sb[sb.Length-1] == ' ' || \n sb[sb.Length-1] == '\\t' ))\n {\n embedInQuotes = true;\n }\n\n for (int i = 0; i &lt; sb.Length; i++)\n {\n // Embed in quotes to preserve: commas, line-breaks etc.\n if (sb[i] == DelimiterChar || \n sb[i]=='\\r' || \n sb[i]=='\\n' || \n sb[i] == '\"') \n { \n embedInQuotes = true;\n break;\n }\n }\n\n // If the field itself has quotes, they must each be represented \n // by a pair of consecutive quotes.\n sb.Replace(\"\\\"\", \"\\\"\\\"\");\n\n String rv = sb.ToString();\n\n if (embedInQuotes)\n {\n rv = \"\\\"\" + rv + \"\\\"\";\n }\n\n return rv;\n}\n</code></pre>\n\n<p>Might not be world's most efficient code, but it has been tested. Real world sucks compared to quick sample code :)</p>\n" }, { "answer_id": 17305, "author": "Autodidact", "author_id": 2051, "author_profile": "https://Stackoverflow.com/users/2051", "pm_score": 1, "selected": false, "text": "<p>I've used this method before. The Length property of StringBuilder is NOT readonly so subtracting it by one means truncate the last character. But you have to make sure your length is not zero to start with (which would happen if your list is empty) because setting the length to less than zero is an error.</p>\n\n<pre><code>public string ReturnAsCSV(ContactList contactList)\n{\n StringBuilder sb = new StringBuilder();\n\n foreach (Contact c in contactList) \n { \n sb.Append(c.Name + \",\"); \n }\n\n if (sb.Length &gt; 0) \n sb.Length -= 1;\n\n return sb.ToString(); \n}\n</code></pre>\n" }, { "answer_id": 17340, "author": "yoliho", "author_id": 237, "author_profile": "https://Stackoverflow.com/users/237", "pm_score": 3, "selected": false, "text": "<p><strong>Why not use one of the open source CSV libraries out there?</strong></p>\n\n<p>I know it sounds like overkill for something that appears so simple, but as you can tell by the comments and code snippets, there's more than meets the eye. In addition to handling full CSV compliance, you'll eventually want to handle both reading and writing CSVs... and you may want file manipulation.</p>\n\n<p>I've used <a href=\"http://opencsv.sourceforge.net/\" rel=\"noreferrer\">Open CSV</a> on one of my projects before (but there are plenty of others to choose from). It certainly made my life easier. ;)</p>\n" }, { "answer_id": 11214712, "author": "jocull", "author_id": 97964, "author_profile": "https://Stackoverflow.com/users/97964", "pm_score": 1, "selected": false, "text": "<p>I wrote a small class for this in case someone else finds it useful...</p>\n\n<pre><code>public class clsCSVBuilder\n{\n protected int _CurrentIndex = -1;\n protected List&lt;string&gt; _Headers = new List&lt;string&gt;();\n protected List&lt;List&lt;string&gt;&gt; _Records = new List&lt;List&lt;string&gt;&gt;();\n protected const string SEPERATOR = \",\";\n\n public clsCSVBuilder() { }\n\n public void CreateRow()\n {\n _Records.Add(new List&lt;string&gt;());\n _CurrentIndex++;\n }\n\n protected string _EscapeString(string str)\n {\n return string.Format(\"\\\"{0}\\\"\", str.Replace(\"\\\"\", \"\\\"\\\"\")\n .Replace(\"\\r\\n\", \" \")\n .Replace(\"\\n\", \" \")\n .Replace(\"\\r\", \" \"));\n }\n\n protected void _AddRawString(string item)\n {\n _Records[_CurrentIndex].Add(item);\n }\n\n public void AddHeader(string name)\n {\n _Headers.Add(_EscapeString(name));\n }\n\n public void AddRowItem(string item)\n {\n _AddRawString(_EscapeString(item));\n }\n\n public void AddRowItem(int item)\n {\n _AddRawString(item.ToString());\n }\n\n public void AddRowItem(double item)\n {\n _AddRawString(item.ToString());\n }\n\n public void AddRowItem(DateTime date)\n {\n AddRowItem(date.ToShortDateString());\n }\n\n public static string GenerateTempCSVPath()\n {\n return Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString().ToLower().Replace(\"-\", \"\") + \".csv\");\n }\n\n protected string _GenerateCSV()\n {\n StringBuilder sb = new StringBuilder();\n\n if (_Headers.Count &gt; 0)\n {\n sb.AppendLine(string.Join(SEPERATOR, _Headers.ToArray()));\n }\n\n foreach (List&lt;string&gt; row in _Records)\n {\n sb.AppendLine(string.Join(SEPERATOR, row.ToArray()));\n }\n\n return sb.ToString();\n }\n\n public void SaveAs(string path)\n {\n using (StreamWriter sw = new StreamWriter(path))\n {\n sw.Write(_GenerateCSV());\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 11215149, "author": "Ed Power", "author_id": 150058, "author_profile": "https://Stackoverflow.com/users/150058", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"https://github.com/JoshClose/CsvHelper\" rel=\"nofollow\">CSVHelper</a> - it's a great open-source library that lets you generate compliant CSV streams one element at a time or custom-map your classes:</p>\n\n<pre><code>public string ReturnAsCSV(ContactList contactList)\n{\n StringBuilder sb = new StringBuilder();\n using (StringWriter stringWriter = new StringWriter(sb))\n {\n using (var csvWriter = new CsvHelper.CsvWriter(stringWriter))\n {\n csvWriter.Configuration.HasHeaderRecord = false;\n foreach (Contact c in contactList)\n {\n csvWriter.WriteField(c.Name);\n }\n }\n }\n return sb.ToString();\n}\n</code></pre>\n\n<p>or if you map then something like this: <code>csvWriter.WriteRecords&lt;ContactList&gt;(contactList);</code></p>\n" } ]
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 conditional GET, which should include the <strong>if-modified-since</strong> header in the request.</p>\n\n<p>Basically, this request header contains a date from which the client claims to have a cached copy. You should check if content has changed after this date and send a 304 if it hasn't.</p>\n\n<p>See <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25\" rel=\"nofollow noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25</a> for the related section in the RFC.</p>\n" }, { "answer_id": 4527, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": true, "text": "<p>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 <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html\" rel=\"noreferrer\">RFC 2616</a> and by observing what and when the various browsers were sending.</p>\n\n<p>Here's the pseudocode:</p>\n\n<pre>\nserver_etag = gen_etag_for_this_file(myfile)\netag_from_browser = get_header(\"Etag\")\n\nif etag_from_browser does not exist:\n etag_from_browser = get_header(\"If-None-Match\")\nif the browser has quoted the etag:\n strip the quotes (e.g. \"foo\" --> foo)\n\nset server_etag into http header\n\nif etag_from_browser matches server_etag\n send 304 return code to browser\n</pre>\n\n<p>Here's a snippet of my server logic that handles this.</p>\n\n<pre>\n/* the client should set either Etag or If-None-Match */\n/* some clients quote the parm, strip quotes if so */\nmketag(etag, &sb);\n\netagin = apr_table_get(r->headers_in, \"Etag\");\nif (etagin == NULL)\n etagin = apr_table_get(r->headers_in, \"If-None-Match\");\nif (etag != NULL && etag[0] == '\"') {\n int sl; \n sl = strlen(etag);\n memmove(etag, etag+1, sl+1);\n etag[sl-2] = 0;\n logit(2,\"etag=:%s:\",etag);\n} \n... \napr_table_add(r->headers_out, \"ETag\", etag);\n... \nif (etagin != NULL && strcmp(etagin, etag) == 0) {\n /* if the etag matches, we return a 304 */\n rc = HTTP_NOT_MODIFIED;\n} \n</pre>\n\n<p>If you want some help with etag generation post another question and I'll dig out some code that does that as well. HTH!</p>\n" }, { "answer_id": 4535, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 1, "selected": false, "text": "<p>regarding cache-control:</p>\n\n<p>You shouldn't have to worry about the cache-control when serving out, other than setting it to a reasonable value. It's basically telling the browser and other downstream entities (such as a proxy) the maximum time that should elapse before timing out the cache.</p>\n" }, { "answer_id": 6768, "author": "Justin Sheehy", "author_id": 11944, "author_profile": "https://Stackoverflow.com/users/11944", "pm_score": 2, "selected": false, "text": "<p>A 304 Not Modified response can result from a GET or HEAD request with either an If-Modified-Since (\"IMS\") or an If-Not-Match (\"INM\") header.</p>\n\n<p>In order to decide what to do when you receive these headers, imagine that you are handling the GET request without these conditional headers. Determine what the values of your ETag and Last-Modified headers would be in that response and use them to make the decision. Hopefully you have built your system such that determining this is less costly than constructing the complete response.</p>\n\n<p>If there is an INM and the value of that header is the same as the value you would place in the ETag, then respond with 304.</p>\n\n<p>If there is an IMS and the date value in that header is later than the one you would place in the Last-Modified, then respond with 304.</p>\n\n<p>Else, proceed as though the request did not contain those headers.</p>\n\n<p>For a least-effort approach to part 2 of your question, figure out which of the (Expires, ETag, and Last-Modified) headers you can easily and correctly produce in your Web application. </p>\n\n<p>For suggested reading material:</p>\n\n<p><a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616.html\" rel=\"nofollow noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616.html</a></p>\n\n<p><a href=\"http://www.mnot.net/cache_docs/\" rel=\"nofollow noreferrer\">http://www.mnot.net/cache_docs/</a></p>\n" }, { "answer_id": 1560461, "author": "Thomas S. Trias", "author_id": 189048, "author_profile": "https://Stackoverflow.com/users/189048", "pm_score": 2, "selected": false, "text": "<p>We are also handling cached, but secured, resources.  If you send / generate an ETAg header (which RFC 2616 section 13.3 recommends you SHOULD), then the client MUST use it in a conditional request (typically in an If-None-Match - HTTP_IF_NONE_MATCH - header).  If you send a Last-Modified header (again you SHOULD), then you should check the If-Modified-Since - HTTP_IF_MODIFIED_SINCE - header.  If you send both, then the client SHOULD send both, but it MUST send the ETag.  Also note that validtion is just defined as checking the conditional headers for strict equality against the ones you would send out.  Also, only a strong validator (such as an ETag) will be used for ranged requests (where only part of a resource is requested).</p>\n\n<p>In practice, since the resources we are protecting are fairly static, and a one second lag time is acceptable, we are doing the following:</p>\n\n<ol>\n<li><p> Check to see if the user is authorized to access the requested resource</p>\n\n<p>     If they are not, Redirect them or send a 4xx response as appropriate.  We will generate 404 responses to requests that look like hack attempts or blatant tries to perform a security end run.</p></li>\n<li><p> Compare the If-Modified-Since header to the Last-Modified header we would send (see below) for strict equality</p>\n\n<p>     If they match, send a 304 Not Modified response and exit page processing</p></li>\n<li><p> Create a Last-Modified header using the modification time of the requested resource</p>\n\n<p>    Look up the HTTP Date format in RFC 2616</p></li>\n<li><p> Send out the header and resource content along with an appropriate Content-Type</p></li>\n</ol>\n\n<p>We decided to eschew the ETag header since it is overkill for our purposes.  I suppose we could also just use the date time stamp as an ETag.  If we move to a true ETag system, we would probably store computed hashes for the resources and use those as ETags.</p>\n\n<p>If your resources are dynamically generated, from say database content, then ETags may be better for your needs, since they are just text to be populated as you see fit.</p>\n" } ]
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 time the file is requested.</p>\n<p>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.</p>\n<pre><code> server client\n \n &lt;------------- request file foo\n \n file foo etag: &quot;xyz&quot; --------&gt;\n \n &lt;------------- request file foo\n etag: &quot;xyz&quot; (what the server just sent)\n \n (the etag is the same, so the server can send a 304)\n</code></pre>\n<p>I built up a string in the format &quot;datestamp-file size-file inode number&quot;. 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.</p>\n<pre class=\"lang-c prettyprint-override\"><code>char *mketag(char *s, struct stat *sb)\n{\n sprintf(s, &quot;%d-%d-%d&quot;, sb-&gt;st_mtime, sb-&gt;st_size, sb-&gt;st_ino);\n return s;\n}\n</code></pre>\n" }, { "answer_id": 4563, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 3, "selected": false, "text": "<p>From <a href=\"http://developer.yahoo.com/performance/rules.html#etags\" rel=\"noreferrer\">http://developer.yahoo.com/performance/rules.html#etags</a>:</p>\n<blockquote>\n<p>By default, both Apache and IIS embed data in the ETag that dramatically reduces the odds of the validity test succeeding on web sites with multiple servers.</p>\n<p>...</p>\n<p>If you're not taking advantage of the flexible validation model that ETags provide, it's better to just remove the ETag altogether.</p>\n</blockquote>\n" }, { "answer_id": 6777, "author": "Justin Sheehy", "author_id": 11944, "author_profile": "https://Stackoverflow.com/users/11944", "pm_score": 4, "selected": false, "text": "<p>As long as it changes whenever the resource representation changes, how you produce it is completely up to you.</p>\n\n<p>You should try to produce it in a way that additionally:</p>\n\n<ol>\n<li>doesn't require you to re-compute it on each conditional GET, and</li>\n<li>doesn't change if the resource content hasn't changed</li>\n</ol>\n\n<p>Using hashes of content can cause you to fail at #1 if you don't store the computed hashes along with the files.</p>\n\n<p>Using inode numbers can cause you to fail at #2 if you rearrange your filesystem or you serve content from multiple servers.</p>\n\n<p>One mechanism that can work is to use something entirely content dependent such as a SHA-1 hash or a version string, computed and stored once whenever your resource content changes.</p>\n" }, { "answer_id": 106148, "author": "Rich Bradshaw", "author_id": 16511, "author_profile": "https://Stackoverflow.com/users/16511", "pm_score": 0, "selected": false, "text": "<p>I would recommend not using them and going for last-modified headers instead.</p>\n\n<p>Askapache has a useful article on this. (as they do pretty much everything it seems!)</p>\n\n<p><a href=\"http://www.askapache.com/htaccess/apache-speed-etags.html\" rel=\"nofollow noreferrer\">http://www.askapache.com/htaccess/apache-speed-etags.html</a></p>\n" }, { "answer_id": 7308209, "author": "lolesque", "author_id": 787216, "author_profile": "https://Stackoverflow.com/users/787216", "pm_score": 2, "selected": false, "text": "<p>How to generate the default apache etag in bash</p>\n\n<pre><code>for file in *; do printf \"%x-%x-%x\\t$file\\n\" `stat -c%i $file` `stat -c%s $file` $((`stat -c%Y $file`*1000000)) ; done\n</code></pre>\n\n<p>Even when i was looking for something exactly like the etag (the browser asks for a file only if it has changed on the server), it never worked and i ended using a GET trick (adding a timestamp as a get argument to the js files).</p>\n" }, { "answer_id": 14057468, "author": "peawormsworth", "author_id": 1880288, "author_profile": "https://Stackoverflow.com/users/1880288", "pm_score": 1, "selected": false, "text": "<p>Ive been using Adler-32 as an html link shortener. Im not sure whether this is a good idea, but so far, I havent noticed any duplicates. It may work as a etag generator. And it should be faster then trying to hash using an encryption scheme like sha, but I havent verified this. The code I use is:</p>\n\n<pre><code> shortlink = str(hex(zlib.adler32(link)+(2**32-1)/2))[2:-1]\n</code></pre>\n" }, { "answer_id": 63104602, "author": "Sergey Ponomarev", "author_id": 1049542, "author_profile": "https://Stackoverflow.com/users/1049542", "pm_score": 0, "selected": false, "text": "<p>The code example of Mark Harrison is similar to what used in Apache 2.2. But such algorithm causes problems for load balancing when you have two servers with the same file but the file's <code>inode</code> is different. That's why in Apache 2.4 developers simplified ETag schema and removed the <code>inode</code> part. Also to make ETag shorter usually they encoded in hex:</p>\n<pre class=\"lang-c prettyprint-override\"><code> \n&lt;inttypes.h&gt;\n \n \nchar *mketag(char *s, struct stat *sb)\n{\n sprintf(s, &quot;\\&quot;%&quot; PRIx64 &quot;-%&quot; PRIx64 &quot;\\&quot;&quot;, sb-&gt;st_mtime, sb-&gt;st_size);\n return s;\n}\n \n</code></pre>\n<p>or for Java</p>\n<pre class=\"lang-java prettyprint-override\"><code> etag = '&quot;' + Long.toHexString(lastModified) + '-' +\n Long.toHexString(contentLength) + '&quot;';\n</code></pre>\n<p>for C#</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// Generate ETag from file's size and last modification time as unix timestamp in seconds from 1970\npublic static string MakeEtag(long lastMod, long size)\n{\n string etag = '&quot;' + lastMod.ToString(&quot;x&quot;) + '-' + size.ToString(&quot;x&quot;) + '&quot;';\n return etag;\n}\n\npublic static void Main(string[] args)\n{\n long lastMod = 1578315296;\n long size = 1047;\n string etag = MakeEtag(lastMod, size);\n Console.WriteLine(&quot;ETag: &quot; + etag);\n //=&gt; ETag: &quot;5e132e20-417&quot;\n}\n</code></pre>\n<p>The function returns ETag compatible with Nginx. See <a href=\"https://stackoverflow.com/questions/47512043/how-etags-are-generated-and-configured/62996104#62996104\">comparison of ETags form different servers</a></p>\n" } ]
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:[email protected]/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:[email protected]/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 arrives, so then a second attempt now works because you have the correct cookies.</p>\n" }, { "answer_id": 6996, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 3, "selected": true, "text": "<p>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?</p>\n" }, { "answer_id": 12453, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 1, "selected": false, "text": "<p>I'd recommend checking out the <a href=\"http://www.iopus.com/imacros/firefox/\" rel=\"nofollow noreferrer\">iMacros addon for Firefox</a>. I use it to login to a local web server and after logging in, navigate directly to a certain page. The code I have looks like this, but it allows you to record your own macros:</p>\n\n<pre><code>VERSION BUILD=6000814 RECORDER=FX\nTAB T=1\nURL GOTO=http://10.20.2.4/login\nTAG POS=1 TYPE=INPUT:TEXT FORM=NAME:introduce ATTR=NAME:initials CONTENT=username-goes-here\nSET !ENCRYPTION NO\nTAG POS=1 TYPE=INPUT:PASSWORD FORM=NAME:introduce ATTR=NAME:password CONTENT=password-goes-here\nTAG POS=1 TYPE=INPUT:SUBMIT FORM=NAME:introduce ATTR=NAME:Submit&amp;&amp;VALUE:Go\nURL GOTO=http://10.20.2.4/timecard\n</code></pre>\n\n<p>I middle click on it and it opens a new tab and runs the macro taking me directly to the page I want, logged in with the account I specified.</p>\n" }, { "answer_id": 13585, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 2, "selected": false, "text": "<p>@travis Looks very nice! I will sure take a look into it. I can think of several places I can use that</p>\n\n<p>I never got round to sniff the traffic but found out that a php site on my own server with http-auth worked fine, so i figured it was something with delicious. I then created a php page that does a wget of the delicious api and everything works fine :)</p>\n" } ]
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:[email protected]/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:[email protected]/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 further down, you'll find the zig-zag pattern of data to read from that final matrix. The most important data are in the top left corner, and least important in the bottom right corner. As such, if you stop writing at some point and just consider the rest as 0's, even though they aren't, you'll get a lossy approximation of the image.</p>\n\n<p>The number of values you throw away increases compression at the cost of image fidelity.</p>\n\n<p>But I'm sure someone else can give you a better explanation.</p>\n" }, { "answer_id": 6503, "author": "Anthony Cramp", "author_id": 488, "author_profile": "https://Stackoverflow.com/users/488", "pm_score": 4, "selected": false, "text": "<p>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.</p>\n\n<p>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.</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 6990, "author": "Robert Ellison", "author_id": 2521991, "author_profile": "https://Stackoverflow.com/users/2521991", "pm_score": 1, "selected": false, "text": "<p>I'd recommend picking up a copy of <a href=\"http://isbn.nu/9780071424875/price\" rel=\"nofollow noreferrer\">Digital Video Compression</a> - it's a really good overview of compression algorithms for images and video. </p>\n" }, { "answer_id": 8606, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>I learned everything I know about the DCT from <a href=\"https://rads.stackoverflow.com/amzn/click/com/1558514341\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">The Data Compression Book</a>. In addition to being a great introduction to the field of data compression, it has a chapter near the end on lossy image compression which introduces JPEG and the DCT.</p>\n" }, { "answer_id": 29922, "author": "Lehane", "author_id": 142, "author_profile": "https://Stackoverflow.com/users/142", "pm_score": 1, "selected": false, "text": "<p>Anthony Cramp's answer looked good to me. As he mentions the DCT transforms the data into the frequency domain. The DCT is heavily used in video compression as the human visual system is must less sensitive to high frequency changes, therefore zeroing out the higher frequency values results in a smaller file, with little effect on a human's perception of the video quality.</p>\n\n<p>In terms of using the DCT to compare images, I guess the only real benefit is if you cut away the higher frequency data and therefore have a smaller set of data to search/match. Something like Harr wavelets may give better image matching results.</p>\n" }, { "answer_id": 20864293, "author": "stuartw", "author_id": 1319814, "author_profile": "https://Stackoverflow.com/users/1319814", "pm_score": 2, "selected": false, "text": "<p>The concepts underlying these kinds of transformations are more easily seen by first looking at a one dimensional case. The image <a href=\"http://mathworld.wolfram.com/images/eps-gif/FourierSeriesSquareWave_800.gif\" rel=\"nofollow\">here</a> shows a square wave along with several of the first terms of an infinite series. Looking at it, note that if the functions for the terms are added together, they begin to approximate the shape of the square wave. The more terms you add up, the better the approximation. But, to get from an approximation to the exact signal, you have to sum an infinite number of terms. The reason for this is that the square wave is discontinuous. If you think of a square wave as a function of time, it goes from -1 to 1 in zero time. To represent such a thing requires an infinite series. Take another look at the plot of the series terms. The first is red, the second yellow. Successive terms have more \"up and down\" transitions. These are from the increasing frequency of each term. Sticking with the square wave as a function of time, and each series term a function of frequency there are two equivalent representations: a function of time and a function of frequency (1/time).</p>\n\n<p>In the real world, there are no square waves. Nothing happens in zero time. Audio signals, for example occupy the range 20Hz to 20KHz, where Hz is 1/time. Such things can be represented with finite series'.</p>\n\n<p>For images, the mathematics are the same, but two things are different. First, it's two dimensional. Second the notion of time makes no sense. In the 1D sense, the square wave is merely a function that gives some numerical value for for an argument that we said was time. An (static) image is a function that gives a numerical value for for every pair of row, column indeces. In other words, the image is a function of a 2D space, that being a rectangular region. A function like that can be represented in terms of its spatial frequency. To understand what spatial frequency is, consider an 8 bit grey level image and a pair of adjacent pixels. The most abrupt transistion that can occur in the image is going from 0 (say black) to 255 (say white) over the distance of 1 pixel. This corresponds directly with the highest frequency (last) term of a series representation.</p>\n\n<p>A two dimensional Fourier (or Cosine) transformation of the image results in an array of values the same size as the image, representing the same information not as a function of space, but a function of 1/space. The information is ordered from lowest to highest frequency along the diagonal from the origin highest row and column indeces. An example is <a href=\"http://www.cs.cf.ac.uk/Dave/Multimedia/DCT.jpg\" rel=\"nofollow\">here</a>.</p>\n\n<p>For image compression, you can transform an image, discard some number of higher frequency terms and inverse transform the remaining ones back to an image, which has less detail than the original. Although it transforms back to an image of the same size (with the removed terms replaced by zero), in the frequency domain, it occupies less space.</p>\n\n<p>Another way to look at it is reducing an image to a smaller size. If, for example you try to reduce the size of an image by throwing away three of every four pixels in a row, and three of every four rows, you'll have an array 1/4 the size but the image will look terrible. In most cases, this is accomplished with a 2D interpolator, which produces new pixels by averaging rectangular groups of the larger image's pixels. In so doing, the interpolation has an effect similar throwing away series terms in the frequency domain, only it's much faster to compute.</p>\n\n<p>To do more things, I'm going to refer to a Fourier transformation as an example. Any good discussion of the topic will illustrate how the Fourier and Cosine transformation are related. The Fourier transformation of an image can't be viewed directly as such, because it's made of complex numbers. It's already segregated into two kinds of information, the Real and Imaginary parts of the numbers. Typically, you'll see images or plots of these. But it's more meaningful (usually) to separate the complex numbers into their magnitude and phase angle. This is simply taking a complex number on the complex plane and switching to polar coordinates.</p>\n\n<p>For the audio signal, think of the combined sin and cosine functions taking an attitional quantity in their arguments to shift the function back and forth (as a part of the signal representation). For an image, the phase information describes how each term of the series is shifted with respect to the other terms in frequency space. In images, edges are (hopefully) so distinct that they are well characterized by lowest frequency terms in the frequency domain. This happens not because they are abrupt transitions, but because they have e.g. a lot of black area adjacent to a lot of lighter area. Consider a one dimensional slice of an edge. The grey level is zero then transitions up and stays there. Visualize the sine wave that woud be the first approximation term where it crosses the signal transition's midpoint at sin(0). The phase angle of this term corresponds to a displacement in the image space. A great illustraion of this is available <a href=\"http://en.wikipedia.org/wiki/Phase_correlation\" rel=\"nofollow\">here</a>. If you are trying to find shapes and can make a reference shape, this is one way to recognize them.</p>\n" } ]
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 first parameter of the method needs to be prefixed with \"this\" in the signature.</p>\n\n<pre><code>public static string MyMethod(this string input)\n{\n // do things\n}\n</code></pre>\n\n<p>You can then call it like</p>\n\n<pre><code>\"asdfas\".MyMethod();\n</code></pre>\n" }, { "answer_id": 4615, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 6, "selected": true, "text": "<p>You can't dynamically add methods to existing objects or classes in .NET, except by changing the source for that class.</p>\n\n<p>You can, however, in C# 3.0, use extension methods, which <em>look</em> like new methods, but are compile-time magic.</p>\n\n<p>To do this for your code:</p>\n\n<pre><code>public static class StringExtensions\n{\n public static String trim(this String s)\n {\n return s.Trim();\n }\n}\n</code></pre>\n\n<p>To use it:</p>\n\n<pre><code>String s = \" Test \";\ns = s.trim();\n</code></pre>\n\n<p>This looks like a new method, but will compile the exact same way as this code:</p>\n\n<pre><code>String s = \" Test \";\ns = StringExtensions.trim(s);\n</code></pre>\n\n<p>What exactly are you trying to accomplish? Perhaps there are better ways of doing what you want?</p>\n" }, { "answer_id": 4616, "author": "Andrew Peters", "author_id": 608, "author_profile": "https://Stackoverflow.com/users/608", "pm_score": 0, "selected": false, "text": "<p>Using the 3.5 compiler you can use an Extension Method:</p>\n\n<pre><code>public static void Trim(this string s)\n{\n // implementation\n}\n</code></pre>\n\n<p>You can use this on a CLR 2.0 targeted project (3.5 compiler) by including this hack:</p>\n\n<pre><code>namespace System.Runtime.CompilerServices\n{\n [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Assembly)]\n public sealed class ExtensionAttribute : Attribute\n {\n }\n}\n</code></pre>\n" }, { "answer_id": 4619, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 3, "selected": false, "text": "<p>It sounds like you're talking about C#'s Extension Methods. You add functionality to existing classes by inserting the \"this\" keyword before the first parameter. The method has to be a static method in a static class. Strings in .NET already have a \"Trim\" method, so I'll use another example.</p>\n\n<pre><code>public static class MyStringEtensions\n{\n public static bool ContainsMabster(this string s)\n {\n return s.Contains(\"Mabster\");\n }\n}\n</code></pre>\n\n<p>So now every string has a tremendously useful ContainsMabster method, which I can use like this:</p>\n\n<pre><code>if (\"Why hello there, Mabster!\".ContainsMabster()) { /* ... */ }\n</code></pre>\n\n<p>Note that you can also add extension methods to interfaces (eg IList), which means that any class implementing that interface will also pick up that new method.</p>\n\n<p>Any extra parameters you declare in the extension method (after the first \"this\" parameter) are treated as normal parameters.</p>\n" } ]
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 and virtual classes for my patience.</p>\n\n<p>I don't think the source reader part of the compiler ends up with a DOM tree, but intuitively I would agree with you. The work necessary to transform the DOM to IL should be much less than reading C# source code.</p>\n" }, { "answer_id": 29283, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 4, "selected": true, "text": "<p>CompileAssemblyFromDom compiles to a .cs file which is then run through the normal C# compiler.</p>\n<p>Example:</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing Microsoft.CSharp;\nusing System.CodeDom;\nusing System.IO;\nusing System.CodeDom.Compiler;\nusing System.Reflection;\n\nnamespace CodeDomQuestion\n{\n class Program\n {\n\n private static void Main(string[] args)\n {\n Program p = new Program();\n p.dotest(&quot;C:\\\\fs.exe&quot;);\n }\n\n public void dotest(string outputname)\n {\n CSharpCodeProvider cscProvider = new CSharpCodeProvider();\n CompilerParameters cp = new CompilerParameters();\n cp.MainClass = null;\n cp.GenerateExecutable = true;\n cp.OutputAssembly = outputname;\n \n CodeNamespace ns = new CodeNamespace(&quot;StackOverflowd&quot;);\n\n CodeTypeDeclaration type = new CodeTypeDeclaration();\n type.IsClass = true;\n type.Name = &quot;MainClass&quot;;\n type.TypeAttributes = TypeAttributes.Public;\n \n ns.Types.Add(type);\n\n CodeMemberMethod cmm = new CodeMemberMethod();\n cmm.Attributes = MemberAttributes.Static;\n cmm.Name = &quot;Main&quot;;\n cmm.Statements.Add(new CodeSnippetExpression(&quot;System.Console.WriteLine('f'zxcvv)&quot;));\n type.Members.Add(cmm);\n\n CodeCompileUnit ccu = new CodeCompileUnit();\n ccu.Namespaces.Add(ns);\n\n CompilerResults results = cscProvider.CompileAssemblyFromDom(cp, ccu);\n\n foreach (CompilerError err in results.Errors)\n Console.WriteLine(err.ErrorText + &quot; - &quot; + err.FileName + &quot;:&quot; + err.Line);\n\n Console.WriteLine();\n }\n }\n}\n</code></pre>\n<p>which shows errors in a (now nonexistent) temp file:</p>\n<blockquote>\n<p>) expected - c:\\Documents and Settings\\jacob\\Local Settings\\Temp\\x59n9yb-.0.cs:17</p>\n<p>; expected - c:\\Documents and Settings\\jacob\\Local Settings\\Temp\\x59n9yb-.0.cs:17</p>\n<p>Invalid expression term ')' - c:\\Documents and Settings\\jacob\\Local Settings\\Tem p\\x59n9yb-.0.cs:17</p>\n</blockquote>\n<p>So I guess the answer is &quot;no&quot;</p>\n" } ]
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>\n\n<pre><code>CASE case-expression\n WHEN when-expression-1 THEN value-1\n [ WHEN when-expression-n THEN value-n ... ]\n [ ELSE else-value ]\nEND\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>CASE\n WHEN boolean-when-expression-1 THEN value-1\n [ WHEN boolean-when-expression-n THEN value-n ... ]\n [ ELSE else-value ]\nEND\n</code></pre>\n\n<p>expressions, etc:</p>\n\n<pre><code>case-expression - something that produces a value\nwhen-expression-x - something that is compared against the case-expression\nvalue-1 - the result of the CASE statement if:\n the when-expression == case-expression\n OR the boolean-when-expression == TRUE\nboolean-when-exp.. - something that produces a TRUE/FALSE answer\n</code></pre>\n\n<p>Link: <a href=\"http://msdn.microsoft.com/en-us/library/ms181765.aspx\" rel=\"noreferrer\">CASE (Transact-SQL)</a></p>\n\n<p>Also note that the ordering of the WHEN statements is important. You can easily write multiple WHEN clauses that overlap, and <strong>the first one that matches is used</strong>.</p>\n\n<p><strong>Note</strong>: If no ELSE clause is specified, and no matching WHEN-condition is found, the value of the CASE expression will be <em>NULL</em>.</p>\n" }, { "answer_id": 4631, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>I dug up the Oracle page for the same and it looks like this is the same syntax, just described slightly different.</p>\n\n<p>Link: <a href=\"http://www.techonthenet.com/oracle/functions/case.php\" rel=\"nofollow noreferrer\">Oracle/PLSQL: Case Statement</a></p>\n" }, { "answer_id": 4634, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 4, "selected": false, "text": "<p>Here are the <a href=\"http://www.postgresql.org/docs/current/static/functions-conditional.html\" rel=\"noreferrer\" title=\"Conditional Expressions\"><code>CASE</code> statement examples from the PostgreSQL docs</a> (Postgres follows the SQL standard here):</p>\n\n<pre><code>SELECT a,\n CASE WHEN a=1 THEN 'one'\n WHEN a=2 THEN 'two'\n ELSE 'other'\n END\nFROM test;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>SELECT a,\n CASE a WHEN 1 THEN 'one'\n WHEN 2 THEN 'two'\n ELSE 'other'\n END\nFROM test;\n</code></pre>\n\n<p>Obviously the second form is cleaner when you are just checking one field against a list of possible values. The first form allows more complicated expressions.</p>\n" }, { "answer_id": 223167, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 2, "selected": false, "text": "<p>Oracle <a href=\"http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/expressions004.htm#SQLRF20037\" rel=\"nofollow noreferrer\">syntax from the 11g Documentation</a>:</p>\n\n<pre><code>CASE { simple_case_expression | searched_case_expression }\n [ else_clause ]\n END\n</code></pre>\n\n<p><i>simple_case_expression</i></p>\n\n<pre><code>expr { WHEN comparison_expr THEN return_expr }...\n</code></pre>\n\n<p><i>searched_case_expression</i></p>\n\n<pre><code>{ WHEN condition THEN return_expr }...\n</code></pre>\n\n<p><i>else_clause</i></p>\n\n<pre><code>ELSE else_expr\n</code></pre>\n" }, { "answer_id": 224770, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 4, "selected": false, "text": "<p>Considering you tagged multiple products, I'd say the <em>full</em> correct syntax would be the one found in the ISO/ANSI SQL-92 standard:</p>\n\n<pre><code>&lt;case expression&gt; ::=\n &lt;case abbreviation&gt;\n | &lt;case specification&gt;\n\n&lt;case abbreviation&gt; ::=\n NULLIF &lt;left paren&gt; &lt;value expression&gt; &lt;comma&gt;\n &lt;value expression&gt; &lt;right paren&gt;\n | COALESCE &lt;left paren&gt; &lt;value expression&gt;\n { &lt;comma&gt; &lt;value expression&gt; }... &lt;right paren&gt;\n\n&lt;case specification&gt; ::=\n &lt;simple case&gt;\n | &lt;searched case&gt;\n\n&lt;simple case&gt; ::=\n CASE &lt;case operand&gt;\n &lt;simple when clause&gt;...\n [ &lt;else clause&gt; ]\n END\n\n&lt;searched case&gt; ::=\n CASE\n &lt;searched when clause&gt;...\n [ &lt;else clause&gt; ]\n END\n\n&lt;simple when clause&gt; ::= WHEN &lt;when operand&gt; THEN &lt;result&gt;\n\n&lt;searched when clause&gt; ::= WHEN &lt;search condition&gt; THEN &lt;result&gt;\n\n&lt;else clause&gt; ::= ELSE &lt;result&gt;\n\n&lt;case operand&gt; ::= &lt;value expression&gt;\n\n&lt;when operand&gt; ::= &lt;value expression&gt;\n\n&lt;result&gt; ::= &lt;result expression&gt; | NULL\n\n&lt;result expression&gt; ::= &lt;value expression&gt;\n</code></pre>\n\n<p>Syntax Rules</p>\n\n<pre><code>1) NULLIF (V1, V2) is equivalent to the following &lt;case specification&gt;:\n\n CASE WHEN V1=V2 THEN NULL ELSE V1 END\n\n2) COALESCE (V1, V2) is equivalent to the following &lt;case specification&gt;:\n\n CASE WHEN V1 IS NOT NULL THEN V1 ELSE V2 END\n\n3) COALESCE (V1, V2, . . . ,n ), for n &gt;= 3, is equivalent to the\n following &lt;case specification&gt;:\n\n CASE WHEN V1 IS NOT NULL THEN V1 ELSE COALESCE (V2, . . . ,n )\n END\n\n4) If a &lt;case specification&gt; specifies a &lt;simple case&gt;, then let CO\n be the &lt;case operand&gt;:\n\n a) The data type of each &lt;when operand&gt; WO shall be comparable\n with the data type of the &lt;case operand&gt;.\n\n b) The &lt;case specification&gt; is equivalent to a &lt;searched case&gt;\n in which each &lt;searched when clause&gt; specifies a &lt;search\n condition&gt; of the form \"CO=WO\".\n\n5) At least one &lt;result&gt; in a &lt;case specification&gt; shall specify a\n &lt;result expression&gt;.\n\n6) If an &lt;else clause&gt; is not specified, then ELSE NULL is im-\n plicit.\n\n7) The data type of a &lt;case specification&gt; is determined by ap-\n plying Subclause 9.3, \"Set operation result data types\", to the\n data types of all &lt;result expression&gt;s in the &lt;case specifica-\n tion&gt;.\n\nAccess Rules\n\n None.\n\nGeneral Rules\n\n1) Case:\n\n a) If a &lt;result&gt; specifies NULL, then its value is the null\n value.\n\n b) If a &lt;result&gt; specifies a &lt;value expression&gt;, then its value\n is the value of that &lt;value expression&gt;.\n\n2) Case:\n\n a) If the &lt;search condition&gt; of some &lt;searched when clause&gt; in\n a &lt;case specification&gt; is true, then the value of the &lt;case\n specification&gt; is the value of the &lt;result&gt; of the first\n (leftmost) &lt;searched when clause&gt; whose &lt;search condition&gt; is\n true, cast as the data type of the &lt;case specification&gt;.\n\n b) If no &lt;search condition&gt; in a &lt;case specification&gt; is true,\n then the value of the &lt;case expression&gt; is the value of the\n &lt;result&gt; of the explicit or implicit &lt;else clause&gt;, cast as\n the data type of the &lt;case specification&gt;.\n</code></pre>\n" }, { "answer_id": 687137, "author": "Eric Johnson", "author_id": 58089, "author_profile": "https://Stackoverflow.com/users/58089", "pm_score": 3, "selected": false, "text": "<p>Sybase has the same <a href=\"http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.help.ase_15.0.blocks/html/blocks/blocks115.htm\" rel=\"noreferrer\">case syntax</a> as SQL Server:</p>\n\n<h2>Description</h2>\n\n<p>Supports conditional SQL expressions; can be used anywhere a value expression can be used.</p>\n\n<h3>Syntax</h3>\n\n<pre><code>case \n when search_condition then expression \n [when search_condition then expression]...\n [else expression]\nend\n</code></pre>\n\n<h3>Case and values syntax</h3>\n\n<pre><code>case expression\n when expression then expression \n [when expression then expression]...\n [else expression]\nend\n</code></pre>\n\n<h2>Parameters</h2>\n\n<h3>case</h3>\n\n<p>begins the case expression.</p>\n\n<h3>when</h3>\n\n<p>precedes the search condition or the expression to be compared.</p>\n\n<h3>search_condition</h3>\n\n<p>is used to set conditions for the results that are selected. Search conditions for case expressions are similar to the search conditions in a where clause. Search conditions are detailed in the Transact-SQL User’s Guide.</p>\n\n<h3>then</h3>\n\n<p>precedes the expression that specifies a result value of case.</p>\n\n<h3>expression</h3>\n\n<p>is a column name, a constant, a function, a subquery, or any combination of column names, constants, and functions connected by arithmetic or bitwise operators. For more information about expressions, see “Expressions” in.</p>\n\n<h2>Example</h2>\n\n<pre><code>select disaster, \n case\n when disaster = \"earthquake\" \n then \"stand in doorway\"\n when disaster = \"nuclear apocalypse\" \n then \"hide in basement\"\n when monster = \"zombie apocalypse\" \n then \"hide with Chuck Norris\"\n else\n then \"ask mom\"\n end \n from endoftheworld\n</code></pre>\n" }, { "answer_id": 14558826, "author": "user2001117", "author_id": 2001117, "author_profile": "https://Stackoverflow.com/users/2001117", "pm_score": -1, "selected": false, "text": "<p>Case statement syntax in SQL SERVER:</p>\n\n<pre><code>CASE column\n WHEN value1 THEN 1\n WHEN value3 THEN 2\n WHEN value3 THEN 3\n WHEN value1 THEN 4\n ELSE ''\nEND\n</code></pre>\n\n<p>And we can use like below also:</p>\n\n<pre><code>CASE \n WHEN column=value1 THEN 1\n WHEN column=value3 THEN 2\n WHEN column=value3 THEN 3\n WHEN column=value1 THEN 4\n ELSE ''\nEND\n</code></pre>\n" }, { "answer_id": 65185982, "author": "Aruna Karunarathna", "author_id": 760445, "author_profile": "https://Stackoverflow.com/users/760445", "pm_score": -1, "selected": false, "text": "<p>Here you can find a complete guide for <a href=\"https://geekposting.com/case-statements-in-sql-complete-guide/\" rel=\"nofollow noreferrer\">MySQL case statements in SQL</a>.</p>\n<pre><code>CASE\n WHEN some_condition THEN return_some_value\n ELSE return_some_other_value\nEND\n</code></pre>\n" } ]
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 = theObject.GetType().GetProperty(\"Property\" + i).GetValue(theObject, null);\n</code></pre>\n\n<p>That is, assuming the object that has the property is called \"theObject\" :)</p>\n" }, { "answer_id": 4635, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>You could do it with a prototype function:</p>\n\n<pre><code>void something(int i, string P1) {\n something(i, P1, String.Empty);\n}\n\nvoid something(int i, string P1, string P2) {\n something(i, P1, P2, String.Empty);\n}\n\nvoid something(int i, string P1, string P2, string P3) {\n something(i, P1, P2, P3, String.Empty);\n}\n</code></pre>\n\n<p>and so on...</p>\n" }, { "answer_id": 4636, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 4, "selected": false, "text": "<p>Not really. You can use reflection to achieve what you want, but it won't be nearly as simple as in Javascript. For example, if you wanted to set the private field of an object to something, you could use this function:</p>\n\n<pre><code>protected static void SetField(object o, string fieldName, object value)\n{\n FieldInfo field = o.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);\n field.SetValue(o, value);\n}\n</code></pre>\n" }, { "answer_id": 4637, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 7, "selected": true, "text": "<p><strong>DISCLAIMER:</strong> This answer was written back in 2008. The landscape has changed drastically since then.</p>\n<p>Look at the other answers on this page, especially the one detailing <code>Microsoft.CodeAnalysis.CSharp.Scripting</code>.</p>\n<p>Rest of answer will be left as it was originally posted but is no longer accurate.</p>\n<hr />\n<p>Unfortunately, C# isn't a dynamic language like that.</p>\n<p>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.</p>\n<p>This forum post on MSDN contains an answer with some example code down the page somewhat:<br />\n<a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/6a783cc4-bb54-4fec-b504-f9b1ed786b54/create-a-anonymous-method-from-a-string\" rel=\"nofollow noreferrer\">create a anonymous method from a string? </a></p>\n<p>I would hardly say this is a very good solution, but it is possible anyway.</p>\n<p>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.</p>\n<hr />\n<p><strong>Edit</strong>: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here.</p>\n<p>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.</p>\n<pre><code>String propName = &quot;Text&quot;;\nPropertyInfo pi = someObject.GetType().GetProperty(propName);\npi.SetValue(someObject, &quot;New Value&quot;, new Object[0]);\n</code></pre>\n<p>Link: <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.propertyinfo.setvalue\" rel=\"nofollow noreferrer\">PropertyInfo.SetValue Method</a></p>\n" }, { "answer_id": 4657, "author": "MojoFilter", "author_id": 93, "author_profile": "https://Stackoverflow.com/users/93", "pm_score": 3, "selected": false, "text": "<p>All of that would definitely work. Personally, for that particular problem, I would probably take a little different approach. Maybe something like this:</p>\n\n<pre><code>class MyClass {\n public Point point1, point2, point3;\n\n private Point[] points;\n\n public MyClass() {\n //...\n this.points = new Point[] {point1, point2, point3};\n }\n\n public void DoSomethingWith(int i) {\n Point target = this.points[i+1];\n // do stuff to target\n }\n}\n</code></pre>\n\n<p>When using patterns like this, you have to be careful that your data is stored by reference and not by value. In other words, don't do this with primitives. You have to use their big bloated class counterparts.</p>\n\n<p>I realized that's not exactly the question, but the question has been pretty well answered and I thought maybe an alternative approach might help.</p>\n" }, { "answer_id": 1564919, "author": "Sébastien Ros - MSFT", "author_id": 142772, "author_profile": "https://Stackoverflow.com/users/142772", "pm_score": 3, "selected": false, "text": "<p>I don't now if you absolutely want to execute C# statements, but you can already execute Javascript statements in C# 2.0. The open-source library <a href=\"http://jint.codeplex.com\" rel=\"noreferrer\">Jint</a> is able to do it. It's a Javascript interpreter for .NET. Pass a Javascript program and it will run inside your application. You can even pass C# object as arguments and do automation on it.</p>\n\n<p>Also if you just want to evaluate expression on your properties, give a try to <a href=\"http://ncalc.codeplex.com\" rel=\"noreferrer\">NCalc</a>.</p>\n" }, { "answer_id": 3841433, "author": "Xodem", "author_id": 464085, "author_profile": "https://Stackoverflow.com/users/464085", "pm_score": 1, "selected": false, "text": "<p>You also could implement a Webbrowser, then load a html-file wich contains javascript.</p>\n\n<p>Then u go for the <code>document.InvokeScript</code> Method on this browser. The return Value of the eval function can be catched and converted into everything you need.</p>\n\n<p>I did this in several Projects and it works perfectly.</p>\n\n<p>Hope it helps</p>\n" }, { "answer_id": 6301348, "author": "xnaterm", "author_id": 445334, "author_profile": "https://Stackoverflow.com/users/445334", "pm_score": -1, "selected": false, "text": "<p>Unfortunately, C# doesn't have any native facilities for doing exactly what you are asking. </p>\n\n<p>However, my C# eval program does allow for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, <a href=\"http://csharp-eval.com\" rel=\"nofollow\">http://csharp-eval.com</a>, for additional details.</p>\n" }, { "answer_id": 6457416, "author": "Largo", "author_id": 487303, "author_profile": "https://Stackoverflow.com/users/487303", "pm_score": 4, "selected": false, "text": "<p>This is an eval function under c#. I used it to convert anonymous functions (Lambda Expressions) from a string.\nSource: <a href=\"http://www.codeproject.com/KB/cs/evalcscode.aspx\" rel=\"noreferrer\">http://www.codeproject.com/KB/cs/evalcscode.aspx</a></p>\n\n<pre><code>public static object Eval(string sCSCode) {\n\n CSharpCodeProvider c = new CSharpCodeProvider();\n ICodeCompiler icc = c.CreateCompiler();\n CompilerParameters cp = new CompilerParameters();\n\n cp.ReferencedAssemblies.Add(\"system.dll\");\n cp.ReferencedAssemblies.Add(\"system.xml.dll\");\n cp.ReferencedAssemblies.Add(\"system.data.dll\");\n cp.ReferencedAssemblies.Add(\"system.windows.forms.dll\");\n cp.ReferencedAssemblies.Add(\"system.drawing.dll\");\n\n cp.CompilerOptions = \"/t:library\";\n cp.GenerateInMemory = true;\n\n StringBuilder sb = new StringBuilder(\"\");\n sb.Append(\"using System;\\n\" );\n sb.Append(\"using System.Xml;\\n\");\n sb.Append(\"using System.Data;\\n\");\n sb.Append(\"using System.Data.SqlClient;\\n\");\n sb.Append(\"using System.Windows.Forms;\\n\");\n sb.Append(\"using System.Drawing;\\n\");\n\n sb.Append(\"namespace CSCodeEvaler{ \\n\");\n sb.Append(\"public class CSCodeEvaler{ \\n\");\n sb.Append(\"public object EvalCode(){\\n\");\n sb.Append(\"return \"+sCSCode+\"; \\n\");\n sb.Append(\"} \\n\");\n sb.Append(\"} \\n\");\n sb.Append(\"}\\n\");\n\n CompilerResults cr = icc.CompileAssemblyFromSource(cp, sb.ToString());\n if( cr.Errors.Count &gt; 0 ){\n MessageBox.Show(\"ERROR: \" + cr.Errors[0].ErrorText, \n \"Error evaluating cs code\", MessageBoxButtons.OK, \n MessageBoxIcon.Error );\n return null;\n }\n\n System.Reflection.Assembly a = cr.CompiledAssembly;\n object o = a.CreateInstance(\"CSCodeEvaler.CSCodeEvaler\");\n\n Type t = o.GetType();\n MethodInfo mi = t.GetMethod(\"EvalCode\");\n\n object s = mi.Invoke(o, null);\n return s;\n\n}\n</code></pre>\n" }, { "answer_id": 7204715, "author": "roft", "author_id": 914071, "author_profile": "https://Stackoverflow.com/users/914071", "pm_score": -1, "selected": false, "text": "<p>the correct answer is you need to cache all the result to keep the mem0ry usage low.</p>\n\n<p>an example would look like this</p>\n\n<pre><code>TypeOf(Evaluate)\n{\n\"1+1\":2;\n\"1+2\":3;\n\"1+3\":5;\n....\n\"2-5\":-3;\n\"0+0\":1\n} \n</code></pre>\n\n<p>and add it to a List</p>\n\n<pre><code>List&lt;string&gt; results = new List&lt;string&gt;();\nfor() results.Add(result);\n</code></pre>\n\n<p>save the id and use it in the code</p>\n\n<p>hope this helps</p>\n" }, { "answer_id": 8020865, "author": "Jan Bannister", "author_id": 460845, "author_profile": "https://Stackoverflow.com/users/460845", "pm_score": 1, "selected": false, "text": "<p>Uses reflection to parse and evaluate a data-binding expression against an object at run time. </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.databinder.eval%28v=vs.71%29.aspx\" rel=\"nofollow\">DataBinder.Eval Method</a></p>\n" }, { "answer_id": 14671114, "author": "Davide Icardi", "author_id": 209727, "author_profile": "https://Stackoverflow.com/users/209727", "pm_score": 4, "selected": false, "text": "<p>I have written an open source project, <a href=\"https://github.com/davideicardi/DynamicExpresso/\" rel=\"noreferrer\">Dynamic Expresso</a>, that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into <a href=\"http://msdn.microsoft.com/en-us/library/bb397951.aspx\" rel=\"noreferrer\">Expression Trees</a> without using compilation or reflection.</p>\n\n<p>You can write something like:</p>\n\n<pre><code>var interpreter = new Interpreter();\nvar result = interpreter.Eval(\"8 / 2 + 2\");\n</code></pre>\n\n<p>or</p>\n\n<pre><code>var interpreter = new Interpreter()\n .SetVariable(\"service\", new ServiceExample());\n\nstring expression = \"x &gt; 4 ? service.SomeMethod() : service.AnotherMethod()\";\n\nLambda parsedExpression = interpreter.Parse(expression, \n new Parameter(\"x\", typeof(int)));\n\nparsedExpression.Invoke(5);\n</code></pre>\n\n<p>My work is based on Scott Gu article <a href=\"http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx\" rel=\"noreferrer\">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a> .</p>\n" }, { "answer_id": 37983894, "author": "Eli Arbel", "author_id": 276083, "author_profile": "https://Stackoverflow.com/users/276083", "pm_score": 6, "selected": false, "text": "<p>Using the Roslyn scripting API (more <a href=\"https://github.com/dotnet/roslyn/wiki/Scripting-API-Samples\" rel=\"noreferrer\">samples here</a>):</p>\n\n<pre><code>// add NuGet package 'Microsoft.CodeAnalysis.Scripting'\nusing Microsoft.CodeAnalysis.CSharp.Scripting;\n\nawait CSharpScript.EvaluateAsync(\"System.Math.Pow(2, 4)\") // returns 16\n</code></pre>\n\n<p>You can also run any piece of code:</p>\n\n<pre><code>var script = await CSharpScript.RunAsync(@\"\n class MyClass\n { \n public void Print() =&gt; System.Console.WriteLine(1);\n }\")\n</code></pre>\n\n<p>And reference the code that was generated in previous runs:</p>\n\n<pre><code>await script.ContinueWithAsync(\"new MyClass().Print();\");\n</code></pre>\n" }, { "answer_id": 45673529, "author": "Iucounu", "author_id": 2346932, "author_profile": "https://Stackoverflow.com/users/2346932", "pm_score": 1, "selected": false, "text": "<p>I have written a package, <a href=\"https://bitbucket.org/jeff_varszegi/sharpbyte-net-public/src/f6bc1e2fc59993ae76e3afc248bee364ba189809/SharpByte.Core/Dynamic/?at=master\" rel=\"nofollow noreferrer\">SharpByte.Dynamic</a>, to simplify the task of compiling and executing code dynamically. The code can be invoked on any context object using extension methods as detailed further <a href=\"https://digitalrumpus.wordpress.com/2017/08/14/easily-execute-dynamic-c-using-extension-methods/\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>For example, </p>\n\n<pre><code>someObject.Evaluate&lt;int&gt;(\"6 / {{{0}}}\", 3))\n</code></pre>\n\n<p>returns 3; </p>\n\n<pre><code>someObject.Evaluate(\"this.ToString()\"))\n</code></pre>\n\n<p>returns the context object's string representation;</p>\n\n<pre><code>someObject.Execute(@\n\"Console.WriteLine(\"\"Hello, world!\"\");\nConsole.WriteLine(\"\"This demonstrates running a simple script\"\");\n\");\n</code></pre>\n\n<p>runs those statements as a script, etc. </p>\n\n<p>Executables can be gotten easily using a factory method, as seen in the example <a href=\"https://bitbucket.org/jeff_varszegi/sharpbyte-net-public/src/f6bc1e2fc59993ae76e3afc248bee364ba189809/SharpByte.Core/Dynamic/ObjectExtensions.cs?at=master&amp;fileviewer=file-view-default#ObjectExtensions.cs-396\" rel=\"nofollow noreferrer\">here</a>--all you need is the source code and list of any expected named parameters (tokens are embedded using triple-bracket notation, such as {{{0}}}, to avoid collisions with string.Format() as well as Handlebars-like syntaxes):</p>\n\n<pre><code>IExecutable executable = ExecutableFactory.Default.GetExecutable(executableType, sourceCode, parameterNames, addedNamespaces);\n</code></pre>\n\n<p>Each executable object (script or expression) is thread-safe, can be stored and reused, supports logging from within a script, stores timing information and last exception if encountered, etc. There is also a Copy() method compiled on each to allow creating cheap copies, i.e. using an executable object compiled from a script or expression as a template for creating others. </p>\n\n<p>Overhead of executing an already-compiled script or statement is relatively low, at well under a microsecond on modest hardware, and already-compiled scripts and expressions are cached for reuse. </p>\n" }, { "answer_id": 50136420, "author": "Ilya Dan", "author_id": 7379207, "author_profile": "https://Stackoverflow.com/users/7379207", "pm_score": 0, "selected": false, "text": "<p>I was trying to get a value of a structure (class) member by it's name. The structure was not dynamic. All answers didn't work until I finally got it:</p>\n\n<pre><code>public static object GetPropertyValue(object instance, string memberName)\n{\n return instance.GetType().GetField(memberName).GetValue(instance);\n}\n</code></pre>\n\n<p>This method will return the value of the member by it's name. It works on regular structure (class).</p>\n" }, { "answer_id": 51322656, "author": "Hennadii", "author_id": 9329578, "author_profile": "https://Stackoverflow.com/users/9329578", "pm_score": 0, "selected": false, "text": "<p>You might check the <a href=\"https://github.com/Heleonix/Heleonix.Reflection\" rel=\"nofollow noreferrer\">Heleonix.Reflection</a> library. It provides methods to get/set/invoke members dynamically, including nested members, or if a member is clearly defined, you can create a getter/setter (lambda compiled into a delegate) which is faster than reflection:</p>\n\n<pre><code>var success = Reflector.Set(instance, null, $\"Property{i}\", value);\n</code></pre>\n\n<p>Or if number of properties is not endless, you can generate setters and chache them (setters are faster since they are compiled delegates):</p>\n\n<pre><code>var setter = Reflector.CreateSetter&lt;object, object&gt;($\"Property{i}\", typeof(type which contains \"Property\"+i));\nsetter(instance, value);\n</code></pre>\n\n<p>Setters can be of type <code>Action&lt;object, object&gt;</code> but instances can be different at runtime, so you can create lists of setters.</p>\n" } ]
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. However, just because a site doesn't allow you to create multiple entries doesn't mean you can't swap out OpenID suppliers.</p>\n\n<h2>How to turn your blog into an OpenID</h2>\n\n<p>STEP 1: Get an OpenID. There a lots of servers and services out there you can use. I use <a href=\"http://www.myopenid.com\" rel=\"nofollow noreferrer\">http://www.myopenid.com</a></p>\n\n<p>STEP 2: Add these two lines to your blog's main template in-between the <code>&lt;HEAD&gt;&lt;/HEAD&gt;</code> 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.</p>\n\n<p>Example:</p>\n\n<pre>\n&lt;link rel=\"openid.server\" href=\"http://www.myopenid.com/server\" /&gt; \n&lt;link rel=\"openid.delegate\" href=http://YOURUSERNAME.myopenid.com/ /&gt;\n</pre>\n\n<p>This will let you use your domain/blog as your OpenID.</p>\n\n<p>Credits to <a href=\"http://www.hanselman.com/blog/TheWeeklySourceCode25OpenIDEdition.aspx\" rel=\"nofollow noreferrer\">Scott Hanselman</a> and <a href=\"http://simonwillison.net/2006/Dec/19/openid/\" rel=\"nofollow noreferrer\">Simon Willison</a> for these simple instructions.</p>\n\n<h2>Switch Your Supplier</h2>\n\n<p>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.</p>\n" }, { "answer_id": 4854, "author": "Xetius", "author_id": 274, "author_profile": "https://Stackoverflow.com/users/274", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>@prakesh</p>\n \n <p>As long as you associate all of them\n to the same email address, i would\n think it would lead you to same\n account.</p>\n \n <p>But whats your experience?</p>\n</blockquote>\n\n<p>When I tried it out I got a whole new account with 0 rep and no steenkin badges. So at the moment SO does not allow multiple OpenID's to be associated with the one account</p>\n" }, { "answer_id": 34867, "author": "Mike Heinz", "author_id": 1565, "author_profile": "https://Stackoverflow.com/users/1565", "pm_score": 0, "selected": false, "text": "<p>Doesn't using multiple open-id providers sort of undermine the point of open id?</p>\n" }, { "answer_id": 35287, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>Doesn't using multiple open-id providers sort of undermine the point of open id?</p>\n</blockquote>\n\n<p>No. Say you are using a Yahoo OpenID, but you decide to move to Google instead. Multiple OpenIDs per account allows you to associate your account with the Google OpenID, then deauthorize the Yahoo OpenID.</p>\n" }, { "answer_id": 112662, "author": "Troels Thomsen", "author_id": 20138, "author_profile": "https://Stackoverflow.com/users/20138", "pm_score": 3, "selected": false, "text": "<p>In addition to the meta tag sample by Otto, you should be aware whether your provider supports OpenID 2.0 (there are numerous improvements). If it does use meta tags as the following:</p>\n\n<pre><code>&lt;link rel=\"openid2.provider\" href=\"http://www.loginbuzz.com/provider.axd\" /&gt;\n&lt;link rel=\"openid2.local_id\" href=\"http://example.loginbuzz.com/\" /&gt;\n&lt;link rel=\"openid.server\" href=\"http://www.loginbuzz.com/provider.axd\" /&gt;\n&lt;link rel=\"openid.delegate\" href=\"http://example.loginbuzz.com/\" /&gt;\n</code></pre>\n\n<p>A good idea would also be to use secure links, but this could limit some relying parties from signing in. This could however be solved by providing a <a href=\"http://en.wikipedia.org/wiki/XRDS\" rel=\"nofollow noreferrer\" title=\"XRDS on Wikipedia\">XRDS document</a>.</p>\n\n<p>The really neat thing about XRDS is that you are able to specify multiple providers in this document. Say you have a bunch of different accounts all with different providers supporting different extensions. The relying party are then able to select the best match by itself.\nIn the XRDS document you could also specify multiple URLs for each service, so that https is used when appropriate.</p>\n\n<p>I would also recommend buying an <a href=\"http://www.inames.net/personal.html\" rel=\"nofollow noreferrer\" title=\"More on personal i-names\">i-name</a> as it by design is more secure (the canonical ID - the i-number - associated with an i-name belongs to you even if the i-name expires).</p>\n" }, { "answer_id": 118176, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>The key here is to not change identities, ever.\nChange providers, but not identities. (this is like real life)</p>\n\n<p>So new users to OpenID should first consider what their identity <em>could</em> be.</p>\n\n<p>Users that already have some kind of website they own should choose this URL and users without a website have these options:</p>\n\n<ul>\n<li>Get something like a blog to get a URL</li>\n<li>Buy an i-name (or a domain name)</li>\n<li>or use an identity provider supplied URL</li>\n</ul>\n\n<p>In the case of the identity provider supplied URL, users need to be aware that if in the future they choose to delegate or change identities in some way that its essentially a new identity and that multiple identity support with RPs (and OPs) is limited (required usually to re-associate a local account on an RP site to a different OpenID identity).</p>\n" } ]
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://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html\" rel=\"noreferrer\">http://www.ruby-doc.org/stdlib/libdoc/singleton/rdoc/index.html</a> for more info.</p>\n" }, { "answer_id": 5453, "author": "CodingWithoutComments", "author_id": 25, "author_profile": "https://Stackoverflow.com/users/25", "pm_score": 4, "selected": true, "text": "<p>Actually, the above answer was not completely correct.</p>\n\n<pre><code>require 'singleton'\n\nclass Example\n include Singleton\nend\n</code></pre>\n\n<p>You also need to include the require 'singleton' statement.</p>\n" }, { "answer_id": 5592, "author": "Michael Neale", "author_id": 699, "author_profile": "https://Stackoverflow.com/users/699", "pm_score": 0, "selected": false, "text": "<p>You could use modules to the same effect I believe, although its not \"the singleton pattern\" you can have global state that way (which is what a singleton is ! Naughty global state !).</p>\n" } ]
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); //Path to your config file\nSystem.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);\n</code></pre>\n" }, { "answer_id": 5965, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 3, "selected": false, "text": "<p>In addition to Ishmaeel's answer, the method <code>OpenMappedMachineConfiguration()</code> will always return a <code>Configuration</code> object. So to check to see if it loaded you should check the <code>HasFile</code> property where true means it came from a file.</p>\n" }, { "answer_id": 3818417, "author": "Gavin", "author_id": 78216, "author_profile": "https://Stackoverflow.com/users/78216", "pm_score": 5, "selected": false, "text": "<p>Ishmaeel's answer generally does work, however I found one issue, which is that using <code>OpenMappedMachineConfiguration</code> seems to lose your inherited section groups from machine.config. This means that you can access your own custom sections (which is all the OP wanted), but not the normal system sections. For example, this code will not work:</p>\n\n<pre><code>ConfigurationFileMap fileMap = new ConfigurationFileMap(strConfigPath);\nConfiguration configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);\nMailSettingsSectionGroup thisMail = configuration.GetSectionGroup(\"system.net/mailSettings\") as MailSettingsSectionGroup; // returns null\n</code></pre>\n\n<p>Basically, if you put a watch on the <code>configuration.SectionGroups</code>, you'll see that system.net is not registered as a SectionGroup, so it's pretty much inaccessible via the normal channels.</p>\n\n<p>There are two ways I found to work around this. The first, which I don't like, is to re-implement the system section groups by copying them from machine.config into your own web.config e.g.</p>\n\n<pre><code>&lt;sectionGroup name=\"system.net\" type=\"System.Net.Configuration.NetSectionGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"&gt;\n &lt;sectionGroup name=\"mailSettings\" type=\"System.Net.Configuration.MailSettingsSectionGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\"&gt;\n &lt;section name=\"smtp\" type=\"System.Net.Configuration.SmtpSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" /&gt;\n &lt;/sectionGroup&gt;\n&lt;/sectionGroup&gt;\n</code></pre>\n\n<p>I'm not sure the web application itself will run correctly after that, but you can access the sectionGroups correctly.</p>\n\n<p>The second solution it is instead to open your web.config as an EXE configuration, which is probably closer to its intended function anyway:</p>\n\n<pre><code>ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = strConfigPath };\nConfiguration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);\nMailSettingsSectionGroup thisMail = configuration.GetSectionGroup(\"system.net/mailSettings\") as MailSettingsSectionGroup; // returns valid object!\n</code></pre>\n\n<p>I daresay none of the answers provided here, neither mine or Ishmaeel's, are quite using these functions how the .NET designers intended. But, this seems to work for me.</p>\n" }, { "answer_id": 4157995, "author": "Iftikhar Ali", "author_id": 504911, "author_profile": "https://Stackoverflow.com/users/504911", "pm_score": 2, "selected": false, "text": "<p>I provided the configuration values to word hosted .nET Compoent as follows.</p>\n\n<p>A .NET Class Library component being called/hosted in MS Word. To provide configuration values to my component, I created winword.exe.config in C:\\Program Files\\Microsoft Office\\OFFICE11 folder. You should be able to read configurations values like You do in Traditional .NET.</p>\n\n<pre><code>string sMsg = System.Configuration.ConfigurationManager.AppSettings[\"WSURL\"];\n</code></pre>\n" }, { "answer_id": 14246260, "author": "Roi Shabtai", "author_id": 739558, "author_profile": "https://Stackoverflow.com/users/739558", "pm_score": 6, "selected": false, "text": "<p>Another solution is to override the default environment configuration file path.</p>\n<p>I find it the best solution for the of non-trivial-path configuration file load, specifically the best way to attach configuration file to dll.</p>\n<pre><code>AppDomain.CurrentDomain.SetData(&quot;APP_CONFIG_FILE&quot;, &lt;Full_Path_To_The_Configuration_File&gt;);\n</code></pre>\n<p>Example:</p>\n<pre><code>AppDomain.CurrentDomain.SetData(&quot;APP_CONFIG_FILE&quot;, @&quot;C:\\Shared\\app.config&quot;);\n</code></pre>\n<p>More details may be found at <a href=\"http://web.archive.org/web/20161222190702/http://www.testautomationguy.com/2013/01/override-default-application-config.html\" rel=\"nofollow noreferrer\">this blog</a>.</p>\n<p>Additionally, <a href=\"https://stackoverflow.com/a/6151688/503826\">this other answer</a> has an excellent solution, complete with code to refresh\nthe app config and an <code>IDisposable</code> object to reset it back to it's original state. With this\nsolution, you can keep the temporary app config scoped:</p>\n<pre><code>using(AppConfig.Change(tempFileName))\n{\n // tempFileName is used for the app config during this context\n}\n</code></pre>\n" }, { "answer_id": 24745637, "author": "Javier Cañon", "author_id": 3838468, "author_profile": "https://Stackoverflow.com/users/3838468", "pm_score": 1, "selected": false, "text": "<p>For ASP.NET use WebConfigurationManager:</p>\n\n<pre><code>var config = WebConfigurationManager.OpenWebConfiguration(\"~/Sites/\" + requestDomain + \"/\");\n(..)\nconfig.AppSettings.Settings[\"xxxx\"].Value;\n</code></pre>\n" }, { "answer_id": 35280447, "author": "JoelFan", "author_id": 16012, "author_profile": "https://Stackoverflow.com/users/16012", "pm_score": 0, "selected": false, "text": "<p>Use XML processing:</p>\n\n<pre><code>var appPath = AppDomain.CurrentDomain.BaseDirectory;\nvar configPath = Path.Combine(appPath, baseFileName);;\nvar root = XElement.Load(configPath);\n\n// can call root.Elements(...)\n</code></pre>\n" }, { "answer_id": 51765082, "author": "gatsby", "author_id": 5775048, "author_profile": "https://Stackoverflow.com/users/5775048", "pm_score": 1, "selected": false, "text": "<p>This should do the trick :</p>\n\n<pre><code>AppDomain.CurrentDomain.SetData(\"APP_CONFIG_FILE\", \"newAppConfig.config);\n</code></pre>\n\n<p>Source : <a href=\"https://www.codeproject.com/Articles/616065/Why-Where-and-How-of-NET-Configuration-Files\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Articles/616065/Why-Where-and-How-of-NET-Configuration-Files</a></p>\n" }, { "answer_id": 55241920, "author": "Jacob", "author_id": 665783, "author_profile": "https://Stackoverflow.com/users/665783", "pm_score": 4, "selected": false, "text": "<p><strong>The accepted answer is wrong!!</strong></p>\n\n<p>It throws the following exception on accessing the AppSettings property:</p>\n\n<blockquote>\n <p>Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'.</p>\n</blockquote>\n\n<p><strong>Here is the correct solution:</strong></p>\n\n<pre><code>System.Configuration.ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();\nfileMap.ExeConfigFilename = \"YourFilePath\";\nSystem.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);\n</code></pre>\n" } ]
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 to get rid of it.</p>\n\n<p>The command is:</p>\n\n<pre><code>stsadm.exe -o deletessp -title &lt;sspname&gt; [-deletedatabases]\n</code></pre>\n\n<p>The <code>deletedatbases</code> switch is optional.</p>\n\n<hr>\n\n<p>Also, check in Central Administration under Job Definitions and Job Schedules to ensure no SSP related jobs are still running</p>\n" }, { "answer_id": 7109, "author": "Daniel McPherson", "author_id": 897, "author_profile": "https://Stackoverflow.com/users/897", "pm_score": 2, "selected": false, "text": "<p>I suspect these are related to the SQL Server Agent trying to login to a database that no longer exists. </p>\n\n<p>To clear it up you need to:\n 1. Go to SQL Server Management Studio\n 2. Disable the job called <code>&lt;database name&gt;_job_deleteExpiredSessions</code></p>\n\n<p>If that works, then you should be all clear to delete it.</p>\n" }, { "answer_id": 97256, "author": "Aidenn", "author_id": 15346, "author_profile": "https://Stackoverflow.com/users/15346", "pm_score": 4, "selected": true, "text": "<p>As Daniel McPherson said, this is caused when SSPs are deleted but the associated \njob are not and attempt to communicate with the deleted database.<br><br>If the SSP \ndatabase has been deleted or a problem occurred when deleting an SSP, the job may \nnot be deleted. When the job attempts to run, it will fail since the database no \nlonger exists.</p>\n\n<p>Follow the steps Daniel mentioned:<br>\n1. Go to SQL Server Management Studio <br>\n2. Disable the job called SSPNAME_JobDeleteExpiredSessions, right click and choose Disable Job.</p>\n" } ]
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.WriteLine(address.ToString());\n}\n</code></pre>\n" }, { "answer_id": 4823, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 1, "selected": false, "text": "<p>Try using the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.net.dns\" rel=\"nofollow noreferrer\">System.Net.Dns</a> class</p>\n" } ]
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/clibrary/cstring/strchr.html\" rel=\"nofollow noreferrer\">See here</a></p>\n" }, { "answer_id": 4832, "author": "Bill", "author_id": 102, "author_profile": "https://Stackoverflow.com/users/102", "pm_score": 5, "selected": false, "text": "<p><code>strstr</code> returns a pointer to the found character, so you could use pointer arithmetic: (Note: this code not tested for its ability to compile, it's one step away from pseudocode.)</p>\n\n<pre><code>char * source = \"test string\"; /* assume source address is */\n /* 0x10 for example */\nchar * found = strstr( source, \"in\" ); /* should return 0x18 */\nif (found != NULL) /* strstr returns NULL if item not found */\n{\n int index = found - source; /* index is 8 */\n /* source[8] gets you \"i\" */\n}\n</code></pre>\n" }, { "answer_id": 4833, "author": "Michal Sznajder", "author_id": 501, "author_profile": "https://Stackoverflow.com/users/501", "pm_score": 4, "selected": false, "text": "<p>EDIT: strchr is better only for one char. \nPointer aritmetics says \"Hellow!\":</p>\n\n<pre><code>char *pos = strchr (myString, '#');\nint pos = pos ? pos - myString : -1;\n</code></pre>\n\n<p><strong>Important:</strong> strchr () returns NULL if no string is found</p>\n" }, { "answer_id": 4834, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 2, "selected": false, "text": "<p>You can use strstr to accomplish what you want. Example:</p>\n\n<pre><code>char *a = \"Hello World!\";\nchar *b = strstr(a, \"World\");\n\nint position = b - a;\n\nprintf(\"the offset is %i\\n\", position);\n</code></pre>\n\n<p>This produces the result:</p>\n\n<pre><code>the offset is 6\n</code></pre>\n" }, { "answer_id": 4838, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 5, "selected": true, "text": "<p>I think that</p>\n\n<blockquote>\n <p>size_t strcspn ( const char * str1, const char * str2 );</p>\n</blockquote>\n\n<p>is what you want. Here is an example pulled from <a href=\"http://www.cplusplus.com/reference/clibrary/cstring/strcspn.html\" rel=\"noreferrer\">here</a>:</p>\n\n<pre><code>/* strcspn example */\n#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n\nint main ()\n{\n char str[] = \"fcba73\";\n char keys[] = \"1234567890\";\n int i;\n i = strcspn (str,keys);\n printf (\"The first number in str is at position %d.\\n\",i+1);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 35494788, "author": "fnisi", "author_id": 1884351, "author_profile": "https://Stackoverflow.com/users/1884351", "pm_score": 0, "selected": false, "text": "<p>Write your own :)</p>\n\n<p>Code from a BSD licensed string processing library for C, called <a href=\"https://github.com/fnoyanisi/zString\" rel=\"nofollow\">zString</a></p>\n\n<p><a href=\"https://github.com/fnoyanisi/zString\" rel=\"nofollow\">https://github.com/fnoyanisi/zString</a></p>\n\n<pre><code>int zstring_search_chr(char *token,char s){\n if (!token || s=='\\0')\n return 0;\n\n for (;*token; token++)\n if (*token == s)\n return 1;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 48264846, "author": "snack0verflow", "author_id": 9004745, "author_profile": "https://Stackoverflow.com/users/9004745", "pm_score": 0, "selected": false, "text": "<p>You can write </p>\n\n<pre><code>s=\"bvbrburbhlkvp\";\nint index=strstr(&amp;s,\"h\")-&amp;s;\n</code></pre>\n\n<p>to find the index of <code>'h'</code> in the given garble.</p>\n" } ]
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 it needs a little work.</p>\n\n<p>I just tested this in Eclipse 3.3.2</p>\n\n<pre><code>function test(){\n\n}\n\nte&lt;CTRL+SPACE&gt;\n</code></pre>\n\n<p>and it completed the method for me as did this:</p>\n\n<pre><code>var test = function(){\n\n};\n\n\nte&lt;CTRL+SPACE&gt;\n</code></pre>\n\n<p>Can you expand on what more you wanted it to do?</p>\n" }, { "answer_id": 4877, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 3, "selected": true, "text": "<p>I think the JavaScript and CSS need to be in separate files for this to work.</p>\n\n<p>Example of CSS autocomplete in Eclipse:</p>\n\n<p>Starting to type <code>border</code></p>\n\n<blockquote>\n <p><img src=\"https://i.stack.imgur.com/h4Sj9.png\" alt=\"css example in eclipse\"></p>\n</blockquote>\n\n<p>Then setting thickness</p>\n\n<blockquote>\n <p><img src=\"https://i.stack.imgur.com/mmaEe.png\" alt=\"autocompleting border thickness\"></p>\n</blockquote>\n\n<p>Then choosing the color</p>\n\n<blockquote>\n <p><img src=\"https://i.stack.imgur.com/Up41q.png\" alt=\"autocompleting border color\"></p>\n</blockquote>\n\n<p>Chose red, and it added the ; for me</p>\n\n<blockquote>\n <p><img src=\"https://i.stack.imgur.com/Up41q.png\" alt=\"alt text\"></p>\n</blockquote>\n\n<p>Works pretty good IMHO.</p>\n" } ]
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 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.</p>\n\n<p>You can extract the modifiers and the key pressed by ANDing with appropriate enum values:</p>\n\n<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n bool shiftPressed = (keyData &amp; Keys.Shift) != 0;\n Keys unmodifiedKey = (keyData &amp; Keys.KeyCode);\n\n // rest of code goes here\n}\n</code></pre>\n" }, { "answer_id": 2033811, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 3, "selected": false, "text": "<p>I upvoted <a href=\"https://stackoverflow.com/questions/4850/c-and-arrow-keys/5026#5026\">Tokabi's answer</a>, but for comparing keys there is some additional advice on <a href=\"https://stackoverflow.com/questions/1369312/c-keys-enumeration-confused-keys-alt-or-keys-rbutton-keys-shiftkey-keys-alt/2033796#2033796\">StackOverflow.com here</a>. Here are some functions which I used to help simplify everything.</p>\n\n<pre><code> public Keys UnmodifiedKey(Keys key)\n {\n return key &amp; Keys.KeyCode;\n }\n\n public bool KeyPressed(Keys key, Keys test)\n {\n return UnmodifiedKey(key) == test;\n }\n\n public bool ModifierKeyPressed(Keys key, Keys test)\n {\n return (key &amp; test) == test;\n }\n\n public bool ControlPressed(Keys key)\n {\n return ModifierKeyPressed(key, Keys.Control);\n }\n\n public bool AltPressed(Keys key)\n {\n return ModifierKeyPressed(key, Keys.Alt);\n }\n\n public bool ShiftPressed(Keys key)\n {\n return ModifierKeyPressed(key, Keys.Shift);\n }\n\n protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n {\n if (KeyPressed(keyData, Keys.Left) &amp;&amp; AltPressed(keyData))\n {\n int n = code.Text.IndexOfPrev('&lt;', code.SelectionStart);\n if (n &lt; 0) return false;\n if (ShiftPressed(keyData))\n {\n code.ExpandSelectionLeftTo(n);\n }\n else\n {\n code.SelectionStart = n;\n code.SelectionLength = 0;\n }\n return true;\n }\n else if (KeyPressed(keyData, Keys.Right) &amp;&amp; AltPressed(keyData))\n {\n if (ShiftPressed(keyData))\n {\n int n = code.Text.IndexOf('&gt;', code.SelectionEnd() + 1);\n if (n &lt; 0) return false;\n code.ExpandSelectionRightTo(n + 1);\n }\n else\n {\n int n = code.Text.IndexOf('&lt;', code.SelectionStart + 1);\n if (n &lt; 0) return false;\n code.SelectionStart = n;\n code.SelectionLength = 0;\n }\n return true;\n }\n return base.ProcessCmdKey(ref msg, keyData);\n }\n</code></pre>\n" } ]
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 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.</p>\n\n<p>You can extract the modifiers and the key pressed by ANDing with appropriate enum values:</p>\n\n<pre><code>protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n{\n bool shiftPressed = (keyData &amp; Keys.Shift) != 0;\n Keys unmodifiedKey = (keyData &amp; Keys.KeyCode);\n\n // rest of code goes here\n}\n</code></pre>\n" }, { "answer_id": 2033811, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 3, "selected": false, "text": "<p>I upvoted <a href=\"https://stackoverflow.com/questions/4850/c-and-arrow-keys/5026#5026\">Tokabi's answer</a>, but for comparing keys there is some additional advice on <a href=\"https://stackoverflow.com/questions/1369312/c-keys-enumeration-confused-keys-alt-or-keys-rbutton-keys-shiftkey-keys-alt/2033796#2033796\">StackOverflow.com here</a>. Here are some functions which I used to help simplify everything.</p>\n\n<pre><code> public Keys UnmodifiedKey(Keys key)\n {\n return key &amp; Keys.KeyCode;\n }\n\n public bool KeyPressed(Keys key, Keys test)\n {\n return UnmodifiedKey(key) == test;\n }\n\n public bool ModifierKeyPressed(Keys key, Keys test)\n {\n return (key &amp; test) == test;\n }\n\n public bool ControlPressed(Keys key)\n {\n return ModifierKeyPressed(key, Keys.Control);\n }\n\n public bool AltPressed(Keys key)\n {\n return ModifierKeyPressed(key, Keys.Alt);\n }\n\n public bool ShiftPressed(Keys key)\n {\n return ModifierKeyPressed(key, Keys.Shift);\n }\n\n protected override bool ProcessCmdKey(ref Message msg, Keys keyData)\n {\n if (KeyPressed(keyData, Keys.Left) &amp;&amp; AltPressed(keyData))\n {\n int n = code.Text.IndexOfPrev('&lt;', code.SelectionStart);\n if (n &lt; 0) return false;\n if (ShiftPressed(keyData))\n {\n code.ExpandSelectionLeftTo(n);\n }\n else\n {\n code.SelectionStart = n;\n code.SelectionLength = 0;\n }\n return true;\n }\n else if (KeyPressed(keyData, Keys.Right) &amp;&amp; AltPressed(keyData))\n {\n if (ShiftPressed(keyData))\n {\n int n = code.Text.IndexOf('&gt;', code.SelectionEnd() + 1);\n if (n &lt; 0) return false;\n code.ExpandSelectionRightTo(n + 1);\n }\n else\n {\n int n = code.Text.IndexOf('&lt;', code.SelectionStart + 1);\n if (n &lt; 0) return false;\n code.SelectionStart = n;\n code.SelectionLength = 0;\n }\n return true;\n }\n return base.ProcessCmdKey(ref msg, keyData);\n }\n</code></pre>\n" } ]
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 to be \"lazy,\" and stop as soon as they have enough to match, rather than checking if the rest of the input matches.</p>\n\n<p>I'm not entirely happy with this answer though, because this mostly applies to question marks after * or +. If I were more familiar with the input, it might make more sense to me.</p>\n\n<p>(Also, for the code formatting, you can select all of your code and press <kbd>Ctrl</kbd>+<kbd>K</kbd> to have it add the four spaces required.)</p>\n" }, { "answer_id": 4915, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 2, "selected": false, "text": "<p>The reason why #1 is slower is that [\\d;]+ is a greedy quantifier. Using +? or *? is going to do lazy quantifing. See <a href=\"http://msdn.microsoft.com/en-us/library/3206d374(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN - Quantifiers</a> for more info.</p>\n\n<p>You may want to try:</p>\n\n<pre><code>\"(\\e\\[(\\d{1,2};)*?[mz]?)?\"\n</code></pre>\n\n<p>That may be faster for you.</p>\n" }, { "answer_id": 52980, "author": "Oskar", "author_id": 5472, "author_profile": "https://Stackoverflow.com/users/5472", "pm_score": 2, "selected": false, "text": "<p>Do you really want to do run the regexp twice? Without having checked (bad me) I would have thought that this would work well:</p>\n\n<pre><code>public static string StripStringFormating(string formattedString)\n{ \n return rTest.Replace(formattedString, string.Empty);\n}\n</code></pre>\n\n<p>If it does, you should see it run ~twice as fast...</p>\n" }, { "answer_id": 84532, "author": "Doug Moore", "author_id": 13179, "author_profile": "https://Stackoverflow.com/users/13179", "pm_score": 1, "selected": false, "text": "<p>I'm not sure if this will help with what you are working on, but long ago I wrote a regular expression to parse ANSI graphic files.</p>\n\n<pre><code>(?s)(?:\\e\\[(?:(\\d+);?)*([A-Za-z])(.*?))(?=\\e\\[|\\z)\n</code></pre>\n\n<p>It will return each code and the text associated with it.</p>\n\n<p>Input string:</p>\n\n<pre><code>&lt;ESC&gt;[1;32mThis is bright green.&lt;ESC&gt;[0m This is the default color.\n</code></pre>\n\n<p>Results:</p>\n\n<pre><code>[ [1, 32], m, This is bright green.]\n[0, m, This is the default color.]\n</code></pre>\n" } ]
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 items in the current dropdown list. You'd also need a reference to the currently active/selected item. </p>\n\n<p>Each time <code>keyup</code> or <code>keydown</code> is fired, update the reference to the active/selected item in the data structure. To provide highlighting information on the UI, add or remove a class name that is styled via CSS based on if the item is active/selected or not.</p>\n\n<p>Also, this isn't a biggy, but <code>innerHTML</code> is not really standard (look into <code>createTextNode()</code>, <code>createElement()</code>, and <code>appendChild()</code> for standard ways of creating data). You may also want to see about attaching event handlers in the JavaScript rather than doing so in an HTML attribute.</p>\n" }, { "answer_id": 13918, "author": "Walter Rumsby", "author_id": 1654, "author_profile": "https://Stackoverflow.com/users/1654", "pm_score": 4, "selected": true, "text": "<p>What you need to do is attach event listeners to the <code>div</code> with <code>id=\"results\"</code>. You can do this by adding <code>onkeyup</code>, <code>onkeydown</code>, etc. attributes to the <code>div</code> when you create it or you can attach these using JavaScript.</p>\n\n<p>My recommendation would be that you use an AJAX library like <a href=\"http://developer.yahoo.com/yui/\" rel=\"noreferrer\">YUI</a>, <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a>, <a href=\"http://www.prototypejs.org/\" rel=\"noreferrer\">Prototype</a>, etc. for two reasons:</p>\n\n<ol>\n<li>It sounds like you are trying to create an <a href=\"http://developer.yahoo.com/ypatterns/pattern.php?pattern=autocomplete\" rel=\"noreferrer\">Auto Complete</a> control which is something most AJAX libaries should provide. If you can use an existing component you'll save yourself a lot of time.</li>\n<li>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.</li>\n</ol>\n\n<p><a href=\"http://www.dustindiaz.com/yahoo-event-utility/\" rel=\"noreferrer\">Forget addEvent, use Yahoo!’s Event Utility</a> 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. </p>\n\n<p>If that article goes over your head have a look at <a href=\"http://developer.yahoo.com/yui/event/index.html\" rel=\"noreferrer\">this documentation</a> first and then re-read the original article (I found the article made much more sense after I'd used the event library).</p>\n\n<p>A couple of other things:</p>\n\n<ul>\n<li>Using JavaScript gives you much more control than writing <code>onkeyup</code> etc. attributes into your HTML. Unless you want to do something <em>really simple</em> I would use JavaScript.</li>\n<li>If you write your own code to handle keyboard events a <a href=\"http://www.cambiaresearch.com/c4/702b8cd1-e5b0-42e6-83ac-25f0306e3e25/Javascript-Char-Codes-Key-Codes.aspx\" rel=\"noreferrer\">good key code reference</a> is really handy.</li>\n</ul>\n" } ]
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 into a long before it chooses to autobox it to an Integer, so the hello(long) method is chosen to be called.</p>\n\n<p>Edit: <a href=\"https://stackoverflow.com/questions/4242/why-cant-i-call-tostring-on-a-java-primitive#4384\">the original post being referenced</a>.</p>\n\n<p>Further Edit: The reason the second option would print Integer is because there is no \"widening\" into a larger primitive as an option, so it MUST box it up, thus Integer is the only option. Furthermore, java will only autobox to the original type, so it would give a compiler error if you leave the hello(Long) and removed hello(Integer).</p>\n" }, { "answer_id": 5091, "author": "Camilo Díaz Repka", "author_id": 861, "author_profile": "https://Stackoverflow.com/users/861", "pm_score": 5, "selected": true, "text": "<p>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:</p>\n\n<pre><code>public static void main(java.lang.String[]);\n Code:\n 0: iconst_ 5\n 1: istore_ 1\n 2: iload_ 1\n 3: i2l\n 4: invokestatic #6; //Method hello:(J)V\n 7: return\n\n}\n</code></pre>\n\n<p>Clearly, you see the I2L, which is the mnemonic for the widening Integer-To-Long bytecode instruction. See reference <a href=\"http://java.sun.com/docs/books/jvms/second_edition/html/Instructions2.doc6.html\" rel=\"noreferrer\">here</a>.</p>\n\n<p>And in the other case, replacing the \"long x\" with the object \"Long x\" signature, you'll have this code in the main method:</p>\n\n<pre><code>public static void main(java.lang.String[]);\n Code:\n 0: iconst_ 5\n 1: istore_ 1\n 2: iload_ 1\n 3: invokestatic #6; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;\n 6: invokestatic #7; //Method hello:(Ljava/lang/Integer;)V\n 9: return\n\n}\n</code></pre>\n\n<p>So you see the compiler has created the instruction Integer.valueOf(int), to box the primitive inside the wrapper.</p>\n" }, { "answer_id": 5164, "author": "dlinsin", "author_id": 198, "author_profile": "https://Stackoverflow.com/users/198", "pm_score": 2, "selected": false, "text": "<p>Another interesting thing with this example is the method overloading. The combination of type widening and method overloading only working because the compiler has to make a decision of which method to choose. Consider the following example:</p>\n\n<pre><code>public static void hello(Collection x){\n System.out.println(\"Collection\");\n}\n\npublic static void hello(List x){\n System.out.println(\"List\");\n}\n\npublic static void main(String[] args){\n Collection col = new ArrayList();\n hello(col);\n}\n</code></pre>\n\n<p>It doesn't use the run-time type which is List, it uses the compile-time type which is Collection and thus prints \"Collection\". </p>\n\n<p>I encourage your to read <a href=\"http://books.google.com/books?id=ZZOiqZQIbRMC\" rel=\"nofollow noreferrer\">Effective Java</a>, which opened my eyes to some corner cases of the JLS.</p>\n" } ]
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. You can think of regular expressions as wildcards on steroids. You are probably familiar with wildcard notations such as <code>*.txt</code> to find all text files in a file manager. The regex equivalent is <code>.*\\.txt$</code>.</p>\n</blockquote>\n\n<p>A great resource for regular expressions: <a href=\"http://www.regular-expressions.info\" rel=\"nofollow noreferrer\">http://www.regular-expressions.info</a></p>\n" }, { "answer_id": 4962, "author": "Teifion", "author_id": 1384652, "author_profile": "https://Stackoverflow.com/users/1384652", "pm_score": 3, "selected": false, "text": "<p>Regular Expressions (or Regex) are used to pattern match in strings. You can thus pull out all email addresses from a piece of text because it follows a specific pattern.</p>\n\n<p>In some cases regular expressions are enclosed in forward-slashes and after the second slash are placed options such as case-insensitivity. Here's a good one :)</p>\n\n<pre><code>/(bb|[^b]{2})/i\n</code></pre>\n\n<p>Spoken it can read \"2 be or not 2 be\".</p>\n\n<p>The first part are the (brackets), they are split by the pipe | character which equates to an or statement so (a|b) matches \"a\" or \"b\". The first half of the piped area matches \"bb\". The second half's name I don't know but it's the square brackets, they match anything that is <strong>not</strong> \"b\", that's why there is a roof symbol thingie (technical term) there. The squiggly brackets match a count of the things before them, in this case two characters that are not \"b\".</p>\n\n<p>After the second / is an \"i\" which makes it case insensitive. Use of the start and end slashes is environment specific, sometimes you do and sometimes you do not.</p>\n\n<p>Two links that I think you will find handy for this are</p>\n\n<ol>\n<li><a href=\"http://www.regular-expressions.info/\" rel=\"noreferrer\">regular-expressions.info</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Regular_expression\" rel=\"noreferrer\">Wikipedia - Regular expression</a></li>\n</ol>\n" }, { "answer_id": 4972, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 4, "selected": true, "text": "<p>Consider an example in Ruby:</p>\n\n<pre><code>puts \"Matched!\" unless /\\d{3}-\\d{4}/.match(\"555-1234\").nil?\nputs \"Didn't match!\" if /\\d{3}-\\d{4}/.match(\"Not phone number\").nil?\n</code></pre>\n\n<p>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.</p>\n\n<p>Furthermore, using groups you can extract information, as such:</p>\n\n<pre><code>match = /([^@]*)@(.*)/.match(\"[email protected]\")\nname = match[1]\ndomain = match[2]\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 4982, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 0, "selected": false, "text": "<p>If you're just starting out with regular expressions, I heartily recommend a tool like The Regex Coach:</p>\n\n<p><a href=\"http://www.weitz.de/regex-coach/\" rel=\"nofollow noreferrer\">http://www.weitz.de/regex-coach/</a></p>\n\n<p>also heard good things about RegexBuddy:</p>\n\n<p><a href=\"http://www.regexbuddy.com/\" rel=\"nofollow noreferrer\">http://www.regexbuddy.com/</a></p>\n" }, { "answer_id": 15397, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 0, "selected": false, "text": "<p>As you may know, Oracle now has regular expressions: <a href=\"http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html\" rel=\"nofollow noreferrer\">http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/rischert_regexp_pt1.html</a>. I have used the new functionality in a few queries, but it hasn't been as useful as in other contexts. The reason, I believe, is that regular expressions are best suited for finding structured data buried within unstructured data.</p>\n\n<p>For instance, I might use a regex to find Oracle messages that are stuffed in log file. It isn't possible to know where the messages are--only what they look like. So a regex is the best solution to that problem. When you work with a relational database, the data is usually pre-structured, so a regex doesn't shine in that context.</p>\n" }, { "answer_id": 15401, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>If you want to learn about regular expressions, I recommend <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596528124\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Mastering Regular Expressions</a>. It goes all the way from the very basic concepts, all the way up to talking about how different engines work underneath. The last 4 chapters also gives a dedicated chapter to each of PHP, .Net, Perl, and Java. I learned a lot from it, and still use it as a reference. </p>\n" }, { "answer_id": 25850, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>Coolest regular expression <em>ever</em>:</p>\n\n<pre><code>/^1?$|^(11+?)\\1+$/\n</code></pre>\n\n<p>It tests if a number is prime. And it works!!</p>\n\n<p>N.B.: to make it work, a bit of set-up is needed; the number that we want to test has to be converted into a string of “<code>1</code>”s first, <em>then</em> we can apply the expression to test if the string does <em>not</em> contain a prime number of “<code>1</code>”s:</p>\n\n<pre><code>def is_prime(n)\n str = \"1\" * n\n return str !~ /^1?$|^(11+?)\\1+$/ \nend\n</code></pre>\n\n<p>There’s a detailled and very approachable explanation over at <a href=\"http://www.noulakaz.net/weblog/2007/03/18/a-regular-expression-to-check-for-prime-numbers/\" rel=\"nofollow noreferrer\">Avinash Meetoo’s blog</a>.</p>\n" }, { "answer_id": 25889, "author": "Onorio Catenacci", "author_id": 2820, "author_profile": "https://Stackoverflow.com/users/2820", "pm_score": 0, "selected": false, "text": "<p>These RE's are specific to Visual Studio and C++ but I've found them helpful at times:</p>\n\n<p>Find all occurrences of \"routineName\" with non-default params passed: </p>\n\n<p><em>routineName\\(:a+\\)</em></p>\n\n<p>Conversely to find all occurrences of \"routineName\" with only defaults:\n <em>routineName\\(\\)</em></p>\n\n<p>To find code enabled (or disabled) in a debug build:</p>\n\n<p><em>\\#if.</em>_DEBUG*</p>\n\n<p>Note that this will catch all the variants: ifdef, if defined, ifndef, if !defined</p>\n" }, { "answer_id": 1437610, "author": "Philippe Leybaert", "author_id": 113570, "author_profile": "https://Stackoverflow.com/users/113570", "pm_score": 0, "selected": false, "text": "<p><strong>Validating strong passwords</strong>:</p>\n\n<p>This one will validate a password with a length of 5 to 10 alphanumerical characters, with at least one upper case, one lower case and one digit:</p>\n\n<pre><code>^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])[a-zA-Z0-9]{5,10}$\n</code></pre>\n" } ]
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("[email protected]") 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>\n\n<p>I had the nav section \"float: right\" and the main body of the page has a background image about 250px across aligned to the right and \"repeat-y\". I then added something with \"clear: both\" to it. Here is the W3Schools and the <a href=\"http://www.w3schools.com/Css/pr_class_clear.asp\" rel=\"nofollow noreferrer\">CSS clear property</a>.</p>\n\n<p>I placed the clear at the bottom of the \"page\" classed div. My page source looks something like this.</p>\n\n<pre><code>body\n -&gt; header (big blue banner)\n -&gt; headerNav (green bar at the top)\n -&gt; breadcrumbs (invisible at the moment)\n -&gt; page\n -&gt; navigation (floats to the right)\n -&gt; content (main content)\n -&gt; clear (the quote at the bottom)\n -&gt; footerNav (the green bar at the bottom)\n -&gt; clear (empty but still does something)\n -&gt; footer (blue thing at the bottom)\n</code></pre>\n\n<p>I hope that helps :)</p>\n" }, { "answer_id": 4983, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 0, "selected": false, "text": "<p>Just trying to help out here so the code is more readable.<br>\nRemember that you can insert code snippets by clicking on the button at the top with \"101010\". Just enter your code then highlight it and click the button.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>&lt;html&gt;\n &lt;body&gt;\n &lt;style type=\"text/css\"&gt;\n .rightfloat {\n color: red;\n background-color: #BBBBBB;\n float: right;\n width: 200px;\n }\n\n .left {\n font-size: 20pt;\n }\n\n .separator {\n clear: both;\n width: 100%;\n border-top: 1px solid black;\n }\n &lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 5019, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 3, "selected": false, "text": "<p>Give this a try:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body,\r\n#left, #right {\r\n height: 100%\r\n}\r\n\r\n#left {\r\n float: left;\r\n width: 25%;\r\n}\r\n#right {\r\n width: 75%;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;html&gt;\r\n &lt;body&gt;\r\n &lt;div id=\"left\"&gt;\r\n Content\r\n &lt;/div&gt;\r\n &lt;div id=\"right\"&gt;\r\n Content\r\n &lt;/div&gt;\r\n &lt;/body&gt;\r\n&lt;/html&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 5028, "author": "Rich Reuter", "author_id": 283, "author_profile": "https://Stackoverflow.com/users/283", "pm_score": 2, "selected": false, "text": "<p>Here's an example of equal-height columns - <a href=\"http://positioniseverything.net/articles/onetruelayout/equalheight\" rel=\"nofollow noreferrer\">Equal Height Columns - revisited</a></p>\n\n<p>You can also check out the idea of \"Faux Columns\" as well - <a href=\"http://www.alistapart.com/articles/fauxcolumns/\" rel=\"nofollow noreferrer\">Faux Columns</a></p>\n\n<p>Don't go the table route. If it's not tabular data, don't treat it as such. It's bad for accessibility and flexibility.</p>\n" }, { "answer_id": 5035, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>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.</p>\n" }, { "answer_id": 5096, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 0, "selected": false, "text": "<p>A 2 column layout is a little bit tough to get working in CSS (at least until CSS3 is practical.)</p>\n\n<p>Floating left and right will work to a point, but it won't allow you to extend the background. To make backgrounds stay solid, you'll have to implement a technique known as \"faux columns,\" which basically means your columns themselves won't have a background image. Your 2 columns will be contained inside of a parent tag. This parent tag is given a background image that contains the 2 column colors you want. Make this background only as big as you need it to (if it is a solid color, only make it 1 pixel high) and have it repeat-y. AListApart has a great walkthrough on what is needed to make it work.</p>\n\n<p><a href=\"http://www.alistapart.com/articles/fauxcolumns/\" rel=\"nofollow noreferrer\">http://www.alistapart.com/articles/fauxcolumns/</a></p>\n" }, { "answer_id": 5103, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 6, "selected": true, "text": "<p>Ahem...</p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n\n<p>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 <code>div</code>, 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\".</p>\n" }, { "answer_id": 5617, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 0, "selected": false, "text": "<p>I can think of 2 options</p>\n\n<ol>\n<li>Use javascript to resize the smaller column on page load.</li>\n<li>Fake the equal heights by setting the <code>background-color</code> for the column on the container <code>&lt;div/&gt;</code> instead (<code>&lt;div class=\"separator\"/&gt;</code>) with <code>repeat-y</code></li>\n</ol>\n" }, { "answer_id": 1029876, "author": "mxmissile", "author_id": 9604, "author_profile": "https://Stackoverflow.com/users/9604", "pm_score": 3, "selected": false, "text": "<p>I gave up on strictly CSS and used a little jquery:</p>\n\n<pre><code>var leftcol = $(\"#leftcolumn\");\nvar rightcol = $(\"#rightcolumn\");\nvar leftcol_height = leftcol.height();\nvar rightcol_height = rightcol.height();\n\nif (leftcol_height &gt; rightcol_height)\n rightcol.height(leftcol_height);\nelse\n leftcol.height(rightcol_height);\n</code></pre>\n" }, { "answer_id": 1030017, "author": "georgebrock", "author_id": 5168, "author_profile": "https://Stackoverflow.com/users/5168", "pm_score": 3, "selected": false, "text": "<p>Some browsers support CSS tables, so you could create this kind of layout using the various CSS <code>display: table-*</code> values. There's more information on CSS tables in this article (and the book of the same name) by Rachel Andrew: <a href=\"http://www.digital-web.com/articles/everything_you_know_about_CSS_Is_wrong/\" rel=\"nofollow noreferrer\">Everything You Know About CSS is Wrong</a></p>\n\n<p>If you need a consistent layout in older browsers that don't support CSS tables, you need to do two things:</p>\n\n<ol>\n<li><p><em>Make your \"table row\" element clear its internal floated elements.</em></p>\n\n<p>The simplest way of doing this is to set <code>overflow: hidden</code> which takes care of most browsers, and <code>zoom: 1</code> to trigger the <code>hasLayout</code> property in older versions of IE.</p>\n\n<p>There are many other ways of clearing floats, if this approach causes undesirable side effects you should check the question <a href=\"https://stackoverflow.com/a/1633170/5168\">which method of 'clearfix' is best</a> and the article <a href=\"http://www.satzansatz.de/cssd/onhavinglayout.html\" rel=\"nofollow noreferrer\">on having layout</a> for other methods.</p></li>\n<li><p><em>Balance the height of the two \"table cell\" elements.</em></p>\n\n<p>There are two ways you could approach this. Either you can create the appearance of equal heights by setting a background image on the \"table row\" element (the <a href=\"http://www.alistapart.com/articles/fauxcolumns/\" rel=\"nofollow noreferrer\">faux columns technique</a>) or you can make the heights of the columns match by giving each a large padding and equally large negative margin.</p>\n\n<p>Faux columns is the simpler approach and works very well when the width of one or both columns is fixed. The other technique copes better with variable width columns (based on percentage or em units) but can cause problems in some browsers if you link directly to content within your columns (e.g. if a column contained <code>&lt;div id=\"foo\"&gt;&lt;/div&gt;</code> and you linked to <code>#foo</code>)</p></li>\n</ol>\n\n<p>Here's an example using the padding/margin technique to balance the height of the columns.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body {\r\n height: 100%;\r\n}\r\n\r\n.row {\r\n zoom: 1; /* Clear internal floats in IE */\r\n overflow: hidden; /* Clear internal floats */\r\n}\r\n\r\n.right-column,\r\n.left-column {\r\n padding-bottom: 1000em; /* Balance the heights of the columns */\r\n margin-bottom: -1000em; /* */\r\n}\r\n\r\n.right-column {\r\n width: 20%;\r\n float: right;\r\n}\r\n\r\n.left-column {\r\n width: 79%;\r\n float: left;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"row\"&gt;\r\n &lt;div class=\"right-column\"&gt;Right column content&lt;/div&gt;\r\n &lt;div class=\"left-column\"&gt;Left column content&lt;/div&gt;\r\n&lt;/div&gt;\r\n&lt;div class=\"row\"&gt;\r\n &lt;div class=\"right-column\"&gt;Right column content&lt;/div&gt;\r\n &lt;div class=\"left-column\"&gt;Left column content&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This Barcamp demo by Natalie Downe may also be useful when figuring out how to add additional columns and nice spacing and padding: <a href=\"http://natbat.net/code/clientside/css/equalColumnsDemo/11.html\" rel=\"nofollow noreferrer\">Equal Height Columns and other tricks</a> (it's also where I first learnt about the margin/padding trick to balance column heights)</p>\n" }, { "answer_id": 15599857, "author": "user2194160", "author_id": 2194160, "author_profile": "https://Stackoverflow.com/users/2194160", "pm_score": 0, "selected": false, "text": "<p>It's enough to just use the css property <code>width</code> to do so.</p>\n\n<p>Here is an example:</p>\n\n<pre><code>&lt;style type=\"text/css\"&gt;;\n td {\n width:25%;\n height:100%;\n float:left;\n }\n&lt;/style&gt;\n</code></pre>\n" }, { "answer_id": 18505213, "author": "Palm Int Srv", "author_id": 2086668, "author_profile": "https://Stackoverflow.com/users/2086668", "pm_score": 0, "selected": false, "text": "<p>This should work for you: Set the height to 100% in your css for the <code>html</code> and <code>body</code> elements. You can then adjust the height to your needs in the <code>div</code>.</p>\n\n<pre><code>html {\n height: 100%;\n}\n\nbody {\n height: 100%;\n}\ndiv {\n height: 100%; /* Set Div Height */\n} \n</code></pre>\n" }, { "answer_id": 44718603, "author": "pragadeesh mahendran", "author_id": 8203775, "author_profile": "https://Stackoverflow.com/users/8203775", "pm_score": 1, "selected": false, "text": "<p>No need to write own css, there is an library called \"Bootstrap css\" by calling that in your HTML head section, we can achieve many stylings,Here is an example:\nIf you want to provide two column in a row, you can simply do the following:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\"&gt;\r\n\r\n&lt;div class=\"row\"&gt;\r\n &lt;div class=\"col-md-6\"&gt;Content&lt;/div&gt;\r\n &lt;div class=\"col-md-6\"&gt;Content&lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Here md stands for medium device,,you can use col-sm-6 for smaller devices and col-xs-6 for extra small devices</p>\n" }, { "answer_id": 56416085, "author": "aspirew", "author_id": 11590170, "author_profile": "https://Stackoverflow.com/users/11590170", "pm_score": 0, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.rightfloat {\r\n color: red;\r\n background-color: #BBBBBB;\r\n float: right;\r\n width: 200px;\r\n}\r\n\r\n.left {\r\n font-size: 20pt;\r\n}\r\n\r\n.separator {\r\n clear: both;\r\n width: 100%;\r\n border-top: 1px solid black;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"separator\"&gt;\r\n &lt;div class=\"rightfloat\"&gt;\r\n Some really short content.\r\n &lt;/div&gt;\r\n &lt;div class=\"left\"&gt; \r\n Some really really really really really really\r\n really really really really big content\r\n &lt;/div&gt;\r\n&lt;/div&gt;\r\n&lt;div class=\"separator\"&gt;\r\n &lt;div class=\"rightfloat\"&gt;\r\n Some more short content.\r\n &lt;/div&gt;\r\n &lt;div class=\"left\"&gt; \r\n Some really really really really really really\r\n really really really really big content\r\n &lt;/div&gt;\r\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
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>\n\n<pre><code>navigateToURL(new URLRequest(File.applicationStorageDirectory.nativePath + \"/courses/\" + fileName));\n</code></pre>\n" }, { "answer_id": 11214, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 0, "selected": false, "text": "<p>Currently adobe is not supporting opening files in there default applications. Passing it off to the browser seems to be the only way to make it work.</p>\n\n<p>You could however use a FileStream and write a small html file with some javascript that sets the location of an iframe to the file, then after 100ms or so calls window.close(). Then open that file in the browser.</p>\n" }, { "answer_id": 1171296, "author": "user106085", "author_id": 106085, "author_profile": "https://Stackoverflow.com/users/106085", "pm_score": 2, "selected": false, "text": "<p>This is the first release of the FluorineFx Aperture framework.</p>\n\n<p>The framework provides native OS integration (Windows only) support for AIR desktop applications.</p>\n\n<p>The framework extends Adobe AIR applications in a non-intrusive way: simply redistribute the provided libraries with your AIR application, at runtime the framework will automatically hook into your application.</p>\n\n<p><strong>Features</strong></p>\n\n<ul>\n<li>Launch native applications and documents with the provided apsystem library</li>\n<li>Take screenshots of the whole screen with the provided apimaging library</li>\n<li>Access Outlook contacts from an Air application with the provided apoutlook library</li>\n</ul>\n\n<p><a href=\"http://aperture.fluorinefx.com/\" rel=\"nofollow noreferrer\">http://aperture.fluorinefx.com/</a></p>\n" }, { "answer_id": 3233338, "author": "Chris", "author_id": 389993, "author_profile": "https://Stackoverflow.com/users/389993", "pm_score": 4, "selected": false, "text": "<p>You can use the new <code>openWithDefaultApplication();</code> function that's available on the File class (I believe it's only available in AIR 2)</p>\n\n<p>eg:</p>\n\n<pre><code>var file:File = File.desktopDirectory.resolvePath(fileLocation);\nfile.openWithDefaultApplication();\n</code></pre>\n" }, { "answer_id": 32225417, "author": "1.21 gigawatts", "author_id": 441016, "author_profile": "https://Stackoverflow.com/users/441016", "pm_score": 0, "selected": false, "text": "<p>For me it's: </p>\n\n<pre><code>var request:URLRequest = new URLRequest();\nrequest.url = file.url;\nnavigateToURL(request, \"_blank\");\n</code></pre>\n\n<p>The <code>navigateToURL(file.nativePath)</code> didn't work since the path, \"/users/mydirectory/...\" was outside the <a href=\"http://help.adobe.com/en_US/AIR/1.5/devappshtml/WS5b3ccc516d4fbf351e63e3d118666ade46-7cba.html\" rel=\"nofollow\">application sandbox</a>. AIR only allows some protocols to be opened with <code>navigateToURL()</code>.</p>\n" } ]
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 place to start: <a href=\"http://www-mrsrl.stanford.edu/~brian/cvstutorial/\" rel=\"nofollow noreferrer\">http://www-mrsrl.stanford.edu/~brian/cvstutorial/</a></p>\n" }, { "answer_id": 5106, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 1, "selected": false, "text": "<p>I think this is what I did back in my CVS days:</p>\n\n<pre><code>find . -type f | xargs cvs add\n</code></pre>\n" }, { "answer_id": 5262, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": true, "text": "<p>Ah, spaces. This will work with spaces:</p>\n\n<pre><code>find . -type f -print0| xargs -0 cvs add\n</code></pre>\n" }, { "answer_id": 5330, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/a/5262/1287812\">Mark's solution</a> resolves the spaces issue, but produces this issue:</p>\n\n<blockquote>\n <p>cvs add: cannot open CVS/Entries for\n reading: No such file or directory <br /> cvs\n [add aborted]: no repository </p>\n</blockquote>\n\n<p>To fix it, the actual command to use is:</p>\n\n<pre><code>find . -type f -exec cvs add {} \\;\n</code></pre>\n" }, { "answer_id": 34893, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 1, "selected": false, "text": "<p>First add all directories to CVS</p>\n\n<pre><code>find . -type d -print0| xargs -0 cvs add\n</code></pre>\n\n<p>Then add all the files in the directories to CVS</p>\n\n<pre><code>find . -type f -print0| xargs -0 cvs add\n</code></pre>\n" }, { "answer_id": 35344, "author": "Alexander L. Belikoff", "author_id": 3514, "author_profile": "https://Stackoverflow.com/users/3514", "pm_score": 2, "selected": false, "text": "<p><code>cvs import</code> is not just for 3rd-party sources. In fact, directories are not versioned by CVS, so they are not a subject to branch policies. As long as you import empty directories, it is fine.</p>\n" }, { "answer_id": 268246, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 2, "selected": false, "text": "<p>Note that you can only use <code>cvs add</code> on files and folders that are located inside an already checked out working copy, otherwise you will get the <a href=\"http://cvsgui.sourceforge.net/newfaq.htm#cvs-add_nodir\" rel=\"nofollow noreferrer\">\"Cannot open CVS/Entries for reading\"</a> message. A technique for creating a new \"root module\" using <code>cvs add</code> is explained in this WinCVS FAQ item: <a href=\"http://cvsgui.sourceforge.net/newfaq.htm#add_rootmodule\" rel=\"nofollow noreferrer\">http://cvsgui.sourceforge.net/newfaq.htm#add_rootmodule</a></p>\n\n<p>If you are on Windows, both TortoiseCVS and WinCVS support recursive addition (and optional commit) of multiple files in a single operation. In WinCvs look for the macro Add>Recursive Add (auto-commit)... In Tortoise use the Add Contents command on a directory. Both will allow you to select which files to add and what keyword expansion modes to use for them (mostly used for defining which files are binary).</p>\n\n<p>For further info about recursive add in WinCvs look here: <a href=\"http://cvsgui.sourceforge.net/newfaq.htm#cvs-add_recursive\" rel=\"nofollow noreferrer\">http://cvsgui.sourceforge.net/newfaq.htm#cvs-add_recursive</a></p>\n\n<hr>\n\n<p>Apart from that <code>cvs import</code> is well suited for mass-additions. However, the way <code>cvs import</code> is implemented in vanilla CVS has two drawbacks (because it <strong>was</strong> originally written for third-party code):</p>\n\n<ul>\n<li>it creates a mandatory branch with special semantics.</li>\n<li>it does not create the repository meta-data (i.e. the hidden CVS directories) needed to establish the imported code as a checked out working copy, which means that in order to actually work with the imported files you first have to check them out of the repository</li>\n</ul>\n\n<p>If you are using CVSNT you can avoid both drawbacks by specifying the <code>-nC</code> option on import. <code>-n</code> is for avoiding the \"vendor\" branch and <code>-C</code> is for creating the CVS directories.</p>\n" }, { "answer_id": 1979749, "author": "doj", "author_id": 240829, "author_profile": "https://Stackoverflow.com/users/240829", "pm_score": 1, "selected": false, "text": "<p>I'm using this simple shell script, which should be started from an already checked-out CVS directory. It will stupidly try to add/commit any files and directories it finds upon its recursive search, so in the end you should end up with a fully commit tree.</p>\n\n<p>Simply save this as something like <code>/usr/bin/cvsadd</code> and don't forget to <code>chmod +x /usr/bin/cvsadd</code>.</p>\n\n<pre>\n#!/bin/sh\n# @(#) add files and directories recursively to the current CVS directory\n# (c) 2009 by Dirk Jagdmann \n\nif [ -z \"$1\" ] ; then\n echo \"usage: cvsadd 'import message'\"\n exit 1\nfi\n\nif [ -d \"$2\" ] ; then\n cvs add \"$2\"\n cd \"$2\" || exit 1\nfi\n\nif [ ! -d CVS ] ; then\n echo \"current directory needs to contain a CVS/ directory\"\n exit 1\nfi\n\nXARGS=\"xargs -0 -r -t -L 1\"\n\n# first add all files in current directory\nfind . -maxdepth 1 -type f -print0 | $XARGS cvs add\nfind . -maxdepth 1 -type f -print0 | $XARGS cvs ci -m \"$1\"\n\n# then add all directories\nfind . -maxdepth 1 -type d -not -name CVS -a -not -name . -print0 | $XARGS \"$0\" \"$1\"\n</pre>\n" }, { "answer_id": 3862101, "author": "phoneynk", "author_id": 466601, "author_profile": "https://Stackoverflow.com/users/466601", "pm_score": 3, "selected": false, "text": "<p>First add all directories to CVS</p>\n\n<pre><code>find . -type d -print0| xargs -0 cvs add\n</code></pre>\n\n<p>Then add all the files in the directories to CVS</p>\n\n<pre><code>find . -type f | grep -v CVS | xargs cvs add\n</code></pre>\n\n<p>Worked for me</p>\n" }, { "answer_id": 5158092, "author": "Tom", "author_id": 639814, "author_profile": "https://Stackoverflow.com/users/639814", "pm_score": 6, "selected": false, "text": "<p>I found this worked pretty effectively:</p>\n\n<p>First, add all the directories, but not any named \"CVS\":</p>\n\n<pre><code>find . -type d \\! -name CVS -exec cvs add '{}' \\;\n</code></pre>\n\n<p>Then add all the files, excluding anything in a CVS directory:</p>\n\n<pre><code>find . \\( -type d -name CVS -prune \\) -o \\( -type f -exec cvs add '{}' \\; \\)\n</code></pre>\n\n<p>Now, if anyone has a cure for the embarrassment of using CVS in this day and age...</p>\n" }, { "answer_id": 17720754, "author": "borrel", "author_id": 423777, "author_profile": "https://Stackoverflow.com/users/423777", "pm_score": 0, "selected": false, "text": "<p>i like to do (as directory's need an add to) </p>\n\n<pre><code>cvs status 2&gt;/dev/null | awk '{if ($1==\"?\")system(\"cvs add \"$2)}'\n</code></pre>\n\n<p>you might need to run this multiple times(first for directory's then for its children) until there is no output</p>\n" }, { "answer_id": 24548144, "author": "Broomerr", "author_id": 2075608, "author_profile": "https://Stackoverflow.com/users/2075608", "pm_score": 1, "selected": false, "text": "<p>Already discussed methods will do recursive lookup, but it will fail if you perform same action again (if you want to add subtree to existed tree)\nFor that reason you need to check that your directories was not added yet and then add only files which not added yet. To do that we use output of <code>cvs up</code> to see which elements was not added yet - its will have question mark at start of line.</p>\n\n<p>We use options <code>-0</code>, <code>-print0</code> and <code>-zZ</code> to be sure that we correctly process spaces in filenames. We also using <code>--no-run-if-empty</code> to avoid run if nothing need to be added.</p>\n\n<pre><code>CVS_PATTERN=/tmp/cvs_pattern\ncvs -z3 -q up | egrep '^\\?.*' | sed -e 's/^? //' &gt; $CVS_PATTERN\nfind . -type d \\! -name CVS -print0 | grep -zZf $CVS_PATTERN | xargs -0 --no-run-if-empty cvs add\nfind . \\( -type d -name CVS -prune \\) -o \\( -type f -print0 \\) | grep -zZf $CVS_PATTERN | xargs -0 --no-run-if-empty cvs add\ncvs commit -m 'commiting tree recursively'\n</code></pre>\n\n<p>With this approach we will avoid such errors:</p>\n\n<pre><code>cvs add: cannot add special file `.'; skipping\ncvs [add aborted]: there is a version in ./dirname1 already\n</code></pre>\n\n<p>and</p>\n\n<pre><code>cvs add: `./dirname2/filename' already exists, with version number 1.1.1.1\n</code></pre>\n" }, { "answer_id": 24798342, "author": "manufosela", "author_id": 1833198, "author_profile": "https://Stackoverflow.com/users/1833198", "pm_score": 4, "selected": false, "text": "<p>I use this:</p>\n\n<p>First add recursively all directories less the CVS ones:</p>\n\n<pre><code>$> find . -type d \\! -name CVS -exec cvs add '{}' \\;</code></pre>\n\n<p>Second add all files, less ones the CVS directories:</p>\n\n<pre> find . \\( -type d -name CVS -prune \\) -o \\( -type f -exec cvs add '{}' \\; \\)</pre>\n\n<p>Third do “commit” recursively like \"first version\" comment:</p>\n\n<pre> find . \\( -type d -name CVS -prune \\) -o \\( -type f -exec cvs commit -m \"first version\" '{}' \\; \\)</pre>\n\n<p>Last tagging all recursively:</p>\n\n<pre> find . \\( -type d -name CVS -prune \\) -o \\( -type f -exec cvs tag -F MY_CVS_TAG '{}' \\; \\)</pre>\n" }, { "answer_id": 37675508, "author": "TGA", "author_id": 4862672, "author_profile": "https://Stackoverflow.com/users/4862672", "pm_score": 2, "selected": false, "text": "<p>This answer from Mark was usefull (find . -type f -print0| xargs -0 cvs add) but I solved some problem that occured when the cvs add try to add his own files like Tag, Entries, ect..</p>\n\n<ol>\n<li>Add your most high level folder called NEW_FOLDER</li>\n</ol>\n\n<pre>cvs add NEW_FOLDER</pre>\n\n<ol start=\"2\">\n<li>Use the previous command with some exclusion to add all sub-folders tree</li>\n</ol>\n\n<blockquote>\n <p>find NEW_FOLDER/ -type d ! -name \"CVS\" -and ! -name \"Tag\" -and ! -name \"Entries.Log\" -and ! -name \"Entries\" -and ! -name \"Repository\" -and ! -name \"Root\" -print0 | xargs -0 cvs add</p>\n</blockquote>\n\n<ol start=\"3\">\n<li>Use the previous command with some exclusion to add all files</li>\n</ol>\n\n<blockquote>\n <p>find NEW_FOLDER/ -type f ! -name \"CVS\" -and ! -name \"Tag\" -and ! -name \"Entries.Log\" -and ! -name \"Entries\" -and ! -name \"Repository\" -and ! -name \"Root\" -print0 | xargs -0 cvs add</p>\n</blockquote>\n" } ]
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 present all the time. You can check the session in Page_Load and add the appropriate stylesheet reference. It sounds like this is a temporary/development situation, so go with whatever is easy and works.</p>\n\n<pre><code>if (!String.IsNullOrEmpty(Request.QueryString[\"css\"]))\n Session.Add(\"CSS\",Request.QueryString[\"css\"]);\n</code></pre>\n" }, { "answer_id": 5160, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 6, "selected": true, "text": "<p>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.</p>\n\n<p>In your aspx file:</p>\n\n<pre><code>&lt;head&gt;\n &lt;link id=\"linkStyles\" rel=\"stylesheet\" type=\"text/css\" runat=\"server\" /&gt;\n&lt;/head&gt;\n</code></pre>\n\n<p>And in the Code behind:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e) {\n string stylesheetAddress = // logic to determine stylesheet\n linkStyles.Href = stylesheetAddress;\n}\n</code></pre>\n" }, { "answer_id": 5161, "author": "Shawn", "author_id": 26, "author_profile": "https://Stackoverflow.com/users/26", "pm_score": 3, "selected": false, "text": "<p>You should look into <code>ASP.NET</code> themes, that's exactly what they're used for. They also allow you to skin controls, which means give them a set of default attributes.</p>\n" }, { "answer_id": 5162, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": -1, "selected": false, "text": "<p>I would do the following:</p>\n\n<p><a href=\"http://www.website.com/?stylesheet=new.css\" rel=\"nofollow noreferrer\">www.website.com/?stylesheet=new.css</a></p>\n\n<p>Then in your ASP.NET code:</p>\n\n<pre><code>if (Request.Querystring[\"stylesheet\"] != null) {\n Response.Cookies[\"stylesheet\"].Value = Request.QueryString[\"stylesheet\"];\n Response.Redirect(&lt;Current Page&gt;);\n}\n</code></pre>\n\n<p>Then where you define your stylesheets:</p>\n\n<pre><code>if (Request.Cookies[\"stylesheet\"] != null) {\n // New Stylesheet\n} else {\n // Default\n}\n</code></pre>\n" } ]
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 file. If I want to do something more complex Ill normally just skip the scripting part and write a quick c# program that can handle it. </p>\n\n<p>The question then is do you put that c# program in svn and have it versioned :)</p>\n\n<p><strong>edit:</strong> The benefits of a dedicated c# application is that I can reuse code fragments to create new hooks later, including a simple log output I created to handle hook logging.</p>\n" }, { "answer_id": 6362, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 1, "selected": false, "text": "<p>I've written hooks in <a href=\"http://python.org\" rel=\"nofollow noreferrer\">Python</a> on Windows since there are a lot of examples on the net (usually for Linux but the differences are small). We also use <a href=\"http://trac.edgewall.org\" rel=\"nofollow noreferrer\">Trac</a> integrated with SVN and there is a Trac API accessible via Python which lets us automatically create/modify Trac tickets from SVN hook scripts.</p>\n" }, { "answer_id": 13720, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 2, "selected": false, "text": "<p>Check <a href=\"https://sourceforge.net/projects/captainhook/\" rel=\"nofollow noreferrer\">CaptainHook</a>, \"a simple plugin framework for writing Subversion hooks using .NET\".</p>\n" }, { "answer_id": 16624, "author": "Matt", "author_id": 1985, "author_profile": "https://Stackoverflow.com/users/1985", "pm_score": 3, "selected": false, "text": "<p>We've got complex requirements like:</p>\n\n<ol>\n<li>Only certain users can create folders in parts of the SVN tree, but everyone can edit files there</li>\n<li>Certain file extensions cannot contain certain text in the file</li>\n<li>Certain file extensions can only be stored in a subset of directories</li>\n<li>As well as several simpler ones like, Must have a commit comment</li>\n<li>Regression testable by running new hook against all previous SVN commits</li>\n</ol>\n\n<p>#5 is huge for us, there's no better way to know you're not gonna break commits moving forward than to be able to push all previous commits through your new hook. Making the hook understand that 1234 was a revision and 1234-1 was a transaction and making the appropriate argument changes when calling svnlook, etc. was the best decision we made during the process.</p>\n\n<p>For us the nut got big enough that a fully unit testable, regression testable, C# console exe made the most sense. We have config files that feed the directory restrictions, parse the existing httpd_authz file to get \"privileged\" users, etc. Had we not been running on Windows with a .NET development work force, I would have probably written it all in Python, but since others might need to support it in the future I went .NET over .BAT, .VBS, Powershell silliness. </p>\n\n<p>Personally I think Powershell is different enough from .NET to be mostly useless as a \"scripting\" language. It's good if the only cmd line support for a product comes via PS (Exchange, Windows 2k8), etc. but if all you want to do is parse some text or access regular .NET objects PS just adds a crazy syntax and stupid Security Iron Curtain to what could be a quick and easy little .NET app.</p>\n" }, { "answer_id": 1198468, "author": "Troy Hunt", "author_id": 73948, "author_profile": "https://Stackoverflow.com/users/73948", "pm_score": 4, "selected": true, "text": "<p>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:</p>\n\n<pre><code>public void Main(string[] args)\n{\n string repositories = args[0];\n string transaction = args[1];\n\n var processStartInfo = new ProcessStartInfo\n {\n FileName = \"svnlook.exe\",\n UseShellExecute = false,\n CreateNoWindow = true,\n RedirectStandardOutput = true,\n RedirectStandardError = true,\n Arguments = String.Format(\"log -t \\\"{0}\\\" \\\"{1}\\\"\", transaction, repositories)\n };\n\n var p = Process.Start(processStartInfo);\n var s = p.StandardOutput.ReadToEnd();\n p.WaitForExit();\n\n if (s == string.Empty)\n {\n Console.Error.WriteLine(\"Message must be provided\");\n Environment.Exit(1);\n }\n\n Environment.Exit(0);\n}\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>[path]\\PreCommit.exe %1 %2\n</code></pre>\n\n<p>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!</p>\n\n<p>BTW, the code has been adapted from <a href=\"http://irwinj.blogspot.com/2008/04/simple-subversion-trigger.html\" rel=\"noreferrer\">this post</a>.</p>\n" }, { "answer_id": 2067561, "author": "Aleksandr", "author_id": 251070, "author_profile": "https://Stackoverflow.com/users/251070", "pm_score": 1, "selected": false, "text": "<p>If you have a php executable with a help of simple php class you may write hook script in php like it is shown here <a href=\"http://www.devhands.com/2010/01/subversion-hook-php-framework-in/\" rel=\"nofollow noreferrer\">http://www.devhands.com/2010/01/subversion-hook-php-framework-in/</a></p>\n" } ]
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 SUBSTRING(field FROM 5 FOR 15) AS x FROM table;\n</code></pre>\n" }, { "answer_id": 65043, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<ol>\n<li><p>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.</p>\n</li>\n<li><p>Make sure you don't have any UDF called 'substring' registered inside this DB so that Firebird is expecting different parameters.</p>\n</li>\n</ol>\n" } ]
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=\"nofollow noreferrer\">cross-page posting</a>.</p>\n\n<p>Edit: I missed the fact that you're asking about an <em>external</em> page. For that I think you'd need to have your ASP.NET page gen up an HTML form whose action is set to the remote URL and method is set to POST. (Using cross-page posting, this could even be a different page with no UI, only hidden form elements.) Then add a bit of javascript to submit the form as soon as the postback result was received on the client.</p>\n" }, { "answer_id": 5190, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 2, "selected": false, "text": "<p>I have done this by rendering a form that auto-posts (using JavaScript) to the desired remote URL - gather whatever information you need for the post in the web form's postback and then build the HTML for the remote-posting form and render it back to the client.</p>\n\n<p>I built a utility class for this that contains the remote URL and a collection of name/value pairs for the form.</p>\n\n<p>Cross-page posting will work if you own both of the pages involved, but not if you need to post to another site (PayPal, for example).</p>\n" }, { "answer_id": 5219, "author": "saalon", "author_id": 111, "author_profile": "https://Stackoverflow.com/users/111", "pm_score": 5, "selected": true, "text": "<p>Here's how I solved this problem today. I started from <a href=\"http://www.c-sharpcorner.com/UploadFile/desaijm/ASP.NetPostURL11282005005516AM/ASP.NetPostURL.aspx\" rel=\"nofollow noreferrer\">this article</a> 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.</p>\n\n<p>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.</p>\n\n<p>This solution involves using <code>HttpContext.Current.Response.Write()</code> to write the data for the form, then using a bit of Javascript on the <code>&lt;body onload=\"\"&gt;</code> method to submit the form to the proper URL.</p>\n\n<p>When the user clicks on the Support Center link, the following method is called to write the response and redirect the user:</p>\n\n<pre><code>public static void PassthroughAuthentication()\n{\n\n System.Web.HttpContext.Current.Response.Write(\"&lt;body \n onload=document.forms[0].submit();window.location=\\\"Home.aspx\\\";&gt;\");\n\n System.Web.HttpContext.Current.Response.Write(\"&lt;form name=\\\"Form\\\" \n target=_blank method=post \n action=\\\"https://external-url.com/security.asp\\\"&gt;\");\n\n System.Web.HttpContext.Current.Response.Write(string.Format(\"&lt;input \n type=hidden name=\\\"cFName\\\" value=\\\"{0}\\\"&gt;\", \"Username\"));\n\n System.Web.HttpContext.Current.Response.Write(\"&lt;/form&gt;\");\n System.Web.HttpContext.Current.Response.Write(\"&lt;/body&gt;\");\n}\n</code></pre>\n\n<p>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.</p>\n\n<p>I'd be very interested in any cleaner ideas anyone has on this one.</p>\n\n<p>Eric Sipple</p>\n" }, { "answer_id": 5614, "author": "sestocker", "author_id": 285, "author_profile": "https://Stackoverflow.com/users/285", "pm_score": 3, "selected": false, "text": "<p>I would do the form post in your code behind using HttpWebRequest class. Here is a good helper class to get your started:</p>\n<p>&lt;<a href=\"https://web.archive.org/web/20210123193021/http://geekswithblogs.net/rakker/archive/2006/04/21/76044.aspx\" rel=\"nofollow noreferrer\">Link</a>&gt;</p>\n<p>From there, you can just do a Response.Redirect, or perhaps you need to vary your action based on the outcome of the post (if there was an error, display it to the user or whatever). I think you already had the answer in your question to be honest - sounds like you think it is a post OR redirect when in reality you can do them both from your code behind.</p>\n" }, { "answer_id": 2112168, "author": "Kevin", "author_id": 153942, "author_profile": "https://Stackoverflow.com/users/153942", "pm_score": 3, "selected": false, "text": "<p>I started with this example from <a href=\"http://www.codeproject.com/KB/aspnet/ASP_NETRedirectAndPost.aspx\" rel=\"nofollow noreferrer\">CodeProject</a></p>\n\n<p>Then instead of adding to the page, I borrowed from saalon (above) and did a Response.Write().</p>\n" }, { "answer_id": 18473342, "author": "Jenn", "author_id": 818004, "author_profile": "https://Stackoverflow.com/users/818004", "pm_score": 2, "selected": false, "text": "<p>I needed to open in the same window, dealing with possible frame issues from the original page, then redirecting to an external site in code behind:</p>\n\n<pre><code>Private Sub ExternalRedirector(ByVal externalUrl As String)\n Dim clientRedirectName As String = \"ClientExternalRedirect\"\n Dim externalRedirectJS As New StringBuilder()\n\n If Not String.IsNullOrEmpty(externalUrl) Then\n If Not Page.ClientScript.IsStartupScriptRegistered(clientRedirectName) Then\n externalRedirectJS.Append(\"function CheckWindow() {\")\n externalRedirectJS.Append(\" if (window.top != window) {\")\n externalRedirectJS.Append(\" window.top.location = '\")\n externalRedirectJS.Append(externalUrl)\n externalRedirectJS.Append(\"';\")\n externalRedirectJS.Append(\" return false;\")\n externalRedirectJS.Append(\" }\")\n externalRedirectJS.Append(\" else {\")\n externalRedirectJS.Append(\" window.location = '\")\n externalRedirectJS.Append(externalUrl)\n externalRedirectJS.Append(\"';\")\n externalRedirectJS.Append(\" }\")\n externalRedirectJS.Append(\"}\")\n externalRedirectJS.Append(\"CheckWindow();\")\n\n Page.ClientScript.RegisterStartupScript(Page.GetType(), clientRedirectName, externalRedirectJS.ToString(), True)\n End If\n End If\nEnd Sub\n</code></pre>\n" } ]
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/wsdldynamicurl.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/XML/wsdldynamicurl.aspx</a></p>\n" }, { "answer_id": 5193, "author": "Chris Farmer", "author_id": 404, "author_profile": "https://Stackoverflow.com/users/404", "pm_score": 0, "selected": false, "text": "<p>If you mean a VS2005 \"Web Reference\", then the generated proxy classes have a URL property that is the SOAP endpoint url of that service. You can change this property and have your subsequent http communications be made to that new endpoint.</p>\n\n<p>Edit: Ah, thanks bcaff86. I didn't know you could do that simply by changing a property.</p>\n" } ]
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<p>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.</p>\n" }, { "answer_id": 5641, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 0, "selected": false, "text": "<p>Other than the ToList difference, #2 is a lot more readable and natural IMO</p>\n" }, { "answer_id": 7741, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "<p>As mentioned d will be <code>IEnumerable&lt;MyProduct&gt;</code> while f is <code>List&lt;MyProduct&gt;</code></p>\n\n<p>The conversion is done by the C# compiler</p>\n\n<pre><code>var d = \n from mp in MyProducts\n where mp.Price &lt; 50d\n select mp;\n</code></pre>\n\n<p>Is converted to (before compilation to IL and with generics expanded):</p>\n\n<pre><code>var d = \n MyProducts.\n Where&lt;MyProduct&gt;( mp =&gt; mp.Price &lt; 50d ).\n Select&lt;MyProduct&gt;( mp =&gt; mp ); \n //note that this last select is optimised out if it makes no change\n</code></pre>\n\n<p>Note that in this simple case it makes little difference. Where Linq becomes really valuable is in much more complicated loops. </p>\n\n<p>For instance this statement could include group-bys, orders and a few let statements and still be readable in Linq format when the equivalent <code>.Method().Method.Method()</code> would get complicated.</p>\n" }, { "answer_id": 13511, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "<p>The syntax you are using for <em>d</em> will get transformed by the compiler into the same IL as the extension methods. The \"SQL-like\" syntax is supposed to be a more natural way to represent a LINQ expression (although I personally prefer the extension methods). As has already been pointed out, the first example will return an IEnumerable result while the second example will return a List result due to the call to ToList(). If you remove the ToList() call in the second example, they will both return the same result as Where returns an IEnumerable result.</p>\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 have a length method:</p>\n\n<pre><code>var element_count = 0;\nfor (e in myArray) { if (myArray.hasOwnProperty(e)) element_count++; }\n</code></pre>\n\n<p>@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as \"associative arrays\".</p>\n" }, { "answer_id": 6280, "author": "doekman", "author_id": 56, "author_profile": "https://Stackoverflow.com/users/56", "pm_score": 5, "selected": false, "text": "<p>Here's how and don't forget to check that the property is not on the prototype chain:</p>\n\n<pre><code>var element_count = 0;\nfor(var e in myArray)\n if(myArray.hasOwnProperty(e))\n element_count++;\n</code></pre>\n" }, { "answer_id": 6444, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 4, "selected": false, "text": "<blockquote>\n<blockquote>\n<p>@palmsey: In fairness to the OP, the JavaScript documentation actually explicitly refer to using variables of type Object in this manner as &quot;associative arrays&quot;.</p>\n</blockquote>\n</blockquote>\n<p>And in fairness to @palmsey he was quite correct. They aren't associative arrays; they're definitely objects :) - doing the job of an associative array. But as regards to the wider point, you definitely seem to have the right of it according to this rather fine article I found:</p>\n<p><em><a href=\"http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/\" rel=\"nofollow noreferrer\">JavaScript “Associative Arrays” Considered Harmful</a></em></p>\n<p>But according to all this, <a href=\"https://stackoverflow.com/questions/5223/length-of-javascript-associative-array#5234\">the accepted answer</a> itself is bad practice?</p>\n<blockquote>\n<blockquote>\n<p>Specify a prototype size() function for Object</p>\n</blockquote>\n</blockquote>\n<p>If anything else has been added to Object .prototype, then the suggested code will fail:</p>\n<pre><code>&lt;script type=&quot;text/javascript&quot;&gt;\nObject.prototype.size = function () {\n var len = this.length ? --this.length : -1;\n for (var k in this)\n len++;\n return len;\n}\nObject.prototype.size2 = function () {\n var len = this.length ? --this.length : -1;\n for (var k in this)\n len++;\n return len;\n}\nvar myArray = new Object();\nmyArray[&quot;firstname&quot;] = &quot;Gareth&quot;;\nmyArray[&quot;lastname&quot;] = &quot;Simpson&quot;;\nmyArray[&quot;age&quot;] = 21;\nalert(&quot;age is &quot; + myArray[&quot;age&quot;]);\nalert(&quot;length is &quot; + myArray.size());\n&lt;/script&gt;\n</code></pre>\n<p>I don't think that answer should be the accepted one as it can't be trusted to work if you have any other code running in the same execution context. To do it in a robust fashion, surely you would need to define the size method within myArray and check for the type of the members as you iterate through them.</p>\n" }, { "answer_id": 6700, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 13, "selected": true, "text": "<h2>Updated answer</h2>\n<p><strong>Here's an update as of 2016 and <a href=\"http://kangax.github.io/compat-table/es5/\" rel=\"noreferrer\">widespread deployment of ES5</a> and beyond.</strong> For IE9+ and all other modern ES5+ capable browsers, you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\"><code>Object.keys()</code></a> so the above code just becomes:</p>\n<pre><code>var size = Object.keys(myObj).length;\n</code></pre>\n<p>This doesn't have to modify any existing prototype since <code>Object.keys()</code> is now built-in.</p>\n<p><strong>Edit</strong>: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them.</p>\n<p>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.</p>\n<p><code>Object.keys</code> or <code>Object.getOwnPropertyNames</code> does not work for symbolic properties. To return them you need to use <code>Object.getOwnPropertySymbols</code>.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var person = {\n [Symbol('name')]: 'John Doe',\n [Symbol('age')]: 33,\n \"occupation\": \"Programmer\"\n};\n\nconst propOwn = Object.getOwnPropertyNames(person);\nconsole.log(propOwn.length); // 1\n\nlet propSymb = Object.getOwnPropertySymbols(person);\nconsole.log(propSymb.length); // 2</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Older answer</h2>\n<p>The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Object.size = function(obj) {\n var size = 0,\n key;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) size++;\n }\n return size;\n};\n\n// Get the size of an object\nconst myObj = {}\nvar size = Object.size(myObj);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>There's a sort of convention in JavaScript that you <a href=\"https://stackoverflow.com/questions/10757455/object-prototype-is-verboten\">don't add things to Object.prototype</a>, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.</p>\n<hr />\n" }, { "answer_id": 5527037, "author": "aeosynth", "author_id": 131023, "author_profile": "https://Stackoverflow.com/users/131023", "pm_score": 11, "selected": false, "text": "<p>If you know you don't have to worry about <code>hasOwnProperty</code> checks, you can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"noreferrer\">Object.keys()</a> method in this way:</p>\n<pre><code>Object.keys(myArray).length\n</code></pre>\n" }, { "answer_id": 6316862, "author": "DanMan", "author_id": 428241, "author_profile": "https://Stackoverflow.com/users/428241", "pm_score": 5, "selected": false, "text": "<p>To not mess with the prototype or other code, you could build and extend your own object:</p>\n\n<pre><code>function Hash(){\n var length=0;\n this.add = function(key, val){\n if(this[key] == undefined)\n {\n length++;\n }\n this[key]=val;\n }; \n this.length = function(){\n return length;\n };\n}\n\nmyArray = new Hash();\nmyArray.add(\"lastname\", \"Simpson\");\nmyArray.add(\"age\", 21);\nalert(myArray.length()); // will alert 2\n</code></pre>\n\n<p>If you always use the add method, the length property will be correct. If you're worried that you or others forget about using it, you could add the property counter which the others have posted to the length method, too.</p>\n\n<p>Of course, you could always overwrite the methods. But even if you do, your code would probably fail noticeably, making it easy to debug. ;)</p>\n" }, { "answer_id": 6874074, "author": "Jānis Elmeris", "author_id": 99904, "author_profile": "https://Stackoverflow.com/users/99904", "pm_score": 4, "selected": false, "text": "<p>For some cases it is better to just store the size in a separate variable. Especially, if you're adding to the array by one element in one place and can easily increment the size. It would obviously work much faster if you need to check the size often.</p>\n" }, { "answer_id": 7177140, "author": "Jerry", "author_id": 909828, "author_profile": "https://Stackoverflow.com/users/909828", "pm_score": 4, "selected": false, "text": "<p>What about something like this --</p>\n\n<pre><code>function keyValuePairs() {\n this.length = 0;\n function add(key, value) { this[key] = value; this.length++; }\n function remove(key) { if (this.hasOwnProperty(key)) { delete this[key]; this.length--; }}\n}\n</code></pre>\n" }, { "answer_id": 8186938, "author": "wade harrell", "author_id": 1054363, "author_profile": "https://Stackoverflow.com/users/1054363", "pm_score": 3, "selected": false, "text": "<p>A variation on some of the above is:</p>\n\n<pre><code>var objLength = function(obj){ \n var key,len=0;\n for(key in obj){\n len += Number( obj.hasOwnProperty(key) );\n }\n return len;\n};\n</code></pre>\n\n<p>It is a bit more elegant way to integrate hasOwnProp.</p>\n" }, { "answer_id": 11346637, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 8, "selected": false, "text": "<p><strong>Updated</strong>: If you're using <a href=\"http://underscorejs.org/#size\">Underscore.js</a> (recommended, it's lightweight!), then you can just do</p>\n\n<pre><code>_.size({one : 1, two : 2, three : 3});\n=&gt; 3\n</code></pre>\n\n<p><strong>If not</strong>, and you don't want to mess around with Object properties for whatever reason, and are already using jQuery, a plugin is equally accessible:</p>\n\n<pre><code>$.assocArraySize = function(obj) {\n // http://stackoverflow.com/a/6700/11236\n var size = 0, key;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) size++;\n }\n return size;\n};\n</code></pre>\n" }, { "answer_id": 15207568, "author": "Eric Anderson", "author_id": 120067, "author_profile": "https://Stackoverflow.com/users/120067", "pm_score": 2, "selected": false, "text": "<p>Below is a version of James Coglan's answer in CoffeeScript for those who have abandoned straight JavaScript :)</p>\n\n<pre><code>Object.size = (obj) -&gt;\n size = 0\n size++ for own key of obj\n size\n</code></pre>\n" }, { "answer_id": 17332295, "author": "Sherzod", "author_id": 928001, "author_profile": "https://Stackoverflow.com/users/928001", "pm_score": 3, "selected": false, "text": "<p>Here's a different version of James Cogan's answer. Instead of passing an argument, just prototype out the Object class and make the code cleaner.</p>\n\n<pre><code>Object.prototype.size = function () {\n var size = 0,\n key;\n for (key in this) {\n if (this.hasOwnProperty(key)) size++;\n }\n return size;\n};\n\nvar x = {\n one: 1,\n two: 2,\n three: 3\n};\n\nx.size() === 3;\n</code></pre>\n\n<p>jsfiddle example: <a href=\"http://jsfiddle.net/qar4j/1/\" rel=\"noreferrer\">http://jsfiddle.net/qar4j/1/</a></p>\n" }, { "answer_id": 18012581, "author": "Ally", "author_id": 837649, "author_profile": "https://Stackoverflow.com/users/837649", "pm_score": 5, "selected": false, "text": "<p>Here is a completely different solution that will only work in more modern browsers (Internet Explorer 9+, Chrome, Firefox 4+, Opera 11.60+, and Safari 5.1+)</p>\n<p>See <a href=\"http://jsfiddle.net/QHDt7/\" rel=\"noreferrer\" title=\"jsFiddle\">this jsFiddle</a>.</p>\n<p>Setup your associative array class</p>\n<pre><code>/**\n * @constructor\n */\nAssociativeArray = function () {};\n\n// Make the length property work\nObject.defineProperty(AssociativeArray.prototype, &quot;length&quot;, {\n get: function () {\n var count = 0;\n for (var key in this) {\n if (this.hasOwnProperty(key))\n count++;\n }\n return count;\n }\n});\n</code></pre>\n<p>Now you can use this code as follows...</p>\n<pre><code>var a1 = new AssociativeArray();\na1[&quot;prop1&quot;] = &quot;test&quot;;\na1[&quot;prop2&quot;] = 1234;\na1[&quot;prop3&quot;] = &quot;something else&quot;;\nalert(&quot;Length of array is &quot; + a1.length);\n</code></pre>\n" }, { "answer_id": 18560314, "author": "Joon", "author_id": 692528, "author_profile": "https://Stackoverflow.com/users/692528", "pm_score": 6, "selected": false, "text": "<p>Here's the most cross-browser solution.</p>\n\n<p>This is better than the accepted answer because it uses native Object.keys if exists.\nThus, it is the fastest for all modern browsers.</p>\n\n<pre><code>if (!Object.keys) {\n Object.keys = function (obj) {\n var arr = [],\n key;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) {\n arr.push(key);\n }\n }\n return arr;\n };\n}\n\nObject.keys(obj).length;\n</code></pre>\n" }, { "answer_id": 21656259, "author": "abo-elleef", "author_id": 1846073, "author_profile": "https://Stackoverflow.com/users/1846073", "pm_score": 4, "selected": false, "text": "<p>If we have the hash </p>\n\n<blockquote>\n <p>hash = {\"a\" : \"b\", \"c\": \"d\"};</p>\n</blockquote>\n\n<p>we can get the length using the length of the keys which is the length of the hash:</p>\n\n<blockquote>\n <p>keys(hash).length</p>\n</blockquote>\n" }, { "answer_id": 23571866, "author": "Ron Sims II", "author_id": 1341417, "author_profile": "https://Stackoverflow.com/users/1341417", "pm_score": 2, "selected": false, "text": "<p>Like most JavaScript problems, there are many solutions. You could extend the Object that for better or worse works like many other languages' Dictionary (+ first class citizens). Nothing wrong with that, but another option is to construct a new Object that meets your specific needs. </p>\n\n<pre><code>function uberject(obj){\n this._count = 0;\n for(var param in obj){\n this[param] = obj[param];\n this._count++;\n }\n}\n\nuberject.prototype.getLength = function(){\n return this._count;\n};\n\nvar foo = new uberject({bar:123,baz:456});\nalert(foo.getLength());\n</code></pre>\n" }, { "answer_id": 24510557, "author": "venkat7668", "author_id": 2165104, "author_profile": "https://Stackoverflow.com/users/2165104", "pm_score": 5, "selected": false, "text": "<p>This method gets all your object's property names in an array, so you can get the length of that array which is equal to your object's keys' length.</p>\n\n<pre><code>Object.getOwnPropertyNames({\"hi\":\"Hi\",\"msg\":\"Message\"}).length; // =&gt; 2\n</code></pre>\n" }, { "answer_id": 27805509, "author": "Eduardo Cuomo", "author_id": 717267, "author_profile": "https://Stackoverflow.com/users/717267", "pm_score": 2, "selected": false, "text": "<h2>Property</h2>\n<pre><code>Object.defineProperty(Object.prototype, 'length', {\n get: function () {\n var size = 0, key;\n for (key in this)\n if (this.hasOwnProperty(key))\n size++;\n return size;\n }\n});\n</code></pre>\n<h2>Use</h2>\n<pre><code>var o = {a: 1, b: 2, c: 3};\nalert(o.length); // &lt;-- 3\no['foo'] = 123;\nalert(o.length); // &lt;-- 4\n</code></pre>\n" }, { "answer_id": 29579046, "author": "stylesenberg", "author_id": 4132915, "author_profile": "https://Stackoverflow.com/users/4132915", "pm_score": 1, "selected": false, "text": "<p><strong>Simple solution:</strong></p>\n\n<pre><code> var myObject = {}; // ... your object goes here.\n\n var length = 0;\n\n for (var property in myObject) {\n if (myObject.hasOwnProperty(property)){\n length += 1;\n }\n };\n\n console.log(length); // logs 0 in my example.\n</code></pre>\n" }, { "answer_id": 32593870, "author": "pcnate", "author_id": 3851647, "author_profile": "https://Stackoverflow.com/users/3851647", "pm_score": 4, "selected": false, "text": "<p>If you are using <a href=\"http://en.wikipedia.org/wiki/AngularJS\" rel=\"noreferrer\">AngularJS</a> 1.x you can do things the AngularJS way by creating a filter and using the code from any of the other examples such as the following:</p>\n\n<pre><code>// Count the elements in an object\napp.filter('lengthOfObject', function() {\n return function( obj ) {\n var size = 0, key;\n for (key in obj) {\n if (obj.hasOwnProperty(key)) size++;\n }\n return size;\n }\n})\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<p>In your controller:</p>\n\n<pre><code>$scope.filterResult = $filter('lengthOfObject')($scope.object)\n</code></pre>\n\n<p>Or in your view:</p>\n\n<pre><code>&lt;any ng-expression=\"object | lengthOfObject\"&gt;&lt;/any&gt;\n</code></pre>\n" }, { "answer_id": 34734220, "author": "Pian0_M4n", "author_id": 2156913, "author_profile": "https://Stackoverflow.com/users/2156913", "pm_score": 3, "selected": false, "text": "<p>You can always do <code>Object.getOwnPropertyNames(myObject).length</code> to get the same result as <code>[].length</code> would give for normal array.</p>\n" }, { "answer_id": 35844733, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 3, "selected": false, "text": "<p>If you don't care about supporting Internet Explorer 8 or lower, you can easily get the number of properties in an object by applying the following two steps:</p>\n\n<ol>\n<li>Run either <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys\" rel=\"nofollow noreferrer\"><strong><code>Object.keys()</code></strong></a> to get an array that contains the names of only those properties that are <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Enumerability_and_ownership_of_properties\" rel=\"nofollow noreferrer\"><strong>enumerable</strong></a> or <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames\" rel=\"nofollow noreferrer\"><strong><code>Object.getOwnPropertyNames()</code></strong></a> if you want to also include the names of properties that are not enumerable.</li>\n<li>Get the <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length\" rel=\"nofollow noreferrer\"><strong><code>.length</code></strong></a> property of that array.</li>\n</ol>\n\n<hr>\n\n<p>If you need to do this more than once, you could wrap this logic in a function:</p>\n\n<pre><code>function size(obj, enumerablesOnly) {\n return enumerablesOnly === false ?\n Object.getOwnPropertyNames(obj).length :\n Object.keys(obj).length;\n}\n</code></pre>\n\n<p>How to use this particular function:</p>\n\n<pre><code>var myObj = Object.create({}, {\n getFoo: {},\n setFoo: {}\n});\nmyObj.Foo = 12;\n\nvar myArr = [1,2,5,4,8,15];\n\nconsole.log(size(myObj)); // Output : 1\nconsole.log(size(myObj, true)); // Output : 1\nconsole.log(size(myObj, false)); // Output : 3\nconsole.log(size(myArr)); // Output : 6\nconsole.log(size(myArr, true)); // Output : 6\nconsole.log(size(myArr, false)); // Output : 7\n</code></pre>\n\n<p>See also <a href=\"https://jsfiddle.net/0x11tv73/5/\" rel=\"nofollow noreferrer\"><strong>this Fiddle</strong></a> for a demo.</p>\n" }, { "answer_id": 37307278, "author": "Oriol", "author_id": 1529630, "author_profile": "https://Stackoverflow.com/users/1529630", "pm_score": 4, "selected": false, "text": "<p>If you need an associative data structure that exposes its size, better use a map instead of an object.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const myMap = new Map();\n\nmyMap.set(\"firstname\", \"Gareth\");\nmyMap.set(\"lastname\", \"Simpson\");\nmyMap.set(\"age\", 21);\n\nconsole.log(myMap.size); // 3</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 37537045, "author": "Mahendra Kulkarni", "author_id": 6011619, "author_profile": "https://Stackoverflow.com/users/6011619", "pm_score": 4, "selected": false, "text": "<p>Use:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myArray = new Object();\r\nmyArray[\"firstname\"] = \"Gareth\";\r\nmyArray[\"lastname\"] = \"Simpson\";\r\nmyArray[\"age\"] = 21;\r\nobj = Object.keys(myArray).length;\r\nconsole.log(obj)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 38816218, "author": "christian Nguyen", "author_id": 4225143, "author_profile": "https://Stackoverflow.com/users/4225143", "pm_score": 0, "selected": false, "text": "<p>The solution work for many cases and cross browser:</p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>var getTotal = function(collection) {\n\n var length = collection['length'];\n var isArrayObject = typeof length == 'number' &amp;&amp; length &gt;= 0 &amp;&amp; length &lt;= Math.pow(2,53) - 1; // Number.MAX_SAFE_INTEGER\n\n if(isArrayObject) {\n return collection['length'];\n }\n\n i= 0;\n for(var key in collection) {\n if (collection.hasOwnProperty(key)) {\n i++;\n }\n }\n\n return i;\n};\n</code></pre>\n\n<p><strong>Data Examples:</strong></p>\n\n<pre><code>// case 1\nvar a = new Object();\na[\"firstname\"] = \"Gareth\";\na[\"lastname\"] = \"Simpson\";\na[\"age\"] = 21;\n\n//case 2\nvar b = [1,2,3];\n\n// case 3\nvar c = {};\nc[0] = 1;\nc.two = 2;\n</code></pre>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>getLength(a); // 3\ngetLength(b); // 3\ngetLength(c); // 2\n</code></pre>\n" }, { "answer_id": 39542137, "author": "Mystical", "author_id": 6368005, "author_profile": "https://Stackoverflow.com/users/6368005", "pm_score": 3, "selected": false, "text": "<p>You can simply use <code>Object.keys(obj).length</code> on any object to get its length. Object.keys returns an array containing all of the object <em>keys</em> (properties) which can come in handy for finding the length of that object using the length of the corresponding array. You can even write a <em>function</em> for this. Let's get <em>creative</em> and write a <strong>method</strong> for it as well (along with a more convienient getter property):</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function objLength(obj)\r\n{\r\n return Object.keys(obj).length;\r\n}\r\n\r\nconsole.log(objLength({a:1, b:\"summit\", c:\"nonsense\"}));\r\n\r\n// Works perfectly fine\r\nvar obj = new Object();\r\nobj['fish'] = 30;\r\nobj['nullified content'] = null;\r\nconsole.log(objLength(obj));\r\n\r\n// It also works your way, which is creating it using the Object constructor\r\nObject.prototype.getLength = function() {\r\n return Object.keys(this).length;\r\n}\r\nconsole.log(obj.getLength());\r\n\r\n// You can also write it as a method, which is more efficient as done so above\r\n\r\nObject.defineProperty(Object.prototype, \"length\", {get:function(){\r\n return Object.keys(this).length;\r\n}});\r\nconsole.log(obj.length);\r\n\r\n// probably the most effictive approach is done so and demonstrated above which sets a getter property called \"length\" for objects which returns the equivalent value of getLength(this) or this.getLength()</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 44114476, "author": "solanki...", "author_id": 6390817, "author_profile": "https://Stackoverflow.com/users/6390817", "pm_score": 5, "selected": false, "text": "<p>We can find the length of Object by using:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const myObject = {};\nconsole.log(Object.values(myObject).length);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 44909574, "author": "MacroMan", "author_id": 1171032, "author_profile": "https://Stackoverflow.com/users/1171032", "pm_score": 2, "selected": false, "text": "<p>A nice way to achieve this (Internet Explorer 9+ only) is to define a magic getter on the length property:</p>\n<pre><code>Object.defineProperty(Object.prototype, &quot;length&quot;, {\n get: function () {\n return Object.keys(this).length;\n }\n});\n</code></pre>\n<p>And you can just use it like so:</p>\n<pre><code>var myObj = { 'key': 'value' };\nmyObj.length;\n</code></pre>\n<p>It would give <code>1</code>.</p>\n" }, { "answer_id": 48319070, "author": "saurabhgoyal795", "author_id": 7539786, "author_profile": "https://Stackoverflow.com/users/7539786", "pm_score": 5, "selected": false, "text": "<p>Simply use this to get the <code>length</code>:</p>\n\n<pre><code>Object.keys(myObject).length\n</code></pre>\n" }, { "answer_id": 49683151, "author": "tdjprog", "author_id": 4935426, "author_profile": "https://Stackoverflow.com/users/4935426", "pm_score": 4, "selected": false, "text": "<pre><code>var myObject = new Object();\nmyObject[\"firstname\"] = \"Gareth\";\nmyObject[\"lastname\"] = \"Simpson\";\nmyObject[\"age\"] = 21;\n</code></pre>\n\n<ol>\n<li>Object.values(myObject).length</li>\n<li>Object.entries(myObject).length</li>\n<li>Object.keys(myObject).length</li>\n</ol>\n" }, { "answer_id": 49730723, "author": "njmwas", "author_id": 2529302, "author_profile": "https://Stackoverflow.com/users/2529302", "pm_score": -1, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myObject = new Object();\r\nmyObject[\"firstname\"] = \"Gareth\";\r\nmyObject[\"lastname\"] = \"Simpson\";\r\nmyObject[\"age\"] = 21;\r\n\r\nvar size = JSON.stringify(myObject).length;\r\n\r\ndocument.write(size);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>JSON.stringify(myObject)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 50608738, "author": "Mithu A Quayium", "author_id": 2079914, "author_profile": "https://Stackoverflow.com/users/2079914", "pm_score": 4, "selected": false, "text": "<p>The simplest way is like this:</p>\n<pre><code>Object.keys(myobject).length\n</code></pre>\n<p>Where myobject is the object of what you want the length of.</p>\n" }, { "answer_id": 50713932, "author": "PythonProgrammi", "author_id": 6464947, "author_profile": "https://Stackoverflow.com/users/6464947", "pm_score": 4, "selected": false, "text": "<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script&gt;\r\nmyObj = {\"key1\" : \"Hello\", \"key2\" : \"Goodbye\"};\r\nvar size = Object.keys(myObj).length;\r\nconsole.log(size);\r\n&lt;/script&gt;\r\n\r\n&lt;p id=\"myObj\"&gt;The number of &lt;b&gt;keys&lt;/b&gt; in &lt;b&gt;myObj&lt;/b&gt; are: &lt;script&gt;document.write(size)&lt;/script&gt;&lt;/p&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>This works for me:</p>\n\n<pre><code>var size = Object.keys(myObj).length;\n</code></pre>\n" }, { "answer_id": 54662407, "author": "Kamil Kiełczewski", "author_id": 860099, "author_profile": "https://Stackoverflow.com/users/860099", "pm_score": 0, "selected": false, "text": "<p><code>Object.keys</code> does <strong>not</strong> return the right result in case of object <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\" rel=\"nofollow noreferrer\">inheritance</a>. To properly count object properties, including inherited ones, use <code>for-in</code>. For example, by the following function (related <a href=\"https://stackoverflow.com/a/54553880/860099\">question</a>):</p>\n<pre><code>var objLength = (o,i=0) =&gt; { for(p in o) i++; return i }\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myObject = new Object();\nmyObject[\"firstname\"] = \"Gareth\";\nmyObject[\"lastname\"] = \"Simpson\";\nmyObject[\"age\"] = 21;\n\nvar child = Object.create(myObject);\nchild[\"sex\"] = \"male\";\n\nvar objLength = (o,i=0) =&gt; { for(p in o) i++; return i }\n\nconsole.log(\"Object.keys(myObject):\", Object.keys(myObject).length, \"(OK)\");\nconsole.log(\"Object.keys(child) :\", Object.keys(child).length, \"(wrong)\");\nconsole.log(\"objLength(child) :\", objLength(child), \"(OK)\");</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 57525980, "author": "Paul", "author_id": 5939653, "author_profile": "https://Stackoverflow.com/users/5939653", "pm_score": -1, "selected": false, "text": "<p>I had a similar need to calculate the bandwidth used by objects received over a websocket. Simply finding the length of the Stringified object was enough for me.</p>\n\n<pre><code>websocket.on('message', data =&gt; {\n dataPerSecond += JSON.stringify(data).length;\n}\n</code></pre>\n" }, { "answer_id": 57839252, "author": "shaheb", "author_id": 2786194, "author_profile": "https://Stackoverflow.com/users/2786194", "pm_score": 4, "selected": false, "text": "<p>Use <code>Object.keys(myObject).length</code> to get the length of object/array</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var myObject = new Object();\nmyObject[\"firstname\"] = \"Gareth\";\nmyObject[\"lastname\"] = \"Simpson\";\nmyObject[\"age\"] = 21;\n\nconsole.log(Object.keys(myObject).length); //3</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 59694573, "author": "Soura Ghosh", "author_id": 9229338, "author_profile": "https://Stackoverflow.com/users/9229338", "pm_score": 3, "selected": false, "text": "<pre><code>const myObject = new Object();\nmyObject[\"firstname\"] = \"Gareth\";\nmyObject[\"lastname\"] = \"Simpson\";\nmyObject[\"age\"] = 21;\n\nconsole.log(Object.keys(myObject).length)\n\n// o/p 3\n</code></pre>\n" }, { "answer_id": 60540719, "author": "Sheelpriy", "author_id": 2542562, "author_profile": "https://Stackoverflow.com/users/2542562", "pm_score": 2, "selected": false, "text": "<p>With the ECMAScript 6 in-built Reflect object, you can easily count the properties of an object:</p>\n<pre><code>Reflect.ownKeys(targetObject).length\n</code></pre>\n<p>It will give you the length of the target object's own properties (<em>important</em>).</p>\n<pre><code>Reflect.ownKeys(target)\n</code></pre>\n<blockquote>\n<p>Returns an array of the target object's own (not inherited) property\nkeys.</p>\n</blockquote>\n<p>Now, what does that mean? To explain this, let's see this example.</p>\n<pre><code>function Person(name, age){\n this.name = name;\n this.age = age;\n}\n\nPerson.prototype.getIntro= function() {\n return `${this.name} is ${this.age} years old!!`\n}\n\nlet student = new Person('Anuj', 11);\n\nconsole.log(Reflect.ownKeys(student).length) // 2\nconsole.log(student.getIntro()) // Anuj is 11 years old!!\n</code></pre>\n<p>You can see here, it returned only its own properties while the object is still inheriting the property from its parent.</p>\n<p>For more information, refer this: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect\" rel=\"nofollow noreferrer\">Reflect API</a></p>\n" }, { "answer_id": 64231717, "author": "Shashwat Gupta", "author_id": 7765900, "author_profile": "https://Stackoverflow.com/users/7765900", "pm_score": 2, "selected": false, "text": "<p>Simple one liner:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>console.log(Object.values({id:\"1\",age:23,role_number:90}).length);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 67136236, "author": "Rashed Rahat", "author_id": 10427807, "author_profile": "https://Stackoverflow.com/users/10427807", "pm_score": 2, "selected": false, "text": "<p>Try: <code>Object.values(theObject).length</code></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const myObject = new Object();\nmyObject[\"firstname\"] = \"Gareth\";\nmyObject[\"lastname\"] = \"Simpson\";\nmyObject[\"age\"] = 21;\nconsole.log(Object.values(myObject).length);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" }, { "answer_id": 69669301, "author": "Coni", "author_id": 16932102, "author_profile": "https://Stackoverflow.com/users/16932102", "pm_score": -1, "selected": false, "text": "<pre><code> vendor = {1: &quot;&quot;, 2: &quot;&quot;}\n const keysArray = Object.keys(vendor)\n const objectLength = keysArray.length\n console.log(objectLength)\n Result 2\n</code></pre>\n" }, { "answer_id": 70413307, "author": "dazzafact", "author_id": 1163485, "author_profile": "https://Stackoverflow.com/users/1163485", "pm_score": 1, "selected": false, "text": "<p>Here you can give any kind of varible array,object,string</p>\n<pre><code>function length2(obj){\n if (typeof obj==='object' &amp;&amp; obj!== null){return Object.keys(obj).length;}\n //if (Array.isArray){return obj.length;}\n return obj.length;\n\n}\n</code></pre>\n" }, { "answer_id": 71957503, "author": "Ran Turner", "author_id": 7494218, "author_profile": "https://Stackoverflow.com/users/7494218", "pm_score": 3, "selected": false, "text": "<p>Using the <code>Object.entries</code> method to get length is one way of achieving it</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const objectLength = obj =&gt; Object.entries(obj).length;\n\nconst person = {\n id: 1,\n name: 'John',\n age: 30\n}\n \nconst car = {\n type: 2,\n color: 'red',\n}\n\nconsole.log(objectLength(person)); // 3\nconsole.log(objectLength(car)); // 2</code></pre>\r\n</div>\r\n</div>\r\n</p>\n" } ]
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, 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.</p>\n" }, { "answer_id": 5334, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 2, "selected": false, "text": "<p>Okay, how about these? The difference between the approaches should speak for themselves.</p>\n\n<p>Also, this is tested about as far as I can throw it. The warranty lasts until... now.</p>\n\n<p>Hope it helps!</p>\n\n<pre><code>Module Module1\n\n Public Function IsInBusinessHours(ByVal d As Date) As Boolean\n Return Not (d.Hour &lt; 8 OrElse d.Hour &gt; 17 OrElse d.DayOfWeek = DayOfWeek.Saturday OrElse d.DayOfWeek = DayOfWeek.Sunday)\n End Function\n\n\n Public Function AddInBusinessHours(ByVal fromDate As Date, ByVal hours As Integer) As Date\n Dim work As Date = fromDate.AddHours(hours)\n While Not IsInBusinessHours(work)\n work = work.AddHours(1)\n End While\n Return work\n End Function\n\n\n Public Function LoopInBusinessHours(ByVal fromDate As Date, ByVal hours As Integer) As Date\n Dim work As Date = fromDate\n While hours &gt; 0\n While hours &gt; 0 AndAlso IsInBusinessHours(work)\n work = work.AddHours(1)\n hours -= 1\n End While\n While Not IsInBusinessHours(work)\n work = work.AddHours(1)\n End While\n End While\n Return work\n End Function\n\n Sub Main()\n Dim test As Date = New Date(2008, 8, 8, 15, 0, 0)\n Dim hours As Integer = 5\n Console.WriteLine(\"Date: \" + test.ToString() + \", \" + hours.ToString())\n Console.WriteLine(\"Just skipping: \" + AddInBusinessHours(test, hours))\n Console.WriteLine(\"Looping: \" + LoopInBusinessHours(test, hours))\n Console.ReadLine()\n End Sub\n\nEnd Module\n</code></pre>\n" }, { "answer_id": 5588, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 1, "selected": false, "text": "<p>I've worked with the following formula (pseudocode) with some success:</p>\n\n<pre><code>now &lt;- number of minutes since the work day started\ndelay &lt;- number of minutes in the delay\nday &lt;- length of a work day in minutes\n\nx &lt;- (now + delay) / day {integer division}\ny &lt;- (now + delay) % day {modulo remainder}\n\nreturn startoftoday + x {in days} + y {in minutes}\n</code></pre>\n" } ]
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</code></pre>\n" }, { "answer_id": 24472, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 3, "selected": true, "text": "<p>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:</p>\n\n<ol>\n<li>build and save parent</li>\n<li>build and save child with relationship to parent</li>\n</ol>\n\n<p>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.</p>\n" }, { "answer_id": 157189, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 0, "selected": false, "text": "<p>I suggest you add a ForeignKeyConstraint, with UpdateRule set to Cascade.</p>\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 use AndAlso</p>\n" }, { "answer_id": 5276, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 5, "selected": true, "text": "<p>C# : Left to right, and processing stops if a non-match (evaluates to false) is found.</p>\n" }, { "answer_id": 5277, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 0, "selected": false, "text": "<p>I have heard somewhere that compilers work backwards, but I am unsure how true this is.</p>\n" }, { "answer_id": 5278, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 3, "selected": false, "text": "<p><strong>vb.net</strong></p>\n\n<pre><code>if( x isNot Nothing AndAlso x.go()) then\n</code></pre>\n\n<ol>\n<li>Evaluation is done left to right</li>\n<li><strong>AndAlso</strong> operator makes sure that only if the left side was TRUE, the right side will be evaluated (very important, since ifx is nothing x.go will crash)</li>\n</ol>\n\n<p>You may use <strong>And</strong> instead ofAndAlso in vb. in which case the left side gets evaluated first as well, but the right side will get evaluated regardless of result. </p>\n\n<p>Best Practice: Always use AndAlso, unless you have a very good reason why not to.</p>\n\n<hr>\n\n<p><strong>It was asked in a followup why or when would anyone use And instead of AndAlso (or &amp; instead of &amp;&amp;):</strong>\nHere is an example:</p>\n\n<pre><code>if ( x.init() And y.init()) then\n x.process(y)\nend \ny.doDance()\n</code></pre>\n\n<p>In this case, I want to init both X and Y. Y must be initialized in order for y.DoDance to be able to execute. However, in the init() function I am doing also some extra thing like checking a socket is open, and only if that works out ok, for <strong>both</strong>, I should go ahead and do the x.process(y).</p>\n\n<p>Again, this is probably not needed and not elegant in 99% of the cases, that is why I said that the default should be to use <em>AndAlso</em>.</p>\n" }, { "answer_id": 5279, "author": "shsteimer", "author_id": 292, "author_profile": "https://Stackoverflow.com/users/292", "pm_score": 2, "selected": false, "text": "<p>The concept modesty is referring to is operator overloading. in the statement:</p>\n\n<pre><code>if( A &amp;&amp; B){\n // do something\n}\n</code></pre>\n\n<p>A is evaluated first, if it evaluates to false, B is never evaluated. The same applies to</p>\n\n<pre><code>if(A || B){\n //do something\n}\n</code></pre>\n\n<p>A is evaluated first, if it evaluates to true, B is never evaluated.</p>\n\n<p>This concept, overloading, applies to (i think) all of the C style languages, and many others as well.</p>\n" }, { "answer_id": 5292, "author": "Brad Tutterow", "author_id": 308, "author_profile": "https://Stackoverflow.com/users/308", "pm_score": 2, "selected": false, "text": "<p>ZombieSheep is dead-on. The only \"gotcha\" that might be waiting is that this is only true if you are using the &amp;&amp; operator. When using the &amp; operator, both expressions will be evaluated every time, regardless if one or both evaluate to false.</p>\n\n<pre><code>if (amHungry &amp; whiteCastleIsNearby)\n{\n // The code will check if White Castle is nearby\n // even when I am not hungry\n}\n\nif (amHungry &amp;&amp; whiteCastleIsNearby)\n{\n // The code will only check if White Castle is nearby\n // when I am hungry\n}\n</code></pre>\n" }, { "answer_id": 5295, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>Note that there is a difference between &amp;&amp; and &amp; regarding how much of your expression is evaluated.</p>\n\n<p>&amp;&amp; is known as a short-circuited boolean AND, and will, as noted by others here, stop early if the result can be determined before all the sub-expressions are evaluated.</p>\n\n<p>&amp; is known as a logical bitwise operator and will always evaluate all the sub-expressions.</p>\n\n<p>As such:</p>\n\n<pre><code>if (a() &amp;&amp; b())\n</code></pre>\n\n<p>Will only call <em>b</em> if <em>a</em> returns <em>true</em>.</p>\n\n<p>however, this:</p>\n\n<pre><code>if (a() &amp; b())\n</code></pre>\n\n<p>Will always call both <em>a</em> and <em>b</em>, even though the result of calling <em>a</em> is false and thus known to be <em>false</em> regardless of the result of calling <em>b</em>.</p>\n\n<p>This same difference exists for the || and | operators.</p>\n" }, { "answer_id": 5301, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>Some languages have interesting situations where expressions are executed in a different order. I am specifically thinking of Ruby, but I'm sure they borrowed it from elsewhere (probably Perl).</p>\n\n<p>The expressions in the logic will stay left to right, but for example:</p>\n\n<pre><code>puts message unless message.nil?\n</code></pre>\n\n<p>The above will evaluate \"message.nil?\" first, then if it evaluates to false (unless is like if except it executes when the condition is false instead of true), \"puts message\" will execute, which prints the contents of the message variable to the screen.</p>\n\n<p>It's kind of an interesting way to structure your code sometimes... I personally like to use it for very short 1 liners like the above.</p>\n\n<p>Edit:</p>\n\n<p>To make it a little clearer, the above is the same as:</p>\n\n<pre><code>unless message.nil?\n puts message\nend\n</code></pre>\n" }, { "answer_id": 5308, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 1, "selected": false, "text": "<p>Nopes, at least the C# compiler doesn't work backwards (in either &amp;&amp; or ||). It's left to right.</p>\n" }, { "answer_id": 5372, "author": "Bruce Alderman", "author_id": 311, "author_profile": "https://Stackoverflow.com/users/311", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>What is a good example of when to use the bitwise operator instead of the \"short-circuited boolean\"?</p>\n</blockquote>\n\n<p>Suppose you have flags, say for file attributes. Suppose you've defined READ as 4, WRITE as 2, and EXEC as 1. In binary, that's:</p>\n\n<pre><code>READ 0100 \nWRITE 0010 \nEXEC 0001\n</code></pre>\n\n<p>Each flag has one bit set, and each one is unique. The bitwise operators let you combine these flags:</p>\n\n<pre><code>flags = READ &amp; EXEC; // value of flags is 0101\n</code></pre>\n" }, { "answer_id": 5378, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<p>@shsteimer </p>\n\n<blockquote>\n <p>The concept modesty is referring to is operator overloading. in the statement:\n ...\n A is evaluated first, if it evaluates to false, B is never evaluated. The same applies to</p>\n</blockquote>\n\n<p>That's not operator overloading. Operator overloading is the term given for letting you define custom behaviour for operators, such as *, +, = and so on.</p>\n\n<p>This would let you write your own 'Log' class, and then do </p>\n\n<pre><code>a = new Log(); // Log class overloads the + operator\na + \"some string\"; // Call the overloaded method - otherwise this wouldn't work because you can't normally add strings to objects.\n</code></pre>\n\n<p>Doing this</p>\n\n<pre><code>a() || b() // be never runs if a is true\n</code></pre>\n\n<p>is actually called <a href=\"http://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"noreferrer\">Short Circuit Evaluation</a></p>\n" }, { "answer_id": 5382, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "<p>You use &amp; when you specifically want to evaluate all the sub-expressions, most likely because they have side-effects you want, even though the final result will be <em>false</em> and thus not execute your <em>then</em> part of your <em>if</em>-statement.</p>\n\n<p>Note that &amp; and | operates for both bitwise masks and boolean values and is not just for bitwise operations. They're <em>called</em> bitwise, but they are defined for both integers and boolean data types in C#.</p>\n" }, { "answer_id": 5384, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "<p>When things are all in-line, they're executed left-to-right.</p>\n\n<p>When things are nested, they're executed inner-to-outer. This may seem confusing as usually what's \"innermost\" is on the right-hand side of the line, so it seems like it's going backwards...</p>\n\n<p>For example</p>\n\n<pre><code>a = Foo( 5, GetSummary( \"Orion\", GetAddress(\"Orion\") ) );\n</code></pre>\n\n<p>Things happen like this:</p>\n\n<ul>\n<li>Call <code>GetAddress</code> with the literal <code>\"Orion\"</code></li>\n<li>Call <code>GetSummary</code> with the literal <code>\"Orion\"</code> and the result of <code>GetAddress</code></li>\n<li>Call <code>Foo</code> with the literal <code>5</code> and the result of <code>GetSummary</code></li>\n<li>Assign this value to <code>a</code></li>\n</ul>\n" }, { "answer_id": 5412, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 3, "selected": false, "text": "<p>I realise this question has already been answered, but I'd like to throw in another bit of information which is related to the topic.</p>\n\n<p>In languages, like C++, where you can actually overload the behaviour of the &amp;&amp; and || operators, it is highly recommended that you <strong>do not do this</strong>. This is because when you overload this behaviour, you end up forcing the evaluation of both sides of the operation. This does two things:</p>\n\n<ol>\n<li>It breaks the lazy evaluation mechanism because the overload is a function which has to be invoked, and hence both parameters are evaluated before calling the function.</li>\n<li>The order of evaluation of said parameters isn't guaranteed and can be compiler specific. Hence the objects wouldn't behave in the same manner as they do in the examples listed in the question/previous answers.</li>\n</ol>\n\n<p>For more info, have a read of Scott Meyers' book, <a href=\"https://rads.stackoverflow.com/amzn/click/com/020163371X\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">More Effective C++</a>. Cheers!</p>\n" }, { "answer_id": 5432, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "<p>I like Orion's responses. I'll add two things:</p>\n\n<ol>\n<li>The left-to-right still applies first</li>\n<li>The inner-to-outer to ensure that all arguments are resolved before calling the function</li>\n</ol>\n\n<p>Say we have the following example:</p>\n\n<pre><code>a = Foo(5, GetSummary(\"Orion\", GetAddress(\"Orion\")),\n GetSummary(\"Chris\", GetAddress(\"Chris\")));\n</code></pre>\n\n<p>Here's the order of execution:</p>\n\n<ol>\n<li><code>GetAddress(\"Orion\")</code></li>\n<li><code>GetSummary(\"Orion\", ...)</code></li>\n<li><code>GetAddress(\"Chris\")</code></li>\n<li><code>GetSummary(\"Chris\", ...)</code></li>\n<li><code>Foo(...)</code></li>\n<li>Assigns to <code>a</code></li>\n</ol>\n\n<p>I can't speak about C#'s legal requirements (although I did test a similar example using Mono before writing this post), but this order is guaranteed in Java.</p>\n\n<p>And just for completeness (since this is a language-agnostic thread as well), there are languages like C and C++, where the order is not guaranteed unless there is a sequence point. References: <a href=\"http://www.gotw.ca/gotw/056.htm\" rel=\"nofollow noreferrer\">1</a>, <a href=\"http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.16\" rel=\"nofollow noreferrer\">2</a>. In answering the thread's question, however, <code>&amp;&amp;</code> and <code>||</code> are sequence points in C++ (unless overloaded; also see OJ's excellent answer). So some examples:</p>\n\n<ul>\n<li><code>foo() &amp;&amp; bar()</code></li>\n<li><code>foo() &amp; bar()</code></li>\n</ul>\n\n<p>In the <code>&amp;&amp;</code> case, <code>foo()</code> is guaranteed to run before <code>bar()</code> (if the latter is run at all), since <code>&amp;&amp;</code> is a sequence point. In the <code>&amp;</code> case, no such guarantee is made (in C and C++), and indeed <code>bar()</code> can run before <code>foo()</code>, or vice versa.</p>\n" }, { "answer_id": 5749, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 3, "selected": false, "text": "<p>&quot;C# : Left to right, and processing stops if a match (evaluates to true) is found.&quot;</p>\n<p>Zombie sheep is wrong.</p>\n<p>The question is about the &amp;&amp; operator, not the || operator.</p>\n<p>In the case of &amp;&amp; evaluation will stop if a FALSE is found.</p>\n<p>In the case of || evaluation stops if a TRUE is found.</p>\n" }, { "answer_id": 17521, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/5269/c-logic-order-and-compiler-behavior#5278\">@csmba</a>:</p>\n<blockquote>\n<p>It was asked in a followup why or when would anyone use And instead of AndAlso (or &amp; instead of &amp;&amp;): Here is an example:</p>\n<pre><code>if ( x.init() And y.init()) then\n x.process(y)\nend \ny.doDance()\n</code></pre>\n<p>In this case, I want to init both X and Y. Y must be initialized in order for y.DoDance to be able to execute. However, in the init() function I am doing also some extra thing like checking a socket is open, and only if that works out ok, for both, I should go ahead and do the x.process(y).</p>\n</blockquote>\n<p>I believe this is rather confusing. Although your example works, it's not the typical case for using <code>And</code> (and I would probably write this differently to make it clearer). <code>And</code> (<code>&amp;</code> in most other languages) is actually the bitwise-and operation. You would use it to calculate bit operations, for example deleting a flag bit or masking and testing flags:</p>\n<pre><code>Dim x As Formatting = Formatting.Bold Or Formatting.Italic\nIf (x And Formatting.Italic) = Formatting.Italic Then\n MsgBox(&quot;The text will be set in italic.&quot;)\nEnd If\n</code></pre>\n" }, { "answer_id": 2641585, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "<p>The D programming language Does do <a href=\"http://www.digitalmars.com/d/1.0/expression.html#OrOrExpression\" rel=\"nofollow noreferrer\">left-to-right evaluation with short circuiting</a> and <a href=\"http://www.digitalmars.com/d/1.0/operatoroverloading.html#Future\" rel=\"nofollow noreferrer\">doesn't</a> allow overloading of the <a href=\"https://stackoverflow.com/questions/5269/c-logic-order-and-compiler-behavior/5412#5412\"><code>&amp;&amp;</code> and '||'</a> operators.</p>\n" } ]
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 gotta use a table.</p>\n\n<p>Business-wise, it's generally \"what's going to get it done the fastest and most reliable way.\" In my experience, using a few tables generally falls into that category.</p>\n\n<p>I have found that a very effective way to mitigate cross-browser differences in CSS rendering is to use the \"strict\" doctype at the top of your page:</p>\n\n<pre><code>&lt;!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"&gt;\n</code></pre>\n\n<p>Also, for the dreaded IE6 CSS issues, you can use this hack:</p>\n\n<pre><code>.someClass {\n background-color:black; /*this is for most browsers*/\n _background-color:white; /*this is for IE6 only - all others will ignore it*/\n}\n</code></pre>\n" }, { "answer_id": 5332, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 4, "selected": false, "text": "<p>Like a lot of things, it's a good idea that often gets carried too far. I like a div+css driven layout because it's usually quite easy to change the appearance, even drastically, just through the stylesheet. It's also nice to be friendly to lower-level browsers, screen readers, etc. But like most decisions in programming, the purpose of the site and the cost of development should be considered in making a decision. Neither side is the right way to go 100% of the time.</p>\n\n<p>BTW, I think everyone agrees that tables <em>should</em> be used for tabular data.</p>\n" }, { "answer_id": 5338, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 1, "selected": false, "text": "<p>Business reason for CSS layout: You can blow away the customers by saying \"our portal is totally customizable/skinnable without writing code!\"</p>\n\n<p>Then again, I don't see any evil in designing block elements with tables. By block elements I mean where it doesn't make any sense to break apart the said element in different designs. </p>\n\n<p>So, tabular data would best be presented with tables, of course. Designing major building blocks (such as a menu bar, news ticker, etc.) within their own tables should be OK as well. Just don't rely on tables for the overall page layout and you'll be fine, methinks.</p>\n" }, { "answer_id": 5339, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 2, "selected": false, "text": "<p>The <em>idea</em> is that Designers can Design and Web Developers can implement. This is especially the case in dynamic web applications where you do not want your Designers to mess around in your Source Code.</p>\n\n<p>Now, while there are templating engines, Designers apparantly just love to go crazy and CSS allows to pull a lot more stunts than tables.</p>\n\n<p>That being said: As a developer, i abandoned CSS Layout mostly because my Design sucks anyway, so at least it can suck properly :-) But if I would ever hire a Designer, I would let him use whatever his WYSIWYG Editor spits out.</p>\n" }, { "answer_id": 5341, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 3, "selected": false, "text": "<p>Keep your layout and your content separate allows you to redesign or make tweaks and changes to your site easily. It may take a bit longer up front, but <strong>the longest phase of software development is maintenance</strong>. A css friendly site with clear separation between content and design is best over the course of maintenance.</p>\n" }, { "answer_id": 5345, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 3, "selected": false, "text": "<p>Using semantic HTML design is one of those things where you don't know what you're missing unless you make a practice of it. I've worked on several sites where the site was restyled after the fact with little or no impact to the server-side code.</p>\n\n<p>Restyling sites is a very common request, something that I've noticed more now that I'm able to say \"yes\" to instead of try to talk my way out of.</p>\n\n<p>And, once you've learned to work with the page layout system, it's usually no harder than table based layout.</p>\n" }, { "answer_id": 5355, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 0, "selected": false, "text": "<p>:: nods at palmsey and Jon Galloway ::</p>\n\n<p>I agree with the maintainability factor. It does take me a bit longer to get my initial layouts done (since I'm still a jedi apprentice in the CSS arts) but doing a complete revamp of a 15 page web site just by updating 1 file is heaven.</p>\n" }, { "answer_id": 5395, "author": "Brian Lyttle", "author_id": 636, "author_profile": "https://Stackoverflow.com/users/636", "pm_score": 0, "selected": false, "text": "<p>Some additional reasons why this is good practice:</p>\n\n<ul>\n<li>Accessibility - the web should ideally be\naccessible by all</li>\n<li>Performance - save\n bandwidth and load faster on mobile\n devices (these lack bandwidth to some\n degree and cannot layout complex\n tables quickly). Besides loading fast is always a good thing...</li>\n</ul>\n" }, { "answer_id": 5402, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 3, "selected": false, "text": "<p>In my experience, the only time this really adds business value is when there is a need for 100% support for accessibility. When you have users who are visually impaired and/or use screenreaders to view your site, you need to make sure that your site is compliant to accessibility standards.</p>\n\n<p><strike>Users that use screenreaders will tend to have their own high-contrast, large-font stylesheet (if your site doesn't supply one itself) which makes it easy for screenreaders to parse the page.</strike></p>\n\n<p><strike>When a screenreader reads a page and sees a table, it'll tell the user it's a table. Hence, if you use a table for layout, it gets very confusing because the user doesn't know that the content of the table is actually the article instead of some other tabular data.</strike> A menu should be a list or a collection of divs, not a table with menu items, again that's confusing. You should make sure that you use blockquotes, alt-tags title attributes, etc to make it more readable.</p>\n\n<p>If you make your design CSS-driven, then your entire look and feel can be stripped away and replaced with a raw view which is very readable to those users. If you have inline styles, table-based layouts, etc, then you're making it harder for those users to parse your content.</p>\n\n<p>While I do feel that maintenance is made easier for <em>some</em> things when your site is purely laid out with CSS, I don't think it's the case for all kinds of maintenance -- especially when you're dealing with cross-browser CSS, which can obviously be a nightmare.</p>\n\n<p>In short, your page should describe its make-up in a standards compliant way if you want it to be accessible to said users. If you have no need/requirement and likely won't need it in the future, then don't bother wasting too much time attempting to be a CSS purist :) Use the mixture of style and layout techniques that suits you and makes your job easier.</p>\n\n<p>Cheers!</p>\n\n<p>[EDIT - added strikethrough to wrong or misleading parts of this answer - see comments]</p>\n" }, { "answer_id": 5417, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 3, "selected": false, "text": "<p>In the real world, your chances of taking one design and totally reskinning it without touching the markup are pretty remote. It's fine for blogs and concocted demos like the csszengarden, but it's a bogus benefit on any site with a moderately complex design, really. Using a CMS is far more important.</p>\n\n<p>DIVs plus CSS != semantic, either. Good HTML is well worthwhile for SEO and accessibility always, whether tables or CSS are used for layout. You get really efficient, fast web designs by combining really simple tables with some good CSS. </p>\n\n<p>Table layouts can be more accessible than CSS layouts, and the reverse is also true - it depends TOTALLY on the source order of the content, and just because you avoided tables does not mean users with screen readers will automatically have a good time on your site. Layout tables are irrelevant to screen reader access provided the content makes sense when linearised, exactly the same as if you do CSS layout. Data tables are different; they are really hard to mark up properly and even then the users of screen reader software generally don't know the commands they need to use to understand the data. </p>\n\n<p>Rather than agonising over using a few layout tables, you should worry that heading tags and alt text are used properly, and that form labels are properly assigned. Then you'll have a pretty good stab at real world accessibility.</p>\n\n<p>This from several years experience running user testing for web accessibility, specialising in accessible site design, and from consulting for Cahoot, an online bank, on this topic for a year. </p>\n\n<p>So my answer to the poster is no, there is no business reason to prefer CSS over tables. It's more elegant, more satisfying and more correct, but you as the person building it and the person that has to maintain it after you are the only two people in the world who give a rat's ass whether it's CSS or tables.</p>\n" }, { "answer_id": 5421, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 0, "selected": false, "text": "<blockquote>\n <blockquote>\n <p>When a screenreader reads a page and sees a table, it'll tell the user it's a table. Hence, if you use a table for layout, it gets very confusing because the user doesn't know that the content of the table is actually the article instead of some other tabular data</p>\n </blockquote>\n</blockquote>\n\n<p>This is actually not true; screen readers like JAWS, Window Eyes and HAL ignore layout tables. They work really well at dealing with the real web.</p>\n" }, { "answer_id": 5423, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 3, "selected": false, "text": "<p>One other thing I just remembered, you can assign a different stylesheet to a page for printing vs. display.</p>\n\n<p>In addition to your normal stylesheet definition, you can add the following tag</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" type=\"text/css\" media=\"print\" href=\"PrintStyle.css\" /&gt;\n</code></pre>\n\n<p>Which will render the document according to that style when you send it to the printer. This allows you to strip out the background images, additional header/footer information and just print the raw information without creating a separate module.</p>\n" }, { "answer_id": 5429, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 3, "selected": false, "text": "<blockquote>\n <blockquote>\n <p>doing a complete revamp of a 15 page web site just by updating 1 file is heaven.</p>\n </blockquote>\n</blockquote>\n\n<p>This is true. Unfortunately, having one CSS file used by 15,000 complex and widely differing pages is your worst nightmare come true. Change something - did it break a thousand pages? Who knows?</p>\n\n<p>CSS is a double-edged sword on big sites like ours.</p>\n" }, { "answer_id": 5474, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": false, "text": "<p>If you have a public facing website, the real business case is SEO. </p>\n\n<p>Accessibility is important and maintaining semantic (X)HTML <strong>is</strong> much easier than maintaining table layouts, but that #1 spot on Google will bring home the bacon.</p>\n\n<p>For example: <a href=\"http://latimesblogs.latimes.com/readers/2008/08/colleagues-we-c.html\" rel=\"nofollow noreferrer\">Monthly web report: 127 million page views for July</a></p>\n\n<blockquote>\n <p>Monthly web report: 127 million page views for July</p>\n \n <p>...</p>\n \n <p>Latimes.com keeps getting better at SEO (search engine optimization), which means our stories are ranking higher in Google and other search engines. We are also performing better on sites like Digg.com. All that adds up to more exposure and more readership than ever before.</p>\n</blockquote>\n\n<p>If you look at their site, they've got a pretty decent CSS layout going. </p>\n\n<p>Generally, you find relatively few table layouts performing well in the SERPs these days.</p>\n" }, { "answer_id": 5506, "author": "Michael Neale", "author_id": 699, "author_profile": "https://Stackoverflow.com/users/699", "pm_score": 0, "selected": false, "text": "<p>I don't think there is a business reason at all. Technical reason, maybe, even so, barely - it is a huge timesuck the world over, and then you look at it in IE and break down and weep.</p>\n" }, { "answer_id": 5530, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>*I would let him use whatever his WYSIWYG Editor spits out<br>\n I just threw-up a little...<br>\n *ahh hello? You don't think the graphic designer is writing the CSS by hand do you?</p>\n</blockquote>\n\n<p>Funnily enough I have worked with a few designers and the best among them <strong><em>do</em></strong> hand-tweak their css. The guy I am thinking of actually does all of his design work as an XHTML file with a couple of CSS files and creates graphical elements on the fly as he needs them. He uses Dreamweaver but only really as a navigation tool. (I learned a lot from that guy)</p>\n\n<p>Once you've made an investment to learn purely CSS-based design and have had a little experience (found out where IE sucks [to be fair it's getting better]) it ends up being faster I've found. I worked on Content Management Systems and the application rarely had to change for the designers to come up with a radically different look.</p>\n" }, { "answer_id": 75488, "author": "Carl Camera", "author_id": 12804, "author_profile": "https://Stackoverflow.com/users/12804", "pm_score": 5, "selected": false, "text": "<p>Since this is stack<strong>overflow</strong>, I'll give you my <em>programmer's answer</em></p>\nsemantics 101\n<p>First take a look at this code and think about what's wrong here...</p>\n<pre><code>class car {\n int wheels = 4;\n string engine;\n}\n\ncar mybike = new car();\nmybike.wheels = 2;\nmybike.engine = null;\n</code></pre>\n<p>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.</p>\nsemantics 102\n<p>Now apply this to document markup. If your document needs to present tabular data, then the appropriate tag would be <code>&lt;table&gt;</code>. If you place navigation into a table however, then you're misusing the intended purpose of the <code>&lt;table&gt;</code> element. In the second case, you're not presenting tabular data -- you're (mis)using the <code>&lt;table&gt;</code> element to achieve a presentational goal.</p>\nconclusion\n<p>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.</p>\n" }, { "answer_id": 207148, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>i actually can see Tables in Stack Overflow on the user page. </p>\n\n<p>It even has heaps of inline styles...</p>\n" }, { "answer_id": 208308, "author": "Brad", "author_id": 26130, "author_profile": "https://Stackoverflow.com/users/26130", "pm_score": 1, "selected": false, "text": "<p>Besides being easily updatable and compliant...</p>\n\n<p>I use to design all table based web sites and I was resistant at first, but little by little I moved to CSS. It did not happen overnight, but it happened and it is something you should do as well.</p>\n\n<p>There have been some nights I wanted to toss my computer out the window because the style I was applying to a div was not doing what I want, but you learn from those obstacles.</p>\n\n<p>As for a business, once you get to designing web sites by CSS down to a science, you can develop processes for each site and even use past web sites and just add a different header graphic, color, etc.</p>\n\n<p>Also, be sure to embed/include all reusable parts of your website: header, sub-header, footer.</p>\n\n<p>Once you get over the hump, it will be all down hill from there. Good luck!</p>\n" }, { "answer_id": 208501, "author": "Vijesh VP", "author_id": 22016, "author_profile": "https://Stackoverflow.com/users/22016", "pm_score": 3, "selected": false, "text": "<p>The main reason why we changed our web pages to DIV/CSS based layout was the delay in rendering table based pages. </p>\n\n<p>We have a public web site, with most of its users base is in countries like India, where the internet bandwidth is still an issue (its getting improved day by day, but still not on par). In such circumstances, when we used table based layout, users had to stare at a blank page for considerably long time. Then the entire page will get displayed as a whole in a tick. By converting our pages to DIV, we managed to bring some contents to the browser almost instantly as users entered to our web site, and those contents where enough to get the users engaged till browser downloads entire contents of the page. </p>\n\n<p>The major flaw with table based implementation is that, the browser we will show the content of the table only after it downloads the entire html for that table. The issue will blow out when we have a main table which wraps the entire content of the page, and when we have lots of nested tables. For the 'flexible tables' (those without any fixed width), after downloading entire table tag, browser has to parse till the last row of the table to find out the width of each columns, then has to parse it again for displaying the content. Till all these happens users has to stare at a blank screen, then everything will come to screen in a tick.</p>\n" }, { "answer_id": 394955, "author": "datasn.io", "author_id": 49318, "author_profile": "https://Stackoverflow.com/users/49318", "pm_score": 0, "selected": false, "text": "<p>There definitely is. If you are still striving for it, you are not getting it right.</p>\n\n<p>DIV+CSS layout is actually much easier than table layout in terms of maintainability and productivity. Just keep practicing it before it's too early to say that.</p>\n\n<p>Table layout is good too it's just not meant for layouts and have exceptional drawbacks when it comes to minor tuning.</p>\n" } ]
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 case, if they allowed it, it would have to be safe for all cases.</p>\n\n<p>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 <em>unsafe</em> things if one knows how to deal with them.</p>\n\n<p>In C# .NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this:</p>\n\n<pre><code>public ClassName(...) : base(...)\n</code></pre>\n\n<p>in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.</p>\n" }, { "answer_id": 5357, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 1, "selected": false, "text": "<p>I don't know how Java is implemented internally, but if the constructor of the superclass throws an exception, then there isn't a instance of the class you extend. It would be impossible to call the <code>toString()</code> or <code>equals()</code> methods, for example, since they are inherited in most cases.</p>\n\n<p>Java may allow a try/catch around the super() call in the constructor if 1. you override ALL methods from the superclasses, and 2. you don't use the super.XXX() clause, but that all sounds too complicated to me.</p>\n" }, { "answer_id": 5360, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 1, "selected": false, "text": "<p>I can't presume to have a deep understanding of Java internals, but it is my understanding that, when a compiler needs to instantiate a derived class, it has to first create the base (and its base before that(...)) and then slap on the extensions made in the subclass. </p>\n\n<p>So it is not even the danger of uninited variables or anything like that at all. When you try to do something in the subclass' constructor <em>before</em> the base class' <strong>constructor</strong>, you are basically asking the compiler to extend a base object instance that doesn't exist yet.</p>\n\n<p>Edit:In your case, <strong>MyClass</strong> becomes the base object, and <strong>MyClassMock</strong> is a subclass.</p>\n" }, { "answer_id": 76957, "author": "Joshua", "author_id": 14768, "author_profile": "https://Stackoverflow.com/users/14768", "pm_score": 3, "selected": false, "text": "<p>It's done to prevent someone from creating a new <code>SecurityManager</code> object from untrusted code.</p>\n\n<pre><code>public class Evil : SecurityManager {\n Evil()\n {\n try {\n super();\n } catch { Throwable t }\n {\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 10261194, "author": "Edwin Dalorzo", "author_id": 697630, "author_profile": "https://Stackoverflow.com/users/697630", "pm_score": 3, "selected": false, "text": "<p>I know this is an old question, but I liked it, and as such, I decided to give it an answer of my own. Perhaps my understanding of why this cannot be done will contribute to the discussion and to future readers of your interesting question.</p>\n\n<p>Let me start with an example of failing object construction.</p>\n\n<p>Let's define a class A, such that:</p>\n\n<pre><code>class A {\n private String a = \"A\";\n\n public A() throws Exception {\n throw new Exception();\n }\n}\n</code></pre>\n\n<p>Now, let's assume we would like to create an object of type A in a <code>try...catch</code> block.</p>\n\n<pre><code>A a = null;\ntry{\n a = new A();\n}catch(Exception e) {\n //...\n}\nSystem.out.println(a);\n</code></pre>\n\n<p>Evidently, the output of this code will be: <code>null</code>.</p>\n\n<p>Why Java does not return a partially constructed version of <code>A</code>? After all, by the point the constructor fails, the object's <code>name</code> field has already been initialized, right?</p>\n\n<p>Well, Java can't return a partially constructed version of <code>A</code> because the object was not successfully built. The object is in a inconsistent state, and it is therefore discarded by Java. Your variable A is not even initialized, it is kept as null. </p>\n\n<p>Now, as you know, to fully build a new object, all its super classes must be initialized first. If one of the super classes failed to execute, what would be the final state of the object? It is impossible to determine that.</p>\n\n<p>Look at this more elaborate example</p>\n\n<pre><code>class A {\n private final int a;\n public A() throws Exception { \n a = 10;\n }\n}\n\nclass B extends A {\n private final int b;\n public B() throws Exception {\n methodThatThrowsException(); \n b = 20;\n }\n}\n\nclass C extends B {\n public C() throws Exception { super(); }\n}\n</code></pre>\n\n<p>When the constructor of <code>C</code> is invoked, if an exception occurs while initializing <code>B</code>, what would be the value of the final <code>int</code> variable <code>b</code>?</p>\n\n<p>As such, the object C cannot be created, it is bogus, it is trash, it is not fully initialized.</p>\n\n<p>For me, this explains why your code is illegal.</p>\n" }, { "answer_id": 22721701, "author": "aliteralmind", "author_id": 2736496, "author_profile": "https://Stackoverflow.com/users/2736496", "pm_score": -1, "selected": false, "text": "<p>One way to get around it is by calling a private static function. The try-catch can then be placed in the function body.</p>\n\n<pre><code>public class Test {\n public Test() {\n this(Test.getObjectThatMightThrowException());\n }\n public Test(Object o) {\n //...\n }\n private static final Object getObjectThatMightThrowException() {\n try {\n return new ObjectThatMightThrowAnException();\n } catch(RuntimeException rtx) {\n throw new RuntimeException(\"It threw an exception!!!\", rtx);\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 43454831, "author": "Kröw", "author_id": 5921170, "author_profile": "https://Stackoverflow.com/users/5921170", "pm_score": 0, "selected": false, "text": "<p>I know this question has numerous answers, but I'd like to give my little tidbit on why this wouldn't be allowed, specifically to answer why Java does not allow you to do this. So here you go...</p>\n\n<p>Now, keep in mind that <code>super()</code> has to be called before anything else in a subclass's constructor, so, if you did use <code>try</code> and <code>catch</code> blocks around your <code>super()</code> call, the blocks would have to look like this:</p>\n\n<pre><code>try {\n super();\n ...\n} catch (Exception e) {\n super(); //This line will throw the same error...\n ...\n}\n</code></pre>\n\n<p>If <code>super()</code> fails in the <code>try</code> block, it HAS to be executed first in the <code>catch</code> block, so that <code>super</code> runs before anything in your subclass`s constructor. This leaves you with the same problem you had at the beginning: if an exception is thrown, it isn't caught. (In this case it just gets thrown again in the catch block.)</p>\n\n<p>Now, the above code is in no way allowed by Java either. This code may execute half of the first super call, and then call it again, which could cause some problems with some super classes.</p>\n\n<p>Now, the reason that Java doesn't let you throw an exception <em>instead</em> of calling <code>super()</code> is because the exception could be caught somewhere else, and the program would continue <strong>without calling <code>super()</code> on your subclass object,</strong> and possibly because the exception could take your object as a parameter and try to change the value of inherited instance variables, which would not yet have been initialized.</p>\n" } ]
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 times when I <em>thought</em> that I'd already tried that. :D Oh, and I mistyped @myId in the first example, the code was actually $myId.</p>\n\n<pre><code>&lt;xsl:variable name=\"myId\" select=\"@id\" /&gt;\n&lt;xsl value-of select=\"//Root/Some/Other/Path/Where[@id=$myId]/@Name\" /&gt;\n</code></pre>\n" }, { "answer_id": 16386, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 3, "selected": false, "text": "<p>You seem to have got confused with use of a variable (which is just $variable) and Attribute Value Templates, which allow you to put any XPath expression in some attributes, e.g. </p>\n\n<pre><code>&lt;newElement Id=\"{@Id}\"/&gt;\n</code></pre>\n\n<p>They can obviously be combined, so you can include a variable in an Attribute Value Template, such as:</p>\n\n<pre><code>&lt;newElement Id=\"{$myId}\"/&gt;\n</code></pre>\n" } ]
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', b'\\xdb\\x0fI@')\n(3.1415927410125732,)\n&gt;&gt;&gt; struct.pack('4f', 1.0, 2.0, 3.0, 4.0)\n'\\x00\\x00\\x80?\\x00\\x00\\x00@\\x00\\x00@@\\x00\\x00\\x80@'\n</code></pre>\n" }, { "answer_id": 54168810, "author": "NDM", "author_id": 6585198, "author_profile": "https://Stackoverflow.com/users/6585198", "pm_score": 4, "selected": false, "text": "<p>Just a little addition, if you want a float number as output from the unpack method instead of a tuple just write</p>\n<pre><code>&gt;&gt;&gt; import struct\n&gt;&gt;&gt; [x] = struct.unpack('f', b'\\xdb\\x0fI@')\n&gt;&gt;&gt; x\n3.1415927410125732\n</code></pre>\n<p>If you have more floats then just write</p>\n<pre><code>&gt;&gt;&gt; import struct\n&gt;&gt;&gt; [x,y] = struct.unpack('ff', b'\\xdb\\x0fI@\\x0b\\x01I4')\n&gt;&gt;&gt; x\n3.1415927410125732\n&gt;&gt;&gt; y\n1.8719963179592014e-07\n&gt;&gt;&gt; \n</code></pre>\n" }, { "answer_id": 73420517, "author": "Chance Cuddeback", "author_id": 13674247, "author_profile": "https://Stackoverflow.com/users/13674247", "pm_score": 2, "selected": false, "text": "<p>I would add a comment but I don't have enough reputation.</p>\n<p>Just to add some info. If you have a byte buffer containing X amount of floats, the syntax for unpacking would be:</p>\n<pre><code>struct.unpack('Xf', ...)\n</code></pre>\n<p>If the values are doubles the unpacking would be:</p>\n<pre><code>struct.unpack('Xd', ...)\n</code></pre>\n" } ]
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<hr>\n\n<p>Here is a page that details the problem and a solution (search the page for the text <em>Wrapping sys.stdout into an instance</em>):</p>\n\n<p><a href=\"http://wiki.python.org/moin/PrintFails\" rel=\"noreferrer\">PrintFails - Python Wiki</a></p>\n\n<p>Here's a code excerpt from that page:</p>\n\n<pre><code>$ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \\\n sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \\\n line = u\"\\u0411\\n\"; print type(line), len(line); \\\n sys.stdout.write(line); print line'\n UTF-8\n &lt;type 'unicode'&gt; 2\n Б\n Б\n\n $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \\\n sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \\\n line = u\"\\u0411\\n\"; print type(line), len(line); \\\n sys.stdout.write(line); print line' | cat\n None\n &lt;type 'unicode'&gt; 2\n Б\n Б\n</code></pre>\n\n<p>There's some more information on that page, well worth a read.</p>\n" }, { "answer_id": 8020, "author": "Bartosz Radaczyński", "author_id": 985, "author_profile": "https://Stackoverflow.com/users/985", "pm_score": 1, "selected": false, "text": "<p>The cause of your problem is <strong>NOT</strong> the Win console not willing to accept Unicode (as it does this since I guess Win2k by default). It is the default system encoding. Try this code and see what it gives you:</p>\n<pre><code>import sys\nsys.getdefaultencoding()\n</code></pre>\n<p>if it says ascii, there's your cause ;-)\nYou have to create a file called sitecustomize.py and put it under python path (I put it under /usr/lib/python2.5/site-packages, but that is differen on Win - it is c:\\python\\lib\\site-packages or something), with the following contents:</p>\n<pre><code>import sys\nsys.setdefaultencoding('utf-8')\n</code></pre>\n<p>and perhaps you might want to specify the encoding in your files as well:</p>\n<pre><code># -*- coding: UTF-8 -*-\nimport sys,time\n</code></pre>\n<p>Edit: more info can be found <a href=\"http://web.archive.org/web/20120315050914/http://www.diveintopython.net/xml_processing/unicode.html\" rel=\"nofollow noreferrer\">in excellent the Dive into Python book</a></p>\n" }, { "answer_id": 2013263, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 3, "selected": false, "text": "<p>The below code will make Python output to console as UTF-8 even on Windows. </p>\n\n<p>The console will display the characters well on Windows 7 but on Windows XP it will not display them well, but at least it will work and most important you will have a consistent output from your script on all platforms. You'll be able to redirect the output to a file.</p>\n\n<p>Below code was tested with Python 2.6 on Windows.</p>\n\n<pre><code>\n#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport codecs, sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\nprint sys.getdefaultencoding()\n\nif sys.platform == 'win32':\n try:\n import win32console \n except:\n print \"Python Win32 Extensions module is required.\\n You can download it from https://sourceforge.net/projects/pywin32/ (x86 and x64 builds are available)\\n\"\n exit(-1)\n # win32console implementation of SetConsoleCP does not return a value\n # CP_UTF8 = 65001\n win32console.SetConsoleCP(65001)\n if (win32console.GetConsoleCP() != 65001):\n raise Exception (\"Cannot set console codepage to 65001 (UTF-8)\")\n win32console.SetConsoleOutputCP(65001)\n if (win32console.GetConsoleOutputCP() != 65001):\n raise Exception (\"Cannot set console output codepage to 65001 (UTF-8)\")\n\n#import sys, codecs\nsys.stdout = codecs.getwriter('utf8')(sys.stdout)\nsys.stderr = codecs.getwriter('utf8')(sys.stderr)\n\nprint \"This is an Е乂αmp١ȅ testing Unicode support using Arabic, Latin, Cyrillic, Greek, Hebrew and CJK code points.\\n\"\n</code></pre>\n" }, { "answer_id": 4637795, "author": "Daira Hopwood", "author_id": 393146, "author_profile": "https://Stackoverflow.com/users/393146", "pm_score": 5, "selected": false, "text": "<p><strong>Update:</strong> On Python 3.6 or later, printing Unicode strings to the console on Windows just works.</p>\n<p>So, upgrade to recent Python and you're done. At this point I recommend using 2to3 to update your code to Python 3.x if needed, and just dropping support for Python 2.x. Note that there has been no security support for any version of Python before 3.7 (including Python 2.7) <a href=\"https://endoflife.date/python\" rel=\"nofollow noreferrer\">since December 2021</a>.</p>\n<p>If you <em>really</em> still need to support earlier versions of Python (including Python 2.7), you can use <a href=\"https://github.com/Drekin/win-unicode-console\" rel=\"nofollow noreferrer\">https://github.com/Drekin/win-unicode-console</a> , which is based on, and uses the same APIs as the code in the answer that was <a href=\"https://stackoverflow.com/a/3259271/393146\">previously linked here</a>. (That link does include some information on Windows font configuration but I doubt it still applies to Windows 8 or later.)</p>\n<p>Note: despite other plausible-sounding answers that suggest changing the code page to 65001, that <a href=\"https://github.com/python/cpython/issues/45943\" rel=\"nofollow noreferrer\">did not work prior to Python 3.8</a>. (It does kind-of work since then, but as pointed out above, you don't need to do so for Python 3.6+ anyway.) Also, changing the default encoding using <code>sys.setdefaultencoding</code> is (still) <a href=\"https://stackoverflow.com/questions/3578685/how-to-display-utf-8-in-windows-console/3580165#3580165\">not a good idea</a>.</p>\n" }, { "answer_id": 10667978, "author": "Giampaolo Rodolà", "author_id": 376587, "author_profile": "https://Stackoverflow.com/users/376587", "pm_score": 4, "selected": false, "text": "<p>If you're not interested in getting a reliable representation of the bad character(s) you might use something like this (working with python >= 2.6, including 3.x):</p>\n\n<pre><code>from __future__ import print_function\nimport sys\n\ndef safeprint(s):\n try:\n print(s)\n except UnicodeEncodeError:\n if sys.version_info &gt;= (3,):\n print(s.encode('utf8').decode(sys.stdout.encoding))\n else:\n print(s.encode('utf8'))\n\nsafeprint(u\"\\N{EM DASH}\")\n</code></pre>\n\n<p>The bad character(s) in the string will be converted in a representation which is printable by the Windows console.</p>\n" }, { "answer_id": 32176732, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": false, "text": "<p><strong>Update:</strong> <a href=\"https://docs.python.org/3.6/whatsnew/3.6.html#pep-528-change-windows-console-encoding-to-utf-8\" rel=\"noreferrer\">Python 3.6</a> implements <a href=\"https://www.python.org/dev/peps/pep-0528/\" rel=\"noreferrer\">PEP 528: Change Windows console encoding to UTF-8</a>: <em>the default console on Windows will now accept all Unicode characters.</em> Internally, it uses the same Unicode API as <a href=\"https://github.com/Drekin/win-unicode-console\" rel=\"noreferrer\">the <code>win-unicode-console</code> package mentioned below</a>. <code>print(unicode_string)</code> should just work now.</p>\n<hr />\n<blockquote>\n<p>I get a <code>UnicodeEncodeError: 'charmap' codec can't encode character...</code> error.</p>\n</blockquote>\n<p>The error means that Unicode characters that you are trying to print can't be represented using the current (<code>chcp</code>) console character encoding. The codepage is often 8-bit encoding such as <code>cp437</code> that can represent only ~0x100 characters from ~1M Unicode characters:</p>\n<pre>>>> u\"\\N{EURO SIGN}\".encode('cp437')\nTraceback (most recent call last):\n...\nUnicodeEncodeError: 'charmap' codec can't encode character '\\u20ac' in position 0:\ncharacter maps to </pre>\n<blockquote>\n<p>I assume this is because the Windows console does not accept Unicode-only characters. What's the best way around this?</p>\n</blockquote>\n<p>Windows console does accept Unicode characters and it can even display them (BMP only) <strong>if the corresponding font is configured</strong>. <code>WriteConsoleW()</code> API should be used as suggested in <a href=\"https://stackoverflow.com/a/4637795/4279\">@Daira Hopwood's answer</a>. It can be called transparently i.e., you don't need to and should not modify your scripts if you use <a href=\"https://github.com/Drekin/win-unicode-console\" rel=\"noreferrer\"><code>win-unicode-console</code> package</a>:</p>\n<pre><code>T:\\&gt; py -m pip install win-unicode-console\nT:\\&gt; py -m run your_script.py\n</code></pre>\n<p>See <a href=\"https://stackoverflow.com/a/30551552/4279\">What's the deal with Python 3.4, Unicode, different languages and Windows?</a></p>\n<blockquote>\n<p>Is there any way I can make Python\nautomatically print a <code>?</code> instead of failing in this situation?</p>\n</blockquote>\n<p>If it is enough to replace all unencodable characters with <code>?</code> in your case then you could set <a href=\"https://docs.python.org/3/using/cmdline.html#envvar-PYTHONIOENCODING\" rel=\"noreferrer\"><code>PYTHONIOENCODING</code> envvar</a>:</p>\n<pre><code>T:\\&gt; set PYTHONIOENCODING=:replace\nT:\\&gt; python3 -c &quot;print(u'[\\N{EURO SIGN}]')&quot;\n[?]\n</code></pre>\n<p>In Python 3.6+, the encoding specified by <code>PYTHONIOENCODING</code> envvar is ignored for interactive console buffers unless <code>PYTHONLEGACYWINDOWSIOENCODING</code> envvar is set to a non-empty string.</p>\n" }, { "answer_id": 34306583, "author": "Kinjal Dixit", "author_id": 6629, "author_profile": "https://Stackoverflow.com/users/6629", "pm_score": 2, "selected": false, "text": "<p>Kind of related on the answer by J. F. Sebastian, but more direct.</p>\n\n<p>If you are having this problem when printing to the console/terminal, then do this:</p>\n\n<pre><code>&gt;set PYTHONIOENCODING=UTF-8\n</code></pre>\n" }, { "answer_id": 35903736, "author": "mike rodent", "author_id": 595305, "author_profile": "https://Stackoverflow.com/users/595305", "pm_score": 3, "selected": false, "text": "<p>Like Giampaolo Rodolà's answer, but even more dirty: I really, really intend to spend a long time (soon) understanding the whole subject of encodings and how they apply to Windoze consoles, </p>\n\n<p>For the moment I just wanted sthg which would mean my program would NOT CRASH, and which I understood ... and also which didn't involve importing too many exotic modules (in particular I'm using Jython, so half the time a Python module turns out not in fact to be available).</p>\n\n<pre><code>def pr(s):\n try:\n print(s)\n except UnicodeEncodeError:\n for c in s:\n try:\n print( c, end='')\n except UnicodeEncodeError:\n print( '?', end='')\n</code></pre>\n\n<p>NB \"pr\" is shorter to type than \"print\" (and quite a bit shorter to type than \"safeprint\")...!</p>\n" }, { "answer_id": 37229972, "author": "CODE-REaD", "author_id": 5025060, "author_profile": "https://Stackoverflow.com/users/5025060", "pm_score": -1, "selected": false, "text": "<p>James Sulak asked,</p>\n\n<blockquote>\n <p>Is there any way I can make Python automatically print a ? instead of failing in this situation?</p>\n</blockquote>\n\n<p>Other solutions recommend we attempt to modify the Windows environment or replace Python's <code>print()</code> function. The answer below comes closer to fulfilling Sulak's request.</p>\n\n<p>Under Windows 7, Python 3.5 can be made to print Unicode without throwing a <code>UnicodeEncodeError</code> as follows:</p>\n\n<p>&nbsp; &nbsp; In place of:\n&nbsp; &nbsp;<code>print(text)</code><br>\n&nbsp; &nbsp; substitute:\n&nbsp; &nbsp; <code>print(str(text).encode('utf-8'))</code></p>\n\n<p>Instead of throwing an exception, Python now displays unprintable Unicode characters as <em>\\xNN</em> hex codes, e.g.:</p>\n\n<p>&nbsp; <em>Halmalo n\\xe2\\x80\\x99\\xc3\\xa9tait plus qu\\xe2\\x80\\x99un point noir</em></p>\n\n<p>Instead of</p>\n\n<p>&nbsp; <em>Halmalo n’était plus qu’un point noir</em></p>\n\n<p>Granted, the latter is preferable <em>ceteris paribus</em>, but otherwise the former is completely accurate for diagnostic messages. Because it displays Unicode as literal byte values the former may also assist in diagnosing encode/decode problems.</p>\n\n<p><strong>Note:</strong> The <code>str()</code> call above is needed because otherwise <code>encode()</code> causes Python to reject a Unicode character as a tuple of numbers.</p>\n" }, { "answer_id": 43924648, "author": "J. Does", "author_id": 7227370, "author_profile": "https://Stackoverflow.com/users/7227370", "pm_score": 1, "selected": false, "text": "<p>Python 3.6 windows7: There is several way to launch a python you could use the python console (which has a python logo on it) or the windows console (it's written cmd.exe on it). </p>\n\n<p>I could not print utf8 characters in the windows console. Printing utf-8 characters throw me this error:</p>\n\n<pre><code>OSError: [winError 87] The paraneter is incorrect \nException ignored in: (_io-TextIOwrapper name='(stdout)' mode='w' ' encoding='utf8') \nOSError: [WinError 87] The parameter is incorrect \n</code></pre>\n\n<p>After trying and failing to understand the answer above I discovered it was only a setting problem. Right click on the top of the cmd console windows, on the tab <code>font</code> chose lucida console.</p>\n" }, { "answer_id": 45868162, "author": "shubaly", "author_id": 7269358, "author_profile": "https://Stackoverflow.com/users/7269358", "pm_score": 2, "selected": false, "text": "<p>For Python 2 try:</p>\n\n<pre><code>print unicode(string, 'unicode-escape')\n</code></pre>\n\n<p>For Python 3 try:</p>\n\n<pre><code>import os\nstring = \"002 Could've Would've Should've\"\nos.system('echo ' + string)\n</code></pre>\n\n<p>Or try win-unicode-console:</p>\n\n<pre><code>pip install win-unicode-console\npy -mrun your_script.py\n</code></pre>\n" }, { "answer_id": 51124805, "author": "Matthew Estock", "author_id": 2133918, "author_profile": "https://Stackoverflow.com/users/2133918", "pm_score": 2, "selected": false, "text": "<p>TL;DR:</p>\n<pre><code>print(yourstring.encode('ascii','replace').decode('ascii'))\n</code></pre>\n<hr />\n<p>I ran into this myself, working on a Twitch chat (IRC) bot. (Python 2.7 latest)</p>\n<p>I wanted to parse chat messages in order to respond...</p>\n<pre><code>msg = s.recv(1024).decode(&quot;utf-8&quot;)\n</code></pre>\n<p>but also print them safely to the console in a human-readable format:</p>\n<pre><code>print(msg.encode('ascii','replace').decode('ascii'))\n</code></pre>\n<p>This corrected the issue of the bot throwing <code>UnicodeEncodeError: 'charmap'</code> errors and replaced the unicode characters with <code>?</code>.</p>\n" }, { "answer_id": 52617143, "author": "c97", "author_id": 397961, "author_profile": "https://Stackoverflow.com/users/397961", "pm_score": 3, "selected": false, "text": "<p>Just enter this code in command line before executing python script:</p>\n\n<pre><code>chcp 65001 &amp; set PYTHONIOENCODING=utf-8\n</code></pre>\n" }, { "answer_id": 68507839, "author": "Itachi", "author_id": 1831784, "author_profile": "https://Stackoverflow.com/users/1831784", "pm_score": -1, "selected": false, "text": "<p>The issue is with windows default encoding being set to cp1252, and need to be set to utf-8. (<a href=\"https://discuss.python.org/t/pep-597-use-utf-8-for-default-text-file-encoding/1819\" rel=\"nofollow noreferrer\">check PEP</a>)</p>\n<p>Check default encoding using:</p>\n<pre><code>import locale \nlocale.getpreferredencoding()\n</code></pre>\n<p>You can override locale settings</p>\n<pre><code>import os\nif os.name == &quot;nt&quot;:\n import _locale\n _locale._gdl_bak = _locale._getdefaultlocale\n _locale._getdefaultlocale = (lambda *args: (_locale._gdl_bak()[0], 'utf8'))\n</code></pre>\n<p>referenced code from <a href=\"https://stackoverflow.com/questions/31469707/changing-the-locale-preferred-encoding-in-python-3-in-windows/34345136#34345136\">stack link</a></p>\n" }, { "answer_id": 74509356, "author": "Wok", "author_id": 376454, "author_profile": "https://Stackoverflow.com/users/376454", "pm_score": 0, "selected": false, "text": "<p>Nowadays, the Windows console does not encounter this error, <strong>unless you redirect the output</strong>.</p>\n<p>Here is an example Python script <code>scratch_1.py</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>s = &quot;∞&quot;\n\nprint(s)\n</code></pre>\n<p>If you run the script as follows, everything works as intended:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>python scratch_1.py\n</code></pre>\n<pre><code>∞\n</code></pre>\n<p>However, if you run the following, then you get the same error as in the question:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>python scratch_1.py &gt; temp.txt\n</code></pre>\n<pre><code>Traceback (most recent call last):\n File &quot;C:\\Users\\Wok\\AppData\\Roaming\\JetBrains\\PyCharmCE2022.2\\scratches\\scratch_1.py&quot;, line 3, in &lt;module&gt;\n print(s)\n File &quot;C:\\Users\\Wok\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\encodings\\cp1252.py&quot;, line 19, in encode\n return codecs.charmap_encode(input,self.errors,encoding_table)[0]\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nUnicodeEncodeError: 'charmap' codec can't encode character '\\u221e' in position 0: character maps to &lt;undefined&gt;\n</code></pre>\n<hr />\n<p>To solve this issue with the suggestion present in the original question, i.e. by replacing the erroneous characters with question marks <code>?</code>, one can proceed as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>s = &quot;∞&quot;\n\ntry:\n print(s)\nexcept UnicodeEncodeError:\n output_str = s.encode(&quot;ascii&quot;, errors=&quot;replace&quot;).decode(&quot;ascii&quot;)\n\n print(output_str)\n</code></pre>\n<p>It is important:</p>\n<ul>\n<li>to call <code>decode()</code>, so that the type of the output is <code>str</code> instead of <code>bytes</code>,</li>\n<li>with the same encoding, here <code>&quot;ascii&quot;</code>, to avoid the creation of <a href=\"https://en.wikipedia.org/wiki/Mojibake\" rel=\"nofollow noreferrer\">mojibake</a>.</li>\n</ul>\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>\n\n<blockquote>\n <p>For compatibility, the string \"--\"\n (double-hyphen) MUST NOT occur within\n comments.</p>\n</blockquote>\n" }, { "answer_id": 5596, "author": "Lance Fisher", "author_id": 571, "author_profile": "https://Stackoverflow.com/users/571", "pm_score": 2, "selected": false, "text": "<p>If you really want to keep the comment in your page you could use this instead of an HTML comment:</p>\n\n<pre><code>&lt;div style=\"display:none\"&gt;command --option value --option2 value2 --option3 &lt;/div&gt;\n</code></pre>\n\n<p>Or even </p>\n\n<pre><code>&lt;div class=\"comment\"&gt;command --option value --option2 value2 --option3 &lt;/div&gt;\n</code></pre>\n\n<p>and specify:</p>\n\n<pre><code>.comment {display:none;}\n</code></pre>\n\n<p>in your stylesheet.</p>\n" }, { "answer_id": 5632, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>Comments at the top of the page before <code>&lt;html&gt;</code> will throw IE into quirks mode, which could explain why the page breaks, if that's where your comment appears.</p>\n\n<p>For more information, check out the \"Triggering different rendering modes\" on <a href=\"http://en.wikipedia.org/wiki/Quirks_mode\" rel=\"nofollow noreferrer\">this wikipedia page</a></p>\n" } ]
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 say it's pretty pointless.</p>\n\n<p>If you want to use the original definition of it, it might make more sense, but other than that it is mostly syntactic sugar.</p>\n\n<p>If you read the <a href=\"http://en.wikipedia.org/wiki/Hungarian_notation\" rel=\"noreferrer\">Wikipedia article</a> on the subject, you'll find two conflicting notations, <em>Systems Hungarian Notation</em> and <em>Apps Hungarian Notation</em>.</p>\n\n<p>The original, good, definition is the <em>Apps Hungarian Notation</em>, but most people use the <em>Systems Hungarian Notation</em>.</p>\n\n<p>As an example of the two, consider prefixing variables with l for length, a for area and v for volume.</p>\n\n<p>With such notation, the following expression makes sense:</p>\n\n<pre><code>int vBox = aBottom * lVerticalSide;\n</code></pre>\n\n<p>but this doesn't:</p>\n\n<pre><code>int aBottom = lSide1;\n</code></pre>\n\n<p>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.</p>\n\n<p>Unfortunately, the other notation is less useful, where people prefix the variable names with the type of the value, like this:</p>\n\n<pre><code>int iLength;\nint iVolume;\nint iArea;\n</code></pre>\n\n<p>some people use n for number, or i for integer, f for float, s for string etc.</p>\n\n<p>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.</p>\n\n<p>But, you should make up your own mind. All I can say is that I don't use either.</p>\n\n<hr>\n\n<p><strong>Edit</strong> Just to add a short notice, while I don't use <em>Hungarian Notation</em>, 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.</p>\n" }, { "answer_id": 5440, "author": "Steve Willard", "author_id": 402, "author_profile": "https://Stackoverflow.com/users/402", "pm_score": 0, "selected": false, "text": "<p>I've been working for IBM for the past 6 months and I haven't seen it anywhere (thank god because I hate it.) I see either camelCase or c_style.</p>\n\n<pre><code>thisMethodIsPrettyCool()\nthis_method_is_pretty_cool()\n</code></pre>\n" }, { "answer_id": 5443, "author": "Ray", "author_id": 233, "author_profile": "https://Stackoverflow.com/users/233", "pm_score": 0, "selected": false, "text": "<p>It depends on your language and environment. As a rule I wouldn't use it, unless the development environment you're in makes it hard to find the type of the variable.</p>\n\n<p>There's also two different types of Hungarian notation. See Joel's article. I can't find it (his names don't exactly make them easy to find), anyone have a link to the one I mean?</p>\n\n<p>Edit: Wedge has the article I mean in his post.</p>\n" }, { "answer_id": 5445, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 3, "selected": false, "text": "<p>It is pointless (and distracting) but is in relatively heavy use at my company, at least for types like ints, strings, booleans, and doubles.</p>\n\n<p>Things like <code>sValue</code>, <code>iCount</code>, <code>dAmount</code> or <code>fAmount</code>, and <code>bFlag</code> are everywhere.</p>\n\n<p>Once upon a time there was a good reason for this convention. Now, it is a cancer.</p>\n" }, { "answer_id": 5451, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": false, "text": "<p>I think hungarian notation is an interesting footnote along the 'path' to more readable code, and if done properly, is preferable to not-doing it.</p>\n\n<p>In saying that though, I'd rather do away with it, and instead of this:</p>\n\n<pre><code>int vBox = aBottom * lVerticalSide;\n</code></pre>\n\n<p>write this:</p>\n\n<pre><code>int boxVolume = bottomArea * verticalHeight;\n</code></pre>\n\n<p>It's 2008. We don't have 80 character fixed width screens anymore! </p>\n\n<p>Also, if you're writing variable names which are much longer than that you should be looking at refactoring into objects or functions anyway.</p>\n" }, { "answer_id": 5456, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 5, "selected": false, "text": "<p>The Hungarian Naming Convention can be useful when used correctly, unfortunately it tends to be misused more often than not.</p>\n\n<p>Read Joel Spolsky's article <a href=\"http://www.joelonsoftware.com/articles/Wrong.html\" rel=\"noreferrer\">Making Wrong Code Look Wrong</a> for appropriate perspective and justification.</p>\n\n<p>Essentially, type based Hungarian notation, where variables are prefixed with information about their type (e.g. whether an object is a string, a handle, an int, etc.) is mostly useless and generally just adds overhead with very little benefit. This, sadly, is the Hungarian notation most people are familiar with. However, the intent of Hungarian notation as envisioned is to add information on the \"kind\" of data the variable contains. This allows you to partition kinds of data from other kinds of data which shouldn't be allowed to be mixed together except, possibly, through some conversion process. For example, pixel based coordinates vs. coordinates in other units, or unsafe user input versus data from safe sources, etc.</p>\n\n<p>Look at it this way, if you find yourself spelunking through code to find out information on a variable then you probably need to adjust your naming scheme to contain that information, this is the essence of the Hungarian convention.</p>\n\n<p>Note that an alternative to Hungarian notation is to use more classes to show the intent of variable usage rather than relying on primitive types everywhere. For example, instead of having variable prefixes for unsafe user input, you can have simple string wrapper class for unsafe user input, and a separate wrapper class for safe data. This has the advantage, in strongly typed languages, of having partitioning enforced by the compiler (even in less strongly typed languages you can usually add your own tripwire code) but adds a not insignificant amount of overhead.</p>\n" }, { "answer_id": 5557, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 4, "selected": false, "text": "<p>I still use Hungarian Notation when it comes to UI elements, where several UI elements are related to a particular object/value, e.g.,</p>\n\n<p>lblFirstName for the label object, txtFirstName for the text box. I definitely can't name them both \"FirstName\" even if <em>that</em> is the concern/responsibility of both objects.</p>\n\n<p>How do others approach naming UI elements?</p>\n" }, { "answer_id": 5721, "author": "Jonas Follesø", "author_id": 1199387, "author_profile": "https://Stackoverflow.com/users/1199387", "pm_score": 1, "selected": false, "text": "<p>I use Hungarian Naming for UI elements like buttons, textboxes and lables. The main benefit is grouping in the Visual Studio Intellisense Popup. If I want to access my lables, I simply start typing lbl.... and Visual Studio will suggest all my lables, nicley grouped together.</p>\n\n<p>However, after doing more and more Silverlight and WPF stuff, leveraging data binding, I don't even name all my controls anymore, since I don't have to reference them from code-behind (since there really isn't any codebehind anymore ;)</p>\n" }, { "answer_id": 10047, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": false, "text": "<p>Sorry to follow up with a question, but does prefixing interfaces with \"I\" qualify as hungarian notation? If that is the case, then yes, a lot of people are using it in the real world. If not, ignore this.</p>\n" }, { "answer_id": 10099, "author": "ColinYounger", "author_id": 1223, "author_profile": "https://Stackoverflow.com/users/1223", "pm_score": 1, "selected": false, "text": "<p>What's wrong is mixing standards. </p>\n\n<p>What's right is making sure that everyone does the same thing.</p>\n\n<pre><code>int Box = iBottom * nVerticleSide\n</code></pre>\n" }, { "answer_id": 30175, "author": "Will", "author_id": 3234, "author_profile": "https://Stackoverflow.com/users/3234", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>The original prefix was meant to be\n used to spot problems in equations,\n but has somehow devolved into making\n the code slightly easier to read since\n you don't have to go look for the\n variable declaration. With todays\n smart editors where you can simply\n hover over any variable to find the\n full type, and not just an\n abbreviation for it, this type of\n hungarian notation has lost a lot of\n its meaning.</p>\n</blockquote>\n\n<p>I'm breaking the habit a little bit but prefixing with the type can be useful in JavaScript that doesn't have strong variable typing. </p>\n" }, { "answer_id": 30236, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": 0, "selected": false, "text": "<p>Original form (The Right Hungarian Notation :) ) where prefix means type (i.e. length, quantity) of value stored by variable is OK, but not necessary in all type of applications.</p>\n\n<p>The popular form (The Wrong Hungarian Notation) where prefix means type (String, int) is useless in most of modern programming languages. </p>\n\n<p>Especially with meaningless names like strA. I can't understand we people use meaningless names with long prefixes which gives nothing.</p>\n" }, { "answer_id": 30256, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "<p>When using a dynamically typed language, I occasionally use Apps Hungarian. For statically typed languages I don't. See my explanation <a href=\"https://stackoverflow.com/questions/26086/how-do-you-make-wrong-code-look-wrong-what-patterns-do-you-use-to-avoid-semanti#26174\">in the other thread</a>.</p>\n" }, { "answer_id": 53101, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "<p>When I see Hungarian discussion, I'm glad to see people thinking hard about how to make their code clearer, and how to mistakes more visible. That's exactly what we should all be doing!</p>\n\n<p>But don't forget that you have some powerful tools at your disposal besides naming. </p>\n\n<p><strong>Extract Method</strong> If your methods are getting so long that your variable declarations have scrolled off the top of the screen, consider making your methods smaller. (If you have too many methods, consider a new class.) </p>\n\n<p><strong>Strong typing</strong> If you find that you are taking <em>zip code</em>s stored in an integer variable and assigning them to a <em>shoe size</em> integer variable, consider making a class for zip codes and a class for shoe size. Then your bug will be caught at compile time, instead of requiring careful inspection by a human. When I do this, I usually find a bunch of zip code- and shoe size-specific logic that I've peppered around my code, which I can then move in to my new classes. Suddenly all my code gets clearer, simpler, and protected from certain classes of bugs. Wow.</p>\n\n<p>To sum up: yes, think hard about how you use names in code to express your ideas clearly, but also look to the other powerful OO tools you can call on.</p>\n" }, { "answer_id": 53159, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I use type based (Systems HN) for components (eg editFirstName, lblStatus etc) as it makes autocomplete work better. </p>\n\n<p>I sometimes use App HN for variables where the type infomation is isufficient. Ie fpX indicates a fixed pointed variable (int type, but can't be mixed and matched with an int), rawInput for user strings that haven't been validated etc</p>\n" }, { "answer_id": 79628, "author": "James Wulkan", "author_id": 12384, "author_profile": "https://Stackoverflow.com/users/12384", "pm_score": 3, "selected": false, "text": "<p>I see Hungarian Notation as a way to circumvent the capacity of our short term memories. According to psychologists, we can store approximately <strong><a href=\"http://psychclassics.yorku.ca/Miller/\" rel=\"noreferrer\">7 plus-or-minus 2 chunks</a></strong> of information. The extra information added by including a prefix helps us by providing more details about the meaning of an identifier even with no other context. In other words, we can guess what a variable is for without seeing how it is used or declared. This can be avoided by applying oo techniques such as <a href=\"http://en.wikipedia.org/wiki/Encapsulation_(classes_-_computers)\" rel=\"noreferrer\">encapsulation</a> and the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"noreferrer\">single responsibility principle</a>.</p>\n\n<p>I'm unaware of whether or not this has been studied empirically. I would hypothesize that the amount of effort increases dramatically when we try to understand classes with more than nine instance variables or methods with more than 9 local variables.</p>\n" }, { "answer_id": 107654, "author": "titanae", "author_id": 2387, "author_profile": "https://Stackoverflow.com/users/2387", "pm_score": 2, "selected": false, "text": "<p>Isn't scope more important than type these days, e.g.</p>\n\n<ul>\n<li>l for local</li>\n<li>a for argument</li>\n<li>m for member</li>\n<li>g for global</li>\n<li>etc</li>\n</ul>\n\n<p>With modern techniques of refactoring old code, search and replace of a symbol because you changed its type is tedious, the compiler will catch type changes, but often will not catch incorrect use of scope, sensible naming conventions help here. </p>\n" }, { "answer_id": 233586, "author": "AgentThirteen", "author_id": 26199, "author_profile": "https://Stackoverflow.com/users/26199", "pm_score": 2, "selected": false, "text": "<p>I don't use a very strict sense of hungarian notation, but I do find myself using it sparing for some common custom objects to help identify them, and also I tend to prefix gui control objects with the type of control that they are. For example, labelFirstName, textFirstName, and buttonSubmit.</p>\n" }, { "answer_id": 907212, "author": "Jason Williams", "author_id": 97385, "author_profile": "https://Stackoverflow.com/users/97385", "pm_score": 1, "selected": false, "text": "<p>Hungarian notation is pointless in type-safe languages. e.g. A common prefix you will see in old Microsoft code is \"lpsz\" which means \"long pointer to a zero-terminated string\". Since the early 1700's we haven't used segmented architectures where short and long pointers exist, the normal string representation in C++ is always zero-terminated, and the compiler is type-safe so won't let us apply non-string operations to the string. Therefore none of this information is of any real use to a programmer - it's just more typing.</p>\n\n<p>However, I use a similar idea: prefixes that clarify the <strong>usage</strong> of a variable.\nThe main ones are:</p>\n\n<ul>\n<li>m = member</li>\n<li>c = const</li>\n<li>s = static</li>\n<li>v = volatile</li>\n<li>p = pointer (and pp=pointer to pointer, etc)</li>\n<li>i = index or iterator</li>\n</ul>\n\n<p>These can be combined, so a static member variable which is a pointer would be \"mspName\".</p>\n\n<p>Where are these useful?</p>\n\n<ul>\n<li>Where the usage is important, it is a good idea to constantly remind the programmer that a variable is (e.g.) a volatile or a pointer</li>\n<li>Pointer dereferencing used to do my head in until I used the p prefix. Now it's really easy to know when you have an object (Orange) a pointer to an object (pOrange) or a pointer to a pointer to an object (ppOrange). To dereference an object, just put an asterisk in front of it for each p in its name. Case solved, no more deref bugs!</li>\n<li>In constructors I usually find that a parameter name is identical to a member variable's name (e.g. size). I prefer to use \"mSize = size;\" than \"size = theSize\" or \"this.size = size\". It is also much safer: I don't accidentally use \"size = 1\" (setting the parameter) when I meant to say \"mSize = 1\" (setting the member)</li>\n<li>In loops, my iterator variables are all meaningful names. Most programmers use \"i\" or \"index\" and then have to make up new meaningless names (\"j\", \"index2\") when they want an inner loop. I use a meaningful name with an i prefix (iHospital, iWard, iPatient) so I always know what an iterator is iterating.</li>\n<li>In loops, you can mix several related variables by using the same base name with different prefixes: Orange orange = pOrange[iOrange]; This also means you don't make array indexing errors (pApple[i] looks ok, but write it as pApple[iOrange] and the error is immediately obvious).</li>\n<li>Many programmers will use my system without knowing it: by add a lengthy suffix like \"Index\" or \"Ptr\" - there isn't any good reason to use a longer form than a single character IMHO, so I use \"i\" and \"p\". Less typing, more consistent, easier to read.</li>\n</ul>\n\n<p>This is a simple system which adds meaningful and useful information to code, and eliminates the possibility of many simple but common programming mistakes.</p>\n" }, { "answer_id": 1371123, "author": "Joshua K", "author_id": 139609, "author_profile": "https://Stackoverflow.com/users/139609", "pm_score": 0, "selected": false, "text": "<p>Being a PHP programmer where it's very loosely typed, I don't make a point to use it. However I will occasionally identify something as an array or as an object depending on the size of the system and the scope of the variable.</p>\n" } ]
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 const CONSTANT = 'Const var';\n}\n\n$classname = 'MyClass';\necho eval( 'return '.$classname.'::CONSTANT;' );\n?&gt;\n</code></pre>\n\n<p>But, if i were you, I'd try not to use eval.</p>\n" }, { "answer_id": 19601, "author": "AdamTheHutt", "author_id": 1103, "author_profile": "https://Stackoverflow.com/users/1103", "pm_score": 4, "selected": true, "text": "<p>You can accomplish this without using <a href=\"http://php.net/manual/en/function.eval.php\" rel=\"nofollow noreferrer\"><code>eval</code></a> in pre-5.3 code. Just use the <a href=\"http://php.net/manual/en/function.constant.php\" rel=\"nofollow noreferrer\"><code>constant</code></a> function:</p>\n\n<pre><code>&lt;?php\n\nclass MyClass\n{\n const CONSTANT = 'Const var';\n}\n\n$classname = 'MyClass';\necho constant(\"$classname::CONSTANT\");\n\n?&gt;\n</code></pre>\n" } ]
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 reflog (<code>git reflog</code>) and then doing</p>\n<pre><code>git reset --hard &lt;sha1 of desired commit&gt;\n</code></pre>\n<p>But don't wait too long... after a few weeks git will eventually see that commit as unreferenced and delete all the blobs.</p>\n" }, { "answer_id": 21778, "author": "Brian Riehman", "author_id": 2063, "author_profile": "https://Stackoverflow.com/users/2063", "pm_score": 12, "selected": true, "text": "<p>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.</p>\n\n<pre><code>$ git init\nInitialized empty Git repository in .git/\n\n$ echo \"testing reset\" &gt; file1\n$ git add file1\n$ git commit -m 'added file1'\nCreated initial commit 1a75c1d: added file1\n 1 files changed, 1 insertions(+), 0 deletions(-)\n create mode 100644 file1\n\n$ echo \"added new file\" &gt; file2\n$ git add file2\n$ git commit -m 'added file2'\nCreated commit f6e5064: added file2\n 1 files changed, 1 insertions(+), 0 deletions(-)\n create mode 100644 file2\n\n$ git reset --hard HEAD^\nHEAD is now at 1a75c1d... added file1\n\n$ cat file2\ncat: file2: No such file or directory\n\n$ git reflog\n1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEAD\nf6e5064... HEAD@{1}: commit: added file2\n\n$ git reset --hard f6e5064\nHEAD is now at f6e5064... added file2\n\n$ cat file2\nadded new file\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 21873, "author": "sverrejoh", "author_id": 473, "author_profile": "https://Stackoverflow.com/users/473", "pm_score": 7, "selected": false, "text": "<p>It is possible to recover it if Git hasn't garbage collected yet.</p>\n\n<p>Get an overview of dangling commits with <code>fsck</code>:</p>\n\n<pre><code>$ git fsck --lost-found\ndangling commit b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf\n</code></pre>\n\n<p>Recover the dangling commit with rebase:</p>\n\n<pre><code>$ git rebase b72e67a9bb3f1fc1b64528bcce031af4f0d6fcbf\n</code></pre>\n" }, { "answer_id": 29469, "author": "Jörg W Mittag", "author_id": 2988, "author_profile": "https://Stackoverflow.com/users/2988", "pm_score": 5, "selected": false, "text": "<p>If you have not yet garbage collected your repository (e.g. using <code>git repack -d</code> or <code>git gc</code>, but note that garbage collection can also happen automatically), then your commit is still there – it's just no longer reachable through the HEAD.</p>\n\n<p>You can try to find your commit by looking through the output of <code>git fsck --lost-found</code>.</p>\n\n<p>Newer versions of Git have something called the \"reflog\", which is a log of all changes that are made to the refs (as opposed to changes that are made to the repository contents). So, for example, every time you switch your HEAD (i.e. every time you do a <code>git checkout</code> to switch branches) that will be logged. And, of course, your <code>git reset</code> also manipulated the HEAD, so it was also logged. You can access older states of your refs in a similar way that you can access older states of your repository, by using an <code>@</code> sign instead of a <code>~</code>, like <code>git reset HEAD@{1}</code>.</p>\n\n<p>It took me a while to understand what the difference is between HEAD@{1} and HEAD~1, so here is a little explanation:</p>\n\n<pre><code>git init\ngit commit --allow-empty -mOne\ngit commit --allow-empty -mTwo\ngit checkout -b anotherbranch\ngit commit --allow-empty -mThree\ngit checkout master # This changes the HEAD, but not the repository contents\ngit show HEAD~1 # =&gt; One\ngit show HEAD@{1} # =&gt; Three\ngit reflog\n</code></pre>\n\n<p>So, <code>HEAD~1</code> means \"go to the commit before the commit that HEAD currently points at\", while <code>HEAD@{1}</code> means \"go to the commit that HEAD pointed at before it pointed at where it currently points at\".</p>\n\n<p>That will easily allow you to find your lost commit and recover it.</p>\n" }, { "answer_id": 5127681, "author": "markmc", "author_id": 627058, "author_profile": "https://Stackoverflow.com/users/627058", "pm_score": 8, "selected": false, "text": "<p>The answer is hidden in the detailed response above, you can simply do:</p>\n\n<pre><code>$&gt; git reset --hard HEAD@{1}\n</code></pre>\n\n<p>(See the output of <em>git reflog show</em>)</p>\n" }, { "answer_id": 8844506, "author": "Chris", "author_id": 59198, "author_profile": "https://Stackoverflow.com/users/59198", "pm_score": 6, "selected": false, "text": "<p>If you're really lucky, like I was, you can go back into your text editor and hit 'undo'.</p>\n\n<p>I know that's not really a proper answer, but it saved me half a day's work so hopefully it'll do the same for someone else!</p>\n" }, { "answer_id": 11965255, "author": "Stian Høiland", "author_id": 659310, "author_profile": "https://Stackoverflow.com/users/659310", "pm_score": 5, "selected": false, "text": "<h2>Example of IRL case:</h2>\n\n<h3><code>$ git fsck --lost-found</code></h3>\n\n<pre><code>Checking object directories: 100% (256/256), done.\nChecking objects: 100% (3/3), done.\ndangling blob 025cab9725ccc00fbd7202da543f556c146cb119\ndangling blob 84e9af799c2f5f08fb50874e5be7fb5cb7aa7c1b\ndangling blob 85f4d1a289e094012819d9732f017c7805ee85b4\ndangling blob 8f654d1cd425da7389d12c17dd2d88d318496d98\ndangling blob 9183b84bbd292dcc238ca546dab896e073432933\ndangling blob 1448ee51d0ea16f259371b32a557b60f908d15ee\ndangling blob 95372cef6148d980ab1d7539ee6fbb44f5e87e22\ndangling blob 9b3bf9fb1ee82c6d6d5ec9149e38fe53d4151fbd\ndangling blob 2b21002ca449a9e30dbb87e535fbd4e65bac18f7\ndangling blob 2fff2f8e4ea6408ac84a8560477aa00583002e66\ndangling blob 333e76340b59a944456b4befd0e007c2e23ab37b\ndangling blob b87163c8def315d40721e592f15c2192a33816bb\ndangling blob c22aafb90358f6bf22577d1ae077ad89d9eea0a7\ndangling blob c6ef78dd64c886e9c9895e2fc4556e69e4fbb133\ndangling blob 4a71f9ff8262701171d42559a283c751fea6a201\ndangling blob 6b762d368f44ddd441e5b8eae6a7b611335b49a2\ndangling blob 724d23914b48443b19eada79c3eb1813c3c67fed\ndangling blob 749ffc9a412e7584245af5106e78167b9480a27b\ndangling commit f6ce1a403399772d4146d306d5763f3f5715cb5a &lt;- it's this one\n</code></pre>\n\n<h3><code>$ git show f6ce1a403399772d4146d306d5763f3f5715cb5a</code></h3>\n\n<pre><code>commit f6ce1a403399772d4146d306d5763f3f5715cb5a\nAuthor: Stian Gudmundsen Høiland &lt;[email protected]&gt;\nDate: Wed Aug 15 08:41:30 2012 +0200\n\n *MY COMMIT MESSAGE IS DISPLAYED HERE*\n\ndiff --git a/Some.file b/Some.file\nnew file mode 100644\nindex 0000000..15baeba\n--- /dev/null\n+++ b/Some.file\n*THE WHOLE COMMIT IS DISPLAYED HERE*\n</code></pre>\n\n<h3><code>$ git rebase f6ce1a403399772d4146d306d5763f3f5715cb5a</code></h3>\n\n<pre><code>First, rewinding head to replay your work on top of it...\nFast-forwarded master to f6ce1a403399772d4146d306d5763f3f5715cb5a.\n</code></pre>\n" }, { "answer_id": 21227533, "author": "martin", "author_id": 1725579, "author_profile": "https://Stackoverflow.com/users/1725579", "pm_score": 4, "selected": false, "text": "<p>I know this is an old thread... but as many people are searching for ways to undo stuff in Git, I still think it may be a good idea to continue giving tips here.</p>\n\n<p>When you do a \"git add\" or move anything from the top left to the bottom left in git gui the content of the file is stored in a blob and the file content is possible to recover from that blob. </p>\n\n<p>So it is possible to recover a file even if it was not committed but it has to have been added.</p>\n\n<pre><code>git init \necho hello &gt;&gt; test.txt \ngit add test.txt \n</code></pre>\n\n<p>Now the blob is created but it is referenced by the index so it will no be listed with git fsck until we reset. So we reset... </p>\n\n<pre><code>git reset --hard \ngit fsck \n</code></pre>\n\n<p>you will get a dangling blob ce013625030ba8dba906f756967f9e9ca394464a </p>\n\n<pre><code>git show ce01362 \n</code></pre>\n\n<p>will give you the file content \"hello\" back</p>\n\n<p>To find unreferenced commits I found a tip somewhere suggesting this. </p>\n\n<pre><code>gitk --all $(git log -g --pretty=format:%h) \n</code></pre>\n\n<p>I have it as a tool in git gui and it is very handy.</p>\n" }, { "answer_id": 22319764, "author": "neuron", "author_id": 461421, "author_profile": "https://Stackoverflow.com/users/461421", "pm_score": 3, "selected": false, "text": "<p>Made a tiny script to make it slightly easier to find the commit one is looking for:</p>\n\n<p><code>git fsck --lost-found | grep commit | cut -d ' ' -f 3 | xargs -i git show \\{\\} | egrep '^commit |Date:'</code></p>\n\n<p>Yes, it can be made considerably prettier with awk or something like it, but it's simple and I just needed it. Might save someone else 30 seconds.</p>\n" }, { "answer_id": 27990599, "author": "Ajedi32", "author_id": 1157054, "author_profile": "https://Stackoverflow.com/users/1157054", "pm_score": 6, "selected": false, "text": "<h1>In most cases, yes.</h1>\n\n<p>Depending on the state your repository was in when you ran the command, the effects of <code>git reset --hard</code> can range from trivial to undo, to basically impossible.</p>\n\n<p>Below I have listed a range of different possible scenarios, and how you might recover from them.</p>\n\n<h2>All my changes were committed, but now the commits are gone!</h2>\n\n<p>This situation usually occurs when you run <code>git reset</code> with an argument, as in <code>git reset --hard HEAD~</code>. Don't worry, this is easy to recover from!</p>\n\n<p>If you just ran <code>git reset</code> and haven't done anything else since, you can get back to where you were with this one-liner:</p>\n\n<pre><code>git reset --hard @{1}\n</code></pre>\n\n<p>This resets your current branch whatever state it was in before the last time it was modified (in your case, the most recent modification to the branch would be the hard reset you are trying to undo).</p>\n\n<p>If, however, you <em>have</em> made other modifications to your branch since the reset, the one-liner above won't work. Instead, you should run <a href=\"http://git-scm.com/docs/git-reflog\" rel=\"noreferrer\"><code>git reflog</code></a> <em><code>&lt;branchname&gt;</code></em> to see a list of all recent changes made to your branch (including resets). That list will look something like this:</p>\n\n<pre><code>7c169bd master@{0}: reset: moving to HEAD~\n3ae5027 master@{1}: commit: Changed file2\n7c169bd master@{2}: commit: Some change\n5eb37ca master@{3}: commit (initial): Initial commit\n</code></pre>\n\n<p>Find the operation in this list that you want to \"undo\". In the example above, it would be the first line, the one that says \"reset: moving to HEAD~\". Then copy the representation of the commit <em>before</em> (below) that operation. In our case, that would be <code>master@{1}</code> (or <code>3ae5027</code>, they both represent the same commit), and run <code>git reset --hard &lt;commit&gt;</code> to reset your current branch back to that commit. </p>\n\n<h2>I staged my changes with <code>git add</code>, but never committed. Now my changes are gone!</h2>\n\n<p>This is a bit trickier to recover from. git <em>does</em> have copies of the files you added, but since these copies were never tied to any particular commit you can't restore the changes all at once. Instead, you have to locate the individual files in git's database and restore them manually. You can do this using <a href=\"http://git-scm.com/docs/git-fsck\" rel=\"noreferrer\"><code>git fsck</code></a>.</p>\n\n<p>For details on this, see <a href=\"https://stackoverflow.com/q/7374069/1157054\">Undo git reset --hard with uncommitted files in the staging area</a>.</p>\n\n<h2>I had changes to files in my working directory that I never staged with <code>git add</code>, and never committed. Now my changes are gone!</h2>\n\n<p>Uh oh. I hate to tell you this, but you're probably out of luck. git doesn't store changes that you don't add or commit to it, and according to the <a href=\"http://git-scm.com/docs/git-reset\" rel=\"noreferrer\">documentation for <code>git reset</code></a>:</p>\n\n<blockquote>\n <p><strong>--hard</strong></p>\n \n <p>Resets the index and working tree. <strong>Any changes to tracked files in the working tree since <code>&lt;commit&gt;</code> are discarded.</strong></p>\n</blockquote>\n\n<p>It's possible that you <em>might</em> be able to recover your changes with some sort of disk recovery utility or a professional data recovery service, but at this point that's probably more trouble than it's worth.</p>\n" }, { "answer_id": 29408886, "author": "suhailvs", "author_id": 2351696, "author_profile": "https://Stackoverflow.com/users/2351696", "pm_score": 7, "selected": false, "text": "<p>As far as I know, <code>--hard</code> will discard uncommitted changes. Since these aren't tracked by git. But you can undo the <code>discarded commit</code>.</p>\n<pre><code>$ git reflog\n</code></pre>\n<p>will list:</p>\n<pre><code>b0d059c HEAD@{0}: reset: moving to HEAD~1\n4bac331 HEAD@{1}: commit: added level introduction....\n....\n</code></pre>\n<p>where <code>4bac331</code> is the <code>discarded commit</code>.</p>\n<p>Now just move the head to that commit:</p>\n<pre><code>$ git reset --hard 4bac331\n</code></pre>\n" }, { "answer_id": 43273653, "author": "Maciek Łoziński", "author_id": 1004787, "author_profile": "https://Stackoverflow.com/users/1004787", "pm_score": 3, "selected": false, "text": "<p>I've just did a hard reset on wrong project. What saved my life was Eclipse's local history. IntelliJ Idea is said to have one, too, and so may your editor, it's worth checking:</p>\n\n<ol>\n<li><a href=\"http://help.eclipse.org/juno/topic/org.eclipse.platform.doc.user/gettingStarted/qs-55.htm\" rel=\"noreferrer\">Eclipse help topic on Local History</a></li>\n<li><a href=\"http://wiki.eclipse.org/FAQ_Where_is_the_workspace_local_history_stored%3F\" rel=\"noreferrer\">http://wiki.eclipse.org/FAQ_Where_is_the_workspace_local_history_stored%3F</a></li>\n</ol>\n" }, { "answer_id": 49957891, "author": "CodeWizard", "author_id": 1755598, "author_profile": "https://Stackoverflow.com/users/1755598", "pm_score": 4, "selected": false, "text": "<p>Before answering lets add some background, explaining what is this <code>HEAD</code>.</p>\n<h1><em><strong><code>First of all what is HEAD?</code></strong></em></h1>\n<p><code>HEAD</code> is simply a reference to the current commit (latest) on the current branch.<br />\nThere can only be a single <code>HEAD</code> at any given time. (excluding <code>git worktree</code>)</p>\n<p>The content of <code>HEAD</code> is stored inside <code>.git/HEAD</code> and it contains the 40 bytes SHA-1 of the current commit.</p>\n<hr />\n<h1><em><strong><code>detached HEAD</code></strong></em></h1>\n<p>If you are not on the latest commit - meaning that <code>HEAD</code> is pointing to a prior commit in history its called <em><strong><code>detached HEAD</code></strong></em>.</p>\n<p><a href=\"https://i.stack.imgur.com/OlavO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OlavO.png\" alt=\"enter image description here\" /></a></p>\n<p>On the command line it will look like this- SHA-1 instead of the branch name since the <code>HEAD</code> is not pointing to the the tip of the current branch</p>\n<p><a href=\"https://i.stack.imgur.com/U0l3s.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/U0l3s.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<h3>A few options on how to recover from a detached HEAD:</h3>\n<hr />\n<h3><a href=\"https://git-scm.com/docs/git-checkout\" rel=\"noreferrer\"><code>git checkout</code></a></h3>\n<pre><code>git checkout &lt;commit_id&gt;\ngit checkout -b &lt;new branch&gt; &lt;commit_id&gt;\ngit checkout HEAD~X // x is the number of commits t go back\n</code></pre>\n<p>This will checkout new branch pointing to the desired commit.<br />\nThis command will checkout to a given commit.<br />\nAt this point you can create a branch and start to work from this point on.</p>\n<pre><code># Checkout a given commit. \n# Doing so will result in a `detached HEAD` which mean that the `HEAD`\n# is not pointing to the latest so you will need to checkout branch\n# in order to be able to update the code.\ngit checkout &lt;commit-id&gt;\n\n# create a new branch forked to the given commit\ngit checkout -b &lt;branch name&gt;\n</code></pre>\n<hr />\n<h3><a href=\"https://git-scm.com/docs/git-reflog\" rel=\"noreferrer\"><code>git reflog</code></a></h3>\n<p>You can always use the <code>reflog</code> as well.<br />\n<code>git reflog </code> will display any change which updated the <code>HEAD</code> and checking out the desired reflog entry will set the <code>HEAD</code> back to this commit.</p>\n<p><strong>Every time the HEAD is modified there will be a new entry in the <code>reflog</code></strong></p>\n<pre><code>git reflog\ngit checkout HEAD@{...}\n</code></pre>\n<p>This will get you back to your desired commit</p>\n<p><a href=\"https://i.stack.imgur.com/atW9w.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/atW9w.png\" alt=\"enter image description here\" /></a></p>\n<hr />\n<h3><em><strong><a href=\"https://git-scm.com/docs/git-reset\" rel=\"noreferrer\"><code>git reset HEAD --hard &lt;commit_id&gt;</code></a></strong></em></h3>\n<p>&quot;Move&quot; your head back to the desired commit.</p>\n<pre class=\"lang-sh prettyprint-override\"><code># This will destroy any local modifications.\n# Don't do it if you have uncommitted work you want to keep.\ngit reset --hard 0d1d7fc32\n\n# Alternatively, if there's work to keep:\ngit stash\ngit reset --hard 0d1d7fc32\ngit stash pop\n# This saves the modifications, then reapplies that patch after resetting.\n# You could get merge conflicts, if you've modified things which were\n# changed since the commit you reset to.\n</code></pre>\n<ul>\n<li>Note: (<a href=\"https://github.com/git/git/blob/master/Documentation/RelNotes/2.7.0.txt\" rel=\"noreferrer\">Since Git 2.7</a>)<br />\nyou can also use the <code>git rebase --no-autostash</code> as well.</li>\n</ul>\n<hr />\n<hr />\n<h3><em><strong><a href=\"https://git-scm.com/docs/git-revert\" rel=\"noreferrer\"><code>git revert &lt;sha-1&gt;</code></a></strong></em></h3>\n<p>&quot;Undo&quot; the given commit or commit range.<br />\nThe reset command will &quot;undo&quot; any changes made in the given commit.<br />\nA new commit with the undo patch will be commited while the original commit will remain in the history as well.</p>\n<pre class=\"lang-sh prettyprint-override\"><code># add new commit with the undo of the original one.\n# the &lt;sha-1&gt; can be any commit(s) or commit range\ngit revert &lt;sha-1&gt;\n</code></pre>\n<hr />\n<p>This schema illustrate which command does what.<br />\nAs you can see there <code>reset &amp;&amp; checkout</code> modify the <code>HEAD</code>.</p>\n<p><a href=\"https://i.stack.imgur.com/NuThL.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/NuThL.png\" alt=\"enter image description here\" /></a></p>\n" }, { "answer_id": 57491027, "author": "ScottyBlades", "author_id": 3833666, "author_profile": "https://Stackoverflow.com/users/3833666", "pm_score": 5, "selected": false, "text": "<p><code>git reflog</code></p>\n\n<ul>\n<li>Find your commit sha in the list then copy and paste it into this command: </li>\n</ul>\n\n<p><code>git cherry-pick &lt;the sha&gt;</code></p>\n" }, { "answer_id": 57531719, "author": "Newbyte", "author_id": 9315690, "author_profile": "https://Stackoverflow.com/users/9315690", "pm_score": 5, "selected": false, "text": "<p>If you are using a JetBrains IDE (anything IntelliJ based), you can recover even your uncommited changes via their \"Local History\" feature.</p>\n\n<p>Right-click on your top-level directory in your file tree, find \"Local History\" in the context menu, and choose \"Show History\". This will open up a view where your recent edits can be found, and once you have found the revision you want to go back to, right click on it and click \"Revert\". </p>\n" }, { "answer_id": 60669149, "author": "flyingpluto7", "author_id": 6343586, "author_profile": "https://Stackoverflow.com/users/6343586", "pm_score": 2, "selected": false, "text": "<p>My problem is almost similar. I have uncommitted files before I enter <code>git reset --hard</code>.</p>\n<p>Thankfully. I managed to skip all these resources. After I noticed that I can just undo (<code>ctrl-z</code> for windows/linux <code>cmd-shift-z</code> for mac). I just want to add this to all of the answers above.</p>\n<p><em>Note. Its not possible to undo unopened files.</em></p>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/5473/how-can-i-undo-git-reset-hard-head1\">How can I undo git reset --hard HEAD~1?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/7374069/undo-git-reset-hard-with-uncommitted-files-in-the-staging-area\">Undo git reset --hard with uncommitted files in the staging area</a></li>\n<li><a href=\"https://stackoverflow.com/questions/1108853/recovering-added-file-after-doing-git-reset-hard-head\">Recovering added file after doing git reset --hard HEAD^</a></li>\n<li><strong>Medium article:</strong> <a href=\"https://medium.com/@CarrieGuss/how-to-recover-from-a-git-hard-reset-b830b5e3f60c#.353djvmkb\" rel=\"nofollow noreferrer\">How To: Recover From a Git Hard Reset\n(Or, This is Why We Probably Shouldn’t but Totally Can Have Nice Things)</a></li>\n</ul>\n" }, { "answer_id": 60767938, "author": "tuan.dinh", "author_id": 4963534, "author_profile": "https://Stackoverflow.com/users/4963534", "pm_score": 2, "selected": false, "text": "<p>This has saved my life: \n<code>https://medium.com/@CarrieGuss/how-to-recover-from-a-git-hard-reset-b830b5e3f60c</code></p>\n\n<p>Basically you need to run:</p>\n\n<pre><code>for blob in $(git fsck --lost-found | awk ‘$2 == “blob” { print $3 }’); do git cat-file -p $blob &gt; $blob.txt; done\n</code></pre>\n\n<p>Then manually going through the pain to re-organise your files to the correct structure.</p>\n\n<p>Takeaway: Never use <code>git reset --hard</code> if you dont completely 100% understand how it works, best not to use it.</p>\n" }, { "answer_id": 63639989, "author": "NATALIAGJ", "author_id": 12296962, "author_profile": "https://Stackoverflow.com/users/12296962", "pm_score": 2, "selected": false, "text": "<p><code>git reflog</code> and back to the last HEAD\n6a56624 (HEAD -&gt; master) HEAD@{0}: reset: moving to HEAD~3\n1a9bf73 HEAD@{1}: commit: add changes in model generate binary</p>\n" }, { "answer_id": 68114239, "author": "Abdulrahim Klis", "author_id": 5737758, "author_profile": "https://Stackoverflow.com/users/5737758", "pm_score": 1, "selected": false, "text": "<p>git reset --hard - you can use to revert one page and after that you can stash or pull everything from origin again</p>\n" } ]
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 the onClick event of the trigger which should still fire the modal popup and run the javascript at the same time?</p>\n" }, { "answer_id": 5493, "author": "slolife", "author_id": 698, "author_profile": "https://Stackoverflow.com/users/698", "pm_score": 2, "selected": false, "text": "<p>The ModalPopupExtender modifies the button/hyperlink that you tell it to be the \"trigger\" element. The onclick script I add triggers before the popup is shown. I want script to fire after the popup is shown.</p>\n\n<p>Also, still leaves me with the problem of when I show the modal from server side.</p>\n" }, { "answer_id": 5500, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 6, "selected": true, "text": "<p>hmmm... I'm <em>pretty sure</em> 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</p>\n\n<pre><code>function pageLoad()\n{\n var popup = $find('ModalPopupClientID');\n popup.add_shown(SetFocus);\n}\n\nfunction SetFocus()\n{\n $get('TriggerClientId').focus();\n}\n</code></pre>\n\n<p>i'm not sure tho if this will help you with calling it from the server side tho</p>\n" }, { "answer_id": 2143771, "author": "Brunz", "author_id": 259688, "author_profile": "https://Stackoverflow.com/users/259688", "pm_score": 2, "selected": false, "text": "<p>TinyMCE work on invisible textbox if you hide it with css (display:none;)\nYou make an \"onclick\" event on TargetControlID, for init TinyMCE, if you use also an updatepanel</p>\n" }, { "answer_id": 2365547, "author": "Mircea Dunka", "author_id": 284646, "author_profile": "https://Stackoverflow.com/users/284646", "pm_score": 4, "selected": false, "text": "<p>You should use the <strong>BehaviorID</strong> value <code>mpeBID</code> of your ModalPopupExtender.</p>\n\n<pre><code>function pageLoad() {\n $find('mpeBID').add_shown(HideMediaPlayer);\n}\n\nfunction HideMediaPlayer() {\n var divMovie = $get('&lt;%=divMovie.ClientID%&gt;');\n divMovie.style.display = \"none\";\n}\n</code></pre>\n" }, { "answer_id": 9529512, "author": "John Ward", "author_id": 1244536, "author_profile": "https://Stackoverflow.com/users/1244536", "pm_score": 4, "selected": false, "text": "<p>Here's a simple way to do it in markup:</p>\n<pre><code>&lt;ajaxToolkit:ModalPopupExtender \n ID=&quot;ModalPopupExtender2&quot; runat=&quot;server&quot; \n TargetControlID=&quot;lnk_OpenGame&quot; \n PopupControlID=&quot;Panel1&quot; \n BehaviorID=&quot;SilverPracticeBehaviorID&quot; &gt;\n &lt;Animations&gt;\n &lt;OnShown&gt;\n &lt;ScriptAction Script=&quot;InitializeGame();&quot; /&gt; \n &lt;/OnShown&gt;\n &lt;/Animations&gt; \n&lt;/ajaxToolkit:ModalPopupExtender&gt;\n</code></pre>\n" }, { "answer_id": 15915119, "author": "Mormon SUD", "author_id": 2241412, "author_profile": "https://Stackoverflow.com/users/2241412", "pm_score": 2, "selected": false, "text": "<pre><code>var launch = false;\n\nfunction launchModal() {\n launch = true;\n}\n\nfunction pageLoad() {\n if (launch) {\n var ModalPedimento = $find('ModalPopupExtender_Pedimento');\n ModalPedimento.show();\n ModalPedimento.add_shown(SetFocus);\n }\n}\n\nfunction SetFocus() {\n $get('TriggerClientId').focus();\n}\n</code></pre>\n" }, { "answer_id": 15932547, "author": "Mormon SUD", "author_id": 2241412, "author_profile": "https://Stackoverflow.com/users/2241412", "pm_score": 2, "selected": false, "text": "<p>For two modal forms:</p>\n\n<pre><code>var launch = false;\nvar NameObject = '';\n\nfunction launchModal(ModalPopupExtender) {\n launch = true;\n NameObject = ModalPopupExtender;\n}\n\nfunction pageLoad() {\n if (launch) {\n var ModalObject = $find(NameObject);\n ModalObject.show();\n ModalObject.add_shown(SetFocus);\n }\n} \n\nfunction SetFocus() {\n $get('TriggerClientId').focus();\n}\n</code></pre>\n\n<p>Server side: behand</p>\n\n<pre><code>protected void btnNuevo_Click(object sender, EventArgs e)\n{\n //Para recuperar el formulario modal desde el lado del sercidor\n ScriptManager.RegisterStartupScript(Page, Page.GetType(), \"key\", \"&lt;script&gt;launchModal('\" + ModalPopupExtender_Factura.ID.ToString() + \"');&lt;/script&gt;\", false);\n}\n</code></pre>\n" } ]
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 from receiving cursor focus, thereby creating your own cheap NumericUpDown control?</p>\n" }, { "answer_id": 7794, "author": "Arcturus", "author_id": 900, "author_profile": "https://Stackoverflow.com/users/900", "pm_score": 7, "selected": true, "text": "<p>How about:</p>\n\n<pre><code>protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)\n{\n e.Handled = !AreAllValidNumericChars(e.Text);\n base.OnPreviewTextInput(e);\n}\n\nprivate bool AreAllValidNumericChars(string str)\n{\n foreach(char c in str)\n {\n if(!Char.IsNumber(c)) return false;\n }\n\n return true;\n}\n</code></pre>\n" }, { "answer_id": 8483, "author": "Nidonocu", "author_id": 483, "author_profile": "https://Stackoverflow.com/users/483", "pm_score": 2, "selected": false, "text": "<p>You can also try using data validation if users commit data before you use it. Doing that I found was fairly simple and cleaner than fiddling about with keys.</p>\n\n<p>Otherwise, you could always disable Paste too!</p>\n" }, { "answer_id": 28001, "author": "user3035", "author_id": 3035, "author_profile": "https://Stackoverflow.com/users/3035", "pm_score": 4, "selected": false, "text": "<p>I've been using an attached property to allow the user to use the up and down keys to change the values in the text box. To use it, you just use</p>\n\n<pre><code>&lt;TextBox local:TextBoxNumbers.SingleDelta=\"1\"&gt;100&lt;/TextBox&gt;\n</code></pre>\n\n<p>This doesn't actually address the validation issues that are referred to in this question, but it addresses what I do about not having a numeric up/down control. Using it for a little bit, I think I might actually like it better than the old numeric up/down control.</p>\n\n<p>The code isn't perfect, but it handles the cases I needed it to handle:</p>\n\n<ul>\n<li><code>Up</code> arrow, <code>Down</code> arrow</li>\n<li><code>Shift + Up</code> arrow, <code>Shift + Down</code> arrow</li>\n<li><code>Page Up</code>, <code>Page Down</code></li>\n<li>Binding <code>Converter</code> on the text property</li>\n</ul>\n\n<p><code>Code behind</code></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Data;\nusing System.Windows.Input;\n\nnamespace Helpers\n{\n public class TextBoxNumbers\n { \n public static Decimal GetSingleDelta(DependencyObject obj)\n {\n return (Decimal)obj.GetValue(SingleDeltaProperty);\n }\n\n public static void SetSingleDelta(DependencyObject obj, Decimal value)\n {\n obj.SetValue(SingleDeltaProperty, value);\n }\n\n // Using a DependencyProperty as the backing store for SingleValue. This enables animation, styling, binding, etc...\n public static readonly DependencyProperty SingleDeltaProperty =\n DependencyProperty.RegisterAttached(\"SingleDelta\", typeof(Decimal), typeof(TextBoxNumbers), new UIPropertyMetadata(0.0m, new PropertyChangedCallback(f)));\n\n public static void f(DependencyObject o, DependencyPropertyChangedEventArgs e)\n {\n TextBox t = o as TextBox;\n\n if (t == null)\n return;\n\n t.PreviewKeyDown += new System.Windows.Input.KeyEventHandler(t_PreviewKeyDown);\n }\n\n private static Decimal GetSingleValue(DependencyObject obj)\n {\n return GetSingleDelta(obj);\n }\n\n private static Decimal GetDoubleValue(DependencyObject obj)\n {\n return GetSingleValue(obj) * 10;\n }\n\n private static Decimal GetTripleValue(DependencyObject obj)\n {\n return GetSingleValue(obj) * 100;\n }\n\n static void t_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)\n {\n TextBox t = sender as TextBox;\n Decimal i;\n\n if (t == null)\n return;\n\n if (!Decimal.TryParse(t.Text, out i))\n return;\n\n switch (e.Key)\n {\n case System.Windows.Input.Key.Up:\n if (Keyboard.Modifiers == ModifierKeys.Shift)\n i += GetDoubleValue(t);\n else\n i += GetSingleValue(t);\n break;\n\n case System.Windows.Input.Key.Down:\n if (Keyboard.Modifiers == ModifierKeys.Shift)\n i -= GetDoubleValue(t);\n else\n i -= GetSingleValue(t);\n break;\n\n case System.Windows.Input.Key.PageUp:\n i += GetTripleValue(t);\n break;\n\n case System.Windows.Input.Key.PageDown:\n i -= GetTripleValue(t);\n break;\n\n default:\n return;\n }\n\n if (BindingOperations.IsDataBound(t, TextBox.TextProperty))\n {\n try\n {\n Binding binding = BindingOperations.GetBinding(t, TextBox.TextProperty);\n t.Text = (string)binding.Converter.Convert(i, null, binding.ConverterParameter, binding.ConverterCulture);\n }\n catch\n {\n t.Text = i.ToString();\n }\n }\n else\n t.Text = i.ToString();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 57784, "author": "Mark Allen", "author_id": 5948, "author_profile": "https://Stackoverflow.com/users/5948", "pm_score": 1, "selected": false, "text": "<p>Can you not just use something like the following?</p>\n\n<pre><code>int numericValue = 0;\n\nif (false == int.TryParse(yourInput, out numericValue))\n{\n // handle non-numeric input\n}\n</code></pre>\n" }, { "answer_id": 561577, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<pre><code>private void txtNumericValue_PreviewKeyDown(object sender, KeyEventArgs e)\n{\n KeyConverter converter = new KeyConverter();\n\n string key = converter.ConvertToString(e.Key);\n\n if (key != null &amp;&amp; key.Length == 1)\n {\n e.Handled = Char.IsDigit(key[0]) == false;\n }\n}\n</code></pre>\n\n<p>This is the easiest technique I've found to accomplish this. The down side is that the context menu of the TextBox still allows non-numerics via Paste. To resolve this quickly I simply added the attribute/property: ContextMenu=\"{x:Null}\" to the TextBox thereby disabling it. Not ideal but for my scenario it will suffice.</p>\n\n<p>Obviously you could add a few more keys/chars in the test to include additional acceptable values (e.g. '.', '$' etc...)</p>\n" }, { "answer_id": 1923737, "author": "Eric", "author_id": 218177, "author_profile": "https://Stackoverflow.com/users/218177", "pm_score": 4, "selected": false, "text": "<p>This is how I do it. It uses a regular expression to check if the text that will be in the box is numeric or not. </p>\n\n<pre><code>Regex NumEx = new Regex(@\"^-?\\d*\\.?\\d*$\");\n\nprivate void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)\n{\n if (sender is TextBox)\n {\n string text = (sender as TextBox).Text + e.Text;\n e.Handled = !NumEx.IsMatch(text);\n }\n else\n throw new NotImplementedException(\"TextBox_PreviewTextInput Can only Handle TextBoxes\");\n}\n</code></pre>\n\n<p>There is now a much better way to do this in WPF and Silverlight. If your control is bound to a property, all you have to do is change your binding statement a bit. Use the following for your binding:</p>\n\n<pre><code>&lt;TextBox Text=\"{Binding Number, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}\"/&gt;\n</code></pre>\n\n<p>Note that you can use this on custom properties too, all you have to do is throw an exception if the value in the box is invalid and the control will get highlighted with a red border. If you click on the upper right of the red border then the exception message will pop up.</p>\n" }, { "answer_id": 2122964, "author": "Ritz", "author_id": 257370, "author_profile": "https://Stackoverflow.com/users/257370", "pm_score": 1, "selected": false, "text": "<pre><code>Private Sub Value1TextBox_PreviewTextInput(ByVal sender As Object, ByVal e As TextCompositionEventArgs) Handles Value1TextBox.PreviewTextInput\n Try\n If Not IsNumeric(e.Text) Then\n e.Handled = True\n End If\n Catch ex As Exception\n End Try\nEnd Sub\n</code></pre>\n\n<p>Worked for me.</p>\n" }, { "answer_id": 2165796, "author": "bcd", "author_id": 262212, "author_profile": "https://Stackoverflow.com/users/262212", "pm_score": 1, "selected": false, "text": "<pre><code>void PreviewTextInputHandler(object sender, TextCompositionEventArgs e)\n{\n string sVal = e.Text;\n int val = 0;\n\n if (sVal != null &amp;&amp; sVal.Length &gt; 0)\n {\n if (int.TryParse(sVal, out val))\n {\n e.Handled = false;\n }\n else\n {\n e.Handled = true;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 2673131, "author": "juanagui", "author_id": 168435, "author_profile": "https://Stackoverflow.com/users/168435", "pm_score": 2, "selected": false, "text": "<pre><code>public class NumericTextBox : TextBox\n{\n public NumericTextBox()\n : base()\n {\n DataObject.AddPastingHandler(this, new DataObjectPastingEventHandler(CheckPasteFormat));\n }\n\n private Boolean CheckFormat(string text)\n {\n short val;\n return Int16.TryParse(text, out val);\n }\n\n private void CheckPasteFormat(object sender, DataObjectPastingEventArgs e)\n {\n var isText = e.SourceDataObject.GetDataPresent(System.Windows.DataFormats.Text, true);\n\n if (isText)\n {\n var text = e.SourceDataObject.GetData(DataFormats.Text) as string;\n if (CheckFormat(text))\n {\n return;\n }\n }\n\n e.CancelCommand();\n }\n\n protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)\n {\n if (!CheckFormat(e.Text))\n {\n e.Handled = true;\n }\n else\n {\n base.OnPreviewTextInput(e);\n }\n }\n}\n</code></pre>\n\n<p>Additionally you may customize the parsing behavior by providing appropriate dependency properties.</p>\n" }, { "answer_id": 2764514, "author": "BrownBot", "author_id": 332246, "author_profile": "https://Stackoverflow.com/users/332246", "pm_score": 2, "selected": false, "text": "<p>Add this to the main solution to make sure the the binding is updated to zero when the textbox is cleared.</p>\n\n<pre><code>protected override void OnPreviewKeyUp(System.Windows.Input.KeyEventArgs e)\n{\n base.OnPreviewKeyUp(e);\n\n if (BindingOperations.IsDataBound(this, TextBox.TextProperty))\n {\n if (this.Text.Length == 0)\n {\n this.SetValue(TextBox.TextProperty, \"0\");\n this.SelectAll();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 2824205, "author": "erodewald", "author_id": 24399, "author_profile": "https://Stackoverflow.com/users/24399", "pm_score": 4, "selected": false, "text": "<p>I decided to simplify the reply marked as the answer on here to basically 2 lines using a LINQ expression.</p>\n\n<pre><code>e.Handled = !e.Text.All(Char.IsNumber);\nbase.OnPreviewTextInput(e);\n</code></pre>\n" }, { "answer_id": 4889675, "author": "Dead.Rabit", "author_id": 424963, "author_profile": "https://Stackoverflow.com/users/424963", "pm_score": 2, "selected": false, "text": "<p>My Version of <a href=\"https://stackoverflow.com/questions/5511/numeric-data-entry-in-wpf/7794#7794\">Arcturus</a> answer, can change the convert method used to work with int / uint / decimal / byte (for colours) or any other numeric format you care to use, also works with copy / paste</p>\n\n<pre><code>protected override void OnPreviewTextInput( System.Windows.Input.TextCompositionEventArgs e )\n{\n try\n {\n if ( String.IsNullOrEmpty( SelectedText ) )\n {\n Convert.ToDecimal( this.Text.Insert( this.CaretIndex, e.Text ) );\n }\n else\n {\n Convert.ToDecimal( this.Text.Remove( this.SelectionStart, this.SelectionLength ).Insert( this.SelectionStart, e.Text ) );\n }\n }\n catch\n {\n // mark as handled if cannot convert string to decimal\n e.Handled = true;\n }\n\n base.OnPreviewTextInput( e );\n}\n</code></pre>\n\n<p>N.B. Untested code.</p>\n" }, { "answer_id": 5546415, "author": "Jroonk", "author_id": 692098, "author_profile": "https://Stackoverflow.com/users/692098", "pm_score": 2, "selected": false, "text": "<p>Why don't you just try using the KeyDown event rather than the PreviewKeyDown Event. You can stop the invalid characters there, but all the control characters are accepted. This seems to work for me:</p>\n\n<pre><code>private void NumericKeyDown(object sender, System.Windows.Input.KeyEventArgs e)\n{\n bool isNumPadNumeric = (e.Key &gt;= Key.NumPad0 &amp;&amp; e.Key &lt;= Key.NumPad9);\n bool isNumeric =((e.Key &gt;= Key.D0 &amp;&amp; e.Key &lt;= Key.D9) &amp;&amp; (e.KeyboardDevice.Modifiers == ModifierKeys.None));\n bool isDecimal = ((e.Key == Key.OemPeriod || e.Key == Key.Decimal) &amp;&amp; (((TextBox)sender).Text.IndexOf('.') &lt; 0));\n e.Handled = !(isNumPadNumeric || isNumeric || isDecimal);\n}\n</code></pre>\n" }, { "answer_id": 8998307, "author": "Jonny Ots", "author_id": 712714, "author_profile": "https://Stackoverflow.com/users/712714", "pm_score": 2, "selected": false, "text": "<p>I use a custom <code>ValidationRule</code> to check if text is numeric.</p>\n\n<pre><code>public class DoubleValidation : ValidationRule\n{\n public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)\n {\n if (value is string)\n {\n double number;\n if (!Double.TryParse((value as string), out number))\n return new ValidationResult(false, \"Please enter a valid number\");\n }\n\n return ValidationResult.ValidResult;\n }\n</code></pre>\n\n<p>Then when I bind a <code>TextBox</code> to a numeric property, I add the new custom class to the <code>Binding.ValidationRules</code> collection. In the example below the validation rule is checked everytime the <code>TextBox.Text</code> changes.</p>\n\n<pre><code>&lt;TextBox&gt;\n &lt;TextBox.Text&gt;\n &lt;Binding Path=\"MyNumericProperty\" UpdateSourceTrigger=\"PropertyChanged\"&gt;\n &lt;Binding.ValidationRules&gt;\n &lt;local:DoubleValidation/&gt;\n &lt;/Binding.ValidationRules&gt;\n &lt;/Binding&gt;\n &lt;/TextBox.Text&gt;\n&lt;/TextBox&gt;\n</code></pre>\n" }, { "answer_id": 11858030, "author": "Varun", "author_id": 1583635, "author_profile": "https://Stackoverflow.com/users/1583635", "pm_score": 1, "selected": false, "text": "<p><strong>Can also use a converter like:</strong></p>\n\n<pre><code>public class IntegerFormatConverter : IValueConverter\n{\n public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n int result;\n int.TryParse(value.ToString(), out result);\n return result;\n }\n\n public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n int result;\n int.TryParse(value.ToString(), out result);\n return result;\n }\n}\n</code></pre>\n" }, { "answer_id": 16807485, "author": "Brian Hinchey", "author_id": 62278, "author_profile": "https://Stackoverflow.com/users/62278", "pm_score": 2, "selected": false, "text": "<p>Combining the ideas from a few of these answers, I have created a NumericTextBox that</p>\n\n<ul>\n<li>Handles decimals</li>\n<li>Does some basic validation to ensure any entered '-' or '.' is valid</li>\n<li>Handles pasted values</li>\n</ul>\n\n<p>Please feel free to update if you can think of any other logic that should be included.</p>\n\n<pre><code>public class NumericTextBox : TextBox\n{\n public NumericTextBox()\n {\n DataObject.AddPastingHandler(this, OnPaste);\n }\n\n private void OnPaste(object sender, DataObjectPastingEventArgs dataObjectPastingEventArgs)\n {\n var isText = dataObjectPastingEventArgs.SourceDataObject.GetDataPresent(System.Windows.DataFormats.Text, true);\n\n if (isText)\n {\n var text = dataObjectPastingEventArgs.SourceDataObject.GetData(DataFormats.Text) as string;\n if (IsTextValid(text))\n {\n return;\n }\n }\n\n dataObjectPastingEventArgs.CancelCommand();\n }\n\n private bool IsTextValid(string enteredText)\n {\n if (!enteredText.All(c =&gt; Char.IsNumber(c) || c == '.' || c == '-'))\n {\n return false;\n }\n\n //We only validation against unselected text since the selected text will be replaced by the entered text\n var unselectedText = this.Text.Remove(SelectionStart, SelectionLength);\n\n if (enteredText == \".\" &amp;&amp; unselectedText.Contains(\".\"))\n {\n return false;\n }\n\n if (enteredText == \"-\" &amp;&amp; unselectedText.Length &gt; 0)\n {\n return false;\n }\n\n return true;\n }\n\n protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)\n {\n e.Handled = !IsTextValid(e.Text);\n base.OnPreviewTextInput(e);\n }\n}\n</code></pre>\n" } ]
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, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 6, "selected": true, "text": "<p>Adding, multiplying, or truncating a poor random source will give you a poor random result. See <a href=\"http://random.org/randomness/\" rel=\"noreferrer\">Introduction to Randomness and Random Numbers</a> for an explanation.</p>\n\n<p>You're right about PHP rand() function. See the second figure on <a href=\"http://random.org/analysis/\" rel=\"noreferrer\">Statistical Analysis</a> for a striking illustration. (The first figure is striking, but it's been drawn by Scott Adams, not plotted with rand()).</p>\n\n<p>One solution is to use a true random generator such as <a href=\"http://random.org/integers/\" rel=\"noreferrer\">random.org</a>. Another, if you're on Linux/BSD/etc. is to use <a href=\"http://en.wikipedia.org/wiki/Urandom\" rel=\"noreferrer\">/dev/random</a>. If the randomness is mission critical, you will have to use a <a href=\"http://en.wikipedia.org/wiki/Hardware_random_number_generator\" rel=\"noreferrer\">hardware random generator</a>.</p>\n" }, { "answer_id": 5835, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://random.org/clients/http/\" rel=\"nofollow noreferrer\">random.org</a> has an API you can access via HTTP.</p>\n\n<blockquote>\n <p>RANDOM.ORG is a true random number service that generates randomness\n via atmospheric noise.</p>\n</blockquote>\n" }, { "answer_id": 6344, "author": "Christian Lescuyer", "author_id": 341, "author_profile": "https://Stackoverflow.com/users/341", "pm_score": 2, "selected": false, "text": "<p>I would be wary of the impression of randomness: there have been many experiments where people would choose the less random distribution. It seems the mind is not very good at producing or estimating randomness.</p>\n\n<p>There are good articles on randomness at <a href=\"http://www.fourmilab.ch/hotbits/\" rel=\"nofollow noreferrer\">Fourmilab</a>, including another <a href=\"https://www.fourmilab.ch/hotbits/secure_generate.html\" rel=\"nofollow noreferrer\">true random generator</a>. Maybe you could get random data from both sites so if one is down you still have the other.</p>\n\n<p>Fourmilab also provides a <a href=\"http://www.fourmilab.ch/random/\" rel=\"nofollow noreferrer\">test program</a> to check randomness. You could use it to check your various myRand() programs. </p>\n\n<p>As for your last program, if you generate 10000 values, why don't you choose the final value amongst the 10 thousand? You restrict yourself to a subset. Also, it won't work if your $min and $max are greater than 10000.</p>\n\n<p>Anyway, the randomness you need depends on your application. rand() will be OK for an online game, but not OK for cryptography (anything not thoroughly tested with statistical programs will not be suitable for cryptography anyway). You be the judge!</p>\n" }, { "answer_id": 18867906, "author": "Aaron Gong", "author_id": 2215486, "author_profile": "https://Stackoverflow.com/users/2215486", "pm_score": 2, "selected": false, "text": "<p>Another way of getting random numbers, similar in concept to getting UUID</p>\n\n<p>PHP Version 5.3 and above</p>\n\n<pre><code>openssl_random_pseudo_bytes(...)\n</code></pre>\n\n<p>Or you can try the following <a href=\"https://github.com/ramsey/uuid\" rel=\"nofollow\">library</a> using RFC4122</p>\n" }, { "answer_id": 31444887, "author": "Salvador Dali", "author_id": 1090562, "author_profile": "https://Stackoverflow.com/users/1090562", "pm_score": 1, "selected": false, "text": "<p>A new <a href=\"https://wiki.php.net/rfc/easy_userland_csprng\" rel=\"nofollow noreferrer\">PHP7</a> there is a function that does exactly what you needed: it generates <a href=\"http://php.net/manual/en/function.random-int.php\" rel=\"nofollow noreferrer\">cryptographically secure pseudo-random integers.</a></p>\n\n<pre><code>int random_int ( int $min , int $max )\n</code></pre>\n\n<blockquote>\n <p>Generates cryptographic random integers that are suitable for use\n where unbiased results are critical (i.e. shuffling a Poker deck).</p>\n</blockquote>\n\n<p>For a more detailed explanation about PRNG and CSPRNG (and their difference) as well as why your original approach is actually a bad idea, please read my <a href=\"https://stackoverflow.com/a/31443898/1090562\">another highly similar answer</a>.</p>\n" } ]
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)\\Microsoft.CSharp.targets\" /&gt;\n</code></pre>\n\n<p>and change it to</p>\n\n<pre><code>&lt;Import Project=\"$(MSBuildBinPath)\\Microsoft.CSharp.targets\" /&gt;\n</code></pre>\n" }, { "answer_id": 876831, "author": "Oleg Sakharov", "author_id": 87057, "author_profile": "https://Stackoverflow.com/users/87057", "pm_score": 4, "selected": false, "text": "<p>This <a href=\"http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/4c8249db-85ad-4356-9313-5d47411f1a1a\" rel=\"noreferrer\">link on MSDN</a> also helps a lot to understand the reason why it doesn't work. $(MSBuildToolsPath) is the path to Microsoft.Build.Engine v3.5 (inserted automatically in a project file when you create in VS2008). If you try to build your project for .Net 2.0, be sure that you changed this path to $(MSBuildBinPath) which is the path to Microsoft.Build.Engine v2.0.</p>\n" }, { "answer_id": 2912317, "author": "Andre Luus", "author_id": 323071, "author_profile": "https://Stackoverflow.com/users/323071", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>ok so what if it say this: between the\n gt/lt signs</p>\n \n <p>Import\n Project=\"$(MSBuildExtensionsPath)\\Microsoft\\Silverlight\\v3.0\\Microsoft.Silverlight.CSharp.targets\"\n /</p>\n \n <p>how do i fix the targets error?</p>\n</blockquote>\n\n<p>I also found that import string in a demo project (specifically \"Build your own MVVM Framework\" by Rob Eisenburg).</p>\n\n<p>If you replace that import with the one suggested by lomaxx VS2010 RTM reports that you need to install <a href=\"http://go.microsoft.com/fwlink/?LinkId=168436\" rel=\"nofollow noreferrer\">this</a>.</p>\n" }, { "answer_id": 7042664, "author": "Peter", "author_id": 15349, "author_profile": "https://Stackoverflow.com/users/15349", "pm_score": 2, "selected": false, "text": "<p>I got this after reinstalling Windows. Visual Studio was installed, and I could see the Silverlight project type in the New Project window, but opening one didn't work. The solution was simple: I had to install the Silverlight Developer runtime and/or the Microsoft Silverlight 4 Tools for Visual Studio. This may seem stupid, but I overlooked it because I thought it should work, as the Silverlight project type was available.</p>\n" }, { "answer_id": 7239367, "author": "stack247", "author_id": 661900, "author_profile": "https://Stackoverflow.com/users/661900", "pm_score": 2, "selected": false, "text": "<p>For errors with <code>Microsoft.WebApplications.targets</code>, you can:</p>\n\n<ol>\n<li>Install Visual Studio 2010 (or the same version as in development machine) in your TFS server.</li>\n<li>Copy the “<code>Microsoft.WebApplication.targets</code>” from development machine file to TFS build machine.</li>\n</ol>\n\n<p><a href=\"http://stack247.wordpress.com/2011/08/29/the-imported-project-microsoft-webapplications-targets-was-not-found/\" rel=\"nofollow\">Here's</a> the post.</p>\n" }, { "answer_id": 13995747, "author": "appenthused", "author_id": 1017156, "author_profile": "https://Stackoverflow.com/users/1017156", "pm_score": 3, "selected": false, "text": "<p>I used to have this following line in the csproj file:</p>\n\n<pre><code>&lt;Import Project=\"$(MSBuildExtensionsPath32)\\Microsoft\\VisualStudio\\v10.0\\WebApplications\\Microsoft.WebApplication.targets\" /&gt;\n</code></pre>\n\n<p>After deleting this file, it works fine.</p>\n" }, { "answer_id": 18078170, "author": "Greg Gum", "author_id": 425823, "author_profile": "https://Stackoverflow.com/users/425823", "pm_score": 1, "selected": false, "text": "<p>This error can also occur when opening a Silverlight project that was built in SL 4, while you have SL 5 installed.</p>\n\n<p>Here is an example error message: The imported project \"C:\\Program Files (x86)\\MSBuild\\Microsoft\\Silverlight\\v4.0\\Microsoft.Silverlight.CSharp.targets\" was not found.</p>\n\n<p>Note the v4.0.</p>\n\n<p>To resolve, edit the project and find: </p>\n\n<pre><code>&lt;TargetFrameworkVersion&gt;v4.0&lt;/TargetFrameworkVersion&gt;\n</code></pre>\n\n<p>And change it to v5.0.</p>\n\n<p>Then reload project and it will open (unless you do not have SL 5 installed).</p>\n" }, { "answer_id": 38782270, "author": "Alf Moh", "author_id": 5138921, "author_profile": "https://Stackoverflow.com/users/5138921", "pm_score": 3, "selected": false, "text": "<p>If you are to encounter the error that says <code>Microsoft.CSharp.Core.targets not found</code>, these are the steps I took to correct mine:</p>\n\n<ol>\n<li><p>Open any previous working projects folder and navigate to the link showed in the error, that is <code>Projects/(working project name)/packages/Microsoft.Net.Compilers.1.3.2/tools/</code> and search for <code>Microsoft.CSharp.Core.targets</code> file. </p></li>\n<li><p>Copy this file and put it in the non-working project <code>tools folder</code> (that is, navigating to the tools folder in the non-working project as shown above)</p></li>\n<li><p>Now close your project (if it was open) and reopen it. </p></li>\n</ol>\n\n<p>It should be working now.</p>\n\n<p>Also, to make sure everything is working properly in your now open Visual Studio Project, Go to <code>Tools &gt; NuGetPackage Manager &gt; Manage NuGet Packages For Solution</code>. Here, you might find an error that says, CodeAnalysis.dll is being used by another application. </p>\n\n<p>Again, go to the <code>tools folder</code>, find the specified file and delete it. Come back to <code>Manage NuGet Packages For Solution</code>. You will find a link that will ask you to Reload, click it and everything gets re-installed. </p>\n\n<p>Your project should be working properly now.</p>\n" }, { "answer_id": 40190795, "author": "Bharat", "author_id": 5816119, "author_profile": "https://Stackoverflow.com/users/5816119", "pm_score": 6, "selected": false, "text": "<blockquote>\n<p>This is a global solution, not dependent on particular package or bin.</p>\n</blockquote>\n<p>In my case, I removed <strong>Packages</strong> folder from my root directory.</p>\n<blockquote>\n<p>Maybe it happens because of your packages are there but compiler is not finding it's reference. so remove older packages first and add new packages.</p>\n</blockquote>\n<p>Steps to <strong>Add new packages</strong></p>\n<ul>\n<li>First remove, packages folder (<strong>it will be near by or one step up to your current project folder</strong>).</li>\n<li>Then restart the project or solution.</li>\n<li>Now, Rebuild solution file.</li>\n<li>Project will get new references from nuGet package manager. And your issue will be resolved.</li>\n</ul>\n<p>This is not proper solution, but <strong>I posted it here because I face same issue.</strong></p>\n<p>In my case, <strong>I wasn't even able to open my solution in visual studio and didn't get any help with other SO answers.</strong></p>\n" }, { "answer_id": 42238377, "author": "Gichamba", "author_id": 487030, "author_profile": "https://Stackoverflow.com/users/487030", "pm_score": 2, "selected": false, "text": "<p>In my case, I opened my .csproj file in notepad and removed the following three lines. Worked like a charm:</p>\n\n<pre><code>&lt;Import Project=\"..\\packages\\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\\build\\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props\" Condition=\"Exists('..\\packages\\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\\build\\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')\" /&gt;\n&lt;Import Project=\"..\\packages\\Microsoft.Net.Compilers.1.0.0\\build\\Microsoft.Net.Compilers.props\" Condition=\"Exists('..\\packages\\Microsoft.Net.Compilers.1.0.0\\build\\Microsoft.Net.Compilers.props')\" /&gt;\n&lt;Import Project=\"..\\packages\\Microsoft.Net.Compilers.1.3.2\\build\\Microsoft.Net.Compilers.props\" Condition=\"Exists('..\\packages\\Microsoft.Net.Compilers.1.3.2\\build\\Microsoft.Net.Compilers.props')\" /&gt;\n</code></pre>\n" }, { "answer_id": 43467560, "author": "user2042930", "author_id": 2042930, "author_profile": "https://Stackoverflow.com/users/2042930", "pm_score": 5, "selected": false, "text": "<p>For me the issue was that the path of the project contained %20 characters, because git added those instead of spaces when the repository was cloned. Another problem might be if the path to a package is too long.</p>\n" }, { "answer_id": 46618902, "author": "Atron Seige", "author_id": 375114, "author_profile": "https://Stackoverflow.com/users/375114", "pm_score": 0, "selected": false, "text": "<p>I deleted the obj folder and then the project loaded as expected.</p>\n" }, { "answer_id": 47452127, "author": "Vojta", "author_id": 2524260, "author_profile": "https://Stackoverflow.com/users/2524260", "pm_score": 4, "selected": false, "text": "<p>In my case I could not load <strong>one</strong> out of <strong>5 projects</strong> in my solution.</p>\n\n<p>It helped to <strong>close Visual Studio</strong> and I had to <strong>delete</strong> <code>Microsoft.Net.Compilers.1.3.2</code> nuget folder under <code>packages</code> folder.</p>\n\n<p><strong>Afterwards, open your solution again and the project loaded as expected</strong></p>\n\n<p><em>Just to be sure, close all instances of VS before you delete the folder.</em></p>\n" }, { "answer_id": 49113817, "author": "WholeLifeLearner", "author_id": 1528883, "author_profile": "https://Stackoverflow.com/users/1528883", "pm_score": 0, "selected": false, "text": "<p>Sometimes the problem might be with hardcoded VS version in .csproj file. If you have in your csproj something like this:</p>\n\n<pre><code>[...]\\VisualStudio\\v12.0\\WebApplications\\Microsoft.WebApplication.targets\"\n</code></pre>\n\n<p>You should check if the number is correct (the reason it's wrong can be the project was created with another version of Visual Studio). If it's wrong, replace it with your current version of build tools OR use the VS variable:</p>\n\n<pre><code>[...]\\VisualStudio\\v$(VisualStudioVersion)\\WebApplications\\Microsoft.WebApplication.targets\"\n</code></pre>\n" }, { "answer_id": 54716193, "author": "Alex", "author_id": 6146387, "author_profile": "https://Stackoverflow.com/users/6146387", "pm_score": 0, "selected": false, "text": "<p>I ran into this issue while executing an Ansible playbook so I want to add my 2 cents here. I noticed a warning message about missing Visual Studio 14. Visual Studio version 14 was released in 2015 and the solution to my problem was installing Visual Studio 2015 Professional on the host machine of my Azure DevOps agent.</p>\n" }, { "answer_id": 55723368, "author": "Worthy7", "author_id": 1079267, "author_profile": "https://Stackoverflow.com/users/1079267", "pm_score": 0, "selected": false, "text": "<p>After trying to restore, closing VS, deleting the failed package, reopening, trying to restore, multiple times I just deleted everything in packages and when I did a restore and it worked perfectly.</p>\n" }, { "answer_id": 66758114, "author": "Andreas", "author_id": 6344387, "author_profile": "https://Stackoverflow.com/users/6344387", "pm_score": 0, "selected": false, "text": "<p>For me, the issue was the path.. When cloning the project that had a space in the name. The project folder was named <code>&quot;Sample%20-%205&quot;</code> instead of what it should be: <code>&quot;Sample - 5&quot;</code></p>\n<p>Opening the project was fine, but building failed with</p>\n<blockquote>\n<p>Could not find the file:\n/packages/Microsoft.Net.Compilers.1.3.2/tools/Microsoft.CSharp.Core.targets</p>\n</blockquote>\n" }, { "answer_id": 71736175, "author": "Mark Homer", "author_id": 2316129, "author_profile": "https://Stackoverflow.com/users/2316129", "pm_score": 0, "selected": false, "text": "<p>it seems now that the nuget packages folder has moved to a machine wide global cache, using VS2022</p>\n<p><a href=\"https://i.stack.imgur.com/7bz2y.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7bz2y.png\" alt=\"visual studio 2022 global nuget packages\" /></a></p>\n" }, { "answer_id": 73687669, "author": "vsarunov", "author_id": 3574176, "author_profile": "https://Stackoverflow.com/users/3574176", "pm_score": 0, "selected": false, "text": "<p>For me the issue was that the solution was to deep into the documents folder and on windows 10 there is a path character limit which was reached. As soon as I moved the solution folder up couple of folders this fixed the issue.</p>\n" } ]
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/C++ language? </p>\n</blockquote>\n\n<p>The concept of a placeholder for a value - variables - maps onto something we're taught in school - algebra. There isn't an existing parallel you can draw without understanding how memory is physically laid out within a computer, and no one thinks about this kind of thing until they're dealing with low level things - at the C/C++/byte communications level.</p>\n\n<blockquote>\n <p>Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level?</p>\n</blockquote>\n\n<p>Addresses boxes. I remember when I was learning to program BASIC into microcomputers, there were these pretty books with games in them, and sometimes you had to poke values into particular addresses. They had a picture of a bunch of boxes, incrementally labelled with 0, 1, 2... and it was explained that only one small thing (a byte) could fit in these boxes, and there were a lot of them - some computers had as many as 65535! They were next to each other, and they all had an address.</p>\n\n<blockquote>\n <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>\n</blockquote>\n\n<p>For a drill? Make a struct:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>struct {\nchar a;\nchar b;\nchar c;\nchar d;\n} mystruct;\nmystruct.a = 'r';\nmystruct.b = 's';\nmystruct.c = 't';\nmystruct.d = 'u';\n\nchar* my_pointer;\nmy_pointer = &amp;mystruct.b;\ncout &lt;&lt; 'Start: my_pointer = ' &lt;&lt; *my_pointer &lt;&lt; endl;\nmy_pointer++;\ncout &lt;&lt; 'After: my_pointer = ' &lt;&lt; *my_pointer &lt;&lt; endl;\nmy_pointer = &amp;mystruct.a;\ncout &lt;&lt; 'Then: my_pointer = ' &lt;&lt; *my_pointer &lt;&lt; endl;\nmy_pointer = my_pointer + 3;\ncout &lt;&lt; 'End: my_pointer = ' &lt;&lt; *my_pointer &lt;&lt; endl;\n</code></pre>\n\n<p>Same example as above, except in C:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>// Same example as above, except in C:\nstruct {\n char a;\n char b;\n char c;\n char d;\n} mystruct;\n\nmystruct.a = 'r';\nmystruct.b = 's';\nmystruct.c = 't';\nmystruct.d = 'u';\n\nchar* my_pointer;\nmy_pointer = &amp;mystruct.b;\n\nprintf(\"Start: my_pointer = %c\\n\", *my_pointer);\nmy_pointer++;\nprintf(\"After: my_pointer = %c\\n\", *my_pointer);\nmy_pointer = &amp;mystruct.a;\nprintf(\"Then: my_pointer = %c\\n\", *my_pointer);\nmy_pointer = my_pointer + 3;\nprintf(\"End: my_pointer = %c\\n\", *my_pointer);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Start: my_pointer = s\nAfter: my_pointer = t\nThen: my_pointer = r\nEnd: my_pointer = u\n</code></pre>\n\n<p>Perhaps that explains some of the basics through example?</p>\n" }, { "answer_id": 5734, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 3, "selected": false, "text": "<p>I don't think pointers as a concept are particularly tricky - most students' mental models map to something like this and some quick box sketches can help.</p>\n\n<p>The difficulty, at least that which I've experienced in the past and seen others deal with, is that the management of pointers in C/C++ can be unncessarily convoluted.</p>\n" }, { "answer_id": 5735, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 0, "selected": false, "text": "<p>I don't see what is so confusing about pointers. They point to a location in memory, that is it stores the memory address. In C/C++ you can specify the type the pointer points to. For example:</p>\n\n<pre><code>int* my_int_pointer;\n</code></pre>\n\n<p>Says that my_int_pointer contains the address to a location that contains an int.</p>\n\n<p>The problem with pointers is that they point to a location in memory, so it is easy to trail off into some location you should not be in. As proof look at the numerous security holes in C/C++ applications from buffer overflow (incrementing the pointer past the allocated boundary).</p>\n" }, { "answer_id": 5736, "author": "JSN", "author_id": 108465, "author_profile": "https://Stackoverflow.com/users/108465", "pm_score": 6, "selected": false, "text": "<p>The reason pointers seem to confuse so many people is that they mostly come with little or no background in computer architecture. Since many don't seem to have an idea of how computers (the machine) is actually implemented - working in C/C++ seems alien.</p>\n\n<p>A drill is to ask them to implement a simple bytecode based virtual machine (in any language they chose, python works great for this) with an instruction set focussed on pointer operations (load, store, direct/indirect addressing). Then ask them to write simple programs for that instruction set.</p>\n\n<p>Anything requiring slightly more than simple addition is going to involve pointers and they are sure to get it.</p>\n" }, { "answer_id": 5750, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 2, "selected": false, "text": "<p>I think that the main reason that people have trouble with it is because it's generally not taught in an interesting and engaging manner. I'd like to see a lecturer get 10 volunteers from the crowd and give them a 1 meter ruler each, get them to stand around in a certain configuration and use the rulers to point at each other. Then show pointer arithmetic by moving people around (and where they point their rulers). It'd be a simple but effective (and above all memorable) way of showing the concepts without getting too bogged down in the mechanics.</p>\n\n<p>Once you get to C and C++ it seems to get harder for some people. I'm not sure if this is because they are finally putting theory that they don't properly grasp into practice or because pointer manipulation is inherently harder in those languages. I can't remember my own transition that well, but I <strong>knew</strong> pointers in Pascal and then moved to C and got totally lost.</p>\n" }, { "answer_id": 5754, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 11, "selected": true, "text": "<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p><em>Disclaimer: For all intents and purposes, this explanation and the example memory\nlayouts are vastly simplified. There's more overhead and a lot more details you would\nneed to know if you need to deal with memory on a low-level basis. However, for the\nintents of explaining memory and pointers, it is accurate enough.</em></p>\n\n<hr>\n\n<p>Let's assume the THouse class used below looks like this:</p>\n\n<pre><code>type\n THouse = class\n private\n FName : array[0..9] of Char;\n public\n constructor Create(name: PChar);\n end;\n</code></pre>\n\n<p>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.</p>\n\n<p>In memory, there will be some overhead associated with the house allocation, I'll illustrate this below like this:</p>\n\n<pre>\n---[ttttNNNNNNNNNN]---\n ^ ^\n | |\n | +- the FName array\n |\n +- overhead\n</pre>\n\n<p>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.</p>\n\n<hr>\n\n<p><strong>Allocate memory</strong></p>\n\n<p>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.</p>\n\n<p>In other words, the entrepreneur will choose the spot.</p>\n\n<pre><code>THouse.Create('My house');\n</code></pre>\n\n<p>Memory layout:</p>\n\n<pre>\n---[ttttNNNNNNNNNN]---\n 1234My house\n</pre>\n\n<hr>\n\n<p><strong>Keep a variable with the address</strong></p>\n\n<p>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.</p>\n\n<pre><code>var\n h: THouse;\nbegin\n h := THouse.Create('My house');\n ...\n</code></pre>\n\n<p>Memory layout:</p>\n\n<pre>\n h\n v\n---[ttttNNNNNNNNNN]---\n 1234My house\n</pre>\n\n<hr>\n\n<p><strong>Copy pointer value</strong> </p>\n\n<p>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 <em>the other house</em> has been modified in the same manner, unless you can explicitly detect that it's actually just one house.</p>\n\n<p><em>Note</em> This is usually the concept that I have the most problem explaining to people, two pointers does not mean two objects or memory blocks.</p>\n\n<pre><code>var\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('My house');\n h2 := h1; // copies the address, not the house\n ...\n</code></pre>\n\n<pre>\n h1\n v\n---[ttttNNNNNNNNNN]---\n 1234My house\n ^\n h2\n</pre>\n\n<hr>\n\n<p><strong>Freeing the memory</strong> </p>\n\n<p>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.</p>\n\n<pre><code>var\n h: THouse;\nbegin\n h := THouse.Create('My house');\n ...\n h.Free;\n h := nil;\n</code></pre>\n\n<p>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.</p>\n\n<p>Memory layout:</p>\n\n<pre>\n h &lt;--+\n v +- before free\n---[ttttNNNNNNNNNN]--- |\n 1234My house &lt;--+\n\n h (now points nowhere) &lt;--+\n +- after free\n---------------------- | (note, memory might still\n xx34My house &lt;--+ contain some data)\n</pre>\n\n<hr>\n\n<p><strong>Dangling pointers</strong></p>\n\n<p>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).</p>\n\n<pre><code>var\n h: THouse;\nbegin\n h := THouse.Create('My house');\n ...\n h.Free;\n ... // forgot to clear h here\n h.OpenFrontDoor; // will most likely fail\n</code></pre>\n\n<p>Using <code>h</code> after the call to <code>.Free</code> <em>might</em> work, but that is just pure luck. Most likely it will fail, at a customers place, in the middle of a critical operation.</p>\n\n<pre>\n h &lt;--+\n v +- before free\n---[ttttNNNNNNNNNN]--- |\n 1234My house &lt;--+\n\n h &lt;--+\n v +- after free\n---------------------- |\n xx34My house &lt;--+\n</pre>\n\n<p>As you can see, h still points to the remnants of the data in memory, but\nsince it might not be complete, using it as before might fail.</p>\n\n<hr>\n\n<p><strong>Memory leak</strong> </p>\n\n<p>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.</p>\n\n<pre><code>var\n h: THouse;\nbegin\n h := THouse.Create('My house');\n h := THouse.Create('My house'); // uh-oh, what happened to our first house?\n ...\n h.Free;\n h := nil;\n</code></pre>\n\n<p>Here we overwrote the contents of the <code>h</code> 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.</p>\n\n<p>Memory layout after first allocation:</p>\n\n<pre>\n h\n v\n---[ttttNNNNNNNNNN]---\n 1234My house\n</pre>\n\n<p>Memory layout after second allocation:</p>\n\n<pre>\n h\n v\n---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN]\n 1234My house 5678My house\n</pre>\n\n<p>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:</p>\n\n<pre><code>procedure OpenTheFrontDoorOfANewHouse;\nvar\n h: THouse;\nbegin\n h := THouse.Create('My house');\n h.OpenFrontDoor;\n // uh-oh, no .Free here, where does the address go?\nend;\n</code></pre>\n\n<p>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.</p>\n\n<p>Memory layout:</p>\n\n<pre>\n h &lt;--+\n v +- before losing pointer\n---[ttttNNNNNNNNNN]--- |\n 1234My house &lt;--+\n\n h (now points nowhere) &lt;--+\n +- after losing pointer\n---[ttttNNNNNNNNNN]--- |\n 1234My house &lt;--+\n</pre>\n\n<p>As you can see, the old data is left intact in memory, and will not\nbe reused by the memory allocator. The allocator keeps track of which\nareas of memory has been used, and will not reuse them unless you\nfree it.</p>\n\n<hr>\n\n<p><strong>Freeing the memory but keeping a (now invalid) reference</strong> </p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>var\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('My house');\n h2 := h1; // copies the address, not the house\n ...\n h1.Free;\n h1 := nil;\n h2.OpenFrontDoor; // uh-oh, what happened to our house?\n</code></pre>\n\n<p>Here the house was torn down, through the reference in <code>h1</code>, and while <code>h1</code> was cleared as well, <code>h2</code> still has the old, out-of-date, address. Access to the house that is no longer standing might or might not work.</p>\n\n<p>This is a variation of the dangling pointer above. See its memory layout.</p>\n\n<hr>\n\n<p><strong>Buffer overrun</strong> </p>\n\n<p>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.</p>\n\n<p>This is the reason I chose a fixed-size array. To set the stage, assume that\nthe second house we allocate will, for some reason, be placed before the\nfirst one in memory. In other words, the second house will have a lower\naddress than the first one. Also, they're allocated right next to each other.</p>\n\n<p>Thus, this code:</p>\n\n<pre><code>var\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('My house');\n h2 := THouse.Create('My other house somewhere');\n ^-----------------------^\n longer than 10 characters\n 0123456789 &lt;-- 10 characters\n</code></pre>\n\n<p>Memory layout after first allocation:</p>\n\n<pre>\n h1\n v\n-----------------------[ttttNNNNNNNNNN]\n 5678My house\n</pre>\n\n<p>Memory layout after second allocation:</p>\n\n<pre>\n h2 h1\n v v\n---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN]\n 1234My other house somewhereouse\n ^---+--^\n |\n +- overwritten\n</pre>\n\n<p>The part that will most often cause crash is when you overwrite important parts\nof the data you stored that really should not be randomly changed. For instance\nit might not be a problem that parts of the name of the h1-house was changed,\nin terms of crashing the program, but overwriting the overhead of the\nobject will most likely crash when you try to use the broken object,\nas will overwriting links that is stored to\nother objects in the object.</p>\n\n<hr>\n\n<p><strong>Linked lists</strong> </p>\n\n<p>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.</p>\n\n<pre><code>var\n h1, h2: THouse;\nbegin\n h1 := THouse.Create('Home');\n h2 := THouse.Create('Cabin');\n h1.NextHouse := h2;\n</code></pre>\n\n<p>Here we create a link from our home house to our cabin. We can follow the chain until a house has no <code>NextHouse</code> reference, which means it's the last one. To visit all our houses, we could use the following code:</p>\n\n<pre><code>var\n h1, h2: THouse;\n h: THouse;\nbegin\n h1 := THouse.Create('Home');\n h2 := THouse.Create('Cabin');\n h1.NextHouse := h2;\n ...\n h := h1;\n while h &lt;&gt; nil do\n begin\n h.LockAllDoors;\n h.CloseAllWindows;\n h := h.NextHouse;\n end;\n</code></pre>\n\n<p>Memory layout (added NextHouse as a link in the object, noted with\nthe four LLLL's in the below diagram):</p>\n\n<pre>\n h1 h2\n v v\n---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL]\n 1234Home + 5678Cabin +\n | ^ |\n +--------+ * (no link)\n</pre>\n\n<hr>\n\n<p><strong>In basic terms, what is a memory address?</strong></p>\n\n<p>A memory address is in basic terms just a number. If you think of memory\nas a big array of bytes, the very first byte has the address 0, the next one\nthe address 1 and so on upwards. This is simplified, but good enough.</p>\n\n<p>So this memory layout:</p>\n\n<pre>\n h1 h2\n v v\n---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN]\n 1234My house 5678My house\n</pre>\n\n<p>Might have these two address (the leftmost - is address 0):</p>\n\n<ul>\n<li>h1 = 4</li>\n<li>h2 = 23</li>\n</ul>\n\n<p>Which means that our linked list above might actuall look like this:</p>\n\n<pre>\n h1 (=4) h2 (=28)\n v v\n---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL]\n 1234Home 0028 5678Cabin 0000\n | ^ |\n +--------+ * (no link)\n</pre>\n\n<p>It is typical to store an address that \"points nowhere\" as a zero-address.</p>\n\n<hr>\n\n<p><strong>In basic terms, what is a pointer?</strong></p>\n\n<p>A pointer is just a variable holding a memory address. You can typically ask the programming\nlanguage to give you its number, but most programming languages and runtimes tries to\nhide the fact that there is a number beneath, just because the number itself does not\nreally hold any meaning to you. It is best to think of a pointer as a black box, ie.\nyou don't really know or care about how it is actually implemented, just as long as it\nworks.</p>\n" }, { "answer_id": 5772, "author": "David", "author_id": 381, "author_profile": "https://Stackoverflow.com/users/381", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.augustcouncil.com/~tgibson/tutorial/ptr.html\" rel=\"noreferrer\">An example of a tutorial with a good set of diagrams helps greatly with the understanding of pointers</a>. </p>\n\n<p>Joel Spolsky makes some good points about understanding pointers in his <a href=\"http://www.joelonsoftware.com/articles/fog0000000073.html\" rel=\"noreferrer\">Guerrilla Guide to Interviewing</a> article:</p>\n\n<blockquote>\n <p>For some reason most people seem to be born without the part of the brain that understands pointers. This is an aptitude thing, not a skill thing – it requires a complex form of doubly-indirected thinking that some people just can't do.</p>\n</blockquote>\n" }, { "answer_id": 6416, "author": "Tryke", "author_id": 773, "author_profile": "https://Stackoverflow.com/users/773", "pm_score": 7, "selected": false, "text": "<p>In my first Comp Sci class, we did the following exercise. Granted, this was a lecture hall with roughly 200 students in it...</p>\n\n<p>Professor writes on the board: <code>int john;</code></p>\n\n<p>John stands up</p>\n\n<p>Professor writes: <code>int *sally = &amp;john;</code></p>\n\n<p>Sally stands up, points at john</p>\n\n<p>Professor: <code>int *bill = sally;</code></p>\n\n<p>Bill stands up, points at John</p>\n\n<p>Professor: <code>int sam;</code></p>\n\n<p>Sam stands up</p>\n\n<p>Professor: <code>bill = &amp;sam;</code></p>\n\n<p>Bill now points to Sam.</p>\n\n<p>I think you get the idea. I think we spent about an hour doing this, until we went over the basics of pointer assignment.</p>\n" }, { "answer_id": 7271, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": false, "text": "<p>The complexities of pointers go beyond what we can easily teach. Having students point to each other and using pieces of paper with house addresses are both great learning tools. They do a great job of introducing the basic concepts. Indeed, learning the basic concepts is <em>vital</em> to successfully using pointers. However, in production code, it's common to get into much more complex scenarios than these simple demonstrations can encapsulate.</p>\n\n<p>I've been involved with systems where we had structures pointing to other structures pointing to other structures. Some of those structures also contained embedded structures (rather than pointers to additional structures). This is where pointers get really confusing. If you've got multiple levels of indirection, and you start ending up with code like this:</p>\n\n<pre><code>widget-&gt;wazzle.fizzle = fazzle.foozle-&gt;wazzle;\n</code></pre>\n\n<p>it can get confusing really quickly (imagine a lot more lines, and potentially more levels). Throw in arrays of pointers, and node to node pointers (trees, linked lists) and it gets worse still. I've seen some really good developers get lost once they started working on such systems, even developers who understood the basics really well.</p>\n\n<p>Complex structures of pointers don't necessarily indicate poor coding, either (though they can). Composition is a vital piece of good object-oriented programming, and in languages with raw pointers, it will inevitably lead to multi-layered indirection. Further, systems often need to use third-party libraries with structures which don't match each other in style or technique. In situations like that, complexity is naturally going to arise (though certainly, we should fight it as much as possible).</p>\n\n<p>I think the best thing colleges can do to help students learn pointers is to to use good demonstrations, combined with projects that require pointer use. One difficult project will do more for pointer understanding than a thousand demonstrations. Demonstrations can get you a shallow understanding, but to deeply grasp pointers, you have to really use them.</p>\n" }, { "answer_id": 7283, "author": "bruceatk", "author_id": 791, "author_profile": "https://Stackoverflow.com/users/791", "pm_score": 2, "selected": false, "text": "<p>I don't think that pointers themselves are confusing. Most people can understand the concept. Now how many pointers can you think about or how many levels of indirection are you comfortable with. It doesn't take too many to put people over the edge. The fact that they can be changed accidently by bugs in your program can also make them very difficult to debug when things go wrong in your code.</p>\n" }, { "answer_id": 7510, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 4, "selected": false, "text": "<p>I found Ted Jensen's &quot;Tutorial on Pointers and Arrays in C&quot; an excellent resource for learning about pointers. It is divided into 10 lessons, beginning with an explanation of what pointers are (and what they're for) and finishing with function pointers. <a href=\"http://web.archive.org/web/20181011221220/http://home.netcom.com:80/%7Etjensen/ptr/cpoint.htm\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20181011221220/http://home.netcom.com:80/~tjensen/ptr/cpoint.htm</a></p>\n<p>Moving on from there, Beej's Guide to Network Programming teaches the Unix sockets API, from which you can begin to do really fun things. <a href=\"http://beej.us/guide/bgnet/\" rel=\"nofollow noreferrer\">http://beej.us/guide/bgnet/</a></p>\n" }, { "answer_id": 12978, "author": "Christopher Scott", "author_id": 1346, "author_profile": "https://Stackoverflow.com/users/1346", "pm_score": 2, "selected": false, "text": "<p>I like the house address analogy, but I've always thought of the address being to the mailbox itself. This way you can visualize the concept of dereferencing the pointer (opening the mailbox). </p>\n\n<p>For instance following a linked list:\n1) start with your paper with the address\n2) Go to the address on the paper\n3) Open the mailbox to find a new piece of paper with the next address on it</p>\n\n<p>In a linear linked list, the last mailbox has nothing in it (end of the list). In a circular linked list, the last mailbox has the address of the first mailbox in it.</p>\n\n<p>Note that step 3 is where the dereference occurs and where you'll crash or go wrong when the address is invalid. Assuming you could walk up to the mailbox of an invalid address, imagine that there's a black hole or something in there that turns the world inside out :)</p>\n" }, { "answer_id": 13096, "author": "Wilka", "author_id": 1367, "author_profile": "https://Stackoverflow.com/users/1367", "pm_score": 7, "selected": false, "text": "<p>An analogy I've found helpful for explaining pointers is hyperlinks. Most people can understand that a link on a web page 'points' to another page on the internet, and if you can copy &amp; paste that hyperlink then they will both point to the same original web page. If you go and edit that original page, then follow either of those links (pointers) you'll get that new updated page.</p>\n" }, { "answer_id": 23118, "author": "SarekOfVulcan", "author_id": 2531, "author_profile": "https://Stackoverflow.com/users/2531", "pm_score": 0, "selected": false, "text": "<p>Just to confuse things a bit more, sometimes you have to work with handles instead of pointers. Handles are pointers to pointers, so that the back end can move things in memory to defragment the heap. If the pointer changes in mid-routine, the results are unpredictable, so you first have to lock the handle to make sure nothing goes anywhere.</p>\n\n<p><a href=\"http://arjay.bc.ca/Modula-2/Text/Ch15/Ch15.8.html#15.8.5\" rel=\"nofollow noreferrer\">http://arjay.bc.ca/Modula-2/Text/Ch15/Ch15.8.html#15.8.5</a> talks about it a bit more coherently than me. :-)</p>\n" }, { "answer_id": 23241, "author": "Baltimark", "author_id": 1179, "author_profile": "https://Stackoverflow.com/users/1179", "pm_score": 3, "selected": false, "text": "<p>I think that what makes pointers tricky to learn is that until pointers you're comfortable with the idea that \"at this memory location is a set of bits that represent an int, a double, a character, whatever\". </p>\n\n<p>When you first see a pointer, you don't really get what's at that memory location. \"What do you mean, it holds an <em>address</em>?\"</p>\n\n<p>I don't agree with the notion that \"you either get them or you don't\". </p>\n\n<p>They become easier to understand when you start finding real uses for them (like not passing large structures into functions). </p>\n" }, { "answer_id": 35003, "author": "joel.neely", "author_id": 3525, "author_profile": "https://Stackoverflow.com/users/3525", "pm_score": 1, "selected": false, "text": "<p>Post office box number.</p>\n\n<p>It's a piece of information that allows you to access something else.</p>\n\n<p>(And if you do arithmetic on post office box numbers, you may have a problem, because the letter goes in the wrong box. And if somebody moves to another state -- with no forwarding address -- then you have a dangling pointer. On the other hand -- if the post office forwards the mail, then you have a pointer to a pointer.)</p>\n" }, { "answer_id": 758499, "author": "Breton", "author_id": 51101, "author_profile": "https://Stackoverflow.com/users/51101", "pm_score": 3, "selected": false, "text": "<p>The problem with pointers is not the concept. It's the execution and language involved. Additional confusion results when teachers assume that it's the CONCEPT of pointers that's difficult, and not the jargon, or the convoluted mess C and C++ makes of the concept. So vast amounts of effort are poored into explaining the concept (like in the accepted answer for this question) and it's pretty much just wasted on someone like me, because I already understand all of that. It's just explaining the wrong part of the problem.</p>\n\n<p>To give you an idea of where I'm coming from, I'm someone who understands pointers perfectly well, and I can use them competently in assembler language. Because in assembler language they are not referred to as pointers. They are referred to as addresses. When it comes to programming and using pointers in C, I make a lot of mistakes and get really confused. I still have not sorted this out. Let me give you an example.</p>\n\n<p>When an api says:</p>\n\n<pre><code>int doIt(char *buffer )\n//*buffer is a pointer to the buffer\n</code></pre>\n\n<p>what does it want?</p>\n\n<p>it could want:</p>\n\n<p>a number representing an address to a buffer</p>\n\n<p>(To give it that, do I say <code>doIt(mybuffer)</code>, or <code>doIt(*myBuffer)</code>?)</p>\n\n<p>a number representing the address to an address to a buffer</p>\n\n<p>(is that <code>doIt(&amp;mybuffer)</code> or <code>doIt(mybuffer)</code> or <code>doIt(*mybuffer)</code>?)</p>\n\n<p>a number representing the address to the address to the address to the buffer</p>\n\n<p>(maybe that's <code>doIt(&amp;mybuffer)</code>. or is it <code>doIt(&amp;&amp;mybuffer)</code> ? or even <code>doIt(&amp;&amp;&amp;mybuffer)</code>)</p>\n\n<p>and so on, and the language involved doesn't make it as clear because it involves the words \"pointer\" and \"reference\" that don't hold as much meaning and clarity to me as \"x holds the address to y\" and \"this function requires an address to y\". The answer additionally depends on just what the heck \"mybuffer\" is to begin with, and what doIt intends to do with it. The language doesn't support the levels of nesting that are encountered in practice. Like when I have to hand a \"pointer\" in to a function that creates a new buffer, and it modifies the pointer to point at the new location of the buffer. Does it really want the pointer, or a pointer to the pointer, so it knows where to go to modify the contents of the pointer. Most of the time I just have to guess what is meant by \"pointer\" and most of the time I'm wrong, regardless of how much experience I get at guessing.</p>\n\n<p>\"Pointer\" is just too overloaded. Is a pointer an address to a value? or is it a variable that holds an address to a value. When a function wants a pointer, does it want the address that the pointer variable holds, or does it want the address to the pointer variable?\nI'm confused.</p>\n" }, { "answer_id": 758569, "author": "Waylon Flinn", "author_id": 74291, "author_profile": "https://Stackoverflow.com/users/74291", "pm_score": 2, "selected": false, "text": "<p>I think it might actually be a syntax issue. The C/C++ syntax for pointers seems inconsistent and more complex than it needs to be.</p>\n\n<p>Ironically, the thing that actually helped me to understand pointers was encountering the concept of an iterator in the c++ <a href=\"http://www.sgi.com/tech/stl/stl_introduction.html\" rel=\"nofollow noreferrer\">Standard Template Library</a>. It's ironic because I can only assume that iterators were conceived as a generalization of the pointer.</p>\n\n<p>Sometimes you just can't see the forest until you learn to ignore the trees.</p>\n" }, { "answer_id": 758598, "author": "rama-jka toti", "author_id": 75248, "author_profile": "https://Stackoverflow.com/users/75248", "pm_score": 1, "selected": false, "text": "<p>Not a bad way to grasp it, via iterators.. but keep looking you'll see Alexandrescu start complaining about them.</p>\n\n<p>Many ex-C++ devs (that never understood that iterators are a modern pointer before dumping the language) jump to C# and still believe they have decent iterators.</p>\n\n<p>Hmm, the problem is that all that iterators are is in complete odds at what the runtime platforms (Java/CLR) are trying to achieve: new, simple, everyone-is-a-dev usage. Which can be good, but they said it once in the purple book and they said it even before and before C:</p>\n\n<p>Indirection.</p>\n\n<p>A very powerful concept but never so if you do it all the way.. Iterators are useful as they help with abstraction of algorithms, another example. And compile-time is the place for an algorithm, very simple. You know code + data, or in that other language C#:</p>\n\n<p>IEnumerable + LINQ + Massive Framework = 300MB runtime penalty indirection of lousy, dragging apps via heaps of instances of reference types..</p>\n\n<p>\"Le Pointer is cheap.\"</p>\n" }, { "answer_id": 761227, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>The reason it's so hard to understand is not because it's a difficult concept but because <strong>the syntax is inconsistent</strong>.</p>\n<pre><code>int *mypointer;\n</code></pre>\n<p>You are first learned that the leftmost part of a variable creation defines the type of the variable. Pointer declaration does not work like this in C and C++. Instead they say that the variable is pointing on the type to the left. In this case: <em><code>*</code>mypointer <strong>is pointing</strong> on an int.</em></p>\n<p>I didn't fully grasp pointers until i tried using them in C# (with unsafe), they work in exact same way but with logical and consistent syntax. The pointer is a type itself. Here <em>mypointer <strong>is</strong> a pointer to an int.</em></p>\n<pre><code>int* mypointer;\n</code></pre>\n<p>Don't even get me started on function pointers...</p>\n" }, { "answer_id": 800619, "author": "toto", "author_id": 92942, "author_profile": "https://Stackoverflow.com/users/92942", "pm_score": 3, "selected": false, "text": "<p>I could work with pointers when I only knew C++. I kind of knew what to do in some cases and what not to do from trial/error. But the thing that gave me complete understanding is assembly language. If you do some serious instruction level debugging with an assembly language program you've written, you should be able to understand a lot of things.</p>\n" }, { "answer_id": 819331, "author": "Joshua Fox", "author_id": 39242, "author_profile": "https://Stackoverflow.com/users/39242", "pm_score": 2, "selected": false, "text": "<p>The confusion comes from the multiple abstraction layers mixed together in the \"pointer\" concept. Programmers don't get confused by ordinary references in Java/Python, but pointers are different in that they expose characteristics of the underlying memory-architecture.</p>\n\n<p>It is a good principle to cleanly separate layers of abstraction, and pointers do not do that.</p>\n" }, { "answer_id": 2057116, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 5, "selected": false, "text": "<p>The reason I had a hard time understanding pointers, at first, is that many explanations include a lot of crap about passing by reference. All this does is confuse the issue. When you use a pointer parameter, you're <em>still</em> passing by value; but the value happens to be an address rather than, say, an int.</p>\n\n<p>Someone else has already linked to this tutorial, but I can highlight the moment when I began to understand pointers:</p>\n\n<p><a href=\"http://pweb.netcom.com/~tjensen/ptr/ch3x.htm\" rel=\"noreferrer\">A Tutorial on Pointers and Arrays in C: Chapter 3 - Pointers and Strings</a></p>\n\n<pre><code>int puts(const char *s);\n</code></pre>\n\n<blockquote>\n <p>For the moment, ignore the <code>const.</code> The parameter passed to <code>puts()</code> is a pointer, <strong>that is the value of a pointer (since all parameters in C are passed by value), and the value of a pointer is the address to which it points, or, simply, an address.</strong> Thus when we write <code>puts(strA);</code> as we have seen, we are passing the address of strA[0].</p>\n</blockquote>\n\n<p>The moment I read these words, the clouds parted and a beam of sunlight enveloped me with pointer understanding.</p>\n\n<p>Even if you're a VB .NET or C# developer (as I am) and never use unsafe code, it's still worth understanding how pointers work, or you won't understand how object references work. Then you'll have the common-but-mistaken notion that passing an object reference to a method copies the object.</p>\n" }, { "answer_id": 2057337, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 3, "selected": false, "text": "<p>I think the main barrier to understanding pointers is bad teachers.</p>\n\n<p>Almost everyone are taught lies about pointers: That they are <em>nothing more than memory addresses</em>, or that they allow you to point to <em>arbitrary locations</em>. </p>\n\n<p>And of course that they are difficult to understand, dangerous and semi-magical.</p>\n\n<p>None of which is true. Pointers are actually fairly simple concepts, <em>as long as you stick to what the C++ language has to say about them</em> and don't imbue them with attributes that \"usually\" turn out to work in practice, but nevertheless aren't guaranteed by the language, and so aren't part of the actual concept of a pointer.</p>\n\n<p>I tried to write up an explanation of this a few months ago in <a href=\"https://github.com/kgisl/cs8251/blob/master/files/pointerConspiracy2.pdf\" rel=\"nofollow noreferrer\">this blog post</a> -- hopefully it'll help someone.</p>\n\n<p>(Note, before anyone gets pedantic on me, yes, the C++ standard does say that pointers <em>represent</em> memory addresses. But it does not say that \"pointers are memory addresses, and nothing but memory addresses and may be used or thought of interchangeably with memory addresses\". The distinction is important)</p>\n" }, { "answer_id": 13204366, "author": "nurmurat", "author_id": 887620, "author_profile": "https://Stackoverflow.com/users/887620", "pm_score": 0, "selected": false, "text": "<p>Every C/C++ beginner has the same problem and that problem occurs not because \"pointers are hard to learn\" but \"who and how it is explained\". Some learners gather it verbally some visually and the best way of explaining it is to use <strong>\"train\" example</strong> (suits for verbal and visual example).</p>\n\n<p>Where <strong>\"locomotive\"</strong> is a pointer which <strong>can not</strong> hold anything and <strong>\"wagon\"</strong> is what \"locomotive\" tries pull (or point to). After, you can classify the \"wagon\" itself, can it hold animals,plants or people (or a mix of them).</p>\n" }, { "answer_id": 15842434, "author": "Mike", "author_id": 1348709, "author_profile": "https://Stackoverflow.com/users/1348709", "pm_score": 3, "selected": false, "text": "<p>I thought I'd add an analogy to this list that I found very helpful when explaining pointers (back in the day) as a Computer Science Tutor; first, let's:</p>\n\n<hr>\n\n<p><strong>Set the stage</strong>: </p>\n\n<p>Consider a parking lot with 3 spaces, these spaces are numbered:</p>\n\n<pre><code>-------------------\n| | | |\n| 1 | 2 | 3 |\n| | | |\n</code></pre>\n\n<p>In a way, this is like memory locations, they are sequential and contiguous.. sort of like an array. Right now there are no cars in them so it's like an empty array (<code>parking_lot[3] = {0}</code>).</p>\n\n<hr>\n\n<p><strong>Add the data</strong></p>\n\n<p>A parking lot never stays empty for long... if it did it would be pointless and no one would build any. So let's say as the day moves on the lot fills up with 3 cars, a blue car, a red car, and a green car:</p>\n\n<pre><code> 1 2 3\n-------------------\n| o=o | o=o | o=o |\n| |B| | |R| | |G| |\n| o-o | o-o | o-o |\n</code></pre>\n\n<p>These cars are all the same type (car) so one way to think of this is that our cars are some sort of data (say an <code>int</code>) but they have different values (<code>blue</code>, <code>red</code>, <code>green</code>; that could be an color <code>enum</code>)</p>\n\n<hr>\n\n<p><strong>Enter the pointer</strong></p>\n\n<p>Now if I take you into this parking lot, and ask you to find me a blue car, you extend one finger and use it to point to a blue car in spot 1. This is like taking a pointer and assigning it to a memory address (<code>int *finger = parking_lot</code>)</p>\n\n<p>Your finger (the pointer) is not the answer to my question. Looking <strong><em>at</em></strong> your finger tells me nothing, but if I look where you're finger is <em>pointing to</em> (dereferencing the pointer), I can find the car (the data) I was looking for.</p>\n\n<hr>\n\n<p><strong>Reassigning the pointer</strong></p>\n\n<p>Now I can ask you to find a red car instead and you can redirect your finger to a new car. Now your pointer (the same one as before) is showing me new data (the parking spot where the red car can be found) of the same type (the car). </p>\n\n<p>The pointer hasn't physically changed, it's still <em>your</em> finger, just the data it was showing me changed. (the \"parking spot\" address)</p>\n\n<hr>\n\n<p><strong>Double pointers (or a pointer to a pointer)</strong></p>\n\n<p>This works with more than one pointer as well. I can ask where is the pointer, which is pointing to the red car and you can use your other hand and point with a finger to the first finger. (this is like <code>int **finger_two = &amp;finger</code>)</p>\n\n<p>Now if I want to know where the blue car is I can follow the first finger's direction to the second finger, to the car (the data). </p>\n\n<hr>\n\n<p><strong>The dangling pointer</strong></p>\n\n<p>Now let's say you're feeling very much like a statue, and you want to hold your hand pointing at the red car indefinitely. What if that red car drives away?</p>\n\n<pre><code> 1 2 3\n-------------------\n| o=o | | o=o |\n| |B| | | |G| |\n| o-o | | o-o |\n</code></pre>\n\n<p>Your pointer is still pointing to where the red car <em>was</em> but is no longer. Let's say a new car pulls in there... a Orange car. Now if I ask you again, \"where is the red car\", you're still pointing there, but now you're wrong. That's not an red car, that's orange. </p>\n\n<hr>\n\n<p><strong>Pointer arithmetic</strong></p>\n\n<p>Ok, so you're still pointing at the second parking spot (now occupied by the Orange car)</p>\n\n<pre><code> 1 2 3\n-------------------\n| o=o | o=o | o=o |\n| |B| | |O| | |G| |\n| o-o | o-o | o-o |\n</code></pre>\n\n<p>Well I have a new question now... I want to know the color of the car in the <em>next</em> parking spot. You can see you're pointing at spot 2, so you just add 1 and you're pointing at the next spot. (<code>finger+1</code>), now since I wanted to know what the data was there, you have to check that spot (not just the finger) so you can deference the pointer (<code>*(finger+1)</code>) to see there is a green car present there (the data at that location)</p>\n" }, { "answer_id": 16264783, "author": "Bernd Jendrissek", "author_id": 117911, "author_profile": "https://Stackoverflow.com/users/117911", "pm_score": 1, "selected": false, "text": "<p>Some answers above have asserted that \"pointers aren't really hard\", but haven't gone on to address directly where \"pointer are hard!\" comes from. Some years back I tutored first year CS students (for only one year, since I clearly sucked at it) and it was clear to me that the <strong>idea</strong> of pointer is not hard. What's hard is understanding <strong>why and when you would want a pointer</strong>.</p>\n\n<p>I don't think you can divorce that question - why and when to use a pointer - from explaining broader software engineering issues. Why every variable should <em>not</em> be a global variable, and why one should factor out similar code into functions (that, get this, use <em>pointers</em> to specialize their behaviour to their call site).</p>\n" }, { "answer_id": 16694780, "author": "sashoalm", "author_id": 492336, "author_profile": "https://Stackoverflow.com/users/492336", "pm_score": 2, "selected": false, "text": "<p>The way I liked to explain it was in terms of arrays and indexes - people might not be familiar with pointers, but they generally know what an index is.</p>\n\n<p>So I say imagine that the RAM is an array (and you have only 10-bytes of RAM):</p>\n\n<pre><code>unsigned char RAM[10] = { 10, 14, 4, 3, 2, 1, 20, 19, 50, 9 };\n</code></pre>\n\n<p>Then a pointer to a variable is really just the index of (the first byte of) that variable in the RAM.</p>\n\n<p>So if you have a pointer/index <code>unsigned char index = 2</code>, then the value is obviously the third element, or the number 4. A pointer to a pointer is where you take that number and use it as an index itself, like <code>RAM[RAM[index]]</code>.</p>\n\n<p>I would draw an array on a list of paper, and just use it to show things like many pointers pointing to the same memory, pointer arithmetic, pointer to pointer, and so on.</p>\n" } ]
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#using-wildcard-characters-as-literals\" rel=\"noreferrer\">T-SQL Reference for LIKE</a>:</p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n\n<p>For your case:</p>\n\n<pre><code>... LIKE '%[_]d'\n</code></pre>\n" }, { "answer_id": 10415670, "author": "Gerardo Lima", "author_id": 394042, "author_profile": "https://Stackoverflow.com/users/394042", "pm_score": 8, "selected": false, "text": "<p>Obviously @Lasse solution is right, but there's another way to solve your problem: T-SQL operator <code>LIKE</code> defines the optional <a href=\"http://msdn.microsoft.com/en-us/library/ms179859%28v=sql.90%29.aspx\" rel=\"noreferrer\">ESCAPE</a> clause, that lets you declare a character which will escape the next character into the pattern.</p>\n\n<p>For your case, the following WHERE clauses are equivalent:</p>\n\n<pre><code>WHERE username LIKE '%[_]d'; -- @Lasse solution\nWHERE username LIKE '%$_d' ESCAPE '$';\nWHERE username LIKE '%^_d' ESCAPE '^';\n</code></pre>\n" }, { "answer_id": 50650186, "author": "Tek Mailer", "author_id": 5697368, "author_profile": "https://Stackoverflow.com/users/5697368", "pm_score": 3, "selected": false, "text": "<p>These solutions totally make sense. Unfortunately, neither worked for me as expected. Instead of trying to hassle with it, I went with a work around:</p>\n<pre><code>select *\nfrom information_schema.columns \nwhere replace(table_name,'_','!') not like '%!%'\norder by table_name\n</code></pre>\n" }, { "answer_id": 52702908, "author": "Arnór Barkarson", "author_id": 7436253, "author_profile": "https://Stackoverflow.com/users/7436253", "pm_score": 2, "selected": false, "text": "<p>This worked for me, just use the escape\n<code>'%\\_%'</code></p>\n" }, { "answer_id": 56812000, "author": "wolverine87", "author_id": 7885982, "author_profile": "https://Stackoverflow.com/users/7885982", "pm_score": 1, "selected": false, "text": "<p>None of these worked for me in SSIS v18.0, so I would up doing something like this:<br /><br />\n<code>WHERE CHARINDEX('_', thingyoursearching) &lt; 1</code><br /><br />..where I am trying to ignore strings with an underscore in them. If you want to find things that have an underscore, just flip it around:<br /><br />\n<code>WHERE CHARINDEX('_', thingyoursearching) &gt; 0</code></p>\n" }, { "answer_id": 64153299, "author": "Freddy Madsen", "author_id": 12632795, "author_profile": "https://Stackoverflow.com/users/12632795", "pm_score": 3, "selected": false, "text": "<p>I had a similar issue using like pattern <code>'%_%'</code> did not work - as the question indicates :-)</p>\n<p>Using <code>'%\\_%'</code> did not work either as this first <code>\\</code> is interpreted &quot;before the like&quot;.</p>\n<p>Using <code>'%\\\\_%'</code> works. The <code>\\\\</code> (double backslash) is first converted to single <code>\\</code> (backslash) and then used in the like pattern.</p>\n" }, { "answer_id": 66069453, "author": "Alex C.", "author_id": 2349128, "author_profile": "https://Stackoverflow.com/users/2349128", "pm_score": 3, "selected": false, "text": "<p>Adding <code>[ ]</code> did the job for me</p>\n<pre><code>like '%[\\\\_]%'\n</code></pre>\n" }, { "answer_id": 71712662, "author": "Zosoled", "author_id": 12221876, "author_profile": "https://Stackoverflow.com/users/12221876", "pm_score": 0, "selected": false, "text": "<p>Adding to <a href=\"https://stackoverflow.com/a/10415670/12221876\">Gerardo Lima's answer</a>, I was having problems when trying to use backslash as my escape character for the ESCAPE clause. This caused issues:</p>\n<pre><code>SELECT * FROM table WHERE email LIKE '%@%\\_%' ESCAPE '\\'\n</code></pre>\n<p>It was resolved by switching to an exclamation point. This worked:</p>\n<pre><code>SELECT * FROM table WHERE email LIKE '%@%!_%' ESCAPE '!'\n</code></pre>\n" } ]
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_query($sql);\n$db-&gt;sql_freeresult($result);\n</code></pre>\n\n<p>In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL.</p>\n\n<p>In the general case, you should not use NULL to represent zero. Incrementing NULL <em>should</em> 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</p>\n\n<pre><code>$sql = \"UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id\";\n</code></pre>\n\n<p>...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include</p>\n\n<pre><code>level INT DEFAULT '0' NOT NULL\n</code></pre>\n\n<p>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.</p>\n" }, { "answer_id": 5849, "author": "Mat", "author_id": 48, "author_profile": "https://Stackoverflow.com/users/48", "pm_score": 2, "selected": false, "text": "<pre><code>$sql = &quot;UPDATE skills SET level = level + 1 WHERE id = $id&quot;;\n</code></pre>\n<p>I just hope you are properly sanitising <code>$id</code> elsewhere in your code!</p>\n" }, { "answer_id": 5850, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 2, "selected": false, "text": "<p>try this</p>\n\n<pre><code>UPDATE skills SET level = level + 1 WHERE id = $id\n</code></pre>\n" }, { "answer_id": 5851, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 4, "selected": false, "text": "<p>This way:</p>\n\n<pre><code>UPDATE skills\nSET level = level + 1\nWHERE id = $id\n</code></pre>\n" }, { "answer_id": 5852, "author": "Sean Carpenter", "author_id": 729, "author_profile": "https://Stackoverflow.com/users/729", "pm_score": 1, "selected": false, "text": "<p>How about: </p>\n\n<pre><code>UPDATE skills SET level = level + 1 WHERE id = $id;\n</code></pre>\n" }, { "answer_id": 5861, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": -1, "selected": false, "text": "<p>Mat: That's what pasted in from the question. It hasn't been edited, so I attribute that to a bug in Markdown. But, oddly enough, I have noticed.</p>\n\n<p>Also: yes, <code>mysql_escape_string()</code>!</p>\n" }, { "answer_id": 25535, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 3, "selected": false, "text": "<p>With PDO and prepared query:</p>\n\n<pre><code>$query = $db-&gt;prepare(\"UPDATE skills SET level = level + 1 WHERE id = :id\")\n$query-&gt;bindValue(\":id\", $id);\n$result = $query-&gt;execute();\n</code></pre>\n" } ]
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 working.</p>\n\n<p>The code looked like this:</p>\n\n<pre><code>&lt;form action=\"mailto:[email protected]\"&gt;\n &lt;input type=\"hidden\" name=\"Subject\" value=\"Email subject\"&gt;\n &lt;input type=\"hidden\" name=\"Body\" value=\"Email body\"&gt;\n &lt;input type=\"submit\"&gt;\n&lt;/form&gt;\n</code></pre>\n\n<hr>\n\n<p><strong>Edit</strong>: 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.</p>\n" }, { "answer_id": 5868, "author": "Jay Mooney", "author_id": 733, "author_profile": "https://Stackoverflow.com/users/733", "pm_score": 0, "selected": false, "text": "<p>Does the e-mail content need to be in the e-mail? Could you store the large content somewhere centrally (file-share/FTP site) then just send a link to the content?</p>\n\n<p>This makes the recipient have an extra step, but you have a consistent e-mail size, so won't run into reliability problems due to unexpectedly large or excessive content.</p>\n" } ]
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:[email protected]"> <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 remember, however, that you need basicHttpBinding, and you can't use the new serializer (which is the default); you have to use the \"old\" XmlSerializer.</p>\n\n<p>Unfortunately, I don't work at the place where I did this anymore, so I can't go look at the code. I'll call my boss and see what I can dig up.</p>\n" }, { "answer_id": 15966, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": true, "text": "<p>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.</p>\n\n<p>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. :)</p>\n" }, { "answer_id": 3810639, "author": "Christian Hayter", "author_id": 115413, "author_profile": "https://Stackoverflow.com/users/115413", "pm_score": 0, "selected": false, "text": "<p>You do have to use the XmlSerializer. For example:</p>\n\n<pre><code>[ServiceContract(Namespace=\"CentreServiceNamespace\")]\n[XmlSerializerFormat(Style=OperationFormatStyle.Document, SupportFaults=true, Use=OperationFormatUse.Literal)]\npublic interface ICentreService {\n [OperationContract(Action=\"CentreServiceNamespace/MethodToReturnTrue\")]\n bool MethodToReturnTrue(string seedValue);\n}\n</code></pre>\n\n<p>You have to manually set the operation action name because the auto-generated WCF name is constructed differently from the ASMX action name (WCF includes the interface name as well, ASMX does not).</p>\n\n<p>Any data contracts you use should be decorated with <code>[XmlType]</code> rather than <code>[DataContract]</code>.</p>\n\n<p>Your config file should not need to change.</p>\n" } ]
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 behaviour. It's the only other parameter I could find that might be close to relevant.</p>\n<p>What does your hosts file look like? Maybe something weird is going on there that makes it think all weird domains are local to your network?</p>\n" }, { "answer_id": 5980, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 2, "selected": false, "text": "<p>try querying with a trailing dot to explicitly set the root:</p>\n\n<pre><code>host dlksfhoiahdsfiuhsdf.com.\n</code></pre>\n" }, { "answer_id": 160319, "author": "Zan Lynx", "author_id": 13422, "author_profile": "https://Stackoverflow.com/users/13422", "pm_score": 2, "selected": false, "text": "<p>It is probably not dnsmasq doing it, but your local resolver library. If you use a unixish, try removing the \"search\" or \"domain\" lines from /etc/resolv.conf</p>\n" }, { "answer_id": 342481, "author": "benc", "author_id": 2910, "author_profile": "https://Stackoverflow.com/users/2910", "pm_score": 1, "selected": false, "text": "<p>There might be other causes, but the most obvious cause is the configuration of /etc/resolv.conf, and the fact that most DNS clients like to be very terse about errors.</p>\n\n<pre><code>benc$ host thing.one\nHost thing.one not found: 3(NXDOMAIN)\n</code></pre>\n\n<p>(okay, what was I using for a DNS config?)</p>\n\n<pre><code>benc$ cat /etc/resolv.conf \nnameserver 192.168.1.1\n</code></pre>\n\n<p>(edit...)</p>\n\n<pre><code>benc$ cat /etc/resolv.conf \nsearch test.com\nnameserver 192.168.1.1\nbenc$ host thing.one\nthing.one.test.com has address 64.214.163.132\n</code></pre>\n\n<p>Without bothering to do a packet trace, the likely behavior is that it returns the error for the last FQDN it tried.</p>\n" }, { "answer_id": 21961685, "author": "parawizard", "author_id": 3341986, "author_profile": "https://Stackoverflow.com/users/3341986", "pm_score": 1, "selected": false, "text": "<p>You have a wildcard domain?</p>\n\n<p>dnsmasq is forwarding the appended name out to the external dns server and its getting wildcarded.</p>\n\n<p>you can use --server=/yourinternaldomainhere/ to make sure that your internal domain name lookups are not forwarded out.</p>\n\n<p>syntax in this case would be:</p>\n\n<p>--server=/domain/iptoforwardto</p>\n\n<p>and in this case leave the iptoforwardto area blank as you don't want it to forward anywhere.</p>\n" } ]
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>&gt;&gt;&gt; site = urllib.urlopen(\"http://python.org\")\n&gt;&gt;&gt; meta = site.info()\n&gt;&gt;&gt; print meta.getheaders(\"Content-Length\")\n['16535']\n&gt;&gt;&gt;\n</code></pre>\n" }, { "answer_id": 5935, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 5, "selected": false, "text": "<p>Using the returned-urllib-object method <code>info()</code>, you can get various information on the retrieved document. Example of grabbing the current Google logo:</p>\n<pre><code>&gt;&gt;&gt; import urllib\n&gt;&gt;&gt; d = urllib.urlopen(&quot;http://www.google.co.uk/logos/olympics08_opening.gif&quot;)\n&gt;&gt;&gt; print d.info()\n\nContent-Type: image/gif\nLast-Modified: Thu, 07 Aug 2008 16:20:19 GMT \nExpires: Sun, 17 Jan 2038 19:14:07 GMT \nCache-Control: public \nDate: Fri, 08 Aug 2008 13:40:41 GMT \nServer: gws \nContent-Length: 20172 \nConnection: Close\n</code></pre>\n<p>It's a dict, so to get the size of the file, you do <code>urllibobject.info()['Content-Length']</code></p>\n<pre><code>print f.info()['Content-Length']\n</code></pre>\n<p>And to get the size of the local file (for comparison), you can use the os.stat() command:</p>\n<pre><code>os.stat(&quot;/the/local/file.zip&quot;).st_size\n</code></pre>\n" }, { "answer_id": 5938, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 3, "selected": false, "text": "<p>Also if the server you are connecting to supports it, look at <a href=\"http://en.wikipedia.org/wiki/HTTP_ETag\" rel=\"noreferrer\">Etags</a> and the <a href=\"http://en.wikipedia.org/wiki/List_of_HTTP_headers#Requests\" rel=\"noreferrer\">If-Modified-Since</a> and <a href=\"http://en.wikipedia.org/wiki/List_of_HTTP_headers#Requests\" rel=\"noreferrer\">If-None-Match</a> headers.</p>\n\n<p>Using these will take advantage of the webserver's caching rules and will return a <a href=\"http://en.wikipedia.org/wiki/List_of_HTTP_status_codes#3xx_Redirection\" rel=\"noreferrer\">304 Not Modified</a> status code if the content hasn't changed.</p>\n" }, { "answer_id": 5985, "author": "Jonathan Works", "author_id": 309844, "author_profile": "https://Stackoverflow.com/users/309844", "pm_score": 6, "selected": true, "text": "<p>I have reproduced what you are seeing:</p>\n\n<pre><code>import urllib, os\nlink = \"http://python.org\"\nprint \"opening url:\", link\nsite = urllib.urlopen(link)\nmeta = site.info()\nprint \"Content-Length:\", meta.getheaders(\"Content-Length\")[0]\n\nf = open(\"out.txt\", \"r\")\nprint \"File on disk:\",len(f.read())\nf.close()\n\n\nf = open(\"out.txt\", \"w\")\nf.write(site.read())\nsite.close()\nf.close()\n\nf = open(\"out.txt\", \"r\")\nprint \"File on disk after download:\",len(f.read())\nf.close()\n\nprint \"os.stat().st_size returns:\", os.stat(\"out.txt\").st_size\n</code></pre>\n\n<p>Outputs this:</p>\n\n<pre><code>opening url: http://python.org\nContent-Length: 16535\nFile on disk: 16535\nFile on disk after download: 16535\nos.stat().st_size returns: 16861\n</code></pre>\n\n<p>What am I doing wrong here? Is os.stat().st_size not returning the correct size?</p>\n\n<hr>\n\n<p>Edit:\nOK, I figured out what the problem was:</p>\n\n<pre><code>import urllib, os\nlink = \"http://python.org\"\nprint \"opening url:\", link\nsite = urllib.urlopen(link)\nmeta = site.info()\nprint \"Content-Length:\", meta.getheaders(\"Content-Length\")[0]\n\nf = open(\"out.txt\", \"rb\")\nprint \"File on disk:\",len(f.read())\nf.close()\n\n\nf = open(\"out.txt\", \"wb\")\nf.write(site.read())\nsite.close()\nf.close()\n\nf = open(\"out.txt\", \"rb\")\nprint \"File on disk after download:\",len(f.read())\nf.close()\n\nprint \"os.stat().st_size returns:\", os.stat(\"out.txt\").st_size\n</code></pre>\n\n<p>this outputs:</p>\n\n<pre><code>$ python test.py\nopening url: http://python.org\nContent-Length: 16535\nFile on disk: 16535\nFile on disk after download: 16535\nos.stat().st_size returns: 16535\n</code></pre>\n\n<p>Make sure you are opening both files for binary read/write.</p>\n\n<pre><code>// open for binary write\nopen(filename, \"wb\")\n// open for binary read\nopen(filename, \"rb\")\n</code></pre>\n" }, { "answer_id": 25502448, "author": "Madhusudhan", "author_id": 3963432, "author_profile": "https://Stackoverflow.com/users/3963432", "pm_score": 3, "selected": false, "text": "<p>In Python3:</p>\n\n<pre><code>&gt;&gt;&gt; import urllib.request\n&gt;&gt;&gt; site = urllib.request.urlopen(\"http://python.org\")\n&gt;&gt;&gt; print(\"FileSize: \", site.length)\n</code></pre>\n" }, { "answer_id": 40957594, "author": "ccpizza", "author_id": 191246, "author_profile": "https://Stackoverflow.com/users/191246", "pm_score": 4, "selected": false, "text": "<p>A <a href=\"http://python-requests.org\" rel=\"noreferrer\">requests</a>-based solution using HEAD instead of GET (also prints HTTP headers):</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>#!/usr/bin/python\n# display size of a remote file without downloading\n\nfrom __future__ import print_function\nimport sys\nimport requests\n\n# number of bytes in a megabyte\nMBFACTOR = float(1 &lt;&lt; 20)\n\nresponse = requests.head(sys.argv[1], allow_redirects=True)\n\nprint(\"\\n\".join([('{:&lt;40}: {}'.format(k, v)) for k, v in response.headers.items()]))\nsize = response.headers.get('content-length', 0)\nprint('{:&lt;40}: {:.2f} MB'.format('FILE SIZE', int(size) / MBFACTOR))\n</code></pre>\n\n<h3>Usage</h3>\n\n<blockquote>\n<pre><code>$ python filesize-remote-url.py https://httpbin.org/image/jpeg\n...\nContent-Length : 35588\nFILE SIZE (MB) : 0.03 MB\n</code></pre>\n</blockquote>\n" }, { "answer_id": 46440161, "author": "yukashima huksay", "author_id": 5120089, "author_profile": "https://Stackoverflow.com/users/5120089", "pm_score": 2, "selected": false, "text": "<p>For a python3 (tested on 3.5) approach I'd recommend:</p>\n\n<pre><code>with urlopen(file_url) as in_file, open(local_file_address, 'wb') as out_file:\n print(in_file.getheader('Content-Length'))\n out_file.write(response.read())\n</code></pre>\n" }, { "answer_id": 59956757, "author": "Hrisimir Dakov", "author_id": 12198227, "author_profile": "https://Stackoverflow.com/users/12198227", "pm_score": 0, "selected": false, "text": "<p>@PabloG Regarding the local/server filesize difference</p>\n<p>Following is high-level illustrative explanation of why it may occur:</p>\n<p>The size on disk sometimes is different from the actual size of the data.\nIt depends on the underlying file-system and how it operates on data.\nAs you may have seen in Windows when formatting a flash drive you are asked to provide 'block/cluster size' and it varies [512b - 8kb].\nWhen a file is written on the disk, it is stored in a 'sort-of linked list' of disk blocks.\nWhen a certain block is used to store part of a file, no other file contents will be stored in the same blok, so even if the chunk is no occupuing the entire block space, the block is rendered unusable by other files.</p>\n<p>Example:\nWhen the filesystem is divided on 512b blocks, and we need to store 600b file, two blocks will be occupied. The first block will be fully utilized, while the second block will have only 88b utilized and the remaining (512-88)b will be unusable resulting in 'file-size-on-disk' being 1024b.\nThis is why Windows has different notations for 'file size' and 'size on disk'.</p>\n<p>NOTE:\nThere are different pros &amp; cons that come with smaller/bigger FS block, so do a better research before playing with your filesystem.</p>\n" }, { "answer_id": 70382014, "author": "Kalob Taulien", "author_id": 2074077, "author_profile": "https://Stackoverflow.com/users/2074077", "pm_score": 2, "selected": false, "text": "<p>For anyone using Python 3 and looking for a quick solution using the <code>requests</code> package:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import requests \nresponse = requests.head( \n &quot;https://website.com/yourfile.mp4&quot;, # Example file \n allow_redirects=True\n)\nprint(response.headers['Content-Length']) \n</code></pre>\n<p>Note: Not all responses will have a <code>Content-Length</code> so your application will want to check to see if it exists.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if 'Content-Length' in response.headers:\n ... # Do your stuff here \n</code></pre>\n" }, { "answer_id": 73009100, "author": "Harshana", "author_id": 6952359, "author_profile": "https://Stackoverflow.com/users/6952359", "pm_score": 1, "selected": false, "text": "<p>Here is a much more safer way for Python 3:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import urllib.request\nsite = urllib.request.urlopen(&quot;http://python.org&quot;)\nmeta = site.info()\nmeta.get('Content-Length') \n</code></pre>\n<p>Returns:</p>\n<pre><code>'49829'\n</code></pre>\n<p><code>meta.get('Content-Length')</code> will return the &quot;Content-Length&quot; header if exists. Otherwise it will be blank</p>\n" }, { "answer_id": 74214042, "author": "Eugene Chabanov", "author_id": 11524604, "author_profile": "https://Stackoverflow.com/users/11524604", "pm_score": 0, "selected": false, "text": "<p>Quick and reliable one-liner for Python3 using urllib:</p>\n<pre><code>import urllib\n\nurl = 'https://&lt;your url here&gt;'\n\nsize = urllib.request.urlopen(url).info().get('Content-Length', 0)\n</code></pre>\n<p><code>.get(&lt;dict key&gt;, 0)</code> gets the key from dict and if the key is absent returns 0 (or whatever the 2nd argument is)</p>\n" }, { "answer_id": 74595076, "author": "kareem said", "author_id": 14272080, "author_profile": "https://Stackoverflow.com/users/14272080", "pm_score": 0, "selected": false, "text": "<p>you can use requests to pull this data</p>\n<pre><code>\nFile_Name=requests.head(LINK).headers[&quot;X-File-Name&quot;]\n\n#And other useful info** like the size of the file from this dict (headers)\n#like \n\nFile_size=requests.head(LINK).headers[&quot;Content-Length&quot;]\n</code></pre>\n" } ]
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" }, { "answer_id": 5924, "author": "Thejesh GN", "author_id": 482, "author_profile": "https://Stackoverflow.com/users/482", "pm_score": 3, "selected": false, "text": "<pre><code>document.getElementById('newSkill').options[document.getElementById('newSkill').selectedIndex].value \n</code></pre>\n\n<p>Should work</p>\n" }, { "answer_id": 5939, "author": "Tanerax", "author_id": 567, "author_profile": "https://Stackoverflow.com/users/567", "pm_score": 3, "selected": false, "text": "<p>This should return the text value of the selected value</p>\n\n<pre><code>var vSkill = document.getElementById('newSkill');\n\nvar vSkillText = vSkill.options[vSkill.selectedIndex].innerHTML;\n\nalert(vSkillText);\n</code></pre>\n\n<p>Props: @Tanerax for reading the question, knowing what was asked and answering it before others figured it out.</p>\n\n<p>Edit: DownModed, cause I actually read a question fully, and answered it, sad world it is.</p>\n" }, { "answer_id": 5947, "author": "Patrick McElhaney", "author_id": 437, "author_profile": "https://Stackoverflow.com/users/437", "pm_score": 8, "selected": true, "text": "<p>Based on your example HTML code, here's one way to get the displayed text of the currently selected option:</p>\n\n<pre><code>var skillsSelect = document.getElementById(\"newSkill\");\nvar selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;\n</code></pre>\n" }, { "answer_id": 14665677, "author": "Lilith", "author_id": 1533141, "author_profile": "https://Stackoverflow.com/users/1533141", "pm_score": 2, "selected": false, "text": "<p>This works i tried it my self i thought i post it here in case someone need it...</p>\n\n<pre><code>document.getElementById(\"newSkill\").options[document.getElementById('newSkill').selectedIndex].text;\n</code></pre>\n" }, { "answer_id": 23616510, "author": "raton", "author_id": 1770154, "author_profile": "https://Stackoverflow.com/users/1770154", "pm_score": 0, "selected": false, "text": "<pre><code> var ele = document.getElementById('newSkill')\n ele.onchange = function(){\n var length = ele.children.length\n for(var i=0; i&lt;length;i++){\n if(ele.children[i].selected){alert(ele.children[i].text)}; \n }\n } \n</code></pre>\n" }, { "answer_id": 32887007, "author": "shekh danishuesn", "author_id": 5291660, "author_profile": "https://Stackoverflow.com/users/5291660", "pm_score": 2, "selected": false, "text": "<p>Attaches a change event to the select that gets the text for each selected option and writes them in the div.</p>\n\n<p>You can use jQuery it very face and successful and easy to use</p>\n\n<pre><code>&lt;select name=\"sweets\" multiple=\"multiple\"&gt;\n &lt;option&gt;Chocolate&lt;/option&gt;\n &lt;option&gt;Candy&lt;/option&gt;\n &lt;option&gt;Taffy&lt;/option&gt;\n &lt;option selected=\"selected\"&gt;Caramel&lt;/option&gt;\n &lt;option&gt;Fudge&lt;/option&gt;\n &lt;option&gt;Cookie&lt;/option&gt;\n&lt;/select&gt;\n&lt;div&gt;&lt;/div&gt;\n\n\n$(\"select\").change(function () {\n var str = \"\";\n\n $(\"select option:selected\").each(function() {\n str += $( this ).text() + \" \";\n });\n\n $( \"div\" ).text( str );\n}).change();\n</code></pre>\n" }, { "answer_id": 35123258, "author": "Debanjan Roy", "author_id": 5086165, "author_profile": "https://Stackoverflow.com/users/5086165", "pm_score": 0, "selected": false, "text": "<pre><code>var selectoption = document.getElementById(\"dropdown\");\nvar optionText = selectoption.options[selectoption.selectedIndex].text;\n</code></pre>\n" }, { "answer_id": 36276432, "author": "IbrahimSediq", "author_id": 6127529, "author_profile": "https://Stackoverflow.com/users/6127529", "pm_score": 0, "selected": false, "text": "<p>Please try the below this is the easiest way and it works perfectly</p>\n\n<pre><code>var newSkill_Text = document.getElementById(\"newSkill\")[document.getElementById(\"newSkill\").selectedIndex];\n</code></pre>\n" }, { "answer_id": 44130853, "author": "BOBIN JOSEPH", "author_id": 4238869, "author_profile": "https://Stackoverflow.com/users/4238869", "pm_score": 4, "selected": false, "text": "<p>Simply You can use jQuery instead of JavaScript</p>\n<pre><code>$(&quot;#yourdropdownid option:selected&quot;).text();\n</code></pre>\n<p>Try This.</p>\n" }, { "answer_id": 46924743, "author": "Muhammad Tariq Ahmed Khan", "author_id": 8829462, "author_profile": "https://Stackoverflow.com/users/8829462", "pm_score": 2, "selected": false, "text": "<pre><code>function getValue(obj)\n{ \n // it will return the selected text\n // obj variable will contain the object of check box\n var text = obj.options[obj.selectedIndex].innerHTML ; \n\n}\n</code></pre>\n\n<p>HTML Snippet </p>\n\n<pre><code> &lt;asp:DropDownList ID=\"ddl\" runat=\"server\" CssClass=\"ComboXXX\" \n onchange=\"getValue(this)\"&gt;\n&lt;/asp:DropDownList&gt;\n</code></pre>\n" }, { "answer_id": 54680935, "author": "Manpreet Singh Dhillon", "author_id": 3495713, "author_profile": "https://Stackoverflow.com/users/3495713", "pm_score": 2, "selected": false, "text": "<p>Here is an easy and short method</p>\n\n<pre><code>document.getElementById('elementID').selectedOptions[0].innerHTML\n</code></pre>\n" }, { "answer_id": 67819800, "author": "RayH", "author_id": 16084726, "author_profile": "https://Stackoverflow.com/users/16084726", "pm_score": 0, "selected": false, "text": "<p>Found this a tricky question but using ideas from here I eventually got the solution using PHP &amp; Mysqli to populate the list : and then a bit of javascript to get the working variable out.</p>\n<pre><code> &lt;select id=&quot;mfrbtn&quot; onchange=&quot;changemfr()&quot; &gt; \n &lt;option selected=&quot;selected&quot;&gt;Choose one&lt;/option&gt;\n &lt;?php\n foreach($rows as $row)\n {\n echo '&lt;option value=implode($rows)&gt;'.$row[&quot;Mfrname&quot;].'&lt;/option&gt;';\n }\n ?&gt;\n &lt;/select&gt;\n</code></pre>\n<p>Then :</p>\n<pre><code>&lt;script language=&quot;JavaScript&quot;&gt;\n \n function changemfr()\n {\n var $mfr2=document.getElementById(&quot;mfrbtn&quot;).selectedOptions[0].text;\n alert($mfr2);\n }\n&lt;/script&gt;\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 and I find it really useful for folding functions, I know what my \"getGet\" function does, I don't need it taking up 10 lines of oh so valuable screen space.</p>\n\n<p>I never use it to hide a for loop, if statement or similar unless showing the code to someone else where I will hide code they have seen to avoid showing the same code twice.</p>\n" }, { "answer_id": 5929, "author": "Pat", "author_id": 36, "author_profile": "https://Stackoverflow.com/users/36", "pm_score": 4, "selected": false, "text": "<p>This was talked about on <a href=\"https://blog.codinghorror.com/the-problem-with-code-folding/\" rel=\"nofollow noreferrer\">Coding Horror</a>.</p>\n\n<p>My personal belief is that is that they are useful, but like anything in excess can be too much. </p>\n\n<p>I use it to order my code blocks into:\n<br>Enumerations\n<br>Declarations\n<br>Constructors\n<br>Methods\n<br>Event Handlers\n<br>Properties</p>\n" }, { "answer_id": 5930, "author": "Brian Childress", "author_id": 721, "author_profile": "https://Stackoverflow.com/users/721", "pm_score": 1, "selected": false, "text": "<p>I personally use #Regions all the time. I find that it helps me to keep things like properties, declarations, etc separated from each other.</p>\n\n<p>This is probably a good answer, too!</p>\n\n<p><a href=\"https://blog.codinghorror.com/the-problem-with-code-folding/\" rel=\"nofollow noreferrer\">Coding Horror</a></p>\n\n<p>Edit: Dang, Pat beat me to this!</p>\n" }, { "answer_id": 5953, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "<p>While I understand the problem that Jeff, et. al. have with regions, what I <em>don't</em> understand is why hitting <kbd>CTRL</kbd>+<kbd>M</kbd>,<kbd>CTRL</kbd>+<kbd>L</kbd> to expand all regions in a file is so difficult to deal with.</p>\n" }, { "answer_id": 5954, "author": "Adam V", "author_id": 517, "author_profile": "https://Stackoverflow.com/users/517", "pm_score": 0, "selected": false, "text": "<p>I prefer #regions myself, but an old coworker couldn't stand to have things hidden. I understood his point once I worked on a page with 7 #regions, at least 3 of which had been auto-generated and had the same name, but in general I think they're a useful way of splitting things up and keeping everything less cluttered.</p>\n" }, { "answer_id": 5962, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 2, "selected": false, "text": "<p>I prefer partial classes as opposed to regions.</p>\n\n<p>Extensive use of regions by others also give me the impression that someone, somewhere, is violating the Single Responsibility Principle and is trying to do too many things with one object.</p>\n" }, { "answer_id": 5971, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 2, "selected": false, "text": "<p>I'm not a fan of partial classes - I try to develop my classes such that each class has a very clear, single issue for which it's responsible. To that end, I don't believe that something with a clear responsibility should be split across multiple files. That's why I don't like partial classes.</p>\n\n<p>With that said, I'm on the fence about regions. For the most part, I don't use them; however, I work with code every day that includes regions - some people go really heavy on them (folding up private methods into a region and then each method folded into its own region), and some people go light on them (folding up enums, folding up attributes, etc). My general rule of thumb, as of now, is that I only put code in regions if (a) the data is likely to remain static or will not be touched very often (like enums), or (b) if there are methods that are implemented out of necessity because of subclassing or abstract method implementation, but, again, won't be touched very often.</p>\n" }, { "answer_id": 5972, "author": "Joseph Daigle", "author_id": 507, "author_profile": "https://Stackoverflow.com/users/507", "pm_score": 3, "selected": false, "text": "<p>Sometimes you might find yourself working on a team where #regions are encouraged or required. If you're like me and you can't stand messing around with folded code you can turn off outlining for C#:</p>\n\n<ol>\n<li>Options -> Text Editor -> C# -> Advanced Tab</li>\n<li>Uncheck \"Enter outlining mode when files open\"</li>\n</ol>\n" }, { "answer_id": 5990, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 3, "selected": false, "text": "<p>I use #Region to hide ugly and useless automatically generated code, which really belongs in the automatically generated part of the partial class. But, when working with old projects or upgraded projects, you don't always have that luxury.</p>\n\n<p>As for other types of folding, I fold Functions all the time. If you name the function well, you will never have to look inside unless you're testing something or (re-)writing it.</p>\n" }, { "answer_id": 6287, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "<p>@<a href=\"https://stackoverflow.com/questions/5916/how-do-you-feel-about-code-folding#5971\">Tom</a></p>\n\n<p>Partial classes are provided so that you can separate tool auto-generated code from any customisations you may need to make after the code gen has done its bit. This means your code stays intact after you re-run the codegen and doesn't get overwritten. This is a good thing. </p>\n" }, { "answer_id": 6295, "author": "Brandon Wood", "author_id": 423, "author_profile": "https://Stackoverflow.com/users/423", "pm_score": 0, "selected": false, "text": "<p>I really don't have a problem with using #region to organize code. Personally, I'll usually setup different regions for things like properties, event handlers, and public/private methods.</p>\n" }, { "answer_id": 7752, "author": "Adam Lerman", "author_id": 673, "author_profile": "https://Stackoverflow.com/users/673", "pm_score": 0, "selected": false, "text": "<p>Eclipse does some of this in Java (or PHP with plugins) on its own. Allows you to fold functions and such. I tend to like it. If I know what a function does and I am not working on it, I dont need to look at it.</p>\n" }, { "answer_id": 7767, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 6, "selected": true, "text": "<p>9 out of 10 times, code folding means that you have failed to use the <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"noreferrer\">SoC principle</a> for what its worth.<br />\nI 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.<br />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.<br />\n<br />\nWhenever you can, pull some code out of the main class, and into a helper or factory class.\n<br /></p>\n\n<pre><code>foreach (var item in Items)\n{\n //.. 100 lines of validation and data logic..\n}\n</code></pre>\n\n<p>is not as readable as</p>\n\n<pre><code>foreach (var item in Items)\n{\n if (ValidatorClass.Validate(item))\n RepositoryClass.Update(item);\n}\n</code></pre>\n\n<p><br />\n<br />\nMy $0.02 anyways.</p>\n" }, { "answer_id": 9049, "author": "Serhat Ozgel", "author_id": 31505, "author_profile": "https://Stackoverflow.com/users/31505", "pm_score": 2, "selected": false, "text": "<p>Regions must never be used inside methods. They may be used to group methods but this must be handled with extreme caution so that the reader of the code does not go insane. There is no point in folding methods by their modifiers. But sometimes folding may increase readability. For e.g. grouping some methods that you use for working around some issues when using an external library and you won't want to visit too often may be helpful. But the coder must always seek for solutions like wrapping the library with appropriate classes in this particular example. When all else fails, use folding for improving readibility.</p>\n" }, { "answer_id": 9053, "author": "Thomas Owens", "author_id": 572, "author_profile": "https://Stackoverflow.com/users/572", "pm_score": 1, "selected": false, "text": "<p>I think that it's a useful tool, when used properly. In many cases, I feel that methods and enumerations and other things that are often folded should be little black boxes. Unless you must look at them for some reason, their contents don't matter and should be as hidden as possible. However, I never fold private methods, comments, or inner classes. Methods and enums are really the only things I fold.</p>\n" }, { "answer_id": 9063, "author": "Mun", "author_id": 775, "author_profile": "https://Stackoverflow.com/users/775", "pm_score": 1, "selected": false, "text": "<p>My approach is similar to a few others here, using regions to organize code blocks into constructors, properties, events, etc.</p>\n\n<p>There's an excellent set of VS.NET macros by Roland Weigelt available from his blog entry, <a href=\"http://weblogs.asp.net/rweigelt/archive/2003/07/06/9741.aspx\" rel=\"nofollow noreferrer\">Better Keyboard Support for #region ... #endregion</a>. I've been using these for years, mapping ctrl+. to collapse the current region and ctrl++ to expand it. Find that it works a lot better that the default VS.NET functionality which folds/unfolds everything.</p>\n" }, { "answer_id": 14568, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 1, "selected": false, "text": "<p>The <a href=\"https://blog.codinghorror.com/the-problem-with-code-folding/\" rel=\"nofollow noreferrer\">Coding Horror</a> article actual got me thinking about this as well.</p>\n\n<p>Generally, I large classes I will put a region around the member variables, constants, and properties to reduce the amount of text I have to scroll through and leave everything else outside of a region. On forms I will generally group things into \"member variables, constants, and properties\", form functions, and event handlers. Once again, this is more so I don't have to scroll through a lot of text when I just want to review some event handlers.</p>\n" }, { "answer_id": 25984, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 0, "selected": false, "text": "<p>Emacs has a folding minor mode, but I only fire it up occasionally. Mostly when I'm working on some monstrosity inherited from another physicist who evidently had less instruction or took less care about his/her coding practices. </p>\n" }, { "answer_id": 26003, "author": "Tundey", "author_id": 1453, "author_profile": "https://Stackoverflow.com/users/1453", "pm_score": 2, "selected": false, "text": "<p>This is just one of those silly discussions that lead to nowhere. If you like regions, use them. If you don't, configure your editor to turn them off. There, everybody is happy.</p>\n" }, { "answer_id": 33023, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "<p>Using regions (or otherwise folding code) <strong>should</strong> have nothing to do with code smells (or hiding them) or any other idea of hiding code you don't want people to \"easily\" see.</p>\n\n<p>Regions and code folding is really all about providing a way to easily group sections of code that can be collapsed/folded/hidden to minimize the amount of extraneous \"noise\" around what you are currently working on. If you set things up correctly (meaning actually name your regions something useful, like the name of the method contained) then you can collapse everything except for the function you are currently editing and still maintain some level of context without having to actually see the other code lines.</p>\n\n<p>There probably should be some best practice type guidelines around these ideas, but I use regions extensively to provide a standard structure to my code files (I group events, class-wide fields, private properties/methods, public properties/methods). Each method or property also has a region, where the region name is the method/property name. If I have a bunch of overloaded methods, the region name is the full signature and then that entire group is wrapped in a region that is just the function name.</p>\n" }, { "answer_id": 217785, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 2, "selected": false, "text": "<p>Region folding would be fine if I didn't have to manually maintain region groupings based on features of my code that are intrinsic to the language. For example, the compiler already knows it's a constructor. The IDE's code model already knows it's a constructor. But if I want to see a view of the code where the constructors are grouped together, for some reason I have to restate the fact that these things are constructors, by physically placing them together and then putting a group around them. The same goes for any other way of slicing up a class/struct/interface. What if I change my mind and want to see the public/protected/private stuff separated out into groups first, and then grouped by member kind?</p>\n<p>Using regions to mark out public properties (for example) is as bad as entering a redundant comment that adds nothing to what is already discernible from the code itself.</p>\n<p>Anyway, to avoid having to use regions for that purpose, I wrote a free, open source Visual Studio 2008 IDE add-in called Ora. It provides a grouped view automatically, making it far less necessary to maintain physical grouping or to use regions. <a href=\"http://www.codeplex.com/ora\" rel=\"nofollow noreferrer\">You may find it useful</a>.</p>\n" }, { "answer_id": 296577, "author": "Mykroft", "author_id": 2191, "author_profile": "https://Stackoverflow.com/users/2191", "pm_score": 2, "selected": false, "text": "<p>I generally find that when dealing with code like Events in C# where there's about 10 lines of code that are actually just part of an event declaration (the EventArgs class the delegate declaration and the event declaration) Putting a region around them and then folding them out of the way makes it a little more readable. </p>\n" }, { "answer_id": 9030438, "author": "Piotr Perak", "author_id": 679340, "author_profile": "https://Stackoverflow.com/users/679340", "pm_score": 0, "selected": false, "text": "<p>I personally hate regions. The only code that should be in regions in my opinion is generated code.\nWhen I open file I always start with Ctrl+M+O. This folds to method level. When you have regions you see nothing but region names.</p>\n<p>Before checking in I group methods/fields logically so that it looks ok after Ctrl+M+O.\nIf you need regions you have to much lines in your class. I also find that this is very common.</p>\n<h1>region ThisLooksLikeWellOrganizedCodeBecauseIUseRegions</h1>\n<p>// total garbage, no structure here</p>\n<h1>endregion</h1>\n" }, { "answer_id": 14829202, "author": "Lezzer", "author_id": 1326137, "author_profile": "https://Stackoverflow.com/users/1326137", "pm_score": 0, "selected": false, "text": "<p>Enumerations</p>\n\n<p>Properties</p>\n\n<p>.ctors</p>\n\n<p>Methods</p>\n\n<p>Event Handlers</p>\n\n<p>That's all I use regions for. I had no idea you could use them inside of methods.</p>\n\n<p>Sounds like a terrible idea :)</p>\n" } ]
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 unique ID.</p>\n\n<p>Although this is probably a good idea for an architectural point of view, it makes working with on a daily basis difficult. Sometimes there is a need to do bulk inserts and having a UUID makes this very difficult, usually requiring writing a cursor instead of a simple SELECT INTO statement.</p>\n" }, { "answer_id": 5960, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 1, "selected": false, "text": "<p>I think using a GUID would be the better choice in your situation. It takes up more space but it's more secure.</p>\n" }, { "answer_id": 5963, "author": "Douglas Tosi", "author_id": 626, "author_profile": "https://Stackoverflow.com/users/626", "pm_score": 6, "selected": true, "text": "<p>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. \nAnd the speed difference is generally small.</p>\n\n<p>Make sure your database supports an efficient storage datatype (16 bytes, 128 bits).\nAt the very least you can encode the uuid string in base64 and use char(22).</p>\n\n<p>I've used them extensively with Firebird and do recommend.</p>\n" }, { "answer_id": 5967, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 5, "selected": false, "text": "<p>I can answer you that in SQL server if you use a uniqueidentifier (GUID) datatype and use the NEWID() function to create values you will get horrible fragmentation because of page splits. The reason is that when using NEWID() the value generated is not sequential. SQL 2005 added the NEWSEQUANTIAL() function to remedy that</p>\n\n<p>One way to still use GUID and int is to have a guid and an int in a table so that the guid maps to the int. the guid is used externally but the int internally in the DB</p>\n\n<p>for example</p>\n\n<pre><code>457180FB-C2EA-48DF-8BEF-458573DA1C10 1\n9A70FF3C-B7DA-4593-93AE-4A8945943C8A 2\n</code></pre>\n\n<p>1 and 2 will be used in joins and the guids in the web app. This table will be pretty narrow and should be pretty fast to query</p>\n" }, { "answer_id": 6052, "author": "Brian Lyttle", "author_id": 636, "author_profile": "https://Stackoverflow.com/users/636", "pm_score": 2, "selected": false, "text": "<p>I don't think a GUID gives you many benefits. Users hate long, incomprehensible URLs.</p>\n\n<p>Create a shorter ID that you can map to the URL, or enforce a unique user name convention (<a href=\"http://example.com/user/brianly\" rel=\"nofollow noreferrer\">http://example.com/user/brianly</a>). The guys at <a href=\"http://gettingreal.37signals.com/\" rel=\"nofollow noreferrer\">37Signals</a> would probably mock you for worrying about something like this when it comes to a web app.</p>\n\n<p>Incidentally you can force your database to start creating integer IDs from a base value.</p>\n" }, { "answer_id": 6062, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 5, "selected": false, "text": "<p>For what it's worth, I've seen a long running stored procedure (9+ seconds) drop to just a few hundred milliseconds of run time simply by switching from GUID primary keys to integers. That's not to say <em>displaying</em> a GUID is a bad idea, but as others have pointed out, joining on them, and indexing them, by definition, is not going to be anywhere near as fast as with integers.</p>\n" }, { "answer_id": 6227, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 2, "selected": false, "text": "<p>Rather than URLs like this:</p>\n\n<pre><code>http://example.com/user/783\n</code></pre>\n\n<p>Why not have:</p>\n\n<pre><code>http://example.com/user/yukondude\n</code></pre>\n\n<p>Which is friendlier to humans and doesn't leak that tiny bit of information?</p>\n" }, { "answer_id": 9098, "author": "Andrea Bertani", "author_id": 1005, "author_profile": "https://Stackoverflow.com/users/1005", "pm_score": 2, "selected": false, "text": "<p>You could use an integer which is related to the row number but is not sequential. For example, you could take the 32 bits of the sequential ID and rearrange them with a fixed scheme (for example, bit 1 becomes bit 6, bit 2 becomes bit 15, etc..).<br>\nThis will be a bidirectional encryption, and you will be sure that two different IDs will always have different encryptions.<br>\nIt would obviously be easy to decode, if one takes the time to generate enough IDs and get the schema, but, if I understand correctly your problem, you just want to not give away information too easily.</p>\n" }, { "answer_id": 9164, "author": "Dan", "author_id": 230, "author_profile": "https://Stackoverflow.com/users/230", "pm_score": 1, "selected": false, "text": "<p>I think that this is one of these issues that cause quasi-religious debates, and its almost futile to talk about. I would just say use what you prefer. In 99% of systems it will no matter which type of key you use, so the benefits (stated in the other posts) of using one sort over the other will never be an issue. </p>\n" }, { "answer_id": 9236, "author": "Marius", "author_id": 1008, "author_profile": "https://Stackoverflow.com/users/1008", "pm_score": 2, "selected": false, "text": "<p>We use GUIDs as primary keys for all our tables as it doubles as the RowGUID for MS SQL Server Replication. Makes it very easy when the client suddenly opens an office in another part of the world...</p>\n" }, { "answer_id": 68255, "author": "Michael Barker", "author_id": 6365, "author_profile": "https://Stackoverflow.com/users/6365", "pm_score": 2, "selected": false, "text": "<p>It also depends on what you care about for your application. For n-tier apps GUIDs/UUIDs are simpler to implement and are easier to port between different databases. To produce Integer keys some database support a sequence object natively and some require custom construction of a sequence table.</p>\n\n<p>Integer keys probably (I don't have numbers) provide an advantage for query and indexing performance as well as space usage. Direct DB querying is also much easier using numeric keys, less copy/paste as they are easier to remember.</p>\n" }, { "answer_id": 69586, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 3, "selected": false, "text": "<p>Why couple your primary key with your URI?</p>\n\n<p>Why not have your URI key be human readable (or unguessable, depending on your needs), and your primary index integer based, that way you get the best of both worlds. A lot of blog software does that, where the exposed id of the entry is identified by a 'slug', and the numeric id is hidden away inside of the system.</p>\n\n<p>The added benefit here is that you now have a really nice URL structure, which is good for SEO. Obviously for a transaction this is not a good thing, but for something like stackoverflow, it is important (see URL up top...). Getting uniqueness isn't that difficult. If you are really concerned, store a hash of the slug inside a table somewhere, and do a lookup before insertion.</p>\n\n<p><strong>edit:</strong> Stackoverflow doesn't quite use the system I describe, see Guy's comment below.</p>\n" }, { "answer_id": 15065086, "author": "user2106945", "author_id": 2106945, "author_profile": "https://Stackoverflow.com/users/2106945", "pm_score": -1, "selected": false, "text": "<p>As long as you use a DB system with efficient storage, HDD is cheap these days anyway...</p>\n\n<p>I know GUID's can be a b*tch to work with some times and come with some query overhead however from a security perspective they are a savior. </p>\n\n<p>Thinking security by obscurity they fit well when forming obscure URI's and building normalised DB's with Table, Record and Column defined security you cant go wrong with GUID's, try doing that with integer based id's.</p>\n" }, { "answer_id": 19129647, "author": "Daniel Alexiuc", "author_id": 34553, "author_profile": "https://Stackoverflow.com/users/34553", "pm_score": 2, "selected": false, "text": "<p>I've tried both in real web apps.</p>\n<p>My opinion is that it is preferable to use integers and have short, comprehensible URLs.</p>\n<p>As a developer, it feels a little bit awful seeing sequential integers and knowing that some information about total record count is leaking out, but honestly - most people probably don't care, and that information has never really been critical to my businesses.</p>\n<p>Having long ugly UUID URLs seems to me like much more of a turn off to normal users.</p>\n" }, { "answer_id": 51471301, "author": "Sousaplex", "author_id": 5371123, "author_profile": "https://Stackoverflow.com/users/5371123", "pm_score": 0, "selected": false, "text": "<p>YouTube uses 11 characters with base64 encoding which offers 11^64 possibilities, and they are usually pretty manageable to write. I wonder if that would offer better performance than a full on UUID. UUID converted to base 64 would be double the size I believe.</p>\n<p>More information can be found here: <a href=\"https://www.youtube.com/watch?v=gocwRvLhDf8\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=gocwRvLhDf8</a></p>\n" }, { "answer_id": 72440275, "author": "ZiiMakc", "author_id": 10188661, "author_profile": "https://Stackoverflow.com/users/10188661", "pm_score": 0, "selected": false, "text": "<h1>Pros and Cons of UUID</h1>\n<blockquote>\n<p>Note: <a href=\"https://github.com/kripod/uuidv7\" rel=\"nofollow noreferrer\">uuid_v7</a> is time based uuid instead of random. So you can\nuse it to order by creation date and solve <a href=\"https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-03.html#section-1-4\" rel=\"nofollow noreferrer\">some performance issues\nwith db inserts</a> if you do really many of them.</p>\n</blockquote>\n<p><strong>Pros</strong>:</p>\n<ul>\n<li>can be generated on api level (good for distributed systems)</li>\n<li>hides count information about entity</li>\n<li>doesn't have limit 2,147,483,647 as 32-bit int</li>\n<li>removes layer of errors related to passing one entity id <code>userId: 25</code> to get another <code>bookId: 25</code> accidently</li>\n<li>more friendly graphql usage as <code>ID</code> key</li>\n</ul>\n<p><strong>Cons</strong>:</p>\n<ul>\n<li>128-bit instead 32-bit int (slightly bigger size in db and ~40% bigger index, around ~30MB for 1 million rows), should be a minor concern</li>\n<li>can't be sorted by creation (<strong>can be solved with uuid_v7</strong>)</li>\n<li><a href=\"https://www.ietf.org/archive/id/draft-peabody-dispatch-new-uuid-format-03.html#name-introduction-5\" rel=\"nofollow noreferrer\">non-time-ordered UUID versions such as UUIDv4 have poor database index locality</a> (<strong>can be solved with uuid_v7</strong>)</li>\n</ul>\n<hr />\n<h1>URL usage</h1>\n<p>Depending on app you may care or not care about url. If you don't care, just use <code>uuid</code> as is, it's fine.</p>\n<p>If you care, then you will need to decide on url format.</p>\n<p>Best case scenario is a use of unique slug if you ok with never changing it:</p>\n<pre><code>http://example.com/sale/super-duper-phone\n</code></pre>\n<p>If your url is generated from title and you want to change slug on title change there is a few options. Use it as is and query by uuid (slug is just decoration):</p>\n<pre><code>http://example.com/book/035a46e0-6550-11dd-ad8b-0800200c9a66/new-title\n</code></pre>\n<p>Convert it to base64url:</p>\n<ul>\n<li>you can get uuid back from <code>AYEWXcsicACGA6PT7v_h3A</code></li>\n<li><code>AYEWXcsicACGA6PT7v_h3A</code> - 22 characters</li>\n<li><code>035a46e0-6550-11dd-ad8b-0800200c9a66</code> - 36 characters</li>\n</ul>\n<pre><code>http://example.com/book/AYEWXcsicACGA6PT7v_h3A/new-title\n</code></pre>\n<p>Generate a unique <a href=\"https://github.com/ai/nanoid\" rel=\"nofollow noreferrer\">short 11 chars</a> length string just for slug usage:</p>\n<pre><code>http://example.com/book/icACEWXcsAY-new-title\nhttp://example.com/book/icACEWXcsAY/new-title\n</code></pre>\n<p>If you don't want uuid or short id in url and want only slug, but do care about seo and user bookmarks, you will need to redirect all request from</p>\n<pre><code>http://example.com/sale/phone-1-title\n</code></pre>\n<p>to</p>\n<pre><code>http://example.com/sale/phone-1-title-updated\n</code></pre>\n<p>this will add additional complexity of managing slug history, adding fallback to history for all queries where slug is used and redirects if slugs doesn't match</p>\n" } ]
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 the Python docs for <a href=\"http://docs.python.org/lib/module-sqlite3.html\" rel=\"nofollow noreferrer\">sqlite3</a></p>\n\n<hr>\n\n<p>If you don't want to use SQLite you could do an array of dicts.</p>\n\n<pre><code>episodes = []\nepisodes.append({'season':1, 'episode': 2, 'name':'Something'})\nepisodes.append({'season':1, 'episode': 2, 'name':'Something', 'actors':['Billy Bob', 'Sean Penn']})\n</code></pre>\n\n<p>That way you add metadata to any record and search it very easily</p>\n\n<pre><code>season_1 = [e for e in episodes if e['season'] == 1]\nbilly_bob = [e for e in episodes if 'actors' in e and 'Billy Bob' in e['actors']]\n\nfor episode in billy_bob:\n print \"Billy bob was in Season %s Episode %s\" % (episode['season'], episode['episode'])\n</code></pre>\n" }, { "answer_id": 6805, "author": "Mike Minutillo", "author_id": 358, "author_profile": "https://Stackoverflow.com/users/358", "pm_score": 0, "selected": false, "text": "<p>I have done something similar in the past and used an in-memory XML document as a quick and dirty hierarchical database for storage. You can store each show/season/episode as an element (nested appropriately) and attributes of these things as xml attributes on the elements. Then you can use XQuery to get info back out.</p>\n<p><strong>NOTE:</strong> I'm not a Python guy so I don't know what your xml support is like.</p>\n<p><strong>NOTE 2:</strong> You'll want to profile this because it'll be bigger and slower than the solution you've already got. Likely enough if you are doing some high-volume processing then XML is probably not going to be your friend.</p>\n" }, { "answer_id": 8165, "author": "Bartosz Radaczyński", "author_id": 985, "author_profile": "https://Stackoverflow.com/users/985", "pm_score": 0, "selected": false, "text": "<p>I don't get this part here:</p>\n\n<blockquote>\n <p>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)</p>\n</blockquote>\n\n<p>There is a way to do it - called <strong>in</strong>:</p>\n\n<pre><code>&gt;&gt;&gt;x={}\n&gt;&gt;&gt;x[1]={}\n&gt;&gt;&gt;x[1][2]={}\n&gt;&gt;&gt;x\n{1: {2: {}}}\n&gt;&gt;&gt; 2 in x[1]\nTrue\n&gt;&gt;&gt; 3 in x[1]\nFalse\n</code></pre>\n\n<p>what seems to be the problem with that?</p>\n" }, { "answer_id": 9080, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 0, "selected": false, "text": "<p>Bartosz/To clarify \"This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not\"</p>\n\n<p><code>x['some show'][3][24]</code> would return season 3, episode 24 of \"some show\". If there was no season 3, I want the pseudo-dict to raise tvdb_seasonnotfound, if \"some show\" doesn't exist, then raise tvdb_shownotfound</p>\n\n<p>The current system of a series of classes, each with a <code>__getitem__</code> - Show checks <code>if self.seasons.has_key(requested_season_number)</code>, the Season class checks <code>if self.episodes.has_key(requested_episode_number)</code> and so on.</p>\n\n<p>It works, but it there seems to be a lot of repeated code (each class is basically the same, but raises a different error)</p>\n" }, { "answer_id": 10778, "author": "Bartosz Radaczyński", "author_id": 985, "author_profile": "https://Stackoverflow.com/users/985", "pm_score": 4, "selected": true, "text": "<p>OK, what you need is <code>classobj</code> from new module. That would allow you to construct exception classes dynamically (<code>classobj</code> takes a string as an argument for the class name). </p>\n\n<pre><code>import new\nmyexc=new.classobj(\"ExcName\",(Exception,),{})\ni=myexc(\"This is the exc msg!\")\nraise i\n</code></pre>\n\n<p>this gives you:</p>\n\n<pre><code>Traceback (most recent call last):\nFile \"&lt;stdin&gt;\", line 1, in &lt;module&gt;\n__main__.ExcName: This is the exc msg!\n</code></pre>\n\n<p>remember that you can always get the class name through:</p>\n\n<pre><code>self.__class__.__name__\n</code></pre>\n\n<p>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>\n\n<p>P.S. - you can also raise strings, but this is deprecated.</p>\n\n<pre><code>raise(self.__class__.__name__+\"Exception\")\n</code></pre>\n" } ]
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 box and the model are updated when either of the two change.</p>\n<pre><code>public static function bindProperty2(site:Object, prop:String, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher\n{\n var cbx:ComboBox = null;\n if ( site is ComboBox ) { cbx = ComboBox(site); }\n if ( host is ComboBox ) { cbx = ComboBox(host); }\n var labelField:String = &quot;listID&quot;;\n \n var w:ChangeWatcher = ChangeWatcher.watch(host, chain, null, commitOnly);\n \n if (w != null)\n {\n var func:Function;\n \n if ( site is ComboBox )\n {\n func = function(event:*):void\n {\n var dp:ICollectionView = ICollectionView(site.dataProvider);\n var selItem:Object = null;\n \n for ( var i:int=0; i&lt;dp.length; i++ )\n {\n var obj:Object = dp[i];\n if ( obj.hasOwnProperty(labelField) )\n {\n var val:String = String(obj[labelField]);\n if ( val == w.getValue() )\n {\n selItem = obj;\n break;\n }\n }\n }\n \n site.selectedItem = selItem;\n };\n \n w.setHandler(func);\n func(null);\n }\n else\n {\n func = function(event:*):void\n {\n var value:Object = w.getValue();\n if ( value == null )\n {\n site[prop] = null;\n }\n else\n {\n site[prop] = String(w.getValue()[labelField]);\n }\n };\n w.setHandler(func);\n func(null);\n }\n }\n \n return w;\n}\n</code></pre>\n" }, { "answer_id": 378558, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It is better to override the property in question and declare it final.</p>\n" } ]
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 prettyprint-override\"><code>&lt;appender name=\"AdoNetAppender\" type=\"log4net.Appender.AdoNetAppender\"&gt;\n &lt;filter type=\"log4net.Filter.LevelRangeFilter\"&gt;\n &lt;param name=\"LevelMin\" value=\"INFO\"/&gt;\n &lt;param name=\"LevelMax\" value=\"INFO\"/&gt;\n &lt;/filter&gt;\n ...\n&lt;/appender&gt;\n</code></pre>\n" }, { "answer_id": 85028, "author": "Charley Rathkopf", "author_id": 10119, "author_profile": "https://Stackoverflow.com/users/10119", "pm_score": 3, "selected": false, "text": "<p><strong>Yes.</strong> It is done with a filter on the appender. </p>\n\n<p>Here is the appender configuration I normally use, limited to only INFO level.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;appender name=\"RollingFileAppender\" type=\"log4net.Appender.RollingFileAppender\"&gt;\n &lt;file value=\"${HOMEDRIVE}\\\\PI.Logging\\\\PI.ECSignage.${COMPUTERNAME}.log\" /&gt;\n &lt;appendToFile value=\"true\" /&gt;\n &lt;maxSizeRollBackups value=\"30\" /&gt;\n &lt;maximumFileSize value=\"5MB\" /&gt;\n &lt;rollingStyle value=\"Size\" /&gt; &lt;!--A maximum number of backup files when rolling on date/time boundaries is not supported. --&gt;\n &lt;staticLogFileName value=\"false\" /&gt;\n &lt;lockingModel type=\"log4net.Appender.FileAppender+MinimalLock\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;param name=\"ConversionPattern\" value=\"%date{yyyy-MM-dd HH:mm:ss.ffff} [%2thread] %-5level %20.20type{1}.%-25method at %-4line| (%-30.30logger) %message%newline\" /&gt;\n &lt;/layout&gt;\n\n &lt;filter type=\"log4net.Filter.LevelRangeFilter\"&gt;\n &lt;levelMin value=\"INFO\" /&gt;\n &lt;levelMax value=\"INFO\" /&gt;\n &lt;/filter&gt;\n&lt;/appender&gt; \n</code></pre>\n" }, { "answer_id": 816854, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 2, "selected": false, "text": "<p>If you would like to perform it dynamically try this:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing log4net;\nusing log4net.Config;\nusing NUnit.Framework;\n\nnamespace ExampleConsoleApplication\n{\n enum DebugLevel : int\n { \n Fatal_Msgs = 0 , \n Fatal_Error_Msgs = 1 , \n Fatal_Error_Warn_Msgs = 2 , \n Fatal_Error_Warn_Info_Msgs = 3 ,\n Fatal_Error_Warn_Info_Debug_Msgs = 4 \n }\n\n class TestClass\n {\n private static readonly ILog logger = LogManager.GetLogger(typeof(TestClass));\n\n static void Main ( string[] args )\n {\n TestClass objTestClass = new TestClass ();\n\n Console.WriteLine ( \" START \" );\n\n int shouldLog = 4; //CHANGE THIS FROM 0 TO 4 integer to check the functionality of the example\n //0 -- prints only FATAL messages \n //1 -- prints FATAL and ERROR messages \n //2 -- prints FATAL , ERROR and WARN messages \n //3 -- prints FATAL , ERROR , WARN and INFO messages \n //4 -- prints FATAL , ERROR , WARN , INFO and DEBUG messages \n\n string srtLogLevel = String.Empty; \n switch (shouldLog)\n {\n case (int)DebugLevel.Fatal_Msgs :\n srtLogLevel = \"FATAL\";\n break;\n case (int)DebugLevel.Fatal_Error_Msgs:\n srtLogLevel = \"ERROR\";\n break;\n case (int)DebugLevel.Fatal_Error_Warn_Msgs :\n srtLogLevel = \"WARN\";\n break;\n case (int)DebugLevel.Fatal_Error_Warn_Info_Msgs :\n srtLogLevel = \"INFO\"; \n break;\n case (int)DebugLevel.Fatal_Error_Warn_Info_Debug_Msgs :\n srtLogLevel = \"DEBUG\" ;\n break ;\n default:\n srtLogLevel = \"FATAL\";\n break;\n }\n\n objTestClass.SetLogingLevel ( srtLogLevel );\n\n\n objTestClass.LogSomething ();\n\n\n Console.WriteLine ( \" END HIT A KEY TO EXIT \" );\n Console.ReadLine ();\n } //eof method \n\n /// &lt;summary&gt;\n /// Activates debug level \n /// &lt;/summary&gt;\n /// &lt;sourceurl&gt;http://geekswithblogs.net/rakker/archive/2007/08/22/114900.aspx&lt;/sourceurl&gt;\n private void SetLogingLevel ( string strLogLevel )\n {\n string strChecker = \"WARN_INFO_DEBUG_ERROR_FATAL\" ;\n\n if (String.IsNullOrEmpty ( strLogLevel ) == true || strChecker.Contains ( strLogLevel ) == false)\n throw new Exception ( \" The strLogLevel should be set to WARN , INFO , DEBUG ,\" );\n\n\n\n log4net.Repository.ILoggerRepository[] repositories = log4net.LogManager.GetAllRepositories ();\n\n //Configure all loggers to be at the debug level.\n foreach (log4net.Repository.ILoggerRepository repository in repositories)\n {\n repository.Threshold = repository.LevelMap[ strLogLevel ];\n log4net.Repository.Hierarchy.Hierarchy hier = (log4net.Repository.Hierarchy.Hierarchy)repository;\n log4net.Core.ILogger[] loggers = hier.GetCurrentLoggers ();\n foreach (log4net.Core.ILogger logger in loggers)\n {\n ( (log4net.Repository.Hierarchy.Logger)logger ).Level = hier.LevelMap[ strLogLevel ];\n }\n }\n\n //Configure the root logger.\n log4net.Repository.Hierarchy.Hierarchy h = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository ();\n log4net.Repository.Hierarchy.Logger rootLogger = h.Root;\n rootLogger.Level = h.LevelMap[ strLogLevel ];\n }\n\n private void LogSomething ()\n {\n #region LoggerUsage\n DOMConfigurator.Configure (); //tis configures the logger \n logger.Debug ( \"Here is a debug log.\" );\n logger.Info ( \"... and an Info log.\" );\n logger.Warn ( \"... and a warning.\" );\n logger.Error ( \"... and an error.\" );\n logger.Fatal ( \"... and a fatal error.\" );\n #endregion LoggerUsage\n\n }\n } //eof class \n} //eof namespace \n</code></pre>\n\n<p>The app config:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;?xml version=\"1.0\" encoding=\"utf-8\" ?&gt;\n&lt;configuration&gt;\n &lt;configSections&gt;\n &lt;section name=\"log4net\"\n type=\"log4net.Config.Log4NetConfigurationSectionHandler, log4net\" /&gt;\n &lt;/configSections&gt;\n &lt;log4net&gt;\n &lt;appender name=\"LogFileAppender\" type=\"log4net.Appender.FileAppender\"&gt;\n &lt;param name=\"File\" value=\"LogTest2.txt\" /&gt;\n &lt;param name=\"AppendToFile\" value=\"true\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;param name=\"Header\" value=\"[Header] \\r\\n\" /&gt;\n &lt;param name=\"Footer\" value=\"[Footer] \\r\\n\" /&gt;\n &lt;param name=\"ConversionPattern\" value=\"%d [%t] %-5p %c %m%n\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n\n &lt;appender name=\"ColoredConsoleAppender\" type=\"log4net.Appender.ColoredConsoleAppender\"&gt;\n &lt;mapping&gt;\n &lt;level value=\"ERROR\" /&gt;\n &lt;foreColor value=\"White\" /&gt;\n &lt;backColor value=\"Red, HighIntensity\" /&gt;\n &lt;/mapping&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n\n\n &lt;appender name=\"AdoNetAppender\" type=\"log4net.Appender.AdoNetAppender\"&gt;\n &lt;connectionType value=\"System.Data.SqlClient.SqlConnection, System.Data, Version=1.2.10.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" /&gt;\n &lt;connectionString value=\"data source=ysg;initial catalog=DBGA_DEV;integrated security=true;persist security info=True;\" /&gt;\n &lt;commandText value=\"INSERT INTO [DBGA_DEV].[ga].[tb_Data_Log] ([Date],[Thread],[Level],[Logger],[Message]) VALUES (@log_date, @thread, @log_level, @logger, @message)\" /&gt;\n\n &lt;parameter&gt;\n &lt;parameterName value=\"@log_date\" /&gt;\n &lt;dbType value=\"DateTime\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\" value=\"%date{yyyy'-'MM'-'dd HH':'mm':'ss'.'fff}\" /&gt;\n &lt;/parameter&gt;\n &lt;parameter&gt;\n &lt;parameterName value=\"@thread\" /&gt;\n &lt;dbType value=\"String\" /&gt;\n &lt;size value=\"255\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\" value=\"%thread\" /&gt;\n &lt;/parameter&gt;\n &lt;parameter&gt;\n &lt;parameterName value=\"@log_level\" /&gt;\n &lt;dbType value=\"String\" /&gt;\n &lt;size value=\"50\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\" value=\"%level\" /&gt;\n &lt;/parameter&gt;\n &lt;parameter&gt;\n &lt;parameterName value=\"@logger\" /&gt;\n &lt;dbType value=\"String\" /&gt;\n &lt;size value=\"255\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\" value=\"%logger\" /&gt;\n &lt;/parameter&gt;\n &lt;parameter&gt;\n &lt;parameterName value=\"@message\" /&gt;\n &lt;dbType value=\"String\" /&gt;\n &lt;size value=\"4000\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\" value=\"%messag2e\" /&gt;\n &lt;/parameter&gt;\n &lt;/appender&gt;\n &lt;root&gt;\n &lt;level value=\"INFO\" /&gt;\n &lt;appender-ref ref=\"LogFileAppender\" /&gt;\n &lt;appender-ref ref=\"AdoNetAppender\" /&gt;\n &lt;appender-ref ref=\"ColoredConsoleAppender\" /&gt;\n &lt;/root&gt;\n &lt;/log4net&gt;\n&lt;/configuration&gt;\n</code></pre>\n\n<p>The references in the csproj file:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;Reference Include=\"log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821, processorArchitecture=MSIL\"&gt;\n &lt;SpecificVersion&gt;False&lt;/SpecificVersion&gt;\n &lt;HintPath&gt;..\\..\\..\\Log4Net\\log4net-1.2.10\\bin\\net\\2.0\\release\\log4net.dll&lt;/HintPath&gt;\n&lt;/Reference&gt;\n&lt;Reference Include=\"nunit.framework, Version=2.4.8.0, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77, processorArchitecture=MSIL\" /&gt;\n</code></pre>\n" }, { "answer_id": 6879650, "author": "Javier Sanchez", "author_id": 185766, "author_profile": "https://Stackoverflow.com/users/185766", "pm_score": 5, "selected": false, "text": "<p>Use <code>threshold</code>.</p>\n\n<p>For example:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code> &lt;appender name=\"RollingFileAppender\" type=\"log4net.Appender.RollingFileAppender\"&gt;\n &lt;threshold value=\"WARN\"/&gt;\n &lt;param name=\"File\" value=\"File.log\" /&gt;\n &lt;param name=\"AppendToFile\" value=\"true\" /&gt;\n &lt;param name=\"RollingStyle\" value=\"Size\" /&gt;\n &lt;param name=\"MaxSizeRollBackups\" value=\"10\" /&gt;\n &lt;param name=\"MaximumFileSize\" value=\"1024KB\" /&gt;\n &lt;param name=\"StaticLogFileName\" value=\"true\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;param name=\"Header\" value=\"[Server startup]&amp;#13;&amp;#10;\" /&gt;\n &lt;param name=\"Footer\" value=\"[Server shutdown]&amp;#13;&amp;#10;\" /&gt;\n &lt;param name=\"ConversionPattern\" value=\"%d %m%n\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n &lt;appender name=\"EventLogAppender\" type=\"log4net.Appender.EventLogAppender\" &gt;\n &lt;threshold value=\"ERROR\"/&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%date [%thread]- %message%newline\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n &lt;appender name=\"ConsoleAppender\" type=\"log4net.Appender.ConsoleAppender\"&gt;\n &lt;threshold value=\"INFO\"/&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;param name=\"ConversionPattern\" value=\"%d [%thread] %m%n\" /&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n</code></pre>\n\n<p>In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.</p>\n" }, { "answer_id": 47055940, "author": "Sarfaraaz", "author_id": 4801298, "author_profile": "https://Stackoverflow.com/users/4801298", "pm_score": 1, "selected": false, "text": "<p>you can use log4net.Filter.LevelMatchFilter.\nother options can be found at\n<a href=\"http://www.beefycode.com/post/log4net-tutorial-pt-7-filters.aspx\" rel=\"nofollow noreferrer\">log4net tutorial - filters</a></p>\n\n<p>in ur appender section add</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;filter type=\"log4net.Filter.LevelMatchFilter\"&gt;\n &lt;levelToMatch value=\"Info\" /&gt;\n &lt;acceptOnMatch value=\"true\" /&gt;\n&lt;/filter&gt;\n</code></pre>\n\n<p>the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters</p>\n" } ]
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 good blog post explaining the issue and how to solve it: </p>\n\n<p><a href=\"http://kpumuk.info/asp-net/using-panel-defaultbutton-property-with-linkbutton-control-in-asp-net/\" rel=\"nofollow noreferrer\">Using Panel.DefaultButton property with LinkButton control in ASP.NET</a></p>\n" }, { "answer_id": 6097, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 0, "selected": false, "text": "<p>I might be wrong and this might not make a difference but have you tried:</p>\n\n<pre><code>Me.Page.Form.DefaultButton = SearchButton.ID\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>Me.Page.Form.DefaultButton = SearchButton.UniqueID\n</code></pre>\n" }, { "answer_id": 7740, "author": "brendan", "author_id": 225, "author_profile": "https://Stackoverflow.com/users/225", "pm_score": 3, "selected": true, "text": "<p>Ends up this resolved my issue:</p>\n\n<pre><code> SearchButton.UseSubmitBehavior = False\n</code></pre>\n" } ]
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 console interface and grouping select statements. First, add your \"Company Name\" field. Then:</p>\n\n<pre><code>SELECT count(*) AS repcount, \"Location Name\" FROM mytable\n WHERE \"Company Name\" IS NULL\n GROUP BY \"Location Name\"\n ORDER BY repcount DESC\n LIMIT 5;\n</code></pre>\n\n<p>Figure out what company the location at the top of the list belongs to and then update your company name field with an UPDATE ... WHERE \"Location Name\" = \"The Location\" statement.</p>\n\n<p>P.S. - You should really break your company names and location names out into separate tables and refer to them by their primary keys.</p>\n\n<p>Update: - Wow - no duplicates? How many records do you have?</p>\n" }, { "answer_id": 6120, "author": "Jake McGraw", "author_id": 302, "author_profile": "https://Stackoverflow.com/users/302", "pm_score": 2, "selected": true, "text": "<p>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.</p>\n\n<hr>\n\n<p><strong>Update</strong></p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n\n<p>Okay... try this:</p>\n\n<ol>\n<li>Build a list of candidate CompanyNames by finding LocationNames made up of mostly or all alphabetic characters. You can use <a href=\"http://us2.php.net/manual/en/book.pcre.php\" rel=\"nofollow noreferrer\">regular expressions</a> for this. Store this list in a separate table.</li>\n<li>Sort that list alphabetically and (manually) determine which entries should be CompanyNames.</li>\n<li>Compare each CompanyName to each LocationName and come up with a match score (use <a href=\"http://us2.php.net/manual/en/function.levenshtein.php\" rel=\"nofollow noreferrer\">Levenshtein</a> or some other string matching algo). Store the result in a separate table.</li>\n<li>Set a threshold score such that any MatchScore &lt; Threshold will not be considered a match for a given CompanyName.</li>\n<li>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.</li>\n</ol>\n\n<p>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.</p>\n" }, { "answer_id": 6124, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 0, "selected": false, "text": "<p>I was going to recommend some complicated token matching algorithm but it's really tricky to get right and if you're data does not have a lot of correlation (typos, etc) then it's not going to give very good results.</p>\n\n<p>I would recommend you submit a job to the <a href=\"http://www.mturk.com/mturk/welcome\" rel=\"nofollow noreferrer\">Amazon Mechanical Turk</a> and let a human sort it out.</p>\n" }, { "answer_id": 6129, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 0, "selected": false, "text": "<p>Ideally, you'd probably want a separate table named Company and then a company_id column in this \"Location\" table that is a foreign key to the Company table's primary key, likely called id. That would avoid a fair bit of text duplication in this table (over 18,000 rows, an integer foreign key would save quite a bit of space over a varchar column).</p>\n\n<p>But you're still faced with a method for loading that Company table and then properly associating it with the rows in Location. There's no general solution, but you could do something along these lines:</p>\n\n<ol>\n<li>Create the Company table, with an id column that auto-increments (depends on your RDBMS).</li>\n<li>Find all of the unique company names and insert them into Company.</li>\n<li>Add a column, company_id, to Location that accepts NULLs (for now) and that is a foreign key of the Company.id column.</li>\n<li>For each row in Location, determine the corresponding company, and UPDATE that row's company_id column with that company's id. This is likely the most challenging step. If your data is like what you show in the example, you'll likely have to take many runs at this with various string matching approaches.</li>\n<li>Once all rows in Location have a company_id value, then you can ALTER the Company table to add a NOT NULL constraint to the company_id column (assuming that every location <em>must</em> have a company, which seems reasonable).</li>\n</ol>\n\n<p>If you can make a copy of your Location table, you can gradually build up a series of SQL statements to populate the company_id foreign key. If you make a mistake, you can just start over and rerun the script up to the point of failure.</p>\n" }, { "answer_id": 6428, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 0, "selected": false, "text": "<p>Yes, that step 4 from my previous post is a doozy.</p>\n\n<p>No matter what, you're probably going to have to do some of this by hand, but you may be able to automate the bulk of it. For the example locations you gave, a query like the following would set the appropriate company_id value:</p>\n\n<pre><code>UPDATE Location\nSET Company_ID = 1\nWHERE (LOWER(Location_Name) LIKE '%to_n shop%'\nOR LOWER(Location_Name) LIKE '%tts%')\nAND Company_ID IS NULL;\n</code></pre>\n\n<p>I believe that would match your examples (I added the <code>IS NULL</code> part to not overwrite previously set Company_ID values), but of course in 18,000 rows you're going to have to be pretty inventive to handle the various combinations.</p>\n\n<p>Something else that might help would be to use the names in Company to generate queries like the one above. You could do something like the following (in MySQL):</p>\n\n<pre><code>SELECT CONCAT('UPDATE Location SET Company_ID = ',\n Company_ID, ' WHERE LOWER(Location_Name) LIKE ',\n LOWER(REPLACE(Company_Name), ' ', '%'), ' AND Company_ID IS NULL;')\nFROM Company;\n</code></pre>\n\n<p>Then just run the statements that it produces. That could do a lot of the grunge work for you.</p>\n" } ]
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 search for the reasons. Sometimes I see I should use polymorphism, sometimes I need to add some state object. Basically, it implies a refactoring is needed (a code smell). </p>\n\n<p>Sometimes I use <a href=\"http://en.wikipedia.org/wiki/De_Morgan%27s_laws\" rel=\"nofollow noreferrer\">De-Morgan's laws</a> to simplify boolean expressions a bit.</p>\n" }, { "answer_id": 6132, "author": "TimM", "author_id": 32, "author_profile": "https://Stackoverflow.com/users/32", "pm_score": 1, "selected": false, "text": "<p>I resort to separate boolean values:</p>\n\n<pre><code>Bool cond1 == (var1 &amp;&amp; var2);\nBool cond2 == (var3 &amp;&amp; var4);\n\nif ( cond1 &amp;&amp; cond2 ) {}\n</code></pre>\n" }, { "answer_id": 6133, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 2, "selected": false, "text": "<p>I've seen a lot of people and editors either indenting each condition in your if statement with one tab, or matching it up with the open paren:</p>\n\n<pre><code>if (var1 == true\n &amp;&amp; var2 == true\n &amp;&amp; var3 == true\n ) {\n /* do something.. */\n}\n</code></pre>\n\n<p>I usually put the close paren on the same line as the last condition:</p>\n\n<pre><code>if (var1 == true\n &amp;&amp; var2 == true\n &amp;&amp; var3 == true) {\n /* do something.. */\n}\n</code></pre>\n\n<p>But I don't think this is quite as clean.</p>\n" }, { "answer_id": 6135, "author": "Mike Powell", "author_id": 205, "author_profile": "https://Stackoverflow.com/users/205", "pm_score": 3, "selected": false, "text": "<p>I'll often split these up into component boolean variables:</p>\n\n<pre><code>bool orderValid = orderDate &lt; DateTime.Now &amp;&amp; orderStatus != Status.Canceled;\nbool custValid = customerBalance == 0 &amp;&amp; customerName != \"Mike\";\nif (orderValid &amp;&amp; custValid)\n{\n...\n</code></pre>\n" }, { "answer_id": 6140, "author": "Coincoin", "author_id": 42, "author_profile": "https://Stackoverflow.com/users/42", "pm_score": 7, "selected": true, "text": "<p>Separate the condition in several booleans and then use a master boolean as the condition.</p>\n\n<pre><code>bool isOpaque = object.Alpha == 1.0f;\nbool isDrawable = object.CanDraw &amp;&amp; object.Layer == currentLayer;\nbool isHidden = hideList.Find(object);\n\nbool isVisible = isOpaque &amp;&amp; isDrawable &amp;&amp; ! isHidden;\n\nif(isVisible)\n{\n // ...\n}\n</code></pre>\n\n<p>Better yet:</p>\n\n<pre><code>public bool IsVisible {\n get\n {\n bool isOpaque = object.Alpha == 1.0f;\n bool isDrawable = object.CanDraw &amp;&amp; object.Layer == currentLayer;\n bool isHidden = hideList.Find(object);\n\n return isOpaque &amp;&amp; isDrawable &amp;&amp; ! isHidden;\n }\n}\n\nvoid Draw()\n{\n if(IsVisible)\n {\n // ...\n }\n}\n</code></pre>\n\n<p>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!</p>\n" }, { "answer_id": 6142, "author": "Mark Renouf", "author_id": 758, "author_profile": "https://Stackoverflow.com/users/758", "pm_score": 2, "selected": false, "text": "<p>Well, first off, why not:</p>\n\n<blockquote>\n <p>if (var1 &amp;&amp; var2 &amp;&amp; var2 &amp;&amp; var3 &amp;&amp; var4 &amp;&amp; var5 &amp;&amp; var6) {<br>\n ... </p>\n</blockquote>\n\n<p>Also, it's very hard to refactor abstract code examples. If you showed a specific example it would be easier to identify a better pattern to fit the problem.</p>\n\n<p>It's no better, but what I've done in the past:\n(The following method prevents short-circuiting boolean testing, all tests are run even if the first is false. Not a recommended pattern unless you know you need to always execute all the code before returning -- Thanks to ptomato for spotting my mistake!)</p>\n\n<blockquote>\n <p>boolean ok = cond1;<br>\n ok &amp;= cond2;<br>\n ok &amp;= cond3;<br>\n ok &amp;= cond4;<br>\n ok &amp;= cond5;<br>\n ok &amp;= cond6; </p>\n</blockquote>\n\n<p><strike>Which is the same as:</strike> (not the same, see above note!)</p>\n\n<blockquote>\n <p>ok = (cond1 &amp;&amp; cond2 &amp;&amp; cond3 &amp;&amp; cond4 &amp;&amp; cond5 &amp;&amp; cond6);</p>\n</blockquote>\n" }, { "answer_id": 6148, "author": "Nicholas Trandem", "author_id": 765, "author_profile": "https://Stackoverflow.com/users/765", "pm_score": 0, "selected": false, "text": "<p>I like to break them down by level, so I'd format you example like this:</p>\n\n<pre><code>if (var1 = true\n &amp;&amp; var2 = true\n &amp;&amp; var2 = true\n &amp;&amp; var3 = true\n &amp;&amp; var4 = true\n &amp;&amp; var5 = true\n &amp;&amp; var6 = true){\n</code></pre>\n\n<p>It's handy when you have more nesting, like this (obviously the real conditions would be more interesting than \"= true\" for everything):</p>\n\n<pre><code>if ((var1 = true &amp;&amp; var2 = true)\n &amp;&amp; ((var2 = true &amp;&amp; var3 = true)\n &amp;&amp; (var4 = true &amp;&amp; var5 = true))\n &amp;&amp; (var6 = true)){\n</code></pre>\n" }, { "answer_id": 6152, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321413091\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Implementation Patterns</a> by Kent Beck. There is a particular pattern I am thinking of that may help in this situation... it is called \"Guards\". Rather than having tons of conditions, you can break them out into a guard, which makes it clear which are the adverse conditions in a method.</p>\n\n<p>So for example, if you have a method that does something, but there are certain conditions where it shouldn't do something, rather than:</p>\n\n<pre><code>public void doSomething() {\n if (condition1 &amp;&amp; condition2 &amp;&amp; condition3 &amp;&amp; condition4) {\n // do something\n }\n}\n</code></pre>\n\n<p>You could change it to:</p>\n\n<pre><code>public void doSomething() {\n if (!condition1) {\n return;\n }\n\n if (!condition2) {\n return;\n }\n\n if (!condition3) {\n return;\n }\n\n if (!condition4) {\n return;\n }\n\n // do something\n}\n</code></pre>\n\n<p>It's a bit more verbose, but a lot more readable, especially when you start having weird nesting, the guard can help (combined with extracting methods).</p>\n\n<p>I HIGHLY recommend that book by the way.</p>\n" }, { "answer_id": 6157, "author": "Karl Seguin", "author_id": 34, "author_profile": "https://Stackoverflow.com/users/34", "pm_score": 4, "selected": false, "text": "<p>I'm surprised no one got this one yet. There's a refactoring specifically for this type of problem:</p>\n\n<p><a href=\"http://www.refactoring.com/catalog/decomposeConditional.html\" rel=\"nofollow noreferrer\">http://www.refactoring.com/catalog/decomposeConditional.html</a></p>\n" }, { "answer_id": 6158, "author": "Simon Gillbee", "author_id": 756, "author_profile": "https://Stackoverflow.com/users/756", "pm_score": 3, "selected": false, "text": "<p>There are two issues to address here: readability and understandability</p>\n\n<p>The \"readability\" solution is a style issue and as such is open to interpretation. My preference is this:</p>\n\n<pre><code>if (var1 == true &amp;&amp; // Explanation of the check\n var2 == true &amp;&amp; // Explanation of the check\n var3 == true &amp;&amp; // Explanation of the check\n var4 == true &amp;&amp; // Explanation of the check\n var5 == true &amp;&amp; // Explanation of the check\n var6 == true) // Explanation of the check\n { }\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>if (var1 &amp;&amp; // Explanation of the check\n var2 &amp;&amp; // Explanation of the check\n var3 &amp;&amp; // Explanation of the check\n var4 &amp;&amp; // Explanation of the check\n var5 &amp;&amp; // Explanation of the check\n var6) // Explanation of the check\n { }\n</code></pre>\n\n<p>That said, this kind of complex check can be quite difficult to mentally parse while scanning the code (especially if you are not the original author). Consider creating a helper method to abstract some of the complexity away:</p>\n\n<pre><code>/// &lt;Summary&gt;\n/// Tests whether all the conditions are appropriately met\n/// &lt;/Summary&gt;\nprivate bool AreAllConditionsMet (\n bool var1,\n bool var2,\n bool var3,\n bool var4,\n bool var5,\n bool var6)\n{\n return (\n var1 &amp;&amp; // Explanation of the check\n var2 &amp;&amp; // Explanation of the check\n var3 &amp;&amp; // Explanation of the check\n var4 &amp;&amp; // Explanation of the check\n var5 &amp;&amp; // Explanation of the check\n var6); // Explanation of the check\n}\n\nprivate void SomeMethod()\n{\n // Do some stuff (including declare the required variables)\n if (AreAllConditionsMet (var1, var2, var3, var4, var5, var6))\n {\n // Do something\n }\n}\n</code></pre>\n\n<p>Now when visually scanning the \"SomeMethod\" method, the actual complexity of the test logic is hidden but the semantic meaning is preserved for humans to understand at a high-level. If the developer really needs to understand the details, the AreAllConditionsMet method can be examined.</p>\n\n<p>This is formally known as the \"Decompose Conditional\" refactoring pattern I think. Tools like Resharper or Refactor Pro! can making doing this kind of refactoring easy!</p>\n\n<p>In all cases, the key to having readable and understandable code is to use realistic variable names. While I understand this is a contrived example, \"var1\", \"var2\", etc are <strong>not</strong> acceptable variable names. They should have a name which reflects the underlying nature of the data they represent.</p>\n" }, { "answer_id": 6159, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 0, "selected": false, "text": "<p>If you happen to be programming in Python, it's a cinch with the built-in <code>all()</code> function applied over the list of your variables (I'll just use Boolean literals here):</p>\n\n<pre><code>&gt;&gt;&gt; L = [True, True, True, False, True]\n&gt;&gt;&gt; all(L) # True, only if all elements of L are True.\nFalse\n&gt;&gt;&gt; any(L) # True, if any elements of L are True.\nTrue\n</code></pre>\n\n<p>Is there any corresponding function in your language (C#? Java?). If so, that's likely the cleanest approach.</p>\n" }, { "answer_id": 6163, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": -1, "selected": false, "text": "<p>If you do this:</p>\n\n<pre><code>if (var1 == true) {\n if (var2 == true) {\n if (var3 == true) {\n ...\n }\n }\n}\n</code></pre>\n\n<p>Then you can also respond to cases where something isn't true. For example, if you're validating input, you could give the user a tip for how to properly format it, or whatever.</p>\n" }, { "answer_id": 6178, "author": "TimM", "author_id": 32, "author_profile": "https://Stackoverflow.com/users/32", "pm_score": 0, "selected": false, "text": "<p>McDowell,</p>\n\n<p>You are correct that when using the single '&amp;' operator that both sides of the expression evaluate. However, when using the '&amp;&amp;' operator (at least in C#) then the first expression to return false is the last expression evaluated. This makes putting the evaulation before the FOR statement just as good as any other way of doing it.</p>\n" }, { "answer_id": 6187, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 1, "selected": false, "text": "<p>As others have mentioned, I would analyze your conditionals to see if there's a way you can outsource it to other methods to increase readability.</p>\n" }, { "answer_id": 6193, "author": "fastcall", "author_id": 328, "author_profile": "https://Stackoverflow.com/users/328", "pm_score": 0, "selected": false, "text": "<p>@tweakt</p>\n\n<blockquote>\n <p>It's no better, but what I've done in the past:</p>\n \n <p>boolean ok = cond1;\n ok &amp;= cond2;\n ok &amp;= cond3;\n ok &amp;= cond4;\n ok &amp;= cond5;\n ok &amp;= cond6;</p>\n \n <p>Which is the same as:</p>\n \n <p>ok = (cond1 &amp;&amp; cond2 &amp;&amp; cond3 &amp;&amp; cond4 &amp;&amp; cond5 &amp;&amp; cond6);</p>\n</blockquote>\n\n<p>Actually, these two things are not the same in most languages. The second expression will typically stop being evaluated as soon as one of the conditions is false, which can be a big performance improvement if evaluating the conditions is expensive.</p>\n\n<p>For readability, I personally prefer Mike Stone's proposal above. It's easy to verbosely comment and preserves all of the computational advantages of being able to early out. You can also do the same technique inline in a function if it'd confuse the organization of your code to move the conditional evaluation far away from your other function. It's a bit cheesy, but you can always do something like:</p>\n\n<pre><code>do {\n if (!cond1)\n break;\n if (!cond2)\n break;\n if (!cond3)\n break;\n ...\n DoSomething();\n} while (false);\n</code></pre>\n\n<p>the while (false) is kind of cheesy. I wish languages had a scoping operator called \"once\" or something that you could break out of easily.</p>\n" }, { "answer_id": 14148, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 2, "selected": false, "text": "<p>Try looking at Functors and Predicates. The Apache Commons project has a great set of objects to allow you to encapsulate conditional logic into objects. Example of their use is available on O'reilly <a href=\"http://www.onjava.com/pub/a/onjava/2004/12/22/jakarta-gems-1.html?page=2\" rel=\"nofollow noreferrer\">here</a>. Excerpt of code example:</p>\n\n<pre><code>import org.apache.commons.collections.ClosureUtils;\nimport org.apache.commons.collections.CollectionUtils;\nimport org.apache.commons.collections.functors.NOPClosure;\n\nMap predicateMap = new HashMap();\n\npredicateMap.put( isHonorRoll, addToHonorRoll );\npredicateMap.put( isProblem, flagForAttention );\npredicateMap.put( null, ClosureUtils.nopClosure() );\n\nClosure processStudents = \n ClosureUtils.switchClosure( predicateMap );\n\nCollectionUtils.forAllDo( allStudents, processStudents );\n</code></pre>\n\n<p>Now the details of all those isHonorRoll predicates and the closures used to evaluate them:</p>\n\n<pre><code>import org.apache.commons.collections.Closure;\nimport org.apache.commons.collections.Predicate;\n\n// Anonymous Predicate that decides if a student \n// has made the honor roll.\nPredicate isHonorRoll = new Predicate() {\n public boolean evaluate(Object object) {\n Student s = (Student) object;\n\n return( ( s.getGrade().equals( \"A\" ) ) ||\n ( s.getGrade().equals( \"B\" ) &amp;&amp; \n s.getAttendance() == PERFECT ) );\n }\n};\n\n// Anonymous Predicate that decides if a student\n// has a problem.\nPredicate isProblem = new Predicate() {\n public boolean evaluate(Object object) {\n Student s = (Student) object;\n\n return ( ( s.getGrade().equals( \"D\" ) || \n s.getGrade().equals( \"F\" ) ) ||\n s.getStatus() == SUSPENDED );\n }\n};\n\n// Anonymous Closure that adds a student to the \n// honor roll\nClosure addToHonorRoll = new Closure() {\n public void execute(Object object) {\n Student s = (Student) object;\n\n // Add an award to student record\n s.addAward( \"honor roll\", 2005 );\n Database.saveStudent( s );\n }\n};\n\n// Anonymous Closure flags a student for attention\nClosure flagForAttention = new Closure() {\n public void execute(Object object) {\n Student s = (Student) object;\n\n // Flag student for special attention\n s.addNote( \"talk to student\", 2005 );\n s.addNote( \"meeting with parents\", 2005 );\n Database.saveStudent( s );\n }\n};\n</code></pre>\n" }, { "answer_id": 14167, "author": "wusher", "author_id": 1632, "author_profile": "https://Stackoverflow.com/users/1632", "pm_score": 0, "selected": false, "text": "<p>I like to break each condition into descriptive variables.</p>\n\n<pre><code>bool isVar1Valid, isVar2Valid, isVar3Valid, isVar4Valid;\nisVar1Valid = ( var1 == 1 )\nisVar2Valid = ( var2.Count &gt;= 2 )\nisVar3Valid = ( var3 != null )\nisVar4Valid = ( var4 != null &amp;&amp; var4.IsEmpty() == false )\nif ( isVar1Valid &amp;&amp; isVar2Valid &amp;&amp; isVar3Valid &amp;&amp; isVar4Valid ) {\n //do code\n}\n</code></pre>\n" }, { "answer_id": 14220, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 2, "selected": false, "text": "<p>Steve Mcconell's advice, from <a href=\"https://rads.stackoverflow.com/amzn/click/com/0735619670\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Code Complete</a>:\nUse a multi-dimensional table. Each variable serves as an index to the table,\nand the if statement turns into a table lookup. For example if (size == 3 &amp;&amp; weight > 70)\ntranslates into the table entry decision[size][weight_group]</p>\n" }, { "answer_id": 202845, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 0, "selected": false, "text": "<p>If I was doing it in Perl, This is how I might run the checks.</p>\n\n<pre><code>{\n last unless $var1;\n last unless $var2;\n last unless $var3;\n last unless $var4;\n last unless $var5;\n last unless $var6;\n\n ... # Place Code Here\n}\n</code></pre>\n\n<p>If you plan on using this over a subroutine replace every instance of <code>last</code> with <code>return</code>;</p>\n" }, { "answer_id": 2797562, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 1, "selected": false, "text": "<p>In reflective languages like PHP, you can use variable-variables:</p>\n\n<pre><code>$vars = array('var1', 'var2', ... etc.);\nforeach ($vars as $v)\n if ($$v == true) {\n // do something\n break;\n }\n</code></pre>\n" }, { "answer_id": 43766233, "author": "Sean", "author_id": 7892369, "author_profile": "https://Stackoverflow.com/users/7892369", "pm_score": 0, "selected": false, "text": "<pre><code> if ( (condition_A)\n &amp;&amp; (condition_B)\n &amp;&amp; (condition_C)\n &amp;&amp; (condition_D)\n &amp;&amp; (condition_E)\n &amp;&amp; (condition_F)\n )\n {\n ...\n }\n</code></pre>\n\n<p>as opposed to</p>\n\n<pre><code> if (condition_A) {\n if (condition_B) {\n if (condition_C) {\n if (condition_D) {\n if (condition_E) {\n if (condition_F) {\n ...\n }\n }\n }\n }\n }\n }\n</code></pre>\n\n<p>and</p>\n\n<pre><code> if ( ( (condition_A)\n &amp;&amp; (condition_B)\n )\n || ( (condition_C)\n &amp;&amp; (condition_D)\n )\n || ( (condition_E)\n &amp;&amp; (condition_F)\n )\n )\n {\n do_this_same_thing();\n }\n</code></pre>\n\n<p>as opposed to</p>\n\n<pre><code> if (condition_A &amp;&amp; condition_B) {\n do_this_same_thing();\n }\n if (condition_C &amp;&amp; (condition_D) {\n do_this_same_thing();\n }\n if (condition_E &amp;&amp; condition_F) {\n do_this_same_thing();\n }\n</code></pre>\n\n<p>Most of the static analysis tools for examining code will complain if multiple conditional expressions do not use explicit parenthesis dictating expression analysis, instead of relying on operator precedence rules and fewer parenthesis.</p>\n\n<p>Vertical alignment at the same indent level of open/close braces {}, open close parenthesis (), conditional expressions with parenthesis and operators on the left is an very useful practice, which greatly ENHANCES readability and clarity of the code as opposed to jamming everything that can possibly be jammed onto a single line, sans vertical alignment, spaces or parenthesis</p>\n\n<p>Operator precedence rules are tricky, e.g. &amp;&amp; has higher precedence than ||, but | has precedence than &amp;&amp;</p>\n\n<p>So, ...</p>\n\n<pre><code> if (expr_A &amp; expr_B || expr_C | expr_D &amp; expr_E || expr_E &amp;&amp; expr_F &amp; expr_G || expr_H {\n }\n</code></pre>\n\n<p>is a really easy multiple conditional expression for mere humans to read and evaluate improperly.</p>\n\n<pre><code> if ( ( (expr_A)\n &amp; (expr_B)\n )\n || ( (expr_C)\n | ( (expr_D)\n &amp; (expr_E)\n )\n )\n || ( (expr_E)\n &amp;&amp; ( (expr_F)\n &amp; (expr_G)\n )\n )\n || (expr_H)\n )\n {\n }\n</code></pre>\n\n<p>There is nothing wrong with horizontal space (linefeeds), vertical alignment, or explicit parenthesis guiding expression evaluation, all of which ENHANCES readability and clarity</p>\n" } ]
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 option to tell it which fields to show and by which to sort. You can sort the output by running time, grep the process you want and then kill it.</p>\n\n<p>HTH</p>\n" }, { "answer_id": 6145, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 5, "selected": false, "text": "<p>For anything older than one day,</p>\n\n<pre><code>ps aux\n</code></pre>\n\n<p>will give you the answer, but it drops down to day-precision which might not be as useful.</p>\n\n<pre><code>USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND\nroot 1 0.0 0.0 7200 308 ? Ss Jun22 0:02 init [5]\nroot 2 0.0 0.0 0 0 ? S Jun22 0:02 [migration/0]\nroot 3 0.0 0.0 0 0 ? SN Jun22 0:18 [ksoftirqd/0]\nroot 4 0.0 0.0 0 0 ? S Jun22 0:00 [watchdog/0]\n</code></pre>\n\n<p>If you're on linux or another system with the /proc filesystem, In this example, you can only see that process 1 has been running since June 22, but no indication of the time it was started.</p>\n\n<pre><code>stat /proc/&lt;pid&gt;\n</code></pre>\n\n<p>will give you a more precise answer. For example, here's an exact timestamp for process 1, which ps shows only as Jun22:</p>\n\n<pre><code>ohm ~$ stat /proc/1\n File: `/proc/1'\n Size: 0 Blocks: 0 IO Block: 4096 directory\nDevice: 3h/3d Inode: 65538 Links: 5\nAccess: (0555/dr-xr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root)\nAccess: 2008-06-22 15:37:44.347627750 -0700\nModify: 2008-06-22 15:37:44.347627750 -0700\nChange: 2008-06-22 15:37:44.347627750 -0700\n</code></pre>\n" }, { "answer_id": 6150, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 5, "selected": false, "text": "<p>Found an answer that works for me:</p>\n\n<p><strong>warning: this will find <em>and kill</em> long running processes</strong></p>\n\n<pre><code>ps -eo uid,pid,etime | egrep '^ *user-id' | egrep ' ([0-9]+-)?([0-9]{2}:?){3}' | awk '{print $2}' | xargs -I{} kill {}\n</code></pre>\n\n<p>(Where <em>user-id</em> is a specific user's ID with long-running processes.)</p>\n\n<p>The second regular expression matches the a time that has an optional days figure, followed by an hour, minute, and second component, and so is at least one hour in length.</p>\n" }, { "answer_id": 6167, "author": "ggasp", "author_id": 527, "author_profile": "https://Stackoverflow.com/users/527", "pm_score": 3, "selected": false, "text": "<p>In this way you can obtain the list of the ten oldest processes: </p>\n\n<pre>ps -elf | sort -r -k12 | head -n 10</pre>\n" }, { "answer_id": 1616779, "author": "Maniraj Patri", "author_id": 195723, "author_profile": "https://Stackoverflow.com/users/195723", "pm_score": 2, "selected": false, "text": "<p>do a <code>ps -aef</code>. this will show you the time at which the process started. Then using the <code>date</code> command find the current time. Calculate the difference between the two to find the age of the process.</p>\n" }, { "answer_id": 3474710, "author": "Peter V. Mørch", "author_id": 345716, "author_profile": "https://Stackoverflow.com/users/345716", "pm_score": 3, "selected": false, "text": "<p>Perl's Proc::ProcessTable will do the trick:\n<a href=\"http://search.cpan.org/dist/Proc-ProcessTable/\" rel=\"noreferrer\">http://search.cpan.org/dist/Proc-ProcessTable/</a></p>\n\n<p>You can install it in debian or ubuntu with <code>sudo apt-get install libproc-processtable-perl</code></p>\n\n<p>Here is a one-liner:</p>\n\n<pre><code>perl -MProc::ProcessTable -Mstrict -w -e 'my $anHourAgo = time-60*60; my $t = new Proc::ProcessTable;foreach my $p ( @{$t-&gt;table} ) { if ($p-&gt;start() &lt; $anHourAgo) { print $p-&gt;pid, \"\\n\" } }'\n</code></pre>\n\n<p>Or, more formatted, put this in a file called process.pl:</p>\n\n<pre><code>#!/usr/bin/perl -w\nuse strict;\nuse Proc::ProcessTable;\nmy $anHourAgo = time-60*60;\nmy $t = new Proc::ProcessTable;\nforeach my $p ( @{$t-&gt;table} ) {\n if ($p-&gt;start() &lt; $anHourAgo) {\n print $p-&gt;pid, \"\\n\";\n }\n}\n</code></pre>\n\n<p>then run <code>perl process.pl</code></p>\n\n<p>This gives you more versatility and 1-second-resolution on start time.</p>\n" }, { "answer_id": 7020431, "author": "Rodney Amato", "author_id": 4342, "author_profile": "https://Stackoverflow.com/users/4342", "pm_score": 1, "selected": false, "text": "<p>I did something similar to the accepted answer but slightly differently since I want to match based on process name and based on the bad process running for more than 100 seconds </p>\n\n<pre><code>kill $(ps -o pid,bsdtime -p $(pgrep bad_process) | awk '{ if ($RN &gt; 1 &amp;&amp; $2 &gt; 100) { print $1; }}')\n</code></pre>\n" }, { "answer_id": 9316199, "author": "mob", "author_id": 168657, "author_profile": "https://Stackoverflow.com/users/168657", "pm_score": 1, "selected": false, "text": "<p><code>stat -t /proc/&lt;pid&gt; | awk '{print $14}'</code></p>\n\n<p>to get the start time of the process in seconds since the epoch. Compare with current time (<code>date +%s</code>) to get the current age of the process.</p>\n" }, { "answer_id": 9973593, "author": "David Jeske", "author_id": 519568, "author_profile": "https://Stackoverflow.com/users/519568", "pm_score": 0, "selected": false, "text": "<p>In case anyone needs this in C, you can use readproc.h and libproc:</p>\n\n<pre><code>#include &lt;proc/readproc.h&gt;\n#include &lt;proc/sysinfo.h&gt;\n\nfloat\npid_age(pid_t pid)\n{\n proc_t proc_info;\n int seconds_since_boot = uptime(0,0);\n if (!get_proc_stats(pid, &amp;proc_info)) {\n return 0.0;\n }\n\n // readproc.h comment lies about what proc_t.start_time is. It's\n // actually expressed in Hertz ticks since boot\n\n int seconds_since_1970 = time(NULL);\n int time_of_boot = seconds_since_1970 - seconds_since_boot;\n long t = seconds_since_boot - (unsigned long)(proc_info.start_time / Hertz);\n\n int delta = t;\n float days = ((float) delta / (float)(60*60*24));\n return days;\n}\n</code></pre>\n" }, { "answer_id": 10525736, "author": "Jodie C", "author_id": 812270, "author_profile": "https://Stackoverflow.com/users/812270", "pm_score": 6, "selected": true, "text": "<p>If they just need to be killed:</p>\n\n<pre><code>if [[ \"$(uname)\" = \"Linux\" ]];then killall --older-than 1h someprocessname;fi\n</code></pre>\n\n<p>If you want to see what it's matching</p>\n\n<pre><code>if [[ \"$(uname)\" = \"Linux\" ]];then killall -i --older-than 1h someprocessname;fi\n</code></pre>\n\n<p>The <code>-i</code> flag will prompt you with yes/no for each process match. </p>\n" }, { "answer_id": 11042931, "author": "Rafael S. Calsaverini", "author_id": 114388, "author_profile": "https://Stackoverflow.com/users/114388", "pm_score": 2, "selected": false, "text": "<p>You can use <code>bc</code> to join the two commands in mob's answer and get how many seconds ellapsed since the process started: </p>\n\n<pre><code>echo `date +%s` - `stat -t /proc/&lt;pid&gt; | awk '{print $14}'` | bc\n</code></pre>\n\n<p>edit:</p>\n\n<p>Out of boredom while waiting for long processes to run, this is what came out after a few minutes fiddling:</p>\n\n<pre><code>#file: sincetime\n#!/bin/bash\ninit=`stat -t /proc/$1 | awk '{print $14}'`\ncurr=`date +%s`\nseconds=`echo $curr - $init| bc`\nname=`cat /proc/$1/cmdline`\necho $name $seconds\n</code></pre>\n\n<p>If you put this on your path and call it like this:\n sincetime </p>\n\n<p>it will print the process cmdline and seconds since started. You can also put this in your path:</p>\n\n<pre><code>#file: greptime\n#!/bin/bash\npidlist=`ps ax | grep -i -E $1 | grep -v grep | awk '{print $1}' | grep -v PID | xargs echo`\nfor pid in $pidlist; do\n sincetime $pid\ndone\n</code></pre>\n\n<p>And than if you run:</p>\n\n<pre><code>greptime &lt;pattern&gt;\n</code></pre>\n\n<p>where patterns is a string or extended regular expression, it will print out all processes matching this pattern and the seconds since they started. :)</p>\n" }, { "answer_id": 16547667, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Jodie C and others have pointed out that <code>killall -i</code> can be used, which is fine if you want to use the process name to kill. But if you want to kill by the same parameters as <code>pgrep -f</code>, you need to use something like the following, using pure bash and the <code>/proc</code> filesystem.</p>\n\n<pre><code>#!/bin/sh \n\nmax_age=120 # (seconds) \nnaughty=\"$(pgrep -f offlineimap)\" \nif [[ -n \"$naughty\" ]]; then # naughty is running \n age_in_seconds=$(echo \"$(date +%s) - $(stat -c %X /proc/$naughty)\" | bc) \n if [[ \"$age_in_seconds\" -ge \"$max_age\" ]]; then # naughty is too old! \n kill -s 9 \"$naughty\" \n fi \nfi \n</code></pre>\n\n<p>This lets you find and kill processes older than <code>max_age</code> seconds using the <strong>full process name</strong>; i.e., the process named <code>/usr/bin/python2 offlineimap</code> can be killed by reference to \"offlineimap\", whereas the <code>killall</code> solutions presented here will only work on the string \"python2\".</p>\n" }, { "answer_id": 24594339, "author": "user3743785", "author_id": 3743785, "author_profile": "https://Stackoverflow.com/users/3743785", "pm_score": 0, "selected": false, "text": "<p>Came across somewhere..thought it is simple and useful</p>\n\n<p>You can use the command in crontab directly ,</p>\n\n<pre><code>* * * * * ps -lf | grep \"user\" | perl -ane '($h,$m,$s) = split /:/,$F\n+[13]; kill 9, $F[3] if ($h &gt; 1);'\n</code></pre>\n\n<p>or, we can write it as shell script ,</p>\n\n<pre><code>#!/bin/sh\n# longprockill.sh\nps -lf | grep \"user\" | perl -ane '($h,$m,$s) = split /:/,$F[13]; kill\n+ 9, $F[3] if ($h &gt; 1);'\n</code></pre>\n\n<p>And call it crontab like so,</p>\n\n<pre><code>* * * * * longprockill.sh\n</code></pre>\n" }, { "answer_id": 52023199, "author": "Phil Hudson", "author_id": 6375702, "author_profile": "https://Stackoverflow.com/users/6375702", "pm_score": 0, "selected": false, "text": "<p>My version of <code>sincetime</code> above by @Rafael S. Calsaverini :</p>\n\n<pre><code>#!/bin/bash\nps --no-headers -o etimes,args \"$1\"\n</code></pre>\n\n<p>This reverses the output fields: elapsed time first, full command including arguments second. This is preferred because the full command may contain spaces.</p>\n" } ]
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 the 'pre-revprop-change' hook script to allow that. The example provided, if enabled allows editing only the comment property and only be the original comitter. Great for correcting typos.</p>\n" }, { "answer_id": 6296, "author": "abyx", "author_id": 573, "author_profile": "https://Stackoverflow.com/users/573", "pm_score": 2, "selected": false, "text": "<p>In my work place we've set up a post-commit hook that generates RSS feeds that are displayed in various dash boards and are used for code reviewers to know when it is time to review and for us to see that new employees are committing enough.</p>\n" }, { "answer_id": 6359, "author": "Matt Miller", "author_id": 763, "author_profile": "https://Stackoverflow.com/users/763", "pm_score": 1, "selected": false, "text": "<p>I'm using post-commit hooks (<a href=\"http://lincolnloop.com/blog/2007/may/04/basecamp-svn-integration/\" rel=\"nofollow noreferrer\">I think it's this one</a>) to post a message to a forum on Basecamp for each commit. Two advantages:</p>\n\n<ol>\n<li><p>As the lead developer, I get a roll-up of commits every morning (via the RSS feed from that basecamp forum) and can see what my team has been up to pretty quickly.</p></li>\n<li><p>Our Trac/SVN install is behind our firewall, so this gives my higher-ups in other locations a window into what we're doing. They might not understand it, but to a manager a lot of activity looks like, well, a lot of activity ;)</p></li>\n</ol>\n\n<p>I guess the end result of this is similar to what @Aviv is doing.</p>\n\n<p>I'm looking into solutions for building the latest commit on a separate server for continuous integration, but I'm going to have to change the way we make changes to our database schema before that will work.</p>\n" }, { "answer_id": 9532, "author": "kauppi", "author_id": 964, "author_profile": "https://Stackoverflow.com/users/964", "pm_score": 0, "selected": false, "text": "<p>A hook to notify the bug/issue management system of changes to repository. Ie. the commit message has issue:546 or similar tag in it that is parsed and fed to the bug management system.</p>\n" }, { "answer_id": 27003, "author": "Sir Rippov the Maple", "author_id": 2822, "author_profile": "https://Stackoverflow.com/users/2822", "pm_score": 0, "selected": false, "text": "<p>We check the following with our hook scripts:</p>\n\n<ul>\n<li>That a commit log message has been supplied</li>\n<li>That a reviewer has been specified for the commit</li>\n<li>That no automatically generated code or banned file types land up in the repository</li>\n<li>Send an email out when a branch / tag is created</li>\n</ul>\n\n<p>We still want to implement the following:</p>\n\n<ul>\n<li>Send an email when a user acquires a lock on a file</li>\n<li>Send an email when your lock has been stolen</li>\n<li>Send an email to everyone when a revision property has been changed</li>\n</ul>\n" }, { "answer_id": 29219, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 2, "selected": false, "text": "<p>several things we use them for:</p>\n\n<ul>\n<li>integrating with the bug tracker (<a href=\"http://trac.edgewall.org/\" rel=\"nofollow noreferrer\">Trac in our case</a> - a commit message that says 'Closes #514' automatically marks that bug as closed</li>\n<li>integrating with the build integration (<a href=\"http://buildbot.net/\" rel=\"nofollow noreferrer\">buildbot in our case</a> - a commit to a watched branch triggers a build</li>\n<li>pre-commit hook for validating the commit - we use <a href=\"http://svnchecker.tigris.org/\" rel=\"nofollow noreferrer\">svnchecker</a>. It validates our Python code for <a href=\"http://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8 correctness</a></li>\n<li>sending checkin mails to a mailing list</li>\n<li>running indentation scripts</li>\n</ul>\n" }, { "answer_id": 30649, "author": "Nathan Black", "author_id": 3265, "author_profile": "https://Stackoverflow.com/users/3265", "pm_score": 3, "selected": false, "text": "<p>We use <a href=\"http://www.fogcreek.com/FogBugz/\" rel=\"nofollow noreferrer\">FogBugz</a> for bug tracking, it provides subversion commit scripts that allow you to include a case number in your check in comments and then associates the bug with the check in that fixed it. It does require a <a href=\"http://websvn.tigris.org/\" rel=\"nofollow noreferrer\">WebSVN</a> instance to be set up so that you have a web based viewer for your repository.</p>\n" }, { "answer_id": 44773, "author": "Johan Lübcke", "author_id": 4220, "author_profile": "https://Stackoverflow.com/users/4220", "pm_score": 0, "selected": false, "text": "<p>We use a commit hook script to trigger our release robot. Writing new release information to a file named changes.txt in our different products will trigger the creation of a tag and the relevant artifacts.</p>\n" }, { "answer_id": 44815, "author": "jonezy", "author_id": 2272, "author_profile": "https://Stackoverflow.com/users/2272", "pm_score": 0, "selected": false, "text": "<p>I have one setup using the Ruby Tinder library that I send to a campfire room, if anyone wants the script I can post or send the code to you.</p>\n\n<p>Other common ones I've seen are posts to bug tracking systems and email notifications.</p>\n" }, { "answer_id": 44858, "author": "Troels Arvin", "author_id": 4462, "author_profile": "https://Stackoverflow.com/users/4462", "pm_score": 3, "selected": false, "text": "<p>If you have a mix of unix and Windows users working with the repository, I urge you to use the <em><a href=\"http://svn.apache.org/viewvc/subversion/trunk/contrib/hook-scripts/case-insensitive.py?view=markup\" rel=\"nofollow noreferrer\">case-insensitive.py</a></em> pre-commit hook-script as a precautionary measure. It prevents hard-to-sort-out situations where svn <a href=\"http://subversion.apache.org/faq.html#case-change\" rel=\"nofollow noreferrer\">updates fail for Windows users because of a file rename which only changed the case of the file name</a>. Believe me, there is a good chance it will save you trouble.</p>\n" }, { "answer_id": 53793, "author": "clawrence", "author_id": 5534, "author_profile": "https://Stackoverflow.com/users/5534", "pm_score": 1, "selected": false, "text": "<p>This was discussed on the subversion users mailing list a while ago. <a href=\"http://svn.haxx.se/users/archive-2008-07/0779.shtml\" rel=\"nofollow noreferrer\">This</a> post in particular has some useful ideas.</p>\n" }, { "answer_id": 68850, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 6, "selected": false, "text": "<p>I am using the <code>pre-revprop-change</code> 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.</p>\n\n<p>Here I post a <code>pre-revprop-change.bat</code> batch file for Windows NT or later. You\ncan certainly enhance it with more modifications. You can also derive a\n<code>post-revprop-change.cmd</code> from it to back up the old <code>snv:log</code> somewhere or just to append it to the new log.</p>\n\n<p>The only tricky part was to be able to actually parse the stdin from\nthe batch file. This is done here with the <code>FIND.EXE</code> command.</p>\n\n<p>The other thing is that I have had reports from other users of issues with the use of the <code>/b</code> with the <code>exit</code> command. You may just need to remove that <code>/b</code> in your specific application if error cases do not behave well.</p>\n\n<pre><code>@ECHO OFF\n\nset repos=%1\nset rev=%2\nset user=%3\nset propname=%4\nset action=%5\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow changes to svn:log. The author, date and other revision\n:: properties cannot be changed\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%propname%'=='svn:log' goto ERROR_PROPNAME\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Only allow modifications to svn:log (no addition/overwrite or deletion)\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nif /I not '%action%'=='M' goto ERROR_ACTION\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Make sure that the new svn:log message contains some text.\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset bIsEmpty=true\nfor /f \"tokens=*\" %%g in ('find /V \"\"') do (\n set bIsEmpty=false\n)\nif '%bIsEmpty%'=='true' goto ERROR_EMPTY\n\ngoto :eof\n\n\n\n:ERROR_EMPTY\necho Empty svn:log properties are not allowed. &gt;&amp;2\ngoto ERROR_EXIT\n\n:ERROR_PROPNAME\necho Only changes to svn:log revision properties are allowed. &gt;&amp;2\ngoto ERROR_EXIT\n\n:ERROR_ACTION\necho Only modifications to svn:log revision properties are allowed. &gt;&amp;2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\nexit /b 1 \n</code></pre>\n" }, { "answer_id": 3630318, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 0, "selected": false, "text": "<p>Windows pre-commit hook to check that log contains something.</p>\n\n<pre><code>@ECHO OFF\nsetlocal\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Get subversion arguments\nset repos=%~1\nset txn=%2\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Set some variables\nset svnlookparam=\"%repos%\" -t %txn%\n\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Make sure that the new svn:log message contains some text.\nset bIsEmpty=true\nfor /f \"tokens=* usebackq\" %%g in (`svnlook log %svnlookparam%`) do (\n set bIsEmpty=false\n)\nif '%bIsEmpty%'=='true' goto ERROR_EMPTY\n\necho Allowed. &gt;&amp;2\n\ngoto :END\n\n\n:ERROR_EMPTY\necho Empty log messages are not allowed. &gt;&amp;2\ngoto ERROR_EXIT\n\n:ERROR_EXIT\n:: You may require to remove the /b below if your hook is called directly by subversion\nexit /b 1\n\n:END\nendlocal\n</code></pre>\n" }, { "answer_id": 3630534, "author": "Philibert Perusse", "author_id": 7984, "author_profile": "https://Stackoverflow.com/users/7984", "pm_score": 1, "selected": false, "text": "<p>post-commit hook to send email notification that something changed in the repository to a list of emails. You need <a href=\"http://glob.com.au/sendmail/\" rel=\"nofollow noreferrer\">sendmail.exe</a> in the same folder than your hook file, along with sendmail.ini.</p>\n\n<p>You also need a file post-commit.tos.txt next to your post-commit.cmd to list the mail recipients. The file should contain:</p>\n\n<pre><code>[email protected],[email protected],[email protected]\n</code></pre>\n\n<p>Here is the hook code:</p>\n\n<pre><code>@ECHO OFF\nsetlocal\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Get subversion arguments\nset repos=%~1\nset rev=%2\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Set some variables\nset tos=%repos%\\hooks\\%~n0.tos.txt\nset reposname=%~nx1\nset svnlookparam=\"%repos%\" --revision %rev%\n\nif not exist \"%tos%\" goto :END\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Prepare sendmail email file\nset author=\nfor /f \"tokens=* usebackq\" %%g in (`svnlook author %svnlookparam%`) do (\n set author=%%g\n)\n\nfor /f \"tokens=* usebackq delims=\" %%g in (\"%tos%\") do (\n set EmailNotificationTo=%%g\n)\nset SendMailFile=%~n0_%reposname%_%rev%.sm\n\necho To: %EmailNotificationTo% &gt;&gt; \"%SendMailFile%\"\necho From: %reposname%[email protected] &gt;&gt; \"%SendMailFile%\"\necho Subject: [%reposname%] Revision %rev% - Subversion Commit Notification &gt;&gt; \"%SendMailFile%\"\n\necho --- log [%author%] --- &gt;&gt; \"%SendMailFile%\"\nsvnlook log %svnlookparam% &gt;&gt; \"%SendMailFile%\" 2&gt;&amp;1\necho --- changed --- &gt;&gt; \"%SendMailFile%\"\nsvnlook changed %svnlookparam% --copy-info &gt;&gt; \"%SendMailFile%\" 2&gt;&amp;1\n\necho .&gt;&gt; \"%SendMailFile%\"\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Send email\ntype \"%SendMailFile%\" | \"%~dp0sendmail.exe\" -t\n\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n:: Clean-up\nif exist \"%SendMailFile%\" del \"%SendMailFile%\"\n\n\n:END\nendlocal\n</code></pre>\n" }, { "answer_id": 7303568, "author": "JohnUlmer", "author_id": 928175, "author_profile": "https://Stackoverflow.com/users/928175", "pm_score": 0, "selected": false, "text": "<p>I forgot to enter a comment while committing. Didn't have time to figure out why my pre-revprop-change hook wasn't working. So the following svnadmin command worked for me to enter a commit message: \n <code>svnadmin setlog &lt;filesystem path to my repository&gt; --bypass-hooks -r 117 junk</code>,\nwhere \"junk\" is the file containing the text which I wanted to be the comment. <code>svn setlog help</code> has more usage info...</p>\n" }, { "answer_id": 9010360, "author": "nicobo", "author_id": 579827, "author_profile": "https://Stackoverflow.com/users/579827", "pm_score": 2, "selected": false, "text": "<p>For those who are looking for a pre-revprop-change.bat for a <strong>snvsync</strong> operation :</p>\n\n<p><a href=\"https://gist.github.com/1679659\" rel=\"nofollow\">https://gist.github.com/1679659</a></p>\n\n<pre><code>@ECHO OFF\n\nset user=%3\n\nif /I '%user%'=='syncuser' goto ERROR_REV\n\nexit 0\n\n:ERROR_REV echo \"Only the syncuser user may change revision properties\" &gt;&amp;2\nexit 1\n</code></pre>\n\n<p>It just comes from here : <a href=\"http://chestofbooks.com/computers/revision-control/subversion-svn/Repository-Replication-Reposadmin-Maint-Replication.html\" rel=\"nofollow\">http://chestofbooks.com/computers/revision-control/subversion-svn/Repository-Replication-Reposadmin-Maint-Replication.html</a> and has been adapted for Windows.</p>\n" } ]
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 all the HTTP links in a modest web page. When I say modest I definitely do not mean one page all encompassing HTML manuals like that of ELisp manual. Also performance is a touchy topic. My advice would be to measure your performance and then decide if you are going to extract all the links using one single regex or with multiple simpler regex expressions.</p>\n<p><a href=\"http://gbiv.com/protocols/uri/rfc/rfc3986.html\" rel=\"nofollow noreferrer\">http://gbiv.com/protocols/uri/rfc/rfc3986.html</a></p>\n" }, { "answer_id": 6179, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 0, "selected": false, "text": "<p>URL's? As in images/scripts/css/etc.?</p>\n\n<blockquote>\n <p><code>%href=\"(.[\"]*)\"%</code></p>\n</blockquote>\n" }, { "answer_id": 6181, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "<p>This will capture the URLs from all a tags as long as the author of the HTML used quotes:</p>\n\n<pre><code>&lt;a[^&gt;]+href=\"([^\"]+)\"[^&gt;]*&gt;\n</code></pre>\n\n<p>I made an example <a href=\"http://www.rubular.com/regexes/840\" rel=\"nofollow noreferrer\">here</a>.</p>\n" }, { "answer_id": 6182, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 1, "selected": false, "text": "<p>I don't have time to try and think of a regex that probably won't work, but I wanted to comment that you should most definitely break up your regex, at least if it gets to <a href=\"http://www.codinghorror.com/blog/archives/000214.html\" rel=\"nofollow noreferrer\">this level of ugliness</a>:</p>\n\n<pre><code>(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\0\n....*SNIP*....\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()&lt;&gt;@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()&lt;&gt;@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\&gt;(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)\n</code></pre>\n\n<p>(this supposedly matches email addresses)</p>\n\n<p>Edit: I can't even fit it on one post it's so nasty....</p>\n" }, { "answer_id": 6183, "author": "csmba", "author_id": 350, "author_profile": "https://Stackoverflow.com/users/350", "pm_score": 5, "selected": true, "text": "<pre><code>((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)\n</code></pre>\n\n<p>I took this from <a href=\"http://regexlib.com/Search.aspx?k=URL\" rel=\"nofollow noreferrer\">regexlib.com</a></p>\n\n<p>[editor's note: the {1} has no real function in this regex; <a href=\"https://stackoverflow.com/questions/13470/question-about-specific-regular-expression\">see this post</a>]</p>\n" }, { "answer_id": 6202, "author": "Grant", "author_id": 30, "author_profile": "https://Stackoverflow.com/users/30", "pm_score": 2, "selected": false, "text": "<p>All HTTP's and MAILTO's</p>\n\n<pre><code>([\"'])(mailto:|http:).*?\\1\n</code></pre>\n\n<p>All links, including relative ones, that are called by href or src.</p>\n\n<pre><code>#Matches things in single or double quotes, but not the quotes themselves\n(?&lt;=([\"']))((?&lt;=href=['\"])|(?&lt;=src=['\"])).*?(?=\\1)\n\n#Maches thing in either double or single quotes, including the quotes.\n([\"'])((?&lt;=href=\")|(?&lt;=src=\")).*?\\1\n</code></pre>\n\n<p>The second one will only get you links that use double quotes, however.</p>\n" }, { "answer_id": 13446, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 2, "selected": false, "text": "<p>With <a href=\"https://html-agility-pack.net/\" rel=\"nofollow noreferrer\">Html Agility Pack</a>, you can use:</p>\n\n<pre><code>HtmlDocument doc = new HtmlDocument();\ndoc.Load(\"file.htm\");\nforeach(HtmlNode link in doc.DocumentElement.SelectNodes(\"//a@href\")\n{\nResponse.Write(link[\"href\"].Value);\n}\ndoc.Save(\"file.htm\");\n</code></pre>\n" }, { "answer_id": 13488, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 3, "selected": false, "text": "<p>from the RegexBuddy library:</p>\n<h2>URL: Find in full text</h2>\n<p>The final character class makes sure that if an URL is part of some text, punctuation such as a comma or full stop after the URL is not interpreted as part of the URL.</p>\n<blockquote>\n<p><code>\\b(https?|ftp|file)://[-A-Z0-9+&amp;@#/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#/%=~_|]</code></p>\n</blockquote>\n" }, { "answer_id": 12285635, "author": "dvcama", "author_id": 1649650, "author_profile": "https://Stackoverflow.com/users/1649650", "pm_score": 0, "selected": false, "text": "<p>according to <a href=\"https://www.rfc-editor.org/rfc/rfc3986\" rel=\"nofollow noreferrer\">https://www.rfc-editor.org/rfc/rfc3986</a></p>\n<p>extracting url from ANY text (not only HTML)</p>\n<pre><code>(http\\\\://[:/?#\\\\[\\\\]@!%$&amp;'()*+,;=a-zA-Z0-9._\\\\-~]+)\n</code></pre>\n" } ]
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 were created on (the form's thread).</li>\n<li>Delegate invocations (ie, event hooks) are triggered on the same thread as the object that is firing the event. </li>\n</ol>\n\n<p>So, if you have a separate \"engine\" thread doing some work and have some UI watching for state changes which can be reflected in the UI (such as a progress bar or whatever), you have a problem. The engine fire's an object changed event which has been hooked by the Form. But the callback delegate that the Form registered with the engine gets called on the engine's thread… not on the Form's thread. And so you can't update any controls from that callback. Doh!</p>\n\n<p><strong>BeginInvoke</strong> comes to the rescue. Just use this simple coding model in all your callback methods and you can be sure that things are going to be okay:</p>\n\n<pre><code>private delegate void EventArgsDelegate(object sender, EventArgs ea);\n\nvoid SomethingHappened(object sender, EventArgs ea)\n{\n //\n // Make sure this callback is on the correct thread\n //\n if (this.InvokeRequired)\n {\n this.Invoke(new EventArgsDelegate(SomethingHappened), new object[] { sender, ea });\n return;\n }\n\n //\n // Do something with the event such as update a control\n //\n textBox1.Text = \"Something happened\";\n}\n</code></pre>\n\n<p>It's quite simple really.</p>\n\n<ol>\n<li>Use <strong>InvokeRequired</strong> to find out if this callback happened on the correct thread.</li>\n<li>If not, then reinvoke the callback on the correct thread with the same parameters. You can reinvoke a method by using the <strong>Invoke</strong> (blocking) or <strong>BeginInvoke</strong> (non-blocking) methods.</li>\n<li>The next time the function is called, <strong>InvokeRequired</strong> returns false because we are now on the correct thread and everybody is happy. </li>\n</ol>\n\n<p>This is a very compact way of addressing this problem and making your Forms safe from multi-threaded event callbacks.</p>\n" }, { "answer_id": 6197, "author": "Chris Farmer", "author_id": 404, "author_profile": "https://Stackoverflow.com/users/404", "pm_score": 0, "selected": false, "text": "<p>In many simple cases, you can use the MethodInvoker delegate and avoid the need to create your own delegate type.</p>\n" }, { "answer_id": 6211, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": 6, "selected": true, "text": "<p>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.</p>\n\n<pre><code>void SomethingHappened(object sender, EventArgs ea)\n{\n if (InvokeRequired)\n {\n Invoke(new Action&lt;object, EventArgs&gt;(SomethingHappened), sender, ea);\n return;\n }\n\n textBox1.Text = \"Something happened\";\n}\n</code></pre>\n" }, { "answer_id": 37136, "author": "Jason Diller", "author_id": 2187, "author_profile": "https://Stackoverflow.com/users/2187", "pm_score": 3, "selected": false, "text": "<p>I use anonymous methods a lot in this scenario: </p>\n\n<pre><code>void SomethingHappened(object sender, EventArgs ea)\n{\n MethodInvoker del = delegate{ textBox1.Text = \"Something happened\"; }; \n InvokeRequired ? Invoke( del ) : del(); \n}\n</code></pre>\n" }, { "answer_id": 341879, "author": "OwenP", "author_id": 2547, "author_profile": "https://Stackoverflow.com/users/2547", "pm_score": 2, "selected": false, "text": "<p>I'm a bit late to this topic, but you might want to take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/wewwczdw.aspx\" rel=\"nofollow noreferrer\">Event-Based Asynchronous Pattern</a>. When implemented properly, it guarantees that events are always raised from the UI thread.</p>\n\n<p>Here's a brief example that only allows one concurrent invocation; supporting multiple invocations/events requires a little bit more plumbing.</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Threading;\nusing System.Windows.Forms;\n\nnamespace WindowsFormsApplication1\n{\n public class MainForm : Form\n {\n private TypeWithAsync _type;\n\n [STAThread()]\n public static void Main()\n {\n Application.EnableVisualStyles();\n Application.Run(new MainForm());\n }\n\n public MainForm()\n {\n _type = new TypeWithAsync();\n _type.DoSomethingCompleted += DoSomethingCompleted;\n\n var panel = new FlowLayoutPanel() { Dock = DockStyle.Fill };\n\n var btn = new Button() { Text = \"Synchronous\" };\n btn.Click += SyncClick;\n panel.Controls.Add(btn);\n\n btn = new Button { Text = \"Asynchronous\" };\n btn.Click += AsyncClick;\n panel.Controls.Add(btn);\n\n Controls.Add(panel);\n }\n\n private void SyncClick(object sender, EventArgs e)\n {\n int value = _type.DoSomething();\n MessageBox.Show(string.Format(\"DoSomething() returned {0}.\", value));\n }\n\n private void AsyncClick(object sender, EventArgs e)\n {\n _type.DoSomethingAsync();\n }\n\n private void DoSomethingCompleted(object sender, DoSomethingCompletedEventArgs e)\n {\n MessageBox.Show(string.Format(\"DoSomethingAsync() returned {0}.\", e.Value));\n }\n }\n\n class TypeWithAsync\n {\n private AsyncOperation _operation;\n\n // synchronous version of method\n public int DoSomething()\n {\n Thread.Sleep(5000);\n return 27;\n }\n\n // async version of method\n public void DoSomethingAsync()\n {\n if (_operation != null)\n {\n throw new InvalidOperationException(\"An async operation is already running.\");\n }\n\n _operation = AsyncOperationManager.CreateOperation(null);\n ThreadPool.QueueUserWorkItem(DoSomethingAsyncCore);\n }\n\n // wrapper used by async method to call sync version of method, matches WaitCallback so it\n // can be queued by the thread pool\n private void DoSomethingAsyncCore(object state)\n {\n int returnValue = DoSomething();\n var e = new DoSomethingCompletedEventArgs(returnValue);\n _operation.PostOperationCompleted(RaiseDoSomethingCompleted, e);\n }\n\n // wrapper used so async method can raise the event; matches SendOrPostCallback\n private void RaiseDoSomethingCompleted(object args)\n {\n OnDoSomethingCompleted((DoSomethingCompletedEventArgs)args);\n }\n\n private void OnDoSomethingCompleted(DoSomethingCompletedEventArgs e)\n {\n var handler = DoSomethingCompleted;\n\n if (handler != null) { handler(this, e); }\n }\n\n public EventHandler&lt;DoSomethingCompletedEventArgs&gt; DoSomethingCompleted;\n }\n\n public class DoSomethingCompletedEventArgs : EventArgs\n {\n private int _value;\n\n public DoSomethingCompletedEventArgs(int value)\n : base()\n {\n _value = value;\n }\n\n public int Value\n {\n get { return _value; }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 10824842, "author": "Chase", "author_id": 1234970, "author_profile": "https://Stackoverflow.com/users/1234970", "pm_score": 2, "selected": false, "text": "<p>As the <code>lazy programmer</code>, I have a very lazy method of doing this.</p>\n\n<p>What I do is simply this.</p>\n\n<pre><code>private void DoInvoke(MethodInvoker del) {\n if (InvokeRequired) {\n Invoke(del);\n } else {\n del();\n }\n}\n//example of how to call it\nprivate void tUpdateLabel(ToolStripStatusLabel lbl, String val) {\n DoInvoke(delegate { lbl.Text = val; });\n}\n</code></pre>\n\n<p>You could inline the DoInvoke inside your function or hide it within separate function to do the dirty work for you.</p>\n\n<p>Just keep in mind you can pass functions directly into the DoInvoke method.</p>\n\n<pre><code>private void directPass() {\n DoInvoke(this.directInvoke);\n}\nprivate void directInvoke() {\n textLabel.Text = \"Directly passed.\";\n}\n</code></pre>\n" } ]
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\n</code></pre>\n" }, { "answer_id": 46319782, "author": "joeyk16", "author_id": 4574914, "author_profile": "https://Stackoverflow.com/users/4574914", "pm_score": 0, "selected": false, "text": "<p>This worked.</p>\n\n<p>Where ever the link is to the page do something like this</p>\n\n<pre><code> %div{\"data-turbolinks\" =&gt; \"false\"}\n = link_to 'Send payment', new_payments_manager_path(sender_id: current_user.id, receiver_id: @collaboration.with(current_user).id, collaboration_id: params[:id]), class: 'button'\n</code></pre>\n" }, { "answer_id": 59333930, "author": "Cristian Rennella", "author_id": 7021493, "author_profile": "https://Stackoverflow.com/users/7021493", "pm_score": 1, "selected": false, "text": "<p>You can do multiple conditional class selectors with array syntax:</p>\n\n<blockquote>\n <p>%div{ class: [ (\"active\" if @thing.active?), (\"highlight\" if @thing.important?) ] }</p>\n</blockquote>\n" } ]
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_INCREMENT PRIMARY KEY COMMENT 'Unique ID for each row', \n shipping_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the shipping vendor (vendors_type must be 3)', \n start_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to VENDOR.no for the vendor being shipped from', \n end_vendor_no INT(6) NOT NULL COMMENT 'Foreign key to the VENDOR.no for the vendor being shipped to', \n shipment_duration INT(1) DEFAULT 1 COMMENT 'Duration in whole days shipment will take', \n price FLOAT(5,5) NOT NULL COMMENT 'Price in US dollars per shipment lbs (down to 5 decimal places)', \n is_flat_rate TINYINT(1) DEFAULT 0 COMMENT '1 if is flat rate regardless of weight, 0 if price is by lbs', \n INDEX (shipping_vendor_no), \n INDEX (start_vendor_no), \n INDEX (end_vendor_no), \n FOREIGN KEY (shipping_vendor_no) REFERENCES VENDOR (no), \n FOREIGN KEY (start_vendor_no) REFERENCES VENDOR (no), \n FOREIGN KEY (end_vendor_no) REFERENCES VENDOR (no) \n) TYPE = INNODB;\n</code></pre>\n\n<p>The VENDOR primary key must be INT(6), and both tables must be of type InnoDB.</p>\n" }, { "answer_id": 6350, "author": "Mario Marinato", "author_id": 431, "author_profile": "https://Stackoverflow.com/users/431", "pm_score": 0, "selected": false, "text": "<p>I ran the code here, and the error message showed (and it is right!) that you are setting <em>id</em> field twice as primary key.</p>\n" }, { "answer_id": 6364, "author": "cmcculloh", "author_id": 58, "author_profile": "https://Stackoverflow.com/users/58", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Can you provide the definition of the\n VENDOR table</p>\n</blockquote>\n\n<p>I figured it out. The VENDOR table was MyISAM... (edited your answer to tell me to make them both INNODB ;) )</p>\n\n<p>(any reason <em>not</em> to just switch the VENDOR type over to INNODB?)</p>\n" } ]
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 in an XML file. The openxml \"function\" takes a string and makes it like xml and then if you create a temp table with the data, it is queryable.</p>\n\n<pre><code>DECLARE @idoc int\nDECLARE @doc varchar(1000)\nSET @doc ='\n&lt;ROOT&gt;\n&lt;Customer CustomerID=\"VINET\" ContactName=\"Paul Henriot\"&gt;\n &lt;Order CustomerID=\"VINET\" EmployeeID=\"5\" OrderDate=\"1996-07-04T00:00:00\"&gt;\n &lt;OrderDetail OrderID=\"10248\" ProductID=\"11\" Quantity=\"12\"/&gt;\n &lt;OrderDetail OrderID=\"10248\" ProductID=\"42\" Quantity=\"10\"/&gt;\n &lt;/Order&gt;\n&lt;/Customer&gt;\n&lt;Customer CustomerID=\"LILAS\" ContactName=\"Carlos Gonzlez\"&gt;\n &lt;Order CustomerID=\"LILAS\" EmployeeID=\"3\" OrderDate=\"1996-08-16T00:00:00\"&gt;\n &lt;OrderDetail OrderID=\"10283\" ProductID=\"72\" Quantity=\"3\"/&gt;\n &lt;/Order&gt;\n&lt;/Customer&gt;\n&lt;/ROOT&gt;'\n--Create an internal representation of the XML document.\nEXEC sp_xml_preparedocument @idoc OUTPUT, @doc\n-- Execute a SELECT statement that uses the OPENXML rowset provider.\nSELECT *\nFROM OPENXML (@idoc, '/ROOT/Customer',1)\n WITH (CustomerID varchar(10),\n ContactName varchar(20))\n</code></pre>\n" }, { "answer_id": 6384, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 1, "selected": false, "text": "<p>Pass the comma separated list into a function that returns a table value. There is a MS SQL example somewhere on StackOverflow, damned if I can see it at the moment.</p>\n\n<blockquote>\n<pre><code>CREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\nSELECT * FROM mytbl WHERE name IN (fn_GetKeyList(@keyList))\n</code></pre>\n</blockquote>\n\n<p>Call with -</p>\n\n<blockquote>\n<pre><code>exec getSomething 'John,Tom,Foo,Bar'\n</code></pre>\n</blockquote>\n\n<p>I'm guessing Sybase should be able to do something similar?</p>\n" }, { "answer_id": 6483, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>Regarding Kevin's idea of passing the parameter to a function that splits the text into a table, here's my implementation of that function from a few years back. Works a treat.</p>\n\n<p><a href=\"http://www.madprops.org/blog/splitting-text-into-words-in-sql-revisited/\" rel=\"nofollow noreferrer\">Splitting Text into Words in SQL</a></p>\n" }, { "answer_id": 10838, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>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.</p>\n" }, { "answer_id": 48422, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This is a quick and dirty method that may be useful:</p>\n\n<pre><code>select * \nfrom mytbl \nwhere \",\" + ltrim(rtrim(@keylist)) + \",\" like \"%,\" + ltrim(rtrim(name)) + \",%\"\n</code></pre>\n" }, { "answer_id": 123593, "author": "Lurker Indeed", "author_id": 16951, "author_profile": "https://Stackoverflow.com/users/16951", "pm_score": 0, "selected": false, "text": "<p>Not sure if it's in ASE, but in SQL Anywhere, the <em>sa_split_list</em> function returns a table from a CSV. It has optional arguments to pass a different delimiter (default is a comma) and a maxlength for each returned value.</p>\n\n<p><a href=\"http://www.ianywhere.com/developer/product_manuals/sqlanywhere/1000/en/html/dbrfen10/rf-sa-set-http-option.html\" rel=\"nofollow noreferrer\">sa_split_list function</a></p>\n" }, { "answer_id": 123686, "author": "AdamH", "author_id": 21081, "author_profile": "https://Stackoverflow.com/users/21081", "pm_score": 0, "selected": false, "text": "<p>The problem with the calls like this: exec getSomething '\"John\",\"Tom\"' is that it's treating '\"John\",\"Tom\"' as a single string, it will only match an entry in the table that is '\"John\",\"Tom\"'.</p>\n\n<p>If you didn't want to use a temp table as in Paul's answer, then you could use dynamic sql. (Assumes v12+)</p>\n\n<pre><code>CREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\ndeclare @sql varchar(4096)\nselect @sql = \"SELECT * FROM mytbl WHERE name IN (\" + @keyList +\")\"\nexec(@sql)\n</code></pre>\n\n<p>You will need to ensure the items in @keylist have quotes around them, even if they are single values.</p>\n" }, { "answer_id": 251136, "author": "Abel Gaxiola", "author_id": 31191, "author_profile": "https://Stackoverflow.com/users/31191", "pm_score": 0, "selected": false, "text": "<p>This works in SQL. Declare in your <code>GetSomething</code> procedure a variable of type XML as such:</p>\n\n<pre><code>DECLARE @NameArray XML = NULL\n</code></pre>\n\n<p>The body of the stored procedure implements the following:</p>\n\n<pre><code>SELECT * FROM MyTbl WHERE name IN (SELECT ParamValues.ID.value('.','VARCHAR(10)')\nFROM @NameArray.nodes('id') AS ParamValues(ID))\n</code></pre>\n\n<p>From within the SQL code that calls the SP to declare and initialize the XML variable before calling the stored procedure:</p>\n\n<pre><code>DECLARE @NameArray XML\n\nSET @NameArray = '&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_1&lt;&lt;id&gt;/id&gt;&lt;/id&gt;&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_2&lt;&lt;id&gt;/id&gt;&lt;/id&gt;&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_3&lt;&lt;id&gt;/id&gt;&lt;/id&gt;&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_4&lt;&lt;id&gt;/id&gt;&lt;/id&gt;'\n</code></pre>\n\n<p>Using your example the call to the stored procedure would be:</p>\n\n<pre><code>EXEC GetSomething @NameArray\n</code></pre>\n\n<p>I have used this method before and it works fine. If you want a quick test, copy and paste the following code to a new query and execute:</p>\n\n<pre><code>DECLARE @IdArray XML\n\nSET @IdArray = '&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_1&lt;&lt;id&gt;/id&gt;&lt;/id&gt;&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_2&lt;&lt;id&gt;/id&gt;&lt;/id&gt;&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_3&lt;&lt;id&gt;/id&gt;&lt;/id&gt;&lt;id&gt;&lt;&lt;/id&gt;id&gt;Name_4&lt;&lt;id&gt;/id&gt;&lt;/id&gt;'\n\nSELECT ParamValues.ID.value('.','VARCHAR(10)')\nFROM @IdArray.nodes('id') AS ParamValues(ID)\n</code></pre>\n" }, { "answer_id": 7892156, "author": "Ben", "author_id": 982820, "author_profile": "https://Stackoverflow.com/users/982820", "pm_score": 2, "selected": false, "text": "<p>This is a little late, but I had this exact issue a while ago and I found a solution.</p>\n\n<p>The trick is double quoting and then wrapping the whole string in quotes.</p>\n\n<pre><code>exec getSomething \"\"\"John\"\",\"\"Tom\"\",\"\"Bob\"\",\"\"Harry\"\"\"\n</code></pre>\n\n<p>Modify your proc to match the table entry to the string. </p>\n\n<pre><code>CREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\nSELECT * FROM mytbl WHERE @keyList LIKE '%'+name+'%' \n</code></pre>\n\n<p>I've had this in production since ASE 12.5; we're now on 15.0.3.</p>\n" }, { "answer_id": 37604460, "author": "DeFlanko", "author_id": 4006015, "author_profile": "https://Stackoverflow.com/users/4006015", "pm_score": 0, "selected": false, "text": "<p>To touch on what @Abel provided, what helped me out was:</p>\n\n<p>My purpose was to take what ever the end user inputted from SSRS and use that in my where clause as an In (SELECT)\nObviously @ICD_VALUE_RPT would be commented out in my Dataset query. </p>\n\n<pre><code>DECLARE @ICD_VALUE_RPT VARCHAR(MAX) SET @ICD_VALUE_RPT = 'Value1, Value2'\nDECLARE @ICD_VALUE_ARRAY XML SET @ICD_VALUE_ARRAY = CONCAT('&lt;id&gt;', REPLACE(REPLACE(@ICD_VALUE_RPT, ',', '&lt;/id&gt;,&lt;id&gt;'),' ',''), '&lt;/id&gt;')\n</code></pre>\n\n<p>then in my <code>WHERE</code> i added:</p>\n\n<pre><code>(PATS_WITH_PL_DIAGS.ICD10_CODE IN (SELECT ParamValues.ID.value('.','VARCHAR(MAX)') FROM @ICD_VALUE_ARRAY.nodes('id') AS ParamValues(ID))\nOR PATS_WITH_PL_DIAGS.ICD9_CODE IN (SELECT ParamValues.ID.value('.','VARCHAR(MAX)') FROM @ICD_VALUE_ARRAY.nodes('id') AS ParamValues(ID))\n)\n</code></pre>\n" }, { "answer_id": 46092262, "author": "user3732708", "author_id": 3732708, "author_profile": "https://Stackoverflow.com/users/3732708", "pm_score": 0, "selected": false, "text": "<p>Try this way. Its works for me.</p>\n\n<pre><code>@itemIds varchar(max)\n\nCREATE PROCEDURE getSomething @keyList varchar(4096)\nAS\nSELECT * FROM mytbl WHERE name IN (SELECT Value FROM [Global_Split] (@itemIds,','))\n</code></pre>\n" } ]
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('blah');\n}\nnew Bla();\n</code></pre>\n\n<p>this is actually also executing code. The same goes for the anonymous constructor...</p>\n\n<p>But that was not the question ;-)</p>\n" }, { "answer_id": 6424, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 5, "selected": true, "text": "<p>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.</p>\n\n<p>Basically behaviour of</p>\n\n<pre><code>new expression\n</code></pre>\n\n<p>Is effectively equivalent to</p>\n\n<pre><code>var tempObject = {};\nvar result = expression.call(tempObject);\nif (result is not an object)\n result = tempObject;\n</code></pre>\n\n<p>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.</p>\n\n<p>Broadly speaking the \"new function() { .. }\" method will be slower due to the need to create the this object for the constructor.</p>\n\n<p>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).</p>\n\n<p>Edit: one thing i realised that i missed from this is that the <code>tempObject</code> will get <code>expression</code>s prototype, eg. (before the <code>expression.call</code>) <code>tempObject.__proto__ = expression.prototype</code></p>\n" }, { "answer_id": 6436, "author": "Lance Fisher", "author_id": 571, "author_profile": "https://Stackoverflow.com/users/571", "pm_score": 0, "selected": false, "text": "<p>Well, I made a page like this:</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n&lt;script type=\"text/javascript\"&gt;\nvar a = new function() { \n alert(\"method 1\");\n\n return \"test\";\n};\n\nvar b = (function() {\n alert(\"method 2\");\n\n return \"test\";\n})();\n\nalert(a); //a is a function\nalert(b); //b is a string containing \"test\"\n\n&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Surprisingly enough (to me anyway) it alerted both \"method 1\" and method 2\". I didn't expect \"method 1\" to be alerted. The difference was what the values of a and b were. a was the function itself, while b was the string that the function returned.</p>\n" }, { "answer_id": 6489, "author": "Adhip Gupta", "author_id": 384, "author_profile": "https://Stackoverflow.com/users/384", "pm_score": -1, "selected": false, "text": "<p>Yes, there are differences between the two.</p>\n\n<p>Both are anonymous functions and execute in the exact same way. But, the difference between the two is that in the second case scope of the variables is restricted to the anonymous function itself. There is no chance of accidentally adding variables to the global scope.</p>\n\n<p>This implies that by using the second method, you are not cluttering up the global variables scope which is good as these global variable values can interfere with some other global variables that you may use in some other library or are being used in a third party library.</p>\n\n<p>Example:</p>\n\n<pre><code>&lt;html&gt;\n&lt;body&gt;\n&lt;script type=\"text/javascript\"&gt;\n\nnew function() { \na = \"Hello\";\nalert(a + \" Inside Function\");\n};\n\nalert(a + \" Outside Function\");\n\n(function() { \nvar b = \"World\";\nalert(b + \" Inside Function\");\n})();\n\nalert(b + \" Outside Function\");\n&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>In the above code the output is something like:</p>\n\n<blockquote>\n <p>Hello Inside Function<br>\n Hello Outside Function<br>\n World Inside Function</p>\n</blockquote>\n\n<p>... then, you get an error as 'b' is not defined outside the function!</p>\n\n<p>Thus, I believe that the second method is better... safer!</p>\n" }, { "answer_id": 6542, "author": "Kieron", "author_id": 588, "author_profile": "https://Stackoverflow.com/users/588", "pm_score": 2, "selected": false, "text": "<p>They both create a closure by executing the code block. As a matter of style I much prefer the second for a couple of reasons:</p>\n\n<p>It's not immediately obvious by glancing at the first that the code will actually be executed; the line <em>looks like</em> it is <em>creating</em> a new function, rather than executing it as a constructor, but that's not what's actually happening. Avoid code that doesn't do what it looks like it's doing!</p>\n\n<p>Also the <code>(function(){</code> ... <code>})();</code> make nice bookend tokens so that you can immediately see that you're entering and leaving a closure scope. This is good because it alerts the programmer reading it to the scope change, and is especially useful if you're doing some postprocessing of the file, eg for minification.</p>\n" } ]
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?bug_id=6456628\" rel=\"noreferrer\">Bug ID 6456628</a>.</p>\n\n<p>The easiest workaround is to make /etc/localtime a symlink to the correct zoneinfo file. For Pacific time, the following commands should work:</p>\n\n<pre><code># sudo cp /etc/localtime /etc/localtime.dist\n# sudo ln -fs /usr/share/zoneinfo/America/Los_Angeles /etc/localtime\n</code></pre>\n\n<p>I haven't had any problems with the symlink approach.</p>\n\n<p>Edit: Added \"sudo\" to the commands.</p>\n" }, { "answer_id": 6502, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 0, "selected": false, "text": "<p>It may help to double-check the timezone rules your OS is using.</p>\n\n<pre><code>/usr/bin/zdump -v /etc/localtime | less\n</code></pre>\n\n<p>This file should contain your daylight savings rules, like this one for the year 2080:</p>\n\n<pre><code>/etc/localtime Sun Mar 31 01:00:00 2080 UTC = Sun Mar 31 02:00:00 2080 BST isdst=1 gmtoff=3600\n</code></pre>\n\n<p>You can compare this with the timezone rules you think you should be using. They can be found in <strong>/usr/share/zoneinfo/</strong>.</p>\n" }, { "answer_id": 182437, "author": "abarax", "author_id": 24390, "author_profile": "https://Stackoverflow.com/users/24390", "pm_score": 2, "selected": false, "text": "<p>I had a similar issue, possibly the same one. However my tomcat server runs on a windows box so the symlink solution will not work. </p>\n\n<p>I set <code>-Duser.timezone=Australia/Sydney</code> in the <code>JAVA_OPTS</code> however tomcat would not recognize that DST was in effect. As a workaround I changed <code>Australia/Sydney</code> (GMT+10:00) to <code>Pacific/Numea</code> (GMT+11:00) so that times would correctly display however I would love to know the actual solution or bug, if any.</p>\n" }, { "answer_id": 3912695, "author": "Liu Zehua", "author_id": 473064, "author_profile": "https://Stackoverflow.com/users/473064", "pm_score": 5, "selected": false, "text": "<p>On Ubuntu, it's not enough to just change the /etc/localtime file. It seems to read /etc/timezone file, too. It's better follow the <a href=\"https://help.ubuntu.com/community/UbuntuTime\" rel=\"noreferrer\">instruction</a> to set the time zone properly. In particular, do the following:</p>\n\n<pre><code>$ sudo cp /etc/timezone /etc/timezone.dist\n$ echo \"Australia/Adelaide\" | sudo tee /etc/timezone\nAustralia/Adelaide\n$ sudo dpkg-reconfigure --frontend noninteractive tzdata\n\nCurrent default time zone: 'Australia/Adelaide'\nLocal time is now: Sat May 8 21:19:24 CST 2010.\nUniversal Time is now: Sat May 8 11:49:24 UTC 2010.\n</code></pre>\n\n<p>On my Ubuntu, if /etc/localtime and /etc/timezone are inconsistent, Java seems to read default time zone from /etc/timezone .</p>\n" }, { "answer_id": 66403246, "author": "Sleem", "author_id": 238813, "author_profile": "https://Stackoverflow.com/users/238813", "pm_score": 0, "selected": false, "text": "<p>Adding a short answer that worked for me, you can use <code>timedatectl</code> to set the timezone. Then restart the JVM afterwards.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>sudo timedatectl set-timezone UTC\n</code></pre>\n" } ]
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></pre>\n\n<p><strong>Edit:</strong> since PeopleListView will be declared protected by default, you will either need to change this to public, or create a public property wrapper so that you can access it from your page.</p>\n" }, { "answer_id": 6412, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 5, "selected": true, "text": "<p>I believe you <em>could</em> 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.</p>\n\n<p>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.</p>\n" }, { "answer_id": 6413, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 2, "selected": false, "text": "<p>Assuming the control is called \"PeopleListView\" on the master page</p>\n\n<pre><code>ListView peopleListView = (ListView)this.Master.FindControl(\"PeopleListView\");\npeopleListView.DataSource = [whatever];\npeopleListView.DataBind();\n</code></pre>\n\n<p>But @<a href=\"https://stackoverflow.com/users/521/palmsey\">palmsey</a> is more correct, especially if your page could have the possibility of more than one master page. Decouple them and use an event.</p>\n" }, { "answer_id": 23871, "author": "Adam Carr", "author_id": 1405, "author_profile": "https://Stackoverflow.com/users/1405", "pm_score": 1, "selected": false, "text": "<p>One think to remember is the following ASP.NET directive.</p>\n\n<pre><code>&lt;%@ MasterType attribute=\"value\" [attribute=\"value\"...] %&gt;\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms228274.aspx\" rel=\"nofollow noreferrer\">MSDN Reference</a></p>\n\n<p>It will help you when referencing this.Master by creating a strongly typed reference to the master page. You can then reference your ListView without needing to CAST.</p>\n" }, { "answer_id": 5591665, "author": "icaptan", "author_id": 696296, "author_profile": "https://Stackoverflow.com/users/696296", "pm_score": 0, "selected": false, "text": "<p>you can access with the code this.Master.FindControl(ControlID) which control you wish. It returns the reference of the control, so that the changes are effective. about firing an event could not be possible each situation. </p>\n" }, { "answer_id": 10945605, "author": "BrainCoder", "author_id": 1245631, "author_profile": "https://Stackoverflow.com/users/1245631", "pm_score": 2, "selected": false, "text": "<p>Option 1 :you can create public property of your master page control</p>\n\n<pre><code>public TextBox PropMasterTextBox1\n{\n get { return txtMasterBox1; }\n set { txtMasterBox1 = value; }\n}\n</code></pre>\n\n<p>access it on content page like</p>\n\n<pre><code>Master.PropMasterTextBox1.Text=\"SomeString\";\n</code></pre>\n\n<p>Option 2:\non Master page:</p>\n\n<pre><code>public string SetMasterTextBox1Text\n{ \n get { return txtMasterBox1.Text; }\n set { txtMasterBox1.Text = value; }\n}\n</code></pre>\n\n<p>on Content Page:</p>\n\n<pre><code>Master.SetMasterTextBox1Text=\"someText\";\n</code></pre>\n\n<p>option 3 : \nyou can create some public method that works for you</p>\n\n<hr>\n\n<p>these approach is not so useful but it helps if you just want to use some limited and predefined control</p>\n" } ]
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>DataRow</code>.</p>\n" }, { "answer_id": 6417, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 12, "selected": true, "text": "<p><code>break</code> will exit the loop completely, <code>continue</code> will just <strong>skip</strong> the current iteration.</p>\n\n<p>For example:</p>\n\n<pre><code>for (int i = 0; i &lt; 10; i++) {\n if (i == 0) {\n break;\n }\n\n DoSomeThingWith(i);\n}\n</code></pre>\n\n<p>The break will cause the loop to exit on the first iteration - <code>DoSomeThingWith</code> will never be executed. This here:</p>\n\n<pre><code>for (int i = 0; i &lt; 10; i++) {\n if(i == 0) {\n continue;\n }\n\n DoSomeThingWith(i);\n}\n</code></pre>\n\n<p>Will not execute <code>DoSomeThingWith</code> for <code>i = 0</code>, but the loop will <strong>continue</strong> and <code>DoSomeThingWith</code> will be executed for <code>i = 1</code> to <code>i = 9</code>.</p>\n" }, { "answer_id": 6442, "author": "JeremiahClark", "author_id": 581, "author_profile": "https://Stackoverflow.com/users/581", "pm_score": 9, "selected": false, "text": "<p>A really easy way to understand this is to place the word \"loop\" after each of the keywords. The terms now make sense if they are just read like everyday phrases.</p>\n\n<p><strong><code>break</code></strong> loop - looping is broken and stops.</p>\n\n<p><strong><code>continue</code></strong> loop - loop continues to execute with the next iteration.</p>\n" }, { "answer_id": 6446, "author": "yukondude", "author_id": 726, "author_profile": "https://Stackoverflow.com/users/726", "pm_score": 4, "selected": false, "text": "<p>There are more than a few people who don't like <code>break</code> and <code>continue</code>. The latest complaint I saw about them was in <em>JavaScript: The Good Parts</em> by Douglas Crockford. But I find that sometimes using one of them really simplifies things, especially if your language doesn't include a <code>do-while</code> or <code>do-until</code> style of loop.</p>\n\n<p>I tend to use <code>break</code> in loops that are searching a list for something. Once found, there's no point in continuing, so you might as well quit.</p>\n\n<p>I use <code>continue</code> when doing something with most elements of a list, but still want to skip over a few.</p>\n\n<p>The <code>break</code> statement also comes in handy when polling for a valid response from somebody or something. Instead of:</p>\n\n<pre><code>Ask a question\nWhile the answer is invalid:\n Ask the question\n</code></pre>\n\n<p>You could eliminate some duplication and use:</p>\n\n<pre><code>While True:\n Ask a question\n If the answer is valid:\n break\n</code></pre>\n\n<p>The <code>do-until</code> loop that I mentioned before is the more elegant solution for that particular problem:</p>\n\n<pre><code>Do:\n Ask a question\n Until the answer is valid\n</code></pre>\n\n<p>No duplication, and no <code>break</code> needed either.</p>\n" }, { "answer_id": 6555, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 3, "selected": false, "text": "<p>Ruby unfortunately is a bit different. \nPS: My memory is a bit hazy on this so apologies if I'm wrong</p>\n\n<p>instead of break/continue, it has break/next, which behave the same in terms of loops</p>\n\n<p>Loops (like everything else) are expressions, and \"return\" the last thing that they did. Most of the time, getting the return value from a loop is pointless, so everyone just does this</p>\n\n<pre><code>a = 5\nwhile a &lt; 10\n a + 1\nend\n</code></pre>\n\n<p>You can however do this</p>\n\n<pre><code>a = 5\nb = while a &lt; 10\n a + 1\nend # b is now 10\n</code></pre>\n\n<p>HOWEVER, a lot of ruby code 'emulates' a loop by using a block.\nThe canonical example is</p>\n\n<pre><code>10.times do |x|\n puts x\nend\n</code></pre>\n\n<p>As it is much more common for people to want to do things with the result of a block, this is where it gets messy.\nbreak/next mean different things in the context of a block.</p>\n\n<p>break will jump out of the code that called the block</p>\n\n<p>next will skip the rest of the code in the block, and 'return' what you specify to the caller of the block. This doesn't make any sense without examples.</p>\n\n<pre><code>def timesten\n 10.times{ |t| puts yield t }\nend\n\n\ntimesten do |x|\n x * 2\nend\n# will print\n2\n4\n6\n8 ... and so on\n\n\ntimesten do |x|\n break\n x * 2\nend\n# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped\n\ntimesten do |x|\n break 5\n x * 2\nend\n# This is the same as above. it's \"returning\" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5\n\ntimesten do |x|\n next 5\n x * 2\nend \n# this would print\n5\n5\n5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.\n</code></pre>\n\n<p>So yeah. Ruby is awesome, but it has some awful corner-cases. This is the second worst one I've seen in my years of using it :-)</p>\n" }, { "answer_id": 16866, "author": "SemiColon", "author_id": 1994, "author_profile": "https://Stackoverflow.com/users/1994", "pm_score": 7, "selected": false, "text": "<p><strong>break</strong> causes the program counter to jump out of the scope of the innermost loop</p>\n\n<pre><code>for(i = 0; i &lt; 10; i++)\n{\n if(i == 2)\n break;\n}\n</code></pre>\n\n<p>Works like this</p>\n\n<pre><code>for(i = 0; i &lt; 10; i++)\n{\n if(i == 2)\n goto BREAK;\n}\nBREAK:;\n</code></pre>\n\n<p><strong>continue</strong> jumps to the end of the loop. In a for loop, continue jumps to the increment expression.</p>\n\n<pre><code>for(i = 0; i &lt; 10; i++)\n{\n if(i == 2)\n continue;\n\n printf(\"%d\", i);\n}\n</code></pre>\n\n<p>Works like this</p>\n\n<pre><code>for(i = 0; i &lt; 10; i++)\n{\n if(i == 2)\n goto CONTINUE;\n\n printf(\"%d\", i);\n\n CONTINUE:;\n}\n</code></pre>\n" }, { "answer_id": 224965, "author": "Maltrap", "author_id": 10644, "author_profile": "https://Stackoverflow.com/users/10644", "pm_score": 3, "selected": false, "text": "<p>Simple answer: </p>\n\n<p><strong>Break</strong> exits the loop immediately.<br>\n<strong>Continue</strong> starts processing the next item. (If there are any, by jumping to the evaluating line of the for/while)</p>\n" }, { "answer_id": 674617, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Please let me state the obvious: note that adding neither break nor continue, will resume your program; i.e. I trapped for a certain error, then after logging it, I wanted to resume processing, and there were more code tasks in between the next row, so I just let it fall through.</p>\n" }, { "answer_id": 4497072, "author": "Pritom Nandy", "author_id": 548420, "author_profile": "https://Stackoverflow.com/users/548420", "pm_score": 4, "selected": false, "text": "<p>All have given a very good explanation. I am still posting my answer just to give an example if that can help.</p>\n\n<pre><code>// break statement\nfor (int i = 0; i &lt; 5; i++) {\n if (i == 3) {\n break; // It will force to come out from the loop\n }\n\n lblDisplay.Text = lblDisplay.Text + i + \"[Printed] \";\n}\n</code></pre>\n\n<p>Here is the output:</p>\n\n<blockquote>\n <p>0[Printed] 1[Printed] 2[Printed] </p>\n</blockquote>\n\n<p>So 3[Printed] &amp; 4[Printed] will not be displayed as there is break when i == 3</p>\n\n<pre><code>//continue statement\nfor (int i = 0; i &lt; 5; i++) {\n if (i == 3) {\n continue; // It will take the control to start point of loop\n }\n\n lblDisplay.Text = lblDisplay.Text + i + \"[Printed] \";\n}\n</code></pre>\n\n<p>Here is the output:</p>\n\n<blockquote>\n <p>0[Printed] 1[Printed] 2[Printed] 4[Printed] </p>\n</blockquote>\n\n<p>So 3[Printed] will not be displayed as there is continue when i == 3</p>\n" }, { "answer_id": 15310861, "author": "Gopesh Sharma", "author_id": 1266135, "author_profile": "https://Stackoverflow.com/users/1266135", "pm_score": 2, "selected": false, "text": "<p>To break completely out of a foreach loop, <strong>break</strong> is used;</p>\n\n<p>To go to the next iteration in the loop, <strong>continue</strong> is used;</p>\n\n<p><strong>Break</strong> is useful if you’re looping through a collection of Objects (like Rows in a Datatable) and you are searching for a particular match, when you find that match, there’s no need to continue through the remaining rows, so you want to break out.</p>\n\n<p><strong>Continue</strong> is useful when you have accomplished what you need to in side a loop iteration. You’ll normally have <strong>continue</strong> after an <strong>if</strong>.</p>\n" }, { "answer_id": 15675992, "author": "Sona Rijesh", "author_id": 1522741, "author_profile": "https://Stackoverflow.com/users/1522741", "pm_score": 3, "selected": false, "text": "<p><strong>Break</strong></p>\n\n<p>Break forces a loop to exit immediately. </p>\n\n<p><strong>Continue</strong></p>\n\n<p>This does the opposite of break. Instead of terminating the loop, it immediately loops again, skipping the rest of the code.</p>\n" }, { "answer_id": 19300205, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "<p>By example</p>\n\n<pre><code>foreach(var i in Enumerable.Range(1,3))\n{\n Console.WriteLine(i);\n}\n</code></pre>\n\n<p>Prints 1, 2, 3 (on separate lines).</p>\n\n<p>Add a break condition at i = 2</p>\n\n<pre><code>foreach(var i in Enumerable.Range(1,3))\n{\n if (i == 2)\n break;\n\n Console.WriteLine(i);\n}\n</code></pre>\n\n<p>Now the loop prints 1 and stops.</p>\n\n<p>Replace the break with a continue.</p>\n\n<pre><code>foreach(var i in Enumerable.Range(1,3))\n{\n if (i == 2)\n continue;\n\n Console.WriteLine(i);\n}\n</code></pre>\n\n<p>Now to loop prints 1 and 3 (skipping 2).</p>\n\n<p>Thus, <code>break</code> stops the loop, whereas <code>continue</code> skips to the next iteration.</p>\n" }, { "answer_id": 35169830, "author": "Umair Khalid", "author_id": 4732930, "author_profile": "https://Stackoverflow.com/users/4732930", "pm_score": 2, "selected": false, "text": "<p>if you don't want to use <strong>break</strong> you just increase value of I in such a way that it make iteration condition false and loop will not execute on next iteration.</p>\n\n<pre><code>for(int i = 0; i &lt; list.Count; i++){\n if(i == 5)\n i = list.Count; //it will make \"i&lt;list.Count\" false and loop will exit\n}\n</code></pre>\n" }, { "answer_id": 47664169, "author": "BenKoshy", "author_id": 4880924, "author_profile": "https://Stackoverflow.com/users/4880924", "pm_score": 6, "selected": false, "text": "<h2>When to use break vs continue?</h2>\n<ol>\n<li><strong>Break</strong> - We're leaving the loop forever. Good bye.</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/s97tT.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s97tT.png\" alt=\"Break\" /></a></p>\n<ol start=\"2\">\n<li><strong>Continue</strong> - means that you're gonna give today a rest and sort it all out tomorrow (i.e. skip the current iteration)!</li>\n</ol>\n<p><a href=\"https://i.stack.imgur.com/MilvY.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MilvY.jpg\" alt=\"Continue\" /></a></p>\n<p>(Corny stories ¯\\<em>(ツ)</em>/¯ but hopefully helps you remember)</p>\n" }, { "answer_id": 48887451, "author": "dba", "author_id": 2408978, "author_profile": "https://Stackoverflow.com/users/2408978", "pm_score": 0, "selected": false, "text": "<p>As for other languages:</p>\n<pre class=\"lang-vb prettyprint-override\"><code> 'VB\n For i=0 To 10\n If i=5 then Exit For '= break in C#;\n 'Do Something for i&lt;5\n next\n \n For i=0 To 10\n If i=5 then Continue For '= continue in C#\n 'Do Something for i&lt;&gt;5...\n Next\n</code></pre>\n" }, { "answer_id": 69146895, "author": "Mostafa Ghorbani", "author_id": 12094348, "author_profile": "https://Stackoverflow.com/users/12094348", "pm_score": 0, "selected": false, "text": "<p>Since the example written here are pretty simple for understanding the concept I think it's also a good idea to look at the more <strong>practical version</strong> of the <strong>continue statement</strong> being used.\nFor example:</p>\n<p>we ask the user to enter 5 unique numbers if the number is already entered we give them an error and we continue our program.</p>\n<pre><code>static void Main(string[] args)\n {\n var numbers = new List&lt;int&gt;();\n\n\n while (numbers.Count &lt; 5)\n { \n \n Console.WriteLine(&quot;Enter 5 uniqe numbers:&quot;);\n var number = Convert.ToInt32(Console.ReadLine());\n\n\n\n if (numbers.Contains(number))\n {\n Console.WriteLine(&quot;You have already entered&quot; + number);\n continue;\n }\n\n\n\n numbers.Add(number);\n }\n\n\n numbers.Sort();\n\n\n foreach(var number in numbers)\n {\n Console.WriteLine(number);\n }\n\n\n }\n</code></pre>\n<p>lets say the users input were 1,2,2,2,3,4,5.the result printed would be:</p>\n<pre><code>1,2,3,4,5\n</code></pre>\n<p>Why? because every time user entered a number that was already on the list, our program ignored it and didn't add what's already on the list to it.\nNow if we try the same code but <strong>without continue statement</strong> and let's say with the same input from the user which was 1,2,2,2,3,4,5.\nthe output would be :</p>\n<pre><code>1,2,2,2,3,4\n</code></pre>\n<p>Why? because there was no continue statement to let our program know it should ignore the already entered number.</p>\n<p>Now for the <strong>Break statement</strong>, again I think its the best to show by example. For example:</p>\n<p>Here we want our program to continuously ask the user to enter a number. We want the loop to terminate when the user types “ok&quot; and at the end Calculate the sum of all the previously entered numbers and display it on the console.</p>\n<p>This is how the <strong>break statement</strong> is used in this example:</p>\n<pre><code>{\n var sum = 0;\n while (true)\n {\n Console.Write(&quot;Enter a number (or 'ok' to exit): &quot;);\n var input = Console.ReadLine();\n\n if (input.ToLower() == &quot;ok&quot;)\n break;\n\n sum += Convert.ToInt32(input);\n }\n Console.WriteLine(&quot;Sum of all numbers is: &quot; + sum);\n }\n</code></pre>\n<p>The program will ask the user to enter a number till the user types &quot;OK&quot; and only after that, the result would be shown. Why?\nbecause break statement finished or stops the ongoing process when it has reached the condition needed.</p>\n<p>if there was no break statement there, the program would keep running and nothing would happen when the user typed &quot;ok&quot;.</p>\n<p>I recommend copying this code and trying to remove or add these statements and see the changes yourself.</p>\n" } ]
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`.