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
35,805
<p>If I create a class <code>A</code> as follows:</p> <pre><code>class A: def __init__(self): self.name = 'A' </code></pre> <p>Inspecting the <code>__dict__</code> member looks like <code>{'name': 'A'}</code></p> <p>If however I create a class <code>B</code>:</p> <pre><code>class B: name = 'B' </code></pre> <p><code>__dict__</code> is empty.</p> <p>What is the difference between the two, and why doesn't <code>name</code> show up in <code>B</code>'s <code>__dict__</code>?</p>
[ { "answer_id": 35823, "author": "Carl Meyer", "author_id": 3207, "author_profile": "https://Stackoverflow.com/users/3207", "pm_score": 7, "selected": true, "text": "<p><code>B.name</code> is a class attribute, not an instance attribute. It shows up in <code>B.__dict__</code>, but not in...
2008/08/30
[ "https://Stackoverflow.com/questions/35805", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3154/" ]
If I create a class `A` as follows: ``` class A: def __init__(self): self.name = 'A' ``` Inspecting the `__dict__` member looks like `{'name': 'A'}` If however I create a class `B`: ``` class B: name = 'B' ``` `__dict__` is empty. What is the difference between the two, and why doesn't `name` show up in `B`'s `__dict__`?
`B.name` is a class attribute, not an instance attribute. It shows up in `B.__dict__`, but not in `b = B(); b.__dict__`. The distinction is obscured somewhat because when you access an attribute on an instance, the class dict is a fallback. So in the above example, `b.name` will give you the value of `B.name`.
35,817
<p>When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash.</p> <p>I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option:</p> <pre><code>def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort &gt; %s" % (sh_escape(in_filename), sh_escape(out_filename))) </code></pre> <p><em>Edit:</em> I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently.</p> <p>Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).</p>
[ { "answer_id": 35831, "author": "pauldoo", "author_id": 755, "author_profile": "https://Stackoverflow.com/users/755", "pm_score": 2, "selected": false, "text": "<p>I believe that os.system just invokes whatever command shell is configured for the user, so I don't think you can do it in a...
2008/08/30
[ "https://Stackoverflow.com/questions/35817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715/" ]
When using os.system() it's often necessary to escape filenames and other arguments passed as parameters to commands. How can I do this? Preferably something that would work on multiple operating systems/shells but in particular for bash. I'm currently doing the following, but am sure there must be a library function for this, or at least a more elegant/robust/efficient option: ``` def sh_escape(s): return s.replace("(","\\(").replace(")","\\)").replace(" ","\\ ") os.system("cat %s | grep something | sort > %s" % (sh_escape(in_filename), sh_escape(out_filename))) ``` *Edit:* I've accepted the simple answer of using quotes, don't know why I didn't think of that; I guess because I came from Windows where ' and " behave a little differently. Regarding security, I understand the concern, but, in this case, I'm interested in a quick and easy solution which os.system() provides, and the source of the strings is either not user-generated or at least entered by a trusted user (me).
This is what I use: ``` def shellquote(s): return "'" + s.replace("'", "'\\''") + "'" ``` The shell will always accept a quoted filename and remove the surrounding quotes before passing it to the program in question. Notably, this avoids problems with filenames that contain spaces or any other kind of nasty shell metacharacter. **Update**: If you are using Python 3.3 or later, use [shlex.quote](http://docs.python.org/dev/library/shlex.html#shlex.quote) instead of rolling your own.
35,842
<p>How do I get the id of my Java process? </p> <p>I know there are several platform-dependent hacks, but I would prefer a more generic solution.</p>
[ { "answer_id": 35885, "author": "Wouter Coekaerts", "author_id": 3432, "author_profile": "https://Stackoverflow.com/users/3432", "pm_score": 10, "selected": true, "text": "<p>There exists no platform-independent way that can be guaranteed to work in all jvm implementations.\n<code>Manage...
2008/08/30
[ "https://Stackoverflow.com/questions/35842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3583/" ]
How do I get the id of my Java process? I know there are several platform-dependent hacks, but I would prefer a more generic solution.
There exists no platform-independent way that can be guaranteed to work in all jvm implementations. `ManagementFactory.getRuntimeMXBean().getName()` looks like the best (closest) solution, and typically includes the PID. It's short, and *probably* works in every implementation in wide use. On linux+windows it returns a value like `"12345@hostname"` (`12345` being the process id). Beware though that [according to the docs](http://docs.oracle.com/javase/6/docs/api/java/lang/management/RuntimeMXBean.html#getName%28%29), there are no guarantees about this value: > > Returns the name representing the running Java virtual machine. The > returned name string can be any arbitrary string and a Java virtual > machine implementation can choose to embed platform-specific useful > information in the returned name string. Each running virtual machine > could have a different name. > > > **In Java 9** the new [process API](https://docs.oracle.com/javase/9/docs/api/java/lang/ProcessHandle.html) can be used: ``` long pid = ProcessHandle.current().pid(); ```
35,879
<p>I am building an open search add-on for Firefox/IE and the image needs to be Base64 Encoded so how can I base 64 encode the favicon I have?</p> <p>I am only familiar with PHP</p>
[ { "answer_id": 35881, "author": "OysterD", "author_id": 2638, "author_profile": "https://Stackoverflow.com/users/2638", "pm_score": 0, "selected": false, "text": "<p>Google led me to <a href=\"http://fr.php.net/base64_encode\" rel=\"nofollow noreferrer\">this</a> solution (base64_encode)...
2008/08/30
[ "https://Stackoverflow.com/questions/35879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
I am building an open search add-on for Firefox/IE and the image needs to be Base64 Encoded so how can I base 64 encode the favicon I have? I am only familiar with PHP
As far as I remember there is an xml element for the image data. You can use this [website](http://www.motobit.com/util/base64-decoder-encoder.asp) to encode a file (use the upload field). Then just copy and paste the data to the XML element. You could also use PHP to do this like so: ``` <?php $im = file_get_contents('filename.gif'); $imdata = base64_encode($im); ?> ``` Use [Mozilla's guide](http://developer.mozilla.org/en/Creating_OpenSearch_plugins_for_Firefox) for help on creating OpenSearch plugins. For example, the icon element is used like this: ``` <img width="16" height="16">data:image/x-icon;base64,imageData</> ``` Where `imageData` is your base64 data.
35,896
<p>Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx" rel="noreferrer">System.Media.SoundPlayer</a> can handle only WAV, but those are typically to big to embed in a downloadable apllication. MP3 is protected with patents, so even if there was a fully managed decoder/player it wouldn't be free to redistribute. The best format available would seem to be OGG Vorbis, but I had no luck getting any C# Vorbis libraries to work (I managed to extract a raw PCM with <a href="https://github.com/mono/csvorbis" rel="noreferrer">csvorbis</a> but I don't know how to play it afterwards).</p> <p>I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL.</p> <p>[this question is a follow up to a <a href="http://lists.ximian.com/pipermail/mono-devel-list/2007-June/023863.html" rel="noreferrer">mailing list discussion on mono-dev</a> mailing list a year ago]</p>
[ { "answer_id": 36050, "author": "skolima", "author_id": 3205, "author_profile": "https://Stackoverflow.com/users/3205", "pm_score": 4, "selected": true, "text": "<p>I finally revisited this topic, and, using help from <a href=\"https://stackoverflow.com/a/7152153/3205\">BrokenGlass on wr...
2008/08/30
[ "https://Stackoverflow.com/questions/35896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205/" ]
Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program. [System.Media.SoundPlayer](http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx) can handle only WAV, but those are typically to big to embed in a downloadable apllication. MP3 is protected with patents, so even if there was a fully managed decoder/player it wouldn't be free to redistribute. The best format available would seem to be OGG Vorbis, but I had no luck getting any C# Vorbis libraries to work (I managed to extract a raw PCM with [csvorbis](https://github.com/mono/csvorbis) but I don't know how to play it afterwards). I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL. [this question is a follow up to a [mailing list discussion on mono-dev](http://lists.ximian.com/pipermail/mono-devel-list/2007-June/023863.html) mailing list a year ago]
I finally revisited this topic, and, using help from [BrokenGlass on writing WAVE header](https://stackoverflow.com/a/7152153/3205), updated csvorbis. I've added an [OggDecodeStream](https://github.com/mono/csvorbis/blob/master/OggDecoder/OggDecodeStream.cs) that can be passed to `System.Media.SoundPlayer` to simply play any (compatible) Ogg Vorbis stream. Example usage: ``` using (var file = new FileStream(oggFilename, FileMode.Open, FileAccess.Read)) { var player = new SoundPlayer(new OggDecodeStream(file)); player.PlaySync(); } ``` 'Compatible' in this case means 'it worked when I tried it out'. The decoder is fully managed, works fine on Microsoft .Net - at the moment, there seems to be a regression in Mono's `SoundPlayer` that causes distortion. Outdated: ~~`System.Diagnostics.Process.Start("fullPath.mp3");`~~ I am surprised but the [method Dinah mentioned](https://stackoverflow.com/questions/35896/how-can-i-play-compressed-sound-files-in-c-in-a-portable-way#35987) actually works. However, I was thinking about playing short "jingle" sounds on various events occurring in the program, I don't want to launch user's media player each time I need to do a 'ping!' sound. As for the code project link - this is unfortunately only a P/Invoke wrapper.
35,905
<p>I've created a few <code>autorun</code> script files on various USB devices that run <code>bash</code> scripts when they mount. These scripts run "in the background", how do I get them to run in a terminal window? (Like the "Application in Terminal" gnome Launcher type.)</p>
[ { "answer_id": 35924, "author": "Vagnerr", "author_id": 3720, "author_profile": "https://Stackoverflow.com/users/3720", "pm_score": 4, "selected": true, "text": "<p>Run them as a two stage process with your \"autorun\" script calling the second script in a new terminal eg</p>\n\n<pre><co...
2008/08/30
[ "https://Stackoverflow.com/questions/35905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715/" ]
I've created a few `autorun` script files on various USB devices that run `bash` scripts when they mount. These scripts run "in the background", how do I get them to run in a terminal window? (Like the "Application in Terminal" gnome Launcher type.)
Run them as a two stage process with your "autorun" script calling the second script in a new terminal eg ``` gnome-terminal -e top --title Testing ``` Would run the program "top" in a new gnome terminal window with the title "Testing" You can add additional arguments like setting the geometry to determine the size and location of the window checkout the man page for *gnome-terminal* and the "X" man page for more details
35,914
<p>Here's the situation: I am trying to launch an application, but the location of the .exe isn't known to me. Now, if the file extension is registered (in Windows), I can do something like:</p> <pre><code>Process.Start("Sample.xls"); </code></pre> <p>However, I need to pass some command line arguments as well. I couldn't get this to work</p> <pre><code> Process p = new Process(); p.StartInfo.FileName = "Sample.xls"; p.StartInfo.Arguments = "/r"; // open in read-only mode p.Start(); </code></pre> <p>Any suggestions on a mechanism to solve this?</p> <p><strong>Edit</strong> @ aku</p> <p>My StackOverflow search skills are weak; I did not find that post. Though I generally dislike peering into the registry, that's a great solution. Thanks!</p>
[ { "answer_id": 35928, "author": "Palgar", "author_id": 3479, "author_profile": "https://Stackoverflow.com/users/3479", "pm_score": 2, "selected": false, "text": "<p>If you query the registry, you can retrieve the data about the registered file type and then call the app directly passing ...
2008/08/30
[ "https://Stackoverflow.com/questions/35914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2258/" ]
Here's the situation: I am trying to launch an application, but the location of the .exe isn't known to me. Now, if the file extension is registered (in Windows), I can do something like: ``` Process.Start("Sample.xls"); ``` However, I need to pass some command line arguments as well. I couldn't get this to work ``` Process p = new Process(); p.StartInfo.FileName = "Sample.xls"; p.StartInfo.Arguments = "/r"; // open in read-only mode p.Start(); ``` Any suggestions on a mechanism to solve this? **Edit** @ aku My StackOverflow search skills are weak; I did not find that post. Though I generally dislike peering into the registry, that's a great solution. Thanks!
Using my code from [this](https://stackoverflow.com/questions/24954/windows-list-and-launch-applications-associated-with-an-extension#24974) answer you can get command associated with xls extension. Then you can pass this command to `Process.Start` method.
35,948
<p>I'm using Google App Engine and Django templates.<br> I have a table that I want to display the objects look something like:<br></p> <pre><code>Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] </code></pre> <p>The Django template is:</p> <pre><code>&lt;table&gt; &lt;tr align="center"&gt; &lt;th&gt;user&lt;/th&gt; {% for item in result.items %} &lt;th&gt;{{item}}&lt;/th&gt; {% endfor %} &lt;/tr&gt; {% for user in result.users %} &lt;tr align="center"&gt; &lt;td&gt;{{user.name}}&lt;/td&gt; {% for item in result.items %} &lt;td&gt;{{ user.item }}&lt;/td&gt; {% endfor %} &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>Now the <a href="http://www.djangoproject.com/documentation/0.96/templates/#variables" rel="noreferrer">Django documention</a> states that when it sees a <strong>.</strong> in variables<br> It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...</p>
[ { "answer_id": 35978, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 3, "selected": false, "text": "<p>I'm assuming that the part the doesn't work is <code>{{ user.item }}</code>.</p>\n\n<p>Django will be trying a dictiona...
2008/08/30
[ "https://Stackoverflow.com/questions/35948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3117/" ]
I'm using Google App Engine and Django templates. I have a table that I want to display the objects look something like: ``` Object Result: Items = [item1,item2] Users = [{name='username',item1=3,item2=4},..] ``` The Django template is: ``` <table> <tr align="center"> <th>user</th> {% for item in result.items %} <th>{{item}}</th> {% endfor %} </tr> {% for user in result.users %} <tr align="center"> <td>{{user.name}}</td> {% for item in result.items %} <td>{{ user.item }}</td> {% endfor %} </tr> {% endfor %} </table> ``` Now the [Django documention](http://www.djangoproject.com/documentation/0.96/templates/#variables) states that when it sees a **.** in variables It tries several things to get the data, one of which is dictionary lookup which is exactly what I want but doesn't seem to happen...
I found a "nicer"/"better" solution for getting variables inside Its not the nicest way, but it works. You install a custom filter into django which gets the key of your dict as a parameter To make it work in google app-engine you need to add a file to your main directory, I called mine *django\_hack.py* which contains this little piece of code ``` from google.appengine.ext import webapp register = webapp.template.create_template_register() def hash(h,key): if key in h: return h[key] else: return None register.filter(hash) ``` Now that we have this file, all we need to do is tell the app-engine to use it... we do that by adding this little line to your main file ``` webapp.template.register_template_library('django_hack') ``` and in your template view add this template instead of the usual code ``` {{ user|hash:item }} ``` And its should work perfectly =)
35,954
<p>I have a query that originally looks like this:</p> <pre><code>select c.Id, c.Name, c.CountryCode, c.CustomerNumber, cacc.AccountNumber, ca.Line1, ca.CityName, ca.PostalCode from dbo.Customer as c left join dbo.CustomerAddress as ca on ca.CustomerId = c.Id left join dbo.CustomerAccount as cacc on cacc.CustomerId = c.Id where c.CountryCode = 'XX' and (cacc.AccountNumber like '%C17%' or c.Name like '%op%' or ca.Line1 like '%ae%' or ca.CityName like '%ab%' or ca.PostalCode like '%10%') </code></pre> <p>On a database with 90,000 records this query takes around 7 seconds to execute (obviously all the joins and likes are taxing). </p> <p>I have been trying to find a way to bring the query execution time down with full-text search on the columns concerned. However, I haven't seen an example of a full-text search that has three table joins like this, especially since my join condition is not part of the search term.</p> <p>Is there a way to do this in full-text search?</p> <hr> <p>@David</p> <p>Yep, there are indexes on the Ids.</p> <p>I've tried adding indexes on the CustomerAddress stuff (CityName, PostalCode, etc.) and it brought down the query to 3 seconds, but I still find that too slow for something like this.</p> <p>Note that all of the text fields (with the exception of the ids) are nvarchars, and Line1 is an nvarchar 1000, so that might affect the speed, but still.</p>
[ { "answer_id": 35955, "author": "wesc", "author_id": 3738, "author_profile": "https://Stackoverflow.com/users/3738", "pm_score": 0, "selected": false, "text": "<p>I <em>think</em> that an unordered_map and hash_map are more or less the same thing. The difference is that the STL doesn't o...
2008/08/30
[ "https://Stackoverflow.com/questions/35954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372/" ]
I have a query that originally looks like this: ``` select c.Id, c.Name, c.CountryCode, c.CustomerNumber, cacc.AccountNumber, ca.Line1, ca.CityName, ca.PostalCode from dbo.Customer as c left join dbo.CustomerAddress as ca on ca.CustomerId = c.Id left join dbo.CustomerAccount as cacc on cacc.CustomerId = c.Id where c.CountryCode = 'XX' and (cacc.AccountNumber like '%C17%' or c.Name like '%op%' or ca.Line1 like '%ae%' or ca.CityName like '%ab%' or ca.PostalCode like '%10%') ``` On a database with 90,000 records this query takes around 7 seconds to execute (obviously all the joins and likes are taxing). I have been trying to find a way to bring the query execution time down with full-text search on the columns concerned. However, I haven't seen an example of a full-text search that has three table joins like this, especially since my join condition is not part of the search term. Is there a way to do this in full-text search? --- @David Yep, there are indexes on the Ids. I've tried adding indexes on the CustomerAddress stuff (CityName, PostalCode, etc.) and it brought down the query to 3 seconds, but I still find that too slow for something like this. Note that all of the text fields (with the exception of the ids) are nvarchars, and Line1 is an nvarchar 1000, so that might affect the speed, but still.
[Boost documentation of unordered containers](http://www.boost.org/doc/libs/1_36_0/doc/html/unordered.html) The difference is in the method of how you generate the look up. In the map/set containers the `operator<` is used to generate an ordered tree. In the unordered containers, an `operator( key ) => index` is used. See hashing for a description of how that works.
35,973
<p>What is the best approach to define additional data for typedef enums in C?</p> <p>Example:</p> <pre><code>typedef enum { kVizsla = 0, kTerrier = 3, kYellowLab = 10 } DogType; </code></pre> <p>Now I would like to define names for each, for example <code>kVizsla</code> should be "vizsla". I currently use a function that returns a string using a large switch block.</p>
[ { "answer_id": 35994, "author": "On Freund", "author_id": 2150, "author_profile": "https://Stackoverflow.com/users/2150", "pm_score": 0, "selected": false, "text": "<p>That's kind of an open ended question, but one suggestion would be to use a map with the enum as the key type and the ex...
2008/08/30
[ "https://Stackoverflow.com/questions/35973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
What is the best approach to define additional data for typedef enums in C? Example: ``` typedef enum { kVizsla = 0, kTerrier = 3, kYellowLab = 10 } DogType; ``` Now I would like to define names for each, for example `kVizsla` should be "vizsla". I currently use a function that returns a string using a large switch block.
@dmckee: I think the suggested solution is good, but for simple data (e.g. if only the name is needed) it could be augmented with auto-generated code. While there are lots of ways to auto-generate code, for something as simple as this I believe you could write a simple XSLT that takes in an XML representation of the enum and outputs the code file. The XML would be of the form: ``` <EnumsDefinition> <Enum name="DogType"> <Value name="Vizsla" value="0" /> <Value name="Terrier" value="3" /> <Value name="YellowLab" value="10" /> </Enum> </EnumsDefinition> ``` and the resulting code would be something similar to what dmckee suggested in his solution. For information of how to write such an XSLT try [here](http://www.w3schools.com/xsl/) or just search it up in google and find a tutorial that fits. Writing XSLT is not much fun IMO, but it's not that bad either, at least for relatively simple tasks such as these.
35,988
<p>Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:</p> <pre><code>class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 </code></pre>
[ { "answer_id": 35990, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 6, "selected": false, "text": "<p>How about a dictionary?</p>\n\n<p>Something like this:</p>\n\n<pre><code>myStruct = {'field1': 'some val', 'field2': 'some...
2008/08/30
[ "https://Stackoverflow.com/questions/35988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3738/" ]
Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like: ``` class MyStruct(): def __init__(self, field1, field2, field3): self.field1 = field1 self.field2 = field2 self.field3 = field3 ```
Use a [named tuple](https://docs.python.org/2/library/collections.html#collections.namedtuple), which was added to the [collections module](http://docs.python.org/library/collections.html) in the standard library in Python 2.6. It's also possible to use Raymond Hettinger's [named tuple](http://code.activestate.com/recipes/500261/) recipe if you need to support Python 2.4. It's nice for your basic example, but also covers a bunch of edge cases you might run into later as well. Your fragment above would be written as: ``` from collections import namedtuple MyStruct = namedtuple("MyStruct", "field1 field2 field3") ``` The newly created type can be used like this: ``` m = MyStruct("foo", "bar", "baz") ``` You can also use named arguments: ``` m = MyStruct(field1="foo", field2="bar", field3="baz") ```
36,001
<p>I have a table defined (see code snippet below). How can I add a constraint or whatever so that the LastUpdate column is automatically updated anytime the row is changed?</p> <pre><code>CREATE TABLE dbo.Profiles ( UserName varchar(100) NOT NULL, LastUpdate datetime NOT NULL CONSTRAINT DF_Profiles_LastUpdate DEFAULT (getdate()), FullName varchar(50) NOT NULL, Birthdate smalldatetime NULL, PageSize int NOT NULL CONSTRAINT DF_Profiles_PageSize DEFAULT ((10)), CONSTRAINT PK_Profiles PRIMARY KEY CLUSTERED (UserName ASC), CONSTRAINT FK_Profils_Users FOREIGN KEY (UserName) REFERENCES dbo.Users (UserName) ON UPDATE CASCADE ON DELETE CASCADE ) </code></pre>
[ { "answer_id": 36002, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 2, "selected": false, "text": "<p>You're going to have to use triggers for that.</p>\n" }, { "answer_id": 36011, "author": "SQLMenace", "auth...
2008/08/30
[ "https://Stackoverflow.com/questions/36001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
I have a table defined (see code snippet below). How can I add a constraint or whatever so that the LastUpdate column is automatically updated anytime the row is changed? ``` CREATE TABLE dbo.Profiles ( UserName varchar(100) NOT NULL, LastUpdate datetime NOT NULL CONSTRAINT DF_Profiles_LastUpdate DEFAULT (getdate()), FullName varchar(50) NOT NULL, Birthdate smalldatetime NULL, PageSize int NOT NULL CONSTRAINT DF_Profiles_PageSize DEFAULT ((10)), CONSTRAINT PK_Profiles PRIMARY KEY CLUSTERED (UserName ASC), CONSTRAINT FK_Profils_Users FOREIGN KEY (UserName) REFERENCES dbo.Users (UserName) ON UPDATE CASCADE ON DELETE CASCADE ) ```
A default constraint only works on inserts; for an update use a trigger.
36,014
<p>I'm working on a project using the <a href="http://antlr.org" rel="noreferrer">ANTLR</a> parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception.</p> <p>The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime:</p> <pre> Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C# Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C# Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C# </pre> <p>The code snippet from the bottom-most call in Parse() looks like:</p> <pre><code> try { // Execution stopped at parser.prog() TimeDefParser.prog_return prog_ret = parser.prog(); return prog_ret == null ? null : prog_ret.value; } catch (Exception ex) { throw new ParserException(ex.Message, ex); } </code></pre> <p>To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't?</p> <p><strong>Update:</strong> I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block.</p> <p>Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result.</p> <p>One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result.</p> <p>Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode.</p> <p>Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue?</p> <p><strong>Update 2:</strong> I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0.</p> <p>I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases.</p> <p><strong>Update 3:</strong> I've replicated this scenario in a <a href="http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip" rel="noreferrer">simplified VS 2008 project</a>. Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet.</p> <p>If you can find a workaround, please do share your findings. Thanks again!</p> <hr> <p>Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception.</p> <p>The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.</p>
[ { "answer_id": 36029, "author": "Daniel Auger", "author_id": 1644, "author_profile": "https://Stackoverflow.com/users/1644", "pm_score": 2, "selected": false, "text": "<p>Is it possible that the exception is being thrown in another thread? Obviously your calling code is single threaded, ...
2008/08/30
[ "https://Stackoverflow.com/questions/36014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3347/" ]
I'm working on a project using the [ANTLR](http://antlr.org) parser library for C#. I've built a grammar to parse some text and it works well. However, when the parser comes across an illegal or unexpected token, it throws one of many exceptions. The problem is that in some cases (not all) that my try/catch block won't catch it and instead stops execution as an unhandled exception. The issue for me is that I can't replicate this issue anywhere else but in my full code. The call stack shows that the exception definitely occurs within my try/catch(Exception) block. The only thing I can think of is that there are a few ANTLR assembly calls that occur between my code and the code throwing the exception and this library does not have debugging enabled, so I can't step through it. I wonder if non-debuggable assemblies inhibit exception bubbling? The call stack looks like this; external assembly calls are in Antlr.Runtime: ``` Expl.Itinerary.dll!TimeDefLexer.mTokens() Line 1213 C# Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xfc bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x22c bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 1) + 0x68 bytes Expl.Itinerary.dll!TimeDefParser.prog() Line 109 + 0x17 bytes C# Expl.Itinerary.dll!Expl.Itinerary.TDLParser.Parse(string Text = "", Expl.Itinerary.IItinerary Itinerary = {Expl.Itinerary.MemoryItinerary}) Line 17 + 0xa bytes C# ``` The code snippet from the bottom-most call in Parse() looks like: ``` try { // Execution stopped at parser.prog() TimeDefParser.prog_return prog_ret = parser.prog(); return prog_ret == null ? null : prog_ret.value; } catch (Exception ex) { throw new ParserException(ex.Message, ex); } ``` To me, a catch (Exception) clause should've captured any exception whatsoever. Is there any reason why it wouldn't? **Update:** I traced through the external assembly with Reflector and found no evidence of threading whatsoever. The assembly seems to just be a runtime utility class for ANTLR's generated code. The exception thrown is from the TimeDefLexer.mTokens() method and its type is NoViableAltException, which derives from RecognitionException -> Exception. This exception is thrown when the lexer cannot understand the next token in the stream; in other words, invalid input. This exception is SUPPOSED to happen, however it should've been caught by my try/catch block. Also, the rethrowing of ParserException is really irrelevant to this situation. That is a layer of abstraction that takes any exception during parse and convert to my own ParserException. The exception handling problem I'm experiencing is never reaching that line of code. In fact, I commented out the "throw new ParserException" portion and still received the same result. One more thing, I modified the original try/catch block in question to instead catch NoViableAltException, eliminating any inheritance confusion. I still received the same result. Someone once suggested that sometimes VS is overactive on catching handled exceptions when in debug mode, but this issue also happens in release mode. Man, I'm still stumped! I hadn't mentioned it before, but I'm running VS 2008 and all my code is 3.5. The external assembly is 2.0. Also, some of my code subclasses a class in the 2.0 assembly. Could a version mismatch cause this issue? **Update 2:** I was able to eliminate the .NET version conflict by porting relevant portions of my .NET 3.5 code to a .NET 2.0 project and replicate the same scenario. I was able to replicate the same unhandled exception when running consistently in .NET 2.0. I learned that ANTLR has recently released 3.1. So, I upgraded from 3.0.1 and retried. It turns out the generated code is a little refactored, but the same unhandled exception occurs in my test cases. **Update 3:** I've replicated this scenario in a [simplified VS 2008 project](http://www.explodingcoder.com/cms/files/TestAntlr-3.1.zip). Feel free to download and inspect the project for yourself. I've applied all the great suggestions, but have not been able to overcome this obstacle yet. If you can find a workaround, please do share your findings. Thanks again! --- Thank you, but VS 2008 automatically breaks on unhandled exceptions. Also, I don't have a Debug->Exceptions dialog. The NoViableAltException that is thrown is fully intended, and designed to be caught by user code. Since it is not caught as expected, program execution halts unexpectedly as an unhandled exception. The exception thrown is derived from Exception and there is no multi-threading going on with ANTLR.
I believe I understand the problem. The exception is being caught, the issue is confusion over the debugger's behavior and differences in the debugger settings among each person trying to repro it. In the 3rd case from your repro I believe you are getting the following message: "NoViableAltException was unhandled by user code" and a callstack that looks like this: ``` [External Code] > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C# [External Code] TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C# [External Code] ``` If you right click in the callstack window and run turn on show external code you see this: ``` Antlr3.Runtime.dll!Antlr.Runtime.DFA.NoViableAlt(int s = 0x00000000, Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x80 bytes Antlr3.Runtime.dll!Antlr.Runtime.DFA.Predict(Antlr.Runtime.IIntStream input = {Antlr.Runtime.ANTLRStringStream}) + 0x21e bytes > TestAntlr-3.1.exe!TimeDefLexer.mTokens() Line 852 + 0xe bytes C# Antlr3.Runtime.dll!Antlr.Runtime.Lexer.NextToken() + 0xc4 bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.FillBuffer() + 0x147 bytes Antlr3.Runtime.dll!Antlr.Runtime.CommonTokenStream.LT(int k = 0x00000001) + 0x2d bytes TestAntlr-3.1.exe!TimeDefParser.prog() Line 141 + 0x14 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.ParseTest(string Text = "foobar;") Line 49 + 0x9 bytes C# TestAntlr-3.1.exe!TestAntlr_3._1.Program.Main(string[] args = {string[0x00000000]}) Line 30 + 0xb bytes C# [Native to Managed Transition] [Managed to Native Transition] mscorlib.dll!System.AppDomain.ExecuteAssembly(string assemblyFile, System.Security.Policy.Evidence assemblySecurity, string[] args) + 0x39 bytes Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() + 0x2b bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x3b bytes mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x81 bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x40 bytes ``` The debugger's message is telling you that an exception originating outside your code (from NoViableAlt) is going through code you own in TestAntlr-3.1.exe!TimeDefLexer.mTokens() without being handled. The wording is confusing, but it does not mean the exception is uncaught. The debugger is letting you know that code you own mTokens()" needs to be robust against this exception being thrown through it. Things to play with to see how this looks for those who didn't repro the problem: * Go to Tools/Options/Debugging and turn off "Enable Just My code (Managed only)". or option. * Go to Debugger/Exceptions and turn off "User-unhandled" for Common-Language Runtime Exceptions.
36,028
<p>How do I assign a method's output to a textbox value without code behind?</p> <pre><code>&lt;%@ Page Language="VB" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;script runat="server"&gt; Public TextFromString As String = "test text test text" Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w") Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer) Return New String(Input, Count) End Function &lt;/script&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head id="Head1" runat="server"&gt; &lt;title&gt;Test Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;%=TextFromString%&gt; &lt;br /&gt; &lt;asp:TextBox ID="TextBox1" runat="server" Text="&lt;%# TextFromString %&gt;"&gt;&lt;/asp:TextBox&gt; &lt;br /&gt; &lt;%=TextFromMethod%&gt; &lt;br /&gt; &lt;asp:TextBox ID="TextBox2" runat="server" Text="&lt;%# TextFromMethod %&gt;"&gt;&lt;/asp:TextBox&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>it was mostly so the designer guys could use it in the aspx page. Seems like a simple thing to push a variable value into a textbox to me.</p> <p>It's also confusing to me why</p> <pre><code>&lt;asp:Label runat="server" ID="label1"&gt;&lt;%=TextFromString%&gt;&lt;/asp:Label&gt; </code></pre> <p>and</p> <pre><code>&lt;asp:TextBox ID="TextBox3" runat="server"&gt;Hello&lt;/asp:TextBox&gt; </code></pre> <p>works but </p> <pre><code>&lt;asp:TextBox ID="TextBox4" runat="server"&gt;&lt;%=TextFromString%&gt;&lt;/asp:TextBox&gt; </code></pre> <p>causes a compilation error.</p>
[ { "answer_id": 36164, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 1, "selected": false, "text": "<p>Have you tried using an HTML control instead of the server control? Does it also cause a compilation error?</p>\n\n...
2008/08/30
[ "https://Stackoverflow.com/questions/36028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
How do I assign a method's output to a textbox value without code behind? ``` <%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> Public TextFromString As String = "test text test text" Public TextFromMethod As String = RepeatChar("S", 50) 'SubSonic.Sugar.Web.GenerateLoremIpsum(400, "w") Public Function RepeatChar(ByVal Input As String, ByVal Count As Integer) Return New String(Input, Count) End Function </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title>Test Page</title> </head> <body> <form id="form1" runat="server"> <div> <%=TextFromString%> <br /> <asp:TextBox ID="TextBox1" runat="server" Text="<%# TextFromString %>"></asp:TextBox> <br /> <%=TextFromMethod%> <br /> <asp:TextBox ID="TextBox2" runat="server" Text="<%# TextFromMethod %>"></asp:TextBox> </div> </form> </body> </html> ``` it was mostly so the designer guys could use it in the aspx page. Seems like a simple thing to push a variable value into a textbox to me. It's also confusing to me why ``` <asp:Label runat="server" ID="label1"><%=TextFromString%></asp:Label> ``` and ``` <asp:TextBox ID="TextBox3" runat="server">Hello</asp:TextBox> ``` works but ``` <asp:TextBox ID="TextBox4" runat="server"><%=TextFromString%></asp:TextBox> ``` causes a compilation error.
There's a couple of different expression types in .ASPX files. There's: ``` <%= TextFromMethod %> ``` which simply reserves a literal control, and outputs the text at render time. and then there's: ``` <%# TextFromMethod %> ``` which is a databinding expression, evaluated when the control is DataBound(). There's also expression builders, like: ``` <%$ ConnectionStrings:Database %> ``` but that's not really important here.... So, the `<%= %>` method won't work because it would try to insert a Literal into the .Text property...obviously, not what you want. The `<%# %>` method doesn't work because the TextBox isn't DataBound, nor are any of it's parents. If your TextBox was in a Repeater or GridView, then this method would work. So - what to do? Just call `TextBox.DataBind()` at some point. Or, if you have more than 1 control, just call `Page.DataBind()` in your `Page_Load`. ``` Private Function Page_Load(sender as Object, e as EventArgs) If Not IsPostback Then Me.DataBind() End If End Function ```
36,058
<p>I have a popup window containing a form which gathers data for a report. When I click submit in that window, I want it to close the popup, and open the report in the original window that called the popup.</p> <p>I think I can open the report in the correct window by using</p> <pre><code>{ :target =&gt; &lt;name of window&gt; } </code></pre> <p>in the <code>form_tag</code>, but I don't know how to determine or set the name of the originating window.</p> <p>I also don't know how to close the popup window.</p>
[ { "answer_id": 36065, "author": "Craig", "author_id": 1611, "author_profile": "https://Stackoverflow.com/users/1611", "pm_score": 0, "selected": false, "text": "<p>How is <a href=\"http://railsforum.com/viewtopic.php?id=17785\" rel=\"nofollow noreferrer\">this</a> for starters?</p>\n\n<p...
2008/08/30
[ "https://Stackoverflow.com/questions/36058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a popup window containing a form which gathers data for a report. When I click submit in that window, I want it to close the popup, and open the report in the original window that called the popup. I think I can open the report in the correct window by using ``` { :target => <name of window> } ``` in the `form_tag`, but I don't know how to determine or set the name of the originating window. I also don't know how to close the popup window.
`:target =>` adds the html attribute target to the link. This opens up a new window and names the new window the target. You have to use javascript or Ajax to redirect the old page, ``` window.opener.location.href="http://new_url"; ``` and then close the old window. ``` window.close(); ``` This can be done either through the rjs file or directly in the javascript.
36,064
<p>I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form?</p>
[ { "answer_id": 36206, "author": "Dane O'Connor", "author_id": 1946, "author_profile": "https://Stackoverflow.com/users/1946", "pm_score": 2, "selected": false, "text": "<p>Not sure where it went. You could roll your own extension though:</p>\n\n<p>public static class MyBindingExtensions ...
2008/08/30
[ "https://Stackoverflow.com/questions/36064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3412/" ]
I am attempting to update a project from ASP.NET MVC Preview 3 to Preview 5 and it seems that Controller.ReadFromRequest(string key) has been removed from the Controller class. Does anyone know of any alternatives to retrieving information based on an identifier from a form?
Looks like they've added controller.UpdateModel to address this issue, signature is: ``` UpdateModel(object model, string[] keys) ``` I haven't upgraded my app personally, so I'm not sure of the actual usage. I'll be interested to find out about this myself, as I'm using `controller.ReadFromRequest` as well.
36,077
<p>I'm looking for an answer in MS VC++.</p> <p>When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want.</p> <p>Example in pseudo code:</p> <pre><code>FunctionB() { ... throw e; ... } FunctionA() { ... FunctionB() ... } try { Function A() } catch(e) { (&lt;--- breakpoint) ... } </code></pre> <p>I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in <code>FunctionA()</code> or <code>FunctionB()</code>, or some other function. (Assuming extensive exception use and a huge version of the above example).</p> <p>One solution to my problem is to determine and save the call stack <strong>in the exception constructor</strong> (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program.</p> <p>Is there an easier way that requires less work? Without having to change my large code base?</p> <p>Are there better solutions to this problem in other languages?</p>
[ { "answer_id": 36087, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>Other languages? Well, in Java you call e.printStackTrace(); It doesn't get much simpler than that.</p>\n" }, {...
2008/08/30
[ "https://Stackoverflow.com/questions/36077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
I'm looking for an answer in MS VC++. When debugging a large C++ application, which unfortunately has a very extensive usage of C++ exceptions. Sometimes I catch an exception a little later than I actually want. Example in pseudo code: ``` FunctionB() { ... throw e; ... } FunctionA() { ... FunctionB() ... } try { Function A() } catch(e) { (<--- breakpoint) ... } ``` I can catch the exception with a breakpoint when debugging. But I can't trace back if the exception occurred in `FunctionA()` or `FunctionB()`, or some other function. (Assuming extensive exception use and a huge version of the above example). One solution to my problem is to determine and save the call stack **in the exception constructor** (i.e. before it is caught). But this would require me to derive all exceptions from this base exception class. It would also require a lot of code, and perhaps slow down my program. Is there an easier way that requires less work? Without having to change my large code base? Are there better solutions to this problem in other languages?
If you are just interested in where the exception came from, you could just write a simple macro like ``` #define throwException(message) \ { \ std::ostringstream oss; \ oss << __FILE __ << " " << __LINE__ << " " \ << __FUNC__ << " " << message; \ throw std::exception(oss.str().c_str()); \ } ``` which will add the file name, line number and function name to the exception text (if the compiler provides the respective macros). Then throw exceptions using ``` throwException("An unknown enum value has been passed!"); ```
36,079
<p>In my PHP web app, I want to be notified via email whenever certain errors occur. I'd like to use my Gmail account for sending these. How could this be done?</p>
[ { "answer_id": 36086, "author": "maxsilver", "author_id": 1477, "author_profile": "https://Stackoverflow.com/users/1477", "pm_score": 2, "selected": false, "text": "<p>You could use PEAR's mail function with Gmail's SMTP Server</p>\n\n<p>Note that when sending e-mail using Gmail's SMTP s...
2008/08/30
[ "https://Stackoverflow.com/questions/36079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/356/" ]
In my PHP web app, I want to be notified via email whenever certain errors occur. I'd like to use my Gmail account for sending these. How could this be done?
Gmail's SMTP-server requires a very specific configuration. From [Gmail help](http://mail.google.com/support/bin/answer.py?answer=13287): ``` Outgoing Mail (SMTP) Server (requires TLS) - smtp.gmail.com - Use Authentication: Yes - Use STARTTLS: Yes (some clients call this SSL) - Port: 465 or 587 Account Name: your full email address (including @gmail.com) Email Address: your email address (username@gmail.com) Password: your Gmail password ``` You can probably set these settings up in [Pear::Mail](http://pear.php.net/package/Mail) or [PHPMailer](http://phpmailer.codeworxtech.com/). Check out their documentation for more details.
36,081
<p>I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction?</p> <p>Edit: The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block.</p> <hr> <p>I'm looking for more detail on rolling my own catching block inside a using block.</p> <p>Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue...</p> <p>Edit: @Blair, this is exactly what I was looking for, thanks for the detailed reply!</p>
[ { "answer_id": 36094, "author": "Quibblesome", "author_id": 1143, "author_profile": "https://Stackoverflow.com/users/1143", "pm_score": 2, "selected": false, "text": "<p>Yeah there is nothing different about throwing exceptions in using blocks.\nRemember that the using block basically tr...
2008/08/30
[ "https://Stackoverflow.com/questions/36081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ]
I'm trying to leverage the using block more and more these days when I have an object that implements IDisposable but one thing I have not figured out is how to catch an exception as I would in a normal try/catch/finally ... any code samples to point me in the right direction? Edit: The question was modified after reading through the replies. It was "How to Throw an exception in a using block with .NET 2.0?" but I was actually looking for a way to catch these exceptions inside a using block. --- I'm looking for more detail on rolling my own catching block inside a using block. Edit: What I wanted to avoid is having to use a try/catch/finally inside my using block like @Blair showed. But maybe this is a non issue... Edit: @Blair, this is exactly what I was looking for, thanks for the detailed reply!
I don't really understand the question - you throw an exception as you normally would. If `MyThing` implements `IDisposable`, then: ``` using ( MyThing thing = new MyThing() ) { ... throw new ApplicationException("oops"); } ``` And `thing.Dispose` will be called as you leave the block, as the exception's thrown. If you want to combine a try/catch/finally and a using, you can either nest them: ``` try { ... using ( MyThing thing = new MyThing() ) { ... } ... } catch ( Exception e ) { .... } finally { .... } ``` (Or put the try/catch/finally in the using): ``` using ( MyThing thing = new MyThing() ) { ... try { ... } catch ( Exception e ) { .... } finally { .... } ... } // thing.Dispose is called now ``` Or you can unroll the `using` and explicitly call `Dispose` in the `finally` block as @Quarrelsome demonstrated, adding any extra exception-handling or -recovery code that you need in the `finally` (or in the `catch`). EDIT: In response to @Toran Billups, if you need to process exceptions aside from ensuring that your `Dispose` method is called, you'll either have to use a `using` and `try/catch/finally` or unroll the `using` - I don't thinks there's any other way to accomplish what you want.
36,101
<p>How do I "name" a browser window in ROR, such that I can open a page in it later, from another (popup) window (using the target="name" html parameter)</p>
[ { "answer_id": 36131, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 4, "selected": true, "text": "<p>You have to use JavaScript for this:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n window.name = \"MyWin...
2008/08/30
[ "https://Stackoverflow.com/questions/36101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
How do I "name" a browser window in ROR, such that I can open a page in it later, from another (popup) window (using the target="name" html parameter)
You have to use JavaScript for this: ``` <script type="text/javascript"> window.name = "MyWindow"; </script> ``` Of course you could easily package this up into a Rails helper method. For example, in `app/helpers/application_helper.rb` add a new method: ``` def window_name(name) content_for(:window_name) do "<script type=\"text/javascript\">window.name = \"#{name}\";</script>" end end ``` Next, in your layout file, add this line somewhere within the HTML `<head>` element: ``` <%= yield :window_name %> ``` Finally, in your view templates, simply add a line like this (can be anywhere you want) to output the correct JavaScript: ``` <% window_name 'MyWindow' %> ```
36,109
<p>The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE.</p> <pre><code>#! /bin/sh if [ "${1+set}" != "set" ] then echo "Usage; winewrap EXEC [ARGS...]" exit 1 fi EXEC="$1" shift ARGS="" for p in "$@"; do if [ -e "$p" ] then p=$(winepath -w $p) fi ARGS="$ARGS '$p'" done CMD="wine '$EXEC' $ARGS" echo $CMD $CMD </code></pre> <p>However, there's something wrong with the quotation of command-line arguments.</p> <pre><code>$ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt' wine: cannot find ''/home/chris/.wine/drive_c/Program' </code></pre> <p>Note that:</p> <ol> <li>The path to the executable is being chopped off at the first space, even though it is single-quoted.</li> <li>The literal "\t" in the last path is being transformed into a tab character.</li> </ol> <p>Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors?</p> <p>EDIT: The "\t" is being expanded through two levels of indirection: first, <code>"$p"</code> (and/or <code>"$ARGS"</code>) is being expanded into <code>Z:\tmp\smtlib3cee8b.smt</code>; then, <code>\t</code> is being expanded into the tab character. This is (seemingly) equivalent to</p> <pre><code>Y='y\ty' Z="z${Y}z" echo $Z </code></pre> <p>which yields </p> <pre><code>zy\tyz </code></pre> <p>and <em>not</em></p> <pre><code>zy yz </code></pre> <p>UPDATE: <code>eval "$CMD"</code> does the trick. The "<code>\t</code>" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." (<a href="http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html" rel="nofollow noreferrer">POSIX specification of <code>echo</code></a>)</p>
[ { "answer_id": 36113, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 0, "selected": false, "text": "<p>You can try preceeding the spaces with \\ like so:</p>\n\n<pre><code>/home/chris/.wine/drive_c/Program Files/Microsoft\\...
2008/08/30
[ "https://Stackoverflow.com/questions/36109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1412/" ]
The following shell script takes a list of arguments, turns Unix paths into WINE/Windows paths and invokes the given executable under WINE. ``` #! /bin/sh if [ "${1+set}" != "set" ] then echo "Usage; winewrap EXEC [ARGS...]" exit 1 fi EXEC="$1" shift ARGS="" for p in "$@"; do if [ -e "$p" ] then p=$(winepath -w $p) fi ARGS="$ARGS '$p'" done CMD="wine '$EXEC' $ARGS" echo $CMD $CMD ``` However, there's something wrong with the quotation of command-line arguments. ``` $ winewrap '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' -smt /tmp/smtlib3cee8b.smt Executing: wine '/home/chris/.wine/drive_c/Program Files/Microsoft Research/Z3-1.3.6/bin/z3.exe' '-smt' 'Z: mp\smtlib3cee8b.smt' wine: cannot find ''/home/chris/.wine/drive_c/Program' ``` Note that: 1. The path to the executable is being chopped off at the first space, even though it is single-quoted. 2. The literal "\t" in the last path is being transformed into a tab character. Obviously, the quotations aren't being parsed the way I intended by the shell. How can I avoid these errors? EDIT: The "\t" is being expanded through two levels of indirection: first, `"$p"` (and/or `"$ARGS"`) is being expanded into `Z:\tmp\smtlib3cee8b.smt`; then, `\t` is being expanded into the tab character. This is (seemingly) equivalent to ``` Y='y\ty' Z="z${Y}z" echo $Z ``` which yields ``` zy\tyz ``` and *not* ``` zy yz ``` UPDATE: `eval "$CMD"` does the trick. The "`\t`" problem seems to be echo's fault: "If the first operand is -n, or if any of the operands contain a backslash ( '\' ) character, the results are implementation-defined." ([POSIX specification of `echo`](http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html))
I you do want to have the assignment to CMD you should use `eval $CMD` instead of just `$CMD` in the last line of your script. This should solve your problem with spaces in the paths, I don't know what to do about the "\t" problem.
36,114
<p>I know I must be missing something, but in a <code>while</code> statement how does the variable hold the data, when it finishes the first pass and goes into the second pass?</p> <hr> <p>{</p> <pre><code>int num1 = 0 ; int num2 = 0; int num3 = 0; while (num1 &lt; 10) {cout &lt;&lt; "enter your first number: "; cin &gt;&gt; num1; cout &lt;&lt; "Enter your second number: "; cin &gt;&gt; num2; num1 = num1 + num2 ; cout &lt;&lt; "Number 1 is now: " &lt;&lt; num1 &lt;&lt;endl; cout &lt;&lt; "Enter Number 3: " ; cin &gt;&gt; num3; num1 = num1 + num3; cout &lt;&lt; "Number 1 is now: " &lt;&lt; num1 &lt;&lt; endl; num1++; }; </code></pre> <p>In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong!</p>
[ { "answer_id": 36133, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 1, "selected": false, "text": "<p>I'm not sure I understand your question. In C any data that's not overwritten is carried over into the next iteration of...
2008/08/30
[ "https://Stackoverflow.com/questions/36114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/335696/" ]
I know I must be missing something, but in a `while` statement how does the variable hold the data, when it finishes the first pass and goes into the second pass? --- { ``` int num1 = 0 ; int num2 = 0; int num3 = 0; while (num1 < 10) {cout << "enter your first number: "; cin >> num1; cout << "Enter your second number: "; cin >> num2; num1 = num1 + num2 ; cout << "Number 1 is now: " << num1 <<endl; cout << "Enter Number 3: " ; cin >> num3; num1 = num1 + num3; cout << "Number 1 is now: " << num1 << endl; num1++; }; ``` In this code. The Variable doesn't hold the data. I'm not sure what I'm doing wrong!
Is num1 the variable you're having trouble with? This line: ``` cin >> num1; ``` is setting num1 to the value input by the user. So the value calculated for it in the previous run through the loop is being overwritten each time by the new input.
36,129
<p>I'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world.</p> <p>If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below.</p>
[ { "answer_id": 36167, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 3, "selected": true, "text": "<p>An ah-ha moment for me for the observer pattern was to realize how closely associated it is with events. Consider a Windows pro...
2008/08/30
[ "https://Stackoverflow.com/questions/36129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1603/" ]
I'm reading through head first design patterns at the moment and while the book is excellent I also would like to see how these are actually used in the real world. If you know of a good example of design pattern usage (preferably in a OSS program so we can have a look :) then please list it below.
An ah-ha moment for me for the observer pattern was to realize how closely associated it is with events. Consider a Windows program that needs to acheive loosely communications between two forms. That can easily be accomplished with the observer pattern. The code below shows how Form2 fires an event and any other class registered as an observer get its data. See this link for a great patterns resource: <http://sourcemaking.com/design-patterns-and-tips> Form1's code: ``` namespace PublishSubscribe { public partial class Form1 : Form { Form2 f2 = new Form2(); public Form1() { InitializeComponent(); f2.PublishData += new PublishDataEventHander( DataReceived ); f2.Show(); } private void DataReceived( object sender, Form2EventArgs e ) { MessageBox.Show( e.OtherData ); } } } ``` Form2's code ``` namespace PublishSubscribe { public delegate void PublishDataEventHander( object sender, Form2EventArgs e ); public partial class Form2 : Form { public event PublishDataEventHander PublishData; public Form2() { InitializeComponent(); } private void button1_Click( object sender, EventArgs e ) { PublishData( this, new Form2EventArgs( "data from form2" ) ); } } public class Form2EventArgs : System.EventArgs { public string OtherData; public Form2EventArgs( string OtherData ) { this.OtherData = OtherData; } } } ```
36,139
<p>What is the best way of creating an alphabetically sorted list in Python?</p>
[ { "answer_id": 36143, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 5, "selected": false, "text": "<pre><code>list.sort()\n</code></pre>\n\n<p>It really is that simple :)</p>\n" }, { "answer_id": 36156, "author":...
2008/08/30
[ "https://Stackoverflow.com/questions/36139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3205/" ]
What is the best way of creating an alphabetically sorted list in Python?
Basic answer: ``` mylist = ["b", "C", "A"] mylist.sort() ``` This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the [`sorted()`](http://docs.python.org/library/functions.html#sorted) function: ``` for x in sorted(mylist): print x ``` However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter `key` to specify custom sorting order (the alternative, using `cmp`, is a deprecated solution, as it has to be evaluated multiple times - `key` is only computed once per element). So, to sort according to the current locale, taking language-specific rules into account ([`cmp_to_key`](http://docs.python.org/library/functools.html#functools.cmp_to_key) is a helper function from functools): ``` sorted(mylist, key=cmp_to_key(locale.strcoll)) ``` And finally, if you need, you can specify a [custom locale](http://docs.python.org/library/locale.html) for sorting: ``` import locale locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale assert sorted((u'Ab', u'ad', u'aa'), key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad'] ``` Last note: you will see examples of case-insensitive sorting which use the `lower()` method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data: ``` # this is incorrect! mylist.sort(key=lambda x: x.lower()) # alternative notation, a bit faster, but still wrong mylist.sort(key=str.lower) ```
36,144
<p>I'm trying to open a new browser tab with the results of a POST request. I'm trying to do so using a function containing the following code:</p> <pre><code>var windowManager = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interface s.nsIWindowMediator); var browserWindow = windowManager.getMostRecentWindow("navigator:browser"); var browser = browserWindow.getBrowser(); if(browser.mCurrentBrowser.currentURI.spec == "about:blank") browserWindow.loadURI(url, null, postData, false); else browser.loadOneTab(url, null, null, postData, false, false); </code></pre> <p>I'm using a string as url, and JSON data as postData. Is there something I'm doing wrong?</p> <p>What happens, is a new tab is created, the location shows the URL I want to post to, but the document is blank. The Back, Forward, and Reload buttons are all grayed out on the browser. It seems like it did everything except executed the POST. If I leave the postData parameter off, then it properly runs a GET.</p> <p>Build identifier: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1</p>
[ { "answer_id": 36216, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 0, "selected": false, "text": "<p>try with addTab instead of loadOneTab, and remove the last parameter. </p>\n\n<p>Check out <a href=\"http://developer.mozil...
2008/08/30
[ "https://Stackoverflow.com/questions/36144", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3288/" ]
I'm trying to open a new browser tab with the results of a POST request. I'm trying to do so using a function containing the following code: ``` var windowManager = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interface s.nsIWindowMediator); var browserWindow = windowManager.getMostRecentWindow("navigator:browser"); var browser = browserWindow.getBrowser(); if(browser.mCurrentBrowser.currentURI.spec == "about:blank") browserWindow.loadURI(url, null, postData, false); else browser.loadOneTab(url, null, null, postData, false, false); ``` I'm using a string as url, and JSON data as postData. Is there something I'm doing wrong? What happens, is a new tab is created, the location shows the URL I want to post to, but the document is blank. The Back, Forward, and Reload buttons are all grayed out on the browser. It seems like it did everything except executed the POST. If I leave the postData parameter off, then it properly runs a GET. Build identifier: Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1
Something which is less Mozilla specific and should work reasonably well with most of the browsers: * Create a hidden form with the fields set up the way you need them * Make sure that the "target" attribute of the form is set to "\_BLANK" * Submit the form programatically
36,182
<p>In postgis, is the <code>ST_GeomFromText</code> call very expensive? I ask mostly because I have a frequently called query that attempts to find the point that is nearest another point that matches some criteria, and which is also within a certain distance of that other point, and the way I currently wrote it, it's doing the same <code>ST_GeomFromText</code> twice:</p> <pre><code> $findNearIDMatchStmt = $postconn-&gt;prepare( "SELECT internalid " . "FROM waypoint " . "WHERE id = ? AND " . " category = ? AND ". " (b.category in (1, 3) OR type like ?) AND ". " ST_DWithin(point, ST_GeomFromText(?," . SRID . " ),". SMALL_EPSILON . ") " . " ORDER BY ST_Distance(point, ST_GeomFromText(?,", SRID . " )) " . " LIMIT 1"); </code></pre> <p>Is there a better way to re-write this?</p> <p>Slightly OT: In the preview screen, all my underscores are being rendered as <code>&amp; # 9 5 ;</code> - I hope that's not going to show up that way in the post.</p>
[ { "answer_id": 36165, "author": "Silas Snider", "author_id": 2933, "author_profile": "https://Stackoverflow.com/users/2933", "pm_score": 3, "selected": true, "text": "<p>Go to about:ubiquity in Firefox. Under the section \"subscribed feeds\" there should be an option to unsubscribe to co...
2008/08/30
[ "https://Stackoverflow.com/questions/36182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ]
In postgis, is the `ST_GeomFromText` call very expensive? I ask mostly because I have a frequently called query that attempts to find the point that is nearest another point that matches some criteria, and which is also within a certain distance of that other point, and the way I currently wrote it, it's doing the same `ST_GeomFromText` twice: ``` $findNearIDMatchStmt = $postconn->prepare( "SELECT internalid " . "FROM waypoint " . "WHERE id = ? AND " . " category = ? AND ". " (b.category in (1, 3) OR type like ?) AND ". " ST_DWithin(point, ST_GeomFromText(?," . SRID . " ),". SMALL_EPSILON . ") " . " ORDER BY ST_Distance(point, ST_GeomFromText(?,", SRID . " )) " . " LIMIT 1"); ``` Is there a better way to re-write this? Slightly OT: In the preview screen, all my underscores are being rendered as `& # 9 5 ;` - I hope that's not going to show up that way in the post.
Go to about:ubiquity in Firefox. Under the section "subscribed feeds" there should be an option to unsubscribe to command feeds you no longer desire. Also, if you clear your entire browser history, it will delete all command feeds (this will be fixed by 0.2)
36,183
<p>I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string:</p> <pre><code>12||34||56 </code></pre> <p>I want to replace the second set of pipes with ampersands to get this string:</p> <pre><code>12||34&amp;&amp;56 </code></pre> <p>The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements:</p> <pre><code>23||45||45||56||67 -&gt; 23&amp;&amp;45||45||56||67 23||34||98||87 -&gt; 23||34||98&amp;&amp;87 </code></pre> <p>I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on <code>/\|\|/</code> and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this. Note that this would be for Javascript, so it's possible to generate a regex at runtime using <code>eval()</code>, but it's not possible to use any Perl-specific regex instructions.</p>
[ { "answer_id": 36191, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 5, "selected": true, "text": "<p>here's something that works:</p>\n\n<pre><code>\"23||45||45||56||67\".replace(/^((?:[0-9]+\\|\\|){n})([0-9]+)\\|\\|/,\"$...
2008/08/30
[ "https://Stackoverflow.com/questions/36183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289/" ]
I'm trying to write a regex function that will identify and replace a single instance of a match within a string without affecting the other instances. For example, I have this string: ``` 12||34||56 ``` I want to replace the second set of pipes with ampersands to get this string: ``` 12||34&&56 ``` The regex function needs to be able to handle x amount of pipes and allow me to replace the nth set of pipes, so I could use the same function to make these replacements: ``` 23||45||45||56||67 -> 23&&45||45||56||67 23||34||98||87 -> 23||34||98&&87 ``` I know that I could just split/replace/concat the string at the pipes, and I also know that I can match on `/\|\|/` and iterate through the resulting array, but I'm interested to know if it's possible to write a single expression that can do this. Note that this would be for Javascript, so it's possible to generate a regex at runtime using `eval()`, but it's not possible to use any Perl-specific regex instructions.
here's something that works: ``` "23||45||45||56||67".replace(/^((?:[0-9]+\|\|){n})([0-9]+)\|\|/,"$1$2&&") ``` where n is the one less than the nth pipe, (of course you don't need that first subexpression if n = 0) And if you'd like a function to do this: ``` function pipe_replace(str,n) { var RE = new RegExp("^((?:[0-9]+\\|\\|){" + (n-1) + "})([0-9]+)\|\|"); return str.replace(RE,"$1$2&&"); } ```
36,239
<p>I would like to think that some of the software I'm writing today will be used in 30 years. But I am also aware that a lot of it is based upon the UNIX tradition of exposing time as the number of seconds since 1970.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;limits.h&gt; void print(time_t rt) { struct tm * t = gmtime(&amp;rt); puts(asctime(t)); } int main() { print(0); print(time(0)); print(LONG_MAX); print(LONG_MAX+1); } </code></pre> <p>Execution results in:</p> <ul> <li>Thu Jan 1 00:00:00 1970</li> <li>Sat Aug 30 18:37:08 2008</li> <li>Tue Jan 19 03:14:07 <strong>2038</strong></li> <li>Fri Dec 13 20:45:52 <strong>1901</strong></li> </ul> <blockquote> <blockquote> <p>The functions ctime(), gmtime(), and localtime() all take as an argument a time value representing the time in seconds since the Epoch (00:00:00 UTC, January 1, 1970; see time(3) ).</p> </blockquote> </blockquote> <p>I wonder if there is anything proactive to do in this area as a programmer, or are we to trust that all software systems (aka Operating Systems) will some how be magically upgraded in the future?</p> <p><strong>Update</strong> It would seem that indeed 64-bit systems are safe from this:</p> <pre class="lang-java prettyprint-override"><code>import java.util.*; class TimeTest { public static void main(String[] args) { print(0); print(System.currentTimeMillis()); print(Long.MAX_VALUE); print(Long.MAX_VALUE + 1); } static void print(long l) { System.out.println(new Date(l)); } } </code></pre> <ul> <li>Wed Dec 31 16:00:00 PST 1969</li> <li>Sat Aug 30 12:02:40 PDT 2008</li> <li>Sat Aug 16 23:12:55 PST <strong>292278994</strong></li> <li>Sun Dec 02 08:47:04 PST <strong>292269055</strong></li> </ul> <p>But what about the year 292278994?</p>
[ { "answer_id": 36242, "author": "rmmh", "author_id": 3694, "author_profile": "https://Stackoverflow.com/users/3694", "pm_score": -1, "selected": false, "text": "<p>By 2038, time libraries should all be using 64-bit integers, so this won't actually be that big of a deal (on software that ...
2008/08/30
[ "https://Stackoverflow.com/questions/36239", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
I would like to think that some of the software I'm writing today will be used in 30 years. But I am also aware that a lot of it is based upon the UNIX tradition of exposing time as the number of seconds since 1970. ```c #include <stdio.h> #include <time.h> #include <limits.h> void print(time_t rt) { struct tm * t = gmtime(&rt); puts(asctime(t)); } int main() { print(0); print(time(0)); print(LONG_MAX); print(LONG_MAX+1); } ``` Execution results in: * Thu Jan 1 00:00:00 1970 * Sat Aug 30 18:37:08 2008 * Tue Jan 19 03:14:07 **2038** * Fri Dec 13 20:45:52 **1901** > > > > > > The functions ctime(), gmtime(), and localtime() all take as an argument a time value representing the time in seconds since the Epoch (00:00:00 UTC, January 1, 1970; see time(3) ). > > > > > > > > > I wonder if there is anything proactive to do in this area as a programmer, or are we to trust that all software systems (aka Operating Systems) will some how be magically upgraded in the future? **Update** It would seem that indeed 64-bit systems are safe from this: ```java import java.util.*; class TimeTest { public static void main(String[] args) { print(0); print(System.currentTimeMillis()); print(Long.MAX_VALUE); print(Long.MAX_VALUE + 1); } static void print(long l) { System.out.println(new Date(l)); } } ``` * Wed Dec 31 16:00:00 PST 1969 * Sat Aug 30 12:02:40 PDT 2008 * Sat Aug 16 23:12:55 PST **292278994** * Sun Dec 02 08:47:04 PST **292269055** But what about the year 292278994?
I have written portable replacement for time.h (currently just localtime(), gmtime(), mktime() and timegm()) which uses 64 bit time even on 32 bit machines. It is intended to be dropped into C projects as a replacement for time.h. It is being used in Perl and I intend to fix Ruby and Python's 2038 problems with it as well. This gives you a safe range of +/- 292 million years. You can find the code [at the y2038 project](https://github.com/schwern/y2038). Please feel free to post any questions to the [issue tracker](https://github.com/schwern/y2038/issues). As to the "this isn't going to be a problem for another 29 years", peruse this [list of standard answers](https://github.com/schwern/y2038/wiki/Why-Bother%3F) to that. In short, stuff happens in the future and sometimes you need to know when. I also have [a presentation on the problem, what is not a solution, and what is](http://www.slideshare.net/schwern/whos-afraid-of-2038-presentation). Oh, and don't forget that many time systems don't handle dates before 1970. Stuff happened before 1970, sometimes you need to know when.
36,260
<p>I'm writing an interpreter for an experimental language. Three of the main constructs of the language are definitions, statements, and expressions. Definitions can contain statements and expressions, statements can contain definitions and expressions, and one kind of expression can contain statements. I represent all of these using union types so I can easily use pattern matching on them. Ideally, I would like to put the code for these in different files, but OMake complains about circular dependency issues. As far as I know, circular type definitions across modules are not allowed.</p> <p>The only way I know of to solve this is to define all three types at once:</p> <pre><code>type defn = ... and stmt = ... and expr = ... </code></pre> <p>It seems like this requires all the code for types to be in the same file. Is there any way around this? How do you deal with circular definitions in your code?</p>
[ { "answer_id": 36527, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 5, "selected": true, "text": "<p>Recursive definitions need to appear in the same file. If you want to separate definitions, statements, and expression...
2008/08/30
[ "https://Stackoverflow.com/questions/36260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1891/" ]
I'm writing an interpreter for an experimental language. Three of the main constructs of the language are definitions, statements, and expressions. Definitions can contain statements and expressions, statements can contain definitions and expressions, and one kind of expression can contain statements. I represent all of these using union types so I can easily use pattern matching on them. Ideally, I would like to put the code for these in different files, but OMake complains about circular dependency issues. As far as I know, circular type definitions across modules are not allowed. The only way I know of to solve this is to define all three types at once: ``` type defn = ... and stmt = ... and expr = ... ``` It seems like this requires all the code for types to be in the same file. Is there any way around this? How do you deal with circular definitions in your code?
Recursive definitions need to appear in the same file. If you want to separate definitions, statements, and expressions into separate modules, you can do so using [recursive modules](http://caml.inria.fr/pub/docs/manual-ocaml/manual021.html#htoc100), but they will still need to appear in the same file. DAG-ifying inter-file dependencies is one of the annoyances of OCaml.
36,294
<p>Looks like here in StackOveflow there is a group of <strong>F#</strong> enthusiasts. </p> <p>I'd like to know better this language, so, apart from the <a href="http://en.wikipedia.org/wiki/Functional_programming" rel="noreferrer">functional programming theory</a>, can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language.</p> <p>Thanks a lot</p> <p>Andrea</p>
[ { "answer_id": 36337, "author": "Alexandru Nedelcu", "author_id": 3280, "author_profile": "https://Stackoverflow.com/users/3280", "pm_score": 1, "selected": false, "text": "<p>Check out the <a href=\"http://msdn.microsoft.com/en-gb/fsharp/default.aspx\" rel=\"nofollow noreferrer\">F# Dev...
2008/08/30
[ "https://Stackoverflow.com/questions/36294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1178/" ]
Looks like here in StackOveflow there is a group of **F#** enthusiasts. I'd like to know better this language, so, apart from the [functional programming theory](http://en.wikipedia.org/wiki/Functional_programming), can you point me to the better starting points to start using the F# language? I mean, tutorials, how-tos, but first of all working samples to have the chance to start doing something and enjoy the language. Thanks a lot Andrea
Not to whore myself horribly but I wrote a couple F# overview posts on my blog [here](http://www.codegrunt.co.uk/blog/?p=58) and [here](http://www.codegrunt.co.uk/blog/?p=81). Chris Smith (guy on the F# team at MS) has an article called 'F# in 20 minutes' - [part 1](http://blogs.msdn.com/chrsmith/archive/2008/05/02/f-in-20-minutes-part-i.aspx) and [part 2](http://blogs.msdn.com/chrsmith/archive/2008/05/09/f-in-20-minutes-part-ii.aspx). Note you have to be careful as the latest CTP of F# (version 1.9.6.0) has some seriously breaking changes compared to previous versions, so some examples/tutorials out there might not work without modification. Here's a quick run-down of some cool stuff, maybe I can give you a few hints here myself which are clearly *very* brief and probably not great but hopefully gives you something to play with!:- First note - most examples on the internet will assume 'lightweight syntax' is turned on. To achieve this use the following line of code:- ``` #light ``` This prevents you from having to insert certain keywords that are present for OCaml compatibility and also having to terminate each line with semicolons. Note that using this syntax means indentation defines scope. This will become clear in later examples, all of which rely on lightweight syntax being switched on. If you're using the interactive mode you have to terminate all statements with double semi-colons, for example:- ``` > #light;; > let f x y = x + y;; val f : int -> int -> int > f 1 2;; val it : int = 3 ``` Note that interactive mode returns a 'val' result after each line. This gives important information about the definitions we are making, for example 'val f : int -> int -> int' indicates that a function which takes two ints returns an int. Note that only in interactive do we need to terminate lines with semi-colons, when actually defining F# code we are free of that :-) You define functions using the 'let' keyword. This is probably the most important keyword in all of F# and you'll be using it a lot. For example:- ``` let sumStuff x y = x + y let sumStuffTuple (x, y) = x + y ``` We can call these functions thus:- ``` sumStuff 1 2 3 sumStuffTuple (1, 2) 3 ``` Note there are two different ways of defining functions here - you can either separate parameters by whitespace or specify parameters in 'tuples' (i.e. values in parentheses separated by commas). The difference is that we can use 'partial function application' to obtain functions which take less than the required parameters using the first approach, and not with the second. E.g.:- ``` let sumStuff1 = sumStuff 1 sumStuff 2 3 ``` Note we are obtaining a function from the expression 'sumStuff 1'. When we can pass around functions just as easily as data that is referred to as the language having 'first class functions', this is a fundamental part of any functional language such as F#. Pattern matching is pretty darn cool, it's basically like a switch statement on steroids (yeah I nicked that phrase from another F#-ist :-). You can do stuff like:- ``` let someThing x = match x with | 0 -> "zero" | 1 -> "one" | 2 -> "two" | x when x < 0 -> "negative = " + x.ToString() | _ when x%2 = 0 -> "greater than two but even" | _ -> "greater than two but odd" ``` Note we use the '\_' symbol when we want to match on something but the expression we are returning does not depend on the input. We can abbreviate pattern matching using if, elif, and else statements as required:- ``` let negEvenOdd x = if x < 0 then "neg" elif x % 2 = 0 then "even" else "odd" ``` F# lists (which are implemented as linked lists underneath) can be manipulated thus:- ``` let l1 = [1;2;3] l1.[0] 1 let l2 = [1 .. 10] List.length l2 10 let squares = [for i in 1..10 -> i * i] squares [1; 4; 9; 16; 25; 36; 49; 64; 81; 100] let square x = x * x;; let squares2 = List.map square [1..10] squares2 [1; 4; 9; 16; 25; 36; 49; 64; 81; 100] let evenSquares = List.filter (fun x -> x % 2 = 0) squares evenSqares [4; 16; 36; 64; 100] ``` Note the List.map function 'maps' the square function on to the list from 1 to 10, i.e. applies the function to each element. List.filter 'filters' a list by only returning values in the list that pass the predicate function provided. Also note the 'fun x -> f' syntax - this is the F# lambda. Note that throughout we have not defined any types - the F# compiler/interpreter 'infers' types, i.e. works out what you want from usage. For example:- ``` let f x = "hi " + x ``` Here the compiler/interpreter will determine x is a string since you're performing an operation which requires x to be a string. It also determines the return type will be string as well. When there is ambiguity the compiler makes assumptions, for example:- ``` let f x y = x + y ``` Here x and y could be a number of types, but the compiler defaults to int. If you want to define types you can using type annotation:- ``` let f (x:string) y = x + y ``` Also note that we have had to enclose x:string in parentheses, we often have to do this to separate parts of a function definition. Two really useful and heavily used operators in F# are the pipe forward and function composition operators |> and >> respectively. We define |> thus:- ``` let (|>) x f = f x ``` Note that you can define operators in F#, this is pretty cool :-). This allows you to write things in a clearer way, e.g.:- ``` [1..10] |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0) ``` Will allow you to obtain the first 10 even squares. That is clearer than:- ``` List.filter (fun x -> x % 2 = 0) (List.map (fun x -> x * x) [1..10]) ``` Well, at least I think so :-) Function composition defined by the >> operator is defined as follows:- ``` let (>>) f g x = g(f(x)) ``` I.e. you forward-pipe an operation only the parameter of the first function remains unspecified. This is useful as you can do the following:- ``` let mapFilter = List.map (fun x -> x * x) >> List.filter (fun x -> x % 2 = 0) ``` Here mapFilter will accept a list an input and return the list filtered as before. It's an abbreviated version of:- ``` let mapFilter = l |> List.map (fun x -> x * x) |> List.filter (fun x -> x % 2 = 0) ``` If we want to write recursive functions we have to define the function as recursive by placing 'rec' after the let. Examples below. *Some cool stuff:-* **Factorial** ``` let rec fact x = if x <= 1 then 1 else x * fact (x-1) ``` **nth Fibonacci Number** ``` let rec fib n = if n <= 1 then n else fib (n-1) + fib (n-2) ``` **FizzBuzz** ``` let (/%) x y = x % y = 0 let fb = function | x when x /% 15 -> "FizzBuzz" | x when x /% 3 -> "Fizz" | x when x /% 5 -> "Buzz" | x -> x.ToString() [1..100] |> List.map (fb >> printfn "%s") ``` Anyway that's a *very* brief overview, hopefully it helps a little!!
36,296
<p>In <a href="http://channel9.msdn.com/posts/Dan/Countdown-to-PDC2008-By-Developers-for-Developers-Don-Box-and-Chris-Anderson/" rel="nofollow noreferrer">today's channel9.msdn.com video</a>, the PDC guys posted a challenge to decipher this code:</p> <pre><code>2973853263233233753482843823642933243283 6434928432937228939232737732732535234532 9335283373377282333349287338349365335325 3283443783243263673762933373883363333472 8936639338428833535236433333237634438833 3275387394324354374325383293375366284282 3323383643473233852922933873933663333833 9228632439434936334633337636632933333428 9285333384346333346365364364365365336367 2873353883543533683523253893663653393433 8837733538538437838338536338232536832634 8284348375376338372376377364368392352393 3883393733943693253343433882852753933822 7533337432433532332332328232332332932432 3323323323323336323333323323323327323324 2873323253233233233892792792792792792792 7934232332332332332332332733432333832336 9344372376326339329376282344 </code></pre> <p>Decipher it and win a t-shirt. (Lame, I know, was hoping for a free trip to the PDC.)</p> <p>I notice some interesting patterns in this code, such as the 332 pattern towards the end, but I'm at a loss as to where to go from here. They've said the answer is a text question.</p> <p>Any ideas on deciphering this code?</p>
[ { "answer_id": 36304, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 2, "selected": false, "text": "<p>Well, based on the 332 pattern you pointed out and the fact that the number of numbers is divisible by 3, and that severa...
2008/08/30
[ "https://Stackoverflow.com/questions/36296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
In [today's channel9.msdn.com video](http://channel9.msdn.com/posts/Dan/Countdown-to-PDC2008-By-Developers-for-Developers-Don-Box-and-Chris-Anderson/), the PDC guys posted a challenge to decipher this code: ``` 2973853263233233753482843823642933243283 6434928432937228939232737732732535234532 9335283373377282333349287338349365335325 3283443783243263673762933373883363333472 8936639338428833535236433333237634438833 3275387394324354374325383293375366284282 3323383643473233852922933873933663333833 9228632439434936334633337636632933333428 9285333384346333346365364364365365336367 2873353883543533683523253893663653393433 8837733538538437838338536338232536832634 8284348375376338372376377364368392352393 3883393733943693253343433882852753933822 7533337432433532332332328232332332932432 3323323323323336323333323323323327323324 2873323253233233233892792792792792792792 7934232332332332332332332733432333832336 9344372376326339329376282344 ``` Decipher it and win a t-shirt. (Lame, I know, was hoping for a free trip to the PDC.) I notice some interesting patterns in this code, such as the 332 pattern towards the end, but I'm at a loss as to where to go from here. They've said the answer is a text question. Any ideas on deciphering this code?
Well, based on the 332 pattern you pointed out and the fact that the number of numbers is divisible by 3, and that several of the first 3 digit groups have matches... it might be that each 3 digits represent a character. Get a distribution of the number matches for all the 3 digit groups, then see if that distribution looks like the distribution of common letters. If so, each 3 digit code could then be mapped to a character, and you might get a lot of the characters filled in for you this way, then just see if you can fill in the blanks of the less common letters that may not match the distribution perfectly. A quick google search revealed [this source for distribution of frequency](https://web.archive.org/web/20080220140738/http://www.csm.astate.edu/~rossa/datasec/frequency.html) in the English language. This, of course, may not be fruitful, but it's a good first attempt.
36,314
<p>I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)</p>
[ { "answer_id": 36321, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 11, "selected": true, "text": "<p>Currying is when you break down a function that takes multiple arguments into a series of functions that each take only ...
2008/08/30
[ "https://Stackoverflow.com/questions/36314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786/" ]
I've seen references to curried functions in several articles and blogs but I can't find a good explanation (or at least one that makes sense!)
Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument. Here's an example in JavaScript: ```js function add (a, b) { return a + b; } add(3, 4); // returns 7 ``` This is a function that takes two arguments, a and b, and returns their sum. We will now curry this function: ```js function add (a) { return function (b) { return a + b; } } ``` This is a function that takes one argument, `a`, and returns a function that takes another argument, `b`, and that function returns their sum. ```js add(3)(4); // returns 7 var add3 = add(3); // returns a function add3(4); // returns 7 ``` * The first statement returns 7, like the `add(3, 4)` statement. * The second statement defines a new function called `add3` that will add 3 to its argument. (This is what some may call a closure.) * The third statement uses the `add3` operation to add 3 to 4, again producing 7 as a result.
36,344
<p>I'm trying to "install SGML::Parser::OpenSP" from the cpan shell, but it fails on the first "make test". I also get the same error if I go into the build directory and run make test.</p> <p>I believe this bit of the output below is the relevant part. Note the Symbol not found when perl gets to the "use" line for the new library. The file listed there exists and is readable. When I run the unix command "nm" it <em>does</em> show the symbol.</p> <p>I don't know what to make of the symbol not found error. I'm not running as admin/root if that matters. This is on a mac, 10.4.11 My googling turned up some hints that this can happen if gcc is called instead of g++, but I believe that is set up correctly.</p> <p>What else could it be, and how can I try to fix?</p> <p>Here's the excerpt from running make test:</p> <pre><code>PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/01basic...........1/4 # Failed test 'use SGML::Parser::OpenSP;' # at t/01basic.t line 14. # Tried to use 'SGML::Parser::OpenSP'. # Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication # Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle # Expected in: dynamic lookup # at (eval 3) line 2 # Compilation failed in require at (eval 3) line 2. # BEGIN failed--compilation aborted at (eval 3) line 2. </code></pre>
[ { "answer_id": 36332, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": 4, "selected": true, "text": "<p>If you use the Settings for the project, you can mark each setting as either application or user.</p>\n\n<p>If they're...
2008/08/30
[ "https://Stackoverflow.com/questions/36344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to "install SGML::Parser::OpenSP" from the cpan shell, but it fails on the first "make test". I also get the same error if I go into the build directory and run make test. I believe this bit of the output below is the relevant part. Note the Symbol not found when perl gets to the "use" line for the new library. The file listed there exists and is readable. When I run the unix command "nm" it *does* show the symbol. I don't know what to make of the symbol not found error. I'm not running as admin/root if that matters. This is on a mac, 10.4.11 My googling turned up some hints that this can happen if gcc is called instead of g++, but I believe that is set up correctly. What else could it be, and how can I try to fix? Here's the excerpt from running make test: ``` PERL_DL_NONLAZY=1 /usr/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/lib', 'blib/arch')" t/*.t t/01basic...........1/4 # Failed test 'use SGML::Parser::OpenSP;' # at t/01basic.t line 14. # Tried to use 'SGML::Parser::OpenSP'. # Error: Can't load '/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle' for module SGML::Parser::OpenSP: dlopen(/Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle, 2): Symbol not found: __ZTI15SGMLApplication # Referenced from: /Users/joshgold/.cpan/build/SGML-Parser-OpenSP-0.994/blib/arch/auto/SGML/Parser/OpenSP/OpenSP.bundle # Expected in: dynamic lookup # at (eval 3) line 2 # Compilation failed in require at (eval 3) line 2. # BEGIN failed--compilation aborted at (eval 3) line 2. ```
If you use the Settings for the project, you can mark each setting as either application or user. If they're set as user, they will be stored per-user and when you call the Save method it will be updated in the config for that user. Code project has a really detailed [article](http://www.codeproject.com/KB/dotnet/user_settings.aspx) on saving all types of settings.
36,347
<p>Java has generics and C++ provides a very strong programming model with <code>template</code>s. So then, what is the difference between C++ and Java generics?</p>
[ { "answer_id": 36356, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": false, "text": "<p>C++ has templates. Java has generics, which look kinda sorta like C++ templates, but they're very, very different.</p>\n\n<p>T...
2008/08/30
[ "https://Stackoverflow.com/questions/36347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
Java has generics and C++ provides a very strong programming model with `template`s. So then, what is the difference between C++ and Java generics?
There is a big difference between them. In C++ you don't have to specify a class or an interface for the generic type. That's why you can create truly generic functions and classes, with the caveat of a looser typing. ```cpp template <typename T> T sum(T a, T b) { return a + b; } ``` The method above adds two objects of the same type, and can be used for any type T that has the "+" operator available. In Java you have to specify a type if you want to call methods on the objects passed, something like: ```java <T extends Something> T sum(T a, T b) { return a.add ( b ); } ``` In C++ generic functions/classes can only be defined in headers, since the compiler generates different functions for different types (that it's invoked with). So the compilation is slower. In Java the compilation doesn't have a major penalty, but Java uses a technique called "erasure" where the generic type is erased at runtime, so at runtime Java is actually calling ... ```java Something sum(Something a, Something b) { return a.add ( b ); } ``` Nevertheless, Java's generics help with type-safety.
36,350
<p>I have a method which takes params object[] such as:</p> <pre><code>void Foo(params object[] items) { Console.WriteLine(items[0]); } </code></pre> <p>When I pass two object arrays to this method, it works fine:</p> <pre><code>Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[] </code></pre> <p>But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:</p> <pre><code>Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[] </code></pre> <p>How do I pass a single object[] as a first argument to a params array?</p>
[ { "answer_id": 36360, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "<p>You need to encapsulate it into another object[] array, like this:</p>\n\n<pre><code>Foo(new Object[] { new object[...
2008/08/30
[ "https://Stackoverflow.com/questions/36350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
I have a method which takes params object[] such as: ``` void Foo(params object[] items) { Console.WriteLine(items[0]); } ``` When I pass two object arrays to this method, it works fine: ``` Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } ); // Output: System.Object[] ``` But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one: ``` Foo(new object[]{ (object)"1", (object)"2" }); // Output: 1, expected: System.Object[] ``` How do I pass a single object[] as a first argument to a params array?
A simple typecast will ensure the compiler knows what you mean in this case. ``` Foo((object)new object[]{ (object)"1", (object)"2" })); ``` As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree.
36,417
<p>What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code.</p> <p>I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable.</p> <p>What can I be doing better in my PHP development?</p>
[ { "answer_id": 36421, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>There's a lot that can be said on this topic but a very basic starting point would be to move as much code as possible out...
2008/08/30
[ "https://Stackoverflow.com/questions/36417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3800/" ]
What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code. I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable. What can I be doing better in my PHP development?
You don't need a "system" to do templating. You can do it on your own by keeping presentation & logic separate. This way the designer can screw up the display, but not the logic behind it. Here's a simple example: ``` <?php $people = array('derek','joel','jeff'); $people[0] = 'martin'; // all your logic goes here include 'templates/people.php'; ?> ``` Now here's the people.php file (which you give your designer): ``` <html> <body> <?php foreach($people as $name):?> <b>Person:</b> <?=$name?> <br /> <?php endforeach;?> </body> </html> ```
36,430
<p>I'm not sure of all of them, but what are the commands to do things like update Ruby, download a new gem, or update an existing gem? What other important things are there?</p> <p>Since it might matter, I'm running Windows.</p>
[ { "answer_id": 36447, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 4, "selected": false, "text": "<p>By Ruby commands you probably mean the command line programs for Ruby. These are also called Ruby Helper programs. ...
2008/08/30
[ "https://Stackoverflow.com/questions/36430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I'm not sure of all of them, but what are the commands to do things like update Ruby, download a new gem, or update an existing gem? What other important things are there? Since it might matter, I'm running Windows.
Useful command: Rake ==================== In addition to the commands listed by Joseph Pecoraro, the 'rake' command is also pretty standard when working with Ruby. Rake makes it easy to automate (simple) tasks; like building a RubyGem or running your unit tests. With rake, the only important command to remember is 'rake -T', which shows a list of rake tasks available in the current directory. Updating a Ruby gem =================== To get back to your specific question: To update a specific gem, you can do two things: simply update the gem: ``` gem update <gemname> ``` This will update the gem to the latest version. Install a Ruby gem ================== If you want to update to a specific version, you must install it: ``` gem install <gemname> -v <gemversion> ``` You can leave out the -v options. Rubygems then installs the latest version. How to help yourself ==================== Two useful gem commands to remember are: ``` gem help ``` This shows how to get help with rubygems. ``` gem help commands ``` This shows all commands available to rubygems. From here you can get more specific help on a command by using gem help: ``` gem help update ```
36,475
<p>What would be the best way to design a threaded commenting system so that it doesn't hammer the database?</p>
[ { "answer_id": 36487, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 0, "selected": false, "text": "<p>What I normally do in this case is to have a single thread that is responsible for putting the data into the databa...
2008/08/30
[ "https://Stackoverflow.com/questions/36475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1745/" ]
What would be the best way to design a threaded commenting system so that it doesn't hammer the database?
**SELECT ... START WITH ... CONNECT BY** Oracle has an extension to SELECT that allows easy tree-based retrieval. This query will traverse a table where the nesting relationship is stored in **parent** and **child** columns. ``` select * from my_table start with parent = :TOP_ARTICLE connect by prior child = parent; ``` <http://www.adp-gmbh.ch/ora/sql/connect_by.html>
36,498
<p>I would like to quickly send email from the command line. I realize there are probably a number of different ways to do this.</p> <p>I'm looking for a simple way to do this from a linux terminal (likely a bash shell but anything should do) and an alternative way to do this on Windows. I want to be able to whip up an email right on the command line or have the flexibility to pipe the message into the command line program. How would you go about doing this? If you have small scripts that would be fine as well.</p>
[ { "answer_id": 36499, "author": "aryeh", "author_id": 3288, "author_profile": "https://Stackoverflow.com/users/3288", "pm_score": 4, "selected": false, "text": "<pre><code>$ echo \"This is the email body\" | mail -s \"This is the subject\" me@email.com\n</code></pre>\n\n<p>Alternatively:...
2008/08/31
[ "https://Stackoverflow.com/questions/36498", "https://Stackoverflow.com", "https://Stackoverflow.com/users/792/" ]
I would like to quickly send email from the command line. I realize there are probably a number of different ways to do this. I'm looking for a simple way to do this from a linux terminal (likely a bash shell but anything should do) and an alternative way to do this on Windows. I want to be able to whip up an email right on the command line or have the flexibility to pipe the message into the command line program. How would you go about doing this? If you have small scripts that would be fine as well.
You can use mail: ``` $mail -s <subject> <recipients> ``` You then type your message and end it with a line that has only a period. This signals you are done and sends the message. You can also pipe your email in from STDIN and it will be sent as the text of an email: ``` $<mail-generating-program> | mail -s <subject> <recipients> ``` One small note with this approach - unless your computer is connected to the internet and your DNS settings are set properly, you won't be able to receive replies to your message. For a more robust command-line program you can link to your POP or IMAP email account, check out either [pine](http://www.washington.edu/pine/) or [mutt](http://www.mutt.org/).
36,502
<p>I know Windows Vista (and XP) cache recently loaded DLL's in memory...</p> <p>How can this be disabled via the command prompt?</p>
[ { "answer_id": 36529, "author": "The How-To Geek", "author_id": 291, "author_profile": "https://Stackoverflow.com/users/291", "pm_score": 4, "selected": true, "text": "<p>The only thing you can do is disable SuperFetch, which can be done from the command prompt with this command (there h...
2008/08/31
[ "https://Stackoverflow.com/questions/36502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
I know Windows Vista (and XP) cache recently loaded DLL's in memory... How can this be disabled via the command prompt?
The only thing you can do is disable SuperFetch, which can be done from the command prompt with this command (there has to be a space between the = sign and disabled). ``` sc config Superfetch start= disabled ``` There is a myth out there that you can disable DLL caching, but that only worked for systems prior to Windows 2000. [[source](http://msdn.microsoft.com/en-us/library/bb776795.aspx)]
36,511
<p>I'm attempting to create a dataset based on the properties of an object. For example, I have an instance of a Person class with properties including ID, Forename, Surname, DOB etc. Using reflection, I'm adding columns to a new dataset based on the object properties:</p> <pre><code>For Each pi As PropertyInfo In person.GetType().GetProperties() Dim column As New DataColumn(pi.Name, pi.PropertyType) table.Columns.Add(column) Next </code></pre> <p>My problem is that some of those properies are nullable types which aren't supported by datasets. Is there any way to extract the underlying system type from a nullable type?</p> <p>Thanks.</p>
[ { "answer_id": 36519, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 1, "selected": false, "text": "<p>I'm guessing that the problem is recognizing whether the property is nullable or not. In C# you do this with this code...
2008/08/31
[ "https://Stackoverflow.com/questions/36511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm attempting to create a dataset based on the properties of an object. For example, I have an instance of a Person class with properties including ID, Forename, Surname, DOB etc. Using reflection, I'm adding columns to a new dataset based on the object properties: ``` For Each pi As PropertyInfo In person.GetType().GetProperties() Dim column As New DataColumn(pi.Name, pi.PropertyType) table.Columns.Add(column) Next ``` My problem is that some of those properies are nullable types which aren't supported by datasets. Is there any way to extract the underlying system type from a nullable type? Thanks.
Here's your answer, in VB. This may be overkill for your purposes, but it also might be useful to some other folks. First off, here's the code to find out if you're dealing with a Nullable type: ``` Private Function IsNullableType(ByVal myType As Type) As Boolean Return (myType.IsGenericType) AndAlso (myType.GetGenericTypeDefinition() Is GetType(Nullable(Of ))) End Function ``` Note the unusual syntax in the GetType. It's necessary. Just doing GetType(Nullable) as one of the commentors suggested did not work for me. So, armed with that, you can do something like this... Here, in an ORM tool, I am trying to get values into a generic type that may or not be Nullable: ``` If (Not value Is Nothing) AndAlso IsNullableType(GetType(T)) Then Dim UnderlyingType As Type = Nullable.GetUnderlyingType(GetType(T)) Me.InnerValue = Convert.ChangeType(value, UnderlyingType) Else Me.InnerValue = value End If ``` Note that I check for Nothing in the first line because Convert.ChangeType will choke on it... You may not have that problem, but my situation is extremely open-ended. Hopefully if I didn't answer your question directly, you can cannibalize this and get you where you need to go - but I just implemented this moments ago, and my tests are all passing.
36,515
<p>I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized. </p> <p>I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a <code><a href="http://code.google.com/apis/maps/documentation/reference.html#GScreenOverlay" rel="nofollow noreferrer">GScreenOverlay</a></code> class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized?</p>
[ { "answer_id": 36821, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 2, "selected": false, "text": "<p>I would use HTML like the following:</p>\n\n<pre><code>&lt;div id=\"wrapper\"&gt;\n &lt;div id=\"map\" style=\"width:400px;h...
2008/08/31
[ "https://Stackoverflow.com/questions/36515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1482/" ]
I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized. I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a `[GScreenOverlay](http://code.google.com/apis/maps/documentation/reference.html#GScreenOverlay)` class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized?
You can add your own Custom Control and use it as a legend. This code will add a box 150w x 100h (Gray Border/ with White Background) and the words "Hello World" inside of it. You swap out the text for any HTML you would like in the legend. This will stay Anchored to the Top Right (G\_ANCHOR\_TOP\_RIGHT) 10px down and 50px over of the map. ``` function MyPane() {} MyPane.prototype = new GControl; MyPane.prototype.initialize = function(map) { var me = this; me.panel = document.createElement("div"); me.panel.style.width = "150px"; me.panel.style.height = "100px"; me.panel.style.border = "1px solid gray"; me.panel.style.background = "white"; me.panel.innerHTML = "Hello World!"; map.getContainer().appendChild(me.panel); return me.panel; }; MyPane.prototype.getDefaultPosition = function() { return new GControlPosition( G_ANCHOR_TOP_RIGHT, new GSize(10, 50)); //Should be _ and not &#95; }; MyPane.prototype.getPanel = function() { return me.panel; } map.addControl(new MyPane()); ```
36,563
<p>I'm writing a simple app that's going to have a tiny form sitting in one corner of the screen, updating itself.</p> <p>I'd really love for that form to be transparent and to have the transparency be user-configurable.</p> <p>Is there any easy way to achieve this?</p>
[ { "answer_id": 36576, "author": "Eric Haskins", "author_id": 100, "author_profile": "https://Stackoverflow.com/users/100", "pm_score": 0, "selected": false, "text": "<p>You can set the <code>Form.Opacity</code> property. It should do what you want.</p>\n" }, { "answer_id": 36577,...
2008/08/31
[ "https://Stackoverflow.com/questions/36563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ]
I'm writing a simple app that's going to have a tiny form sitting in one corner of the screen, updating itself. I'd really love for that form to be transparent and to have the transparency be user-configurable. Is there any easy way to achieve this?
You could try using the [Opacity](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.opacity.aspx) property of the Form. Here's the relevant snippet from the MSDN page: ``` private Sub CreateMyOpaqueForm() ' Create a new form. Dim form2 As New Form() ' Set the text displayed in the caption. form2.Text = "My Form" ' Set the opacity to 75%. form2.Opacity = 0.75 ' Size the form to be 300 pixels in height and width. form2.Size = New Size(300, 300) ' Display the form in the center of the screen. form2.StartPosition = FormStartPosition.CenterScreen ' Display the form as a modal dialog box. form2.ShowDialog() End Sub ```
36,567
<p>I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys.</p>
[ { "answer_id": 36588, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 2, "selected": false, "text": "<p>Check out <a href=\"http://frinika.sourceforge.net/\" rel=\"nofollow noreferrer\">Frinika</a>. It's a full-featured mus...
2008/08/31
[ "https://Stackoverflow.com/questions/36567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys.
1. This problem is basically about mapping functions to arrays of numbers. A language that supports first-class functions would come in really handy here. 2. Check out <http://www.harmony-central.com/Computer/Programming> and <http://www.developer.com/java/other/article.php/3071021> for some Java-related info. 3. If you don't know the basic concepts of encoding sound data, then read <http://en.wikipedia.org/wiki/Sampling_rate> 4. The canonical WAVE format is very simple, see <http://www.lightlink.com/tjweber/StripWav/Canon.html>. A header (first 44 bytes) + the wave-data. You don't need any library to implement that. In C/C++, the corresponding data structure would look something like this: ```cpp typedef struct _WAVstruct { char headertag[4]; unsigned int remnantlength; char fileid[4]; char fmtchunktag[4]; unsigned int fmtlength; unsigned short fmttag; unsigned short channels; unsigned int samplerate; unsigned int bypse; unsigned short ba; unsigned short bipsa; char datatag[4]; unsigned int datalength; void* data; //<--- that's where the raw sound-data goes }* WAVstruct; ``` I'm not sure about Java. I guess you'll have to substitute "struct" with "class" and "void\* data" with "char[] data" or "short[] data" or "int[] data", corresponding to the number of bits per sample, as defined in the field bipsa. To fill it with data, you would use something like that in C/C++: ```cpp int data2WAVstruct(unsigned short channels, unsigned short bipsa, unsigned int samplerate, unsigned int datalength, void* data, WAVstruct result) { result->headertag[0] = 'R'; result->headertag[1] = 'I'; result->headertag[2] = 'F'; result->headertag[3] = 'F'; result->remnantlength = 44 + datalength - 8; result->fileid[0] = 'W'; result->fileid[1] = 'A'; result->fileid[2] = 'V'; result->fileid[3] = 'E'; result->fmtchunktag[0] = 'f'; result->fmtchunktag[1] = 'm'; result->fmtchunktag[2] = 't'; result->fmtchunktag[3] = ' '; result->fmtlength = 0x00000010; result->fmttag = 1; result->channels = channels; result->samplerate = samplerate; result->bipsa = bipsa; result->ba = channels*bipsa / 8; result->bypse = samplerate*result->ba; result->datatag[0] = 'd'; result->datatag[1] = 'a'; result->datatag[2] = 't'; result->datatag[3] = 'a'; result->datalength = datalength; result->data = data; // <--- that's were the data comes in return 0; // an error code, not implemented, yet ...; in Java: return result } ``` Again, I'm not sure about Java but the conversion should be straightforward if you convert the void-pointer to an array corresponding to the bitrate. Then simply write the entire structure to a file to get a playable wave file.
36,608
<p>I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set.</p> <p>Something like:</p> <pre><code>Record.find(:all).date.unique.count </code></pre> <p>but of course, that doesn't seem to work.</p>
[ { "answer_id": 36618, "author": "Natalie Weizenbaum", "author_id": 2518, "author_profile": "https://Stackoverflow.com/users/2518", "pm_score": 7, "selected": true, "text": "<p>What you're going for is the following SQL:</p>\n\n<pre><code>SELECT COUNT(DISTINCT date) FROM records\n</code><...
2008/08/31
[ "https://Stackoverflow.com/questions/36608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3764/" ]
I have a record set that includes a date field, and want to determine how many unique dates are represented in the record set. Something like: ``` Record.find(:all).date.unique.count ``` but of course, that doesn't seem to work.
What you're going for is the following SQL: ``` SELECT COUNT(DISTINCT date) FROM records ``` ActiveRecord has this built in: ``` Record.count('date', :distinct => true) ```
36,621
<p>I'm taking the leap: my PHP scripts will ALL fail gracefully!</p> <p>At least, that's what I'm hoping for...`</p> <p>I don't want to wrap (practically) every single line in <code>try...catch</code> statements, so I think my best bet is to make a custom error handler for the beginning of my files.</p> <p>I'm testing it out on a practice page:</p> <pre><code>function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.&lt;br /&gt;"; echo "The function that caused the error says $message.&lt;br /&gt;"; die(); } set_error_handler("customError"); echo($imAFakeVariable); </code></pre> <p>This works fine, returning:</p> <blockquote> <p>Sorry, an error has occurred on line 17. The function that caused the error says Undefined variable: imAFakeVariable.</p> </blockquote> <p>However, this setup doesn't work for undefined functions.</p> <pre><code>function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.&lt;br /&gt;"; echo "The function that caused the error says $message.&lt;br /&gt;"; die(); } set_error_handler("customError"); imAFakeFunction(); </code></pre> <p>This returns:</p> <blockquote> <p>Fatal error: Call to undefined function: imafakefunction() in /Library/WebServer/Documents/experimental/errorhandle.php on line 17</p> </blockquote> <p>Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause?</p>
[ { "answer_id": 36625, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Why isn't my custom error handler catching undefinedd functions? Are there other problems that this ...
2008/08/31
[ "https://Stackoverflow.com/questions/36621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
I'm taking the leap: my PHP scripts will ALL fail gracefully! At least, that's what I'm hoping for...` I don't want to wrap (practically) every single line in `try...catch` statements, so I think my best bet is to make a custom error handler for the beginning of my files. I'm testing it out on a practice page: ``` function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die(); } set_error_handler("customError"); echo($imAFakeVariable); ``` This works fine, returning: > > Sorry, an error has occurred on line 17. The function that caused the > error says Undefined variable: imAFakeVariable. > > > However, this setup doesn't work for undefined functions. ``` function customError($level,$message,$file,$line,$context) { echo "Sorry, an error has occured on line $line.<br />"; echo "The function that caused the error says $message.<br />"; die(); } set_error_handler("customError"); imAFakeFunction(); ``` This returns: > > Fatal error: Call to undefined function: imafakefunction() in > /Library/WebServer/Documents/experimental/errorhandle.php on line 17 > > > Why isn't my custom error handler catching undefined functions? Are there other problems that this will cause?
`set_error_handler` is designed to handle errors with codes of: `E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE`. This is because `set_error_handler` is meant to be a method of reporting errors thrown by the *user* error function `trigger_error`. However, I did find this comment in the manual that may help you: > > "The following error types cannot be handled with a user defined function: `E_ERROR`, `E_PARSE`, `E_CORE_ERROR`, `E_CORE_WARNING`, `E_COMPILE_ERROR`, `E_COMPILE_WARNING`, and most of `E_STRICT` raised in the file where `set_error_handler()` is called." > > > This is not exactly true. `set_error_handler()` can't handle them, but `ob_start()` can handle at least `E_ERROR`. > > > > ``` > <?php > > function error_handler($output) > { > $error = error_get_last(); > $output = ""; > foreach ($error as $info => $string) > $output .= "{$info}: {$string}\n"; > return $output; > } > > ob_start('error_handler'); > > will_this_undefined_function_raise_an_error(); > > ?> > > ``` > > Really though these errors should be silently reported in a file, for example. Hopefully you won't have many `E_PARSE` errors in your project! :-) As for general error reporting, stick with Exceptions (I find it helpful to make them tie in with my MVC system). You can build a pretty versatile Exception to provide options via buttons and add plenty of description to let the user know what's wrong.
36,636
<p>I asked a question about Currying and closures were mentioned. What is a closure? How does it relate to currying?</p>
[ { "answer_id": 36639, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 7, "selected": false, "text": "<p>I'll give an example (in JavaScript):</p>\n<pre class=\"lang-js prettyprint-override\"><code>function makeCounter () {\n...
2008/08/31
[ "https://Stackoverflow.com/questions/36636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3786/" ]
I asked a question about Currying and closures were mentioned. What is a closure? How does it relate to currying?
Variable scope -------------- When you declare a local variable, that variable has a scope. Generally, local variables exist only within the block or function in which you declare them. ```js function() { var a = 1; console.log(a); // works } console.log(a); // fails ``` If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope. ```js var a = 1; function() { console.log(a); // works } console.log(a); // works ``` When a block or function is done with, its local variables are no longer needed and are usually blown out of memory. This is how we normally expect things to work. A closure is a persistent local variable scope ---------------------------------------------- A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block. Languages which support closure (such as JavaScript, Swift, and Ruby) will allow you to keep a reference to a scope (including its parent scopes), even after the block in which those variables were declared has finished executing, provided you keep a reference to that block or function somewhere. The scope object and all its local variables are tied to the function and will persist as long as that function persists. This gives us function portability. We can expect any variables that were in scope when the function was first defined to still be in scope when we later call the function, even if we call the function in a completely different context. For example ----------- Here's a really simple example in JavaScript that illustrates the point: ```js outer = function() { var a = 1; var inner = function() { console.log(a); } return inner; // this returns a function } var fnc = outer(); // execute outer to get inner fnc(); ``` Here I have defined a function within a function. The inner function gains access to all the outer function's local variables, including `a`. The variable `a` is in scope for the inner function. Normally when a function exits, all its local variables are blown away. However, if we return the inner function and assign it to a variable `fnc` so that it persists after `outer` has exited, **all of the variables that were in scope when `inner` was defined also persist**. The variable `a` has been closed over -- it is within a closure. Note that the variable `a` is totally private to `fnc`. This is a way of creating private variables in a functional programming language such as JavaScript. As you might be able to guess, when I call `fnc()` it prints the value of `a`, which is "1". In a language without closure, the variable `a` would have been garbage collected and thrown away when the function `outer` exited. Calling fnc would have thrown an error because `a` no longer exists. In JavaScript, the variable `a` persists because the variable scope is created when the function is first declared and persists for as long as the function continues to exist. `a` belongs to the scope of `outer`. The scope of `inner` has a parent pointer to the scope of `outer`. `fnc` is a variable which points to `inner`. `a` persists as long as `fnc` persists. `a` is within the closure. Further reading (watching) -------------------------- I made a [YouTube video](https://www.youtube.com/watch?v=2cRjcXwsG0I) looking at this code with some practical examples of usage.
36,656
<p>I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains <code>ASCII art</code> and whatnot that I would like to preserve. When I print out the string on the <code>HTML page</code>, even if it does have the same formatting and everything since it is in <code>HTML</code>, the spacing and line breaks are not preserved. What is the best way to print out the text in <code>HTML</code> exactly as it was in the original text file?<br> I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P<br> Basically, I would like suggestions on how to display <code>ASCII art in HTML</code>.</p>
[ { "answer_id": 36657, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 3, "selected": false, "text": "<p>When you print the data use <a href=\"http://www.php.net/manual/en/function.nl2br.php\" rel=\"noreferrer\"><code>nl2br()</...
2008/08/31
[ "https://Stackoverflow.com/questions/36656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831/" ]
I'm parsing text from a file and storing it in a string. The problem is that some of the text in the original files contains `ASCII art` and whatnot that I would like to preserve. When I print out the string on the `HTML page`, even if it does have the same formatting and everything since it is in `HTML`, the spacing and line breaks are not preserved. What is the best way to print out the text in `HTML` exactly as it was in the original text file? I would like to give an example, but unfortunately, I was not able to get it to display correctly in this markdown editor :P Basically, I would like suggestions on how to display `ASCII art in HTML`.
use the <pre> tag (pre formatted), that will use a mono spaced font (for your art) and keep all the white space ``` <pre> text goes here and here and here and here Some out here ▄ ▄█▄ █▄ ▄ ▄█▀█▓ ▄▓▀▀█▀ ▀▀▀█▓▀▀ ▀▀ ▄█▀█▓▀▀▀▀▀▓▄▀██▀▀ ██ ██ ▀██▄▄ ▄█ ▀ ░▒ ░▒ ██ ██ ▄█▄ █▀ ██ █▓▄▀██ ▄ ▀█▌▓█ ▒▓ ▒▓ █▓▄▀██ ▓█ ▀▄ █▓ █▒ █▓ ██▄▓▀ ▀█▄▄█▄▓█ ▓█ █▒ █▓ ▒█ ▓█▄ ▒ ▀▒ ▀ ▀ █▀ ▀▒ ▀ █▀ ░ </pre> ``` You might have to convert any <'s to &lt; 's
36,701
<p>Is it completely against the Java way to create struct like objects?</p> <pre><code>class SomeData1 { public int x; public int y; } </code></pre> <p>I can see a class with accessors and mutators being more Java like.</p> <pre><code>class SomeData2 { int getX(); void setX(int x); int getY(); void setY(int y); private int x; private int y; } </code></pre> <p>The class from the first example is notationally convenient.</p> <pre><code>// a function in a class public int f(SomeData1 d) { return (3 * d.x) / d.y; } </code></pre> <p>This is not as convenient.</p> <pre><code>// a function in a class public int f(SomeData2 d) { return (3 * d.getX()) / d.getY(); } </code></pre>
[ { "answer_id": 36702, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 1, "selected": false, "text": "<p>I don't see the harm if you know that it's always going to be a simple struct and that you're never going to want to a...
2008/08/31
[ "https://Stackoverflow.com/questions/36701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3836/" ]
Is it completely against the Java way to create struct like objects? ``` class SomeData1 { public int x; public int y; } ``` I can see a class with accessors and mutators being more Java like. ``` class SomeData2 { int getX(); void setX(int x); int getY(); void setY(int y); private int x; private int y; } ``` The class from the first example is notationally convenient. ``` // a function in a class public int f(SomeData1 d) { return (3 * d.x) / d.y; } ``` This is not as convenient. ``` // a function in a class public int f(SomeData2 d) { return (3 * d.getX()) / d.getY(); } ```
This is a commonly discussed topic. The drawback of creating public fields in objects is that you have no control over the values that are set to it. In group projects where there are many programmers using the same code, it's important to avoid side effects. Besides, sometimes it's better to return a copy of field's object or transform it somehow etc. You can mock such methods in your tests. If you create a new class you might not see all possible actions. It's like defensive programming - someday getters and setters may be helpful, and it doesn't cost a lot to create/use them. So they are sometimes useful. In practice, most fields have simple getters and setters. A possible solution would look like this: ``` public property String foo; a->Foo = b->Foo; ``` *Update: It's highly unlikely that property support will be added in Java 7 or perhaps ever. Other JVM languages like Groovy, Scala, etc do support this feature now. - Alex Miller*
36,707
<p>Are there good reasons why it's a better practice to have only one return statement in a function? </p> <p>Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?</p>
[ { "answer_id": 36711, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 3, "selected": false, "text": "<p>I would say you should have as many as required, or any that make the code cleaner (such as <a href=\"http://www.refactor...
2008/08/31
[ "https://Stackoverflow.com/questions/36707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/381/" ]
Are there good reasons why it's a better practice to have only one return statement in a function? Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?
I often have several statements at the start of a method to return for "easy" situations. For example, this: ```java public void DoStuff(Foo foo) { if (foo != null) { ... } } ``` ... can be made more readable (IMHO) like this: ```java public void DoStuff(Foo foo) { if (foo == null) return; ... } ``` So yes, I think it's fine to have multiple "exit points" from a function/method.
36,733
<p>I am working on a project management web application. The user has a variety of ways to display a list of tasks. When viewing a list page, they click on task and are redirected to the task edit page. </p> <p>Since they are coming from a variety of ways, I am just curious as to the <strong>best</strong> way to <strong>redirect</strong> the user back to the calling page. I have some ideas, but would like to get other developers input.</p> <p>Would you store the <strong>calling</strong> url in session? as a cookie? I like the concept of using an object <strong>handle</strong> the redirection.</p>
[ { "answer_id": 36735, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<p>I personally would store the required redirection info in an object and handle globally. I would avoid using a QueryStrin...
2008/08/31
[ "https://Stackoverflow.com/questions/36733", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
I am working on a project management web application. The user has a variety of ways to display a list of tasks. When viewing a list page, they click on task and are redirected to the task edit page. Since they are coming from a variety of ways, I am just curious as to the **best** way to **redirect** the user back to the calling page. I have some ideas, but would like to get other developers input. Would you store the **calling** url in session? as a cookie? I like the concept of using an object **handle** the redirection.
I would store the referring URL using the [ViewState](http://msdn.microsoft.com/en-us/library/system.web.ui.control.viewstate.aspx). Storing this outside the scope of the page (i.e. in the Session state or cookie) may cause problems if more than one browser window is open. The example below validates that the page was called internally (i.e. not requested directly) and bounces back to the referring page after the user submits their response. ``` public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Request.UrlReferrer == null) { //Handle the case where the page is requested directly throw new Exception("This page has been called without a referring page"); } if (!IsPostBack) { ReturnUrl = Request.UrlReferrer.PathAndQuery; } } public string ReturnUrl { get { return ViewState["returnUrl"].ToString(); } set { ViewState["returnUrl"] = value; } } protected void btn_Click(object sender, EventArgs e) { //Do what you need to do to save the page //... //Go back to calling page Response.Redirect(ReturnUrl, true); } } ```
36,742
<p>My GPS logger occassionally leaves "unfinished" lines at the end of the log files. I think they're only at the end, but I want to check all lines just in case. </p> <p>A sample complete sentence looks like:</p> <pre><code>$GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76 </code></pre> <p>The line should start with a <code>$</code> sign, and end with an <code>*</code> and a two character hex checksum. I don't care if the checksum is correct, just that it's present. It also needs to ignore "ADVER" sentences which don't have the checksum and are at the start of every file.</p> <p>The following Python code might work: </p> <pre><code>import re from path import path nmea = re.compile("^\$.+\*[0-9A-F]{2}$") for log in path("gpslogs").files("*.log"): for line in log.lines(): if not nmea.match(line) and not "ADVER" in line: print "%s\n\t%s\n" % (log, line) </code></pre> <p>Is there a way to do that with <code>grep</code> or <code>awk</code> or something simple? I haven't really figured out how to get <code>grep</code> to do what I want.</p> <p><strong>Update</strong>: Thanks @Motti and @Paul, I was able to get the following to do almost what I wanted, but had to use single quotes and remove the trailing <code>$</code> before it would work:</p> <pre><code>grep -nvE '^\$.*\*[0-9A-F]{2}' *.log | grep -v ADVER | grep -v ADPMB </code></pre> <p>Two further questions arise, how can I make it ignore blank lines? And can I combine the last two <code>grep</code>s?</p>
[ { "answer_id": 36779, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 2, "selected": false, "text": "<p>The minimum of testing shows that this should do it:</p>\n\n<pre><code>grep -Ev \"^\\$.*\\*[0-9A-Fa-f]{2}$\" a.txt | grep -v...
2008/08/31
[ "https://Stackoverflow.com/questions/36742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3715/" ]
My GPS logger occassionally leaves "unfinished" lines at the end of the log files. I think they're only at the end, but I want to check all lines just in case. A sample complete sentence looks like: ``` $GPRMC,005727.000,A,3751.9418,S,14502.2569,E,0.00,339.17,210808,,,A*76 ``` The line should start with a `$` sign, and end with an `*` and a two character hex checksum. I don't care if the checksum is correct, just that it's present. It also needs to ignore "ADVER" sentences which don't have the checksum and are at the start of every file. The following Python code might work: ``` import re from path import path nmea = re.compile("^\$.+\*[0-9A-F]{2}$") for log in path("gpslogs").files("*.log"): for line in log.lines(): if not nmea.match(line) and not "ADVER" in line: print "%s\n\t%s\n" % (log, line) ``` Is there a way to do that with `grep` or `awk` or something simple? I haven't really figured out how to get `grep` to do what I want. **Update**: Thanks @Motti and @Paul, I was able to get the following to do almost what I wanted, but had to use single quotes and remove the trailing `$` before it would work: ``` grep -nvE '^\$.*\*[0-9A-F]{2}' *.log | grep -v ADVER | grep -v ADPMB ``` Two further questions arise, how can I make it ignore blank lines? And can I combine the last two `grep`s?
The minimum of testing shows that this should do it: ``` grep -Ev "^\$.*\*[0-9A-Fa-f]{2}$" a.txt | grep -v ADVER ``` * -E use extended regexp * -v Show lines that do **not** match * ^ starts with * .\* anything * \\* an asterisk * [0-9A-Fa-f] hexadecimal digit * {2} exactly two of the previous * $ end of line * | `grep -v ADVER` weed out the ADVER lines HTH, Motti.
36,748
<p>What's the best way to asynchronously load an BitmapImage in C# using WPF? </p>
[ { "answer_id": 36757, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>Assuming you're using data binding, setting <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.binding.isas...
2008/08/31
[ "https://Stackoverflow.com/questions/36748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3837/" ]
What's the best way to asynchronously load an BitmapImage in C# using WPF?
I was just looking into this and had to throw in my two cents, though a few years after the original post (just in case any one else comes looking for this same thing I was looking into). I have an **Image** control that needs to have it's image loaded in the background using a **Stream**, and then displayed. The problem that I kept running into is that the **BitmapSource**, it's **Stream** source and the **Image** control all had to be on the same thread. In this case, using a Binding and setting it's IsAsynch = true will throw a cross thread exception. A BackgroundWorker is great for WinForms, and you can use this in WPF, but I prefer to avoid using the WinForm assemblies in WPF (bloating of a project is not recommended, and it's a good rule of thumb too). This should throw an invalid cross reference exception in this case too, but I didn't test it. Turns out that one line of code will make any of these work: ``` //Create the image control Image img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch}; //Create a seperate thread to load the image ThreadStart thread = delegate { //Load the image in a seperate thread BitmapImage bmpImage = new BitmapImage(); MemoryStream ms = new MemoryStream(); //A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(@"C:\ImageFileName.jpg", FileMode.Open); MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms); bmpImage.BeginInit(); bmpImage.StreamSource = ms; bmpImage.EndInit(); //**THIS LINE locks the BitmapImage so that it can be transported across threads!! bmpImage.Freeze(); //Call the UI thread using the Dispatcher to update the Image control Dispatcher.BeginInvoke(new ThreadStart(delegate { img.Source = bmpImage; img.Unloaded += delegate { ms.Close(); ms.Dispose(); }; grdImageContainer.Children.Add(img); })); }; //Start previously mentioned thread... new Thread(thread).Start(); ```
36,760
<p>I have three tables: page, attachment, page-attachment</p> <p>I have data like this:</p> <pre><code>page ID NAME 1 first page 2 second page 3 third page 4 fourth page attachment ID NAME 1 foo.word 2 test.xsl 3 mm.ppt page-attachment ID PAGE-ID ATTACHMENT-ID 1 2 1 2 2 2 3 3 3 </code></pre> <p>I would like to get the number of attachments per page <strong>also when that number is 0</strong>. I have tried with: </p> <pre><code>select page.name, count(page-attachment.id) as attachmentsnumber from page inner join page-attachment on page.id=page-id group by page.id </code></pre> <p>I am getting this output: </p> <pre><code>NAME ATTACHMENTSNUMBER second page 2 third page 1 </code></pre> <p>I would like to get this output:</p> <pre><code>NAME ATTACHMENTSNUMBER first page 0 second page 2 third page 1 fourth page 0 </code></pre> <p>How do I get the 0 part?</p>
[ { "answer_id": 36762, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "<p>Change your \"inner join\" to a \"left outer join\", which means \"get me all the rows on the left of the join, even if...
2008/08/31
[ "https://Stackoverflow.com/questions/36760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I have three tables: page, attachment, page-attachment I have data like this: ``` page ID NAME 1 first page 2 second page 3 third page 4 fourth page attachment ID NAME 1 foo.word 2 test.xsl 3 mm.ppt page-attachment ID PAGE-ID ATTACHMENT-ID 1 2 1 2 2 2 3 3 3 ``` I would like to get the number of attachments per page **also when that number is 0**. I have tried with: ``` select page.name, count(page-attachment.id) as attachmentsnumber from page inner join page-attachment on page.id=page-id group by page.id ``` I am getting this output: ``` NAME ATTACHMENTSNUMBER second page 2 third page 1 ``` I would like to get this output: ``` NAME ATTACHMENTSNUMBER first page 0 second page 2 third page 1 fourth page 0 ``` How do I get the 0 part?
Change your "inner join" to a "left outer join", which means "get me all the rows on the left of the join, even if there isn't a matching row on the right." ``` select page.name, count(page-attachment.id) as attachmentsnumber from page left outer join page-attachment on page.id=page-id group by page.name ```
36,806
<p>I have been sold on mod_wsgi and apache rather than mod_python. I have all the parts installed (django, apache, mod_wsgi) but have run into a problem deploying.</p> <p>I am on osx 10.5 with apache 2.2 and django 1.0b2, mod_wsgi-2.3</p> <p>My application is called tred.</p> <p>Here are the relevant files: httpd-vhosts (included in httpd-conf)</p> <pre> NameVirtualHost tred:80 ServerName tred Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media Order allow,deny Allow from all Alias /media /Users/dmg/Sites/tred/media Order allow,deny Allow from all Alias / /Users/dmg/Sites/tred/ Order allow,deny Allow from all WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10 WSGIProcessGroup tred </pre> <p>mod_wsgi-handle.wsgi</p> <pre> import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </pre> <p>When I go to <a href="http://tred" rel="noreferrer">http://tred</a> I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work?</p>
[ { "answer_id": 37009, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "<p>What happens if you remove the <code>Alias /</code> directive?</p>\n" }, { "answer_id": 37218, "author": ...
2008/08/31
[ "https://Stackoverflow.com/questions/36806", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3431280/" ]
I have been sold on mod\_wsgi and apache rather than mod\_python. I have all the parts installed (django, apache, mod\_wsgi) but have run into a problem deploying. I am on osx 10.5 with apache 2.2 and django 1.0b2, mod\_wsgi-2.3 My application is called tred. Here are the relevant files: httpd-vhosts (included in httpd-conf) ``` NameVirtualHost tred:80 ServerName tred Alias /admin_media /usr/lib/python2.5/site-packages/django/contrib/admin/media Order allow,deny Allow from all Alias /media /Users/dmg/Sites/tred/media Order allow,deny Allow from all Alias / /Users/dmg/Sites/tred/ Order allow,deny Allow from all WSGIScriptAlias / /Users/dmg/Sites/tred/mod_wsgi-handler.wsgi WSGIDaemonProcess tred user=dmg group=staff processes=1 threads=10 WSGIProcessGroup tred ``` mod\_wsgi-handle.wsgi ``` import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') os.environ['DJANGO_SETTINGS_MODULE'] = 'tred.settings' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() ``` When I go to <http://tred> I get a directory listing rather than the rendered website. I think I have followed the tutorials correctly but it is obviously not right. What can I do to make this work?
What happens if you remove the `Alias /` directive?
36,812
<p>Currently, I am writing up a bit of a product-based CMS as my first project.</p> <p>Here is my question. How can I add additional data (products) to my Product model?</p> <p>I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django</p> <p>How can I do this all without using this existing django admin interface.</p>
[ { "answer_id": 36818, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": -1, "selected": false, "text": "<p>Follow the Django tutorial for setting up the \"admin\" part of an application. This will allow you to modify your...
2008/08/31
[ "https://Stackoverflow.com/questions/36812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ]
Currently, I am writing up a bit of a product-based CMS as my first project. Here is my question. How can I add additional data (products) to my Product model? I have added '/admin/products/add' to my urls.py, but I don't really know where to go from there. How would i build both my view and my template? Please keep in mind that I don't really know all that much Python, and i am very new to Django How can I do this all without using this existing django admin interface.
You will want to wire your URL to the Django [create\_object generic view](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object), and pass it either "model" (the model you want to create) or "form\_class" (a customized [ModelForm](https://docs.djangoproject.com/en/1.1/topics/forms/modelforms/#topics-forms-modelforms) class). There are a number of [other arguments](https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-create-update-create-object) you can also pass to override default behaviors. Sample URLconf for the simplest case: ``` from django.conf.urls.defaults import * from django.views.generic.create_update import create_object from my_products_app.models import Product urlpatterns = patterns('', url(r'^admin/products/add/$', create_object, {'model': Product})) ``` Your template will get the context variable "form", which you just need to wrap in a <form> tag and add a submit button. The simplest working template (by default should go in "my\_products\_app/product\_form.html"): ``` <form action="." method="POST"> {{ form }} <input type="submit" name="submit" value="add"> </form> ``` Note that your Product model must have a get\_absolute\_url method, or else you must pass in the post\_save\_redirect parameter to the view. Otherwise it won't know where to redirect to after save.
36,831
<p>I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "<a href="http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx" rel="nofollow noreferrer">GetBestInterface</a>" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation.</p> <p>I've found some examples via Google, like <a href="http://www.justin-cook.com/wp/2006/11/28/convert-an-ip-address-to-ip-number-with-php-asp-c-and-vbnet/" rel="nofollow noreferrer">this one</a> or <a href="http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c10651" rel="nofollow noreferrer">this one</a>, but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation...</p> <p>There is also a way of doing this using IP Helper, using the <a href="http://msdn.microsoft.com/en-us/library/bb408412(VS.85).aspx" rel="nofollow noreferrer">ParseNetworkString</a>, but again, I'd rather use .NET - I believe the less I rely on pInvoke the better.</p> <p>So, anyone knows of a standard way to do this in .NET?</p>
[ { "answer_id": 36841, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 5, "selected": true, "text": "<p>MSDN <a href=\"http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx\" rel=\"noreferrer\">says</a> ...
2008/08/31
[ "https://Stackoverflow.com/questions/36831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1596/" ]
I'm writing C# code that uses the windows IP Helper API. One of the functions I'm trying to call is "[GetBestInterface](http://msdn.microsoft.com/en-us/library/aa365920(VS.85).aspx)" that takes a 'uint' representation of an IP. What I need is to parse a textual representation of the IP to create the 'uint' representation. I've found some examples via Google, like [this one](http://www.justin-cook.com/wp/2006/11/28/convert-an-ip-address-to-ip-number-with-php-asp-c-and-vbnet/) or [this one](http://www.codeguru.com/csharp/.net/net_general/internet/article.php/c10651), but I'm pretty sure there should be a standard way to achieve this with .NET. Only problem is, I can't find this standard way. IPAddress.Parse seems to be in the right direction, but it doesn't supply any way of getting a 'uint' representation... There is also a way of doing this using IP Helper, using the [ParseNetworkString](http://msdn.microsoft.com/en-us/library/bb408412(VS.85).aspx), but again, I'd rather use .NET - I believe the less I rely on pInvoke the better. So, anyone knows of a standard way to do this in .NET?
MSDN [says](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) that IPAddress.Address property (which returns numeric representation of IP address) is obsolete and you should use [GetAddressBytes](http://msdn.microsoft.com/en-us/library/system.net.ipaddress.getaddressbytes.aspx) method. You can convert IP address to numeric value using following code: ``` var ipAddress = IPAddress.Parse("some.ip.address"); var ipBytes = ipAddress.GetAddressBytes(); var ip = (uint)ipBytes [3] << 24; ip += (uint)ipBytes [2] << 16; ip += (uint)ipBytes [1] <<8; ip += (uint)ipBytes [0]; ``` **EDIT:** As other commenters noticed above-mentioned code is for IPv4 addresses only. IPv6 address is 128 bits long so it's impossible to convert it to 'uint' as question's author wanted.
36,832
<p>In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function.</p> <p>I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense:</p> <p>As long as the derived constructor has not been executed the object is <strong>not</strong> yet a <em>derived</em> instance.</p> <p>So how can a derived function be called? The preconditions haven't had the chance to be set up. Example:</p> <pre><code>class base { public: base() { std::cout &lt;&lt; "foo is " &lt;&lt; foo() &lt;&lt; std::endl; } virtual int foo() { return 42; } }; class derived : public base { int* ptr_; public: derived(int i) : ptr_(new int(i*i)) { } // The following cannot be called before derived::derived due to how C++ behaves, // if it was possible... Kaboom! virtual int foo() { return *ptr_; } }; </code></pre> <p>It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for <em>the principle of least surprise</em>? </p> <p>Which do you think is the correct choice?</p>
[ { "answer_id": 36837, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "<p>Both ways can lead to unexpected results. Your best bet is to not call a virtual function in your constructor at a...
2008/08/31
[ "https://Stackoverflow.com/questions/36832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3848/" ]
In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function. I think everyone who encountered this behavior for the first time was surprised but on second thought it made sense: As long as the derived constructor has not been executed the object is **not** yet a *derived* instance. So how can a derived function be called? The preconditions haven't had the chance to be set up. Example: ``` class base { public: base() { std::cout << "foo is " << foo() << std::endl; } virtual int foo() { return 42; } }; class derived : public base { int* ptr_; public: derived(int i) : ptr_(new int(i*i)) { } // The following cannot be called before derived::derived due to how C++ behaves, // if it was possible... Kaboom! virtual int foo() { return *ptr_; } }; ``` It's exactly the same for Java and .NET yet they chose to go the other way, and is possibly the only reason for *the principle of least surprise*? Which do you think is the correct choice?
There's a fundamental difference in how the languages define an object's life time. In Java and .Net the object members are zero/null initialized before any constructor is run and is at this point that the object life time begins. So when you enter the constructor you've already got an initialized object. In C++ the object life time only begins when the constructor finishes (although member variables and base classes are fully constructed before it starts). This explains the behaviour when virtual functions are called and also why the destructor isn't run if there's an exception in the constructor's body. The problem with the Java/.Net definition of object lifetime is that it's harder to make sure the object always meets its invariant without having to put in special cases for when the object is initialized but the constructor hasn't run. The problem with the C++ definition is that you have this odd period where the object is in limbo and not fully constructed.
36,861
<p>I've run into a strange syntax in <a href="http://boo.codehaus.org/Closures" rel="nofollow noreferrer">Boo Language Guide</a> :</p> <pre><code>setter = { value | a = value } </code></pre> <p>What does the | operator mean?</p>
[ { "answer_id": 36866, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "<p>Well, having never used Boo, my (educated) guess is that it's for passing parameter to the closure lambda-style functi...
2008/08/31
[ "https://Stackoverflow.com/questions/36861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2313/" ]
I've run into a strange syntax in [Boo Language Guide](http://boo.codehaus.org/Closures) : ``` setter = { value | a = value } ``` What does the | operator mean?
The documentation of Boo seems to be lacking in this area -- it seems that ``` setter = { value | a = value } ``` is shorthand for ``` setter = def(value): a = value ```
36,862
<p>With SVN, I had a single big repository I kept on a server, and checked-out on a few machines. This was a pretty good backup system, and allowed me easily work on any of the machines. I could checkout a specific project, commit and it updated the 'master' project, or I could checkout the entire thing.</p> <p>Now, I have a bunch of git repositories, for various projects, several of which are on github. I also have the SVN repository I mentioned, imported via the git-svn command..</p> <p>Basically, I like having all my code (not just projects, but random snippets and scripts, some things like my CV, articles I've written, websites I've made and so on) in one big repository I can easily clone onto remote machines, or memory-sticks/harddrives as backup.</p> <p>The problem is, since it's a private repository, and git doesn't allow checking out of a specific folder (that I could push to github as a separate project, but have the changes appear in both the master-repo, and the sub-repos)</p> <p>I <em>could</em> use the git submodule system, but it doesn't act how I want it too (submodules are pointers to other repositories, and don't really contain the actual code, so it's useless for backup)</p> <p>Currently I have a folder of git-repos (for example, ~/code_projects/proj1/.git/ ~/code_projects/proj2/.git/), and after doing changes to proj1 I do <code>git push github</code>, then I copy the files into ~/Documents/code/python/projects/proj1/ and do a single commit (instead of the numerous ones in the individual repos). Then do <code>git push backupdrive1</code>, <code>git push mymemorystick</code> etc</p> <p>So, the question: How do your personal code and projects with git repositories, and keep them synced and backed-up?</p>
[ { "answer_id": 36905, "author": "Spoike", "author_id": 3713, "author_profile": "https://Stackoverflow.com/users/3713", "pm_score": 2, "selected": false, "text": "<p>,I haven't tried nesting git repositories yet because I haven't run into a situation where I need to. As I've read on the <...
2008/08/31
[ "https://Stackoverflow.com/questions/36862", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
With SVN, I had a single big repository I kept on a server, and checked-out on a few machines. This was a pretty good backup system, and allowed me easily work on any of the machines. I could checkout a specific project, commit and it updated the 'master' project, or I could checkout the entire thing. Now, I have a bunch of git repositories, for various projects, several of which are on github. I also have the SVN repository I mentioned, imported via the git-svn command.. Basically, I like having all my code (not just projects, but random snippets and scripts, some things like my CV, articles I've written, websites I've made and so on) in one big repository I can easily clone onto remote machines, or memory-sticks/harddrives as backup. The problem is, since it's a private repository, and git doesn't allow checking out of a specific folder (that I could push to github as a separate project, but have the changes appear in both the master-repo, and the sub-repos) I *could* use the git submodule system, but it doesn't act how I want it too (submodules are pointers to other repositories, and don't really contain the actual code, so it's useless for backup) Currently I have a folder of git-repos (for example, ~/code\_projects/proj1/.git/ ~/code\_projects/proj2/.git/), and after doing changes to proj1 I do `git push github`, then I copy the files into ~/Documents/code/python/projects/proj1/ and do a single commit (instead of the numerous ones in the individual repos). Then do `git push backupdrive1`, `git push mymemorystick` etc So, the question: How do your personal code and projects with git repositories, and keep them synced and backed-up?
I would **strongly** advise against putting unrelated data in a given Git repository. The overhead of creating new repositories is quite low, and that is a *feature* that makes it possible to keep different lineages completely separate. Fighting that idea means ending up with unnecessarily tangled history, which renders administration more difficult and--more importantly--"archeology" tools less useful because of the resulting dilution. Also, as you mentioned, Git assumes that the "unit of cloning" is the repository, and practically has to do so because of its distributed nature. One solution is to keep every project/package/etc. as its own *bare* repository (i.e., without working tree) under a blessed hierarchy, like: ``` /repos/a.git /repos/b.git /repos/c.git ``` Once a few conventions have been established, it becomes trivial to apply administrative operations (backup, packing, web publishing) to the complete hierarchy, which serves a role not entirely dissimilar to "monolithic" SVN repositories. Working with these repositories also becomes somewhat similar to SVN workflows, with the addition that one *can* use local commits and branches: ``` svn checkout --> git clone svn update --> git pull svn commit --> git push ``` You can have multiple remotes in each working clone, for the ease of synchronizing between the multiple parties: ``` $ cd ~/dev $ git clone /repos/foo.git # or the one from github, ... $ cd foo $ git remote add github ... $ git remote add memorystick ... ``` You can then fetch/pull from each of the "sources", work and commit locally, and then push ("backup") to each of these remotes when you are ready with something like (note how that pushes the *same* commits and history to each of the remotes!): ``` $ for remote in origin github memorystick; do git push $remote; done ``` The easiest way to turn an existing working repository `~/dev/foo` into such a bare repository is probably: ``` $ cd ~/dev $ git clone --bare foo /repos/foo.git $ mv foo foo.old $ git clone /repos/foo.git ``` which is mostly equivalent to a `svn import`--but does not throw the existing, "local" history away. Note: *submodules* are a mechanism to include shared *related* lineages, so I indeed wouldn't consider them an appropriate tool for the problem you are trying to solve.
36,877
<p>How can I set the cookies in my <code>PHP apps</code> as <code>HttpOnly cookies</code>?</p>
[ { "answer_id": 36880, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 3, "selected": false, "text": "<p>Explanation here from Ilia... 5.2 only though</p>\n\n<p><a href=\"http://ilia.ws/archives/121-httpOnly-cookie-flag-support-...
2008/08/31
[ "https://Stackoverflow.com/questions/36877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3871/" ]
How can I set the cookies in my `PHP apps` as `HttpOnly cookies`?
* For **your cookies**, see this answer. * For **PHP's own session cookie** (`PHPSESSID`, by default), see [@richie's answer](https://stackoverflow.com/a/8726269/1820) The [`setcookie()`](http://php.net/manual/en/function.setcookie.php) and [`setrawcookie()`](http://php.net/manual/en/function.setrawcookie.php) functions, introduced the boolean `httponly` parameter, back in the dark ages of PHP 5.2.0, making this nice and easy. Simply set the 7th parameter to true, as per the syntax *Function syntax simplified for brevity* ``` setcookie( $name, $value, $expire, $path, $domain, $secure, $httponly ) setrawcookie( $name, $value, $expire, $path, $domain, $secure, $httponly ) ``` In PHP < 8, specify `NULL` for parameters you wish to remain as default. In PHP >= 8 you can benefit from using named parameters. See [this question about named params](https://stackoverflow.com/a/64997399/1820). ``` setcookie( $name, $value, httponly:true ) ``` It is also possible using the older, lower-level [`header()`](http://php.net/manual/en/function.header.php) function: ``` header( "Set-Cookie: name=value; HttpOnly" ); ``` You may also want to consider if you should be setting the `Secure` parameter.
36,881
<p>I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header.</p> <p>The TabSpecs are created in this way within a <code>setupTabs()</code> method which loops to create the appropriate number of tabs:</p> <pre><code>TabSpec ts = mTabs.newTabSpec(&quot;tab&quot;); ts.setIndicator(&quot;TabTitle&quot;, iconResource); ts.setContent(new TabHost.TabContentFactory( { public View createTabContent(String tag) { ... } }); mTabs.addTab(ts); </code></pre> <p>There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them.</p> <pre><code>mTabs.getTabWidget().removeAllViews(); mTabs.clearAllTabs(true); setupTabs(); </code></pre> <p>Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?</p>
[ { "answer_id": 68078, "author": "dmazzoni", "author_id": 7193, "author_profile": "https://Stackoverflow.com/users/7193", "pm_score": 6, "selected": true, "text": "<p>The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator...
2008/08/31
[ "https://Stackoverflow.com/questions/36881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1197/" ]
I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header. The TabSpecs are created in this way within a `setupTabs()` method which loops to create the appropriate number of tabs: ``` TabSpec ts = mTabs.newTabSpec("tab"); ts.setIndicator("TabTitle", iconResource); ts.setContent(new TabHost.TabContentFactory( { public View createTabContent(String tag) { ... } }); mTabs.addTab(ts); ``` There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them. ``` mTabs.getTabWidget().removeAllViews(); mTabs.clearAllTabs(true); setupTabs(); ``` Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?
The short answer is, you're not missing anything. The Android SDK doesn't provide a direct method to change the indicator of a `TabHost` after it's been created. The `TabSpec` is only used to build the tab, so changing the `TabSpec` after the fact will have no effect. I think there's a workaround, though. Call `mTabs.getTabWidget()` to get a `TabWidget` object. This is just a subclass of `ViewGroup`, so you can call `getChildCount()` and `getChildAt()` to access individual tabs within the `TabWidget`. Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it's almost certainly some other `ViewGroup` (maybe a `LinearLayout`, but it doesn't matter) that contains an `ImageView` and a `TextView`. So with a little fiddling with the debugger or `Log.i`, you should be able to figure out a recipe to get the `ImageView` and change it directly. The downside is that if you're not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems.
36,901
<p>What do <code>*args</code> and <code>**kwargs</code> mean?</p> <pre><code>def foo(x, y, *args): def bar(x, y, **kwargs): </code></pre>
[ { "answer_id": 36902, "author": "Chris Upchurch", "author_id": 2600, "author_profile": "https://Stackoverflow.com/users/2600", "pm_score": 4, "selected": false, "text": "<p>From the Python documentation:</p>\n\n<blockquote>\n <p>If there are more positional arguments than there are form...
2008/08/31
[ "https://Stackoverflow.com/questions/36901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2572/" ]
What do `*args` and `**kwargs` mean? ``` def foo(x, y, *args): def bar(x, y, **kwargs): ```
The `*args` and `**kwargs` is a common idiom to allow arbitrary number of arguments to functions as described in the section [more on defining functions](http://docs.python.org/3/tutorial/controlflow.html#more-on-defining-functions) in the Python documentation. The `*args` will give you all function parameters [as a tuple](https://docs.python.org/3/tutorial/controlflow.html#arbitrary-argument-lists): ``` def foo(*args): for a in args: print(a) foo(1) # 1 foo(1,2,3) # 1 # 2 # 3 ``` The `**kwargs` will give you all **keyword arguments** except for those corresponding to a formal parameter as a dictionary. ``` def bar(**kwargs): for a in kwargs: print(a, kwargs[a]) bar(name='one', age=27) # name one # age 27 ``` Both idioms can be mixed with normal arguments to allow a set of fixed and some variable arguments: ``` def foo(kind, *args, **kwargs): pass ``` It is also possible to use this the other way around: ``` def foo(a, b, c): print(a, b, c) obj = {'b':10, 'c':'lee'} foo(100,**obj) # 100 10 lee ``` Another usage of the `*l` idiom is to **unpack argument lists** when calling a function. ``` def foo(bar, lee): print(bar, lee) l = [1,2] foo(*l) # 1 2 ``` In Python 3 it is possible to use `*l` on the left side of an assignment ([Extended Iterable Unpacking](http://www.python.org/dev/peps/pep-3132/)), though it gives a list instead of a tuple in this context: ``` first, *rest = [1,2,3,4] first, *l, last = [1,2,3,4] ``` Also Python 3 adds new semantic (refer [PEP 3102](https://www.python.org/dev/peps/pep-3102/)): ``` def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass ``` For example the following works in python 3 but not python 2: ``` >>> x = [1, 2] >>> [*x] [1, 2] >>> [*x, 3, 4] [1, 2, 3, 4] >>> x = {1:1, 2:2} >>> x {1: 1, 2: 2} >>> {**x, 3:3, 4:4} {1: 1, 2: 2, 3: 3, 4: 4} ``` Such function accepts only 3 positional arguments, and everything after `*` can only be passed as keyword arguments. ### Note: * A Python `dict`, semantically used for keyword argument passing, are arbitrarily ordered. However, in Python 3.6, keyword arguments are guaranteed to remember insertion order. * "The order of elements in `**kwargs` now corresponds to the order in which keyword arguments were passed to the function." - [What’s New In Python 3.6](https://docs.python.org/3/whatsnew/3.6.html) * In fact, all dicts in CPython 3.6 will remember insertion order as an implementation detail, this becomes standard in Python 3.7.
36,906
<p>I want to swap two integers, and I want to know which of these two implementations will be faster: The obvious way with a temp variable:</p> <pre><code>void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } </code></pre> <p>Or the xor version that I'm sure most people have seen:</p> <pre><code>void swap(int* a, int* b) { *a ^= *b; *b ^= *a; *a ^= *b; } </code></pre> <p>It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important.</p>
[ { "answer_id": 36910, "author": "caramelcarrot", "author_id": 3877, "author_profile": "https://Stackoverflow.com/users/3877", "pm_score": 7, "selected": false, "text": "<p>Number 2 is often quoted as being the \"clever\" way of doing it. It is in fact most likely slower as it obscures th...
2008/08/31
[ "https://Stackoverflow.com/questions/36906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3869/" ]
I want to swap two integers, and I want to know which of these two implementations will be faster: The obvious way with a temp variable: ``` void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } ``` Or the xor version that I'm sure most people have seen: ``` void swap(int* a, int* b) { *a ^= *b; *b ^= *a; *a ^= *b; } ``` It seems like the first uses an extra register, but the second one is doing three loads and stores while the first only does two of each. Can someone tell me which is faster and why? The why being more important.
The XOR method fails if a and b point to the same address. The first XOR will clear all of the bits at the memory address pointed to by both variables, so once the function returns (\*a == \*b == 0), regardless of the initial value. More info on the Wiki page: [XOR swap algorithm](http://en.wikipedia.org/wiki/XOR_swap_algorithm) Although it's not likely that this issue would come up, I'd always prefer to use the method that's guaranteed to work, not the clever method that fails at unexpected moments.
36,932
<p>I'm mainly a C# developer, but I'm currently working on a project in Python.</p> <p>How can I represent the equivalent of an Enum in Python? </p>
[ { "answer_id": 36937, "author": "Alexandru Nedelcu", "author_id": 3280, "author_profile": "https://Stackoverflow.com/users/3280", "pm_score": 10, "selected": false, "text": "<p>Before PEP 435, Python didn't have an equivalent but you could implement your own.</p>\n<p>Myself, I like keepi...
2008/08/31
[ "https://Stackoverflow.com/questions/36932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3880/" ]
I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python?
[Enums](https://docs.python.org/3/library/enum.html) have been added to Python 3.4 as described in [PEP 435](http://www.python.org/dev/peps/pep-0435/). It has also been [backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4](https://pypi.python.org/pypi/enum34) on pypi. For more advanced Enum techniques try the [aenum library](https://pypi.python.org/pypi/aenum) (2.7, 3.3+, same author as `enum34`. Code is not perfectly compatible between py2 and py3, e.g. you'll need [`__order__` in python 2](https://stackoverflow.com/a/25982264/57461)). * To use `enum34`, do `$ pip install enum34` * To use `aenum`, do `$ pip install aenum` Installing `enum` (no numbers) will install a completely different and incompatible version. --- ``` from enum import Enum # for enum34, or the stdlib version # from aenum import Enum # for the aenum version Animal = Enum('Animal', 'ant bee cat dog') Animal.ant # returns <Animal.ant: 1> Animal['ant'] # returns <Animal.ant: 1> (string lookup) Animal.ant.name # returns 'ant' (inverse lookup) ``` or equivalently: ``` class Animal(Enum): ant = 1 bee = 2 cat = 3 dog = 4 ``` --- In earlier versions, one way of accomplishing enums is: ``` def enum(**enums): return type('Enum', (), enums) ``` which is used like so: ``` >>> Numbers = enum(ONE=1, TWO=2, THREE='three') >>> Numbers.ONE 1 >>> Numbers.TWO 2 >>> Numbers.THREE 'three' ``` You can also easily support automatic enumeration with something like this: ``` def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) ``` and used like so: ``` >>> Numbers = enum('ZERO', 'ONE', 'TWO') >>> Numbers.ZERO 0 >>> Numbers.ONE 1 ``` Support for converting the values back to names can be added this way: ``` def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) reverse = dict((value, key) for key, value in enums.iteritems()) enums['reverse_mapping'] = reverse return type('Enum', (), enums) ``` This overwrites anything with that name, but it is useful for rendering your enums in output. It will throw a `KeyError` if the reverse mapping doesn't exist. With the first example: ``` >>> Numbers.reverse_mapping['three'] 'THREE' ``` --- If you are using MyPy another way to express "enums" is with [`typing.Literal`](https://mypy.readthedocs.io/en/stable/literal_types.html#parameterizing-literals). For example: ```py from typing import Literal #python >=3.8 from typing_extensions import Literal #python 2.7, 3.4-3.7 Animal = Literal['ant', 'bee', 'cat', 'dog'] def hello_animal(animal: Animal): print(f"hello {animal}") hello_animal('rock') # error hello_animal('bee') # passes ```
36,959
<p>In MS SQL Server, I create my scripts to use customizable variables:</p> <pre><code>DECLARE @somevariable int SELECT @somevariable = -1 INSERT INTO foo VALUES ( @somevariable ) </code></pre> <p>I'll then change the value of <code>@somevariable</code> at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember.</p> <p>How do I do the same with the PostgreSQL client <code>psql</code>?</p>
[ { "answer_id": 36979, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 4, "selected": false, "text": "<p>FWIW, the real problem was that I had included a semicolon at the end of my \\set command:</p>\n\n<blockquote>\n <p>...
2008/08/31
[ "https://Stackoverflow.com/questions/36959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
In MS SQL Server, I create my scripts to use customizable variables: ``` DECLARE @somevariable int SELECT @somevariable = -1 INSERT INTO foo VALUES ( @somevariable ) ``` I'll then change the value of `@somevariable` at runtime, depending on the value that I want in the particular situation. Since it's at the top of the script it's easy to see and remember. How do I do the same with the PostgreSQL client `psql`?
Postgres variables are created through the \set command, for example ... ``` \set myvariable value ``` ... and can then be substituted, for example, as ... ``` SELECT * FROM :myvariable.table1; ``` ... or ... ``` SELECT * FROM table1 WHERE :myvariable IS NULL; ``` *edit: As of psql 9.1, variables can be expanded in quotes as in:* ``` \set myvariable value SELECT * FROM table1 WHERE column1 = :'myvariable'; ``` *In older versions of the psql client:* ... If you want to use the variable as the value in a conditional string query, such as ... ``` SELECT * FROM table1 WHERE column1 = ':myvariable'; ``` ... then you need to include the quotes in the variable itself as the above will not work. Instead define your variable as such ... ``` \set myvariable 'value' ``` However, if, like me, you ran into a situation in which you wanted to make a string from an existing variable, I found the trick to be this ... ``` \set quoted_myvariable '\'' :myvariable '\'' ``` Now you have both a quoted and unquoted variable of the same string! And you can do something like this .... ``` INSERT INTO :myvariable.table1 SELECT * FROM table2 WHERE column1 = :quoted_myvariable; ```
36,991
<p>So, I am a total beginner in any kind of <code>Windows</code> related programming. I have been playing around with the <code>Windows</code> <code>API</code> and came across a couple of examples on how to initialize create windows and such. </p> <p>One example creates a regular window (I abbreviated some of the code):</p> <pre><code>int WINAPI WinMain( [...] ) { [...] // Windows Class setup wndClass.cbSize = sizeof( wndClass ); wndClass.style = CS_HREDRAW | CS_VREDRAW; [...] // Register class RegisterClassEx( &amp;wndClass ); // Create window hWnd = CreateWindow( szAppName, "Win32 App", WS_OVERLAPPEDWINDOW, 0, 0, 512, 384, NULL, NULL, hInstance, NULL ); [...] } </code></pre> <p>The second example creates a dialog box (no abbreviations except the WinMain arguments):</p> <pre><code>int WINAPI WinMain( [...] ) { // Create dialog box DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN_DLG), NULL, (DLGPROC)DialogProc); } </code></pre> <p>The second example does not contain any call to the register function. It just creates the DialogBox with its DialogProc process attached. </p> <p>This works fine, but I am wondering if there is a benefit of registering the window class and then creating the dialog box (if this is at all possible). </p>
[ { "answer_id": 36986, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>I've always done it exactly the way you're describing. I'm curious to see if there's a more accepted approach.</p>\n" }...
2008/08/31
[ "https://Stackoverflow.com/questions/36991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2386/" ]
So, I am a total beginner in any kind of `Windows` related programming. I have been playing around with the `Windows` `API` and came across a couple of examples on how to initialize create windows and such. One example creates a regular window (I abbreviated some of the code): ``` int WINAPI WinMain( [...] ) { [...] // Windows Class setup wndClass.cbSize = sizeof( wndClass ); wndClass.style = CS_HREDRAW | CS_VREDRAW; [...] // Register class RegisterClassEx( &wndClass ); // Create window hWnd = CreateWindow( szAppName, "Win32 App", WS_OVERLAPPEDWINDOW, 0, 0, 512, 384, NULL, NULL, hInstance, NULL ); [...] } ``` The second example creates a dialog box (no abbreviations except the WinMain arguments): ``` int WINAPI WinMain( [...] ) { // Create dialog box DialogBox(hInstance, MAKEINTRESOURCE(IDD_MAIN_DLG), NULL, (DLGPROC)DialogProc); } ``` The second example does not contain any call to the register function. It just creates the DialogBox with its DialogProc process attached. This works fine, but I am wondering if there is a benefit of registering the window class and then creating the dialog box (if this is at all possible).
I would say exposing properties on your custom dialog is the idiomatic way to go because that is how standard dialogs (like the Select/OpenFileDialog) do it. Someone could argue it is more explicit and intention revealing to have a ShowBirthdayDialog() method that returns the result you're looking for, but following the framework's pattern is probably the wise way to go.
37,026
<p>If one Googles for "difference between <code>notify()</code> and <code>notifyAll()</code>" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in <code>notify()</code> and all in <code>notifyAll()</code>.</p> <p>However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer.</p> <p>What's the <strong>useful</strong> difference between <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29" rel="noreferrer">notify()</a> and <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29" rel="noreferrer">notifyAll()</a> then? Am I missing something?</p>
[ { "answer_id": 37038, "author": "Spoike", "author_id": 3713, "author_profile": "https://Stackoverflow.com/users/3713", "pm_score": 2, "selected": false, "text": "<p><code>notify()</code> will wake up one thread while <code>notifyAll()</code> will wake up all. As far as I know there is no...
2008/08/31
[ "https://Stackoverflow.com/questions/37026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3894/" ]
If one Googles for "difference between `notify()` and `notifyAll()`" then a lot of explanations will pop up (leaving apart the javadoc paragraphs). It all boils down to the number of waiting threads being waken up: one in `notify()` and all in `notifyAll()`. However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition; in the first case the one selected by the VM, in the second case the one selected by the system thread scheduler. The exact selection procedures for both of them (in the general case) are not known to the programmer. What's the **useful** difference between [notify()](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notify%28%29) and [notifyAll()](http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#notifyAll%28%29) then? Am I missing something?
> > However (if I do understand the difference between these methods right), only one thread is always selected for further monitor acquisition. > > > That is not correct. `o.notifyAll()` wakes *all* of the threads that are blocked in `o.wait()` calls. The threads are only allowed to return from `o.wait()` one-by-one, but they each *will* get their turn. --- Simply put, it depends on why your threads are waiting to be notified. Do you want to tell one of the waiting threads that something happened, or do you want to tell all of them at the same time? In some cases, all waiting threads can take useful action once the wait finishes. An example would be a set of threads waiting for a certain task to finish; once the task has finished, all waiting threads can continue with their business. In such a case you would use **notifyAll()** to wake up all waiting threads at the same time. Another case, for example mutually exclusive locking, only one of the waiting threads can do something useful after being notified (in this case acquire the lock). In such a case, you would rather use **notify()**. Properly implemented, you *could* use **notifyAll()** in this situation as well, but you would unnecessarily wake threads that can't do anything anyway. --- In many cases, the code to await a condition will be written as a loop: ``` synchronized(o) { while (! IsConditionTrue()) { o.wait(); } DoSomethingThatOnlyMakesSenseWhenConditionIsTrue_and_MaybeMakeConditionFalseAgain(); } ``` That way, if an `o.notifyAll()` call wakes more than one waiting thread, and the first one to return from the `o.wait()` makes leaves the condition in the false state, then the other threads that were awakened will go back to waiting.
37,069
<p>On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod_rewrite. This wasn't statically linked and the module was not built in the /modules folder either.</p> <p>I had to do the following to build Apache and mod_rewrite:</p> <pre><code>./configure --prefix=/usr/local/apache2 --enable-rewrite=shared </code></pre> <ul> <li>Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config?</li> <li>Now that I have built Apache and the mod_rewrite DSO, how can I build another shared module without building all of Apache?</li> </ul> <p>(The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.)</p>
[ { "answer_id": 37111, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 5, "selected": true, "text": "<p>Try the <code>./configure</code> option <code>--enable-mods-shared=\"all\"</code>, or <code>--enable-mods-shared=\"&lt;list ...
2008/08/31
[ "https://Stackoverflow.com/questions/37069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
On Mac OS X 10.5 I downloaded the latest version of Apache 2.2.9. After the usual configure, make, make install dance I had a build of apache without mod\_rewrite. This wasn't statically linked and the module was not built in the /modules folder either. I had to do the following to build Apache and mod\_rewrite: ``` ./configure --prefix=/usr/local/apache2 --enable-rewrite=shared ``` * Is there a way to tell Apache to build all modules as Shared Modules (DSOs) so I can control loading from the Apache config? * Now that I have built Apache and the mod\_rewrite DSO, how can I build another shared module without building all of Apache? (The last time I built Apache (2.2.8) on Solaris, by default it built everything as a shared module.)
Try the `./configure` option `--enable-mods-shared="all"`, or `--enable-mods-shared="<list of modules>"` to compile modules as shared objects. See further [details in Apache 2.2 docs](http://httpd.apache.org/docs/2.2/programs/configure.html#otheroptfeat) To just compile Apache with the ability to load shared objects (and add modules later), use `--enable-so`, then consult the documentation on compiling modules seperately in the [Apache 2.2. DSO docs](http://httpd.apache.org/docs/2.2/dso.html).
37,073
<p>What is currently the best way to get a favicon to display in all browsers that currently support it?</p> <p>Please include:</p> <ol> <li><p>Which image formats are supported by which browsers.</p></li> <li><p>Which lines are needed in what places for the various browsers.</p></li> </ol>
[ { "answer_id": 37076, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "<p>Having a <code>favicon.*</code> in your root directory is automatically detected by most browsers. You can ensure it's detect...
2008/08/31
[ "https://Stackoverflow.com/questions/37073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/177/" ]
What is currently the best way to get a favicon to display in all browsers that currently support it? Please include: 1. Which image formats are supported by which browsers. 2. Which lines are needed in what places for the various browsers.
I go for a belt and braces approach here. I create a 32x32 icon in both the `.ico` and `.png` formats called `favicon.ico` and `favicon.png`. The icon name doesn't really matter unless you are dealing with older browsers. 1. Place `favicon.ico` at your site root to support the older browsers (optional and only relevant for older browsers. 2. Place favicon.png in my images sub-directory (just to keep things tidy). 3. Add the following HTML inside the `<head>` element. ``` <link rel="icon" href="/images/favicon.png" type="image/png" /> <link rel="shortcut icon" href="/favicon.ico" /> ``` Please note that: * The MIME type for `.ico` files was registered as image/vnd.microsoft.icon by the [**IANA**](http://www.iana.org). * Internet Explorer will ignore the `type` attribute for the shortcut icon relationship and this is the only browser to support this relationship, it doesn't need to be supplied. [**Reference**](http://www.jonathantneal.com/blog/understand-the-favicon/)
37,101
<p>Is there a way clear or reset the outputcache for an entire website without a restart?</p> <p>I'm just starting to use outputcache on a site and when I make a mistake in setting it up I need a page I can browse to that will reset it.</p>
[ { "answer_id": 37167, "author": "Ethan Gunderson", "author_id": 2066, "author_profile": "https://Stackoverflow.com/users/2066", "pm_score": 4, "selected": true, "text": "<p>This should do the trick:</p>\n\n<pre><code>Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.Eve...
2008/08/31
[ "https://Stackoverflow.com/questions/37101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3747/" ]
Is there a way clear or reset the outputcache for an entire website without a restart? I'm just starting to use outputcache on a site and when I make a mistake in setting it up I need a page I can browse to that will reset it.
This should do the trick: ``` Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim path As String path="/AbosoluteVirtualPath/OutputCached.aspx" HttpResponse.RemoveOutputCacheItem(path) End Sub ```
37,103
<p>I have a container div with a fixed <code>width</code> and <code>height</code>, with <code>overflow: hidden</code>.</p> <p>I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the <code>height</code> of the parent should not allow this. This is how this looks:</p> <p><img src="https://i.stack.imgur.com/v2x7d.png" alt="Wrong" /></p> <p>How I would like it to look:</p> <p>![Right][2] - <em>removed image shack image that had been replaced by an advert</em></p> <p>Note: the effect I want can be achieved by using inline elements &amp; <code>white-space: no-wrap</code> (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements.</p>
[ { "answer_id": 37125, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "<p>This seems close to what you want:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console...
2008/08/31
[ "https://Stackoverflow.com/questions/37103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1349865/" ]
I have a container div with a fixed `width` and `height`, with `overflow: hidden`. I want a horizontal row of float: left divs within this container. Divs which are floated left will naturally push onto the 'line' below after they read the right bound of their parent. This will happen even if the `height` of the parent should not allow this. This is how this looks: ![Wrong](https://i.stack.imgur.com/v2x7d.png) How I would like it to look: ![Right][2] - *removed image shack image that had been replaced by an advert* Note: the effect I want can be achieved by using inline elements & `white-space: no-wrap` (that is how I did it in the image shown). This, however, is no good to me (for reasons too lengthy to explain here), as the child divs need to be floated block level elements.
You may put an inner div in the container that is enough wide to hold all the floated divs. ```css #container { background-color: red; overflow: hidden; width: 200px; } #inner { overflow: hidden; width: 2000px; } .child { float: left; background-color: blue; width: 50px; height: 50px; } ``` ```html <div id="container"> <div id="inner"> <div class="child"></div> <div class="child"></div> <div class="child"></div> </div> </div> ```
37,122
<p>How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time.</p> <p><em>Edit: These users do want to be distracted when a new message arrives.</em></p>
[ { "answer_id": 37134, "author": "Robin Barnes", "author_id": 1349865, "author_profile": "https://Stackoverflow.com/users/1349865", "pm_score": 2, "selected": false, "text": "<p>The only way I can think of doing this is by doing something like alert('you have a new message') when the mess...
2008/08/31
[ "https://Stackoverflow.com/questions/37122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1191/" ]
How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time. *Edit: These users do want to be distracted when a new message arrives.*
this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab. ``` newExcitingAlerts = (function () { var oldTitle = document.title; var msg = "New!"; var timeoutId; var blink = function() { document.title = document.title == msg ? ' ' : msg; }; var clear = function() { clearInterval(timeoutId); document.title = oldTitle; window.onmousemove = null; timeoutId = null; }; return function () { if (!timeoutId) { timeoutId = setInterval(blink, 1000); window.onmousemove = clear; } }; }()); ``` --- *Update*: You may want to look at using [HTML5 notifications](https://paulund.co.uk/how-to-use-the-html5-notification-api).
37,189
<p>I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log.</p> <pre><code>EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0, P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b, P7 1, P8 80, P9 system.io.filenotfoundexception, P10 NIL. </code></pre> <p>I wrote a batch file to run the fax program and it fails with this message.</p> <pre><code>Unhandled Exception: System.IO.FileNotFoundException: Operation failed. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer) </code></pre> <p>Can anyone explain this behavior to me?</p>
[ { "answer_id": 37199, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>Check that you set correct working directory for your task</p>\n" }, { "answer_id": 37200, "author": "Glenn Slaven...
2008/08/31
[ "https://Stackoverflow.com/questions/37189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1203/" ]
I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log. ``` EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0, P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b, P7 1, P8 80, P9 system.io.filenotfoundexception, P10 NIL. ``` I wrote a batch file to run the fax program and it fails with this message. ``` Unhandled Exception: System.IO.FileNotFoundException: Operation failed. at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer) ``` Can anyone explain this behavior to me?
I can't explain it - but I have a few ideas. Most of the times, when a program works fine testing it, and doesn't when scheduling it - security is the case. In the context of which user is your program scheduled? Maybe that user isn't granted enough access. Is the resource your programm is trying to access a network drive, that the user running the scheduled task simply haven't got?
37,198
<ol> <li>Specifically getting on Windows the "..\Documents &amp; Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. <strong>(Now I need the answer to this)</strong></li> <li>the current users My Documents dirctory <strong>(okay this has been answered)</strong> and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.</li> </ol>
[ { "answer_id": 37240, "author": "nimish", "author_id": 3926, "author_profile": "https://Stackoverflow.com/users/3926", "pm_score": 3, "selected": false, "text": "<p>My docs would probably best be handled by accessing:</p>\n\n<pre><code>System.getProperty(\"user.home\");\n</code></pre>\n\...
2008/08/31
[ "https://Stackoverflow.com/questions/37198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3576/" ]
1. Specifically getting on Windows the "..\Documents & Settings\All Users, basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on. **(Now I need the answer to this)** 2. the current users My Documents dirctory **(okay this has been answered)** and basicaly any path that needs the front end to be dynamically derived based on the OS your software is running on.
My docs would probably best be handled by accessing: ``` System.getProperty("user.home"); ``` Look up the docs on [System.getProperty](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html).
37,219
<p>Suppose your git history looks like this:</p> <p>1 2 3 4 5</p> <p>1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done?</p> <p>Is there an efficient method when there are hundreds of revisions after the one to be deleted?</p>
[ { "answer_id": 37267, "author": "garethm", "author_id": 2219, "author_profile": "https://Stackoverflow.com/users/2219", "pm_score": 7, "selected": true, "text": "<p>To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3...
2008/08/31
[ "https://Stackoverflow.com/questions/37219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
Suppose your git history looks like this: 1 2 3 4 5 1–5 are separate revisions. You need to remove 3 while still keeping 1, 2, 4 and 5. How can this be done? Is there an efficient method when there are hundreds of revisions after the one to be deleted?
To combine revision 3 and 4 into a single revision, you can use git rebase. If you want to remove the changes in revision 3, you need to use the edit command in the interactive rebase mode. If you want to combine the changes into a single revision, use squash. I have successfully used this squash technique, but have never needed to remove a revision before. The git-rebase documentation under "Splitting commits" should hopefully give you enough of an idea to figure it out. (Or someone else might know). From the [git documentation](http://git-scm.com/docs/git-rebase): > > Start it with the oldest commit you want to retain as-is: > > > > > `git rebase -i <after-this-commit>` > > > An editor will be fired up with all the commits in your current branch (ignoring merge commits), which come after the given commit. You can reorder the commits in this list to your heart's content, and you can remove them. The list looks more or less like this: > > > > > > > ``` > > pick deadbee The oneline of this commit > > pick fa1afe1 The oneline of the next commit > > ... > > ``` > > > > > The oneline descriptions are purely for your pleasure; git-rebase will not look at them but at the commit names ("deadbee" and "fa1afe1" in this example), so do not delete or edit the names. > > > By replacing the command "pick" with the command "edit", you can tell git-rebase to stop after applying that commit, so that you can edit the files and/or the commit message, amend the commit, and continue rebasing. > > > If you want to fold two or more commits into one, replace the command "pick" with "squash" for the second and subsequent commit. If the commits had different authors, it will attribute the squashed commit to the author of the first commit. > > >
37,248
<p>While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find reference to this now). From experience, this is certainly a good decision, as there were some really terrible un-maintainable macros created back when I was doing a lot of C/C++. </p> <p>That said, there are a number of scenarios where I could find a slightly more flexible pre-processor to be useful. Code such as the following could be improved by some simple pre-processor directives:</p> <pre><code>public string MyProperty { get { return _myProperty; } set { if (value != _myProperty) { _myProperty = value; NotifyPropertyChanged("MyProperty"); // This line above could be improved by replacing the literal string with // a pre-processor directive like "#Property", which could be translated // to the string value "MyProperty" This new notify call would be as follows: // NotifyPropertyChanged(#Property); } } } </code></pre> <p>Would it be a good idea to write a pre-processor to handle extremely simple cases like this? Steve McConnell wrote in <a href="https://rads.stackoverflow.com/amzn/click/com/0735619670" rel="nofollow noreferrer" rel="nofollow noreferrer">Code Complete</a> (p208):</p> <blockquote> <p><em>Write your own preprocessor</em> If a language doesn't include a preprocessor, it's fairly easy to write one...</p> </blockquote> <p>I am torn. It was a design decision to leave such a flexible pre-processor out of C#. However, an author I highly respect mentions it may be ok in some circumstances.</p> <p><strong>Should I build a C# pre-processor? Is there one available that does the simple things I want to do?</strong></p>
[ { "answer_id": 37249, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Should I build a C# pre-processor? Is there one available that does the simple things I want to do?<...
2008/08/31
[ "https://Stackoverflow.com/questions/37248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ]
While the C# spec does include a pre-processor and basic directives (#define, #if, etc), the language does not have the same flexible pre-processor found in languages such as C/C++. I believe the lack of such a flexible pre-processor was a design decision made by Anders Hejlsberg (although, unfortunately, I can't find reference to this now). From experience, this is certainly a good decision, as there were some really terrible un-maintainable macros created back when I was doing a lot of C/C++. That said, there are a number of scenarios where I could find a slightly more flexible pre-processor to be useful. Code such as the following could be improved by some simple pre-processor directives: ``` public string MyProperty { get { return _myProperty; } set { if (value != _myProperty) { _myProperty = value; NotifyPropertyChanged("MyProperty"); // This line above could be improved by replacing the literal string with // a pre-processor directive like "#Property", which could be translated // to the string value "MyProperty" This new notify call would be as follows: // NotifyPropertyChanged(#Property); } } } ``` Would it be a good idea to write a pre-processor to handle extremely simple cases like this? Steve McConnell wrote in [Code Complete](https://rads.stackoverflow.com/amzn/click/com/0735619670) (p208): > > *Write your own preprocessor* If a language doesn't include a preprocessor, it's fairly easy to write one... > > > I am torn. It was a design decision to leave such a flexible pre-processor out of C#. However, an author I highly respect mentions it may be ok in some circumstances. **Should I build a C# pre-processor? Is there one available that does the simple things I want to do?**
Consider taking a look at an aspect-oriented solution like [PostSharp](http://www.postsharp.org/), which injects code after the fact based on custom attributes. It's the opposite of a precompiler but can give you the sort of functionality you're looking for (PropertyChanged notifications etc).
37,275
<p>What is the SQL query to select all of the MSSQL Server's logins?</p> <p>Thank you. More than one of you had the answer I was looking for:</p> <pre><code>SELECT * FROM syslogins </code></pre>
[ { "answer_id": 37280, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 4, "selected": false, "text": "<pre><code>EXEC sp_helplogins\n</code></pre>\n\n<p>You can also pass an \"@LoginNamePattern\" parameter to get informatio...
2008/08/31
[ "https://Stackoverflow.com/questions/37275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1208/" ]
What is the SQL query to select all of the MSSQL Server's logins? Thank you. More than one of you had the answer I was looking for: ``` SELECT * FROM syslogins ```
Is this what you're after? ``` select * from master.syslogins ```
37,299
<p>What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap").</p> <p>I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue).</p> <p>For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides.</p> <hr> <p>John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone.</p> <hr> <p>Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain.</p> <p>Your suggestion of attempting to replace the hander via an implementation of '__assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to __assert on the Mac it doesn't on other platforms.</p>
[ { "answer_id": 37303, "author": "GateKiller", "author_id": 383, "author_profile": "https://Stackoverflow.com/users/383", "pm_score": 2, "selected": false, "text": "<p>I found the following in an <a href=\"http://lists.apple.com/archives/Cocoa-dev/2003/Nov/msg00166.html\" rel=\"nofollow n...
2008/09/01
[ "https://Stackoverflow.com/questions/37299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '\_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap"). I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue). For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides. --- John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone. --- Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain. Your suggestion of attempting to replace the hander via an implementation of '\_\_assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to \_\_assert on the Mac it doesn't on other platforms.
<http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html> ``` asm {trap} ; Halts a program running on PPC32 or PPC64. __asm {int 3} ; Halts a program running on IA-32. ```
37,310
<p>I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object. What is the best way to test that the factory has worked correctly?</p> <p>I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it.</p> <p>Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.</p>
[ { "answer_id": 37316, "author": "Cem Catikkas", "author_id": 3087, "author_profile": "https://Stackoverflow.com/users/3087", "pm_score": 6, "selected": true, "text": "<p>Since I don't know how your factory method looks like, all I can advise right now is to </p>\n\n<ol>\n<li><p>Check to ...
2008/09/01
[ "https://Stackoverflow.com/questions/37310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3576/" ]
I have developed some classes with similar behavior, they all implement the same interface. I implemented a factory that creates the appropriate object and returns the interface. I am writing a unit test for the factory. All you get back is an interface to the object. What is the best way to test that the factory has worked correctly? I would like to know the answer in Java, but if there is a solution that crosses languages I would like to know it. Number 2. in the answer, would be done like the other answer? If so I will mark the other answer accepted as well and reword my question to adress both a factory where an interface is returned and you have no clue what type of concrete class implemented the interface, and the case where you do know what concrete class was used.
Since I don't know how your factory method looks like, all I can advise right now is to 1. Check to see the object is the correct concrete implementation you were looking for: ``` IMyInterface fromFactory = factory.create(...); Assert.assertTrue(fromFactory instanceof MyInterfaceImpl1); ``` 2. You can check if the factory setup the concrete instances with valid instance variables.
37,317
<p>I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about:</p> <p><img src="https://lh6.ggpht.com/joe.r.barone/SLs4KZMBqfI/AAAAAAAABNw/P6xtqhCo8Y4/s800/SampleApp1.jpg" alt="Sample App Screen Shot"></p> <p>The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked.</p> <p>I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now:</p> <pre><code> public partial class Form1 : Form { Control _lastEnteredControl; private void textBox_Enter(object sender, EventArgs e) { _lastEnteredControl = (Control)sender; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Do something here"); _lastEnteredControl.Focus(); } } </code></pre> <p>So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?</p>
[ { "answer_id": 37319, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>Your implementation looks good enough -- what I do want to know is why you want to do this in the first place? Won't it b...
2008/09/01
[ "https://Stackoverflow.com/questions/37317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3452/" ]
I'm working on a windows forms application (C#) where a user is entering data in a form. At any point while editing the data in the form the user can click one of the buttons on the form to perform certain actions. By default the focus goes to the clicked button so the user has to click back on to the control they want to edit in order to continue modifying the data on the form. What I need to be able to do is return the focus to the last edited control after the button click event has been processed. Here's a sample screenshot that illustrates what I'm talking about: ![Sample App Screen Shot](https://lh6.ggpht.com/joe.r.barone/SLs4KZMBqfI/AAAAAAAABNw/P6xtqhCo8Y4/s800/SampleApp1.jpg) The user can be entering data in textbox1, textbox2, textbox3, etc and click the button. I need the button to return the focus back to the control that most recently had the focus before the button was clicked. I'm wondering if anyone has a better way of implementing this functionality than what I've come up with. Here's what I'm doing right now: ``` public partial class Form1 : Form { Control _lastEnteredControl; private void textBox_Enter(object sender, EventArgs e) { _lastEnteredControl = (Control)sender; } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Do something here"); _lastEnteredControl.Focus(); } } ``` So basically what we have here is a class variable that points to the last entered control. Each textbox on the form is setup so the textBox\_Enter method is fired when the control receives the focus. Then, when the button is clicked focus is returned to the control that had the focus before the button was clicked. Anybody have any more elegant solutions for this?
For a bit of 'simplicity' maybe try. ``` public Form1() { InitializeComponent(); foreach (Control ctrl in Controls) { if (ctrl is TextBox) { ctrl.Enter += delegate(object sender, EventArgs e) { _lastEnteredControl = (Control)sender; }; } } } ``` then you don't have to worry about decorating each textbox manually (or forgetting about one too).
37,324
<p>I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an <code>ON</code> clause in C#.</p> <p>How do you represent the following in LINQ to SQL:</p> <pre><code>select DealerContact.* from Dealer inner join DealerContact on Dealer.DealerID = DealerContact.DealerID </code></pre>
[ { "answer_id": 37332, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 10, "selected": true, "text": "<p>It goes something like:</p>\n\n<pre><code>from t1 in db.Table1\njoin t2 in db.Table2 on t1.field equals t2.field\nselect ...
2008/09/01
[ "https://Stackoverflow.com/questions/37324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
I'm writing a LINQ to SQL statement, and I'm after the standard syntax for a normal inner join with an `ON` clause in C#. How do you represent the following in LINQ to SQL: ``` select DealerContact.* from Dealer inner join DealerContact on Dealer.DealerID = DealerContact.DealerID ```
It goes something like: ``` from t1 in db.Table1 join t2 in db.Table2 on t1.field equals t2.field select new { t1.field2, t2.field3} ``` It would be nice to have sensible names and fields for your tables for a better example. :) **Update** I think for your query this might be more appropriate: ``` var dealercontacts = from contact in DealerContact join dealer in Dealer on contact.DealerId equals dealer.ID select contact; ``` Since you are looking for the contacts, not the dealers.
37,346
<p>If I create a class like so: </p> <pre><code>// B.h #ifndef _B_H_ #define _B_H_ class B { private: int x; int y; }; #endif // _B_H_ </code></pre> <p>and use it like this:</p> <pre><code>// main.cpp #include &lt;iostream&gt; #include &lt;vector&gt; class B; // Forward declaration. class A { public: A() { std::cout &lt;&lt; v.size() &lt;&lt; std::endl; } private: std::vector&lt;B&gt; v; }; int main() { A a; } </code></pre> <p>The compiler fails when compiling <code>main.cpp</code>. Now the solution I know is to <code>#include "B.h"</code>, but I'm curious as to why it fails. Neither <code>g++</code> or <code>cl</code>'s error messages were very enlightening in this matter.</p>
[ { "answer_id": 37347, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 3, "selected": false, "text": "<p>To instantiate A::v, the compiler needs to know the concrete type of B.</p>\n\n<p>If you're trying to minimize the amount of #i...
2008/09/01
[ "https://Stackoverflow.com/questions/37346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
If I create a class like so: ``` // B.h #ifndef _B_H_ #define _B_H_ class B { private: int x; int y; }; #endif // _B_H_ ``` and use it like this: ``` // main.cpp #include <iostream> #include <vector> class B; // Forward declaration. class A { public: A() { std::cout << v.size() << std::endl; } private: std::vector<B> v; }; int main() { A a; } ``` The compiler fails when compiling `main.cpp`. Now the solution I know is to `#include "B.h"`, but I'm curious as to why it fails. Neither `g++` or `cl`'s error messages were very enlightening in this matter.
The compiler needs to know how big "B" is before it can generate the appropriate layout information. If instead, you said `std::vector<B*>`, then the compiler wouldn't need to know how big B is because it knows how big a pointer is.
37,391
<p>Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide).</p> <p>My target is dealing with 128-bit integers.</p> <p>There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated.</p> <p><strong>Approach #1:</strong> Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands.</p> <p><strong>Approach #2:</strong> Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions).</p> <p><strong>Approach #3:</strong> Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.</p>
[ { "answer_id": 37422, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 2, "selected": false, "text": "<p>There are already various <a href=\"http://www.pear.php.net/package/Crypt_DiffieHellman/docs/latest/Crypt_DiffieHellman/BigIn...
2008/09/01
[ "https://Stackoverflow.com/questions/37391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384/" ]
Ok, so PHP isn't the best language to be dealing with arbitrarily large integers in, considering that it only natively supports 32-bit signed integers. What I'm trying to do though is create a class that could represent an arbitrarily large binary number and be able to perform simple arithmetic operations on two of them (add/subtract/multiply/divide). My target is dealing with 128-bit integers. There's a couple of approaches I'm looking at, and problems I see with them. Any input or commentary on what you would choose and how you might go about it would be greatly appreciated. **Approach #1:** Create a 128-bit integer class that stores its integer internally as four 32-bit integers. The only problem with this approach is that I'm not sure how to go about handling overflow/underflow issues when manipulating individual chunks of the two operands. **Approach #2:** Use the bcmath extension, as this looks like something it was designed to tackle. My only worry in taking this approach is the scale setting of the bcmath extension, because there can't be any rounding errors in my 128-bit integers; they must be precise. I'm also worried about being able to eventually convert the result of the bcmath functions into a binary string (which I'll later need to shove into some mcrypt encryption functions). **Approach #3:** Store the numbers as binary strings (probably LSB first). Theoretically I should be able to store integers of any arbitrary size this way. All I would have to do is write the four basic arithmetic functions to perform add/sub/mult/div on two binary strings and produce a binary string result. This is exactly the format I need to hand over to mcrypt as well, so that's an added plus. This is the approach I think has the most promise at the moment, but the one sticking point I've got is that PHP doesn't offer me any way to manipulate the individual bits (that I know of). I believe I'd have to break it up into byte-sized chunks (no pun intended), at which point my questions about handling overflow/underflow from Approach #1 apply.
The [PHP GMP extension](http://us2.php.net/gmp) will be better for this. As an added bonus, you can use it to do your decimal-to-binary conversion, like so: ``` gmp_strval(gmp_init($n, 10), 2); ```
37,464
<p>If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store?</p> <p>It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store.</p>
[ { "answer_id": 37476, "author": "Robert Höglund", "author_id": 143, "author_profile": "https://Stackoverflow.com/users/143", "pm_score": 4, "selected": false, "text": "<p>Yes, once you have joined the iPhone Developer Program, and paid Apple $99, you can provision your applications on up...
2008/09/01
[ "https://Stackoverflow.com/questions/37464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/752/" ]
If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store? It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store.
Official Developer Program ========================== For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using [Ad Hoc Helper](http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=285691333&mt=8) available from the App Store. For further details on this method, see Craig Hockenberry's [Beta testing on iPhone 2.0](http://furbo.org/2008/08/06/beta-testing-on-iphone-20/) article Jailbroken iPhone ================= For jailbroken iPhones, you can use the following method which I have personally tested using the [AccelerometerGraph](http://developer.apple.com/iphone/library/samplecode/AccelerometerGraph/index.html) sample app on iPhone OS 3.0. Create Self-Signed Certificate ------------------------------ First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate: 1. Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate. Name: iPhone Developer Certificate Type: Code Signing Let me override defaults: Yes 2. Click Continue Validity: 3650 days 3. Click Continue 4. Blank out the Email address field. 5. Click Continue until complete. You should see "This root certificate is not trusted". This is expected. 6. Set the iPhone SDK to allow the self-signed certificate to be used: > > sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist > > > If you have Xcode open, restart it for this change to take effect. Manual Deployment over WiFi --------------------------- The following steps require `openssh`, and `uikittools` to be installed first. Replace `jasoniphone.local` with the hostname of the target device. Be sure to set your own password on both the `mobile` and `root` users after installing SSH. To manually compile and install your application on the phone as a system app (bypassing Apple's installation system): 1. Project, Set Active SDK, Device and Set Active Build Configuration, Release. 2. Compile your project normally (using Build, not Build & Go). 3. In the `build/Release-iphoneos` directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device. > > `scp -r AccelerometerGraph.app root@jasoniphone:/Applications/` > > > 4. Let SpringBoard know the new application has been installed: > > `ssh mobile@jasoniphone.local uicache` > > > This only has to be done when you add or remove applications. Updated applications just need to be relaunched. To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project. Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard: ``` ssh root@jasoniphone.local rm -r /Applications/AccelerometerGraph.app && ssh mobile@jasoniphone.local uicache ```
37,471
<p>The minimum spanning tree problem is to take a connected weighted graph and find the subset of its edges with the lowest total weight while keeping the graph connected (and as a consequence resulting in an acyclic graph).</p> <p>The algorithm I am considering is:</p> <ul> <li>Find all cycles.</li> <li>remove the largest edge from each cycle.</li> </ul> <p>The impetus for this version is an environment that is restricted to "rule satisfaction" without any iterative constructs. It might also be applicable to insanely parallel hardware (i.e. a system where you expect to have several times more degrees of parallelism then cycles).</p> <p>Edits:</p> <p>The above is done in a stateless manner (all edges that are not the largest edge in any cycle are selected/kept/ignored, all others are removed).</p>
[ { "answer_id": 37477, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 1, "selected": false, "text": "<p>What happens if two cycles overlap? Which one has its longest edge removed first? Does it matter if the longest e...
2008/09/01
[ "https://Stackoverflow.com/questions/37471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
The minimum spanning tree problem is to take a connected weighted graph and find the subset of its edges with the lowest total weight while keeping the graph connected (and as a consequence resulting in an acyclic graph). The algorithm I am considering is: * Find all cycles. * remove the largest edge from each cycle. The impetus for this version is an environment that is restricted to "rule satisfaction" without any iterative constructs. It might also be applicable to insanely parallel hardware (i.e. a system where you expect to have several times more degrees of parallelism then cycles). Edits: The above is done in a stateless manner (all edges that are not the largest edge in any cycle are selected/kept/ignored, all others are removed).
What happens if two cycles overlap? Which one has its longest edge removed first? Does it matter if the longest edge of each is shared between the two cycles or not? For example: ``` V = { a, b, c, d } E = { (a,b,1), (b,c,2), (c,a,4), (b,d,9), (d,a,3) } ``` There's an a -> b -> c -> a cycle, and an a -> b -> d -> a
37,473
<p>If I use <code>assert()</code> and the assertion fails then <code>assert()</code> will call <code>abort()</code>, ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?</p>
[ { "answer_id": 37474, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 6, "selected": true, "text": "<p>Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s <code>assert()</co...
2008/09/01
[ "https://Stackoverflow.com/questions/37473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/456/" ]
If I use `assert()` and the assertion fails then `assert()` will call `abort()`, ending the running program abruptly. I can't afford that in my production code. Is there a way to assert in runtime yet be able to catch failed assertions so I have the chance to handle them gracefully?
Yes, as a matter of fact there is. You will need to write a custom assert function yourself, as C++'s `assert()` is exactly C's `assert()`, with the `abort()` "feature" bundled in. Fortunately, this is surprisingly straightforward. *Assert.hh* ``` template <typename X, typename A> inline void Assert(A assertion) { if( !assertion ) throw X(); } ``` The above function will throw an exception if a predicate doesn't hold. You will then have the chance to catch the exception. If you don't catch the exception, `terminate()` will be called, which will end the program similarly to `abort()`. You may wonder what about optimizing away the assertion when we're building for production. In this case, you can define constants that will signify that you're building for production and then refer to the constant when you `Assert()`. *debug.hh* ``` #ifdef NDEBUG const bool CHECK_WRONG = false; #else const bool CHECK_WRONG = true; #endif ``` *main.cc* ``` #include<iostream> struct Wrong { }; int main() { try { Assert<Wrong>(!CHECK_WRONG || 2 + 2 == 5); std::cout << "I can go to sleep now.\n"; } catch( Wrong e ) { std::cerr << "Someone is wrong on the internet!\n"; } return 0; } ``` If `CHECK_WRONG` is a constant then the call to `Assert()` will be compiled away in production, even if the assertion is not a constant expression. There is a slight disadvantage in that by referring to `CHECK_WRONG` we type a little more. But in exchange we gain an advantage in that we can classify various groups of assertions and enable and disable each of them as we see fit. So, for example we could define a group of assertions that we want enabled even in production code, and then define a group of assertions that we only want to see in development builds. The `Assert()` function is equivalent to typing ``` if( !assertion ) throw X(); ``` but it clearly indicates the intent of the programmer: make an assertion. Assertions are also easier to grep for with this approach, just like plain `assert()`s. For more details on this technique see Bjarne Stroustrup's The C++ Programming Language 3e, section 24.3.7.2.
37,479
<p>Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name.</p> <pre><code>import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("&lt;H1&gt;","&lt;/H1&gt;")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() </code></pre> <p>Output:</p> <pre>Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters</pre> <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>
[ { "answer_id": 37488, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>Is what I'm trying to do possible? If so, what am I doing wrong?</p>\n</blockquote>\n\n<p>It's certa...
2008/09/01
[ "https://Stackoverflow.com/questions/37479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1057/" ]
Below I have a very simple example of what I'm trying to do. I want to be able to use HTMLDecorator with any other class. Ignore the fact it's called decorator, it's just a name. ``` import cgi class ClassX(object): pass # ... with own __repr__ class ClassY(object): pass # ... with own __repr__ inst_x=ClassX() inst_y=ClassY() inst_z=[ i*i for i in range(25) ] inst_b=True class HTMLDecorator(object): def html(self): # an "enhanced" version of __repr__ return cgi.escape(self.__repr__()).join(("<H1>","</H1>")) print HTMLDecorator(inst_x).html() print HTMLDecorator(inst_y).html() wrapped_z = HTMLDecorator(inst_z) inst_z[0] += 70 wrapped_z[0] += 71 print wrapped_z.html() print HTMLDecorator(inst_b).html() ``` Output: ``` Traceback (most recent call last): File "html.py", line 21, in print HTMLDecorator(inst_x).html() TypeError: default __new__ takes no parameters ``` Is what I'm trying to do possible? If so, what am I doing wrong?
> > Very close, but then I lose everything from ClassX. Below is something a collegue gave me that does do the trick, but it's hideous. There has to be a better way. > > > Looks like you're trying to set up some sort of proxy object scheme. That's doable, and there are better solutions than your colleague's, but first consider whether it would be easier to just patch in some extra methods. This won't work for built-in classes like `bool`, but it will for your user-defined classes: ``` def HTMLDecorator (obj): def html (): sep = cgi.escape (repr (obj)) return sep.join (("<H1>", "</H1>")) obj.html = html return obj ``` And here is the proxy version: ``` class HTMLDecorator(object): def __init__ (self, wrapped): self.__wrapped = wrapped def html (self): sep = cgi.escape (repr (self.__wrapped)) return sep.join (("<H1>", "</H1>")) def __getattr__ (self, name): return getattr (self.__wrapped, name) def __setattr__ (self, name, value): if not name.startswith ('_HTMLDecorator__'): setattr (self.__wrapped, name, value) return super (HTMLDecorator, self).__setattr__ (name, value) def __delattr__ (self, name): delattr (self.__wraped, name) ```
37,486
<p>Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.</p>
[ { "answer_id": 37496, "author": "bernhardrusch", "author_id": 3056, "author_profile": "https://Stackoverflow.com/users/3056", "pm_score": 2, "selected": false, "text": "<p>How about parsing the HTML data and extracting the data with the help of the parser ?</p>\n\n<p>I'd try something li...
2008/09/01
[ "https://Stackoverflow.com/questions/37486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3971/" ]
Because regular expressions scare me, I'm trying to find a way to remove all HTML tags and resolve HTML entities from a string in Python.
Use [lxml](http://lxml.de/) which is the best xml/html library for python. ``` import lxml.html t = lxml.html.fromstring("...") t.text_content() ``` And if you just want to sanitize the html look at the lxml.html.clean [module](http://lxml.de/lxmlhtml.html#cleaning-up-html)
37,538
<p>How do I determine the size of my array in C? </p> <p>That is, the number of elements the array can hold?</p>
[ { "answer_id": 37539, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 12, "selected": true, "text": "<p><strong>Executive summary:</strong></p>\n\n<pre><code>int a[17];\nsize_t n = sizeof(a)/sizeof(a[0]);\n</code></pre>\n\...
2008/09/01
[ "https://Stackoverflow.com/questions/37538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
How do I determine the size of my array in C? That is, the number of elements the array can hold?
**Executive summary:** ``` int a[17]; size_t n = sizeof(a)/sizeof(a[0]); ``` --- **Full answer:** To determine the size of your array in bytes, you can use the `sizeof` operator: ``` int a[17]; size_t n = sizeof(a); ``` On my computer, ints are 4 bytes long, so n is 68. To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this: ``` int a[17]; size_t n = sizeof(a) / sizeof(int); ``` and get the proper answer (68 / 4 = 17), but if the type of `a` changed you would have a nasty bug if you forgot to change the `sizeof(int)` as well. So the preferred divisor is `sizeof(a[0])` or the equivalent `sizeof(*a)`, the size of the first element of the array. ``` int a[17]; size_t n = sizeof(a) / sizeof(a[0]); ``` Another advantage is that you can now easily parameterize the array name in a macro and get: ``` #define NELEMS(x) (sizeof(x) / sizeof((x)[0])) int a[17]; size_t n = NELEMS(a); ```
37,551
<p>I have a problem with an application running on Fedora Core 6 with JDK 1.5.0_08.</p> <p>After some amount of uptime (usually some days) threads begin getting stuck in native methods.</p> <p>The threads are locked in something like this:</p> <pre><code>&quot;pool-2-thread-2571&quot; prio=1 tid=0x08dd0b28 nid=0x319e waiting for monitor entry [0xb91fe000..0xb91ff7d4] at java.lang.Class.getDeclaredConstructors0(Native Method) </code></pre> <p>or</p> <pre><code>&quot;pool-2-thread-2547&quot; prio=1 tid=0x75641620 nid=0x1745 waiting for monitor entry [0xbc7fe000..0xbc7ff554] at sun.misc.Unsafe.defineClass(Native Method) </code></pre> <p>Especially puzzling to me is this one:</p> <pre><code>&quot;HealthMonitor-10&quot; daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4] at java.lang.Thread.dumpThreads(Native Method) at java.lang.Thread.getStackTrace(Thread.java:1383) </code></pre> <p>The threads remain stuck until the VM is restarted.</p> <p>Can anyone give me an idea as to what is happening here, what might be causing the native methods to block? The monitor entry address range at the top of each stuck thread is different. How can I figure out what is holding this monitor?</p>
[ { "answer_id": 38320, "author": "John Smithers", "author_id": 1069, "author_profile": "https://Stackoverflow.com/users/1069", "pm_score": 0, "selected": false, "text": "<p>Maybe you should use another jdk version.<br>\nFor your \"puzzling one\", there is a bug entry for 1.5.0_08. A memor...
2008/09/01
[ "https://Stackoverflow.com/questions/37551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3904/" ]
I have a problem with an application running on Fedora Core 6 with JDK 1.5.0\_08. After some amount of uptime (usually some days) threads begin getting stuck in native methods. The threads are locked in something like this: ``` "pool-2-thread-2571" prio=1 tid=0x08dd0b28 nid=0x319e waiting for monitor entry [0xb91fe000..0xb91ff7d4] at java.lang.Class.getDeclaredConstructors0(Native Method) ``` or ``` "pool-2-thread-2547" prio=1 tid=0x75641620 nid=0x1745 waiting for monitor entry [0xbc7fe000..0xbc7ff554] at sun.misc.Unsafe.defineClass(Native Method) ``` Especially puzzling to me is this one: ``` "HealthMonitor-10" daemon prio=1 tid=0x0868d1c0 nid=0x2b72 waiting for monitor entry [0xbe5ff000..0xbe5ff4d4] at java.lang.Thread.dumpThreads(Native Method) at java.lang.Thread.getStackTrace(Thread.java:1383) ``` The threads remain stuck until the VM is restarted. Can anyone give me an idea as to what is happening here, what might be causing the native methods to block? The monitor entry address range at the top of each stuck thread is different. How can I figure out what is holding this monitor?
My initial suspicion would be that you are experiencing some sort of class-loader realted dead lock. I imagine, that class loading needs to be synchronized at some level because class information will become available for the entire VM, not just the thread where it was initially loaded. The fact that the methods on top of the stack are native methods seems to be pure coincidence, since part of the class loading mechanism happens to implemented that way. I would investigate further what is going on class-loading wise. Maybe some thread uses the class loader to load a class from a network location which is slow/unavailable and thus blocks for a really long time, not yielding the monitor to other threads that want to load a class. Investigating the output when starting the JVM with -verbose:class might be one thing to try.
37,568
<p>How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better?</p> <p>Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: </p> <pre><code>Quellenstrasse 66/11 Quellenstr. 66a-11 </code></pre> <p>I'm talking German addresses... Thanks!</p>
[ { "answer_id": 37577, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 0, "selected": false, "text": "<p>Often you use constraints in a database to ensure data to be \"unique\" in the data-based sense.</p>\n\n<p>Regarding \"isomorph...
2008/09/01
[ "https://Stackoverflow.com/questions/37568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/925/" ]
How do I find duplicate addresses in a database, or better stop people already when filling in the form ? I guess the earlier the better? Is there any good way of abstracting street, postal code etc so that typos and simple attempts to get 2 registrations can be detected? like: ``` Quellenstrasse 66/11 Quellenstr. 66a-11 ``` I'm talking German addresses... Thanks!
> > Johannes: > > > > > > > @PConroy: This was my initial thougt also. the interesting part on this is to find good transformation rules for the different parts of the address! Any good suggestions? > > > > > > > > > When we were working on this type of project before, our approach was to take our existing corpus of addresses (150k or so), then apply the most common transformations for our domain (Ireland, so "Dr"->"Drive", "Rd"->"Road", etc). I'm afraid there was no comprehensive online resource for such things at the time, so we ended up basically coming up with a list ourselves, checking things like the phone book (pressed for space there, addresses are abbreviated in all manner of ways!). As I mentioned earlier, you'd be amazed how many "duplicates" you'll detect with the addition of only a few common rules! I've recently stumbled across a page with a fairly comprehensive [list of address abbreviations](https://sites.google.com/site/masteraddressfile//zp4/abbrev), although it's american english, so I'm not sure how useful it'd be in Germany! A quick google turned up a couple of sites, but they seemed like spammy newsletter sign-up traps. Although that was me googling in english, so you may have more look with "german address abbreviations" in german :)
37,591
<p>I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job.</p> <p>The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of:</p> <pre><code>&lt;error&gt; &lt;serverVariables&gt; &lt;item&gt; &lt;value&gt; &lt;/item&gt; &lt;/serverVariables&gt; &lt;queryString&gt; &lt;item name=""&gt; &lt;value string=""&gt; &lt;/item&gt; &lt;/queryString&gt; &lt;/error&gt; </code></pre> <p>I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a <em>Name : string</em> format.</p> <p>Any suggestions or am I looking and a custom implementation?</p> <p>[EDIT] A section of the data that needs to be displayed:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;error host="WIN12" type="System.Web.HttpException" message="The file '' does not exist." source="System.Web" detail="System.Web.HttpException: The file '' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at" time="2008-09-01T07:13:08.9171250+02:00" statusCode="404"&gt; &lt;serverVariables&gt; &lt;item name="ALL_HTTP"&gt; &lt;value string="HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) " /&gt; &lt;/item&gt; &lt;item name="AUTH_TYPE"&gt; &lt;value string="" /&gt; &lt;/item&gt; &lt;item name="HTTPS"&gt; &lt;value string="off" /&gt; &lt;/item&gt; &lt;item name="HTTPS_KEYSIZE"&gt; &lt;value string="" /&gt; &lt;/item&gt; &lt;item name="HTTP_USER_AGENT"&gt; &lt;value string="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" /&gt; &lt;/item&gt; &lt;/serverVariables&gt; &lt;queryString&gt; &lt;item name="tid"&gt; &lt;value string="196" /&gt; &lt;/item&gt; &lt;/queryString&gt; &lt;/error&gt; </code></pre>
[ { "answer_id": 37612, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<p>You could try using the <code>DataGridView</code> control. To see an example, load an XML file in DevStudio and then right-c...
2008/09/01
[ "https://Stackoverflow.com/questions/37591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/231/" ]
I would like to display details of an xml error log to a user in a winforms application and am looking for the best control to do the job. The error data contains all of the sever variables at the time that the error occurred. These have been formatted into an XML document that looks something to the effect of: ``` <error> <serverVariables> <item> <value> </item> </serverVariables> <queryString> <item name=""> <value string=""> </item> </queryString> </error> ``` I would like to read this data from the string that it is stored in and display it to the user via a windows form in a useful way. XML Notepad does a cool job of formatting xml, but is not really was I am looking for since I would prefer to rather display item details in a *Name : string* format. Any suggestions or am I looking and a custom implementation? [EDIT] A section of the data that needs to be displayed: ``` <?xml version="1.0" encoding="utf-8"?> <error host="WIN12" type="System.Web.HttpException" message="The file '' does not exist." source="System.Web" detail="System.Web.HttpException: The file '' does not exist. at System.Web.UI.Util.CheckVirtualFileExists(VirtualPath virtualPath) at" time="2008-09-01T07:13:08.9171250+02:00" statusCode="404"> <serverVariables> <item name="ALL_HTTP"> <value string="HTTP_CONNECTION:close HTTP_USER_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) " /> </item> <item name="AUTH_TYPE"> <value string="" /> </item> <item name="HTTPS"> <value string="off" /> </item> <item name="HTTPS_KEYSIZE"> <value string="" /> </item> <item name="HTTP_USER_AGENT"> <value string="Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)" /> </item> </serverVariables> <queryString> <item name="tid"> <value string="196" /> </item> </queryString> </error> ```
You can transform your XML data using [XSLT](http://www.xml.com/pub/a/2002/08/14/dotnetxslt.html) Another option is to use XLinq. If you want concrete code example provide us with sample data **EDIT**: here is a sample XSLT transform for your XML file: ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:template match="//error/serverVariables"> <xsl:text>Server variables: </xsl:text> <xsl:for-each select="item"> <xsl:value-of select="@name"/>:<xsl:value-of select="value/@string"/> <xsl:text> </xsl:text> </xsl:for-each> </xsl:template> <xsl:template match="//error/queryString"> <xsl:text>Query string items: </xsl:text> <xsl:for-each select="item"> <xsl:value-of select="@name"/>:<xsl:value-of select="value/@string"/> <xsl:text> </xsl:text> </xsl:for-each> </xsl:template> </xsl:stylesheet> ``` You can apply this transform using [XslCompiledTransform](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx) class. It should give output like this: > > Server variables: > > ALL\_HTTP:HTTP\_CONNECTION:close HTTP\_USER\_AGENT:Mozilla/4.0 (compatible MSIE 6.0; Windows NT 5.1; SV1) > > AUTH\_TYPE: > > HTTPS:off > > HTTPS\_KEYSIZE: > > HTTP\_USER\_AGENT:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;S ) > > > Query string items: > > tid:196 > > >
37,597
<p>TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics?</p>
[ { "answer_id": 37607, "author": "Luke Halliwell", "author_id": 3974, "author_profile": "https://Stackoverflow.com/users/3974", "pm_score": 0, "selected": false, "text": "<p>Yes, Windows Forms dates back to before generics in .Net</p>\n" }, { "answer_id": 37609, "author": "Art...
2008/09/01
[ "https://Stackoverflow.com/questions/37597", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2608/" ]
TreeNodeCollection, like some of the other control collections in System.Windows.Forms, implements IEnumerable. Is there any design reason behind this or is it just a hangover from the days before generics?
Yes, there are many .NET Framework collection, that does not implement generic IEnumerable. I think that's because after 2.0 there was no (at least not so match) development of the core part of FW. Meanwhile I suggest you to make use of following workaround: ``` using System.Linq; ... var nodes = GetTreeNodeCollection().OfType<TreeNode>(); ```
37,628
<p>What is reflection, and why is it useful?</p> <p>I'm particularly interested in Java, but I assume the principles are the same in any language.</p>
[ { "answer_id": 37632, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 12, "selected": true, "text": "<p>The name reflection is used to describe code which is able to inspect other code in the same system (or itself).</p>\n...
2008/09/01
[ "https://Stackoverflow.com/questions/37628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/142/" ]
What is reflection, and why is it useful? I'm particularly interested in Java, but I assume the principles are the same in any language.
The name reflection is used to describe code which is able to inspect other code in the same system (or itself). For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to. So, to give you a code example of this in Java (imagine the object in question is foo) : ``` Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null); ``` One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test. There are some good reflection examples to get you started at <http://docs.oracle.com/javase/tutorial/reflect/index.html> And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common. **Update from a comment:** > > The ability to inspect the code in the system and see object types is > not reflection, but rather Type Introspection. Reflection is then the > ability to make modifications at runtime by making use of > introspection. The distinction is necessary here as some languages > support introspection, but do not support reflection. One such example > is C++ > > >
37,649
<p>I have a MySQL table with coordinates, the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that.</p> <p>Is this possible to do with <b>UPDATE</b> in some way? <b>UPDATE table SET X=Y, Y=X</b> obviously won't do what I want.</p> <hr> <p>Edit: Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.</p>
[ { "answer_id": 37653, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 2, "selected": false, "text": "<p>Two alternatives \n 1. Use a temporary table \n 2. Investigate\n the <a href=\"http://en.wikipedia.org/wiki/XOR_swap_a...
2008/09/01
[ "https://Stackoverflow.com/questions/37649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/890/" ]
I have a MySQL table with coordinates, the column names are X and Y. Now I want to swap the column values in this table, so that X becomes Y and Y becomes X. The most apparent solution would be renaming the columns, but I don't want to make structure changes since I don't necessarily have permissions to do that. Is this possible to do with **UPDATE** in some way? **UPDATE table SET X=Y, Y=X** obviously won't do what I want. --- Edit: Please note that my restriction on permissions, mentioned above, effectively prevents the use of ALTER TABLE or other commands that change the table/database structure. Renaming columns or adding new ones are unfortunately not options.
I just had to deal with the same and I'll summarize my findings. 1. The `UPDATE table SET X=Y, Y=X` approach obviously doesn't work, as it'll just set both values to Y. 2. Here's a method that uses a temporary variable. Thanks to Antony from the comments of <http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/> for the "IS NOT NULL" tweak. Without it, the query works unpredictably. See the table schema at the end of the post. This method doesn't swap the values if one of them is NULL. Use method #3 that doesn't have this limitation. `UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL;` 3. This method was offered by Dipin in, yet again, the comments of <http://beerpla.net/2009/02/17/swapping-column-values-in-mysql/>. I think it’s the most elegant and clean solution. It works with both NULL and non-NULL values. `UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp;` 4. Another approach I came up with that seems to work: `UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;` Essentially, the 1st table is the one getting updated and the 2nd one is used to pull the old data from. Note that this approach requires a primary key to be present. This is my test schema: ``` CREATE TABLE `swap_test` ( `id` int(11) NOT NULL AUTO_INCREMENT, `x` varchar(255) DEFAULT NULL, `y` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB; INSERT INTO `swap_test` VALUES ('1', 'a', '10'); INSERT INTO `swap_test` VALUES ('2', NULL, '20'); INSERT INTO `swap_test` VALUES ('3', 'c', NULL); ```
37,650
<p>What is the best way to implement, from a web page a download action using asp.net 2.0?</p> <p>Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.</p>
[ { "answer_id": 37656, "author": "Martin", "author_id": 770, "author_profile": "https://Stackoverflow.com/users/770", "pm_score": 6, "selected": true, "text": "<p>Does this help:</p>\n\n<p><a href=\"http://www.west-wind.com/weblog/posts/76293.aspx\" rel=\"noreferrer\">http://www.west-wind...
2008/09/01
[ "https://Stackoverflow.com/questions/37650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3416/" ]
What is the best way to implement, from a web page a download action using asp.net 2.0? Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.
Does this help: <http://www.west-wind.com/weblog/posts/76293.aspx> ``` Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt"); Response.TransmitFile( Server.MapPath("~/logfile.txt") ); Response.End(); ``` Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.
37,665
<p>When <strong>Eclipse</strong> creates a new file (<strong>.c</strong> or <strong>.h</strong> file) in a C project the editor always auto creates a <code>#define</code> at the top of the file like this: If the file is named 'myCFile.c' there will be a <code>#define</code> at the start of the file like this</p> <pre><code>#ifndef MYCFILE_C_ #define MYCFILE_C_ </code></pre> <p>I have seen other editors do this as well (Codewright and SlikEdit I think). The <code>#defines</code> don't seem to do anything for the editor as I can just delete them without any problem, and I can't think of a reason why <em>I</em> would want to use them. Does anyone know why they are there? </p>
[ { "answer_id": 37668, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 3, "selected": true, "text": "<p>It's to guard against <a href=\"http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html\" rel=\"nofollow norefer...
2008/09/01
[ "https://Stackoverflow.com/questions/37665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2079/" ]
When **Eclipse** creates a new file (**.c** or **.h** file) in a C project the editor always auto creates a `#define` at the top of the file like this: If the file is named 'myCFile.c' there will be a `#define` at the start of the file like this ``` #ifndef MYCFILE_C_ #define MYCFILE_C_ ``` I have seen other editors do this as well (Codewright and SlikEdit I think). The `#defines` don't seem to do anything for the editor as I can just delete them without any problem, and I can't think of a reason why *I* would want to use them. Does anyone know why they are there?
It's to guard against [multiple definitions](http://www.fredosaurus.com/notes-cpp/preprocessor/ifdef.html).
37,684
<p>I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match.</p> <p>How I can replace all the URL? I guess I should be using the <em>exec</em> command, but I did not really figure how to do it.</p> <pre><code>function replaceURLWithHTMLLinks(text) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&amp;@#\/%?=~_|!:,.;]*[-A-Z0-9+&amp;@#\/%=~_|])/i; return text.replace(exp,"&lt;a href='$1'&gt;$1&lt;/a&gt;"); } </code></pre>
[ { "answer_id": 37687, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 8, "selected": false, "text": "<h3>Replacing URLs with links (Answer to the General Problem)</h3>\n\n<p>The regular expression in the question misses <em...
2008/09/01
[ "https://Stackoverflow.com/questions/37684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I am using the function below to match URLs inside a given text and replace them for HTML links. The regular expression is working great, but currently I am only replacing the first match. How I can replace all the URL? I guess I should be using the *exec* command, but I did not really figure how to do it. ``` function replaceURLWithHTMLLinks(text) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i; return text.replace(exp,"<a href='$1'>$1</a>"); } ```
First off, rolling your own regexp to parse URLs is a *terrible idea*. You must imagine this is a common enough problem that someone has written, debugged and [tested](http://benalman.com/code/test/js-linkify/) a library for it, according to [the RFCs](https://metacpan.org/pod/Regexp::Common::URI#REFERENCES). **URIs are complex** - check out the [code for URL parsing in Node.js](https://github.com/joyent/node/blob/master/lib/url.js) and the Wikipedia page on [URI schemes](http://en.wikipedia.org/wiki/URI_scheme). There are a ton of edge cases when it comes to parsing URLs: [international domain names](http://en.wikipedia.org/wiki/Top-level_domain#IDN_test_domains), actual (`.museum`) vs. nonexistent (`.etc`) TLDs, weird punctuation including [parentheses](http://www.codinghorror.com/blog/2008/10/the-problem-with-urls.html), punctuation at the end of the URL, IPV6 hostnames etc. I've looked at [a ton](https://github.com/search?l=JavaScript&q=linkify&ref=cmdform&search_target=global&type=Repositories) of [libraries](https://github.com/search?l=JavaScript&q=autolink&ref=cmdform&search_target=global&type=Repositories), and there are a few worth using despite some downsides: * Soapbox's [linkify](http://soapbox.github.io/jQuery-linkify/) has seen some serious effort put into it, and [a major refactor in June 2015](https://github.com/SoapBox/jQuery-linkify/pull/51) [removed the jQuery dependency](https://github.com/SoapBox/jQuery-linkify/issues/56). It still has [issues with IDNs](https://github.com/SoapBox/linkifyjs/issues/92). * [AnchorMe](http://alexcorvi.github.io/anchorme.js/) is a newcomer that [claims to be faster](https://github.com/ali-saleem/anchorme.js/issues/2) and leaner. Some [IDN issues](https://github.com/ali-saleem/anchorme.js/issues/1) as well. * [Autolinker.js](https://github.com/gregjacobs/Autolinker.js) lists features very specifically (e.g. *"Will properly handle HTML input. The utility will not change the `href` attribute inside anchor () tags"*). I'll thrown some tests at it when a [demo becomes available](https://github.com/gregjacobs/Autolinker.js/issues/138). Libraries that I've disqualified quickly for this task: * Django's urlize [didn't handle certain TLDs properly](https://github.com/ljosa/urlize.js/pull/18) (here is the official [list of valid TLDs](http://data.iana.org/TLD/tlds-alpha-by-domain.txt). [No demo](https://github.com/ljosa/urlize.js/issues/21). * [autolink-js](https://github.com/bryanwoods/autolink-js/issues/12) wouldn't detect "www.google.com" without http://, so it's not quite suitable for autolinking "casual URLs" (without a scheme/protocol) found in plain text. * [Ben Alman's linkify](https://github.com/cowboy/javascript-linkify) hasn't been maintained since 2009. If you insist on a regular expression, the most comprehensive is the [URL regexp from Component](https://github.com/component/regexps/blob/master/index.js#L3), though it will falsely detect some non-existent two-letter TLDs by looking at it.
37,696
<p>I have three tables <code>tag</code>, <code>page</code>, <code>pagetag</code></p> <p>With the data below</p> <p><strong><em>page</em></strong></p> <pre><code>ID NAME 1 page 1 2 page 2 3 page 3 4 page 4 </code></pre> <p><strong><em>tag</em></strong></p> <pre><code>ID NAME 1 tag 1 2 tag 2 3 tag 3 4 tag 4 </code></pre> <p><strong><em>pagetag</em></strong></p> <pre><code>ID PAGEID TAGID 1 2 1 2 2 3 3 3 4 4 1 1 5 1 2 6 1 3 </code></pre> <p>I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output.</p> <pre><code>ID NAME TAGS 1 page 1 tag 1, tag 2, tag 3 2 page 2 tag 1, tag 3 3 page 3 tag 4 4 page 4 </code></pre> <p>Is this possible with SQL?</p> <hr> <p>I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.</p>
[ { "answer_id": 37700, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 2, "selected": false, "text": "<p>Yep, you can do it across the 3 something like the below:</p>\n\n<pre><code>SELECT page_tag.id, page.name, group_concat(ta...
2008/09/01
[ "https://Stackoverflow.com/questions/37696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I have three tables `tag`, `page`, `pagetag` With the data below ***page*** ``` ID NAME 1 page 1 2 page 2 3 page 3 4 page 4 ``` ***tag*** ``` ID NAME 1 tag 1 2 tag 2 3 tag 3 4 tag 4 ``` ***pagetag*** ``` ID PAGEID TAGID 1 2 1 2 2 3 3 3 4 4 1 1 5 1 2 6 1 3 ``` I would like to get a string containing the correspondent tag names for each page with SQL in a single query. This is my desired output. ``` ID NAME TAGS 1 page 1 tag 1, tag 2, tag 3 2 page 2 tag 1, tag 3 3 page 3 tag 4 4 page 4 ``` Is this possible with SQL? --- I am using MySQL. Nonetheless, I would like a database vendor independent solution if possible.
> > Sergio del Amo: > > > > > > > However, I am not getting the pages without tags. I guess i need to write my query with left outer joins. > > > > > > > > > ``` SELECT pagetag.id, page.name, group_concat(tag.name) FROM ( page LEFT JOIN pagetag ON page.id = pagetag.pageid ) LEFT JOIN tag ON pagetag.tagid = tag.id GROUP BY page.id; ``` Not a very pretty query, but should give you what you want - `pagetag.id` and `group_concat(tag.name)` will be `null` for page 4 in the example you've posted above, but the page shall appear in the results.