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
|
---|---|---|---|---|---|---|
68,283 | <p>What's a quick and easy way to view and edit ID3 tags (artist, album, etc.) using C#?</p>
| [
{
"answer_id": 68306,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html\" rel=\"noreferrer\">TagLib Sharp</a> has support for reading ID3 tags.</p>\n"
},
{
"answer_id": 68407,
"author": "mmcdole",
"author_id": 2635,
"author_profile": "https://Stackoverflow.com/users/2635",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html\" rel=\"noreferrer\">TagLib Sharp</a> is pretty popular.</p>\n\n<p>As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.</p>\n\n<pre><code>class MusicID3Tag\n\n{\n\n public byte[] TAGID = new byte[3]; // 3\n public byte[] Title = new byte[30]; // 30\n public byte[] Artist = new byte[30]; // 30 \n public byte[] Album = new byte[30]; // 30 \n public byte[] Year = new byte[4]; // 4 \n public byte[] Comment = new byte[30]; // 30 \n public byte[] Genre = new byte[1]; // 1\n\n}\n\nstring filePath = @\"C:\\Documents and Settings\\All Users\\Documents\\My Music\\Sample Music\\041105.mp3\";\n\n using (FileStream fs = File.OpenRead(filePath))\n {\n if (fs.Length >= 128)\n {\n MusicID3Tag tag = new MusicID3Tag();\n fs.Seek(-128, SeekOrigin.End);\n fs.Read(tag.TAGID, 0, tag.TAGID.Length);\n fs.Read(tag.Title, 0, tag.Title.Length);\n fs.Read(tag.Artist, 0, tag.Artist.Length);\n fs.Read(tag.Album, 0, tag.Album.Length);\n fs.Read(tag.Year, 0, tag.Year.Length);\n fs.Read(tag.Comment, 0, tag.Comment.Length);\n fs.Read(tag.Genre, 0, tag.Genre.Length);\n string theTAGID = Encoding.Default.GetString(tag.TAGID);\n\n if (theTAGID.Equals(\"TAG\"))\n {\n string Title = Encoding.Default.GetString(tag.Title);\n string Artist = Encoding.Default.GetString(tag.Artist);\n string Album = Encoding.Default.GetString(tag.Album);\n string Year = Encoding.Default.GetString(tag.Year);\n string Comment = Encoding.Default.GetString(tag.Comment);\n string Genre = Encoding.Default.GetString(tag.Genre);\n\n Console.WriteLine(Title);\n Console.WriteLine(Artist);\n Console.WriteLine(Album);\n Console.WriteLine(Year);\n Console.WriteLine(Comment);\n Console.WriteLine(Genre);\n Console.WriteLine();\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 281381,
"author": "Matt",
"author_id": 12747,
"author_profile": "https://Stackoverflow.com/users/12747",
"pm_score": 5,
"selected": false,
"text": "<p><s><a href=\"http://UltraID3Lib.com\" rel=\"nofollow noreferrer\">UltraID3Lib</a>...</s></p>\n\n<p>Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library</p>\n\n<pre><code>//using HundredMilesSoftware.UltraID3Lib;\nUltraID3 u = new UltraID3();\nu.Read(@\"C:\\mp3\\song.mp3\");\n//view\nConsole.WriteLine(u.Artist);\n//edit\nu.Artist = \"New Artist\";\nu.Write();\n</code></pre>\n"
},
{
"answer_id": 281413,
"author": "Luke",
"author_id": 261917,
"author_profile": "https://Stackoverflow.com/users/261917",
"pm_score": 9,
"selected": true,
"text": "<p>Thirding <a href=\"https://github.com/mono/taglib-sharp\" rel=\"noreferrer\">TagLib Sharp</a>.</p>\n\n<pre><code>TagLib.File f = TagLib.File.Create(path);\nf.Tag.Album = \"New Album Title\";\nf.Save();\n</code></pre>\n"
},
{
"answer_id": 3560409,
"author": "Daniel Mošmondor",
"author_id": 166251,
"author_profile": "https://Stackoverflow.com/users/166251",
"pm_score": 2,
"selected": false,
"text": "<p>I wrapped mp3 decoder library and made it available for .net developers. You can find it here:</p>\n\n<p><a href=\"http://sourceforge.net/projects/mpg123net/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/mpg123net/</a></p>\n\n<p>Included are the samples to convert mp3 file to PCM, and read ID3 tags.</p>\n"
},
{
"answer_id": 26444188,
"author": "0x8BADF00D",
"author_id": 3436418,
"author_profile": "https://Stackoverflow.com/users/3436418",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://id3.codeplex.com/\" rel=\"nofollow\">ID3.NET</a> implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files.\nThere's also a <a href=\"https://www.nuget.org/packages/ID3/\" rel=\"nofollow\">NuGet package</a> available.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68283",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10606/"
]
| What's a quick and easy way to view and edit ID3 tags (artist, album, etc.) using C#? | Thirding [TagLib Sharp](https://github.com/mono/taglib-sharp).
```
TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";
f.Save();
``` |
68,291 | <p>If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this? </p>
<p>Simple Click logging in the DB associated with the post entry? </p>
<p>A/B testing where you would show one version of the algorithm togroup A and another to group B and measure the clicks? </p>
<p>What sort of characteristics would you base your decision on as to whether the changes were better? </p>
| [
{
"answer_id": 68306,
"author": "tslocum",
"author_id": 1662,
"author_profile": "https://Stackoverflow.com/users/1662",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html\" rel=\"noreferrer\">TagLib Sharp</a> has support for reading ID3 tags.</p>\n"
},
{
"answer_id": 68407,
"author": "mmcdole",
"author_id": 2635,
"author_profile": "https://Stackoverflow.com/users/2635",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://www.novell.com/products/linuxpackages/opensuse11.1/taglib-sharp.html\" rel=\"noreferrer\">TagLib Sharp</a> is pretty popular.</p>\n\n<p>As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.</p>\n\n<pre><code>class MusicID3Tag\n\n{\n\n public byte[] TAGID = new byte[3]; // 3\n public byte[] Title = new byte[30]; // 30\n public byte[] Artist = new byte[30]; // 30 \n public byte[] Album = new byte[30]; // 30 \n public byte[] Year = new byte[4]; // 4 \n public byte[] Comment = new byte[30]; // 30 \n public byte[] Genre = new byte[1]; // 1\n\n}\n\nstring filePath = @\"C:\\Documents and Settings\\All Users\\Documents\\My Music\\Sample Music\\041105.mp3\";\n\n using (FileStream fs = File.OpenRead(filePath))\n {\n if (fs.Length >= 128)\n {\n MusicID3Tag tag = new MusicID3Tag();\n fs.Seek(-128, SeekOrigin.End);\n fs.Read(tag.TAGID, 0, tag.TAGID.Length);\n fs.Read(tag.Title, 0, tag.Title.Length);\n fs.Read(tag.Artist, 0, tag.Artist.Length);\n fs.Read(tag.Album, 0, tag.Album.Length);\n fs.Read(tag.Year, 0, tag.Year.Length);\n fs.Read(tag.Comment, 0, tag.Comment.Length);\n fs.Read(tag.Genre, 0, tag.Genre.Length);\n string theTAGID = Encoding.Default.GetString(tag.TAGID);\n\n if (theTAGID.Equals(\"TAG\"))\n {\n string Title = Encoding.Default.GetString(tag.Title);\n string Artist = Encoding.Default.GetString(tag.Artist);\n string Album = Encoding.Default.GetString(tag.Album);\n string Year = Encoding.Default.GetString(tag.Year);\n string Comment = Encoding.Default.GetString(tag.Comment);\n string Genre = Encoding.Default.GetString(tag.Genre);\n\n Console.WriteLine(Title);\n Console.WriteLine(Artist);\n Console.WriteLine(Album);\n Console.WriteLine(Year);\n Console.WriteLine(Comment);\n Console.WriteLine(Genre);\n Console.WriteLine();\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 281381,
"author": "Matt",
"author_id": 12747,
"author_profile": "https://Stackoverflow.com/users/12747",
"pm_score": 5,
"selected": false,
"text": "<p><s><a href=\"http://UltraID3Lib.com\" rel=\"nofollow noreferrer\">UltraID3Lib</a>...</s></p>\n\n<p>Be aware that UltraID3Lib is no longer officially available, and thus no longer maintained. See comments below for the link to a Github project that includes this library</p>\n\n<pre><code>//using HundredMilesSoftware.UltraID3Lib;\nUltraID3 u = new UltraID3();\nu.Read(@\"C:\\mp3\\song.mp3\");\n//view\nConsole.WriteLine(u.Artist);\n//edit\nu.Artist = \"New Artist\";\nu.Write();\n</code></pre>\n"
},
{
"answer_id": 281413,
"author": "Luke",
"author_id": 261917,
"author_profile": "https://Stackoverflow.com/users/261917",
"pm_score": 9,
"selected": true,
"text": "<p>Thirding <a href=\"https://github.com/mono/taglib-sharp\" rel=\"noreferrer\">TagLib Sharp</a>.</p>\n\n<pre><code>TagLib.File f = TagLib.File.Create(path);\nf.Tag.Album = \"New Album Title\";\nf.Save();\n</code></pre>\n"
},
{
"answer_id": 3560409,
"author": "Daniel Mošmondor",
"author_id": 166251,
"author_profile": "https://Stackoverflow.com/users/166251",
"pm_score": 2,
"selected": false,
"text": "<p>I wrapped mp3 decoder library and made it available for .net developers. You can find it here:</p>\n\n<p><a href=\"http://sourceforge.net/projects/mpg123net/\" rel=\"nofollow noreferrer\">http://sourceforge.net/projects/mpg123net/</a></p>\n\n<p>Included are the samples to convert mp3 file to PCM, and read ID3 tags.</p>\n"
},
{
"answer_id": 26444188,
"author": "0x8BADF00D",
"author_id": 3436418,
"author_profile": "https://Stackoverflow.com/users/3436418",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://id3.codeplex.com/\" rel=\"nofollow\">ID3.NET</a> implemented ID3v1.x and ID3v2.3 and supports read/write operations on the ID3 section in MP3 files.\nThere's also a <a href=\"https://www.nuget.org/packages/ID3/\" rel=\"nofollow\">NuGet package</a> available.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/281/"
]
| If you were running a news site that created a list of 10 top news stories, and you wanted to make tweaks to your algorithm and see if people liked the new top story mix better, how would you approach this?
Simple Click logging in the DB associated with the post entry?
A/B testing where you would show one version of the algorithm togroup A and another to group B and measure the clicks?
What sort of characteristics would you base your decision on as to whether the changes were better? | Thirding [TagLib Sharp](https://github.com/mono/taglib-sharp).
```
TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";
f.Save();
``` |
68,327 | <p>I create a new Button object but did not specify the <code>command</code> option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?</p>
| [
{
"answer_id": 68455,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": false,
"text": "<p>Sure; just use the <code>bind</code> method to specify the callback after the button has been created. I've just written and tested the example below. You can find a nice tutorial on doing this at <a href=\"http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm\" rel=\"nofollow noreferrer\">http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm</a></p>\n\n<pre><code>from Tkinter import Tk, Button\n\nroot = Tk()\nbutton = Button(root, text=\"Click Me!\")\nbutton.pack()\n\ndef callback(event):\n print \"Hello World!\"\n\nbutton.bind(\"<Button-1>\", callback)\nroot.mainloop()\n</code></pre>\n"
},
{
"answer_id": 68524,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 6,
"selected": true,
"text": "<p>Though <a href=\"https://stackoverflow.com/questions/68327/change-command-method-for-tkinter-button-in-python#68455\">Eli Courtwright's</a> program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method.</p>\n\n<pre><code>from Tkinter import Tk, Button\n\ndef goodbye_world():\n print \"Goodbye World!\\nWait, I changed my mind!\"\n button.configure(text = \"Hello World!\", command=hello_world)\n\ndef hello_world():\n print \"Hello World!\\nWait, I changed my mind!\"\n button.configure(text = \"Goodbye World!\", command=goodbye_world)\n\nroot = Tk()\nbutton = Button(root, text=\"Hello World!\", command=hello_world)\nbutton.pack()\n\nroot.mainloop()\n</code></pre>\n\n<p>¹ \"fine\" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the <code>command</code> option through <code>.configure</code> is much easier.</p>\n\n<p>² the only attribute that can't change after instantiation is <code>name</code>.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
]
| I create a new Button object but did not specify the `command` option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created? | Though [Eli Courtwright's](https://stackoverflow.com/questions/68327/change-command-method-for-tkinter-button-in-python#68455) program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method.
```
from Tkinter import Tk, Button
def goodbye_world():
print "Goodbye World!\nWait, I changed my mind!"
button.configure(text = "Hello World!", command=hello_world)
def hello_world():
print "Hello World!\nWait, I changed my mind!"
button.configure(text = "Goodbye World!", command=goodbye_world)
root = Tk()
button = Button(root, text="Hello World!", command=hello_world)
button.pack()
root.mainloop()
```
¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the `command` option through `.configure` is much easier.
² the only attribute that can't change after instantiation is `name`. |
68,335 | <p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p>
<p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
| [
{
"answer_id": 68365,
"author": "pdq",
"author_id": 8598,
"author_profile": "https://Stackoverflow.com/users/8598",
"pm_score": 7,
"selected": true,
"text": "<p>You can call the <a href=\"https://en.wikipedia.org/wiki/Secure_copy\" rel=\"noreferrer\"><code>scp</code></a> bash command (it copies files over <a href=\"https://en.wikipedia.org/wiki/Secure_Shell\" rel=\"noreferrer\">SSH</a>) with <a href=\"https://docs.python.org/library/subprocess.html#subprocess.run\" rel=\"noreferrer\"><code>subprocess.run</code></a>:</p>\n\n<pre><code>import subprocess\nsubprocess.run([\"scp\", FILE, \"USER@SERVER:PATH\"])\n#e.g. subprocess.run([\"scp\", \"foo.bar\", \"[email protected]:/path/to/foo.bar\"])\n</code></pre>\n\n<p>If you're creating the file that you want to send in the same Python program, you'll want to call <code>subprocess.run</code> command outside the <code>with</code> block you're using to open the file (or call <code>.close()</code> on the file first if you're not using a <code>with</code> block), so you know it's flushed to disk from Python.</p>\n\n<p>You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).</p>\n"
},
{
"answer_id": 68377,
"author": "Drew Olson",
"author_id": 9434,
"author_profile": "https://Stackoverflow.com/users/9434",
"pm_score": -1,
"selected": false,
"text": "<p>Kind of hacky, but the following should work :)</p>\n\n<pre><code>import os\nfilePath = \"/foo/bar/baz.py\"\nserverPath = \"/blah/boo/boom.py\"\nos.system(\"scp \"+filePath+\" [email protected]:\"+serverPath)\n</code></pre>\n"
},
{
"answer_id": 68382,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": false,
"text": "<p>You'd probably use the <a href=\"http://docs.python.org/lib/module-subprocess.html\" rel=\"noreferrer\">subprocess module</a>. Something like this:</p>\n\n<pre><code>import subprocess\np = subprocess.Popen([\"scp\", myfile, destination])\nsts = os.waitpid(p.pid, 0)\n</code></pre>\n\n<p>Where <code>destination</code> is probably of the form <code>user@remotehost:remotepath</code>. Thanks to\n@Charles Duffy for pointing out the weakness in my original answer, which used a single string argument to specify the scp operation <code>shell=True</code> - that wouldn't handle whitespace in paths.</p>\n\n<p>The module documentation has <a href=\"http://docs.python.org/lib/node536.html\" rel=\"noreferrer\">examples of error checking that you may want to perform in conjunction with this operation.</a></p>\n\n<p>Ensure that you've set up proper credentials so that you can perform an <a href=\"http://www.debian.org/devel/passwordlessssh\" rel=\"noreferrer\">unattended, passwordless scp between the machines</a>. There is a <a href=\"https://stackoverflow.com/questions/7260/how-do-i-setup-public-key-authentication\">stackoverflow question for this already</a>.</p>\n"
},
{
"answer_id": 68566,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>There are a couple of different ways to approach the problem:</p>\n<ol>\n<li>Wrap command-line programs</li>\n<li>use a Python library that provides SSH capabilities (eg - <a href=\"https://www.paramiko.org/\" rel=\"nofollow noreferrer\">Paramiko</a> or <a href=\"https://twistedmatrix.com/trac/wiki/TwistedConch\" rel=\"nofollow noreferrer\">Twisted Conch</a>)</li>\n</ol>\n<p>Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.</p>\n<p>NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.</p>\n<p>I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.</p>\n<p>If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.</p>\n"
},
{
"answer_id": 69596,
"author": "Tony Meyer",
"author_id": 4966,
"author_profile": "https://Stackoverflow.com/users/4966",
"pm_score": 7,
"selected": false,
"text": "<p>To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the <a href=\"https://github.com/paramiko/paramiko\" rel=\"noreferrer\">Paramiko</a> library, you would do something like this:</p>\n\n<pre><code>import os\nimport paramiko\n\nssh = paramiko.SSHClient() \nssh.load_host_keys(os.path.expanduser(os.path.join(\"~\", \".ssh\", \"known_hosts\")))\nssh.connect(server, username=username, password=password)\nsftp = ssh.open_sftp()\nsftp.put(localpath, remotepath)\nsftp.close()\nssh.close()\n</code></pre>\n\n<p>(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).</p>\n"
},
{
"answer_id": 22710513,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://fabfile.org\" rel=\"nofollow\"><code>fabric</code></a> could be used to upload files vis ssh:</p>\n\n<pre><code>#!/usr/bin/env python\nfrom fabric.api import execute, put\nfrom fabric.network import disconnect_all\n\nif __name__==\"__main__\":\n import sys\n # specify hostname to connect to and the remote/local paths\n srcdir, remote_dirname, hostname = sys.argv[1:]\n try:\n s = execute(put, srcdir, remote_dirname, host=hostname)\n print(repr(s))\n finally:\n disconnect_all()\n</code></pre>\n"
},
{
"answer_id": 22710752,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p>Calling <code>scp</code> command via subprocess doesn't allow to receive the progress report inside the script. <code>pexpect</code> could be used to extract that info:</p>\n\n<pre><code>import pipes\nimport re\nimport pexpect # $ pip install pexpect\n\ndef progress(locals):\n # extract percents\n print(int(re.search(br'(\\d+)%$', locals['child'].after).group(1)))\n\ncommand = \"scp %s %s\" % tuple(map(pipes.quote, [srcfile, destination]))\npexpect.run(command, events={r'\\d+%': progress})\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/q/22687296/4279\">python copy file in local network (linux -> linux)</a></p>\n"
},
{
"answer_id": 38556319,
"author": "Maviles",
"author_id": 2653486,
"author_profile": "https://Stackoverflow.com/users/2653486",
"pm_score": 4,
"selected": false,
"text": "<p>Reached the same problem, but instead of \"hacking\" or emulating command line:</p>\n\n<p>Found this answer <a href=\"https://pypi.python.org/pypi/scp\" rel=\"noreferrer\">here</a>.</p>\n\n<pre><code>from paramiko import SSHClient\nfrom scp import SCPClient\n\nssh = SSHClient()\nssh.load_system_host_keys()\nssh.connect('example.com')\n\nwith SCPClient(ssh.get_transport()) as scp:\n scp.put('test.txt', 'test2.txt')\n scp.get('test2.txt')\n</code></pre>\n"
},
{
"answer_id": 45047041,
"author": "michael",
"author_id": 3055831,
"author_profile": "https://Stackoverflow.com/users/3055831",
"pm_score": 2,
"selected": false,
"text": "<p>Using the external resource paramiko;</p>\n\n<pre class=\"lang-py prettyprint-override\"><code> from paramiko import SSHClient\n from scp import SCPClient\n import os\n\n ssh = SSHClient() \n ssh.load_host_keys(os.path.expanduser(os.path.join(\"~\", \".ssh\", \"known_hosts\")))\n ssh.connect(server, username='username', password='password')\n with SCPClient(ssh.get_transport()) as scp:\n scp.put('test.txt', 'test2.txt')\n</code></pre>\n"
},
{
"answer_id": 48098653,
"author": "Roberto Marzocchi",
"author_id": 4903301,
"author_profile": "https://Stackoverflow.com/users/4903301",
"pm_score": 1,
"selected": false,
"text": "<p>A very simple approach is the following: </p>\n\n<pre><code>import os\nos.system('sshpass -p \"password\" scp user@host:/path/to/file ./')\n</code></pre>\n\n<p>No python library are required (only os), and it works, however using this method relies on another ssh client to be installed. This could result in undesired behavior if ran on another system.</p>\n"
},
{
"answer_id": 48634769,
"author": "Jonno_FTW",
"author_id": 150851,
"author_profile": "https://Stackoverflow.com/users/150851",
"pm_score": 1,
"selected": false,
"text": "<p>I used <a href=\"https://wiki.archlinux.org/index.php/SSHFS\" rel=\"nofollow noreferrer\">sshfs</a> to mount the remote directory via ssh, and <a href=\"https://docs.python.org/3/library/shutil.html\" rel=\"nofollow noreferrer\">shutil</a> to copy the files:</p>\n\n<pre><code>$ mkdir ~/sshmount\n$ sshfs user@remotehost:/path/to/remote/dst ~/sshmount\n</code></pre>\n\n<p>Then in python:</p>\n\n<pre><code>import shutil\nshutil.copy('a.txt', '~/sshmount')\n</code></pre>\n\n<p>This method has the advantage that you can stream data over if you are generating data rather than caching locally and sending a single large file.</p>\n"
},
{
"answer_id": 53344419,
"author": "Shawn",
"author_id": 7476764,
"author_profile": "https://Stackoverflow.com/users/7476764",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the vassal package, which is exactly designed for this.</p>\n\n<p>All you need is to install vassal and do</p>\n\n<pre><code>from vassal.terminal import Terminal\nshell = Terminal([\"scp username@host:/home/foo.txt foo_local.txt\"])\nshell.run()\n</code></pre>\n\n<p>Also, it will save you authenticate credential and don't need to type them again and again.</p>\n"
},
{
"answer_id": 53505120,
"author": "JavDomGom",
"author_id": 10691828,
"author_profile": "https://Stackoverflow.com/users/10691828",
"pm_score": 1,
"selected": false,
"text": "<p>Try this if you wan't to use SSL certificates:</p>\n\n<pre><code>import subprocess\n\ntry:\n # Set scp and ssh data.\n connUser = 'john'\n connHost = 'my.host.com'\n connPath = '/home/john/'\n connPrivateKey = '/home/user/myKey.pem'\n\n # Use scp to send file from local to host.\n scp = subprocess.Popen(['scp', '-i', connPrivateKey, 'myFile.txt', '{}@{}:{}'.format(connUser, connHost, connPath)])\n\nexcept CalledProcessError:\n print('ERROR: Connection to host failed!')\n</code></pre>\n"
},
{
"answer_id": 56850195,
"author": "Pradeep Pathak",
"author_id": 8092005,
"author_profile": "https://Stackoverflow.com/users/8092005",
"pm_score": 3,
"selected": false,
"text": "<p>You can do something like this, to handle the host key checking as well</p>\n\n<pre><code>import os\nos.system(\"sshpass -p password scp -o StrictHostKeyChecking=no local_file_path username@hostname:remote_path\")\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10668/"
]
| I have a text file on my local machine that is generated by a daily Python script run in cron.
I would like to add a bit of code to have that file sent securely to my server over SSH. | You can call the [`scp`](https://en.wikipedia.org/wiki/Secure_copy) bash command (it copies files over [SSH](https://en.wikipedia.org/wiki/Secure_Shell)) with [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run):
```
import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "[email protected]:/path/to/foo.bar"])
```
If you're creating the file that you want to send in the same Python program, you'll want to call `subprocess.run` command outside the `with` block you're using to open the file (or call `.close()` on the file first if you're not using a `with` block), so you know it's flushed to disk from Python.
You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password). |
68,352 | <p>I use this question in interviews and I wonder what the best solution is.</p>
<p>Write a Perl sub that takes <em>n</em> lists, and then returns 2^<em>n</em>-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that <em>n</em> is reasonably small (less than 20).</p>
<p>For example:</p>
<pre><code>list_compare([1, 3], [2, 3]);
=> ([1], [2], [3]);
</code></pre>
<p>Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.</p>
<pre><code>list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7])
=> ([1], [2], [3], [4], [5], [6], [7])
</code></pre>
<p>Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.</p>
<p>I usually give this problem as a follow up to the subset of this problem for <em>n</em>=2.</p>
<p>What is the solution? </p>
<p>Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does.</p>
| [
{
"answer_id": 68417,
"author": "nohat",
"author_id": 3101,
"author_profile": "https://Stackoverflow.com/users/3101",
"pm_score": 0,
"selected": false,
"text": "<p>Here is my solution:</p>\n\n<p>Construct a hash whose keys are the union of all the elements in the input lists, and the values are bit strings, where bit <em>i</em> is set if the element is present in list <em>i</em>. The bit strings are constructed using bitwise or. Then, construct the output lists by iterating over the keys of the hash, adding keys to the associated output list.</p>\n\n<pre><code>sub list_compare {\n my (@lists) = @_;\n my %compare;\n my $bit = 1;\n foreach my $list (@lists) {\n $compare{$_} |= $bit foreach @$list;\n $bit *= 2; # shift over one bit\n }\n\n\n my @output_lists;\n foreach my $item (keys %compare) {\n push @{ $output_lists[ $compare{$item} - 1 ] }, $item;\n }\n\n return \\@output_lists;\n\n}\n</code></pre>\n\n<p>Updated to include the inverted output list generation suggested by Aristotle</p>\n"
},
{
"answer_id": 70024,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 1,
"selected": false,
"text": "<p>First of all I would like to note that nohat's answer simply does not work. Try running it, and look at the output in Data::Dumper to verify that.</p>\n\n<p>That said, your question is not well-posed. It looks like you are using sets as arrays. How do you wish to handle duplicates? How do you want to handle complex data structures? What order do you want elements in? For ease I'll assume that the answers are squash duplicates, it is OK to stringify complex data structures, and order does not matter. In that case the following is a perfectly adequate answer:</p>\n\n<pre><code>sub list_compare {\n my @lists = @_;\n\n my @answers;\n for my $list (@lists) {\n my %in_list = map {$_=>1} @$list;\n # We have this list.\n my @more_answers = [keys %in_list];\n for my $answer (@answers) {\n push @more_answers, [grep $in_list{$_}, @$answer];\n }\n push @answers, @more_answers;\n }\n\n return @answers;\n}\n</code></pre>\n\n<p>If you want to adjust those assumptions, you'll need to adjust the code. For example not squashing complex data structures and not squashing duplicates can be done with:</p>\n\n<pre><code>sub list_compare {\n my @lists = @_;\n\n my @answers;\n for my $list (@lists) {\n my %in_list = map {$_=>1} @$list;\n # We have this list.\n my @more_answers = [@$list];\n for my $answer (@answers) {\n push @more_answers, [grep $in_list{$_}, @$answer];\n }\n push @answers, @more_answers;\n }\n\n return @answers;\n}\n</code></pre>\n\n<p>This is, however, using the stringification of the data structure to check whether things that exist in one exist in another. Relaxing that condition would require somewhat more work.</p>\n"
},
{
"answer_id": 70741,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "<p>Your given solution can be simplified quite a bit still.</p>\n\n<p>In the first loop, you can use plain addition since you are only ever ORing with single bits, and you can narrow the scope of <code>$bit</code> by iterating over indices. In the second loop, you can subtract 1 from the index instead of producing an unnecessary 0th output list element that needs to be <code>shift</code>ed off, and where you unnecessarily iterate m*n times (where m is the number of output lists and n is the number of unique elements), iterating over the unique elements would reduce the iterations to just n (which is a significant win in typical use cases where m is much larger than n), <em>and</em> would simplify the code.</p>\n\n<pre><code>sub list_compare {\n my ( @list ) = @_;\n my %dest;\n\n for my $i ( 0 .. $#list ) {\n my $bit = 2**$i;\n $dest{$_} += $bit for @{ $list[ $i ] };\n }\n\n my @output_list;\n\n for my $val ( keys %dest ) {\n push @{ $output_list[ $dest{ $val } - 1 ] }, $val;\n }\n\n return \\@output_list;\n}\n</code></pre>\n\n<p>Note also that once thought of in this way, the result gathering process can be written very concisely with the aid of the <a href=\"http://search.cpan.org/perldoc?List::Part\" rel=\"nofollow noreferrer\">List::Part</a> module:</p>\n\n<pre><code>use List::Part;\n\nsub list_compare {\n my ( @list ) = @_;\n my %dest;\n\n for my $i ( 0 .. $#list ) {\n my $bit = 2**$i;\n $dest{$_} += $bit for @{ $list[ $i ] };\n }\n\n return [ part { $dest{ $_ } - 1 } keys %dest ];\n}\n</code></pre>\n\n<p>But note that <code>list_compare</code> is a terrible name. Something like <code>part_elems_by_membership</code> would be much better. Also, the imprecisions in your question Ben Tilly pointed out need to be rectified.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3101/"
]
| I use this question in interviews and I wonder what the best solution is.
Write a Perl sub that takes *n* lists, and then returns 2^*n*-1 lists telling you which items are in which lists; that is, which items are only in the first list, the second, list, both the first and second list, and all other combinations of lists. Assume that *n* is reasonably small (less than 20).
For example:
```
list_compare([1, 3], [2, 3]);
=> ([1], [2], [3]);
```
Here, the first result list gives all items that are only in list 1, the second result list gives all items that are only in list 2, and the third result list gives all items that are in both lists.
```
list_compare([1, 3, 5, 7], [2, 3, 6, 7], [4, 5, 6, 7])
=> ([1], [2], [3], [4], [5], [6], [7])
```
Here, the first list gives all items that are only in list 1, the second list gives all items that are only in list 2, and the third list gives all items that are in both lists 1 and 2, as in the first example. The fourth list gives all items that are only in list 3, the fifth list gives all items that are only in lists 1 and 3, the sixth list gives all items that are only in lists 2 and 3, and the seventh list gives all items that are in all 3 lists.
I usually give this problem as a follow up to the subset of this problem for *n*=2.
What is the solution?
Follow-up: The items in the lists are strings. There might be duplicates, but since they are just strings, duplicates should be squashed in the output. Order of the items in the output lists doesn't matter, the order of the lists themselves does. | Your given solution can be simplified quite a bit still.
In the first loop, you can use plain addition since you are only ever ORing with single bits, and you can narrow the scope of `$bit` by iterating over indices. In the second loop, you can subtract 1 from the index instead of producing an unnecessary 0th output list element that needs to be `shift`ed off, and where you unnecessarily iterate m\*n times (where m is the number of output lists and n is the number of unique elements), iterating over the unique elements would reduce the iterations to just n (which is a significant win in typical use cases where m is much larger than n), *and* would simplify the code.
```
sub list_compare {
my ( @list ) = @_;
my %dest;
for my $i ( 0 .. $#list ) {
my $bit = 2**$i;
$dest{$_} += $bit for @{ $list[ $i ] };
}
my @output_list;
for my $val ( keys %dest ) {
push @{ $output_list[ $dest{ $val } - 1 ] }, $val;
}
return \@output_list;
}
```
Note also that once thought of in this way, the result gathering process can be written very concisely with the aid of the [List::Part](http://search.cpan.org/perldoc?List::Part) module:
```
use List::Part;
sub list_compare {
my ( @list ) = @_;
my %dest;
for my $i ( 0 .. $#list ) {
my $bit = 2**$i;
$dest{$_} += $bit for @{ $list[ $i ] };
}
return [ part { $dest{ $_ } - 1 } keys %dest ];
}
```
But note that `list_compare` is a terrible name. Something like `part_elems_by_membership` would be much better. Also, the imprecisions in your question Ben Tilly pointed out need to be rectified. |
68,372 | <p>We all know how to use <code><ctrl>-R</code> to reverse search through history, but did you know you can use <code><ctrl>-S</code> to forward search if you set <code>stty stop ""</code>? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default. </p>
<p>What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash?</p>
| [
{
"answer_id": 68386,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "<p>Well, this may be a bit off topic, but if you are an Emacs user, I would say \"emacs\" is the most powerful trick... before you downvote this, try out \"M-x shell\" within an emacs instance... you get a shell inside emacs, and have all the power of emacs along with the power of a shell (there are some limitations, such as opening another emacs within it, but in most cases it is a lot more powerful than a vanilla bash prompt).</p>\n"
},
{
"answer_id": 68388,
"author": "HFLW",
"author_id": 252822,
"author_profile": "https://Stackoverflow.com/users/252822",
"pm_score": 4,
"selected": false,
"text": "<p>You can use the watch command in conjunction with another command to look for changes. An example of this was when I was testing my router, and I wanted to get up-to-date numbers on stuff like signal-to-noise ratio, etc.</p>\n\n<pre><code>watch --interval=10 lynx -dump http://dslrouter/stats.html\n</code></pre>\n"
},
{
"answer_id": 68390,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 5,
"selected": false,
"text": "<p>More of a novelty, but it's clever...</p>\n\n<p>Top 10 commands used:</p>\n\n<pre><code>$ history | awk '{print $2}' | awk 'BEGIN {FS=\"|\"}{print $1}' | sort | uniq -c | sort -nr | head\n</code></pre>\n\n<p>Sample output:</p>\n\n<pre><code> 242 git\n 83 rake\n 43 cd\n 33 ss\n 24 ls\n 15 rsg\n 11 cap\n 10 dig\n 9 ping\n 3 vi\n</code></pre>\n"
},
{
"answer_id": 68397,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 7,
"selected": false,
"text": "<pre><code>cd -\n</code></pre>\n\n<p>It's the command-line equivalent of the back button (takes you to the previous directory you were in).</p>\n"
},
{
"answer_id": 68400,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 1,
"selected": false,
"text": "<p>bash can redirect to and from TCP/IP sockets.\n/dev/tcp/ and /dev/udp.</p>\n\n<p>Some people think it's a security issue,\nbut that's what OS level security like Solaris X's jail is for.</p>\n\n<p>As Will Robertson notes, change prompt to do stuff... print the command # for !nn \nSet the Xterm terminal name. If it's an old Xterm that doesn't sniff traffic to set it's title.</p>\n"
},
{
"answer_id": 68411,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 2,
"selected": false,
"text": "<p>I like a splash of colour in my prompts:</p>\n\n<pre><code>export PS1=\"\\[\\033[07;31m\\] \\h \\[\\033[47;30m\\] \\W \\[\\033[00;31m\\] \\$ \\[\\e[m\\]\"\n</code></pre>\n\n<p>I'm afraid I don't have a screenshot for what that looks like, but it's supposed to be something like (all on one line):</p>\n\n<pre><code>[RED BACK WHITE TEXT] Computer name \n[BLACK BACK WHITE TEXT] Working Directory \n[WHITE BACK RED TEXT] $\n</code></pre>\n\n<p>Customise as per what you like to see <code>:)</code></p>\n"
},
{
"answer_id": 68412,
"author": "dreamlax",
"author_id": 10320,
"author_profile": "https://Stackoverflow.com/users/10320",
"pm_score": 3,
"selected": false,
"text": "<p>When downloading a large file I quite often do:</p>\n\n<pre><code>while ls -la <filename>; do sleep 5; done\n</code></pre>\n\n<p>And then just ctrl+c when I'm done (or if <code>ls</code> returns non-zero). It's similar to the <code>watch</code> program but it uses the shell instead, so it works on platforms without <code>watch</code>.</p>\n\n<p>Another useful tool is netcat, or <code>nc</code>. If you do:</p>\n\n<pre><code>nc -l -p 9100 > printjob.prn\n</code></pre>\n\n<p>Then you can set up a printer on another computer but instead use the IP address of the computer running netcat. When the print job is sent, it is received by the computer running netcat and dumped into <code>printjob.prn</code>.</p>\n"
},
{
"answer_id": 68413,
"author": "Sergio Morales",
"author_id": 9506,
"author_profile": "https://Stackoverflow.com/users/9506",
"pm_score": 0,
"selected": false,
"text": "<p>Some useful mencoder commands I found out about when looking for some audio and video editing tools:</p>\n\n<p>from .xxx to .avi</p>\n\n<pre><code>mencoder movie.wmv -o movie.avi -ovc lavc -oac lavc \n</code></pre>\n\n<p>Dump sound from a video:</p>\n\n<pre><code>mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile fileout.mp3 filein.avi \n</code></pre>\n"
},
{
"answer_id": 68419,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 5,
"selected": false,
"text": "<p><kbd>ESC</kbd><kbd>.</kbd></p>\n\n<p>Inserts the last arguments from your last bash command. It comes in handy more than you think.</p>\n\n<pre><code>cp file /to/some/long/path\n</code></pre>\n\n<p>cd <kbd>ESC</kbd><kbd>.</kbd></p>\n"
},
{
"answer_id": 68421,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 7,
"selected": true,
"text": "<p>When running commands, sometimes I'll want to run a command with the previous ones arguments. To do that, you can use this shortcut:</p>\n\n<pre><code>$ mkdir /tmp/new\n$ cd !!:*\n</code></pre>\n\n<p>Occasionally, in lieu of using find, I'll break-out a one-line loop if I need to run a bunch of commands on a list of files. </p>\n\n<pre><code>for file in *.wav; do lame \"$file\" \"$(basename \"$file\" .wav).mp3\" ; done;\n</code></pre>\n\n<p>Configuring the command-line history options in my .bash_login (or .bashrc) is really useful. The following is a cadre of settings that I use on my Macbook Pro. </p>\n\n<p>Setting the following makes bash erase duplicate commands in your history:</p>\n\n<pre><code>export HISTCONTROL=\"erasedups:ignoreboth\"\n</code></pre>\n\n<p>I also jack my history size up pretty high too. Why not? It doesn't seem to slow anything down on today's microprocessors.</p>\n\n<pre><code>export HISTFILESIZE=500000\nexport HISTSIZE=100000\n</code></pre>\n\n<p>Another thing that I do is ignore some commands from my history. No need to remember the exit command. </p>\n\n<pre><code>export HISTIGNORE=\"&:[ ]*:exit\"\n</code></pre>\n\n<p>You definitely want to set histappend. Otherwise, bash overwrites your history when you exit.</p>\n\n<pre><code>shopt -s histappend\n</code></pre>\n\n<p>Another option that I use is cmdhist. This lets you save multi-line commands to the history as one command.</p>\n\n<pre><code>shopt -s cmdhist\n</code></pre>\n\n<p>Finally, on Mac OS X (if you're not using vi mode), you'll want to reset <CTRL>-S from being scroll stop. This prevents bash from being able to interpret it as forward search. </p>\n\n<pre><code>stty stop \"\"\n</code></pre>\n"
},
{
"answer_id": 68424,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 6,
"selected": false,
"text": "<p>rename</p>\n\n<p>Example:</p>\n\n<pre><code>$ ls\nthis_has_text_to_find_1.txt\nthis_has_text_to_find_2.txt\nthis_has_text_to_find_3.txt\nthis_has_text_to_find_4.txt\n\n$ rename 's/text_to_find/been_renamed/' *.txt\n$ ls\nthis_has_been_renamed_1.txt\nthis_has_been_renamed_2.txt\nthis_has_been_renamed_3.txt\nthis_has_been_renamed_4.txt\n\n</code></pre>\n\n<p>So useful</p>\n"
},
{
"answer_id": 68429,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 7,
"selected": false,
"text": "<p>Another favorite:</p>\n\n<pre><code>!!\n</code></pre>\n\n<p>Repeats your last command. Most useful in the form:</p>\n\n<pre><code>sudo !!\n</code></pre>\n"
},
{
"answer_id": 68441,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 4,
"selected": false,
"text": "<p>I like to construct commands with <strong>echo</strong> and pipe them to the shell:</p>\n\n<pre><code>$ find dir -name \\*~ | xargs echo rm\n...\n$ find dir -name \\*~ | xargs echo rm | ksh -s\n</code></pre>\n\n<p>Why? Because it allows me to look at what's going to be done before I do it. That way if I have a horrible error (like removing my home directory), I can catch it before it happens. Obviously, this is most important for destructive or irrevocable actions.</p>\n"
},
{
"answer_id": 68449,
"author": "porges",
"author_id": 10311,
"author_profile": "https://Stackoverflow.com/users/10311",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a couple of configuration tweaks:</p>\n\n<p><code>~/.inputrc</code>:</p>\n\n<pre><code>\"\\C-[[A\": history-search-backward\n\"\\C-[[B\": history-search-forward\n</code></pre>\n\n<p>This works the same as <code>^R</code> but using the arrow keys instead. This means I can type (e.g.) <code>cd /media/</code> then hit up-arrow to go to the last thing I <code>cd</code>'d to inside the <code>/media/</code> folder.</p>\n\n<p>(I use Gnome Terminal, you may need to change the escape codes for other terminal emulators.)</p>\n\n<p>Bash completion is also incredibly useful, but it's a far more subtle addition. In <code>~/.bashrc</code>:</p>\n\n<pre><code>if [ -f /etc/bash_completion ]; then\n . /etc/bash_completion\nfi\n</code></pre>\n\n<p>This will enable per-program tab-completion (e.g. attempting tab completion when the command line starts with <code>evince</code> will only show files that evince can open, and it will also tab-complete command line options).</p>\n\n<p>Works nicely with this also in <code>~/.inputrc</code>:</p>\n\n<pre><code>set completion-ignore-case on\nset show-all-if-ambiguous on\nset show-all-if-unmodified on\n</code></pre>\n"
},
{
"answer_id": 68489,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>As an extension to CTRL-r to search backwards, you can auto-complete your current input with your history if you bind 'history-search-backward'. I typically bind it to the same key that it is in tcsh: ESC-p. You can do this by putting the following line in your .inputrc file:</p>\n\n<p><code>\"\\M-p\": history-search-backward</code></p>\n\n<p>E.g. if you have previously executed 'make some_really_painfully_long_target' you can type:</p>\n\n<p><code>> make <ESC p></code></p>\n\n<p>and it will give you</p>\n\n<p><code>> make some_really_painfully_long_target</code></p>\n"
},
{
"answer_id": 68496,
"author": "Alex M",
"author_id": 9652,
"author_profile": "https://Stackoverflow.com/users/9652",
"pm_score": 6,
"selected": false,
"text": "<p>I'm a fan of the <code>!$</code>, <code>!^</code> and <code>!*</code> expandos, returning, from the most recent submitted command line: the last item, first non-command item, and all non-command items. To wit (Note that the shell prints out the command first):</p>\n\n<pre><code>$ echo foo bar baz\nfoo bar baz\n$ echo bang-dollar: !$ bang-hat: !^ bang-star: !*\necho bang-dollar: baz bang-hat: foo bang-star: foo bar baz\nbang-dollar: baz bang-hat: foo bang-star: foo bar baz\n</code></pre>\n\n<p>This comes in handy when you, say <code>ls filea fileb</code>, and want to edit one of them: <code>vi !$</code> or both of them: <code>vimdiff !*</code>. It can also be generalized to \"the <code>n</code>th argument\" like so:</p>\n\n<pre><code>$ echo foo bar baz\n$ echo !:2\necho bar\nbar\n</code></pre>\n\n<p>Finally, with pathnames, you can get at parts of the path by appending <code>:h</code> and <code>:t</code> to any of the above expandos:</p>\n\n<pre><code>$ ls /usr/bin/id\n/usr/bin/id\n$ echo Head: !$:h Tail: !$:t\necho Head: /usr/bin Tail: id\nHead: /usr/bin Tail: id\n</code></pre>\n"
},
{
"answer_id": 68547,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 3,
"selected": false,
"text": "<pre><code>$ touch {1,2}.txt\n$ ls [12].txt\n1.txt 2.txt\n$ rm !:1\nrm [12].txt\n$ history | tail -10\n...\n10007 touch {1,2}.txt\n...\n$ !10007\ntouch {1,2}.txt\n$ for f in *.txt; do mv $f ${f/txt/doc}; done\n</code></pre>\n"
},
{
"answer_id": 68551,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 1,
"selected": false,
"text": "<p>And this one is key for me actually:</p>\n\n<p>set -o vi</p>\n\n<p>/Allan</p>\n"
},
{
"answer_id": 68576,
"author": "user10741",
"author_id": 10741,
"author_profile": "https://Stackoverflow.com/users/10741",
"pm_score": 5,
"selected": false,
"text": "<p>^R reverse search. Hit ^R, type a fragment of a previous command you want to match, and hit ^R until you find the one you want. Then I don't have to remember recently used commands that are still in my history. Not exclusively bash, but also: ^E for end of line, ^A for beginning of line, ^U and ^K to delete before and after the cursor, respectively.</p>\n"
},
{
"answer_id": 68590,
"author": "baudtack",
"author_id": 10738,
"author_profile": "https://Stackoverflow.com/users/10738",
"pm_score": 1,
"selected": false,
"text": "<p>I've always liked this one.\nAdd this to your /etc/inputrc or ~/.inputrc</p>\n\n<p>\"\\e[A\":history-search-backward\n\"\\e[B\":history-search-forward</p>\n\n<p>When you type <code>ls <up-arrow></code> it will be replaced with the last command starting with \"ls \" or whatever else you put in.</p>\n"
},
{
"answer_id": 68600,
"author": "user10765",
"author_id": 10765,
"author_profile": "https://Stackoverflow.com/users/10765",
"pm_score": 7,
"selected": false,
"text": "<p>Renaming/moving files with suffixes quickly:<br>\n<code>cp /home/foo/realllylongname.cpp{,-old}</code></p>\n\n<p>This expands to:<br>\n<code>cp /home/foo/realllylongname.cpp /home/foo/realllylongname.cpp-old</code></p>\n"
},
{
"answer_id": 68781,
"author": "jdt141",
"author_id": 10774,
"author_profile": "https://Stackoverflow.com/users/10774",
"pm_score": 3,
"selected": false,
"text": "<p><code>pushd</code> and <code>popd</code> almost always come in handy</p>\n"
},
{
"answer_id": 69024,
"author": "Leonard",
"author_id": 10888,
"author_profile": "https://Stackoverflow.com/users/10888",
"pm_score": 3,
"selected": false,
"text": "<p>Using 'set -o vi' from the command line, or better, in .bashrc, puts you in vi editing mode on the command line. You start in 'insert' mode so you can type and backspace as normal, but if you make a 'large' mistake you can hit the esc key and then use 'b' and 'f' to move around as you do in vi. cw to change a word. Particularly useful after you've brought up a history command that you want to change.</p>\n"
},
{
"answer_id": 69031,
"author": "Leonard",
"author_id": 10888,
"author_profile": "https://Stackoverflow.com/users/10888",
"pm_score": 1,
"selected": false,
"text": "<p>This prevents <a href=\"http://en.wikipedia.org/wiki/Less_%28Unix%29\" rel=\"nofollow noreferrer\">less</a> (less is more) from clearing the screen at the end of a file:</p>\n\n<pre><code>export LESS=\"-X\"\n</code></pre>\n"
},
{
"answer_id": 69033,
"author": "Leonard",
"author_id": 10888,
"author_profile": "https://Stackoverflow.com/users/10888",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer reading man pages in vi, so I have the following in my .profile or .bashrc file</p>\n\n<pre><code>man () {\n sought=$*\n /usr/bin/man $sought | col -b | vim -R -c \"set nonumber\" -c \"set syntax=man\" -\n}\n</code></pre>\n"
},
{
"answer_id": 69039,
"author": "Leonard",
"author_id": 10888,
"author_profile": "https://Stackoverflow.com/users/10888",
"pm_score": 2,
"selected": false,
"text": "<p>I have various typographical error corrections in aliases</p>\n\n<pre><code>alias mkae=make\n\nalias mroe=less\n</code></pre>\n"
},
{
"answer_id": 69041,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": 2,
"selected": false,
"text": "<p><kbd>Ctrl</kbd> + <kbd>L</kbd> will usually clear the screen. Works from the Bash prompt (obviously) and in <a href=\"http://en.wikipedia.org/wiki/GNU_Debugger\" rel=\"nofollow noreferrer\">GDB</a>, and a lot of other prompts. </p>\n"
},
{
"answer_id": 69056,
"author": "Leonard",
"author_id": 10888,
"author_profile": "https://Stackoverflow.com/users/10888",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest keystrokes for me for \"last argument of the last command\" is !$</p>\n\n<pre><code>echo what the heck?\n\nwhat the heck?\n\necho !$\n\nheck?\n</code></pre>\n"
},
{
"answer_id": 69058,
"author": "TChen",
"author_id": 10913,
"author_profile": "https://Stackoverflow.com/users/10913",
"pm_score": 3,
"selected": false,
"text": "<p>String multiple commands together using the <strong>&&</strong> command:</p>\n\n<pre><code>./run.sh && tail -f log.txt\n</code></pre>\n\n<p>or</p>\n\n<pre><code>kill -9 1111 && ./start.sh\n</code></pre>\n"
},
{
"answer_id": 69087,
"author": "Leonard",
"author_id": 10888,
"author_profile": "https://Stackoverflow.com/users/10888",
"pm_score": 3,
"selected": false,
"text": "<p>One preferred way of navigating when I'm using multiple directories in widely separate places in a tree hierarchy is to use acf_func.sh (listed below). Once defined, you can do</p>\n\n<p>cd -- </p>\n\n<p>to see a list of recent directories, with a numerical menu</p>\n\n<p>cd -2</p>\n\n<p>to go to the second-most recent directory.</p>\n\n<p>Very easy to use, very handy.</p>\n\n<p>Here's the code:</p>\n\n<pre><code># do \". acd_func.sh\"\n# acd_func 1.0.5, 10-nov-2004\n# petar marinov, http:/geocities.com/h2428, this is public domain\n\ncd_func ()\n{\n local x2 the_new_dir adir index\n local -i cnt\n\n if [[ $1 == \"--\" ]]; then\n dirs -v\n return 0\n fi\n\n the_new_dir=$1\n [[ -z $1 ]] && the_new_dir=$HOME\n\n if [[ ${the_new_dir:0:1} == '-' ]]; then\n #\n # Extract dir N from dirs\n index=${the_new_dir:1}\n [[ -z $index ]] && index=1\n adir=$(dirs +$index)\n [[ -z $adir ]] && return 1\n the_new_dir=$adir\n fi\n\n #\n # '~' has to be substituted by ${HOME}\n [[ ${the_new_dir:0:1} == '~' ]] && the_new_dir=\"${HOME}${the_new_dir:1}\"\n\n #\n # Now change to the new dir and add to the top of the stack\n pushd \"${the_new_dir}\" > /dev/null\n [[ $? -ne 0 ]] && return 1\n the_new_dir=$(pwd)\n\n #\n # Trim down everything beyond 11th entry\n popd -n +11 2>/dev/null 1>/dev/null\n\n #\n # Remove any other occurence of this dir, skipping the top of the stack\n for ((cnt=1; cnt <= 10; cnt++)); do\n x2=$(dirs +${cnt} 2>/dev/null)\n [[ $? -ne 0 ]] && return 0\n [[ ${x2:0:1} == '~' ]] && x2=\"${HOME}${x2:1}\"\n if [[ \"${x2}\" == \"${the_new_dir}\" ]]; then\n popd -n +$cnt 2>/dev/null 1>/dev/null\n cnt=cnt-1\n fi\n done\n\n return 0\n}\n\nalias cd=cd_func\n\nif [[ $BASH_VERSION > \"2.05a\" ]]; then\n # ctrl+w shows the menu\n bind -x \"\\\"\\C-w\\\":cd_func -- ;\"\nfi\n</code></pre>\n"
},
{
"answer_id": 69118,
"author": "Leonard",
"author_id": 10888,
"author_profile": "https://Stackoverflow.com/users/10888",
"pm_score": 1,
"selected": false,
"text": "<p>When navigating between two separate directories and copying files back and forth, I do this:</p>\n\n<pre><code>cd /some/where/long\nsrc=`pwd`\ncd /other/where/long\ndest=`pwd`\n\ncp $src/foo $dest\n\ncommand completion will work by expanding the variable, so you can use tab completion to specify a file you're working with.\n</code></pre>\n"
},
{
"answer_id": 69198,
"author": "Drew Frezell",
"author_id": 10954,
"author_profile": "https://Stackoverflow.com/users/10954",
"pm_score": 3,
"selected": false,
"text": "<p>I've always been partial to:</p>\n\n<pre><code>ctrl-E # move cursor to end of line\nctrl-A # move cursor to beginning of line\n</code></pre>\n\n<p>I also use <code>shopt -s cdable_vars</code>, then you can create bash variables to common directories. So, for my company's source tree, I create a bunch of variables like:</p>\n\n<pre><code>export Dcentmain=\"/var/localdata/p4ws/centaur/main/apps/core\"\n</code></pre>\n\n<p>then I can change to that directory by <code>cd Dcentmain</code>.</p>\n"
},
{
"answer_id": 69385,
"author": "Kimbo",
"author_id": 10960,
"author_profile": "https://Stackoverflow.com/users/10960",
"pm_score": 1,
"selected": false,
"text": "<p><anything> | sort | uniq -c | sort -n</p>\n\n<p>will give you a count of all the different occurrences of <anything>.</p>\n\n<p>Often, awk, sed, or cut help with the parsing of data in <anything>.</p>\n"
},
{
"answer_id": 69396,
"author": "Kimbo",
"author_id": 10960,
"author_profile": "https://Stackoverflow.com/users/10960",
"pm_score": 1,
"selected": false,
"text": "<p>du -a | sort -n | tail -99</p>\n\n<p>to find the big files (or directories of files) to clean up to free up disk space.</p>\n"
},
{
"answer_id": 69449,
"author": "Steve Lacey",
"author_id": 11077,
"author_profile": "https://Stackoverflow.com/users/11077",
"pm_score": 4,
"selected": false,
"text": "<p>I use the following a lot:</p>\n\n<p>The <code>:p</code> modifier to print a history result. E.g.</p>\n\n<pre><code>!!:p\n</code></pre>\n\n<p>Will print the last command so you can check that it's correct before running it again. Just enter <code>!!</code> to execute it.</p>\n\n<p>In a similar vein:</p>\n\n<pre><code>!?foo?:p\n</code></pre>\n\n<p>Will search your history for the most recent command that contained the string 'foo' and print it.</p>\n\n<p>If you don't need to print,</p>\n\n<pre><code>!?foo\n</code></pre>\n\n<p>does the search and executes it straight away.</p>\n"
},
{
"answer_id": 69475,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": false,
"text": "<p><code>$_</code> (dollar underscore): the last word from the previous command. Similar to <code>!$</code> except it doesn't put its substitution in your history like <code>!$</code> does.</p>\n"
},
{
"answer_id": 69495,
"author": "user10109",
"author_id": 10109,
"author_profile": "https://Stackoverflow.com/users/10109",
"pm_score": 5,
"selected": false,
"text": "<p>My favorite command is \"ls -thor\"</p>\n\n<p>It summons the <a href=\"http://en.wikipedia.org/wiki/Thor\" rel=\"nofollow noreferrer\">power of the gods</a> to list the most recently modified files in a conveniently readable format.</p>\n"
},
{
"answer_id": 69560,
"author": "shiva",
"author_id": 11018,
"author_profile": "https://Stackoverflow.com/users/11018",
"pm_score": 2,
"selected": false,
"text": "<p>Eliminate duplicate lines from a file</p>\n\n<pre><code>#sort -u filename > filename.new\n</code></pre>\n\n<p>List all lines that do not match a condition</p>\n\n<pre><code>#grep -v ajsk filename\n</code></pre>\n\n<p>These are not necessarily Bash specific (but hey neither is <code>ls -thor</code> :) )</p>\n\n<p>Some other useful cmds:</p>\n\n<p>prtdiag, psrinfo, prtconf - more info <a href=\"http://shiv.me/2008/09/09/unix-removing-duplicates-from-a-file/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://shiv.me/2007/09/08/unix-how-to-check-system-configuration-on-solaris/\" rel=\"nofollow noreferrer\">here</a> (posts on my blog).</p>\n"
},
{
"answer_id": 69716,
"author": "dajobe",
"author_id": 11177,
"author_profile": "https://Stackoverflow.com/users/11177",
"pm_score": 4,
"selected": false,
"text": "<pre><code>type -a PROG\n</code></pre>\n\n<p>in order to find all the places where PROG is available, usually somewhere in ~/bin\nrather than the one in /usr/bin/PROG that might have been expected.</p>\n"
},
{
"answer_id": 69737,
"author": "paranoio",
"author_id": 11124,
"author_profile": "https://Stackoverflow.com/users/11124",
"pm_score": 0,
"selected": false,
"text": "<pre><code>alias mycommand = 'verylongcommand -with -a -lot -of -parameters'\nalias grep='grep --color'\n</code></pre>\n\n<p>find more than one word with grep :</p>\n\n<pre><code>netstat -c |grep 'msn\\|skype\\|icq'\n</code></pre>\n"
},
{
"answer_id": 69756,
"author": "seth",
"author_id": 8590,
"author_profile": "https://Stackoverflow.com/users/8590",
"pm_score": 6,
"selected": false,
"text": "<p>My favorite is '^string^string2' which takes the last command, replaces string with string2 and executes it</p>\n\n<pre><code>$ ehco foo bar baz\nbash: ehco: command not found\n$ ^ehco^echo\nfoo bar baz\n</code></pre>\n\n<p><a href=\"http://www.catonmat.net/blog/the-definitive-guide-to-bash-command-line-history/\" rel=\"nofollow noreferrer\">Bash command line history guide</a></p>\n"
},
{
"answer_id": 69757,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 2,
"selected": false,
"text": "<p>Not really obscure, but one of the features I absolutely <em>love</em> is tab completion.<br>\nReally useful when you are navigating trough an entire subtree structure, or when you are using some obscure, or long command!</p>\n"
},
{
"answer_id": 69848,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "<p>A few years ago, I discovered the <strong>p*</strong> commands or get information about processes: <strong>ptree</strong>, <strong>pgrep</strong>, <strong>pkill</strong>, and <strong>pfiles</strong>. Of course, the mother of them all is <strong>ps</strong>, but you need to pipe the output into <strong>less</strong>, <strong>grep</strong> and/or <strong>awk</strong> to make sense of the output under heavy load. <strong>top</strong> (and variants) help too.</p>\n"
},
{
"answer_id": 69870,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 0,
"selected": false,
"text": "<p>You changed to a new directory and want to move a file from the new directory to the old one. In one move: <code>mv file $OLDPWD</code></p>\n"
},
{
"answer_id": 69974,
"author": "user11285",
"author_id": 11285,
"author_profile": "https://Stackoverflow.com/users/11285",
"pm_score": 0,
"selected": false,
"text": "<p>If I am searching for something in a directory, but I am not sure of the file, then I just grep the files in the directory by:</p>\n\n<pre><code>find . -exec grep whatIWantToFind {} \\;\n</code></pre>\n"
},
{
"answer_id": 70190,
"author": "Weidenrinde",
"author_id": 11344,
"author_profile": "https://Stackoverflow.com/users/11344",
"pm_score": 0,
"selected": false,
"text": "<pre><code>alias -- ddt='ls -trFld'\ndt () { ddt --color \"$@\" | tail -n 30; }\n</code></pre>\n\n<p>Gives you the most recent files in the current directory. I use it all the time...</p>\n"
},
{
"answer_id": 70523,
"author": "user11535",
"author_id": 11535,
"author_profile": "https://Stackoverflow.com/users/11535",
"pm_score": 3,
"selected": false,
"text": "<p>Similar to many above, my current favorite is the keystroke [alt]. (Alt and \".\" keys together) this is the same as $! (Inserts the last argument from the previous command) except that it's immediate and for me easier to type. (Just can't be used in scripts)</p>\n\n<p>eg:</p>\n\n<pre><code>mkdir -p /tmp/test/blah/oops/something\ncd [alt].\n</code></pre>\n"
},
{
"answer_id": 70637,
"author": "nikolay",
"author_id": 11505,
"author_profile": "https://Stackoverflow.com/users/11505",
"pm_score": 2,
"selected": false,
"text": "<p>A simple thing to do when you realize you just typed the wrong line is hit Ctrl+C; if you want to keep the line, but need to execute something else first, begin a new line with a back slash - \\, then Ctrl+C. The line will remain in your history.</p>\n"
},
{
"answer_id": 71285,
"author": "Srikanth",
"author_id": 7205,
"author_profile": "https://Stackoverflow.com/users/7205",
"pm_score": 4,
"selected": false,
"text": "<p>I often have aliases for vi, ls, etc. but sometimes you want to escape the alias. Just add a back slash to the command in front:</p>\n\n<p>Eg:</p>\n\n<pre><code>$ alias vi=vim\n$ # To escape the alias for vi:\n$ \\vi # This doesn't open VIM\n</code></pre>\n\n<p>Cool, isn't it?</p>\n"
},
{
"answer_id": 71326,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to paste the following into a bash terminal window.</p>\n\n<p><strong>Display ANSI colour palette:</strong></p>\n\n<pre><code>e=\"\\033[\"\nfor f in 0 7 `seq 6`; do\n no=\"\" bo=\"\"\n for b in n 7 0 `seq 6`; do\n co=\"3$f\"; p=\" \"\n [ $b = n ] || { co=\"$co;4$b\";p=\"\"; }\n no=\"${no}${e}${co}m ${p}${co} ${e}0m\"\n bo=\"${bo}${e}1;${co}m ${p}1;${co} ${e}0m\"\n done\n echo -e \"$no\\n$bo\"\ndone\n</code></pre>\n\n<p><strong>256 colour demo:</strong></p>\n\n<pre><code>yes \"$(seq 232 255;seq 254 -1 233)\" |\nwhile read i; do printf \"\\x1b[48;5;${i}m\\n\"; sleep .01; done\n</code></pre>\n"
},
{
"answer_id": 71418,
"author": "andyuk",
"author_id": 2108,
"author_profile": "https://Stackoverflow.com/users/2108",
"pm_score": 1,
"selected": false,
"text": "<p>Want to get the last few lines of a log file?</p>\n\n<pre><code>tail /var/log/syslog\n</code></pre>\n\n<p>Want to keep an eye on a log file for when it changes?</p>\n\n<pre><code>tail -f /var/log/syslog\n</code></pre>\n\n<p>Want to quickly read over a file from the start?</p>\n\n<pre><code>more /var/log/syslog\n</code></pre>\n\n<p>Want to quickly find if a file contains some text?</p>\n\n<pre><code>grep \"find this text\" /var/log/syslog\n</code></pre>\n"
},
{
"answer_id": 71426,
"author": "Vilmantas Baranauskas",
"author_id": 11662,
"author_profile": "https://Stackoverflow.com/users/11662",
"pm_score": 2,
"selected": false,
"text": "<p><strong>CTRL+D</strong> quits the shell.</p>\n"
},
{
"answer_id": 75005,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To be able to quickly edit a shell script you know is in your $PATH (do not try with ls...):</p>\n\n<pre><code>function viscr { vi $(which $*); }\n</code></pre>\n"
},
{
"answer_id": 75152,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Apropos history -- using cryptic carets, etc. is not entirely intuitive. To print all history items containing a given string:</p>\n\n<pre><code>function histgrep { fc -l -$((HISTSIZE-1)) | egrep \"$@\" ;}\n</code></pre>\n"
},
{
"answer_id": 75765,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 1,
"selected": false,
"text": "<p>The FIGNORE environment variable is nice when you want TAB completion to ignore files or folders with certain suffixes, e.g.:</p>\n\n<pre><code>export FIGNORE=\"CVS:.svn:~\"\n</code></pre>\n\n<p>Use the IFS environment variable when you want to define an item separator other than space, e.g.:</p>\n\n<pre><code>export IFS=\"\n\"\n</code></pre>\n\n<p>This will make you able to loop through files and folders with spaces in them without performing any magic, like this:</p>\n\n<pre><code>$ touch \"with spaces\" withoutspaces\n$ for i in `ls *`; do echo $i; done\nwith\nspaces\nwithoutspaces\n$ IFS=\"\n\"\n$ for i in `ls *`; do echo $i; done\nwith spaces\nwithoutspaces\n</code></pre>\n"
},
{
"answer_id": 76086,
"author": "Mostlyharmless",
"author_id": 12881,
"author_profile": "https://Stackoverflow.com/users/12881",
"pm_score": 3,
"selected": false,
"text": "<p><code>!</code><first few characters of the command> will execute the last command which matches.</p>\n\n<p>Example:</p>\n\n<p><code>!b</code> will run \"build whatever -O -p -t -i -on\"\n<code>!.</code> will run <code>./a.out</code></p>\n\n<p>It works best with long and repetitive commands, like compile, build, execute, etc. It saved me sooo much time when coding and testing.</p>\n"
},
{
"answer_id": 88815,
"author": "Robert Swisher",
"author_id": 1852,
"author_profile": "https://Stackoverflow.com/users/1852",
"pm_score": 1,
"selected": false,
"text": "<p>Good for making an exact recursive copy/backup of a directory including symlinks (rather than following them or ignoring them like cp):</p>\n\n<pre><code>$ mkdir new_dir\n$ cd old_dir\n$ tar cf - . | ( cd ../old_dir; tar xf - )\n</code></pre>\n"
},
{
"answer_id": 93587,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Custom Tab Completion (compgen and complete bash builtins)</p>\n\n<p>Tab Completion is nice, but being able to apply it to more than just filenames is great. I have used it to create custom functions to expand arguments to commands I use all the time. For example, lets say you often need to add the FQDN as an argument to a command (e.g. <code>ping blah.really.long.domain.name.foo.com</code>). You can use compgen and complete to create a bash function that reads your /etc/hosts file for results so all you have to type then is:</p>\n\n<pre><code>ping blah.<tab>\n</code></pre>\n\n<p>and it will display all your current match options.</p>\n\n<p>So basically anything that can return a word list can be used as a function.</p>\n"
},
{
"answer_id": 94335,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>When running a command with lots of output (like a big \"make\") I want to not only save the output, but also see it:</p>\n\n<p>make install 2>&1 | tee E.make</p>\n"
},
{
"answer_id": 94725,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>As a quick calculator, say to compute a percentage:</p>\n\n<pre><code>$ date\nThu Sep 18 12:55:33 EDT 2008\n$ answers=60\n$ curl \"http://stackoverflow.com/questions/68372/what-are-some-of-your-favorite-command-line-tricks-using-bash\" > tmp.html\n$ words=`awk '/class=\"post-text\"/ {s = s $0} \\\n> /<\\/div>/ { gsub(\"<[^>]*>\", \"\", s); print s; s = \"\"} \\\n> length(s) > 0 {s = s $0}' tmp.html \\\n> | awk '{n = n + NF} END {print n}'`\n$ answers=`awk '/([0-9]+) Answers/ {sub(\"<h2>\", \"\", $1); print $1}' tmp.html`\n</code></pre>\n\n<p>and finally:</p>\n\n<pre><code>$ echo $words words, $answers answers, $((words / $answers)) words per answer\n4126 words, 60 answers, 68 words per answer\n$\n</code></pre>\n\n<p>Not that division is truncated, not rounded. But often that's good enough for a quick calculation.</p>\n"
},
{
"answer_id": 95627,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 1,
"selected": false,
"text": "<p>Top 10 commands again (like <a href=\"https://stackoverflow.com/questions/68372/what-are-some-of-your-favorite-command-line-tricks-using-bash#68390\">ctcherry</a>'s post, only shorter):</p>\n\n<pre><code>history | awk '{ print $2 }' | sort | uniq -c |sort -rn | head\n</code></pre>\n"
},
{
"answer_id": 103337,
"author": "rgcb",
"author_id": 8178,
"author_profile": "https://Stackoverflow.com/users/8178",
"pm_score": 1,
"selected": false,
"text": "<p>I'm new to programming on a mac, and I miss being able to launch gui programs from bash...so I have to create functions like this:</p>\n\n<pre><code>function macvim\n{\n/Applications/MacVim.app/Contents/MacOS/Vim \"$@\" -gp &\n}\n</code></pre>\n"
},
{
"answer_id": 104649,
"author": "dr-jan",
"author_id": 2599,
"author_profile": "https://Stackoverflow.com/users/2599",
"pm_score": 0,
"selected": false,
"text": "<p>I always set my default prompt to \"username@hostname:/current/path/name/in/full> \"</p>\n\n<pre><code>PS1='\\u@\\h:\\w> '\nexport PS1\n</code></pre>\n\n<p>Saves lots of confusion when you're dealing with lots of different machines.</p>\n"
},
{
"answer_id": 109998,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<pre><code>while IFS= read -r line; do\necho \"$line\"\ndone < somefile.txt\n</code></pre>\n\n<p>This is a good way to process a file line by line. Clearing IFS is needed to get whitespace characters at the front or end of the line. The \"-r\" is needed to get all raw characters, including backslashes.</p>\n"
},
{
"answer_id": 111118,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 4,
"selected": false,
"text": "<p>I have got a secret weapon : <a href=\"http://www.shell-fu.org/\" rel=\"nofollow noreferrer\">shell-fu.</a></p>\n\n<p>There are thousand of smart tips, cool tricks and efficient recipes that most of the time fit on a single line. </p>\n\n<p>One that I love (but I cheat a bit since I use the fact that Python is installed on most Unix system now) :</p>\n\n<pre><code>alias webshare='python -m SimpleHTTPServer'\n</code></pre>\n\n<p>Now everytime you type \"webshare\", the current directory will be available through the port 8000. Really nice when you want to share files with friends on a local network without usb key or remote dir. Streaming video and music will work too.</p>\n\n<p>And of course the classic fork bomb that is completely useless but still a lot of fun :</p>\n\n<pre><code>$ :(){ :|:& };:\n</code></pre>\n\n<p>Don't try that in a production server...</p>\n"
},
{
"answer_id": 127705,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Some Bash nuggets also here:</p>\n\n<p><a href=\"http://codesnippets.joyent.com/tag/bash\" rel=\"nofollow noreferrer\">http://codesnippets.joyent.com/tag/bash</a></p>\n"
},
{
"answer_id": 139674,
"author": "edomaur",
"author_id": 14262,
"author_profile": "https://Stackoverflow.com/users/14262",
"pm_score": 1,
"selected": false,
"text": "<p>One of my favorites tricks with bash is the \"tar pipe\". When you have a monstrous quantity of files to copy from one directory to another, doing \"cp * /an/other/dir\" doesn't work if the number of files is too high and explode the bash globber, so, the tar pipe :</p>\n\n<p><code>(cd /path/to/source/dir/ ; tar cf - * ) | (cd /path/to/destination/ ; tar xf - )</code></p>\n\n<p>...and if you have netcat, you can even <a href=\"http://compsoc.dur.ac.uk/~djw/tarpipe.html\" rel=\"nofollow noreferrer\">do the \"netcat tar pipe\" through the network !!</a></p>\n"
},
{
"answer_id": 139785,
"author": "jk.",
"author_id": 21284,
"author_profile": "https://Stackoverflow.com/users/21284",
"pm_score": 2,
"selected": false,
"text": "<p>Delete everything <strong>except</strong> <em>important-file</em>:</p>\n\n<pre><code># shopt -s extglob\n# rm -rf !(important-file)\n</code></pre>\n\n<p>The same in <a href=\"http://www.zsh.org/\" rel=\"nofollow noreferrer\">zsh</a>:</p>\n\n<pre><code># rm -rf *~important-file\n</code></pre>\n\n<p>Bevore I knew that I had to move the important fiels to an other dictionary, delete everything and move the important back again.</p>\n"
},
{
"answer_id": 152576,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 1,
"selected": false,
"text": "<p>I have a really stupid, but extremely helpful one when navigating deep tree structures. Put this in .bashrc (or similar):</p>\n\n<pre><code>alias cd6=\"cd ../../../../../..\"\nalias cd5=\"cd ../../../../..\"\nalias cd4=\"cd ../../../..\"\nalias cd3=\"cd ../../..\"\nalias cd2=\"cd ../..\"\n</code></pre>\n"
},
{
"answer_id": 153700,
"author": "Florian Jenn",
"author_id": 23813,
"author_profile": "https://Stackoverflow.com/users/23813",
"pm_score": 2,
"selected": false,
"text": "<p>Using history substiution characters <code>!#</code> to access the current command line, in combination with <code>^</code>, <code>$</code>, etc.</p>\n\n<p>E.g. move a file out of the way with an \"old-\" prefix:</p>\n\n<p><code>mv file-with-long-name-typed-with-tab-completion.txt old-!#^</code></p>\n"
},
{
"answer_id": 164795,
"author": "Philip Durbin",
"author_id": 19464,
"author_profile": "https://Stackoverflow.com/users/19464",
"pm_score": 5,
"selected": false,
"text": "<p>Sure, you can \"<code>diff file1.txt file2.txt</code>\", but Bash supports <a href=\"http://www.gnu.org/software/bash/manual/html_node/Process-Substitution.html\" rel=\"nofollow noreferrer\">process substitution</a>, which allows you to <code>diff</code> the output of commands.</p>\n\n<p>For example, let's say I want to make sure my script gives me the output I expect. I can just wrap my script in <( ) and feed it to <code>diff</code> to get a quick and dirty unit test:</p>\n\n<pre><code>$ cat myscript.sh\n#!/bin/sh\necho -e \"one\\nthree\"\n$\n$ ./myscript.sh \none\nthree\n$\n$ cat expected_output.txt\none\ntwo\nthree\n$\n$ diff <(./myscript.sh) expected_output.txt\n1a2\n> two\n$\n</code></pre>\n\n<p>As another example, let's say I want to check if two servers have the same list of RPMs installed. Rather than sshing to each server, writing each list of RPMs to separate files, and doing a <code>diff</code> on those files, I can just do the <code>diff</code> from my workstation:</p>\n\n<pre><code>$ diff <(ssh server1 'rpm -qa | sort') <(ssh server2 'rpm -qa | sort')\n241c240\n< kernel-2.6.18-92.1.6.el5\n---\n> kernel-2.6.18-92.el5\n317d315\n< libsmi-0.4.5-2.el5\n727,728d724\n< wireshark-0.99.7-1.el5\n< wireshark-gnome-0.99.7-1.el5\n$\n</code></pre>\n\n<p>There are more examples in the \nAdvanced Bash-Scripting Guide at <a href=\"http://tldp.org/LDP/abs/html/process-sub.html\" rel=\"nofollow noreferrer\">http://tldp.org/LDP/abs/html/process-sub.html</a>.</p>\n"
},
{
"answer_id": 164842,
"author": "Trenton",
"author_id": 2601671,
"author_profile": "https://Stackoverflow.com/users/2601671",
"pm_score": 1,
"selected": false,
"text": "<p>On Mac OS X,</p>\n\n<pre><code>ESC .\n</code></pre>\n\n<p>will cycle through recent arguments in place. That's: press and release <code>ESC</code>, then press and release <code>.</code> (period key). On Ubuntu, I think it's <code>ALT+.</code>.</p>\n\n<p>You can do that more than once, to go back through all your recent arguments. It's kind of like <kbd>CTRL</kbd> + <kbd>R</kbd>, but for arguments only. It's also much safer than <code>!!</code> or <code>$!</code>, since you <strong>see</strong> what you're going to get before you actually run the command.</p>\n"
},
{
"answer_id": 171938,
"author": "edomaur",
"author_id": 14262,
"author_profile": "https://Stackoverflow.com/users/14262",
"pm_score": 5,
"selected": false,
"text": "<p>How to list <em>only</em> subdirectories in the current one ?</p>\n\n<pre><code>ls -d */\n</code></pre>\n\n<p>It's a simple trick, but you wouldn't know how much time I needed to find that one !</p>\n"
},
{
"answer_id": 171943,
"author": "Richard Walton",
"author_id": 15075,
"author_profile": "https://Stackoverflow.com/users/15075",
"pm_score": 1,
"selected": false,
"text": "<pre><code>sudo !!\n</code></pre>\n\n<p>Runs the last command with administrator privileges. </p>\n"
},
{
"answer_id": 173682,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 0,
"selected": false,
"text": "<pre><code>find -iregex '.*\\.py$\\|.*\\.xml$' | xargs egrep -niH 'a.search.pattern' | vi -R -\n</code></pre>\n\n<p>Searches a pattern in all Python files and all XML files and pipes the result in a readonly <a href=\"http://en.wikipedia.org/wiki/Vim_%28text_editor%29\" rel=\"nofollow noreferrer\">Vim</a> session.</p>\n"
},
{
"answer_id": 328497,
"author": "kchoose2",
"author_id": 39870,
"author_profile": "https://Stackoverflow.com/users/39870",
"pm_score": 0,
"selected": false,
"text": "<p>Two of my favorites are:</p>\n\n<p>1) Make tab-completion case insensitive (e.g. \"cd /home/User \" converts your command line to: \"cd /home/user\" if the latter exists and the former doesn't. You can turn it on with \"set completion-ignore-case on\" at the prompt, or add it permanently by adding \"set completion-ignore-case on\" to your .inputrc file.</p>\n\n<p>2) The built-in 'type' command is like \"which\" but aware of aliases also. For example</p>\n\n<pre><code>$ type cdhome\ncdhome is aliased to 'cd ~'\n$ type bash\nbash is /bin/bash\n</code></pre>\n"
},
{
"answer_id": 347005,
"author": "Adrian Pronk",
"author_id": 41861,
"author_profile": "https://Stackoverflow.com/users/41861",
"pm_score": 0,
"selected": false,
"text": "<p>I like to set a prompt which shows the current directory in the window title of an xterm. It also shows the time and current directory. In addition, if bash wants to report that a background job has finished, it is reported in a different colour using ANSI escape sequences. I use a black-on-light console so my colours may not be right for you if you favour light-on-black.</p>\n\n<pre><code>PROMPT_COMMAND='echo -e \"\\033]0;${USER}@${HOSTNAME%%.*}:${PWD/#$HOME/~}\\007\\033[1;31m${PWD/#$HOME/~}\\033[1;34m\"'\nPS1='\\[\\e[1;31m\\]\\t \\$ \\[\\e[0m\\]'\n</code></pre>\n\n<p>Make sure you understand how to use <code>\\[</code> and <code>\\]</code> correctly in your PS1 string so that bash knows how long your prompt-string actually renders on screen. This is so it can redraw your command-line correctly when you move beyond a single line command.</p>\n"
},
{
"answer_id": 385293,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I want to mention how we can redirect top command output to file using its batch mode (-b)</p>\n\n<p>$ top -b -n 1 > top.out.$(date +%s)</p>\n\n<p>By default, top is invoked using interactive mode in which top runs indefinitely and accepts keypress to redefine how top works.</p>\n\n<p>A post I wrote can be found <a href=\"http://unstableme.blogspot.com/2008/12/redirect-top-command-output-to-file.html\" rel=\"nofollow noreferrer\">here</a> </p>\n"
},
{
"answer_id": 417987,
"author": "Epitaph",
"author_id": 48725,
"author_profile": "https://Stackoverflow.com/users/48725",
"pm_score": 2,
"selected": false,
"text": "<p>Using <strong>alias</strong> can be time-saving</p>\n\n<pre><code>alias myDir = \"cd /this/is/a/long/directory; pwd\"\n</code></pre>\n"
},
{
"answer_id": 752619,
"author": "Jean-Marc Liotier",
"author_id": 91034,
"author_profile": "https://Stackoverflow.com/users/91034",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.shell-fu.org/\" rel=\"nofollow noreferrer\">Shell-fu</a> is a place for storing, moderating and propagating command line tips and tricks. A bit like StackOverflow, but solely for shell. You'll find plenty of answers to this question there.</p>\n"
},
{
"answer_id": 752702,
"author": "Rob Hruska",
"author_id": 29995,
"author_profile": "https://Stackoverflow.com/users/29995",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a big fan of Bash <a href=\"http://web.mit.edu/gnu/doc/html/features_5.html\" rel=\"nofollow noreferrer\">job control</a>, mainly the use of <code>Control-Z</code> and <code>fg</code>, especially if I'm doing development in a terminal. If I've got emacs open and need to compile, deploy, etc. I just <code>Control-Z</code> to suspend emacs, do what I need, and <code>fg</code> to bring it back. This keeps all of the emacs buffers intact and makes things much easier than re-launching whatever I'm doing.</p>\n"
},
{
"answer_id": 1138910,
"author": "cb0",
"author_id": 85737,
"author_profile": "https://Stackoverflow.com/users/85737",
"pm_score": 1,
"selected": false,
"text": "<p>Since I always need the <code>for i in $(ls)</code> statement I made a shortcut:</p>\n\n<pre><code>fea(){\n if test -z ${2:0:1}; then action=echo; else action=$2; fi\n for i in $(ls $1);\n do $action $i ;\n done;\n}\n</code></pre>\n\n<p>Another one is:</p>\n\n<pre><code>echo ${!B*}\n</code></pre>\n\n<p>It will print a list of all defined variables that start with 'B'.</p>\n"
},
{
"answer_id": 1250809,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.commandlinefu.com\" rel=\"nofollow noreferrer\">http://www.commandlinefu.com</a> is also a great site.</p>\n\n<p>I learned quite useful things there like:</p>\n\n<pre><code>sudo !!\n</code></pre>\n\n<p>or</p>\n\n<pre><code>mount | column -t\n</code></pre>\n"
},
{
"answer_id": 1453399,
"author": "chillitom",
"author_id": 56679,
"author_profile": "https://Stackoverflow.com/users/56679",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Insert preceding lines final parameter</strong></p>\n\n<p><kbd>ALT</kbd>-<kbd>.</kbd> the most useful key combination ever, try it and see, for some reason no one knows about this one.</p>\n\n<p>Press it again and again to select older last parameters. </p>\n\n<p>Great when you want to do something else to something you used just a moment ago.</p>\n"
},
{
"answer_id": 1520801,
"author": "Max Masnick",
"author_id": 173351,
"author_profile": "https://Stackoverflow.com/users/173351",
"pm_score": 3,
"selected": false,
"text": "<p><code>pbcopy</code></p>\n\n<p>This copies to the Mac system clipboard. You can pipe commands to it...try:</p>\n\n<p><code>pwd | pbcopy</code></p>\n"
},
{
"answer_id": 1581540,
"author": "Fergal",
"author_id": 102641,
"author_profile": "https://Stackoverflow.com/users/102641",
"pm_score": 2,
"selected": false,
"text": "<p><code>alias ..='cd ..'</code></p>\n\n<p>So when navigating back up a directory just use <code>..<Enter></code></p>\n"
},
{
"answer_id": 1833646,
"author": "theschmitzer",
"author_id": 2167252,
"author_profile": "https://Stackoverflow.com/users/2167252",
"pm_score": 0,
"selected": false,
"text": "<p>How to find which files match text, using find | grep -H\nIn this example, which ruby file contains the jump string -</p>\n\n<p>find . -name '*.rb' -exec grep -H jump {} \\;</p>\n"
},
{
"answer_id": 2469330,
"author": "kubi",
"author_id": 28422,
"author_profile": "https://Stackoverflow.com/users/28422",
"pm_score": 0,
"selected": false,
"text": "<p>Mac only. This is simple, but MAN do I wish I had known about this years ago.</p>\n\n<pre><code>open ./\n</code></pre>\n\n<p>Opens the current directory in Finder. You can also use it to open any file with it's default application. Can also be used for URLs, but only if you prefix the URL with <code>http://</code>, which limits it's utility for opening the occasional random site.</p>\n"
},
{
"answer_id": 2890180,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em>Curly-Brace Expansion:</em></strong></p>\n\n<p>Really comes in handy when running a <code>./configure</code> with a lot of options:</p>\n\n<pre><code>./configure --{prefix=/usr,mandir=/usr/man,{,sh}libdir=/usr/lib64,\\\nenable-{gpl,pthreads,bzlib,lib{faad{,bin},mp3lame,schroedinger,speex,theora,vorbis,xvid,x264},\\\npic,shared,postproc,avfilter{-lavf,}},disable-static}\n</code></pre>\n\n<p>This is quite literally my configure settings for ffmpeg. Without the braces it's 409 characters.</p>\n\n<p>Or, even better:</p>\n\n<pre><code>echo \"I can count to a thousand!\" ...{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}{0,1,2,3,4,5,6,7,8,9}...\n</code></pre>\n"
},
{
"answer_id": 2894785,
"author": "Thomas ",
"author_id": 348643,
"author_profile": "https://Stackoverflow.com/users/348643",
"pm_score": 1,
"selected": false,
"text": "<p>ctrl-u delete all written stuff</p>\n"
},
{
"answer_id": 2922141,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 1,
"selected": false,
"text": "<p><strong><em>Quick Text</em></strong></p>\n\n<p>I use these sequences of text all too often, so I put shortcuts to them in by <code>.inputrc</code>:</p>\n\n<pre><code># redirection short cuts\n\"\\ew\": \"2>&1\"\n\"\\eq\": \"&>/dev/null &\"\n\"\\e\\C-q\": \"2>/dev/null\"\n\"\\eg\": \"&>~/.garbage.out &\"\n\"\\e\\C-g\": \"2>~/.garbage.out\"\n\n$if term=xterm\n\"\\M-w\": \"2>&1\"\n\"\\M-q\": \"&>/dev/null &\"\n\"\\M-\\C-q\": \"2>/dev/null\"\n\"\\M-g\": \"&>~/.garbage.out &\"\n\"\\M-\\C-g\": \"2>~/.garbage.out\"\n$endif\n</code></pre>\n"
},
{
"answer_id": 2922147,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 1,
"selected": false,
"text": "<p><strong><em>Programmable Completion:</em></strong></p>\n\n<p>Nothing fancy. I always disable it when I'm using Knoppix because it gets in the way too often. Just some basic ones:</p>\n\n<pre><code>shopt -s progcomp\n\ncomplete -A stopped -P '%' bg\ncomplete -A job -P '%' fg jobs disown wait\ncomplete -A variable readonly export\ncomplete -A variable -A function unset\ncomplete -A setopt set\ncomplete -A shopt shopt\ncomplete -A helptopic help\ncomplete -A alias alias unalias\ncomplete -A binding bind\ncomplete -A command type which \\\n killall pidof\ncomplete -A builtin builtin\ncomplete -A disabled enable\n</code></pre>\n"
},
{
"answer_id": 2922191,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 1,
"selected": false,
"text": "<p>Not really interactive shell tricks, but valid nonetheless as tricks for writing good scripts.</p>\n\n<p><strong><em>getopts, shift, $OPTIND, $OPTARG:</em></strong></p>\n\n<p>I love making customizable scripts:</p>\n\n<pre><code>while getopts 'vo:' flag; do\n case \"$flag\" in\n 'v')\n VERBOSE=1\n ;;\n 'o')\n OUT=\"$OPTARG\"\n ;;\n esac\ndone\nshift \"$((OPTIND-1))\"\n</code></pre>\n\n<hr>\n\n<p><strong><em>xargs(1):</em></strong></p>\n\n<p>I have a triple-core processor and like to run scripts that perform compression, or some other CPU-intensive serial operation on a set of files. I like to speed it up using <code>xargs</code> as a job queue.</p>\n\n<pre><code>if [ \"$#\" -gt 1 ]; then\n # schedule using xargs\n (for file; do\n echo -n \"$file\"\n echo -ne '\\0'\n done) |xargs -0 -n 1 -P \"$NUM_JOBS\" -- \"$0\"\nelse\n # do the actual processing\nfi\n</code></pre>\n\n<p>This acts a lot like <code>make -j [NUM_JOBS]</code>.</p>\n"
},
{
"answer_id": 2922237,
"author": "fmsf",
"author_id": 26004,
"author_profile": "https://Stackoverflow.com/users/26004",
"pm_score": 0,
"selected": false,
"text": "<p>./mylittlealgorithm < input.txt > output.txt</p>\n"
},
{
"answer_id": 2922244,
"author": "amphetamachine",
"author_id": 237955,
"author_profile": "https://Stackoverflow.com/users/237955",
"pm_score": 1,
"selected": false,
"text": "<p><strong><em>Signal trapping:</em></strong></p>\n\n<p>You can trap signals sent to the shell process and have them silently run commands in their respective environment as if typed on the command line:</p>\n\n<pre><code># TERM or QUIT probably means the system is shutting down; make sure history is\n# saved to $HISTFILE (does not do this by default)\ntrap 'logout' TERM QUIT\n\n# save history when signalled by cron(1) script with USR1\ntrap 'history -a && history -n' USR1\n</code></pre>\n"
},
{
"answer_id": 3436445,
"author": "jlucktay",
"author_id": 380599,
"author_profile": "https://Stackoverflow.com/users/380599",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Duplicate file finder</strong></p>\n\n<p>This will run checksums recursively from the current directory, and give back the filenames of all identical checksum results:</p>\n\n<pre><code>find ./ -type f -print0 | xargs -0 -n1 md5sum | sort -k 1,32 | uniq -w 32 -d --all-repeated=separate | sed -e 's/^[0-9a-f]*\\ *//;'\n</code></pre>\n\n<p>You can, of course, change the path around.<br>\nMaybe put it into a function or alias, and pass in the target path as a parameter.</p>\n"
},
{
"answer_id": 3539492,
"author": "Omar Ali",
"author_id": 383819,
"author_profile": "https://Stackoverflow.com/users/383819",
"pm_score": 2,
"selected": false,
"text": "<p>SSH tunnel:</p>\n\n<pre><code>ssh -fNR 1234:localhost:22 [email protected]\n</code></pre>\n"
},
{
"answer_id": 3549013,
"author": "Ken Chen",
"author_id": 312123,
"author_profile": "https://Stackoverflow.com/users/312123",
"pm_score": 1,
"selected": false,
"text": "<p>For the sheer humor factor, create an empty file \"myself\" and then: <code>$ touch myself</code></p>\n"
},
{
"answer_id": 3724298,
"author": "Gadolin",
"author_id": 410737,
"author_profile": "https://Stackoverflow.com/users/410737",
"pm_score": 3,
"selected": false,
"text": "<p>I have plenty of directories which I want to access quickly, <code>CDPATH</code> variable is solution \nthat speed up my work-flow enormously: </p>\n\n<pre><code>export CDPATH=.:/home/gadolin/sth:/home/gadolin/dir1/importantDir\n</code></pre>\n\n<p>now with <code>cd</code> I can jump to any of sub directories of <code>/home/gadolin/sth</code> or <code>/home/gadolin/dir1/importantDir</code> without providing the full path. And also <code><tab></code> works here just like I would be there!\nSo if there are directories <code>/home/gadolin/sth/1</code> <code>/home/gadolin/sth/2</code>, I type <code>cd 1</code> wherever, and I am there.</p>\n"
},
{
"answer_id": 4199377,
"author": "Wesley Rice",
"author_id": 534235,
"author_profile": "https://Stackoverflow.com/users/534235",
"pm_score": 0,
"selected": false,
"text": "<pre><code># Batch extension renamer (usage: renamer txt mkd)\nrenamer() {\n local fn\n for fn in *.\"$1\"; do\n mv \"$fn\" \"${fn%.*}\".\"$2\"\n done\n}\n</code></pre>\n"
},
{
"answer_id": 4199491,
"author": "chris",
"author_id": 469276,
"author_profile": "https://Stackoverflow.com/users/469276",
"pm_score": 1,
"selected": false,
"text": "<p>extended globbing:</p>\n\n<pre><code>rm !(foo|bar)\n</code></pre>\n\n<p>expands like <code>*</code> without <code>foo</code> or <code>bar</code>:</p>\n\n<pre><code>$ ls\nfoo\nbar\nfoobar\nFOO\n$ echo !(foo|bar)\nfoobar FOO\n</code></pre>\n"
},
{
"answer_id": 4201124,
"author": "Bauna",
"author_id": 450778,
"author_profile": "https://Stackoverflow.com/users/450778",
"pm_score": 1,
"selected": false,
"text": "<p>pbcopy and pbpaste aliases for GNU/Linux</p>\n\n<pre><code>alias pbcopy='xclip -selection clipboard'\nalias pbpaste='xclip -selection clipboard -o'\n</code></pre>\n"
},
{
"answer_id": 4256192,
"author": "hibbelig",
"author_id": 318457,
"author_profile": "https://Stackoverflow.com/users/318457",
"pm_score": 1,
"selected": false,
"text": "<p>Someone else recommended \"M-x shell RET\" in Emacs. I think \"M-x eshell RET\" is even better.</p>\n"
},
{
"answer_id": 4615572,
"author": "bobbogo",
"author_id": 470195,
"author_profile": "https://Stackoverflow.com/users/470195",
"pm_score": 3,
"selected": false,
"text": "<h3>Expand complicated lines before hitting the dreaded enter</h3>\n\n<ul>\n<li><kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>e</kbd> — <em>shell-expand-line</em> (may need to use <kbd>Esc</kbd>, <kbd>Ctrl</kbd>+<kbd>e</kbd> on your keyboard)</li>\n<li><kbd>Ctrl</kbd>+<kbd>_</kbd> — <em>undo</em></li>\n<li><kbd>Ctrl</kbd>+<kbd>x</kbd>, <kbd>*</kbd> — <em>glob-expand-word</em></li>\n</ul>\n\n<p>$ <code>echo !$ !-2^ *</code> <kbd>Alt</kbd>+<kbd>Ctrl</kbd>+<kbd>e</kbd><br/>\n$ <code>echo aword someotherword *</code> <kbd>Ctrl</kbd>+<kbd>_</kbd><br/>\n$ <code>echo !$ !-2^ *</code> <kbd>Ctrl</kbd>+<kbd>x</kbd>, <kbd>*</kbd><br/>\n$ <code>echo !$ !-2^ LOG Makefile bar.c foo.h</code><br/></p>\n\n<p>&c.</p>\n"
},
{
"answer_id": 5163728,
"author": "Mikel",
"author_id": 102182,
"author_profile": "https://Stackoverflow.com/users/102182",
"pm_score": 2,
"selected": false,
"text": "<p>Not my favorite, by very helpful if you're trying any of the other answers using copy and paste:</p>\n\n<pre><code>function $\n{\n \"$@\"\n}\n</code></pre>\n\n<p>Now you can paste examples that include a <code>$</code> prompt at the start of each line.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3499/"
]
| We all know how to use `<ctrl>-R` to reverse search through history, but did you know you can use `<ctrl>-S` to forward search if you set `stty stop ""`? Also, have you ever tried running bind -p to see all of your keyboard shortcuts listed? There are over 455 on Mac OS X by default.
What is your single most favorite obscure trick, keyboard shortcut or shopt configuration using bash? | When running commands, sometimes I'll want to run a command with the previous ones arguments. To do that, you can use this shortcut:
```
$ mkdir /tmp/new
$ cd !!:*
```
Occasionally, in lieu of using find, I'll break-out a one-line loop if I need to run a bunch of commands on a list of files.
```
for file in *.wav; do lame "$file" "$(basename "$file" .wav).mp3" ; done;
```
Configuring the command-line history options in my .bash\_login (or .bashrc) is really useful. The following is a cadre of settings that I use on my Macbook Pro.
Setting the following makes bash erase duplicate commands in your history:
```
export HISTCONTROL="erasedups:ignoreboth"
```
I also jack my history size up pretty high too. Why not? It doesn't seem to slow anything down on today's microprocessors.
```
export HISTFILESIZE=500000
export HISTSIZE=100000
```
Another thing that I do is ignore some commands from my history. No need to remember the exit command.
```
export HISTIGNORE="&:[ ]*:exit"
```
You definitely want to set histappend. Otherwise, bash overwrites your history when you exit.
```
shopt -s histappend
```
Another option that I use is cmdhist. This lets you save multi-line commands to the history as one command.
```
shopt -s cmdhist
```
Finally, on Mac OS X (if you're not using vi mode), you'll want to reset <CTRL>-S from being scroll stop. This prevents bash from being able to interpret it as forward search.
```
stty stop ""
``` |
68,391 | <p>In an effort to reduce code duplication in my little Rails app, I've been working on getting common code between my models into it's own separate module, so far so good.</p>
<p>The model stuff is fairly easy, I just have to include the module at the beginning, e.g.:</p>
<pre><code>class Iso < Sale
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
def after_initialize
end
order_lines :despatched
# tracks_serial_numbers :items
sendable :customer
def created_at=( date )
write_attribute( :created_at, Chronic.parse( date ) )
end
end
</code></pre>
<p>This is working fine, now however, I'm going to have some controller and view code that's going to be common between these models as well, so far I have this for my sendable stuff:</p>
<pre><code># This is a module that is used for pages/forms that are can be "sent"
# either via fax, email, or printed.
module Sendable
module Model
def self.included( klass )
klass.extend ClassMethods
end
module ClassMethods
def sendable( class_to_send_to )
attr_accessor :fax_number,
:email_address,
:to_be_faxed,
:to_be_emailed,
:to_be_printed
@_class_sending_to ||= class_to_send_to
include InstanceMethods
end
def class_sending_to
@_class_sending_to
end
end # ClassMethods
module InstanceMethods
def after_initialize( )
super
self.to_be_faxed = false
self.to_be_emailed = false
self.to_be_printed = false
target_class = self.send( self.class.class_sending_to )
if !target_class.nil?
self.fax_number = target_class.send( :fax_number )
self.email_address = target_class.send( :email_address )
end
end
end
end # Module Model
end # Module Sendable
</code></pre>
<p>Basically I'm planning on just doing an include Sendable::Controller, and Sendable::View (or the equivalent) for the controller and the view, but, is there a cleaner way to do this? I 'm after a neat way to have a bunch of common code between my model, controller, and view.</p>
<p>Edit: Just to clarify, this just has to be shared across 2 or 3 models.</p>
| [
{
"answer_id": 68934,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 3,
"selected": false,
"text": "<p>If that code needs to get added to all models and all controllers, you could always do the following:</p>\n\n<pre><code># maybe put this in environment.rb or in your module declaration\nclass ActiveRecord::Base\n include Iso\nend\n\n# application.rb\nclass ApplicationController\n include Iso\nend\n</code></pre>\n\n<p>If you needed functions from this module available to the views, you could expose them individually with <code>helper_method</code> declarations in application.rb.</p>\n"
},
{
"answer_id": 69190,
"author": "nikz",
"author_id": 3977,
"author_profile": "https://Stackoverflow.com/users/3977",
"pm_score": 4,
"selected": true,
"text": "<p>You could pluginize it (use script/generate plugin).</p>\n\n<p>Then in your init.rb just do something like:</p>\n\n<pre><code>ActiveRecord::Base.send(:include, PluginName::Sendable)\nActionController::Base.send(:include, PluginName::SendableController)\n</code></pre>\n\n<p>And along with your self.included that should work just fine.</p>\n\n<p>Check out some of the acts_* plugins, it's a pretty common pattern (<a href=\"http://github.com/technoweenie/acts_as_paranoid/tree/master/init.rb\" rel=\"nofollow noreferrer\">http://github.com/technoweenie/acts_as_paranoid/tree/master/init.rb</a>, check line 30)</p>\n"
},
{
"answer_id": 69405,
"author": "user11058",
"author_id": 11058,
"author_profile": "https://Stackoverflow.com/users/11058",
"pm_score": 1,
"selected": false,
"text": "<p>If you do go the plugin route, do check out <a href=\"http://rails-engines.org/\" rel=\"nofollow noreferrer\">Rails-Engines</a>, which are intended to extend plugin semantics to Controllers and Views in a clear way. </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/841/"
]
| In an effort to reduce code duplication in my little Rails app, I've been working on getting common code between my models into it's own separate module, so far so good.
The model stuff is fairly easy, I just have to include the module at the beginning, e.g.:
```
class Iso < Sale
include Shared::TracksSerialNumberExtension
include Shared::OrderLines
extend Shared::Filtered
include Sendable::Model
validates_presence_of :customer
validates_associated :lines
owned_by :customer
def initialize( params = nil )
super
self.created_at ||= Time.now.to_date
end
def after_initialize
end
order_lines :despatched
# tracks_serial_numbers :items
sendable :customer
def created_at=( date )
write_attribute( :created_at, Chronic.parse( date ) )
end
end
```
This is working fine, now however, I'm going to have some controller and view code that's going to be common between these models as well, so far I have this for my sendable stuff:
```
# This is a module that is used for pages/forms that are can be "sent"
# either via fax, email, or printed.
module Sendable
module Model
def self.included( klass )
klass.extend ClassMethods
end
module ClassMethods
def sendable( class_to_send_to )
attr_accessor :fax_number,
:email_address,
:to_be_faxed,
:to_be_emailed,
:to_be_printed
@_class_sending_to ||= class_to_send_to
include InstanceMethods
end
def class_sending_to
@_class_sending_to
end
end # ClassMethods
module InstanceMethods
def after_initialize( )
super
self.to_be_faxed = false
self.to_be_emailed = false
self.to_be_printed = false
target_class = self.send( self.class.class_sending_to )
if !target_class.nil?
self.fax_number = target_class.send( :fax_number )
self.email_address = target_class.send( :email_address )
end
end
end
end # Module Model
end # Module Sendable
```
Basically I'm planning on just doing an include Sendable::Controller, and Sendable::View (or the equivalent) for the controller and the view, but, is there a cleaner way to do this? I 'm after a neat way to have a bunch of common code between my model, controller, and view.
Edit: Just to clarify, this just has to be shared across 2 or 3 models. | You could pluginize it (use script/generate plugin).
Then in your init.rb just do something like:
```
ActiveRecord::Base.send(:include, PluginName::Sendable)
ActionController::Base.send(:include, PluginName::SendableController)
```
And along with your self.included that should work just fine.
Check out some of the acts\_\* plugins, it's a pretty common pattern (<http://github.com/technoweenie/acts_as_paranoid/tree/master/init.rb>, check line 30) |
68,408 | <p>Is there any <strong>simple algorithm</strong> to determine the likeliness of 2 names representing the same person? </p>
<p>I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'.</p>
<p>If there is an algorithm in <code>C#</code> that would be great, but I can translate from any language.</p>
| [
{
"answer_id": 68422,
"author": "Antti",
"author_id": 6037,
"author_profile": "https://Stackoverflow.com/users/6037",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein</a> is close, although maybe not exactly what you want.</p>\n"
},
{
"answer_id": 68437,
"author": "Sergio Morales",
"author_id": 9506,
"author_profile": "https://Stackoverflow.com/users/9506",
"pm_score": 0,
"selected": false,
"text": "<p>I doubt there is, considering even the <a href=\"http://www.upgradetravelbetter.com/2008/09/14/tired-of-secondary-screenings-change-your-name/\" rel=\"nofollow noreferrer\">Customs Department doesn't seem to have a satisfactory answer</a>...</p>\n"
},
{
"answer_id": 68452,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": 0,
"selected": false,
"text": "<p>If there is a solution to this problem I seriously doubt it's a part of core C#. Off the top of my head, it would require a database of first, middle and last name frequencies, as well as account for initials, as in your example. This is fairly complex logic that relies on a database of information.</p>\n"
},
{
"answer_id": 68466,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 0,
"selected": false,
"text": "<p>Second to Levenshtein distance, what language do you want? I was able to find an implementation in C# on codeproject pretty easily.</p>\n"
},
{
"answer_id": 68475,
"author": "Lee",
"author_id": 6035,
"author_profile": "https://Stackoverflow.com/users/6035",
"pm_score": 0,
"selected": false,
"text": "<p>In an application I worked on, the Last name field was considered reliable.\nSo presented all the all the records with the same last name to the user.\nUser could sort by the other fields to look for similar names.\nThis solution was good enough to greatly reduce the issue of users creating duplicate records.</p>\n\n<p>Basically looks like the issue will require human judgement.</p>\n"
},
{
"answer_id": 68511,
"author": "Andrey Fedorov",
"author_id": 10728,
"author_profile": "https://Stackoverflow.com/users/10728",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like you're looking for a phonetic-based algorithms, such as <a href=\"http://en.wikipedia.org/wiki/Soundex\" rel=\"nofollow noreferrer\">soundex</a>, <a href=\"http://en.wikipedia.org/wiki/New_York_State_Identification_and_Intelligence_System\" rel=\"nofollow noreferrer\">NYSIIS</a>, or <a href=\"http://en.wikipedia.org/wiki/Double_Metaphone\" rel=\"nofollow noreferrer\">double metaphone</a>. The first actually <em>is</em> what several government departments use, and is trivial to implement (with many implementations readily <a href=\"http://www.google.com/search?q=soundex+c%23\" rel=\"nofollow noreferrer\">available</a>). The second is a slightly more complicated and more precise version of the first. The latter-most works with some non-English names and alphabets.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Levenshtein_distance\" rel=\"nofollow noreferrer\">Levenshtein distance</a> is a definition of distance between two arbitrary strings. It gives you a distance of 0 between identical strings and non-zero between different strings, which might also be useful if you decide to make a custom algorithm.</p>\n"
},
{
"answer_id": 68570,
"author": "Stanislav Kniazev",
"author_id": 10757,
"author_profile": "https://Stackoverflow.com/users/10757",
"pm_score": 3,
"selected": true,
"text": "<p>I've faced similar problem and tried to use Levenstein distance first, but it did not work well for me. I came up with an algorithm that gives you \"similarity\" value between two strings (higher value means more similar strings, \"1\" for identical strings). This value is not very meaningful by itself (if not \"1\", always 0.5 or less), but works quite well when you throw in Hungarian Matrix to find matching pairs from two lists of strings.</p>\n\n<p>Use like this:</p>\n\n<pre><code>PartialStringComparer cmp = new PartialStringComparer();\ntbResult.Text = cmp.Compare(textBox1.Text, textBox2.Text).ToString();\n</code></pre>\n\n<p>The code behind:</p>\n\n<pre><code>public class SubstringRange {\n string masterString;\n\n public string MasterString {\n get { return masterString; }\n set { masterString = value; }\n }\n int start;\n\n public int Start {\n get { return start; }\n set { start = value; }\n }\n int end;\n\n public int End {\n get { return end; }\n set { end = value; }\n }\n public int Length {\n get { return End - Start; }\n set { End = Start + value;}\n }\n\n public bool IsValid {\n get { return MasterString.Length >= End && End >= Start && Start >= 0; }\n }\n\n public string Contents {\n get {\n if(IsValid) {\n return MasterString.Substring(Start, Length);\n } else {\n return \"\";\n }\n }\n }\n public bool OverlapsRange(SubstringRange range) {\n return !(End < range.Start || Start > range.End);\n }\n public bool ContainsRange(SubstringRange range) {\n return range.Start >= Start && range.End <= End;\n }\n public bool ExpandTo(string newContents) {\n if(MasterString.Substring(Start).StartsWith(newContents, StringComparison.InvariantCultureIgnoreCase) && newContents.Length > Length) {\n Length = newContents.Length;\n return true;\n } else {\n return false;\n }\n }\n}\n\npublic class SubstringRangeList: List<SubstringRange> {\n string masterString;\n\n public string MasterString {\n get { return masterString; }\n set { masterString = value; }\n }\n\n public SubstringRangeList(string masterString) {\n this.MasterString = masterString;\n }\n\n public SubstringRange FindString(string s){\n foreach(SubstringRange r in this){\n if(r.Contents.Equals(s, StringComparison.InvariantCultureIgnoreCase))\n return r;\n }\n return null;\n }\n\n public SubstringRange FindSubstring(string s){\n foreach(SubstringRange r in this){\n if(r.Contents.StartsWith(s, StringComparison.InvariantCultureIgnoreCase))\n return r;\n }\n return null;\n }\n\n public bool ContainsRange(SubstringRange range) {\n foreach(SubstringRange r in this) {\n if(r.ContainsRange(range))\n return true;\n }\n return false;\n }\n\n public bool AddSubstring(string substring) {\n bool result = false;\n foreach(SubstringRange r in this) {\n if(r.ExpandTo(substring)) {\n result = true;\n }\n }\n if(FindSubstring(substring) == null) {\n bool patternfound = true;\n int start = 0;\n while(patternfound){\n patternfound = false;\n start = MasterString.IndexOf(substring, start, StringComparison.InvariantCultureIgnoreCase);\n patternfound = start != -1;\n if(patternfound) {\n SubstringRange r = new SubstringRange();\n r.MasterString = this.MasterString;\n r.Start = start++;\n r.Length = substring.Length;\n if(!ContainsRange(r)) {\n this.Add(r);\n result = true;\n }\n }\n }\n }\n return result;\n }\n\n private static bool SubstringRangeMoreThanOneChar(SubstringRange range) {\n return range.Length > 1;\n }\n\n public float Weight {\n get {\n if(MasterString.Length == 0 || Count == 0)\n return 0;\n float numerator = 0;\n int denominator = 0;\n foreach(SubstringRange r in this.FindAll(SubstringRangeMoreThanOneChar)) {\n numerator += r.Length;\n denominator++;\n }\n if(denominator == 0)\n return 0;\n return numerator / denominator / MasterString.Length;\n }\n }\n\n public void RemoveOverlappingRanges() {\n SubstringRangeList l = new SubstringRangeList(this.MasterString);\n l.AddRange(this);//create a copy of this list\n foreach(SubstringRange r in l) {\n if(this.Contains(r) && this.ContainsRange(r)) {\n Remove(r);//try to remove the range\n if(!ContainsRange(r)) {//see if the list still contains \"superset\" of this range\n Add(r);//if not, add it back\n }\n }\n }\n }\n\n public void AddStringToCompare(string s) {\n for(int start = 0; start < s.Length; start++) {\n for(int len = 1; start + len <= s.Length; len++) {\n string part = s.Substring(start, len);\n if(!AddSubstring(part))\n break;\n }\n }\n RemoveOverlappingRanges();\n }\n}\n\npublic class PartialStringComparer {\n public float Compare(string s1, string s2) {\n SubstringRangeList srl1 = new SubstringRangeList(s1);\n srl1.AddStringToCompare(s2);\n SubstringRangeList srl2 = new SubstringRangeList(s2);\n srl2.AddStringToCompare(s1);\n return (srl1.Weight + srl2.Weight) / 2;\n }\n}\n</code></pre>\n\n<p>Levenstein distance one is much simpler (adapted from <a href=\"http://www.merriampark.com/ld.htm\" rel=\"nofollow noreferrer\">http://www.merriampark.com/ld.htm</a>):</p>\n\n<pre><code>public class Distance {\n /// <summary>\n /// Compute Levenshtein distance\n /// </summary>\n /// <param name=\"s\">String 1</param>\n /// <param name=\"t\">String 2</param>\n /// <returns>Distance between the two strings.\n /// The larger the number, the bigger the difference.\n /// </returns>\n public static int LD(string s, string t) {\n int n = s.Length; //length of s\n int m = t.Length; //length of t\n int[,] d = new int[n + 1, m + 1]; // matrix\n int cost; // cost\n // Step 1\n if(n == 0) return m;\n if(m == 0) return n;\n // Step 2\n for(int i = 0; i <= n; d[i, 0] = i++) ;\n for(int j = 0; j <= m; d[0, j] = j++) ;\n // Step 3\n for(int i = 1; i <= n; i++) {\n //Step 4\n for(int j = 1; j <= m; j++) {\n // Step 5\n cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);\n // Step 6\n d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost);\n }\n }\n // Step 7\n return d[n, m];\n }\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3610/"
]
| Is there any **simple algorithm** to determine the likeliness of 2 names representing the same person?
I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'.
If there is an algorithm in `C#` that would be great, but I can translate from any language. | I've faced similar problem and tried to use Levenstein distance first, but it did not work well for me. I came up with an algorithm that gives you "similarity" value between two strings (higher value means more similar strings, "1" for identical strings). This value is not very meaningful by itself (if not "1", always 0.5 or less), but works quite well when you throw in Hungarian Matrix to find matching pairs from two lists of strings.
Use like this:
```
PartialStringComparer cmp = new PartialStringComparer();
tbResult.Text = cmp.Compare(textBox1.Text, textBox2.Text).ToString();
```
The code behind:
```
public class SubstringRange {
string masterString;
public string MasterString {
get { return masterString; }
set { masterString = value; }
}
int start;
public int Start {
get { return start; }
set { start = value; }
}
int end;
public int End {
get { return end; }
set { end = value; }
}
public int Length {
get { return End - Start; }
set { End = Start + value;}
}
public bool IsValid {
get { return MasterString.Length >= End && End >= Start && Start >= 0; }
}
public string Contents {
get {
if(IsValid) {
return MasterString.Substring(Start, Length);
} else {
return "";
}
}
}
public bool OverlapsRange(SubstringRange range) {
return !(End < range.Start || Start > range.End);
}
public bool ContainsRange(SubstringRange range) {
return range.Start >= Start && range.End <= End;
}
public bool ExpandTo(string newContents) {
if(MasterString.Substring(Start).StartsWith(newContents, StringComparison.InvariantCultureIgnoreCase) && newContents.Length > Length) {
Length = newContents.Length;
return true;
} else {
return false;
}
}
}
public class SubstringRangeList: List<SubstringRange> {
string masterString;
public string MasterString {
get { return masterString; }
set { masterString = value; }
}
public SubstringRangeList(string masterString) {
this.MasterString = masterString;
}
public SubstringRange FindString(string s){
foreach(SubstringRange r in this){
if(r.Contents.Equals(s, StringComparison.InvariantCultureIgnoreCase))
return r;
}
return null;
}
public SubstringRange FindSubstring(string s){
foreach(SubstringRange r in this){
if(r.Contents.StartsWith(s, StringComparison.InvariantCultureIgnoreCase))
return r;
}
return null;
}
public bool ContainsRange(SubstringRange range) {
foreach(SubstringRange r in this) {
if(r.ContainsRange(range))
return true;
}
return false;
}
public bool AddSubstring(string substring) {
bool result = false;
foreach(SubstringRange r in this) {
if(r.ExpandTo(substring)) {
result = true;
}
}
if(FindSubstring(substring) == null) {
bool patternfound = true;
int start = 0;
while(patternfound){
patternfound = false;
start = MasterString.IndexOf(substring, start, StringComparison.InvariantCultureIgnoreCase);
patternfound = start != -1;
if(patternfound) {
SubstringRange r = new SubstringRange();
r.MasterString = this.MasterString;
r.Start = start++;
r.Length = substring.Length;
if(!ContainsRange(r)) {
this.Add(r);
result = true;
}
}
}
}
return result;
}
private static bool SubstringRangeMoreThanOneChar(SubstringRange range) {
return range.Length > 1;
}
public float Weight {
get {
if(MasterString.Length == 0 || Count == 0)
return 0;
float numerator = 0;
int denominator = 0;
foreach(SubstringRange r in this.FindAll(SubstringRangeMoreThanOneChar)) {
numerator += r.Length;
denominator++;
}
if(denominator == 0)
return 0;
return numerator / denominator / MasterString.Length;
}
}
public void RemoveOverlappingRanges() {
SubstringRangeList l = new SubstringRangeList(this.MasterString);
l.AddRange(this);//create a copy of this list
foreach(SubstringRange r in l) {
if(this.Contains(r) && this.ContainsRange(r)) {
Remove(r);//try to remove the range
if(!ContainsRange(r)) {//see if the list still contains "superset" of this range
Add(r);//if not, add it back
}
}
}
}
public void AddStringToCompare(string s) {
for(int start = 0; start < s.Length; start++) {
for(int len = 1; start + len <= s.Length; len++) {
string part = s.Substring(start, len);
if(!AddSubstring(part))
break;
}
}
RemoveOverlappingRanges();
}
}
public class PartialStringComparer {
public float Compare(string s1, string s2) {
SubstringRangeList srl1 = new SubstringRangeList(s1);
srl1.AddStringToCompare(s2);
SubstringRangeList srl2 = new SubstringRangeList(s2);
srl2.AddStringToCompare(s1);
return (srl1.Weight + srl2.Weight) / 2;
}
}
```
Levenstein distance one is much simpler (adapted from <http://www.merriampark.com/ld.htm>):
```
public class Distance {
/// <summary>
/// Compute Levenshtein distance
/// </summary>
/// <param name="s">String 1</param>
/// <param name="t">String 2</param>
/// <returns>Distance between the two strings.
/// The larger the number, the bigger the difference.
/// </returns>
public static int LD(string s, string t) {
int n = s.Length; //length of s
int m = t.Length; //length of t
int[,] d = new int[n + 1, m + 1]; // matrix
int cost; // cost
// Step 1
if(n == 0) return m;
if(m == 0) return n;
// Step 2
for(int i = 0; i <= n; d[i, 0] = i++) ;
for(int j = 0; j <= m; d[0, j] = j++) ;
// Step 3
for(int i = 1; i <= n; i++) {
//Step 4
for(int j = 1; j <= m; j++) {
// Step 5
cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);
// Step 6
d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
}
``` |
68,444 | <p>We have a program that produces several SWF files, some CSS and XML files, all of which need to be deployed for the thing to work.</p>
<p>Is there a program or technique out there for wrapping all these files together into a single SWF file?</p>
| [
{
"answer_id": 68474,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "<p>I think you can just drag them into the library of your main swf and make references to them. At least the other SWFs you can, not sure about the CSS and XML.</p>\n"
},
{
"answer_id": 178420,
"author": "Pedro",
"author_id": 15524,
"author_profile": "https://Stackoverflow.com/users/15524",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the flex sdk and the [EMBED ] tag for all those files, as for the xml and css you can just compile them in the wrapper swf produced by flex. It works by having a 'skeleton' mxml file that will be injected with the css and xml, and then embed the swf files.</p>\n"
},
{
"answer_id": 192919,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "<p>If you use the Flex compiler (<code>mxmlc</code> or FlexBuilder) you can embed SWF files and create them at runtime, more or less like you would create any display object:</p>\n\n<pre><code>package {\n\n\n public class Assets {\n\n [Embed(source=\"another.swf\")]\n public var another : Class;\n\n }\n\n}\n</code></pre>\n\n<p>The code above embeds the file <code>another.swf</code> and makes it possible to create it in another SWF, like this:</p>\n\n<pre><code>package {\n\n import flash.display.Sprite;\n\n\n public class MyFancySite extends Sprite {\n\n public function MyFancySprite( ) {\n var theOther : DisplayObject = new Assets.another();\n\n addChild(theOther);\n }\n\n }\n\n}\n</code></pre>\n\n<p>CSS, XML and any other file can be embedded in a similar fashion. Here's a description: <a href=\"http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html</a></p>\n"
},
{
"answer_id": 195260,
"author": "matt lohkamp",
"author_id": 14026,
"author_profile": "https://Stackoverflow.com/users/14026",
"pm_score": 0,
"selected": false,
"text": "<p>using flex to easily embed them is a good way to go, and if that doesn't sound like fun, think of it this way - XML and CSS data is really just a big long string - so hard-code the string data as a variable inside of your project, and use it as normal.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6277/"
]
| We have a program that produces several SWF files, some CSS and XML files, all of which need to be deployed for the thing to work.
Is there a program or technique out there for wrapping all these files together into a single SWF file? | If you use the Flex compiler (`mxmlc` or FlexBuilder) you can embed SWF files and create them at runtime, more or less like you would create any display object:
```
package {
public class Assets {
[Embed(source="another.swf")]
public var another : Class;
}
}
```
The code above embeds the file `another.swf` and makes it possible to create it in another SWF, like this:
```
package {
import flash.display.Sprite;
public class MyFancySite extends Sprite {
public function MyFancySprite( ) {
var theOther : DisplayObject = new Assets.another();
addChild(theOther);
}
}
}
```
CSS, XML and any other file can be embedded in a similar fashion. Here's a description: <http://livedocs.adobe.com/flex/3/html/help.html?content=embed_4.html> |
68,477 | <p>Is there a way to send a file using POST from a Python script?</p>
| [
{
"answer_id": 68502,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 5,
"selected": false,
"text": "<p>Yes. You'd use the <code>urllib2</code> module, and encode using the <code>multipart/form-data</code> content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:</p>\n\n<pre><code>user_agent = \"image uploader\"\ndefault_message = \"Image $current of $total\"\n\nimport logging\nimport os\nfrom os.path import abspath, isabs, isdir, isfile, join\nimport random\nimport string\nimport sys\nimport mimetypes\nimport urllib2\nimport httplib\nimport time\nimport re\n\ndef random_string (length):\n return ''.join (random.choice (string.letters) for ii in range (length + 1))\n\ndef encode_multipart_data (data, files):\n boundary = random_string (30)\n\n def get_content_type (filename):\n return mimetypes.guess_type (filename)[0] or 'application/octet-stream'\n\n def encode_field (field_name):\n return ('--' + boundary,\n 'Content-Disposition: form-data; name=\"%s\"' % field_name,\n '', str (data [field_name]))\n\n def encode_file (field_name):\n filename = files [field_name]\n return ('--' + boundary,\n 'Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"' % (field_name, filename),\n 'Content-Type: %s' % get_content_type(filename),\n '', open (filename, 'rb').read ())\n\n lines = []\n for name in data:\n lines.extend (encode_field (name))\n for name in files:\n lines.extend (encode_file (name))\n lines.extend (('--%s--' % boundary, ''))\n body = '\\r\\n'.join (lines)\n\n headers = {'content-type': 'multipart/form-data; boundary=' + boundary,\n 'content-length': str (len (body))}\n\n return body, headers\n\ndef send_post (url, data, files):\n req = urllib2.Request (url)\n connection = httplib.HTTPConnection (req.get_host ())\n connection.request ('POST', req.get_selector (),\n *encode_multipart_data (data, files))\n response = connection.getresponse ()\n logging.debug ('response = %s', response.read ())\n logging.debug ('Code: %s %s', response.status, response.reason)\n\ndef make_upload_file (server, thread, delay = 15, message = None,\n username = None, email = None, password = None):\n\n delay = max (int (delay or '0'), 15)\n\n def upload_file (path, current, total):\n assert isabs (path)\n assert isfile (path)\n\n logging.debug ('Uploading %r to %r', path, server)\n message_template = string.Template (message or default_message)\n\n data = {'MAX_FILE_SIZE': '3145728',\n 'sub': '',\n 'mode': 'regist',\n 'com': message_template.safe_substitute (current = current, total = total),\n 'resto': thread,\n 'name': username or '',\n 'email': email or '',\n 'pwd': password or random_string (20),}\n files = {'upfile': path}\n\n send_post (server, data, files)\n\n logging.info ('Uploaded %r', path)\n rand_delay = random.randint (delay, delay + 5)\n logging.debug ('Sleeping for %.2f seconds------------------------------\\n\\n', rand_delay)\n time.sleep (rand_delay)\n\n return upload_file\n\ndef upload_directory (path, upload_file):\n assert isabs (path)\n assert isdir (path)\n\n matching_filenames = []\n file_matcher = re.compile (r'\\.(?:jpe?g|gif|png)$', re.IGNORECASE)\n\n for dirpath, dirnames, filenames in os.walk (path):\n for name in filenames:\n file_path = join (dirpath, name)\n logging.debug ('Testing file_path %r', file_path)\n if file_matcher.search (file_path):\n matching_filenames.append (file_path)\n else:\n logging.info ('Ignoring non-image file %r', path)\n\n total_count = len (matching_filenames)\n for index, file_path in enumerate (matching_filenames):\n upload_file (file_path, index + 1, total_count)\n\ndef run_upload (options, paths):\n upload_file = make_upload_file (**options)\n\n for arg in paths:\n path = abspath (arg)\n if isdir (path):\n upload_directory (path, upload_file)\n elif isfile (path):\n upload_file (path)\n else:\n logging.error ('No such path: %r' % path)\n\n logging.info ('Done!')\n</code></pre>\n"
},
{
"answer_id": 75158,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 0,
"selected": false,
"text": "<p>You may also want to have a look at <a href=\"http://code.google.com/p/httplib2/\" rel=\"nofollow noreferrer\">httplib2</a>, with <a href=\"http://bitworking.org/projects/httplib2/doc/html/libhttplib2.html#examples\" rel=\"nofollow noreferrer\">examples</a>. I find using httplib2 is more concise than using the built-in HTTP modules.</p>\n"
},
{
"answer_id": 525193,
"author": "gotgenes",
"author_id": 38140,
"author_profile": "https://Stackoverflow.com/users/38140",
"pm_score": 2,
"selected": false,
"text": "<p>Chris Atlee's <a href=\"http://atlee.ca/software/poster/\" rel=\"nofollow noreferrer\">poster</a> library works really well for this (particularly the convenience function <code>poster.encode.multipart_encode()</code>). As a bonus, it supports streaming of large files without loading an entire file into memory. See also <a href=\"http://bugs.python.org/issue3244\" rel=\"nofollow noreferrer\">Python issue 3244</a>.</p>\n"
},
{
"answer_id": 7969778,
"author": "ilmarinen",
"author_id": 1024114,
"author_profile": "https://Stackoverflow.com/users/1024114",
"pm_score": 2,
"selected": false,
"text": "<p>The only thing that stops you from using urlopen directly on a file object is the fact that the builtin file object lacks a <strong>len</strong> definition. A simple way is to create a subclass, which provides urlopen with the correct file. \nI have also modified the Content-Type header in the file below.</p>\n\n<pre><code>import os\nimport urllib2\nclass EnhancedFile(file):\n def __init__(self, *args, **keyws):\n file.__init__(self, *args, **keyws)\n\n def __len__(self):\n return int(os.fstat(self.fileno())[6])\n\ntheFile = EnhancedFile('a.xml', 'r')\ntheUrl = \"http://example.com/abcde\"\ntheHeaders= {'Content-Type': 'text/xml'}\n\ntheRequest = urllib2.Request(theUrl, theFile, theHeaders)\n\nresponse = urllib2.urlopen(theRequest)\n\ntheFile.close()\n\n\nfor line in response:\n print line\n</code></pre>\n"
},
{
"answer_id": 10234640,
"author": "Piotr Dobrogost",
"author_id": 95735,
"author_profile": "https://Stackoverflow.com/users/95735",
"pm_score": 8,
"selected": false,
"text": "<p>From: <a href=\"https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file\" rel=\"noreferrer\">https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file</a></p>\n\n<p>Requests makes it very simple to upload Multipart-encoded files:</p>\n\n<pre><code>with open('report.xls', 'rb') as f:\n r = requests.post('http://httpbin.org/post', files={'report.xls': f})\n</code></pre>\n\n<p>That's it. I'm not joking - this is one line of code. The file was sent. Let's check:</p>\n\n<pre><code>>>> r.text\n{\n \"origin\": \"179.13.100.4\",\n \"files\": {\n \"report.xls\": \"<censored...binary...data>\"\n },\n \"form\": {},\n \"url\": \"http://httpbin.org/post\",\n \"args\": {},\n \"headers\": {\n \"Content-Length\": \"3196\",\n \"Accept-Encoding\": \"identity, deflate, compress, gzip\",\n \"Accept\": \"*/*\",\n \"User-Agent\": \"python-requests/0.8.0\",\n \"Host\": \"httpbin.org:80\",\n \"Content-Type\": \"multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1\"\n },\n \"data\": \"\"\n}\n</code></pre>\n"
},
{
"answer_id": 31305207,
"author": "rye",
"author_id": 5091149,
"author_profile": "https://Stackoverflow.com/users/5091149",
"pm_score": 3,
"selected": false,
"text": "<p>Looks like python requests does not handle extremely large multi-part files.</p>\n\n<p>The documentation recommends you look into <code>requests-toolbelt</code>.</p>\n\n<p><a href=\"https://toolbelt.readthedocs.org/en/latest/uploading-data.html\" rel=\"nofollow\">Here's the pertinent page</a> from their documentation.</p>\n"
},
{
"answer_id": 36078069,
"author": "user6081103",
"author_id": 6081103,
"author_profile": "https://Stackoverflow.com/users/6081103",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def visit_v2(device_code, camera_code):\n image1 = MultipartParam.from_file(\"files\", \"/home/yuzx/1.txt\")\n image2 = MultipartParam.from_file(\"files\", \"/home/yuzx/2.txt\")\n datagen, headers = multipart_encode([('device_code', device_code), ('position', 3), ('person_data', person_data), image1, image2])\n print \"\".join(datagen)\n if server_port == 80:\n port_str = \"\"\n else:\n port_str = \":%s\" % (server_port,)\n url_str = \"http://\" + server_ip + port_str + \"/adopen/device/visit_v2\"\n headers['nothing'] = 'nothing'\n request = urllib2.Request(url_str, datagen, headers)\n try:\n response = urllib2.urlopen(request)\n resp = response.read()\n print \"http_status =\", response.code\n result = json.loads(resp)\n print resp\n return result\n except urllib2.HTTPError, e:\n print \"http_status =\", e.code\n print e.read()\n</code></pre>\n"
},
{
"answer_id": 37142773,
"author": "Ranvijay Sachan",
"author_id": 2654232,
"author_profile": "https://Stackoverflow.com/users/2654232",
"pm_score": 2,
"selected": false,
"text": "<p>I am trying to test django rest api and its working for me:</p>\n\n<pre><code>def test_upload_file(self):\n filename = \"/Users/Ranvijay/tests/test_price_matrix.csv\"\n data = {'file': open(filename, 'rb')}\n client = APIClient()\n # client.credentials(HTTP_AUTHORIZATION='Token ' + token.key)\n response = client.post(reverse('price-matrix-csv'), data, format='multipart')\n\n print response\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n</code></pre>\n"
},
{
"answer_id": 67273481,
"author": "Станислав Тышко",
"author_id": 15771153,
"author_profile": "https://Stackoverflow.com/users/15771153",
"pm_score": 1,
"selected": false,
"text": "<p><code>pip install http_file</code></p>\n<pre class=\"lang-py prettyprint-override\"><code>#импорт вспомогательных библиотек\nimport urllib3\nurllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\nimport requests\n#импорт http_file\nfrom http_file import download_file\n#создание новой сессии\ns = requests.Session()\n#соеденение с сервером через созданную сессию\ns.get('URL_MAIN', verify=False)\n#загрузка файла в 'local_filename' из 'fileUrl' через созданную сессию\ndownload_file('local_filename', 'fileUrl', s)\n</code></pre>\n"
},
{
"answer_id": 74142597,
"author": "xCovelus",
"author_id": 1550930,
"author_profile": "https://Stackoverflow.com/users/1550930",
"pm_score": 0,
"selected": false,
"text": "<p>I tried some of the options here, but I had some issue with the headers ('files' field was empty).</p>\n<p>A simple mock to explain how I did the post using requests and fixing the issues:</p>\n<pre><code>import requests\n\nurl = 'http://127.0.0.1:54321/upload'\nfile_to_send = '25893538.pdf'\n\nfiles = {'file': (file_to_send,\n open(file_to_send, 'rb'),\n 'application/pdf',\n {'Expires': '0'})}\n\nreply = requests.post(url=url, files=files)\nprint(reply.text)\n</code></pre>\n<p>More at <a href=\"https://requests.readthedocs.io/en/latest/user/quickstart/\" rel=\"nofollow noreferrer\">https://requests.readthedocs.io/en/latest/user/quickstart/</a></p>\n<p>To test this code, you could use a simple dummy server as this one (thought to run in a GNU/Linux or similar):</p>\n<pre><code>import os\nfrom flask import Flask, request, render_template\n\nrx_file_listener = Flask(__name__)\n\nfiles_store = "/tmp"\n@rx_file_listener.route("/upload", methods=['POST'])\ndef upload_file():\n storage = os.path.join(files_store, "uploaded/")\n print(storage)\n \n if not os.path.isdir(storage):\n os.mkdir(storage)\n\n try:\n for file_rx in request.files.getlist("file"):\n name = file_rx.filename\n destination = "/".join([storage, name])\n file_rx.save(destination)\n \n return "200"\n except Exception:\n return "500"\n\nif __name__ == "__main__":\n rx_file_listener.run(port=54321, debug=True)\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
| Is there a way to send a file using POST from a Python script? | From: <https://requests.readthedocs.io/en/latest/user/quickstart/#post-a-multipart-encoded-file>
Requests makes it very simple to upload Multipart-encoded files:
```
with open('report.xls', 'rb') as f:
r = requests.post('http://httpbin.org/post', files={'report.xls': f})
```
That's it. I'm not joking - this is one line of code. The file was sent. Let's check:
```
>>> r.text
{
"origin": "179.13.100.4",
"files": {
"report.xls": "<censored...binary...data>"
},
"form": {},
"url": "http://httpbin.org/post",
"args": {},
"headers": {
"Content-Length": "3196",
"Accept-Encoding": "identity, deflate, compress, gzip",
"Accept": "*/*",
"User-Agent": "python-requests/0.8.0",
"Host": "httpbin.org:80",
"Content-Type": "multipart/form-data; boundary=127.0.0.1.502.21746.1321131593.786.1"
},
"data": ""
}
``` |
68,485 | <p>In <b>Prototype</b> I can show a "loading..." image with this code:</p>
<pre><code>var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars,
onLoading: showLoad, onComplete: showResponse} );
function showLoad () {
...
}
</code></pre>
<p>In <b>jQuery</b>, I can load a server page into an element with this:</p>
<pre><code>$('#message').load('index.php?pg=ajaxFlashcard');
</code></pre>
<p>but how do I attach a loading spinner to this command as I did in Prototype?</p>
| [
{
"answer_id": 68503,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 11,
"selected": true,
"text": "<p>There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.</p>\n\n<pre><code>$('#loadingDiv')\n .hide() // Hide it initially\n .ajaxStart(function() {\n $(this).show();\n })\n .ajaxStop(function() {\n $(this).hide();\n })\n;\n</code></pre>\n\n<p>The ajaxStart/Stop functions will fire whenever you do any Ajax calls.</p>\n\n<p><strong>Update</strong>: As of jQuery 1.8, the documentation states that <code>.ajaxStart/Stop</code> should only be attached to <code>document</code>. This would transform the above snippet to:</p>\n\n<pre><code>var $loading = $('#loadingDiv').hide();\n$(document)\n .ajaxStart(function () {\n $loading.show();\n })\n .ajaxStop(function () {\n $loading.hide();\n });\n</code></pre>\n"
},
{
"answer_id": 68517,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);\nshowLoad();\n\nfunction showResponse() {\n hideLoad();\n ...\n}\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/Ajax/load#urldatacallback\" rel=\"noreferrer\">http://docs.jquery.com/Ajax/load#urldatacallback</a></p>\n"
},
{
"answer_id": 68546,
"author": "Josh Stodola",
"author_id": 54420,
"author_profile": "https://Stackoverflow.com/users/54420",
"pm_score": 5,
"selected": false,
"text": "<p>You can insert the animated image into the DOM right before the AJAX call, and do an inline function to remove it...</p>\n\n<pre><code>$(\"#myDiv\").html('<img src=\"images/spinner.gif\" alt=\"Wait\" />');\n$('#message').load('index.php?pg=ajaxFlashcard', null, function() {\n $(\"#myDiv\").html('');\n});\n</code></pre>\n\n<p>This will make sure your animation starts at the same frame on subsequent requests (if that matters). Note that old versions of IE <em>might</em> have difficulties with the animation.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 238563,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<h3>JavaScript</h3>\n\n<pre><code>$.listen('click', '#captcha', function() {\n $('#captcha-block').html('<div id=\"loading\" style=\"width: 70px; height: 40px; display: inline-block;\" />');\n $.get(\"/captcha/new\", null, function(data) {\n $('#captcha-block').html(data);\n }); \n return false;\n});\n</code></pre>\n\n<h3>CSS</h3>\n\n<pre><code>#loading { background: url(/image/loading.gif) no-repeat center; }\n</code></pre>\n"
},
{
"answer_id": 1201403,
"author": "Nathan Bubna",
"author_id": 8131,
"author_profile": "https://Stackoverflow.com/users/8131",
"pm_score": 4,
"selected": false,
"text": "<p>Use the loading plugin: <a href=\"http://plugins.jquery.com/project/loading\" rel=\"nofollow noreferrer\">http://plugins.jquery.com/project/loading</a></p>\n\n<pre><code>$.loading.onAjax({img:'loading.gif'});\n</code></pre>\n"
},
{
"answer_id": 2387709,
"author": "kr00lix",
"author_id": 183887,
"author_profile": "https://Stackoverflow.com/users/183887",
"pm_score": 8,
"selected": false,
"text": "<p>For jQuery I use</p>\n\n<pre><code>jQuery.ajaxSetup({\n beforeSend: function() {\n $('#loader').show();\n },\n complete: function(){\n $('#loader').hide();\n },\n success: function() {}\n});\n</code></pre>\n"
},
{
"answer_id": 5863245,
"author": "Paul",
"author_id": 735217,
"author_profile": "https://Stackoverflow.com/users/735217",
"pm_score": 3,
"selected": false,
"text": "<p>Variant: I have an icon with id=\"logo\" at the top left of the main page; a spinner gif is then overlaid on top (with transparency) when ajax is working.</p>\n\n<pre><code>jQuery.ajaxSetup({\n beforeSend: function() {\n $('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')\n },\n complete: function(){\n $('#logo').css('background', 'none')\n },\n success: function() {}\n});\n</code></pre>\n"
},
{
"answer_id": 7389431,
"author": "Umesh kumar",
"author_id": 940764,
"author_profile": "https://Stackoverflow.com/users/940764",
"pm_score": 3,
"selected": false,
"text": "<p>You can simply assign a loader image to the same tag on which you later will load content using an Ajax call:</p>\n\n<pre><code>$(\"#message\").html('<span>Loading...</span>');\n\n$('#message').load('index.php?pg=ajaxFlashcard');\n</code></pre>\n\n<p>You can also replace the span tag with an image tag.</p>\n"
},
{
"answer_id": 7597533,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I do this:</p>\n\n<pre><code>var preloaderdiv = '<div class=\"thumbs_preloader\">Loading...</div>';\n $('#detail_thumbnails').html(preloaderdiv);\n $.ajax({\n async:true,\n url:'./Ajaxification/getRandomUser?top='+ $(sender).css('top') +'&lef='+ $(sender).css('left'),\n success:function(data){\n $('#detail_thumbnails').html(data);\n }\n });\n</code></pre>\n"
},
{
"answer_id": 8360518,
"author": "Quinn Comendant",
"author_id": 277303,
"author_profile": "https://Stackoverflow.com/users/277303",
"pm_score": 2,
"selected": false,
"text": "<p>I've used the following with jQuery UI Dialog. (Maybe it works with other ajax callbacks?)</p>\n\n<pre><code>$('<div><img src=\"/i/loading.gif\" id=\"loading\" /></div>').load('/ajax.html').dialog({\n height: 300,\n width: 600,\n title: 'Wait for it...'\n});\n</code></pre>\n\n<p>The contains an animated loading gif until its content is replaced when the ajax call completes.</p>\n"
},
{
"answer_id": 11454964,
"author": "guy mograbi",
"author_id": 1068746,
"author_profile": "https://Stackoverflow.com/users/1068746",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are right. \nThis method is too global... </p>\n\n<p>However - it is a good default for when your AJAX call has no effect on the page itself. (background save for example). ( you can always switch it off for a certain ajax call by passing \"global\":false - see documentation at <a href=\"http://api.jquery.com/jQuery.ajax/\" rel=\"nofollow\">jquery</a> </p>\n\n<p>When the AJAX call is meant to refresh part of the page, I like my \"loading\" images to be specific to the refreshed section. I would like to see which part is refreshed. </p>\n\n<p>Imagine how cool it would be if you could simply write something like : </p>\n\n<pre><code>$(\"#component_to_refresh\").ajax( { ... } ); \n</code></pre>\n\n<p>And this would show a \"loading\" on this section. \nBelow is a function I wrote that handles \"loading\" display as well but it is specific to the area you are refreshing in ajax. </p>\n\n<p>First, let me show you how to use it </p>\n\n<pre><code><!-- assume you have this HTML and you would like to refresh \n it / load the content with ajax -->\n\n<span id=\"email\" name=\"name\" class=\"ajax-loading\">\n</span>\n\n<!-- then you have the following javascript --> \n\n$(document).ready(function(){\n $(\"#email\").ajax({'url':\"/my/url\", load:true, global:false});\n })\n</code></pre>\n\n<p>And this is the function - a basic start that you can enhance as you wish. it is very flexible. </p>\n\n<pre><code>jQuery.fn.ajax = function(options)\n{\n var $this = $(this);\n debugger;\n function invokeFunc(func, arguments)\n {\n if ( typeof(func) == \"function\")\n {\n func( arguments ) ;\n }\n }\n\n function _think( obj, think )\n {\n if ( think )\n {\n obj.html('<div class=\"loading\" style=\"background: url(/public/images/loading_1.gif) no-repeat; display:inline-block; width:70px; height:30px; padding-left:25px;\"> Loading ... </div>');\n }\n else\n {\n obj.find(\".loading\").hide();\n }\n }\n\n function makeMeThink( think )\n {\n if ( $this.is(\".ajax-loading\") )\n {\n _think($this,think);\n }\n else\n {\n _think($this, think);\n }\n }\n\n options = $.extend({}, options); // make options not null - ridiculous, but still.\n // read more about ajax events\n var newoptions = $.extend({\n beforeSend: function()\n {\n invokeFunc(options.beforeSend, null);\n makeMeThink(true);\n },\n\n complete: function()\n {\n invokeFunc(options.complete);\n makeMeThink(false);\n },\n success:function(result)\n {\n invokeFunc(options.success);\n if ( options.load )\n {\n $this.html(result);\n }\n }\n\n }, options);\n\n $.ajax(newoptions);\n};\n</code></pre>\n"
},
{
"answer_id": 12190482,
"author": "Seeker",
"author_id": 468202,
"author_profile": "https://Stackoverflow.com/users/468202",
"pm_score": 6,
"selected": false,
"text": "<p>You can just use the jQuery's <code>.ajax</code> function and use its option <code>beforeSend</code> and define some function in which you can show something like a loader div and on success option you can hide that loader div.</p>\n\n<pre><code>jQuery.ajax({\n type: \"POST\",\n url: 'YOU_URL_TO_WHICH_DATA_SEND',\n data:'YOUR_DATA_TO_SEND',\n beforeSend: function() {\n $(\"#loaderDiv\").show();\n },\n success: function(data) {\n $(\"#loaderDiv\").hide();\n }\n});\n</code></pre>\n\n<p>You can have any Spinning Gif image. Here is a website that is a great AJAX Loader Generator according to your color scheme: <a href=\"http://ajaxload.info/\" rel=\"noreferrer\">http://ajaxload.info/</a></p>\n"
},
{
"answer_id": 12268009,
"author": "Lee Goddard",
"author_id": 418150,
"author_profile": "https://Stackoverflow.com/users/418150",
"pm_score": 3,
"selected": false,
"text": "<p>As well as setting global defaults for ajax events, you can set behaviour for specific elements. Perhaps just changing their class would be enough?</p>\n\n<pre><code>$('#myForm').ajaxSend( function() {\n $(this).addClass('loading');\n});\n$('#myForm').ajaxComplete( function(){\n $(this).removeClass('loading');\n});\n</code></pre>\n\n<p>Example CSS, to hide #myForm with a spinner:</p>\n\n<pre><code>.loading {\n display: block;\n background: url(spinner.gif) no-repeat center middle;\n width: 124px;\n height: 124px;\n margin: 0 auto;\n}\n/* Hide all the children of the 'loading' element */\n.loading * {\n display: none; \n}\n</code></pre>\n"
},
{
"answer_id": 15763341,
"author": "Emil Stenström",
"author_id": 117268,
"author_profile": "https://Stackoverflow.com/users/117268",
"pm_score": 3,
"selected": false,
"text": "<p>I ended up with two changes to the <a href=\"https://stackoverflow.com/a/68503/117268\">original reply</a>. </p>\n\n<ol>\n<li>As of jQuery 1.8, ajaxStart and ajaxStop should only be attached to <code>document</code>. This makes it harder to filter only a some of the ajax requests. Soo...</li>\n<li>Switching to <a href=\"http://api.jquery.com/ajaxSend/\" rel=\"nofollow noreferrer\">ajaxSend</a> and <a href=\"http://api.jquery.com/ajaxComplete/\" rel=\"nofollow noreferrer\">ajaxComplete</a> makes it possible to interspect the current ajax request before showing the spinner.</li>\n</ol>\n\n<p>This is the code after these changes:</p>\n\n<pre><code>$(document)\n .hide() // hide it initially\n .ajaxSend(function(event, jqxhr, settings) {\n if (settings.url !== \"ajax/request.php\") return;\n $(\".spinner\").show();\n })\n .ajaxComplete(function(event, jqxhr, settings) {\n if (settings.url !== \"ajax/request.php\") return;\n $(\".spinner\").hide();\n })\n</code></pre>\n"
},
{
"answer_id": 15907031,
"author": "keithhackbarth",
"author_id": 965679,
"author_profile": "https://Stackoverflow.com/users/965679",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't want to write your own code, there are also a lot of plugins that do just that:</p>\n\n<ul>\n<li><a href=\"https://github.com/keithhackbarth/jquery-loading\" rel=\"nofollow\">https://github.com/keithhackbarth/jquery-loading</a></li>\n<li><a href=\"http://plugins.jquery.com/project/loading\" rel=\"nofollow\">http://plugins.jquery.com/project/loading</a></li>\n</ul>\n"
},
{
"answer_id": 16938360,
"author": "Amin Saqi",
"author_id": 1814343,
"author_profile": "https://Stackoverflow.com/users/1814343",
"pm_score": 5,
"selected": false,
"text": "<p>If you are using <code>$.ajax()</code> you can use somthing like this:</p>\n<pre><code>$.ajax({\n url: "destination url",\n success: sdialog,\n error: edialog,\n // shows the loader element before sending.\n beforeSend: function() {\n $("#imgSpinner1").show();\n },\n // hides the loader after completion of request, whether successfull or failor. \n complete: function() {\n $("#imgSpinner1").hide();\n },\n type: 'POST',\n dataType: 'json'\n});\n</code></pre>\n<p>Although the setting is named "beforeSend", as of <a href=\"https://api.jquery.com/jQuery.ajax/\" rel=\"noreferrer\">jQuery 1.5 "beforeSend" will be called regardless of the request type.</a> i.e. The <code>.show()</code> function will be called if <code>type: 'GET'</code>.</p>\n"
},
{
"answer_id": 19910389,
"author": "Fred K",
"author_id": 1252920,
"author_profile": "https://Stackoverflow.com/users/1252920",
"pm_score": 2,
"selected": false,
"text": "<p>This is the best way for me:</p>\n\n<p><strong>jQuery</strong>:</p>\n\n<pre><code>$(document).ajaxStart(function() {\n $(\".loading\").show();\n});\n\n$(document).ajaxStop(function() {\n $(\".loading\").hide();\n});\n</code></pre>\n\n<p><strong>Coffee</strong>:</p>\n\n<pre><code> $(document).ajaxStart ->\n $(\".loading\").show()\n\n $(document).ajaxStop ->\n $(\".loading\").hide()\n</code></pre>\n\n<p>Docs: <a href=\"http://api.jquery.com/ajaxStart/\" rel=\"nofollow\">ajaxStart</a>, <a href=\"http://api.jquery.com/ajaxStop/\" rel=\"nofollow\">ajaxStop</a></p>\n"
},
{
"answer_id": 21930015,
"author": "Brendan Vogt",
"author_id": 225799,
"author_profile": "https://Stackoverflow.com/users/225799",
"pm_score": 3,
"selected": false,
"text": "<p>I also want to contribute to this answer. I was looking for something similar in jQuery and this what I eventually ended up using.</p>\n\n<p>I got my loading spinner from <a href=\"http://ajaxload.info/\" rel=\"noreferrer\">http://ajaxload.info/</a>. My solution is based on this simple answer at <a href=\"http://christierney.com/2011/03/23/global-ajax-loading-spinners/\" rel=\"noreferrer\">http://christierney.com/2011/03/23/global-ajax-loading-spinners/</a>.</p>\n\n<p>Basically your HTML markup and CSS would look like this:</p>\n\n<pre><code><style>\n #ajaxSpinnerImage {\n display: none;\n }\n</style>\n\n<div id=\"ajaxSpinnerContainer\">\n <img src=\"~/Content/ajax-loader.gif\" id=\"ajaxSpinnerImage\" title=\"working...\" />\n</div>\n</code></pre>\n\n<p>And then you code for jQuery would look something like this:</p>\n\n<pre><code><script>\n $(document).ready(function () {\n $(document)\n .ajaxStart(function () {\n $(\"#ajaxSpinnerImage\").show();\n })\n .ajaxStop(function () {\n $(\"#ajaxSpinnerImage\").hide();\n });\n\n var owmAPI = \"http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID\";\n $.getJSON(owmAPI)\n .done(function (data) {\n alert(data.coord.lon);\n })\n .fail(function () {\n alert('error');\n });\n });\n</script>\n</code></pre>\n\n<p>It is as simple as that :)</p>\n"
},
{
"answer_id": 26523067,
"author": "Shane Rowatt",
"author_id": 1273319,
"author_profile": "https://Stackoverflow.com/users/1273319",
"pm_score": 2,
"selected": false,
"text": "<p>Note that you must use asynchronous calls for spinners to work (at least that is what caused mine to not show until after the ajax call and then swiftly went away as the call had finished and removed the spinner).</p>\n\n<pre><code>$.ajax({\n url: requestUrl,\n data: data,\n dataType: 'JSON',\n processData: false,\n type: requestMethod,\n async: true, <<<<<<------ set async to true\n accepts: 'application/json',\n contentType: 'application/json',\n success: function (restResponse) {\n // something here\n },\n error: function (restResponse) {\n // something here \n }\n });\n</code></pre>\n"
},
{
"answer_id": 35783093,
"author": "ling",
"author_id": 405042,
"author_profile": "https://Stackoverflow.com/users/405042",
"pm_score": 1,
"selected": false,
"text": "<p>If you plan to use a loader everytime you make a server request, you can use the following pattern.</p>\n\n<pre><code> jTarget.ajaxloader(); // (re)start the loader\n $.post('/libs/jajaxloader/demo/service/service.php', function (content) {\n jTarget.append(content); // or do something with the content\n })\n .always(function () {\n jTarget.ajaxloader(\"stop\");\n });\n</code></pre>\n\n<p>This code in particular uses the jajaxloader plugin (which I just created)</p>\n\n<p><a href=\"https://github.com/lingtalfi/JAjaxLoader/\" rel=\"nofollow\">https://github.com/lingtalfi/JAjaxLoader/</a></p>\n"
},
{
"answer_id": 39982956,
"author": "Izabela Skibinska",
"author_id": 2176086,
"author_profile": "https://Stackoverflow.com/users/2176086",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$('#loading-image').html('<img src=\"/images/ajax-loader.gif\"> Sending...');\n\n $.ajax({\n url: uri,\n cache: false,\n success: function(){\n $('#loading-image').html(''); \n },\n\n error: function(jqXHR, textStatus, errorThrown) {\n var text = \"Error has occured when submitting the job: \"+jqXHR.status+ \" Contact IT dept\";\n $('#loading-image').html('<span style=\"color:red\">'+text +' </span>');\n\n }\n });\n</code></pre>\n"
},
{
"answer_id": 41000442,
"author": "andcl",
"author_id": 3099449,
"author_profile": "https://Stackoverflow.com/users/3099449",
"pm_score": 2,
"selected": false,
"text": "<p>This is a very simple and smart plugin for that specific purpose:\n<a href=\"https://github.com/hekigan/is-loading\" rel=\"nofollow noreferrer\">https://github.com/hekigan/is-loading</a></p>\n"
},
{
"answer_id": 45696924,
"author": "SamyCode",
"author_id": 2770633,
"author_profile": "https://Stackoverflow.com/users/2770633",
"pm_score": 0,
"selected": false,
"text": "<p>You can always use <a href=\"http://malsup.com/jquery/block/#overview\" rel=\"nofollow noreferrer\">Block UI jQuery plugin</a> which does everything for you, and it even blocks the page of any input while the ajax is loading. In case that the plugin seems to not been working, you can read about the right way to use it <a href=\"https://stackoverflow.com/questions/29796115/jquery-blockui-not-working\">in this answer.</a> Check it out.</p>\n"
},
{
"answer_id": 50678783,
"author": "Jaggan_j",
"author_id": 2093481,
"author_profile": "https://Stackoverflow.com/users/2093481",
"pm_score": 1,
"selected": false,
"text": "<p>My ajax code looks like this, in effect, I have just commented out async: false line and the spinner shows up.</p>\n\n<pre><code>$.ajax({\n url: \"@Url.Action(\"MyJsonAction\", \"Home\")\",\n type: \"POST\",\n dataType: \"json\",\n data: {parameter:variable},\n //async: false, \n\n error: function () {\n },\n\n success: function (data) {\n if (Object.keys(data).length > 0) {\n //use data \n }\n $('#ajaxspinner').hide();\n }\n });\n</code></pre>\n\n<p>I am showing the spinner within a function before the ajax code:</p>\n\n<pre><code>$(\"#MyDropDownID\").change(function () {\n $('#ajaxspinner').show();\n</code></pre>\n\n<p>For Html, I have used a font awesome class:</p>\n\n<p><code><i id=\"ajaxspinner\" class=\"fas fa-spinner fa-spin fa-3x fa-fw\" style=\"display:none\"></i></code></p>\n\n<p>Hope it helps someone.</p>\n"
},
{
"answer_id": 72977140,
"author": "Ravi Sharma",
"author_id": 11027707,
"author_profile": "https://Stackoverflow.com/users/11027707",
"pm_score": 0,
"selected": false,
"text": "<pre><code><script>\n $(window).on('beforeunload', function (e) {\n $("#loader").show();\n });\n $(document).ready(function () {\n $(window).load(function () {\n $("#loader").hide();\n });\n });\n </script>\n\n<div id="loader">\n <img src="../images/loader.png" \n style="width:90px;">\n </div>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
| In **Prototype** I can show a "loading..." image with this code:
```
var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars,
onLoading: showLoad, onComplete: showResponse} );
function showLoad () {
...
}
```
In **jQuery**, I can load a server page into an element with this:
```
$('#message').load('index.php?pg=ajaxFlashcard');
```
but how do I attach a loading spinner to this command as I did in Prototype? | There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.
```
$('#loadingDiv')
.hide() // Hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
})
;
```
The ajaxStart/Stop functions will fire whenever you do any Ajax calls.
**Update**: As of jQuery 1.8, the documentation states that `.ajaxStart/Stop` should only be attached to `document`. This would transform the above snippet to:
```
var $loading = $('#loadingDiv').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
``` |
68,509 | <p>If I use the following code I lose the ability to right click on variables in the code behind and refactor (rename in this case) them</p>
<pre><code><a href='<%# "/Admin/Content/EditResource.aspx?ResourceId=" + Eval("Id").ToString() %>'>Edit</a>
</code></pre>
<p>I see this practice everywhere but it seems weird to me as I no longer am able to get compile time errors if I change the property name.
My preferred approach is to do something like this</p>
<pre><code><a runat="server" id="MyLink">Edit</a>
</code></pre>
<p>and then in the code behind</p>
<pre><code>MyLink.Href= "/Admin/Content/EditResource.aspx?ResourceId=" + myObject.Id;
</code></pre>
<p>I'm really interested to hear if people think the above approach is better since that's what I always see on popular coding sites and blogs (e.g. Scott Guthrie) and it's smaller code, but I tend to use ASP.NET because it is compiled and prefer to know if something is broken at compile time, not run time.</p>
| [
{
"answer_id": 68530,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 3,
"selected": true,
"text": "<p>I wouldnt call it bad practice (some would disagree, but why did they give us that option in the first place?), but I would say that you'll improve overall readability and maintainability if you do not submit to this practice. You already conveyed out a good point, and that is IDE feature limitation (i.e., design time inspection, compile time warning, etc.).</p>\n\n<p>I could go on and on about how many principles it violates (code reuse, separation of concerns, etc.), but I can think of many applications out there that break nearly every principle, but still work after several years. I for one, prefer to make my code as modular and maintainable as possible.</p>\n"
},
{
"answer_id": 68533,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 1,
"selected": false,
"text": "<p>It's known as spaghetti code and many programmers find it objectionable... then again, if you and the other developers at your company find it readable and maintainable, who am I to tell you what to do.</p>\n\n<p>For sure though, use includes to reduce redundancy (DRY - don't repeat yourself)</p>\n"
},
{
"answer_id": 68552,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "<p>It's up to you. Sometimes \"spagehetti\" code is easier to maintain than building/using a full on templating system for something simple, but once you get fairly complicated pages, or more specifically, once you start including a lot of logic into the page itself, it can get dirty really quickly. </p>\n"
},
{
"answer_id": 68830,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": 0,
"selected": false,
"text": "<p>I think it is interesting that more asp.net is requiring code in the aspx pages. The listview in 3.5, and even the ASP.NET MVC. The MVC has basically no code behind, but code in the pages to render information.</p>\n"
},
{
"answer_id": 68868,
"author": "Alan Harris",
"author_id": 10847,
"author_profile": "https://Stackoverflow.com/users/10847",
"pm_score": 1,
"selected": false,
"text": "<p>I use it only occasionally, and generally for some particular reason. I will always be a happier developer with my code separated entirely from my HTML markup. It's somewhat a personal preference, but I would say this is a better practice.</p>\n"
},
{
"answer_id": 68924,
"author": "neouser99",
"author_id": 10669,
"author_profile": "https://Stackoverflow.com/users/10669",
"pm_score": 0,
"selected": false,
"text": "<p>If you think of it in terms of template development, then it is wise to keep it in the view, and not in the code behind. What if if needs to change from a anchor to a list item with unobtrusive JS to handle a click? Yes, this is not the best example, rather just that, and example.</p>\n\n<p>I always try to think in terms of if I had a designer (HTML, CSS, anything), what would I have him doing and what would I be doing in the code behind, and how do we not step on each other's toes.</p>\n"
},
{
"answer_id": 68943,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>Its only a bad practice, if you cannot encapsulate it well.</p>\n\n<p>Like everything else, you can create nasty, unreadable spaghetti code, except now you have tags to content with, which by design aren't the most readable things in the world.</p>\n\n<p>I try and keep tons of if's out of hte template, but excessive encapsulation, leads to having to look in 13 diferent places to see why div x isn't firing to the client, so its a trade off.</p>\n"
},
{
"answer_id": 68992,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 0,
"selected": false,
"text": "<p>It's not, but sometimes it's a necessary evil.</p>\n\n<p>Take your case for an example, although code behind seems to have a better separation of concern, but the problem with it is that it may not separate out the concerns as clearly as you wish. Usually when we do the code behind stuff we are not building the apps in MVC framework. The code behind code is also not easy to maintain and test anyway, at least when compare to MVC.</p>\n\n<p>If you are building ASP.NET MVC apps then I think you are surely stuck with inline code. But building in MVC pattern is the best way to go about in terms of maintainability and testability.</p>\n\n<p>To sum: inline code is not a good practice, but it's a necessary evil. </p>\n\n<p>My 2cents.</p>\n"
},
{
"answer_id": 70100,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Normally I use like this way.</p>\n\n<pre><code><a href='<%# DataBinder.Eval(Container.DataItem,\"Id\",\"\"/Admin/Content/EditResource.aspx?ResourceId={0}\") %'>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6084/"
]
| If I use the following code I lose the ability to right click on variables in the code behind and refactor (rename in this case) them
```
<a href='<%# "/Admin/Content/EditResource.aspx?ResourceId=" + Eval("Id").ToString() %>'>Edit</a>
```
I see this practice everywhere but it seems weird to me as I no longer am able to get compile time errors if I change the property name.
My preferred approach is to do something like this
```
<a runat="server" id="MyLink">Edit</a>
```
and then in the code behind
```
MyLink.Href= "/Admin/Content/EditResource.aspx?ResourceId=" + myObject.Id;
```
I'm really interested to hear if people think the above approach is better since that's what I always see on popular coding sites and blogs (e.g. Scott Guthrie) and it's smaller code, but I tend to use ASP.NET because it is compiled and prefer to know if something is broken at compile time, not run time. | I wouldnt call it bad practice (some would disagree, but why did they give us that option in the first place?), but I would say that you'll improve overall readability and maintainability if you do not submit to this practice. You already conveyed out a good point, and that is IDE feature limitation (i.e., design time inspection, compile time warning, etc.).
I could go on and on about how many principles it violates (code reuse, separation of concerns, etc.), but I can think of many applications out there that break nearly every principle, but still work after several years. I for one, prefer to make my code as modular and maintainable as possible. |
68,537 | <p>A basic problem I run into quite often, but ever found a clean solution to, is one where you want to code behaviour for interaction between different objects of a common base class or interface. To make it a bit concrete, I'll throw in an example;</p>
<p><em>Bob has been coding on a strategy game which supports "cool geographical effects". These round up to simple constraints such as if troops are walking in water, they are slowed 25%. If they are walking on grass, they are slowed 5%, and if they are walking on pavement they are slowed by 0%.</em></p>
<p><em>Now, management told Bob that they needed new sorts of troops. There would be jeeps, boats and also hovercrafts. Also, they wanted jeeps to take damage if they went drove into water, and hovercrafts would ignore all three of the terrain types. Rumor has it also that they might add another terrain type with even more features than slowing units down and taking damage.</em></p>
<p>A very rough pseudo code example follows:</p>
<pre><code>public interface ITerrain
{
void AffectUnit(IUnit unit);
}
public class Water : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.75f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.70f;
unit.Health -= 5.0f;
}
if (unit is Boat)
{
// Don't affect it anyhow
}
/*
* List grows larger each day...
*/
}
}
public class Grass : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.95f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.85f;
}
if (unit is Boat)
{
unit.SpeedMultiplier = 0.0f;
unit.Health = 0.0f;
Boat boat = unit as Boat;
boat.DamagePropeller();
// Perhaps throw in an explosion aswell?
}
/*
* List grows larger each day...
*/
}
}
</code></pre>
<p>As you can see, things would have been better if Bob had a solid design document from the beginning. As the number of units and terrain types grow, so does code complexity. Not only does Bob have to worry about figuring out which members might need to be added to the unit interface, but he also has to repeat alot of code. It's very likely that new terrain types require additional information from what can be obtained from the basic IUnit interface. </p>
<p>Each time we add another unit into the game, each terrain must be updated to handle the new unit. Clearly, this makes for a lot of repetition, not to mention the ugly runtime check which determines the type of unit being dealt with. I've opted out calls to the specific subtypes in this example, but those kinds of calls are neccessary to make. <em>An example would be that when a boat hits land, its propeller should be damaged. Not all units have propellers.</em></p>
<p>I am unsure what this kind of problem is called, but it is a many-to-many dependence which I have a hard time decoupling. I don't fancy having 100's of overloads for each IUnit subclass on ITerrain as I would want to come clean with coupling.</p>
<p>Any light on this problem is highly sought after. Perhaps I'm thinking way out of orbit all together?</p>
| [
{
"answer_id": 68560,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 0,
"selected": false,
"text": "<p>Old idea:</p>\n\n<blockquote>\n <p>Make a class iTerrain and another\n class iUnit which accepts an argument\n which is the terrain type including a\n method for affecting each unit type</p>\n \n <p>example:</p>\n\n<pre> <code> boat = new\niUnit(\"watercraft\") field = new\niTerrain(\"grass\")\nfield.effects(boat)</code></pre>\n</blockquote>\n\n<p>ok forget all that I have a better idea:</p>\n\n<p>Make the effects of each terrain a property of each unit</p>\n\n<p>Example:</p>\n\n<pre><code>\npublic class hovercraft : unit {\n #You make a base class for defaults and redefine as necessary\n speed_multiplier.water = 1\n}\n\npublic class boat : unit {\n speed_multiplier.land = 0\n}\n</code></pre>\n"
},
{
"answer_id": 68658,
"author": "Tim Williscroft",
"author_id": 2789,
"author_profile": "https://Stackoverflow.com/users/2789",
"pm_score": 1,
"selected": false,
"text": "<p>Terrain has-a Terrain Attribute </p>\n\n<p>Terrain Attributes are multidimensional. </p>\n\n<p>Units has-a Propulsion.</p>\n\n<p>Propulsion is compatible able with Terrain Attributes.</p>\n\n<p>Units move by a Terrain visit with Propulsion as an argument.\nThat gets delegated to the Propulsion.</p>\n\n<p>Units <em>may</em> get affected by terrain as part of the visit.</p>\n\n<p>Unit code knows nothing about propulsion.\nTerrain types can change w/o changing anything except Terrain Attributes and Propulsion.\nPropuslion's constructors protect existing units from new methods of travel.</p>\n"
},
{
"answer_id": 68888,
"author": "munificent",
"author_id": 9457,
"author_profile": "https://Stackoverflow.com/users/9457",
"pm_score": 1,
"selected": false,
"text": "<p>The limitation you're running into here is that C#, unlike some other OOP languages, lacks <a href=\"http://en.wikipedia.org/wiki/Multiple_dispatch\" rel=\"nofollow noreferrer\">multiple dispatch</a>.</p>\n\n<p>In other words, given these base classes:</p>\n\n<pre><code>public class Base\n{\n public virtual void Go() { Console.WriteLine(\"in Base\"); }\n}\n\npublic class Derived : Base\n{\n public virtual void Go() { Console.WriteLine(\"in Derived\"); }\n}\n</code></pre>\n\n<p>This function:</p>\n\n<pre><code>public void Test()\n{\n Base obj = new Derived();\n obj.Go();\n}\n</code></pre>\n\n<p>will correctly output \"in Derived\" even though the reference \"obj\" is of type Base. This is because <em>at runtime</em> C# will correctly find the most-derived Go() to call. </p>\n\n<p>However, since C# is a single dispatch language, it only does this for the \"first parameter\" which is implicitly \"this\" in an OOP language. The following code does <em>not</em> work like the above:</p>\n\n<pre><code>public class TestClass\n{\n public void Go(Base b)\n {\n Console.WriteLine(\"Base arg\");\n }\n\n public void Go(Derived d)\n {\n Console.WriteLine(\"Derived arg\");\n }\n\n public void Test()\n {\n Base obj = new Derived();\n Go(obj);\n }\n}\n</code></pre>\n\n<p>This will output \"Base arg\" because aside from \"this\" all other parameters are <em>statically</em> dispatched, which means they are bound to the called method at compile time. At compile time, the only thing the compiler knows is the declared type of the argument being passed (\"Base obj\") and not its actual type, so the method call is bound to the Go(Base b) one.</p>\n\n<p>A solution to your problem then, is to basically hand-author a little method dispatcher:</p>\n\n<pre><code>public class Dispatcher\n{\n public void Dispatch(IUnit unit, ITerrain terrain)\n {\n Type unitType = unit.GetType();\n Type terrainType = terrain.GetType();\n\n // go through the list and find the action that corresponds to the\n // most-derived IUnit and ITerrain types that are in the ancestor\n // chain for unitType and terrainType.\n Action<IUnit, ITerrain> action = /* left as exercise for reader ;) */\n\n action(unit, terrain);\n }\n\n // add functions to this\n public List<Action<IUnit, ITerrain>> Actions = new List<Action<IUnit, ITerrain>>();\n}\n</code></pre>\n\n<p>You can use reflection to inspect the generic parameters of each Action passed in and then choose the most-derived one that matches the unit and terrain given, then call that function. The functions added to Actions can be anywhere, even distributed across multiple assemblies.</p>\n\n<p>Interestingly, I've run into this problem a few times, but never outside of the context of games.</p>\n"
},
{
"answer_id": 69129,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 1,
"selected": false,
"text": "<p>decouple the interaction rules from the Unit and Terrain classes; interaction rules are more general than that. For example a hash table might be used with the key being a pair of interacting types and the value being an 'effector' method operating on objects of those types.</p>\n\n<p>when two objects must interact, find ALL of the interaction rules in the hash table and execute them</p>\n\n<p>this eliminates the inter-class dependencies, not to mention the hideous switch statements in your original example</p>\n\n<p>if performance becomes an issue, and the interaction rules do not change during execution, cache the rule-sets for type pairs as they are encountered and emit a new MSIL method to run them all at once</p>\n"
},
{
"answer_id": 69253,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 1,
"selected": false,
"text": "<p>There's definitely three objects in play here:</p>\n\n<blockquote>\n <p>1) Terrain<br>\n 2) Terrain Effects<br>\n 3) Units</p>\n</blockquote>\n\n<p>I would not suggest creating a map with the <em>pair</em> of terrain/unit as a key to look up the action. That is going to make it difficult for you to make sure you've got every combination covered as the lists of units and terrains grow. </p>\n\n<p>In fact, it appears that every terrain-unit combination has a unique terrain effect so it's doubtful that you'd see a benefit from having a common list of terrain effects at all.</p>\n\n<p>Instead, I would have each unit maintain its own map of terrain to terrain effect. Then, the terrain can just call Unit->AffectUnit(myTerrainType) and the unit can look up the effect that the terrain will have on itself.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2166173/"
]
| A basic problem I run into quite often, but ever found a clean solution to, is one where you want to code behaviour for interaction between different objects of a common base class or interface. To make it a bit concrete, I'll throw in an example;
*Bob has been coding on a strategy game which supports "cool geographical effects". These round up to simple constraints such as if troops are walking in water, they are slowed 25%. If they are walking on grass, they are slowed 5%, and if they are walking on pavement they are slowed by 0%.*
*Now, management told Bob that they needed new sorts of troops. There would be jeeps, boats and also hovercrafts. Also, they wanted jeeps to take damage if they went drove into water, and hovercrafts would ignore all three of the terrain types. Rumor has it also that they might add another terrain type with even more features than slowing units down and taking damage.*
A very rough pseudo code example follows:
```
public interface ITerrain
{
void AffectUnit(IUnit unit);
}
public class Water : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.75f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.70f;
unit.Health -= 5.0f;
}
if (unit is Boat)
{
// Don't affect it anyhow
}
/*
* List grows larger each day...
*/
}
}
public class Grass : ITerrain
{
public void AffectUnit(IUnit unit)
{
if (unit is HoverCraft)
{
// Don't affect it anyhow
}
if (unit is FootSoldier)
{
unit.SpeedMultiplier = 0.95f;
}
if (unit is Jeep)
{
unit.SpeedMultiplier = 0.85f;
}
if (unit is Boat)
{
unit.SpeedMultiplier = 0.0f;
unit.Health = 0.0f;
Boat boat = unit as Boat;
boat.DamagePropeller();
// Perhaps throw in an explosion aswell?
}
/*
* List grows larger each day...
*/
}
}
```
As you can see, things would have been better if Bob had a solid design document from the beginning. As the number of units and terrain types grow, so does code complexity. Not only does Bob have to worry about figuring out which members might need to be added to the unit interface, but he also has to repeat alot of code. It's very likely that new terrain types require additional information from what can be obtained from the basic IUnit interface.
Each time we add another unit into the game, each terrain must be updated to handle the new unit. Clearly, this makes for a lot of repetition, not to mention the ugly runtime check which determines the type of unit being dealt with. I've opted out calls to the specific subtypes in this example, but those kinds of calls are neccessary to make. *An example would be that when a boat hits land, its propeller should be damaged. Not all units have propellers.*
I am unsure what this kind of problem is called, but it is a many-to-many dependence which I have a hard time decoupling. I don't fancy having 100's of overloads for each IUnit subclass on ITerrain as I would want to come clean with coupling.
Any light on this problem is highly sought after. Perhaps I'm thinking way out of orbit all together? | Terrain has-a Terrain Attribute
Terrain Attributes are multidimensional.
Units has-a Propulsion.
Propulsion is compatible able with Terrain Attributes.
Units move by a Terrain visit with Propulsion as an argument.
That gets delegated to the Propulsion.
Units *may* get affected by terrain as part of the visit.
Unit code knows nothing about propulsion.
Terrain types can change w/o changing anything except Terrain Attributes and Propulsion.
Propuslion's constructors protect existing units from new methods of travel. |
68,541 | <p>When trying to use <code>libxml2</code> as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.</p>
<p>I have installed <code>python25</code> and all <code>libxml2</code> and <code>libxml2-py25</code> related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo?</p>
| [
{
"answer_id": 69513,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 2,
"selected": false,
"text": "<p>Check your path by running:</p>\n\n<pre><code>'echo $PATH'\n</code></pre>\n"
},
{
"answer_id": 70895,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 0,
"selected": false,
"text": "<p>I would suspect the permissions on the library. Can you do a strace or similar to find out the filenames it's looking for, and then check the permissions on them?</p>\n"
},
{
"answer_id": 77114,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>PATH</code> environment variable was the mistake.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| When trying to use `libxml2` as myself I get an error saying the package cannot be found. If I run as as super user I am able to import fine.
I have installed `python25` and all `libxml2` and `libxml2-py25` related libraries via fink and own the entire path including the library. Any ideas why I'd still need to sudo? | Check your path by running:
```
'echo $PATH'
``` |
68,565 | <p>I like the XMLReader class for it's simplicity and speed. But I like the xml_parse associated functions as it better allows for error recovery. It would be nice if the XMLReader class would throw exceptions for things like invalid entity refs instead of just issuinng a warning.</p>
| [
{
"answer_id": 68580,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://us2.php.net/simplexml\" rel=\"nofollow noreferrer\">SimpleXML</a> seems to do a good job for me.</p>\n"
},
{
"answer_id": 68584,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 0,
"selected": false,
"text": "<p>I mostly stick to SimpleXML, at least whenever PHP5 is available for me.</p>\n\n<p><a href=\"http://www.php.net/simplexml\" rel=\"nofollow noreferrer\">http://www.php.net/simplexml</a></p>\n"
},
{
"answer_id": 68615,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<p>I'd avoid SimpleXML if you can. Though it looks very tempting by getting to avoid a lot of \"ugly\" code, it's just what the name suggests: simple. For example, it can't handle this:</p>\n\n<pre><code><p>\n Here is <strong>a very simple</strong> XML document.\n</p>\n</code></pre>\n\n<p>Bite the bullet and go to the DOM Functions. The power of it far outweighs the little bit extra complexity. If you're familiar at all with DOM manipulation in Javascript, you'll feel right at home with this library.</p>\n"
},
{
"answer_id": 69523,
"author": "Chaoley",
"author_id": 10986,
"author_profile": "https://Stackoverflow.com/users/10986",
"pm_score": 1,
"selected": false,
"text": "<p>There are at least four options when using PHP5 to parse XML files. The best option depends on the complexity and size of the XML file.</p>\n\n<p>There’s a very good 3-part article series titled ‘<a href=\"http://www.ibm.com/developerworks/xml/library/x-xmlphp1.html\" rel=\"nofollow noreferrer\">XML for PHP developers</a>’ at IBM developerWorks.</p>\n\n<p>“Parsing with the DOM, now fully compliant with the W3C standard, is a familiar option, and is your choice for complex but relatively small documents. SimpleXML is the way to go for basic and not-too-large XML documents, and XMLReader, easier and faster than SAX, is the stream parser of choice for large documents.”</p>\n"
},
{
"answer_id": 77607,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>SimpleXML and DOM work seamlessly together, so you can use the same XML interacting with it as SimpleXML or DOM.</p>\n\n<p>For example:</p>\n\n<pre><code>$simplexml = simplexml_load_string(\"<xml></xml>\");\n$simplexml->simple = \"it is simple.\";\n\n$domxml = dom_import_simplexml($simplexml);\n$node = $domxml->ownerDocument->createElement(\"dom\", \"yes, with DOM too.\");\n$domxml->ownerDocument->firstChild->appendChild($node);\n\necho (string)$simplexml->dom;\n</code></pre>\n\n<p>You will get the result: </p>\n\n<pre><code>\"yes, with DOM too.\"\n</code></pre>\n\n<p>Because when you import the object (either into simplexml or dom) it uses the same underlining PHP object by reference. </p>\n\n<p>I figured this out when I was trying to correct some of the errors in SimpleXML by extending/wrapping the object.</p>\n\n<p>See <a href=\"http://code.google.com/p/blibrary/source/browse/trunk/classes/bXml.class.inc\" rel=\"nofollow noreferrer\">http://code.google.com/p/blibrary/source/browse/trunk/classes/bXml.class.inc</a> for examples.</p>\n\n<p>This is really good for small chunks of XML (-2MB), as DOM/SimpleXML pull the full document into memory with some additional overhead (think x2 or x3). For large XML chunks (+2MB) you'll want to use XMLReader/XMLWriter to parse SAX style, with low memory overhead. I've used 14MB+ documents successfully with XMLReader/XMLWriter.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I like the XMLReader class for it's simplicity and speed. But I like the xml\_parse associated functions as it better allows for error recovery. It would be nice if the XMLReader class would throw exceptions for things like invalid entity refs instead of just issuinng a warning. | I'd avoid SimpleXML if you can. Though it looks very tempting by getting to avoid a lot of "ugly" code, it's just what the name suggests: simple. For example, it can't handle this:
```
<p>
Here is <strong>a very simple</strong> XML document.
</p>
```
Bite the bullet and go to the DOM Functions. The power of it far outweighs the little bit extra complexity. If you're familiar at all with DOM manipulation in Javascript, you'll feel right at home with this library. |
68,569 | <p>I am a C++/C# developer and never spent time working on web pages. I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages. I want to be able to read the foreground text and also be able to read the "watermark". I understand that is probably more of a function of color selection. </p>
<p>I have been unsuccessful in my attempts to do what I want. I would imagine this to be very simple for someone with the web design tools or html knowledge. </p>
| [
{
"answer_id": 68591,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>You could make an image with the watermark and then set the image as the background via css.</p>\n\n<p>For example:</p>\n\n<pre><code><style type=\"text/css\">\n.watermark{background:url(urltoimage.png);}\n</style>\n<div class=\"watermark\">\n<p>this is some text with the watermark as the background.</p>\n</div>\n</code></pre>\n\n<p>That should work.</p>\n"
},
{
"answer_id": 73352,
"author": "Doug Kavendek",
"author_id": 9330,
"author_profile": "https://Stackoverflow.com/users/9330",
"pm_score": 3,
"selected": false,
"text": "<p>As suggested, a png background could work, or even just an absolutely positioned png that sizes to fit the page, but you are asking in a comment about what would be a good tool to create one -- if you want to go with free, try <a href=\"http://www.gimp.org/\" rel=\"noreferrer\">GIMP</a>. Create a canvas with a transparent background, add some text, rotate it and resize as you'd like, and then reduce the layer's opacity to taste.</p>\n\n<p>If you'd want it to cover the whole page, make a div with the class 'watermark' and define its style as something like:</p>\n\n<pre>\n.watermark\n{\n background-image: url(image.png);\n background-position: center center;\n background-size: 100%; /* CSS3 only, but not really necessary if you make a large enough image */\n position: absolute;\n width: 100%;\n height: 100%;\n margin: 0;\n z-index: 10;\n}\n</pre>\n\n<p>If you really want the image to stretch to fit, you can go a little further and add an image into that div, and define its style to fit (width/height:100%;).</p>\n\n<p>Of course, this comes with a pretty important caveat: IE6 and some old browsers might not know what to do with transparent pngs. Having a giant, non-transparent image covering your site would <em>certainly</em> not do. But there are <a href=\"http://bjorkoy.com/past/2007/4/8/the_easiest_way_to_png/\" rel=\"noreferrer\">some hacks</a> to get around this, luckily, which you'll most likely want to do if you do use a transparent png.</p>\n"
},
{
"answer_id": 75339,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you add \"background-attachment: fixed\" to the css in kavendek's suggestion above, you can \"pin\" the background image to the specified location in the window. That way, the watermark will always remain visible no matter where the user scrolls on the page. </p>\n\n<p>Personally, I find fixed background images to be visually annoying, but I've heard site-owners say they love knowing that their logo or copyright notice (rendered as an image, presumably) is always right under the user's nose.</p>\n"
},
{
"answer_id": 2486786,
"author": "user136776",
"author_id": 136776,
"author_profile": "https://Stackoverflow.com/users/136776",
"pm_score": 5,
"selected": false,
"text": "<pre><code><style type=\"text/css\">\n#watermark {\n color: #d0d0d0;\n font-size: 200pt;\n -webkit-transform: rotate(-45deg);\n -moz-transform: rotate(-45deg);\n position: absolute;\n width: 100%;\n height: 100%;\n margin: 0;\n z-index: -1;\n left:-100px;\n top:-200px;\n}\n</style>\n</code></pre>\n\n<p>This lets you use just text as the watermark - good for dev/test versions of a web page.</p>\n\n<pre><code><div id=\"watermark\">\n<p>This is the test version.</p>\n</div>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10755/"
]
| I am a C++/C# developer and never spent time working on web pages. I would like to put text (randomly and diagonally perhaps) in large letters across the background of some pages. I want to be able to read the foreground text and also be able to read the "watermark". I understand that is probably more of a function of color selection.
I have been unsuccessful in my attempts to do what I want. I would imagine this to be very simple for someone with the web design tools or html knowledge. | ```
<style type="text/css">
#watermark {
color: #d0d0d0;
font-size: 200pt;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
position: absolute;
width: 100%;
height: 100%;
margin: 0;
z-index: -1;
left:-100px;
top:-200px;
}
</style>
```
This lets you use just text as the watermark - good for dev/test versions of a web page.
```
<div id="watermark">
<p>This is the test version.</p>
</div>
``` |
68,572 | <p>I have a question that I may be over thinking at this point but here goes...</p>
<p>I have 2 classes Users and Groups. Users and groups have a many to many relationship and I was thinking that the join table group_users I wanted to have an IsAuthorized property (because some groups are private -- users will need authorization). </p>
<p><strong>Would you recommend creating a class for the join table as well as the User and Groups table?</strong> Currently my classes look like this.</p>
<pre><code>public class Groups
{
public Groups()
{
members = new List<Person>();
}
...
public virtual IList<Person> members { get; set; }
}
public class User
{
public User()
{
groups = new Groups()
}
...
public virtual IList<Groups> groups{ get; set; }
}
</code></pre>
<p>My mapping is like the following in both classes (I'm only showing the one in the users mapping but they are very similar):</p>
<pre><code>HasManyToMany<Groups>(x => x.Groups)
.WithTableName("GroupMembers")
.WithParentKeyColumn("UserID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
</code></pre>
<p><strong>Should I write a class for the join table that looks like this?</strong></p>
<pre><code>public class GroupMembers
{
public virtual string GroupID { get; set; }
public virtual string PersonID { get; set; }
public virtual bool WaitingForAccept { get; set; }
}
</code></pre>
<p>I would really like to be able to adjust the group membership status and I guess I'm trying to think of the best way to go about this. </p>
| [
{
"answer_id": 68591,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>You could make an image with the watermark and then set the image as the background via css.</p>\n\n<p>For example:</p>\n\n<pre><code><style type=\"text/css\">\n.watermark{background:url(urltoimage.png);}\n</style>\n<div class=\"watermark\">\n<p>this is some text with the watermark as the background.</p>\n</div>\n</code></pre>\n\n<p>That should work.</p>\n"
},
{
"answer_id": 73352,
"author": "Doug Kavendek",
"author_id": 9330,
"author_profile": "https://Stackoverflow.com/users/9330",
"pm_score": 3,
"selected": false,
"text": "<p>As suggested, a png background could work, or even just an absolutely positioned png that sizes to fit the page, but you are asking in a comment about what would be a good tool to create one -- if you want to go with free, try <a href=\"http://www.gimp.org/\" rel=\"noreferrer\">GIMP</a>. Create a canvas with a transparent background, add some text, rotate it and resize as you'd like, and then reduce the layer's opacity to taste.</p>\n\n<p>If you'd want it to cover the whole page, make a div with the class 'watermark' and define its style as something like:</p>\n\n<pre>\n.watermark\n{\n background-image: url(image.png);\n background-position: center center;\n background-size: 100%; /* CSS3 only, but not really necessary if you make a large enough image */\n position: absolute;\n width: 100%;\n height: 100%;\n margin: 0;\n z-index: 10;\n}\n</pre>\n\n<p>If you really want the image to stretch to fit, you can go a little further and add an image into that div, and define its style to fit (width/height:100%;).</p>\n\n<p>Of course, this comes with a pretty important caveat: IE6 and some old browsers might not know what to do with transparent pngs. Having a giant, non-transparent image covering your site would <em>certainly</em> not do. But there are <a href=\"http://bjorkoy.com/past/2007/4/8/the_easiest_way_to_png/\" rel=\"noreferrer\">some hacks</a> to get around this, luckily, which you'll most likely want to do if you do use a transparent png.</p>\n"
},
{
"answer_id": 75339,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you add \"background-attachment: fixed\" to the css in kavendek's suggestion above, you can \"pin\" the background image to the specified location in the window. That way, the watermark will always remain visible no matter where the user scrolls on the page. </p>\n\n<p>Personally, I find fixed background images to be visually annoying, but I've heard site-owners say they love knowing that their logo or copyright notice (rendered as an image, presumably) is always right under the user's nose.</p>\n"
},
{
"answer_id": 2486786,
"author": "user136776",
"author_id": 136776,
"author_profile": "https://Stackoverflow.com/users/136776",
"pm_score": 5,
"selected": false,
"text": "<pre><code><style type=\"text/css\">\n#watermark {\n color: #d0d0d0;\n font-size: 200pt;\n -webkit-transform: rotate(-45deg);\n -moz-transform: rotate(-45deg);\n position: absolute;\n width: 100%;\n height: 100%;\n margin: 0;\n z-index: -1;\n left:-100px;\n top:-200px;\n}\n</style>\n</code></pre>\n\n<p>This lets you use just text as the watermark - good for dev/test versions of a web page.</p>\n\n<pre><code><div id=\"watermark\">\n<p>This is the test version.</p>\n</div>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
]
| I have a question that I may be over thinking at this point but here goes...
I have 2 classes Users and Groups. Users and groups have a many to many relationship and I was thinking that the join table group\_users I wanted to have an IsAuthorized property (because some groups are private -- users will need authorization).
**Would you recommend creating a class for the join table as well as the User and Groups table?** Currently my classes look like this.
```
public class Groups
{
public Groups()
{
members = new List<Person>();
}
...
public virtual IList<Person> members { get; set; }
}
public class User
{
public User()
{
groups = new Groups()
}
...
public virtual IList<Groups> groups{ get; set; }
}
```
My mapping is like the following in both classes (I'm only showing the one in the users mapping but they are very similar):
```
HasManyToMany<Groups>(x => x.Groups)
.WithTableName("GroupMembers")
.WithParentKeyColumn("UserID")
.WithChildKeyColumn("GroupID")
.Cascade.SaveUpdate();
```
**Should I write a class for the join table that looks like this?**
```
public class GroupMembers
{
public virtual string GroupID { get; set; }
public virtual string PersonID { get; set; }
public virtual bool WaitingForAccept { get; set; }
}
```
I would really like to be able to adjust the group membership status and I guess I'm trying to think of the best way to go about this. | ```
<style type="text/css">
#watermark {
color: #d0d0d0;
font-size: 200pt;
-webkit-transform: rotate(-45deg);
-moz-transform: rotate(-45deg);
position: absolute;
width: 100%;
height: 100%;
margin: 0;
z-index: -1;
left:-100px;
top:-200px;
}
</style>
```
This lets you use just text as the watermark - good for dev/test versions of a web page.
```
<div id="watermark">
<p>This is the test version.</p>
</div>
``` |
68,578 | <p>Is there a way to fall through multiple case statements without stating <code>case value:</code> repeatedly?</p>
<p>I know this works:</p>
<pre><code>switch (value)
{
case 1:
case 2:
case 3:
// Do some stuff
break;
case 4:
case 5:
case 6:
// Do some different stuff
break;
default:
// Default stuff
break;
}
</code></pre>
<p>but I'd like to do something like this:</p>
<pre><code>switch (value)
{
case 1,2,3:
// Do something
break;
case 4,5,6:
// Do something
break;
default:
// Do the Default
break;
}
</code></pre>
<p>Is this syntax I'm thinking of from a different language, or am I missing something?</p>
| [
{
"answer_id": 68611,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 10,
"selected": true,
"text": "<p>There is no syntax in C++ nor C# for the second method you mentioned. </p>\n\n<p>There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements.</p>\n"
},
{
"answer_id": 68620,
"author": "Neal",
"author_id": 7071,
"author_profile": "https://Stackoverflow.com/users/7071",
"pm_score": 6,
"selected": false,
"text": "<p>This syntax is from the Visual Basic <a href=\"https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/select-case-statement#Anchor_3\" rel=\"nofollow noreferrer\">Select...Case Statement</a>:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Dim number As Integer = 8\nSelect Case number\n Case 1 To 5\n Debug.WriteLine("Between 1 and 5, inclusive")\n ' The following is the only Case clause that evaluates to True.\n Case 6, 7, 8\n Debug.WriteLine("Between 6 and 8, inclusive")\n Case Is < 1\n Debug.WriteLine("Equal to 9 or 10")\n Case Else\n Debug.WriteLine("Not between 1 and 10, inclusive")\nEnd Select\n</code></pre>\n<p>You cannot use this syntax in C#. Instead, you must use the syntax from your first example.</p>\n"
},
{
"answer_id": 68829,
"author": "Cyber Oliveira",
"author_id": 9793,
"author_profile": "https://Stackoverflow.com/users/9793",
"pm_score": 3,
"selected": false,
"text": "<p>One lesser known facet of <strong>switch</strong> in C# is that it relies on the <strong>operator=</strong> and since it can be overriden you could have something like this:</p>\n\n<pre><code>\nstring s = foo();\n\nswitch (s) {\n case \"abc\": /*...*/ break;\n case \"def\": /*...*/ break;\n}\n</code></pre>\n"
},
{
"answer_id": 69047,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 3,
"selected": false,
"text": "<p>gcc implements an extension to the C language to support sequential ranges:</p>\n\n<pre><code>switch (value)\n{\n case 1...3:\n //Do Something\n break;\n case 4...6:\n //Do Something\n break;\n default:\n //Do the Default\n break;\n}\n</code></pre>\n\n<p><B>Edit</B>: Just noticed the C# tag on the question, so presumably a gcc answer doesn't help.</p>\n"
},
{
"answer_id": 69106,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 5,
"selected": false,
"text": "<p>You can leave out the newline which gives you:</p>\n\n<pre><code>case 1: case 2: case 3:\n break;\n</code></pre>\n\n<p>but I consider that bad style.</p>\n"
},
{
"answer_id": 69173,
"author": "Dr8k",
"author_id": 6014,
"author_profile": "https://Stackoverflow.com/users/6014",
"pm_score": 3,
"selected": false,
"text": "<p>Another option would be to use a routine. If cases 1-3 all execute the same logic then wrap that logic in a routine and call it for each case. I know this doesn't actually get rid of the case statements, but it does implement good style and keep maintenance to a minimum.....</p>\n\n<p>[Edit] Added alternate implementation to match original question...[/Edit]</p>\n\n<pre><code>switch (x)\n{\n case 1:\n DoSomething();\n break;\n case 2:\n DoSomething();\n break;\n case 3:\n DoSomething();\n break;\n ...\n}\n\nprivate void DoSomething()\n{\n ...\n}\n</code></pre>\n\n<p><strong>Alt</strong></p>\n\n<pre><code>switch (x)\n{\n case 1:\n case 2:\n case 3:\n DoSomething();\n break;\n ...\n}\n\nprivate void DoSomething()\n{\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 71023,
"author": "Luca Molteni",
"author_id": 4206,
"author_profile": "https://Stackoverflow.com/users/4206",
"pm_score": 4,
"selected": false,
"text": "<p>.NET Framework 3.5 has got ranges:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx\" rel=\"noreferrer\">Enumerable.Range from MSDN</a></p>\n\n<p>you can use it with \"contains\" and the IF statement, since like someone said the SWITCH statement uses the \"==\" operator.</p>\n\n<p>Here an example:</p>\n\n<pre><code>int c = 2;\nif(Enumerable.Range(0,10).Contains(c))\n DoThing();\nelse if(Enumerable.Range(11,20).Contains(c))\n DoAnotherThing();\n</code></pre>\n\n<p>But I think we can have more fun: since you won't need the return values and this action doesn't take parameters, you can easily use actions!</p>\n\n<pre><code>public static void MySwitchWithEnumerable(int switchcase, int startNumber, int endNumber, Action action)\n{\n if(Enumerable.Range(startNumber, endNumber).Contains(switchcase))\n action();\n}\n</code></pre>\n\n<p>The old example with this new method:</p>\n\n<pre><code>MySwitchWithEnumerable(c, 0, 10, DoThing);\nMySwitchWithEnumerable(c, 10, 20, DoAnotherThing);\n</code></pre>\n\n<p>Since you are passing actions, not values, you should omit the parenthesis, it's very important. If you need function with arguments, just change the type of <code>Action</code> to <code>Action<ParameterType></code>. If you need return values, use <code>Func<ParameterType, ReturnType></code>.</p>\n\n<p>In C# 3.0 there is no easy <a href=\"http://www.haskell.org/haskellwiki/Partial_application\" rel=\"noreferrer\">Partial Application</a> to encapsulate the fact the the case parameter is the same, but you create a little helper method (a bit verbose, tho).</p>\n\n<pre><code>public static void MySwitchWithEnumerable(int startNumber, int endNumber, Action action){ \n MySwitchWithEnumerable(3, startNumber, endNumber, action); \n}\n</code></pre>\n\n<p>Here an example of how new functional imported statement are IMHO more powerful and elegant than the old imperative one.</p>\n"
},
{
"answer_id": 3382204,
"author": "Carlos Quintanilla",
"author_id": 407944,
"author_profile": "https://Stackoverflow.com/users/407944",
"pm_score": 10,
"selected": false,
"text": "<p>I guess this has been already answered. However, I think that you can still mix both options in a syntactically better way by doing:</p>\n\n<pre><code>switch (value)\n{\n case 1: case 2: case 3: \n // Do Something\n break;\n case 4: case 5: case 6: \n // Do Something\n break;\n default:\n // Do Something\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 6637962,
"author": "scone",
"author_id": 421329,
"author_profile": "https://Stackoverflow.com/users/421329",
"pm_score": -1,
"selected": false,
"text": "<p>For this, you would use a goto statement. Such as:</p>\n\n<pre><code> switch(value){\n case 1:\n goto case 3;\n case 2:\n goto case 3;\n case 3:\n DoCase123();\n //This would work too, but I'm not sure if it's slower\n case 4:\n goto case 5;\n case 5:\n goto case 6;\n case 6:\n goto case 7;\n case 7:\n DoCase4567();\n }\n</code></pre>\n"
},
{
"answer_id": 7345127,
"author": "Jiří Herník",
"author_id": 905959,
"author_profile": "https://Stackoverflow.com/users/905959",
"pm_score": 2,
"selected": false,
"text": "<p>Actually I don't like the GOTO command too, but it's in official Microsoft materials, and here are all allowed syntaxes.</p>\n<p>If the end point of the statement list of a switch section is reachable, a compile-time error occurs. This is known as the "no fall through" rule. The example</p>\n<pre><code>switch (i) {\ncase 0:\n CaseZero();\n break;\ncase 1:\n CaseOne();\n break;\ndefault:\n CaseOthers();\n break;\n}\n</code></pre>\n<p>is valid because no switch section has a reachable end point. Unlike C and C++, execution of a switch section is not permitted to "fall through" to the next switch section, and the example</p>\n<pre><code>switch (i) {\ncase 0:\n CaseZero();\ncase 1:\n CaseZeroOrOne();\ndefault:\n CaseAny();\n}\n</code></pre>\n<p>results in a compile-time error. When execution of a switch section is to be followed by execution of another switch section, an explicit goto case or goto default statement must be used:</p>\n<pre><code>switch (i) {\ncase 0:\n CaseZero();\n goto case 1;\ncase 1:\n CaseZeroOrOne();\n goto default;\ndefault:\n CaseAny();\n break;\n}\n</code></pre>\n<p>Multiple labels are permitted in a switch-section. The example</p>\n<pre><code>switch (i) {\ncase 0:\n CaseZero();\n break;\ncase 1:\n CaseOne();\n break;\ncase 2:\ndefault:\n CaseTwo();\n break;\n}\n</code></pre>\n<p>I believe in this particular case, the GOTO can be used, and it's actually the only way to fallthrough.</p>\n<p><a href=\"https://web.archive.org/web/20150110043637/http://msdn.microsoft.com/en-us/library/aa664749(v=vs.71).aspx\" rel=\"nofollow noreferrer\">Source</a></p>\n"
},
{
"answer_id": 9408179,
"author": "Darin",
"author_id": 1227621,
"author_profile": "https://Stackoverflow.com/users/1227621",
"pm_score": 2,
"selected": false,
"text": "<p>An awful lot of work seems to have been put into finding ways to get one of C# least used syntaxes to somehow look better or work better. Personally I find the switch statement is seldom worth using. I would strongly suggest analyzing what data you are testing and the end results you are wanting. </p>\n\n<p>Let us say for example you want to quickly test values in a known range to see if they are prime numbers. You want to avoid having your code do the wasteful calculations and you can find a list of primes in the range you want online. You could use a massive switch statement to compare each value to known prime numbers. </p>\n\n<p>Or you could just create an array map of primes and get immediate results:</p>\n\n<pre><code> bool[] Primes = new bool[] {\n false, false, true, true, false, true, false, \n true, false, false, false, true, false, true,\n false,false,false,true,false,true,false};\n private void button1_Click(object sender, EventArgs e) {\n int Value = Convert.ToInt32(textBox1.Text);\n if ((Value >= 0) && (Value < Primes.Length)) {\n bool IsPrime = Primes[Value];\n textBox2.Text = IsPrime.ToString();\n }\n }\n</code></pre>\n\n<p>Maybe you want to see if a character in a string is hexadecimal. You could use an ungly and somewhat large switch statement.</p>\n\n<p>Or you could use either regular expressions to test the char or use the IndexOf function to search for the char in a string of known hexadecimal letters:</p>\n\n<pre><code> private void textBox2_TextChanged(object sender, EventArgs e) {\n try {\n textBox1.Text = (\"0123456789ABCDEFGabcdefg\".IndexOf(textBox2.Text[0]) >= 0).ToString();\n } catch {\n }\n }\n</code></pre>\n\n<p>Let us say you want to do one of 3 different actions depending on a value that will be the range of 1 to 24. I would suggest using a set of IF statements. And if that became too complex (Or the numbers were larger such as 5 different actions depending on a value in the range of 1 to 90) then use an enum to define the actions and create an array map of the enums. The value would then be used to index into the array map and get the enum of the action you want. Then use either a small set of IF statements or a very simple switch statement to process the resulting enum value.</p>\n\n<p>Also, the nice thing about an array map that converts a range of values into actions is that it can be easily changed by code. With hard wired code you can't easily change behaviour at runtime but with an array map it is easy.</p>\n"
},
{
"answer_id": 13214755,
"author": "none",
"author_id": 1682740,
"author_profile": "https://Stackoverflow.com/users/1682740",
"pm_score": 4,
"selected": false,
"text": "<p>The code below <em>won't</em> work:</p>\n\n<pre><code>case 1 | 3 | 5:\n// Not working do something\n</code></pre>\n\n<p>The only way to do this is:</p>\n\n<pre><code>case 1: case 2: case 3:\n// Do something\nbreak;\n</code></pre>\n\n<p>The code you are looking for works in Visual Basic where you easily can put in ranges... in the <code>none</code> option of the <code>switch</code> statement or <code>if else</code> blocks convenient, I'd suggest to, at very extreme point, make .dll with Visual Basic and import back to your C# project.</p>\n\n<p>Note: the switch equivalent in Visual Basic is <code>Select Case</code>.</p>\n"
},
{
"answer_id": 44848705,
"author": "Steve Gomez",
"author_id": 3180489,
"author_profile": "https://Stackoverflow.com/users/3180489",
"pm_score": 7,
"selected": false,
"text": "<p><strong>Original Answer for C# 7</strong></p>\n<p>In <strong>C# 7</strong> (available by default in Visual Studio 2017/.NET Framework 4.6.2), range-based switching is now possible with the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/switch\" rel=\"noreferrer\">switch statement</a> and would help with the OP's problem.</p>\n<p><strong>Example:</strong></p>\n<pre><code>int i = 5;\n\nswitch (i)\n{\n case int n when (n >= 7):\n Console.WriteLine($"I am 7 or above: {n}");\n break;\n\n case int n when (n >= 4 && n <= 6 ):\n Console.WriteLine($"I am between 4 and 6: {n}");\n break;\n\n case int n when (n <= 3):\n Console.WriteLine($"I am 3 or less: {n}");\n break;\n}\n\n// Output: I am between 4 and 6: 5\n</code></pre>\n<p><em>Notes:</em></p>\n<ul>\n<li>The parentheses <code>(</code> and <code>)</code> are not required in the <code>when</code> condition, but are used in this example to highlight the comparison(s).</li>\n<li><code>var</code> may also be used in lieu of <code>int</code>. For example: <code>case var n when n >= 7:</code>.</li>\n</ul>\n<hr />\n<p><strong>Updated examples for C# 9</strong></p>\n<pre><code>switch(myValue)\n{\n case <= 0:\n Console.WriteLine("Less than or equal to 0");\n break;\n case > 0 and <= 10:\n Console.WriteLine("More than 0 but less than or equal to 10");\n break;\n default:\n Console.WriteLine("More than 10");\n break;\n}\n</code></pre>\n<p><em>or</em></p>\n<pre><code>var message = myValue switch\n{\n <= 0 => "Less than or equal to 0",\n > 0 and <= 10 => "More than 0 but less than or equal to 10",\n _ => "More than 10"\n};\nConsole.WriteLine(message);\n</code></pre>\n"
},
{
"answer_id": 49560460,
"author": "Maxter",
"author_id": 9448877,
"author_profile": "https://Stackoverflow.com/users/9448877",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a very big amount of strings (or any other type) case all doing the same thing, I recommend the use of a string list combined with the string.Contains property.</p>\n\n<p>So if you have a big switch statement like so:</p>\n\n<pre><code>switch (stringValue)\n{\n case \"cat\":\n case \"dog\":\n case \"string3\":\n ...\n case \"+1000 more string\": // Too many string to write a case for all!\n // Do something;\n case \"a lonely case\"\n // Do something else;\n .\n .\n .\n}\n</code></pre>\n\n<p>You might want to replace it with an <code>if</code> statement like this:</p>\n\n<pre><code>// Define all the similar \"case\" string in a List\nList<string> listString = new List<string>(){ \"cat\", \"dog\", \"string3\", \"+1000 more string\"};\n// Use string.Contains to find what you are looking for\nif (listString.Contains(stringValue))\n{\n // Do something;\n}\nelse\n{\n // Then go back to a switch statement inside the else for the remaining cases if you really need to\n}\n</code></pre>\n\n<p>This scale well for any number of string cases.</p>\n"
},
{
"answer_id": 53951944,
"author": "Carter Medlin",
"author_id": 324479,
"author_profile": "https://Stackoverflow.com/users/324479",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the complete C# 7 solution...</p>\n\n<pre><code>switch (value)\n{\n case var s when new[] { 1,2,3 }.Contains(s):\n // Do something\n break;\n case var s when new[] { 4,5,6 }.Contains(s):\n // Do something\n break;\n default:\n // Do the default\n break;\n}\n</code></pre>\n\n<p>It works with strings too...</p>\n\n<pre><code>switch (mystring)\n{\n case var s when new[] { \"Alpha\",\"Beta\",\"Gamma\" }.Contains(s):\n // Do something\n break;\n...\n}\n</code></pre>\n"
},
{
"answer_id": 56861502,
"author": "JeffS",
"author_id": 935140,
"author_profile": "https://Stackoverflow.com/users/935140",
"pm_score": 1,
"selected": false,
"text": "<p>Just to add to the conversation, using .NET 4.6.2 I was also able to do the following.\nI tested the code and it did work for me.</p>\n\n<p>You can also do multiple \"OR\" statements, like below:</p>\n\n<pre><code> switch (value)\n {\n case string a when a.Contains(\"text1\"):\n // Do Something\n break;\n case string b when b.Contains(\"text3\") || b.Contains(\"text4\") || b.Contains(\"text5\"):\n // Do Something else\n break;\n default:\n // Or do this by default\n break;\n }\n</code></pre>\n\n<p>You can also check if it matches a value in an array:</p>\n\n<pre><code> string[] statuses = { \"text3\", \"text4\", \"text5\"};\n\n switch (value)\n {\n case string a when a.Contains(\"text1\"):\n // Do Something\n break;\n case string b when statuses.Contains(value): \n // Do Something else\n break;\n default:\n // Or do this by default\n break;\n }\n</code></pre>\n"
},
{
"answer_id": 57801972,
"author": "Luke T O'Brien",
"author_id": 2137483,
"author_profile": "https://Stackoverflow.com/users/2137483",
"pm_score": 3,
"selected": false,
"text": "<p>In C# 7 we now have <a href=\"https://visualstudiomagazine.com/articles/2017/02/01/pattern-matching.aspx\" rel=\"noreferrer\"><strong>Pattern Matching</strong></a> so you can do something like:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>switch (age)\n{\n case 50:\n ageBlock = \"the big five-oh\";\n break;\n case var testAge when (new List<int>()\n { 80, 81, 82, 83, 84, 85, 86, 87, 88, 89 }).Contains(testAge):\n ageBlock = \"octogenarian\";\n break;\n case var testAge when ((testAge >= 90) & (testAge <= 99)):\n ageBlock = \"nonagenarian\";\n break;\n case var testAge when (testAge >= 100):\n ageBlock = \"centenarian\";\n break;\n default:\n ageBlock = \"just old\";\n break;\n}\n</code></pre>\n"
},
{
"answer_id": 61410938,
"author": "Vikas Lalwani",
"author_id": 3559462,
"author_profile": "https://Stackoverflow.com/users/3559462",
"pm_score": 2,
"selected": false,
"text": "<p>I think this one is better in C# 7 or above.</p>\n<pre><code>switch (value)\n{\n case var s when new[] { 1,2 }.Contains(s):\n // Do something\n break;\n \n default:\n // Do the default\n break;\n }\n</code></pre>\n<p>You can also check Range in C# switch case: <a href=\"https://stackoverflow.com/questions/20147879/switch-case-can-i-use-a-range-instead-of-a-one-number\">Switch case: can I use a range instead of a one number</a></p>\n<p>OR</p>\n<pre><code> int i = 3;\n\n switch (i)\n {\n case int n when (n >= 7):\n Console.WriteLine($"I am 7 or above: {n}");\n break;\n\n case int n when (n >= 4 && n <= 6):\n Console.WriteLine($"I am between 4 and 6: {n}");\n break;\n\n case int n when (n <= 3):\n Console.WriteLine($"I am 3 or less: {n}");\n break;\n }\n</code></pre>\n<p><a href=\"https://qawithexperts.com/article/c-sharp/switch-case-multiple-conditions-in-c/500\" rel=\"nofollow noreferrer\">Switch case multiple conditions in C#</a></p>\n<p>Or if you want to understand basics of\n<a href=\"https://qawithexperts.com/tutorial/c-sharp/13/c-sharp-switch-statement\" rel=\"nofollow noreferrer\">C# switch case</a></p>\n"
},
{
"answer_id": 65864240,
"author": "Esset",
"author_id": 8055755,
"author_profile": "https://Stackoverflow.com/users/8055755",
"pm_score": 5,
"selected": false,
"text": "<p>With C#9 came the Relational Pattern Matching. This allows us to do:</p>\n<pre><code>switch (value)\n{\n case 1 or 2 or 3:\n // Do stuff\n break;\n case 4 or 5 or 6:\n // Do stuff\n break;\n default:\n // Do stuff\n break;\n}\n</code></pre>\n<p><a href=\"https://dotnetcoretutorials.com/2020/08/10/relational-pattern-matching-in-c-9/\" rel=\"noreferrer\">In deep tutorial of Relational Patter in C#9</a></p>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-9.0/patterns3\" rel=\"noreferrer\">Pattern-matching changes for C# 9.0</a></p>\n<blockquote>\n<p>Relational patterns permit the programmer to express that an input\nvalue must satisfy a relational constraint when compared to a constant\nvalue</p>\n</blockquote>\n"
},
{
"answer_id": 66138570,
"author": "AWhatley",
"author_id": 1289955,
"author_profile": "https://Stackoverflow.com/users/1289955",
"pm_score": 2,
"selected": false,
"text": "<p>You can also have conditions that are completely different</p>\n<pre><code> bool isTrue = true;\n\n switch (isTrue)\n {\n case bool ifTrue when (ex.Message.Contains("not found")):\n case bool ifTrue when (thing.number = 123):\n case bool ifTrue when (thing.othernumber != 456):\n response.respCode = 5010;\n break;\n case bool ifTrue when (otherthing.text = "something else"):\n response.respCode = 5020;\n break;\n default:\n response.respCode = 5000;\n break;\n }\n</code></pre>\n"
},
{
"answer_id": 68091589,
"author": "Misha Zaslavsky",
"author_id": 2667173,
"author_profile": "https://Stackoverflow.com/users/2667173",
"pm_score": 2,
"selected": false,
"text": "<p>In C# 8.0 you can use the new <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#switch-expressions\" rel=\"noreferrer\">switch expression</a> syntax which is ideal for your case.</p>\n<pre><code>var someOutput = value switch\n{\n >= 1 and <= 3 => <Do some stuff>,\n >= 4 and <= 6 => <Do some different stuff>,\n _ => <Default stuff>\n};\n</code></pre>\n"
},
{
"answer_id": 69088932,
"author": "Abraham",
"author_id": 14487032,
"author_profile": "https://Stackoverflow.com/users/14487032",
"pm_score": 2,
"selected": false,
"text": "<h1>A more beautiful way to handle that</h1>\n<pre><code>if ([4, 5, 6, 7].indexOf(value) > -1)\n //Do something\n</code></pre>\n<p>You can do that for multiple values with the same result</p>\n"
},
{
"answer_id": 70326316,
"author": "Osama Hussain",
"author_id": 8513973,
"author_profile": "https://Stackoverflow.com/users/8513973",
"pm_score": 0,
"selected": false,
"text": "<p>We can also use this approach to achieve Multiple cases in switch statement... You can use as many conditions as you want using this approach..</p>\n<pre><code> int i = 209;\n int a = 0;\n switch (a = (i>=1 && i<=100) ? 1 : a){ \n case 1:\n System.out.println ("The Number is Between 1 to 100 ==> " + i);\n break;\n default:\n switch (a = (i>100 && i<=200) ? 2 : a) {\n case 2:\n System.out.println("This Number is Between 101 to 200 ==> " + i);\n break;\n \n default:\n switch (a = (i>200 && i<=300) ? 3 : a) {\n case 3:\n System.out.println("This Number is Between 201 to 300 ==> " + i);\n break;\n \n default:\n // You can make as many conditions as you want;\n break;\n }\n }\n \n }\n</code></pre>\n"
},
{
"answer_id": 74102541,
"author": "Nic",
"author_id": 16414383,
"author_profile": "https://Stackoverflow.com/users/16414383",
"pm_score": 0,
"selected": false,
"text": "<p>Using new version of C# I have done in this way</p>\n<pre><code>public string GetValue(string name)\n {\n return name switch\n {\n var x when name is "test1" || name is "test2" => "finch",\n "test2" => somevalue,\n _ => name\n };\n }\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7870/"
]
| Is there a way to fall through multiple case statements without stating `case value:` repeatedly?
I know this works:
```
switch (value)
{
case 1:
case 2:
case 3:
// Do some stuff
break;
case 4:
case 5:
case 6:
// Do some different stuff
break;
default:
// Default stuff
break;
}
```
but I'd like to do something like this:
```
switch (value)
{
case 1,2,3:
// Do something
break;
case 4,5,6:
// Do something
break;
default:
// Do the Default
break;
}
```
Is this syntax I'm thinking of from a different language, or am I missing something? | There is no syntax in C++ nor C# for the second method you mentioned.
There's nothing wrong with your first method. If however you have very big ranges, just use a series of if statements. |
68,583 | <p>I have the following code snippet.</p>
<pre><code>$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";
$index = 0;
foreach($items as $key => $value)
{
echo "$index is a $key containing $value\n";
$index++;
}
</code></pre>
<p>Expected output:</p>
<pre><code>0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test
</code></pre>
<p>Is there a way to leave out the <code>$index</code> variable?</p>
| [
{
"answer_id": 68612,
"author": "Brent",
"author_id": 10680,
"author_profile": "https://Stackoverflow.com/users/10680",
"pm_score": 5,
"selected": true,
"text": "<p>Your $index variable there kind of misleading. That number isn't the index, your \"A\", \"B\", \"C\", \"D\" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd almost restructure the data:</p>\n\n<pre>\n$items[] = array(\"A\", \"Test\");\n$items[] = array(\"B\", \"Test\");\n$items[] = array(\"C\", \"Test\");\n$items[] = array(\"D\", \"Test\");\n\nforeach($items as $key => $value) {\n echo $key.' is a '.$value[0].' containing '.$value[1];\n}\n</pre>\n"
},
{
"answer_id": 68647,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this:</p>\n\n<pre><code>$items[A] = \"Test\";\n$items[B] = \"Test\";\n$items[C] = \"Test\";\n$items[D] = \"Test\";\n\nfor($i=0;$i<count($items);$i++)\n{\n list($key,$value) = each($items[$i]);\n echo \"$i $key contains $value\";\n}\n</code></pre>\n\n<p>I haven't done that before, but in theory it should work.</p>\n"
},
{
"answer_id": 68918,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<p>Be careful how you're defining your keys there. While your example works, it might not always:</p>\n\n<pre><code>$myArr = array();\n$myArr[A] = \"a\"; // \"A\" is assumed.\necho $myArr['A']; // \"a\" - this is expected.\n\ndefine ('A', 'aye');\n\n$myArr2 = array();\n$myArr2[A] = \"a\"; // A is a constant\n\necho $myArr['A']; // error, no key.\nprint_r($myArr);\n\n// Array\n// (\n// [aye] => a\n// )\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264/"
]
| I have the following code snippet.
```
$items['A'] = "Test";
$items['B'] = "Test";
$items['C'] = "Test";
$items['D'] = "Test";
$index = 0;
foreach($items as $key => $value)
{
echo "$index is a $key containing $value\n";
$index++;
}
```
Expected output:
```
0 is a A containing Test
1 is a B containing Test
2 is a C containing Test
3 is a D containing Test
```
Is there a way to leave out the `$index` variable? | Your $index variable there kind of misleading. That number isn't the index, your "A", "B", "C", "D" keys are. You can still access the data through the numbered index $index[1], but that's really not the point. If you really want to keep the numbered index, I'd almost restructure the data:
```
$items[] = array("A", "Test");
$items[] = array("B", "Test");
$items[] = array("C", "Test");
$items[] = array("D", "Test");
foreach($items as $key => $value) {
echo $key.' is a '.$value[0].' containing '.$value[1];
}
``` |
68,598 | <p>I've seen this done in Borland's <a href="https://en.wikipedia.org/wiki/Turbo_C++" rel="noreferrer">Turbo C++</a> environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for?</p>
| [
{
"answer_id": 68722,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 6,
"selected": false,
"text": "<p>In Windows Forms, set the control's AllowDrop property, then listen for DragEnter event and DragDrop event.</p>\n\n<p>When the <code>DragEnter</code> event fires, set the argument's <code>AllowedEffect</code> to something other than none (e.g. <code>e.Effect = DragDropEffects.Move</code>).</p>\n\n<p>When the <code>DragDrop</code> event fires, you'll get a list of strings. Each string is the full path to the file being dropped.</p>\n"
},
{
"answer_id": 68808,
"author": "Phil Wright",
"author_id": 6276,
"author_profile": "https://Stackoverflow.com/users/6276",
"pm_score": 4,
"selected": false,
"text": "<p>You need to be aware of a gotcha. Any class that you pass around as the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.dataobject%28v=vs.110%29.aspx\" rel=\"noreferrer\">DataObject</a> in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!</p>\n"
},
{
"answer_id": 68922,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": 3,
"selected": false,
"text": "<p>Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.</p>\n"
},
{
"answer_id": 89470,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 9,
"selected": false,
"text": "<p>Some sample code:</p>\n\n<pre><code> public partial class Form1 : Form {\n public Form1() {\n InitializeComponent();\n this.AllowDrop = true;\n this.DragEnter += new DragEventHandler(Form1_DragEnter);\n this.DragDrop += new DragEventHandler(Form1_DragDrop);\n }\n\n void Form1_DragEnter(object sender, DragEventArgs e) {\n if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;\n }\n\n void Form1_DragDrop(object sender, DragEventArgs e) {\n string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);\n foreach (string file in files) Console.WriteLine(file);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 300182,
"author": "Guge",
"author_id": 37771,
"author_profile": "https://Stackoverflow.com/users/37771",
"pm_score": 4,
"selected": false,
"text": "<p>Yet another gotcha:</p>\n\n<p>The framework code that calls the Drag-events swallow all exceptions. You might think your event code is running smoothly, while it is gushing exceptions all over the place. You can't see them because the framework steals them.</p>\n\n<p>That's why I always put a try/catch in these event handlers, just so I know if they throw any exceptions. I usually put a Debugger.Break(); in the catch part.</p>\n\n<p>Before release, after testing, if everything seems to behave, I remove or replace these with real exception handling.</p>\n"
},
{
"answer_id": 4789883,
"author": "Wayne Uroda",
"author_id": 588476,
"author_profile": "https://Stackoverflow.com/users/588476",
"pm_score": 7,
"selected": false,
"text": "<p>Be aware of windows vista/windows 7 security rights - if you are running Visual Studio as administrator, you will not be able to drag files from a non-administrator explorer window into your program when you run it from within visual studio. The drag related events will not even fire! I hope this helps somebody else out there not waste hours of their life...</p>\n"
},
{
"answer_id": 36721291,
"author": "CAD bloke",
"author_id": 492,
"author_profile": "https://Stackoverflow.com/users/492",
"pm_score": 3,
"selected": false,
"text": "<p>Here is something I used to drop files and/or folders full of files. In my case I was filtering for <code>*.dwg</code> files only and chose to include all subfolders.</p>\n\n<p><code>fileList</code> is an <code>IEnumerable</code> or similar In my case was bound to a WPF control... </p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var fileList = (IList)FileList.ItemsSource;\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/19954958/492\">https://stackoverflow.com/a/19954958/492</a> for details of that trick.</p>\n\n<p>The drop Handler ...</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> private void FileList_OnDrop(object sender, DragEventArgs e)\n {\n var dropped = ((string[])e.Data.GetData(DataFormats.FileDrop));\n var files = dropped.ToList();\n\n if (!files.Any())\n return;\n\n foreach (string drop in dropped)\n if (Directory.Exists(drop))\n files.AddRange(Directory.GetFiles(drop, \"*.dwg\", SearchOption.AllDirectories));\n\n foreach (string file in files)\n {\n if (!fileList.Contains(file) && file.ToLower().EndsWith(\".dwg\"))\n fileList.Add(file);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 48620095,
"author": "Roland",
"author_id": 1845672,
"author_profile": "https://Stackoverflow.com/users/1845672",
"pm_score": 2,
"selected": false,
"text": "<p>The solution of Judah Himango and Hans Passant is available in the Designer (I am currently using VS2015):</p>\n\n<p><a href=\"https://i.stack.imgur.com/chX8I.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/chX8I.png\" alt=\"enter image description here\"></a></p>\n\n<p><a href=\"https://i.stack.imgur.com/2R8Wx.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2R8Wx.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 61456003,
"author": "Ernest Rutherford",
"author_id": 11660685,
"author_profile": "https://Stackoverflow.com/users/11660685",
"pm_score": 0,
"selected": false,
"text": "<p>You can implement Drag&Drop in WinForms and WPF. </p>\n\n<ul>\n<li>WinForm (Drag from app window)</li>\n</ul>\n\n<p>You should add mousemove event:</p>\n\n<pre><code>private void YourElementControl_MouseMove(object sender, MouseEventArgs e)\n\n {\n ...\n if (e.Button == MouseButtons.Left)\n {\n DoDragDrop(new DataObject(DataFormats.FileDrop, new string[] { PathToFirstFile,PathToTheNextOne }), DragDropEffects.Move);\n }\n ...\n }\n</code></pre>\n\n<ul>\n<li>WinForm (Drag to app window)</li>\n</ul>\n\n<p>You should add DragDrop event:</p>\n\n<p>private void YourElementControl_DragDrop(object sender, DragEventArgs e)</p>\n\n<pre><code> {\n ...\n foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop))\n {\n File.Copy(path, DirPath + Path.GetFileName(path));\n }\n ...\n }\n</code></pre>\n\n<p><a href=\"https://www.brainbeast.best/drag-and-drop-on-c-sharp-in-wpf-dot-net/\" rel=\"nofollow noreferrer\">Source with full code</a>.</p>\n"
},
{
"answer_id": 62944471,
"author": "Jack",
"author_id": 3646777,
"author_profile": "https://Stackoverflow.com/users/3646777",
"pm_score": 0,
"selected": false,
"text": "<p>Note that for this to work, you also need to set the dragDropEffect within _drawEnter...</p>\n<pre><code>private void Form1_DragEnter(object sender, DragEventArgs e)\n{\n Console.WriteLine("DragEnter!");\n e.Effect = DragDropEffects.Copy;\n}\n</code></pre>\n<p>Source: <a href=\"https://stackoverflow.com/questions/26628492/drag-and-drop-not-working-in-c-sharp-winforms-application\">Drag and Drop not working in C# Winforms Application</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I've seen this done in Borland's [Turbo C++](https://en.wikipedia.org/wiki/Turbo_C++) environment, but I'm not sure how to go about it for a C# application I'm working on. Are there best practices or gotchas to look out for? | Some sample code:
```
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
this.AllowDrop = true;
this.DragEnter += new DragEventHandler(Form1_DragEnter);
this.DragDrop += new DragEventHandler(Form1_DragDrop);
}
void Form1_DragEnter(object sender, DragEventArgs e) {
if (e.Data.GetDataPresent(DataFormats.FileDrop)) e.Effect = DragDropEffects.Copy;
}
void Form1_DragDrop(object sender, DragEventArgs e) {
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files) Console.WriteLine(file);
}
}
``` |
68,610 | <p>I am having problems getting text within a table to appear centered in IE. </p>
<p>In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7. </p>
<p>I'm using:</p>
<pre class="lang-css prettyprint-override"><code>h2 {
font: 300 12px "Helvetica", serif;
text-align: center;
text-transform: uppercase;
}
</code></pre>
<p>I've also tried adding <code>margin-left:auto;</code>, <code>margin-right:auto</code> and <code>position:relative;</code> </p>
<p>to no avail. </p>
| [
{
"answer_id": 68621,
"author": "Mike Becatti",
"author_id": 6617,
"author_profile": "https://Stackoverflow.com/users/6617",
"pm_score": 3,
"selected": true,
"text": "<p>The table cell needs the text-align: center.</p>\n"
},
{
"answer_id": 68637,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>text-align: center</code> should be sufficient, since you're centering the text inside a block element (h2) - adjusting the margins will change the position of the block, not the text.</p>\n\n<p>I wonder if it's just that IE is having a dummy-spit at that <code>font</code> declaration you've got there?</p>\n"
},
{
"answer_id": 68643,
"author": "1077",
"author_id": 10776,
"author_profile": "https://Stackoverflow.com/users/10776",
"pm_score": 0,
"selected": false,
"text": "<p>Use text-align:center in the div/td that surrounds the h2.</p>\n\n<pre><code><table style = \"width:400px;border:solid 1px;\">\n <tr>\n <td style = \"text-align:center;\"><h2>hi</h2></td>\n </tr>\n</table>\n</code></pre>\n\n<p>edit: wow, stackoverflow's community is pretty fast!</p>\n"
},
{
"answer_id": 68678,
"author": "Alex Achinfiev",
"author_id": 10785,
"author_profile": "https://Stackoverflow.com/users/10785",
"pm_score": 3,
"selected": false,
"text": "<p>CSS text-align property should be declared on the parent element and not the element you are trying to center. IE uses text-align: center property to center text. Firefox uses margin: 0 auto and it has to be declared on the element you are trying to center.</p>\n\n<pre><code><div style=\"text-align: center\">\n <h2 style=\"margin: 0 auto\">Some text</h2>\n</div>\n</code></pre>\n"
},
{
"answer_id": 68709,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>Might be a typo, but you are missing a semicolon here:</p>\n\n<pre><code>margin-left:auto; margin-right:auto position:relative;\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>margin-left:auto; margin-right:auto; position:relative;\n</code></pre>\n\n<p>If that doesn't work, make sure the element you are trying to center the text on has some width. Try setting the width to 100% and see if anything changes.</p>\n"
},
{
"answer_id": 46956006,
"author": "Rahi.Shah",
"author_id": 7394106,
"author_profile": "https://Stackoverflow.com/users/7394106",
"pm_score": 0,
"selected": false,
"text": "<p>If you can/want to use flexbox, you can use the following as well.</p>\n\n<pre><code>display: flex;\njustify-content: center;\nalign-items:center\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68610",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10761/"
]
| I am having problems getting text within a table to appear centered in IE.
In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7.
I'm using:
```css
h2 {
font: 300 12px "Helvetica", serif;
text-align: center;
text-transform: uppercase;
}
```
I've also tried adding `margin-left:auto;`, `margin-right:auto` and `position:relative;`
to no avail. | The table cell needs the text-align: center. |
68,624 | <p>I would like to parse a string such as <code>p1=6&p2=7&p3=8</code> into a <code>NameValueCollection</code>.</p>
<p>What is the most elegant way of doing this when you don't have access to the <code>Page.Request</code> object?</p>
| [
{
"answer_id": 68639,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 0,
"selected": false,
"text": "<p>Hit up Request.QueryString.Keys for a NameValueCollection of all query string parameters.</p>\n"
},
{
"answer_id": 68644,
"author": "Mike Becatti",
"author_id": 6617,
"author_profile": "https://Stackoverflow.com/users/6617",
"pm_score": 1,
"selected": false,
"text": "<p>Just access Request.QueryString. AllKeys mentioned as another answer just gets you an array of keys. </p>\n"
},
{
"answer_id": 68648,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 10,
"selected": true,
"text": "<p>There's a built-in .NET utility for this: <a href=\"http://msdn.microsoft.com/en-us/library/ms150046.aspx\" rel=\"noreferrer\">HttpUtility.ParseQueryString</a></p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// C#\nNameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);\n</code></pre>\n\n<pre class=\"lang-vb prettyprint-override\"><code>' VB.NET\nDim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)\n</code></pre>\n\n<p>You may need to replace <code>querystring</code> with <code>new Uri(fullUrl).Query</code>.</p>\n"
},
{
"answer_id": 68733,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 2,
"selected": false,
"text": "<pre><code> private void button1_Click( object sender, EventArgs e )\n {\n string s = @\"p1=6&p2=7&p3=8\";\n NameValueCollection nvc = new NameValueCollection();\n\n foreach ( string vp in Regex.Split( s, \"&\" ) )\n {\n string[] singlePair = Regex.Split( vp, \"=\" );\n if ( singlePair.Length == 2 )\n {\n nvc.Add( singlePair[ 0 ], singlePair[ 1 ] ); \n } \n }\n }\n</code></pre>\n"
},
{
"answer_id": 68803,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 6,
"selected": false,
"text": "<p>HttpUtility.ParseQueryString will work as long as you are in a web app or don't mind including a dependency on System.Web. Another way to do this is:</p>\n\n<pre><code>NameValueCollection queryParameters = new NameValueCollection();\nstring[] querySegments = queryString.Split('&');\nforeach(string segment in querySegments)\n{\n string[] parts = segment.Split('=');\n if (parts.Length > 0)\n {\n string key = parts[0].Trim(new char[] { '?', ' ' });\n string val = parts[1].Trim();\n\n queryParameters.Add(key, val);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1322960,
"author": "densom",
"author_id": 158581,
"author_profile": "https://Stackoverflow.com/users/158581",
"pm_score": 4,
"selected": false,
"text": "<p>I wanted to remove the dependency on System.Web so that I could parse the query string of a ClickOnce deployment, while having the prerequisites limited to the \"Client-only Framework Subset\".</p>\n\n<p>I liked rp's answer. I added some additional logic.</p>\n\n<pre><code>public static NameValueCollection ParseQueryString(string s)\n {\n NameValueCollection nvc = new NameValueCollection();\n\n // remove anything other than query string from url\n if(s.Contains(\"?\"))\n {\n s = s.Substring(s.IndexOf('?') + 1);\n }\n\n foreach (string vp in Regex.Split(s, \"&\"))\n {\n string[] singlePair = Regex.Split(vp, \"=\");\n if (singlePair.Length == 2)\n {\n nvc.Add(singlePair[0], singlePair[1]);\n }\n else\n {\n // only one key with no value specified in query string\n nvc.Add(singlePair[0], string.Empty);\n }\n }\n\n return nvc;\n }\n</code></pre>\n"
},
{
"answer_id": 8169365,
"author": "alex1kirch",
"author_id": 991442,
"author_profile": "https://Stackoverflow.com/users/991442",
"pm_score": 1,
"selected": false,
"text": "<p><code>HttpUtility.ParseQueryString(Request.Url.Query)</code> return is <code>HttpValueCollection</code> (internal class). It inherits from <code>NameValueCollection</code>.</p>\n\n<pre><code> var qs = HttpUtility.ParseQueryString(Request.Url.Query);\n qs.Remove(\"foo\"); \n\n string url = \"~/Default.aspx\"; \n if (qs.Count > 0)\n url = url + \"?\" + qs.ToString();\n\n Response.Redirect(url); \n</code></pre>\n"
},
{
"answer_id": 16565615,
"author": "Josh Brown",
"author_id": 341536,
"author_profile": "https://Stackoverflow.com/users/341536",
"pm_score": 3,
"selected": false,
"text": "<p>I needed a function that is a little more versatile than what was provided already when working with OLSC queries.</p>\n\n<ul>\n<li>Values may contain multiple equal signs</li>\n<li>Decode encoded characters in both name and value</li>\n<li>Capable of running on Client Framework</li>\n<li>Capable of running on Mobile Framework.</li>\n</ul>\n\n<p>Here is my solution:</p>\n\n<pre><code>Public Shared Function ParseQueryString(ByVal uri As Uri) As System.Collections.Specialized.NameValueCollection\n Dim result = New System.Collections.Specialized.NameValueCollection(4)\n Dim query = uri.Query\n If Not String.IsNullOrEmpty(query) Then\n Dim pairs = query.Substring(1).Split(\"&\"c)\n For Each pair In pairs\n Dim parts = pair.Split({\"=\"c}, 2)\n\n Dim name = System.Uri.UnescapeDataString(parts(0))\n Dim value = If(parts.Length = 1, String.Empty,\n System.Uri.UnescapeDataString(parts(1)))\n\n result.Add(name, value)\n Next\n End If\n Return result\nEnd Function\n</code></pre>\n\n<p>It may not be a bad idea to tack <code><Extension()></code> on that too to add the capability to Uri itself.</p>\n"
},
{
"answer_id": 19893289,
"author": "Farhawd",
"author_id": 998276,
"author_profile": "https://Stackoverflow.com/users/998276",
"pm_score": -1,
"selected": false,
"text": "<p>This is my code, I think it's very useful: </p>\n\n<pre><code>public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null )\n{\n System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString);\n if (ItemToRemoveOrInsert != null)\n {\n filtered.Remove(ItemToRemoveOrInsert);\n if (!string.IsNullOrWhiteSpace(InsertValue))\n {\n filtered.Add(ItemToRemoveOrInsert, InsertValue);\n }\n }\n\n string StrQr = string.Join(\"&\", filtered.AllKeys.Select(key => key + \"=\" + filtered[key]).ToArray());\n if (!string.IsNullOrWhiteSpace(StrQr)){\n StrQr=\"?\" + StrQr;\n }\n\n return StrQr;\n}\n</code></pre>\n"
},
{
"answer_id": 21309603,
"author": "Tiele Declercq",
"author_id": 1683154,
"author_profile": "https://Stackoverflow.com/users/1683154",
"pm_score": 1,
"selected": false,
"text": "<p>Since everyone seems to be pasting his solution.. here's mine :-)\nI needed this from within a class library without <code>System.Web</code> to fetch id parameters from stored hyperlinks.</p>\n\n<p>Thought I'd share because I find this solution faster and better looking.</p>\n\n<pre><code>public static class Statics\n public static Dictionary<string, string> QueryParse(string url)\n {\n Dictionary<string, string> qDict = new Dictionary<string, string>();\n foreach (string qPair in url.Substring(url.IndexOf('?') + 1).Split('&'))\n {\n string[] qVal = qPair.Split('=');\n qDict.Add(qVal[0], Uri.UnescapeDataString(qVal[1]));\n }\n return qDict;\n }\n\n public static string QueryGet(string url, string param)\n {\n var qDict = QueryParse(url);\n return qDict[param];\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>Statics.QueryGet(url, \"id\")\n</code></pre>\n"
},
{
"answer_id": 22167748,
"author": "James Skimming",
"author_id": 495964,
"author_profile": "https://Stackoverflow.com/users/495964",
"pm_score": 5,
"selected": false,
"text": "<p>A lot of the answers are providing custom examples because of the accepted answer's dependency on <a href=\"http://msdn.microsoft.com/en-us/library/system.web.aspx\" rel=\"noreferrer\">System.Web</a>. From the <a href=\"http://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client\" rel=\"noreferrer\">Microsoft.AspNet.WebApi.Client</a> NuGet package there is a <a href=\"http://msdn.microsoft.com/en-us/library/system.net.http.uriextensions.parsequerystring.aspx\" rel=\"noreferrer\">UriExtensions.ParseQueryString</a>, method that can also be used:</p>\n\n<pre><code>var uri = new Uri(\"https://stackoverflow.com/a/22167748?p1=6&p2=7&p3=8\");\nNameValueCollection query = uri.ParseQueryString();\n</code></pre>\n\n<p>So if you want to avoid the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.aspx\" rel=\"noreferrer\">System.Web</a> dependency and don't want to roll your own, this is a good option.</p>\n"
},
{
"answer_id": 24921357,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 2,
"selected": false,
"text": "<p>I just realized that <a href=\"https://www.nuget.org/packages/Microsoft.AspNet.WebApi.Client/\" rel=\"nofollow\">Web API Client</a> has a <code>ParseQueryString</code> extension method that works on a <code>Uri</code> and returns a <code>HttpValueCollection</code>:</p>\n\n<pre><code>var parameters = uri.ParseQueryString();\nstring foo = parameters[\"foo\"];\n</code></pre>\n"
},
{
"answer_id": 28693490,
"author": "mirko cro 1234",
"author_id": 3386904,
"author_profile": "https://Stackoverflow.com/users/3386904",
"pm_score": 0,
"selected": false,
"text": "<p>To get all Querystring values try this:</p>\n\n<pre><code> Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)\n\nDim sb As New StringBuilder(\"<br />\")\nFor Each s As String In qscoll.AllKeys\n\n Response.Write(s & \" - \" & qscoll(s) & \"<br />\")\n\nNext s\n</code></pre>\n"
},
{
"answer_id": 33224447,
"author": "Jerod Venema",
"author_id": 25330,
"author_profile": "https://Stackoverflow.com/users/25330",
"pm_score": 3,
"selected": false,
"text": "<p>To do this without <code>System.Web</code>, without writing it yourself, and without additional NuGet packages:</p>\n\n<ol>\n<li>Add a reference to <code>System.Net.Http.Formatting</code></li>\n<li>Add <code>using System.Net.Http;</code></li>\n<li><p>Use this code:</p>\n\n<pre><code>new Uri(uri).ParseQueryString()\n</code></pre></li>\n</ol>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/system.net.http.uriextensions(v=vs.118).aspx</a></p>\n"
},
{
"answer_id": 34920103,
"author": "Hamit YILDIRIM",
"author_id": 914284,
"author_profile": "https://Stackoverflow.com/users/914284",
"pm_score": 0,
"selected": false,
"text": "<pre><code> var q = Request.QueryString;\n NameValueCollection qscoll = HttpUtility.ParseQueryString(q.ToString());\n</code></pre>\n"
},
{
"answer_id": 38171014,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<h1>If you don't want the System.Web dependency, just paste this source code from HttpUtility class.</h1>\n\n<p>I just whipped this together from the source code of <a href=\"https://github.com/mono/mono/tree/master/mcs/class/System.Web\" rel=\"nofollow\">Mono</a>. It contains the HttpUtility and all it's dependencies (like IHtmlString, Helpers, HttpEncoder, HttpQSCollection).</p>\n\n<p><em>Then</em> use <code>HttpUtility.ParseQueryString</code>.</p>\n\n<p><a href=\"https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c\" rel=\"nofollow\">https://gist.github.com/bjorn-ali-goransson/b04a7c44808bb2de8cca3fc9a3762f9c</a></p>\n"
},
{
"answer_id": 39055664,
"author": "elgoya",
"author_id": 1828356,
"author_profile": "https://Stackoverflow.com/users/1828356",
"pm_score": -1,
"selected": false,
"text": "<p>I translate to C# version of josh-brown in VB</p>\n\n<pre><code>private System.Collections.Specialized.NameValueCollection ParseQueryString(Uri uri)\n{\n var result = new System.Collections.Specialized.NameValueCollection(4);\n var query = uri.Query;\n if (!String.IsNullOrEmpty(query))\n {\n var pairs = query.Substring(1).Split(\"&\".ToCharArray());\n foreach (var pair in pairs)\n {\n var parts = pair.Split(\"=\".ToCharArray(), 2);\n var name = System.Uri.UnescapeDataString(parts[0]);\n var value = (parts.Length == 1) ? String.Empty : System.Uri.UnescapeDataString(parts[1]);\n result.Add(name, value);\n }\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 45716527,
"author": "Amadeus Sánchez",
"author_id": 1698964,
"author_profile": "https://Stackoverflow.com/users/1698964",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to avoid the dependency on System.Web that is required to use <a href=\"https://msdn.microsoft.com/en-us/library/ms150046.aspx\" rel=\"nofollow noreferrer\">HttpUtility.ParseQueryString</a>, you could use the <code>Uri</code> extension method <code>ParseQueryString</code> found in <code>System.Net.Http</code>.</p>\n\n<p>Make sure to add a reference (if you haven't already) to <code>System.Net.Http</code> in your project.</p>\n\n<p>Note that you have to convert the response body to a valid <code>Uri</code> so that <code>ParseQueryString</code> (in <code>System.Net.Http</code>)works.</p>\n\n<pre><code>string body = \"value1=randomvalue1&value2=randomValue2\";\n\n// \"http://localhost/query?\" is added to the string \"body\" in order to create a valid Uri.\nstring urlBody = \"http://localhost/query?\" + body;\nNameValueCollection coll = new Uri(urlBody).ParseQueryString();\n</code></pre>\n"
},
{
"answer_id": 61217955,
"author": "Nahom Haile",
"author_id": 12178449,
"author_profile": "https://Stackoverflow.com/users/12178449",
"pm_score": -1,
"selected": false,
"text": "<pre><code>let search = window.location.search;\n\nconsole.log(search);\n\nlet qString = search.substring(1);\n\nwhile(qString.indexOf(\"+\") !== -1)\n\n qString = qString.replace(\"+\", \"\");\n\nlet qArray = qString.split(\"&\");\n\nlet values = [];\n\nfor(let i = 0; i < qArray.length; i++){\n let pos = qArray[i].search(\"=\");\n let keyVal = qArray[i].substring(0, pos);\n let dataVal = qArray[i].substring(pos + 1);\n dataVal = decodeURIComponent(dataVal);\n values[keyVal] = dataVal;\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68624",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4998/"
]
| I would like to parse a string such as `p1=6&p2=7&p3=8` into a `NameValueCollection`.
What is the most elegant way of doing this when you don't have access to the `Page.Request` object? | There's a built-in .NET utility for this: [HttpUtility.ParseQueryString](http://msdn.microsoft.com/en-us/library/ms150046.aspx)
```cs
// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
```
```vb
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
```
You may need to replace `querystring` with `new Uri(fullUrl).Query`. |
68,630 | <p>Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? </p>
| [
{
"answer_id": 68638,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 2,
"selected": false,
"text": "<p>Tuples should be slightly more efficient and because of that, faster, than lists because they are immutable.</p>\n"
},
{
"answer_id": 68712,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 8,
"selected": false,
"text": "<p>In general, you might expect tuples to be slightly faster. However you should definitely test your specific case (if the difference might impact the performance of your program -- remember \"premature optimization is the root of all evil\").</p>\n\n<p>Python makes this very easy: <a href=\"https://docs.python.org/2/library/timeit.html\" rel=\"noreferrer\">timeit</a> is your friend.</p>\n\n<pre><code>$ python -m timeit \"x=(1,2,3,4,5,6,7,8)\"\n10000000 loops, best of 3: 0.0388 usec per loop\n\n$ python -m timeit \"x=[1,2,3,4,5,6,7,8]\"\n1000000 loops, best of 3: 0.363 usec per loop\n</code></pre>\n\n<p>and...</p>\n\n<pre><code>$ python -m timeit -s \"x=(1,2,3,4,5,6,7,8)\" \"y=x[3]\"\n10000000 loops, best of 3: 0.0938 usec per loop\n\n$ python -m timeit -s \"x=[1,2,3,4,5,6,7,8]\" \"y=x[3]\"\n10000000 loops, best of 3: 0.0649 usec per loop\n</code></pre>\n\n<p>So in this case, instantiation is almost an order of magnitude faster for the tuple, but item access is actually somewhat faster for the list! So if you're creating a few tuples and accessing them many many times, it may actually be faster to use lists instead.</p>\n\n<p>Of course if you want to <em>change</em> an item, the list will definitely be faster since you'd need to create an entire new tuple to change one item of it (since tuples are immutable).</p>\n"
},
{
"answer_id": 68817,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 9,
"selected": true,
"text": "<p>The <a href=\"https://docs.python.org/3/library/dis.html\" rel=\"noreferrer\"><code>dis</code></a> module disassembles the byte code for a function and is useful to see the difference between tuples and lists.</p>\n\n<p>In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list.</p>\n\n<pre><code>>>> def a():\n... x=[1,2,3,4,5]\n... y=x[2]\n...\n>>> def b():\n... x=(1,2,3,4,5)\n... y=x[2]\n...\n>>> import dis\n>>> dis.dis(a)\n 2 0 LOAD_CONST 1 (1)\n 3 LOAD_CONST 2 (2)\n 6 LOAD_CONST 3 (3)\n 9 LOAD_CONST 4 (4)\n 12 LOAD_CONST 5 (5)\n 15 BUILD_LIST 5\n 18 STORE_FAST 0 (x)\n\n 3 21 LOAD_FAST 0 (x)\n 24 LOAD_CONST 2 (2)\n 27 BINARY_SUBSCR\n 28 STORE_FAST 1 (y)\n 31 LOAD_CONST 0 (None)\n 34 RETURN_VALUE\n>>> dis.dis(b)\n 2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5))\n 3 STORE_FAST 0 (x)\n\n 3 6 LOAD_FAST 0 (x)\n 9 LOAD_CONST 2 (2)\n 12 BINARY_SUBSCR\n 13 STORE_FAST 1 (y)\n 16 LOAD_CONST 0 (None)\n 19 RETURN_VALUE\n</code></pre>\n"
},
{
"answer_id": 70968,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": false,
"text": "<p>Tuples, being immutable, are more memory efficient; lists, for speed efficiency, overallocate memory in order to allow appends without constant <code>realloc</code>s. So, if you want to iterate through a constant sequence of values in your code (eg <code>for direction in 'up', 'right', 'down', 'left':</code>), tuples are preferred, since such tuples are pre-calculated in compile time.</p>\n<p>Read-access speeds should be the same (they are both stored as contiguous arrays in the memory).</p>\n<p>But, <code>alist.append(item)</code> is much preferred to <code>atuple+= (item,)</code> when you deal with mutable data. Remember, tuples are intended to be treated as records without field names.</p>\n"
},
{
"answer_id": 71295,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>You should also consider the <code>array</code> module in the standard library if all the items in your list or tuple are of the same C type. It will take less memory and can be faster.</p>\n"
},
{
"answer_id": 22140115,
"author": "Raymond Hettinger",
"author_id": 424499,
"author_profile": "https://Stackoverflow.com/users/424499",
"pm_score": 8,
"selected": false,
"text": "<h2>Summary</h2>\n<p><em>Tuples tend to perform better than lists</em> in almost every category:</p>\n<ol>\n<li><p>Tuples can be <a href=\"https://en.wikipedia.org/wiki/Constant_folding\" rel=\"noreferrer\">constant folded</a>.</p>\n</li>\n<li><p>Tuples can be reused instead of copied.</p>\n</li>\n<li><p>Tuples are compact and don't over-allocate.</p>\n</li>\n<li><p>Tuples directly reference their elements.</p>\n</li>\n</ol>\n<h2>Tuples can be constant folded</h2>\n<p>Tuples of constants can be precomputed by Python's peephole optimizer or AST-optimizer. Lists, on the other hand, get built-up from scratch:</p>\n<pre><code> >>> from dis import dis\n\n >>> dis(compile("(10, 'abc')", '', 'eval'))\n 1 0 LOAD_CONST 2 ((10, 'abc'))\n 3 RETURN_VALUE \n \n >>> dis(compile("[10, 'abc']", '', 'eval'))\n 1 0 LOAD_CONST 0 (10)\n 3 LOAD_CONST 1 ('abc')\n 6 BUILD_LIST 2\n 9 RETURN_VALUE \n</code></pre>\n<h2>Tuples do not need to be copied</h2>\n<p>Running <code>tuple(some_tuple)</code> returns immediately itself. Since tuples are immutable, they do not have to be copied:</p>\n<pre><code>>>> a = (10, 20, 30)\n>>> b = tuple(a)\n>>> a is b\nTrue\n</code></pre>\n<p>In contrast, <code>list(some_list)</code> requires all the data to be copied to a new list:</p>\n<pre><code>>>> a = [10, 20, 30]\n>>> b = list(a)\n>>> a is b\nFalse\n</code></pre>\n<h2>Tuples do not over-allocate</h2>\n<p>Since a tuple's size is fixed, it can be stored more compactly than lists which need to over-allocate to make <code>append()</code> operations efficient.</p>\n<p>This gives tuples a nice space advantage:</p>\n<pre><code>>>> import sys\n>>> sys.getsizeof(tuple(iter(range(10))))\n128\n>>> sys.getsizeof(list(iter(range(10))))\n200\n</code></pre>\n<p>Here is the comment from <em>Objects/listobject.c</em> that explains what lists are doing:</p>\n<pre class=\"lang-c prettyprint-override\"><code>/* This over-allocates proportional to the list size, making room\n * for additional growth. The over-allocation is mild, but is\n * enough to give linear-time amortized behavior over a long\n * sequence of appends() in the presence of a poorly-performing\n * system realloc().\n * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...\n * Note: new_allocated won't overflow because the largest possible value\n * is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.\n */\n</code></pre>\n<h2>Tuples refer directly to their elements</h2>\n<p>References to objects are incorporated directly in a tuple object. In contrast, lists have an extra layer of indirection to an external array of pointers.</p>\n<p>This gives tuples a small speed advantage for indexed lookups and unpacking:</p>\n<pre><code>$ python3.6 -m timeit -s 'a = (10, 20, 30)' 'a[1]'\n10000000 loops, best of 3: 0.0304 usec per loop\n$ python3.6 -m timeit -s 'a = [10, 20, 30]' 'a[1]'\n10000000 loops, best of 3: 0.0309 usec per loop\n\n$ python3.6 -m timeit -s 'a = (10, 20, 30)' 'x, y, z = a'\n10000000 loops, best of 3: 0.0249 usec per loop\n$ python3.6 -m timeit -s 'a = [10, 20, 30]' 'x, y, z = a'\n10000000 loops, best of 3: 0.0251 usec per loop\n</code></pre>\n<p><a href=\"https://github.com/python/cpython/blob/54ba556c6c7d8fd5504dc142c2e773890c55a774/Include/cpython/tupleobject.h#L9\" rel=\"noreferrer\">Here</a> is how the tuple <code>(10, 20)</code> is stored:</p>\n<pre class=\"lang-c prettyprint-override\"><code> typedef struct {\n Py_ssize_t ob_refcnt;\n struct _typeobject *ob_type;\n Py_ssize_t ob_size;\n PyObject *ob_item[2]; /* store a pointer to 10 and a pointer to 20 */\n } PyTupleObject;\n</code></pre>\n<p><a href=\"https://github.com/python/cpython/blob/master/Include/listobject.h\" rel=\"noreferrer\">Here</a> is how the list <code>[10, 20]</code> is stored:</p>\n<pre class=\"lang-c prettyprint-override\"><code> PyObject arr[2]; /* store a pointer to 10 and a pointer to 20 */\n\n typedef struct {\n Py_ssize_t ob_refcnt;\n struct _typeobject *ob_type;\n Py_ssize_t ob_size;\n PyObject **ob_item = arr; /* store a pointer to the two-pointer array */\n Py_ssize_t allocated;\n } PyListObject;\n</code></pre>\n<p>Note that the tuple object incorporates the two data pointers directly while the list object has an additional layer of indirection to an external array holding the two data pointers.</p>\n"
},
{
"answer_id": 52015256,
"author": "Dev Aggarwal",
"author_id": 7061265,
"author_profile": "https://Stackoverflow.com/users/7061265",
"pm_score": 4,
"selected": false,
"text": "<p>Here is another little benchmark, just for the sake of it..</p>\n\n<pre><code>In [11]: %timeit list(range(100))\n749 ns ± 2.41 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n\nIn [12]: %timeit tuple(range(100))\n781 ns ± 3.34 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)\n</code></pre>\n\n<hr>\n\n<pre><code>In [1]: %timeit list(range(1_000))\n13.5 µs ± 466 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\nIn [2]: %timeit tuple(range(1_000))\n12.4 µs ± 182 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n</code></pre>\n\n<hr>\n\n<pre><code>In [7]: %timeit list(range(10_000))\n182 µs ± 810 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n\nIn [8]: %timeit tuple(range(10_000))\n188 µs ± 2.38 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)\n</code></pre>\n\n<hr>\n\n<pre><code>In [3]: %timeit list(range(1_00_000))\n2.76 ms ± 30.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n\nIn [4]: %timeit tuple(range(1_00_000))\n2.74 ms ± 31.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n</code></pre>\n\n<hr>\n\n<pre><code>In [10]: %timeit list(range(10_00_000))\n28.1 ms ± 266 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n\nIn [9]: %timeit tuple(range(10_00_000))\n28.5 ms ± 447 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n</code></pre>\n\n<p>Let's average these out:</p>\n\n<pre><code>In [3]: l = np.array([749 * 10 ** -9, 13.5 * 10 ** -6, 182 * 10 ** -6, 2.76 * 10 ** -3, 28.1 * 10 ** -3])\n\nIn [2]: t = np.array([781 * 10 ** -9, 12.4 * 10 ** -6, 188 * 10 ** -6, 2.74 * 10 ** -3, 28.5 * 10 ** -3])\n\nIn [11]: np.average(l)\nOut[11]: 0.0062112498000000006\n\nIn [12]: np.average(t)\nOut[12]: 0.0062882362\n\nIn [17]: np.average(t) / np.average(l) * 100\nOut[17]: 101.23946713590554\n</code></pre>\n\n<p>You can call it almost inconclusive. </p>\n\n<p>But sure, tuples took <code>101.239%</code> the time, or <code>1.239%</code> extra time to do the job compared to lists.</p>\n"
},
{
"answer_id": 53385158,
"author": "Divakar",
"author_id": 1613854,
"author_profile": "https://Stackoverflow.com/users/1613854",
"pm_score": -1,
"selected": false,
"text": "<p>The main reason for Tuple to be very efficient in reading is because it's immutable. </p>\n\n<h2>Why immutable objects are easy to read?</h2>\n\n<p>The reason is tuples can be stored in the memory cache, unlike lists. The program always read from the lists memory location as it is mutable (can change any time).</p>\n"
},
{
"answer_id": 64191136,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 3,
"selected": false,
"text": "<p>Tuples perform better but if all the elements of tuple are immutable. If any element of a tuple is mutable a list or a function, it will take longer to be compiled. here I compiled 3 different objects:</p>\n<p><a href=\"https://i.stack.imgur.com/HfsPB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HfsPB.png\" alt=\"enter image description here\" /></a></p>\n<p>In the first example, I compiled a tuple. it loaded at the tuple as constant, it loaded and returned value. it took one step to compile. this is called <strong>constant folding</strong>. when I compiled a list with the same elements, it has to load each individual constant first, then it builds the list and returns it. in the third example, I used a tuple that includes a list. I timed each operation.</p>\n<p><a href=\"https://i.stack.imgur.com/mvl7O.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/mvl7O.png\" alt=\"enter image description here\" /></a></p>\n<p>-- <strong>MEMORY ALLOCATION</strong></p>\n<p>When mutable container objects such as lists, sets, dictionaries, etc are created, and during their lifetime, the allocated capacity of these containers (the number of items they can contain) is greater than the number of elements in the container. This is done to make adding elements to the collection more efficient, and is called <strong>over-allocating</strong>. Thus size of the list doesn't grow every time we append an element - it only does so occasionally. Resizing a list is very expensive, so not resizing every time an item is added helps out but you don't want to overallocate too much as this has a memory cost.</p>\n<p>Immutable containers on the other hand, since their item count is fixed once they have been created, do not need this <strong>overallocation</strong> - so their storage efficiency is greater. As tuples get larger, their size increases.</p>\n<p>-- <strong>COPY</strong></p>\n<p>it does not make sense to make a shallow copy of immutable sequence because you cannot mutate it anyways. So copying tuple just returns itself, with the memory address. That is why copying tuple is faster</p>\n<h2>Retrieving elements</h2>\n<p>I timeD retrieving an element from a tuple and a list:</p>\n<p><a href=\"https://i.stack.imgur.com/On8U0.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/On8U0.png\" alt=\"enter image description here\" /></a></p>\n<p>Retrieving elements from a tuple are very slightly faster than from a list. Because, in CPython, tuples have direct access (pointers) to their elements, while lists need to first access another array that contains the pointers to the elements of the list.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
]
| Is there any performance difference between tuples and lists when it comes to instantiation and retrieval of elements? | The [`dis`](https://docs.python.org/3/library/dis.html) module disassembles the byte code for a function and is useful to see the difference between tuples and lists.
In this case, you can see that accessing an element generates identical code, but that assigning a tuple is much faster than assigning a list.
```
>>> def a():
... x=[1,2,3,4,5]
... y=x[2]
...
>>> def b():
... x=(1,2,3,4,5)
... y=x[2]
...
>>> import dis
>>> dis.dis(a)
2 0 LOAD_CONST 1 (1)
3 LOAD_CONST 2 (2)
6 LOAD_CONST 3 (3)
9 LOAD_CONST 4 (4)
12 LOAD_CONST 5 (5)
15 BUILD_LIST 5
18 STORE_FAST 0 (x)
3 21 LOAD_FAST 0 (x)
24 LOAD_CONST 2 (2)
27 BINARY_SUBSCR
28 STORE_FAST 1 (y)
31 LOAD_CONST 0 (None)
34 RETURN_VALUE
>>> dis.dis(b)
2 0 LOAD_CONST 6 ((1, 2, 3, 4, 5))
3 STORE_FAST 0 (x)
3 6 LOAD_FAST 0 (x)
9 LOAD_CONST 2 (2)
12 BINARY_SUBSCR
13 STORE_FAST 1 (y)
16 LOAD_CONST 0 (None)
19 RETURN_VALUE
``` |
68,633 | <p>I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer.</p>
<p>Here is my regex: <code>"\w+ +\w+ *\(.*\) *\{"</code></p>
<p>For those who do not know what a java method looks like I'll provide a basic one:</p>
<pre><code>int foo()
{
}
</code></pre>
<p>There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have.</p>
<p>Update:
My current Regex is <code>"\w+ +\w+ *\([^\)]*\) *\{"</code> so as to prevent the situation that Mike and adkom described.</p>
| [
{
"answer_id": 68669,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": true,
"text": "<p>Have you considered matching the actual possible keywords? such as:</p>\n\n<pre><code>(?:(?:public)|(?:private)|(?:static)|(?:protected)\\s+)*\n</code></pre>\n\n<p>It might be a bit more likely to match correctly, though it might also make the regex harder to read...</p>\n"
},
{
"answer_id": 68697,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 2,
"selected": false,
"text": "<p>I'm pretty sure Java's regex engine is greedy by default, meaning that <code>\"\\w+ +\\w+ *\\(.*\\) *\\{\"</code> will never match since the <code>.*</code> within the parenthesis will eat everything after the opening paren. I recommend you replace the <code>.*</code> with [^)], this way you it will select all non-closing-paren characters.</p>\n\n<p><strong>NOTE:</strong> Mike Stone corrected me in the comments, and since most people don't really open the comments (I know I frequently don't notice them):</p>\n\n<blockquote>\n <p>Greedy doesn't mean it will never match... but it will eat parens if there are more parens after to satisfy the rest of the regex... so for example \"public void foo(int arg) { if (test) { System.exit(0); } }\" will not match properly... </p>\n</blockquote>\n"
},
{
"answer_id": 68890,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 2,
"selected": false,
"text": "<p>I came up with this:<br /></p>\n\n<pre><code>\\b\\w*\\s*\\w*\\(.*?\\)\\s*\\{[\\x21-\\x7E\\s]*\\}\n</code></pre>\n\n<p>I tested it against a PHP function but it should work just the same, this is the snippet of code I used:\n<br/></p>\n\n<pre><code>function getProfilePic($url)\n {\n if(@open_image($url) !== FALSE)\n {\n @imagepng($image, 'images/profiles/' . $_SESSION['id'] . '.png');\n @imagedestroy($image);\n return TRUE;\n }\n else \n {\n return FALSE;\n }\n }\n</code></pre>\n\n<p>MORE INFO:<br /></p>\n\n<pre><code>Options: case insensitive\n\nAssert position at a word boundary «\\b»\nMatch a single character that is a “word character” (letters, digits, etc.) «\\w*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\\s*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch a single character that is a “word character” (letters, digits, etc.) «\\w*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the character “(” literally «\\(»\nMatch any single character that is not a line break character «.*?»\n Between zero and unlimited times, as few times as possible, expanding as needed (lazy) «*?»\nMatch the character “)” literally «\\)»\nMatch a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.) «\\s*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\nMatch the character “{” literally «\\{»\nMatch a single character present in the list below «[\\x21-\\x7E\\s]*»\n Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»\n A character in the range between ASCII character 0x21 (33 decimal) and ASCII character 0x7E (126 decimal) «\\x21-\\x7E»\n A whitespace character (spaces, tabs, line breaks, etc.) «\\s»\nMatch the character “}” literally «\\}»\n\n\nCreated with RegexBuddy\n</code></pre>\n"
},
{
"answer_id": 69604,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>A tip:</p>\n\n<p>If you are going to write the regex in Perl, please use the \"xms\" options so that you can leave spaces and document the regex. For example you can write a regex like:</p>\n\n<pre><code> m{\\w+ \\s+ #return type\n \\w+ \\s* #function name\n [(] [^)]* [)] #params\n \\s* [{] #open paren\n }xms\n</code></pre>\n\n<p>One of the options (think x) allows the # comments inside a regex. Also use \\s instead of a \" \". \\s stands for any \"blank\" character. So tabs would also match -- which is what you would want. In Perl you don't need to use / /, you can use { } or < > or | |.</p>\n\n<p>Not sure if other languages have this ability. If they do, then please use them.</p>\n"
},
{
"answer_id": 847507,
"author": "Georgios Gousios",
"author_id": 51681,
"author_profile": "https://Stackoverflow.com/users/51681",
"pm_score": 5,
"selected": false,
"text": "<pre><code>(public|protected|private|static|\\s) +[\\w\\<\\>\\[\\]]+\\s+(\\w+) *\\([^\\)]*\\) *(\\{?|[^;])\n</code></pre>\n\n<p>I think that the above regexp can match almost all possible combinations of Java method declarations, even those including generics and arrays are return arguments, which the regexp provided by the original author did not match.</p>\n"
},
{
"answer_id": 11672271,
"author": "idbrii",
"author_id": 79125,
"author_profile": "https://Stackoverflow.com/users/79125",
"pm_score": 0,
"selected": false,
"text": "<p>I built a vim regex to do this for <a href=\"https://github.com/pydave/ctrlp-funky/blob/master/autoload/ctrlp/funky/java.vim\" rel=\"nofollow\">ctrlp/funky</a> based on Georgios Gousios's answer.</p>\n\n<pre><code> let regex = '\\v^\\s+' \" preamble\n let regex .= '%(<\\w+>\\s+){0,3}' \" visibility, static, final\n let regex .= '%(\\w|[<>[\\]])+\\s+' \" return type\n let regex .= '\\w+\\s*' \" method name\n let regex .= '\\([^\\)]*\\)' \" method parameters\n let regex .= '%(\\w|\\s|\\{)+$' \" postamble\n</code></pre>\n\n<p>I'd guess that looks like this in Java:</p>\n\n<pre><code>^\\s+(?:<\\w+>\\s+){0,3}(?:[\\w\\<\\>\\[\\]])+\\s+\\w+\\s*\\([^\\)]*\\)(?:\\w|\\s|\\{)+$\n</code></pre>\n"
},
{
"answer_id": 16118844,
"author": "sbaltes",
"author_id": 1974143,
"author_profile": "https://Stackoverflow.com/users/1974143",
"pm_score": 3,
"selected": false,
"text": "<p>I also needed such a regular expression and came up with this solution:</p>\n\n<pre><code>(?:(?:public|private|protected|static|final|native|synchronized|abstract|transient)+\\s+)+[$_\\w<>\\[\\]\\s]*\\s+[\\$_\\w]+\\([^\\)]*\\)?\\s*\\{?[^\\}]*\\}?\n</code></pre>\n\n<p>This <a href=\"http://cui.unige.ch/isi/bnf/JAVA/BNFindex.html\" rel=\"nofollow noreferrer\">grammar</a> and Georgios Gousios answer have been useful to build the regex.</p>\n\n<p><strong>EDIT:</strong> Considered tharindu_DG's feedback, made groups non-capturing, improved formatting.</p>\n"
},
{
"answer_id": 19030300,
"author": "aliteralmind",
"author_id": 2736496,
"author_profile": "https://Stackoverflow.com/users/2736496",
"pm_score": 3,
"selected": false,
"text": "<p>After looking through the other answers, here is what I came up with:</p>\n\n<pre><code>#permission\n ^[ \\t]*(?:(?:public|protected|private)\\s+)?\n#keywords\n (?:(static|final|native|synchronized|abstract|threadsafe|transient|{#insert zJRgx123GenericsNotInGroup})\\s+){0,}\n#return type\n #If return type is \"return\" then it's actually a 'return funcName();' line. Ignore.\n (?!return)\n \\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,})\\s+\n#function name\n \\b\\w+\\b\\s*\n#parameters\n \\(\n #one\n \\s*(?:\\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\n #two and up\n \\(\\s*(?:,\\s+\\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\\s*){0,})?\\s*\n \\)\n#post parameters\n (?:\\s*throws [\\w.]+(\\s*,\\s*[\\w.]+))?\n#close-curly (concrete) or semi-colon (abstract)\n \\s*(?:\\{|;)[ \\t]*$\n</code></pre>\n\n<hr>\n\n<p>Where <code>{#insert zJRgx123GenericsNotInGroup}</code> equals</p>\n\n<pre><code>`(?:<[?\\w\\[\\] ,.&]+>)|(?:<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>[^>]*>)`\n</code></pre>\n\n<p>Limitations:</p>\n\n<ul>\n<li>ANY parameter can have an ellipsis: \"...\" (Java allows only last)</li>\n<li>Three levels of nested generics at most: (<code><...<...<...>...>...></code> okay, <code><...<...<...<...>...>...>...></code> bad). The syntax inside generics can be very bogus, and still seem okay to this regex.</li>\n<li>Requires no spaces between types and their (optional) opening generics '<'</li>\n<li>Recognizes inner classes, but doesn't prevent two dots next to each other, such as Class....InnerClass</li>\n</ul>\n\n<p>Below is the raw PhraseExpress code (auto-text and description on line 1, body on line 2). Call <code>{#insert zJRgxJavaFuncSigThrSemicOrOpnCrly}</code>, and you get this:</p>\n\n<pre><code>^[ \\t]*(?:(?:public|protected|private)\\s+)?(?:(static|final|native|synchronized|abstract|threadsafe|transient|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))\\s+){0,}(?!return)\\b([\\w.]+)\\b(?:|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))((?:\\[\\]){0,})\\s+\\b\\w+\\b\\s*\\(\\s*(?:\\b([\\w.]+)\\b(?:|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\\s*(?:,\\s+\\b([\\w.]+)\\b(?:|(?:<[?\\w\\[\\] ,&]+>)|(?:<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,&]+>[^>]*>[^>]*>))((?:\\[\\]){0,})(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[])\\s*){0,})?\\s*\\)(?:\\s*throws [\\w.]+(\\s*,\\s*[\\w.]+))?\\s*(?:\\{|;)[ \\t]*$\n</code></pre>\n\n<hr>\n\n<p>Raw code:</p>\n\n<pre><code>zJRgx123GenericsNotInGroup -- To precede return-type (?:<[?\\w\\[\\] ,.&]+>)|(?:<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>)|(?:<[^<]*<[^<]*<[?\\w\\[\\] ,.&]+>[^>]*>[^>]*>) zJRgx123GenericsNotInGroup\nzJRgx0OrMoreParams \\s*(?:{#insert zJRgxParamTypeName}\\s*(?:,\\s+{#insert zJRgxParamTypeName}\\s*){0,})?\\s* zJRgx0OrMoreParams\nzJRgxJavaFuncNmThrClsPrn_M_fnm -- Needs zvFOBJ_NAME (?<=\\s)\\b{#insert zvFOBJ_NAME}{#insert zzJRgxPostFuncNmThrClsPrn} zJRgxJavaFuncNmThrClsPrn_M_fnm\nzJRgxJavaFuncSigThrSemicOrOpnCrly -(**)- {#insert zzJRgxJavaFuncSigPreFuncName}\\w+{#insert zzJRgxJavaFuncSigPostFuncName} zJRgxJavaFuncSigThrSemicOrOpnCrly\nzJRgxJavaFuncSigThrSemicOrOpnCrly_M_fnm -- Needs zvFOBJ_NAME {#insert zzJRgxJavaFuncSigPreFuncName}{#insert zvFOBJ_NAME}{#insert zzJRgxJavaFuncSigPostFuncName} zJRgxJavaFuncSigThrSemicOrOpnCrly_M_fnm\nzJRgxOptKeywordsBtwScopeAndRetType (?:(static|final|native|synchronized|abstract|threadsafe|transient|{#insert zJRgx123GenericsNotInGroup})\\s+){0,} zJRgxOptKeywordsBtwScopeAndRetType\nzJRgxOptionalPubProtPriv (?:(?:public|protected|private)\\s+)? zJRgxOptionalPubProtPriv\nzJRgxParamTypeName -(**)- Ends w/ '\\b(?![>\\[])' to NOT find <? 'extends XClass'> or ...[]> (*Original: zJRgxParamTypeName, Needed by: zJRgxParamTypeName[4FQPTV,ForDel[NmsOnly,Types]]*){#insert zJRgxTypeW0123GenericsArry}(\\.\\.\\.)?\\s+(\\w+)\\b(?![>\\[]) zJRgxParamTypeName\nzJRgxTypeW0123GenericsArry -- Grp1=Type, Grp2='[]', if any \\b([\\w.]+)\\b(?:|{#insert zJRgx123GenericsNotInGroup})((?:\\[\\]){0,}) zJRgxTypeW0123GenericsArry\nzvTTL_PRMS_stL1c {#insert zCutL1c}{#SETPHRASE -description zvTTL_PRMS -content {#INSERTCLIPBOARD} -autotext zvTTL_PRMS -folder ctvv_folder} zvTTL_PRMS_stL1c\nzvTTL_PRMS_stL1cSvRstrCB {#insert zvCB_CONTENTS_stCB}{#insert zvTTL_PRMS_stL1c}{#insert zSetCBToCB_CONTENTS} zvTTL_PRMS_stL1cSvRstrCB\nzvTTL_PRMS_stPrompt {#SETPHRASE -description zvTTL_PRMS -content {#INPUT -head How many parameters? -single} -autotext zvTTL_PRMS -folder ctvv_folder} zvTTL_PRMS_stPrompt\nzzJRgxJavaFuncNmThrClsPrn_M_fnmTtlp -- Needs zvFOBJ_NAME, zvTTL_PRMS (?<=[ \\t])\\b{#insert zvFOBJ_NAME}\\b\\s*\\(\\s*{#insert {#COND -if {#insert zvTTL_PRMS} = 0 -then z1slp -else zzParamsGT0_M_ttlp}}\\) zzJRgxJavaFuncNmThrClsPrn_M_fnmTtlp\nzzJRgxJavaFuncSigPostFuncName {#insert zzJRgxPostFuncNmThrClsPrn}(?:\\s*throws \\b(?:[\\w.]+)\\b(\\s*,\\s*\\b(?:[\\w.]+)\\b))?\\s*(?:\\{|;)[ \\t]*$ zzJRgxJavaFuncSigPostFuncName\nzzJRgxJavaFuncSigPreFuncName (*If a type has generics, there may be no spaces between it and the first open '<', also requires generics with three nestings at the most (<...<...<...>...>...> okay, <...<...<...<...>...>...>...> not)*)^[ \\t]*{#insert zJRgxOptionalPubProtPriv}{#insert zJRgxOptKeywordsBtwScopeAndRetType}(*To prevent 'return funcName();' from being recognized:*)(?!return){#insert zJRgxTypeW0123GenericsArry}\\s+\\b zzJRgxJavaFuncSigPreFuncName\nzzJRgxPostFuncNmThrClsPrn \\b\\s*\\({#insert zJRgx0OrMoreParams}\\) zzJRgxPostFuncNmThrClsPrn\nzzParamsGT0_M_ttlp -- Needs zvTTL_PRMS {#insert zJRgxParamTypeName}\\s*{#insert {#COND -if {#insert zvTTL_PRMS} = 1 -then z1slp -else zzParamsGT1_M_ttlp}} zzParamsGT0_M_ttlp\nzzParamsGT1_M_ttlp {#LOOP ,\\s+{#insert zJRgxParamTypeName}\\s* -count {#CALC {#insert zvTTL_PRMS} - 1 -round 0 -thousands none}} zzParamsGT1_M_ttlp\n</code></pre>\n"
},
{
"answer_id": 21172210,
"author": "Dexygen",
"author_id": 34806,
"author_profile": "https://Stackoverflow.com/users/34806",
"pm_score": 1,
"selected": false,
"text": "<p>This is for a more specific use case but it's so much simpler I believe its worth sharing. I did this for finding 'public static void' methods i.e. Play controller actions, and I did it from the Windows/Cygwin command line, using grep; see: <a href=\"https://stackoverflow.com/a/7167115/34806\">https://stackoverflow.com/a/7167115/34806</a></p>\n\n<pre><code>cat Foobar.java | grep -Pzo '(?s)public static void.*?\\)\\s+{'\n</code></pre>\n\n<p>The last two entries from my output are as follows:</p>\n\n<pre><code>public static void activeWorkEventStations (String type,\n String symbol,\n String section,\n String day,\n String priority,\n @As(\"yyyy-MM-dd\") Date scheduleDepartureDate) {\npublic static void getActiveScheduleChangeLogs(String type,\n String symbol,\n String section,\n String day,\n String priority,\n @As(\"yyyy-MM-dd\") Date scheduleDepartureDate) {\n</code></pre>\n"
},
{
"answer_id": 36217245,
"author": "tharindu_DG",
"author_id": 1894198,
"author_profile": "https://Stackoverflow.com/users/1894198",
"pm_score": 0,
"selected": false,
"text": "<p>I found <strong>seba229</strong>'s answer useful, it captures most of the scenarios, but not the following,</p>\n\n<pre><code>public <T> T name(final Class<T> x, final T y)\n</code></pre>\n\n<p>This regex will capture that also.</p>\n\n<pre><code>((public|private|protected|static|final|native|synchronized|abstract|transient)+\\s)+[\\$_\\w\\<\\>\\w\\s\\[\\]]*\\s+[\\$_\\w]+\\([^\\)]*\\)?\\s*\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 45900932,
"author": "user1122069",
"author_id": 1122069,
"author_profile": "https://Stackoverflow.com/users/1122069",
"pm_score": 0,
"selected": false,
"text": "<pre><code>(public|private|static|protected) ([A-Za-z0-9<>.]+) ([A-Za-z0-9]+)\\(\n</code></pre>\n\n<p>Also, here's a replace sequence you can use in IntelliJ</p>\n\n<pre><code>$1 $2 $3(\n</code></pre>\n\n<p>I use it like this:</p>\n\n<pre><code>$1 $2 aaa$3(\n</code></pre>\n\n<p>when converting Java files to Kotlin to prevent functions that start with \"get\" from automatically turning into variables. Doesn't work with \"default\" access level, but I don't use that much myself.</p>\n"
},
{
"answer_id": 48072172,
"author": "Souvik Das",
"author_id": 9166774,
"author_profile": "https://Stackoverflow.com/users/9166774",
"pm_score": 2,
"selected": false,
"text": "<p><code>(public|private|static|protected|abstract|native|synchronized) +([a-zA-Z0-9<>._?, ]+) +([a-zA-Z0-9_]+) *\\\\([a-zA-Z0-9<>\\\\[\\\\]._?, \\n]*\\\\) *([a-zA-Z0-9_ ,\\n]*) *\\\\{</code></p>\n\n<p>The Regex above will detect all possible java method definitions. Tested on lot's of source code files. To include constructors as well use the below regex :</p>\n\n<p><code>(public|private|static|protected|abstract|native|synchronized) +([a-zA-Z0-9<>._?, ]*) +([a-zA-Z0-9_]+) *\\\\([a-zA-Z0-9<>\\\\[\\\\]._?, \\n]*\\\\) *([a-zA-Z0-9_ ,\\n]*) *\\\\{</code></p>\n"
},
{
"answer_id": 52996479,
"author": "LarsH",
"author_id": 423105,
"author_profile": "https://Stackoverflow.com/users/423105",
"pm_score": 1,
"selected": false,
"text": "<p>As of git 2.19.0, the <a href=\"https://git.kernel.org/pub/scm/git/git.git/tree/userdiff.c\" rel=\"nofollow noreferrer\">built-in regexp for Java</a> now seems to work well, so supplying your own may not be necessary.</p>\n\n<pre><code>\"!^[ \\t]*(catch|do|for|if|instanceof|new|return|switch|throw|while)\\n\"\n\"^[ \\t]*(([A-Za-z_][A-Za-z_0-9]*[ \\t]+)+[A-Za-z_][A-Za-z_0-9]*[ \\t]*\\\\([^;]*)$\"\n</code></pre>\n\n<p>(The first line seems to be for filtering out lines that resemble method declarations but aren't.)</p>\n"
},
{
"answer_id": 55051029,
"author": "Abdullah Khan",
"author_id": 9758506,
"author_profile": "https://Stackoverflow.com/users/9758506",
"pm_score": 1,
"selected": false,
"text": "<p>This will pick the name of method not the whole line.</p>\n\n<pre><code>(?<=public static void )\\w+|(?<=private static void )\\w+|(?<=protected static void )\\w+|(?<=public void )\\w+|(?<=private void )\\w+|(?<=protected void )\\w+|(?<=public final void)\\w+|(?<=private final void)\\w+|(?<=protected final void)\\w+|(?<=private void )\\w+|(?<=protected void )\\w+|(?<=public static final void )\\w+|(?<=private static final void )\\w+|(?<=public final static void )\\w+|(?<=protected final static void )\\\\w+|(?<=private final static void )\\w+|(?<=protected final static void )\\w+|(?<=void )\\w+|(?<=private static )\\w+\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/340/"
]
| I need a Regex that will match a java method declaration. I have come up with one that will match a method declaration, but it requires the opening bracket of the method to be on the same line as the declaration. If you have any suggestions to improve my regex or simply have a better one then please submit an answer.
Here is my regex: `"\w+ +\w+ *\(.*\) *\{"`
For those who do not know what a java method looks like I'll provide a basic one:
```
int foo()
{
}
```
There are several optional parts to java methods that may be added as well but those are the only parts that a method is guaranteed to have.
Update:
My current Regex is `"\w+ +\w+ *\([^\)]*\) *\{"` so as to prevent the situation that Mike and adkom described. | Have you considered matching the actual possible keywords? such as:
```
(?:(?:public)|(?:private)|(?:static)|(?:protected)\s+)*
```
It might be a bit more likely to match correctly, though it might also make the regex harder to read... |
68,640 | <p>Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both?</p>
| [
{
"answer_id": 68681,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 6,
"selected": true,
"text": "<p>Yes, you can. The pointer to the class member variable is stored <strike>on the stack</strike> with the rest of the struct's values, and the class instance's data is stored on the heap.</p>\n\n<p>Structs can also contain class definitions as members (inner classes).</p>\n\n<p>Here's some really useless code that at least compiles and runs to show that it's possible:</p>\n\n<pre><code>using System;\n\nnamespace ConsoleApplication1\n{\n class Program\n {\n static void Main(string[] args)\n {\n MyStr m = new MyStr();\n m.Foo();\n\n MyStr.MyStrInner mi = new MyStr.MyStrInner();\n mi.Bar();\n\n Console.ReadLine();\n }\n }\n\n public class Myclass\n {\n public int a;\n }\n\n struct MyStr\n {\n Myclass mc;\n\n public void Foo()\n {\n mc = new Myclass();\n mc.a = 1;\n }\n\n public class MyStrInner\n {\n string x = \"abc\";\n\n public string Bar()\n {\n return x;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68810,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": 2,
"selected": false,
"text": "<p>It's probably not a recommended practice to do so: see <a href=\"http://msdn.microsoft.com/en-us/library/ms229017(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms229017(VS.85).aspx</a></p>\n\n<blockquote>\n <p>Reference types are allocated on the heap, and memory management is\n handled by the garbage collector. </p>\n \n <p>Value types are allocated on the stack or inline and are deallocated\n when they go out of scope. </p>\n \n <p>In general, value types are cheaper to allocate and deallocate.\n However, if they are used in scenarios that require a significant\n amount of boxing and unboxing, they perform poorly as compared to\n reference types.</p>\n</blockquote>\n"
},
{
"answer_id": 6801550,
"author": "Ben Voigt",
"author_id": 103167,
"author_profile": "https://Stackoverflow.com/users/103167",
"pm_score": 4,
"selected": false,
"text": "<p>The class content gets stored on the heap.</p>\n\n<p>A reference to the class (which is almost the same as a pointer) gets stored with the struct content. Where the struct content is stored depends on whether it's a local variable, method parameter, or member of a class, and whether it's been boxed or captured by a closure.</p>\n"
},
{
"answer_id": 11887584,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 2,
"selected": false,
"text": "<p>If one of the fields of a struct is a class type, that field will either hold the <i>identity</i> of a class object or else a null referece. If the class object in question is immutable (e.g. <code>string</code>), storing its identity will effectively also store its contents. If the class object in question is mutable, however, storing the identity will be an effective means of storing the contents <i>if and only if the reference will never fall into the hands of any code which might mutate it once it is stored in the field</i>.</p>\n\n<p>Generally, one should avoid storing mutable class types within a structure unless one of two situations applies:</p>\n\n<ol>\n<li>What one is interested in is, in fact, the identity of the class object rather than its content. For example, one might define a `FormerControlBounds` structure which holds fields of type `Control` and `Rectangle`, and represents the `Bounds` that control had at some moment in time, for the purpose of being able to later restore the control to its earlier position. The purpose of the `Control` field would not be to hold a copy of the control's state, but rather to identify the control whose position should be restored. Generally the struct should avoid accessing any mutable members of the object to which it holds a reference, except in cases where it is clear that such access is referring to the current mutable state of the object in question (e.g. in a `CaptureControlPosition` or `RestoreControlToCapturedPosition` method, or a `ControlHasMoved` property).\n<li>The field is `private`, the only methods which read it do so for the purpose of examining its properties without exposing the object itself it to outside code, and the only methods which write it will create a new object, perform all of the mutations that are ever going to happen to it, and then store a reference to that object. One could, for example, design a `struct` which behaved much like an array, but with value semantics, by having the struct hold an array in a private field, and by having every attempt to write the array create a new array with data from the old one, modify the new array, and store the modified array to that field. Note that even though the array itself would be a mutable type, every array instance that would ever be stored in the field would be effectively immutable, since it would never be accessible by any code that might mutate it.\n</ol>\n\n<p>Note that scenario #1 is pretty common with generic types; for example, it's very common to have a dictionary whose \"values\" are the identities of mutable objects; enumerating that dictionary will return instances of <code>KeyValuePair</code> whose <code>Value</code> field holds that mutable type.</p>\n\n<p>Scenario #2 is less common. There is alas no way to tell the compiler that struct methods other than property setters will modify a struct and their use should thus be forbidden in read-only contexts; one could have a struct that behaved like a <code>List<T></code>, but with value semantics, and included an <code>Add</code> method, but an attempt to call <code>Add</code> on a read-only struct instance would generate bogus code rather than a compiler error. Further, mutating methods and property setters on such structs will generally perform rather poorly. Such structs can be useful are when they exist as an immutable wrapper on an otherwise-mutable class; if such a struct is never boxed, performance will often be better than a class. If boxed exactly once (e.g. by being cast to an interface type), performance will generally be comparable to a class. If boxed repeatedly, performance can be much worse than a class.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10722/"
]
| Is it possible in C# to have a Struct with a member variable which is a Class type? If so, where does the information get stored, on the Stack, the Heap, or both? | Yes, you can. The pointer to the class member variable is stored on the stack with the rest of the struct's values, and the class instance's data is stored on the heap.
Structs can also contain class definitions as members (inner classes).
Here's some really useless code that at least compiles and runs to show that it's possible:
```
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyStr m = new MyStr();
m.Foo();
MyStr.MyStrInner mi = new MyStr.MyStrInner();
mi.Bar();
Console.ReadLine();
}
}
public class Myclass
{
public int a;
}
struct MyStr
{
Myclass mc;
public void Foo()
{
mc = new Myclass();
mc.a = 1;
}
public class MyStrInner
{
string x = "abc";
public string Bar()
{
return x;
}
}
}
}
``` |
68,645 | <p>How do I create class (i.e. <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods" rel="nofollow noreferrer">static</a>) variables or methods in Python?</p>
| [
{
"answer_id": 68672,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 12,
"selected": true,
"text": "<p>Variables declared inside the class definition, but not inside a method are class or static variables:</p>\n<pre><code>>>> class MyClass:\n... i = 3\n...\n>>> MyClass.i\n3 \n</code></pre>\n<p>As @<a href=\"https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067\">millerdev</a> points out, this creates a class-level <code>i</code> variable, but this is distinct from any instance-level <code>i</code> variable, so you could have</p>\n<pre><code>>>> m = MyClass()\n>>> m.i = 4\n>>> MyClass.i, m.i\n>>> (3, 4)\n</code></pre>\n<p>This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.</p>\n<p>See <a href=\"https://docs.python.org/3/tutorial/classes.html#class-objects\" rel=\"noreferrer\">what the Python tutorial has to say on the subject of classes and class objects</a>.</p>\n<p>@Steve Johnson has already answered regarding <a href=\"http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod\" rel=\"noreferrer\">static methods</a>, also documented under <a href=\"https://docs.python.org/3/library/functions.html#staticmethod\" rel=\"noreferrer\">"Built-in Functions" in the Python Library Reference</a>.</p>\n<pre><code>class C:\n @staticmethod\n def f(arg1, arg2, ...): ...\n</code></pre>\n<p>@beidy recommends <a href=\"https://docs.python.org/3/library/functions.html#classmethod\" rel=\"noreferrer\">classmethod</a>s over staticmethod, as the method then receives the class type as the first argument.</p>\n"
},
{
"answer_id": 68747,
"author": "emb",
"author_id": 10739,
"author_profile": "https://Stackoverflow.com/users/10739",
"pm_score": 5,
"selected": false,
"text": "<p>Personally I would use a classmethod whenever I needed a static method. Mainly because I get the class as an argument.</p>\n\n<pre><code>class myObj(object):\n def myMethod(cls)\n ...\n myMethod = classmethod(myMethod) \n</code></pre>\n\n<p>or use a decorator</p>\n\n<pre><code>class myObj(object):\n @classmethod\n def myMethod(cls)\n</code></pre>\n\n<p>For static properties.. Its time you look up some python definition.. variable can always change. There are two types of them mutable and immutable.. Also, there are class attributes and instance attributes.. Nothing really like static attributes in the sense of java & c++</p>\n\n<p>Why use static method in pythonic sense, if it has no relation whatever to the class! If I were you, I'd either use classmethod or define the method independent from the class.</p>\n"
},
{
"answer_id": 68770,
"author": "willurd",
"author_id": 1943957,
"author_profile": "https://Stackoverflow.com/users/1943957",
"pm_score": 5,
"selected": false,
"text": "<p>Static methods in python are called <a href=\"http://pyref.infogami.com/classmethod\" rel=\"noreferrer\">classmethod</a>s. Take a look at the following code</p>\n\n<pre><code>class MyClass:\n\n def myInstanceMethod(self):\n print 'output from an instance method'\n\n @classmethod\n def myStaticMethod(cls):\n print 'output from a static method'\n\n>>> MyClass.myInstanceMethod()\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: unbound method myInstanceMethod() must be called [...]\n\n>>> MyClass.myStaticMethod()\noutput from a static method\n</code></pre>\n\n<p>Notice that when we call the method <em>myInstanceMethod</em>, we get an error. This is because it requires that method be called on an instance of this class. The method <em>myStaticMethod</em> is set as a classmethod using the <a href=\"http://www.python.org/dev/peps/pep-0318/\" rel=\"noreferrer\">decorator</a> <em>@classmethod</em>.</p>\n\n<p>Just for kicks and giggles, we could call <em>myInstanceMethod</em> on the class by passing in an instance of the class, like so:</p>\n\n<pre><code>>>> MyClass.myInstanceMethod(MyClass())\noutput from an instance method\n</code></pre>\n"
},
{
"answer_id": 69067,
"author": "millerdev",
"author_id": 10840,
"author_profile": "https://Stackoverflow.com/users/10840",
"pm_score": 10,
"selected": false,
"text": "<p>@Blair Conrad said static variables declared inside the class definition, but not inside a method are class or \"static\" variables:</p>\n\n<pre><code>>>> class Test(object):\n... i = 3\n...\n>>> Test.i\n3\n</code></pre>\n\n<p>There are a few gotcha's here. Carrying on from the example above:</p>\n\n<pre><code>>>> t = Test()\n>>> t.i # \"static\" variable accessed via instance\n3\n>>> t.i = 5 # but if we assign to the instance ...\n>>> Test.i # we have not changed the \"static\" variable\n3\n>>> t.i # we have overwritten Test.i on t by creating a new attribute t.i\n5\n>>> Test.i = 6 # to change the \"static\" variable we do it by assigning to the class\n>>> t.i\n5\n>>> Test.i\n6\n>>> u = Test()\n>>> u.i\n6 # changes to t do not affect new instances of Test\n\n# Namespaces are one honking great idea -- let's do more of those!\n>>> Test.__dict__\n{'i': 6, ...}\n>>> t.__dict__\n{'i': 5}\n>>> u.__dict__\n{}\n</code></pre>\n\n<p>Notice how the instance variable <code>t.i</code> got out of sync with the \"static\" class variable when the attribute <code>i</code> was set directly on <code>t</code>. This is because <code>i</code> was re-bound within the <code>t</code> namespace, which is distinct from the <code>Test</code> namespace. If you want to change the value of a \"static\" variable, you must change it within the scope (or object) where it was originally defined. I put \"static\" in quotes because Python does not really have static variables in the sense that C++ and Java do.</p>\n\n<p>Although it doesn't say anything specific about static variables or methods, the <a href=\"http://docs.python.org/tut/\" rel=\"noreferrer\">Python tutorial</a> has some relevant information on <a href=\"https://docs.python.org/2/tutorial/classes.html\" rel=\"noreferrer\">classes and class objects</a>. </p>\n\n<p>@Steve Johnson also answered regarding static methods, also documented under \"Built-in Functions\" in the Python Library Reference.</p>\n\n<pre><code>class Test(object):\n @staticmethod\n def f(arg1, arg2, ...):\n ...\n</code></pre>\n\n<p>@beid also mentioned classmethod, which is similar to staticmethod. A classmethod's first argument is the class object. Example:</p>\n\n<pre><code>class Test(object):\n i = 3 # class (or static) variable\n @classmethod\n def g(cls, arg):\n # here we can use 'cls' instead of the class name (Test)\n if arg > cls.i:\n cls.i = arg # would be the same as Test.i = arg1\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/xqnxe.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/xqnxe.jpg\" alt=\"Pictorial Representation Of Above Example\"></a></p>\n"
},
{
"answer_id": 79840,
"author": "Ross",
"author_id": 14794,
"author_profile": "https://Stackoverflow.com/users/14794",
"pm_score": 3,
"selected": false,
"text": "<p>To avoid any potential confusion, I would like to contrast static variables and immutable objects.</p>\n\n<p>Some primitive object types like integers, floats, strings, and touples are immutable in Python. This means that the object that is referred to by a given name cannot change if it is of one of the aforementioned object types. The name can be reassigned to a different object, but the object itself may not be changed.</p>\n\n<p>Making a variable static takes this a step further by disallowing the variable name to point to any object but that to which it currently points. (Note: this is a general software concept and not specific to Python; please see others' posts for information about implementing statics in Python).</p>\n"
},
{
"answer_id": 81002,
"author": "Gregory",
"author_id": 14351,
"author_profile": "https://Stackoverflow.com/users/14351",
"pm_score": 6,
"selected": false,
"text": "<p>You can also add class variables to classes on the fly</p>\n\n<pre><code>>>> class X:\n... pass\n... \n>>> X.bar = 0\n>>> x = X()\n>>> x.bar\n0\n>>> x.foo\nTraceback (most recent call last):\n File \"<interactive input>\", line 1, in <module>\nAttributeError: X instance has no attribute 'foo'\n>>> X.foo = 1\n>>> x.foo\n1\n</code></pre>\n\n<p>And class instances can change class variables</p>\n\n<pre><code>class X:\n l = []\n def __init__(self):\n self.l.append(1)\n\nprint X().l\nprint X().l\n\n>python test.py\n[1]\n[1, 1]\n</code></pre>\n"
},
{
"answer_id": 8201368,
"author": "Bartosz Ptaszynski",
"author_id": 27098,
"author_profile": "https://Stackoverflow.com/users/27098",
"pm_score": 4,
"selected": false,
"text": "<p>You could also enforce a class to be static using metaclass.</p>\n\n<pre><code>class StaticClassError(Exception):\n pass\n\n\nclass StaticClass:\n __metaclass__ = abc.ABCMeta\n\n def __new__(cls, *args, **kw):\n raise StaticClassError(\"%s is a static class and cannot be initiated.\"\n % cls)\n\nclass MyClass(StaticClass):\n a = 1\n b = 3\n\n @staticmethod\n def add(x, y):\n return x+y\n</code></pre>\n\n<p>Then whenever by accident you try to initialize <strong>MyClass</strong> you'll get an StaticClassError.</p>\n"
},
{
"answer_id": 9613563,
"author": "jondinham",
"author_id": 905418,
"author_profile": "https://Stackoverflow.com/users/905418",
"pm_score": 5,
"selected": false,
"text": "<p>One special thing to note about static properties & instance properties, shown in the example below:</p>\n\n<pre><code>class my_cls:\n my_prop = 0\n\n#static property\nprint my_cls.my_prop #--> 0\n\n#assign value to static property\nmy_cls.my_prop = 1 \nprint my_cls.my_prop #--> 1\n\n#access static property thru' instance\nmy_inst = my_cls()\nprint my_inst.my_prop #--> 1\n\n#instance property is different from static property \n#after being assigned a value\nmy_inst.my_prop = 2\nprint my_cls.my_prop #--> 1\nprint my_inst.my_prop #--> 2\n</code></pre>\n\n<p>This means before assigning the value to instance property, if we try to access the property thru' instance, the static value is used. <strong>Each property declared in python class always has a static slot in memory</strong>.</p>\n"
},
{
"answer_id": 15117875,
"author": "Tomer Zait",
"author_id": 1261677,
"author_profile": "https://Stackoverflow.com/users/1261677",
"pm_score": 3,
"selected": false,
"text": "<p>The best way I found is to use another class. You can create an object and then use it on other objects.</p>\n\n<pre><code>class staticFlag:\n def __init__(self):\n self.__success = False\n def isSuccess(self):\n return self.__success\n def succeed(self):\n self.__success = True\n\nclass tryIt:\n def __init__(self, staticFlag):\n self.isSuccess = staticFlag.isSuccess\n self.succeed = staticFlag.succeed\n\ntryArr = []\nflag = staticFlag()\nfor i in range(10):\n tryArr.append(tryIt(flag))\n if i == 5:\n tryArr[i].succeed()\n print tryArr[i].isSuccess()\n</code></pre>\n\n<p>With the example above, I made a class named <code>staticFlag</code>.</p>\n\n<p>This class should present the static var <code>__success</code> (Private Static Var).</p>\n\n<p><code>tryIt</code> class represented the regular class we need to use.</p>\n\n<p>Now I made an object for one flag (<code>staticFlag</code>). This flag will be sent as reference to all the regular objects.</p>\n\n<p>All these objects are being added to the list <code>tryArr</code>.</p>\n\n<hr>\n\n<p>This Script Results:</p>\n\n<pre><code>False\nFalse\nFalse\nFalse\nFalse\nTrue\nTrue\nTrue\nTrue\nTrue\n</code></pre>\n"
},
{
"answer_id": 15644143,
"author": "user2209576",
"author_id": 2209576,
"author_profile": "https://Stackoverflow.com/users/2209576",
"pm_score": 4,
"selected": false,
"text": "<p>When define some member variable outside any member method, the variable can be either static or non-static depending on how the variable is expressed. </p>\n\n<ul>\n<li>CLASSNAME.var is static variable</li>\n<li>INSTANCENAME.var is not static variable. </li>\n<li>self.var inside class is not static variable. </li>\n<li>var inside the class member function is not defined.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>#!/usr/bin/python\n\nclass A:\n var=1\n\n def printvar(self):\n print \"self.var is %d\" % self.var\n print \"A.var is %d\" % A.var\n\n\n a = A()\n a.var = 2\n a.printvar()\n\n A.var = 3\n a.printvar()\n</code></pre>\n\n<p>The results are</p>\n\n<pre><code>self.var is 2\nA.var is 1\nself.var is 2\nA.var is 3\n</code></pre>\n"
},
{
"answer_id": 24553443,
"author": "Yann",
"author_id": 717357,
"author_profile": "https://Stackoverflow.com/users/717357",
"pm_score": 3,
"selected": false,
"text": "<p>In regards to this <a href=\"https://stackoverflow.com/a/68672/717357\">answer</a>, for a <em>constant</em> static variable, you can use a descriptor. Here's an example:</p>\n\n<pre><code>class ConstantAttribute(object):\n '''You can initialize my value but not change it.'''\n def __init__(self, value):\n self.value = value\n\n def __get__(self, obj, type=None):\n return self.value\n\n def __set__(self, obj, val):\n pass\n\n\nclass Demo(object):\n x = ConstantAttribute(10)\n\n\nclass SubDemo(Demo):\n x = 10\n\n\ndemo = Demo()\nsubdemo = SubDemo()\n# should not change\ndemo.x = 100\n# should change\nsubdemo.x = 100\nprint \"small demo\", demo.x\nprint \"small subdemo\", subdemo.x\nprint \"big demo\", Demo.x\nprint \"big subdemo\", SubDemo.x\n</code></pre>\n\n<p>resulting in ...</p>\n\n<pre><code>small demo 10\nsmall subdemo 100\nbig demo 10\nbig subdemo 10\n</code></pre>\n\n<p>You can always raise an exception if quietly ignoring setting value (<code>pass</code> above) is not your thing. If you're looking for a C++, Java style static class variable:</p>\n\n<pre><code>class StaticAttribute(object):\n def __init__(self, value):\n self.value = value\n\n def __get__(self, obj, type=None):\n return self.value\n\n def __set__(self, obj, val):\n self.value = val\n</code></pre>\n\n<p>Have a look at <a href=\"https://stackoverflow.com/a/102062/717357\">this answer</a> and the official docs <a href=\"https://docs.python.org/2/howto/descriptor.html\" rel=\"noreferrer\">HOWTO</a> for more information about descriptors. </p>\n"
},
{
"answer_id": 27568860,
"author": "Rick",
"author_id": 2437514,
"author_profile": "https://Stackoverflow.com/users/2437514",
"pm_score": 8,
"selected": false,
"text": "<h2>Static and Class Methods</h2>\n<p>As the other answers have noted, static and class methods are easily accomplished using the built-in decorators:</p>\n<pre><code>class Test(object):\n\n # regular instance method:\n def my_method(self):\n pass\n\n # class method:\n @classmethod\n def my_class_method(cls):\n pass\n\n # static method:\n @staticmethod\n def my_static_method():\n pass\n</code></pre>\n<p>As usual, the first argument to <code>my_method()</code> is bound to the class instance object. In contrast, the first argument to <code>my_class_method()</code> is <em>bound to the class object itself</em> (e.g., in this case, <code>Test</code>). For <code>my_static_method()</code>, none of the arguments are bound, and having arguments at all is optional.</p>\n<h2>"Static Variables"</h2>\n<p>However, implementing "static variables" (well, <em>mutable</em> static variables, anyway, if that's not a contradiction in terms...) is not as straight forward. As millerdev <a href=\"https://stackoverflow.com/a/69067/2437514\">pointed out in his answer</a>, the problem is that Python's class attributes are not truly "static variables". Consider:</p>\n<pre><code>class Test(object):\n i = 3 # This is a class attribute\n\nx = Test()\nx.i = 12 # Attempt to change the value of the class attribute using x instance\nassert x.i == Test.i # ERROR\nassert Test.i == 3 # Test.i was not affected\nassert x.i == 12 # x.i is a different object than Test.i\n</code></pre>\n<p>This is because the line <code>x.i = 12</code> has added a new instance attribute <code>i</code> to <code>x</code> instead of changing the value of the <code>Test</code> class <code>i</code> attribute.</p>\n<p><em>Partial</em> expected static variable behavior, i.e., syncing of the attribute between multiple instances (but <strong>not</strong> with the class itself; see "gotcha" below), can be achieved by turning the class attribute into a property:</p>\n<pre><code>class Test(object):\n\n _i = 3\n\n @property\n def i(self):\n return type(self)._i\n\n @i.setter\n def i(self,val):\n type(self)._i = val\n\n## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##\n## (except with separate methods for getting and setting i) ##\n\nclass Test(object):\n\n _i = 3\n\n def get_i(self):\n return type(self)._i\n\n def set_i(self,val):\n type(self)._i = val\n\n i = property(get_i, set_i)\n</code></pre>\n<p>Now you can do:</p>\n<pre><code>x1 = Test()\nx2 = Test()\nx1.i = 50\nassert x2.i == x1.i # no error\nassert x2.i == 50 # the property is synced\n</code></pre>\n<p>The static variable will now remain in sync <em>between all class instances</em>.</p>\n<p>(NOTE: That is, unless a class instance decides to define its own version of <code>_i</code>! But if someone decides to do THAT, they deserve what they get, don't they???)</p>\n<p>Note that technically speaking, <code>i</code> is still not a 'static variable' at all; it is a <code>property</code>, which is a special type of descriptor. However, the <code>property</code> behavior is now equivalent to a (mutable) static variable synced across all class instances.</p>\n<h2>Immutable "Static Variables"</h2>\n<p>For immutable static variable behavior, simply omit the <code>property</code> setter:</p>\n<pre><code>class Test(object):\n\n _i = 3\n\n @property\n def i(self):\n return type(self)._i\n\n## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##\n## (except with separate methods for getting i) ##\n\nclass Test(object):\n\n _i = 3\n\n def get_i(self):\n return type(self)._i\n\n i = property(get_i)\n</code></pre>\n<p>Now attempting to set the instance <code>i</code> attribute will return an <code>AttributeError</code>:</p>\n<pre><code>x = Test()\nassert x.i == 3 # success\nx.i = 12 # ERROR\n</code></pre>\n<h2>One Gotcha to be Aware of</h2>\n<p>Note that the above methods only work with <em>instances</em> of your class - they will <strong>not</strong> work <em>when using the class itself</em>. So for example:</p>\n<pre><code>x = Test()\nassert x.i == Test.i # ERROR\n\n# x.i and Test.i are two different objects:\ntype(Test.i) # class 'property'\ntype(x.i) # class 'int'\n</code></pre>\n<p>The line <code>assert Test.i == x.i</code> produces an error, because the <code>i</code> attribute of <code>Test</code> and <code>x</code> are two different objects.</p>\n<p>Many people will find this surprising. However, it should not be. If we go back and inspect our <code>Test</code> class definition (the second version), we take note of this line:</p>\n<pre><code> i = property(get_i) \n</code></pre>\n<p>Clearly, the member <code>i</code> of <code>Test</code> must be a <code>property</code> object, which is the type of object returned from the <code>property</code> function.</p>\n<p>If you find the above confusing, you are most likely still thinking about it from the perspective of other languages (e.g. Java or c++). You should go study the <code>property</code> object, about the order in which Python attributes are returned, the descriptor protocol, and the method resolution order (MRO).</p>\n<p>I present a solution to the above 'gotcha' below; however I would suggest - strenuously - that you do not try to do something like the following until - at minimum - you thoroughly understand why <code>assert Test.i = x.i</code> causes an error.</p>\n<h2><em>REAL, ACTUAL</em> Static Variables - <code>Test.i == x.i</code></h2>\n<p>I present the (Python 3) solution below for informational purposes only. I am not endorsing it as a "good solution". I have my doubts as to whether emulating the static variable behavior of other languages in Python is ever actually necessary. However, regardless as to whether it is actually useful, the below should help further understanding of how Python works.</p>\n<p>UPDATE: this attempt <strong>is really pretty awful</strong>; if you insist on doing something like this (hint: please don't; Python is a very elegant language and shoe-horning it into behaving like another language is just not necessary), use the code in <a href=\"https://stackoverflow.com/a/36216964/2437514\">Ethan Furman's answer</a> instead.</p>\n<p><strong>Emulating static variable behavior of other languages using a metaclass</strong></p>\n<p>A metaclass is the class of a class. The default metaclass for all classes in Python (i.e., the "new style" classes post Python 2.3 I believe) is <code>type</code>. For example:</p>\n<pre><code>type(int) # class 'type'\ntype(str) # class 'type'\nclass Test(): pass\ntype(Test) # class 'type'\n</code></pre>\n<p>However, you can define your own metaclass like this:</p>\n<pre><code>class MyMeta(type): pass\n</code></pre>\n<p>And apply it to your own class like this (Python 3 only):</p>\n<pre><code>class MyClass(metaclass = MyMeta):\n pass\n\ntype(MyClass) # class MyMeta\n</code></pre>\n<p>Below is a metaclass I have created which attempts to emulate "static variable" behavior of other languages. It basically works by replacing the default getter, setter, and deleter with versions which check to see if the attribute being requested is a "static variable".</p>\n<p>A catalog of the "static variables" is stored in the <code>StaticVarMeta.statics</code> attribute. All attribute requests are initially attempted to be resolved using a substitute resolution order. I have dubbed this the "static resolution order", or "SRO". This is done by looking for the requested attribute in the set of "static variables" for a given class (or its parent classes). If the attribute does not appear in the "SRO", the class will fall back on the default attribute get/set/delete behavior (i.e., "MRO").</p>\n<pre><code>from functools import wraps\n\nclass StaticVarsMeta(type):\n '''A metaclass for creating classes that emulate the "static variable" behavior\n of other languages. I do not advise actually using this for anything!!!\n \n Behavior is intended to be similar to classes that use __slots__. However, "normal"\n attributes and __statics___ can coexist (unlike with __slots__). \n \n Example usage: \n \n class MyBaseClass(metaclass = StaticVarsMeta):\n __statics__ = {'a','b','c'}\n i = 0 # regular attribute\n a = 1 # static var defined (optional)\n \n class MyParentClass(MyBaseClass):\n __statics__ = {'d','e','f'}\n j = 2 # regular attribute\n d, e, f = 3, 4, 5 # Static vars\n a, b, c = 6, 7, 8 # Static vars (inherited from MyBaseClass, defined/re-defined here)\n \n class MyChildClass(MyParentClass):\n __statics__ = {'a','b','c'}\n j = 2 # regular attribute (redefines j from MyParentClass)\n d, e, f = 9, 10, 11 # Static vars (inherited from MyParentClass, redefined here)\n a, b, c = 12, 13, 14 # Static vars (overriding previous definition in MyParentClass here)'''\n statics = {}\n def __new__(mcls, name, bases, namespace):\n # Get the class object\n cls = super().__new__(mcls, name, bases, namespace)\n # Establish the "statics resolution order"\n cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))\n \n # Replace class getter, setter, and deleter for instance attributes\n cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)\n cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)\n cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)\n # Store the list of static variables for the class object\n # This list is permanent and cannot be changed, similar to __slots__\n try:\n mcls.statics[cls] = getattr(cls,'__statics__')\n except AttributeError:\n mcls.statics[cls] = namespace['__statics__'] = set() # No static vars provided\n # Check and make sure the statics var names are strings\n if any(not isinstance(static,str) for static in mcls.statics[cls]):\n typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__\n raise TypeError('__statics__ items must be strings, not {0}'.format(typ))\n # Move any previously existing, not overridden statics to the static var parent class(es)\n if len(cls.__sro__) > 1:\n for attr,value in namespace.items():\n if attr not in StaticVarsMeta.statics[cls] and attr != ['__statics__']:\n for c in cls.__sro__[1:]:\n if attr in StaticVarsMeta.statics[c]:\n setattr(c,attr,value)\n delattr(cls,attr)\n return cls\n def __inst_getattribute__(self, orig_getattribute):\n '''Replaces the class __getattribute__'''\n @wraps(orig_getattribute)\n def wrapper(self, attr):\n if StaticVarsMeta.is_static(type(self),attr):\n return StaticVarsMeta.__getstatic__(type(self),attr)\n else:\n return orig_getattribute(self, attr)\n return wrapper\n def __inst_setattr__(self, orig_setattribute):\n '''Replaces the class __setattr__'''\n @wraps(orig_setattribute)\n def wrapper(self, attr, value):\n if StaticVarsMeta.is_static(type(self),attr):\n StaticVarsMeta.__setstatic__(type(self),attr, value)\n else:\n orig_setattribute(self, attr, value)\n return wrapper\n def __inst_delattr__(self, orig_delattribute):\n '''Replaces the class __delattr__'''\n @wraps(orig_delattribute)\n def wrapper(self, attr):\n if StaticVarsMeta.is_static(type(self),attr):\n StaticVarsMeta.__delstatic__(type(self),attr)\n else:\n orig_delattribute(self, attr)\n return wrapper\n def __getstatic__(cls,attr):\n '''Static variable getter'''\n for c in cls.__sro__:\n if attr in StaticVarsMeta.statics[c]:\n try:\n return getattr(c,attr)\n except AttributeError:\n pass\n raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))\n def __setstatic__(cls,attr,value):\n '''Static variable setter'''\n for c in cls.__sro__:\n if attr in StaticVarsMeta.statics[c]:\n setattr(c,attr,value)\n break\n def __delstatic__(cls,attr):\n '''Static variable deleter'''\n for c in cls.__sro__:\n if attr in StaticVarsMeta.statics[c]:\n try:\n delattr(c,attr)\n break\n except AttributeError:\n pass\n raise AttributeError(cls.__name__ + " object has no attribute '{0}'".format(attr))\n def __delattr__(cls,attr):\n '''Prevent __sro__ attribute from deletion'''\n if attr == '__sro__':\n raise AttributeError('readonly attribute')\n super().__delattr__(attr)\n def is_static(cls,attr):\n '''Returns True if an attribute is a static variable of any class in the __sro__'''\n if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):\n return True\n return False\n</code></pre>\n"
},
{
"answer_id": 36216964,
"author": "Ethan Furman",
"author_id": 208880,
"author_profile": "https://Stackoverflow.com/users/208880",
"pm_score": 4,
"selected": false,
"text": "<p>It is possible to have <code>static</code> class variables, but probably not worth the effort.</p>\n\n<p>Here's a proof-of-concept written in Python 3 -- if any of the exact details are wrong the code can be tweaked to match just about whatever you mean by a <code>static variable</code>:</p>\n\n<hr>\n\n<pre><code>class Static:\n def __init__(self, value, doc=None):\n self.deleted = False\n self.value = value\n self.__doc__ = doc\n def __get__(self, inst, cls=None):\n if self.deleted:\n raise AttributeError('Attribute not set')\n return self.value\n def __set__(self, inst, value):\n self.deleted = False\n self.value = value\n def __delete__(self, inst):\n self.deleted = True\n\nclass StaticType(type):\n def __delattr__(cls, name):\n obj = cls.__dict__.get(name)\n if isinstance(obj, Static):\n obj.__delete__(name)\n else:\n super(StaticType, cls).__delattr__(name)\n def __getattribute__(cls, *args):\n obj = super(StaticType, cls).__getattribute__(*args)\n if isinstance(obj, Static):\n obj = obj.__get__(cls, cls.__class__)\n return obj\n def __setattr__(cls, name, val):\n # check if object already exists\n obj = cls.__dict__.get(name)\n if isinstance(obj, Static):\n obj.__set__(name, val)\n else:\n super(StaticType, cls).__setattr__(name, val)\n</code></pre>\n\n<p>and in use:</p>\n\n<pre><code>class MyStatic(metaclass=StaticType):\n \"\"\"\n Testing static vars\n \"\"\"\n a = Static(9)\n b = Static(12)\n c = 3\n\nclass YourStatic(MyStatic):\n d = Static('woo hoo')\n e = Static('doo wop')\n</code></pre>\n\n<p>and some tests:</p>\n\n<pre><code>ms1 = MyStatic()\nms2 = MyStatic()\nms3 = MyStatic()\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\nassert ms1.c == ms2.c == ms3.c == MyStatic.c\nms1.a = 77\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nms2.b = 99\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\nMyStatic.a = 101\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nMyStatic.b = 139\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\ndel MyStatic.b\nfor inst in (ms1, ms2, ms3):\n try:\n getattr(inst, 'b')\n except AttributeError:\n pass\n else:\n print('AttributeError not raised on %r' % attr)\nms1.c = 13\nms2.c = 17\nms3.c = 19\nassert ms1.c == 13\nassert ms2.c == 17\nassert ms3.c == 19\nMyStatic.c = 43\nassert ms1.c == 13\nassert ms2.c == 17\nassert ms3.c == 19\n\nys1 = YourStatic()\nys2 = YourStatic()\nys3 = YourStatic()\nMyStatic.b = 'burgler'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\nassert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b\nassert ys1.d == ys2.d == ys3.d == YourStatic.d\nassert ys1.e == ys2.e == ys3.e == YourStatic.e\nys1.a = 'blah'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\nys2.b = 'kelp'\nassert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b\nys1.d = 'fee'\nassert ys1.d == ys2.d == ys3.d == YourStatic.d\nys2.e = 'fie'\nassert ys1.e == ys2.e == ys3.e == YourStatic.e\nMyStatic.a = 'aargh'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\n</code></pre>\n"
},
{
"answer_id": 41413059,
"author": "jmunsch",
"author_id": 2026508,
"author_profile": "https://Stackoverflow.com/users/2026508",
"pm_score": 2,
"selected": false,
"text": "<h1>Static Variables in Class factory python3.6</h1>\n<p>For anyone using a class factory with <strong>python3.6</strong> and up use the <code>nonlocal</code> keyword to add it to the scope / context of the class being created like so:</p>\n<pre><code>>>> def SomeFactory(some_var=None):\n... class SomeClass(object):\n... nonlocal some_var\n... def print():\n... print(some_var)\n... return SomeClass\n... \n>>> SomeFactory(some_var="hello world").print()\nhello world\n</code></pre>\n"
},
{
"answer_id": 42392246,
"author": "Mari Selvan",
"author_id": 5483135,
"author_profile": "https://Stackoverflow.com/users/5483135",
"pm_score": 3,
"selected": false,
"text": "<p>Absolutely Yes,\n Python by itself don't have any static data member explicitly, but We can have by doing so </p>\n\n<pre><code>class A:\n counter =0\n def callme (self):\n A.counter +=1\n def getcount (self):\n return self.counter \n>>> x=A()\n>>> y=A()\n>>> print(x.getcount())\n>>> print(y.getcount())\n>>> x.callme() \n>>> print(x.getcount())\n>>> print(y.getcount())\n</code></pre>\n\n<p>output</p>\n\n<pre><code>0\n0\n1\n1\n</code></pre>\n\n<p>explanation</p>\n\n<pre><code>here object (x) alone increment the counter variable\nfrom 0 to 1 by not object y. But result it as \"static counter\"\n</code></pre>\n"
},
{
"answer_id": 46335281,
"author": "Davis Herring",
"author_id": 8586227,
"author_profile": "https://Stackoverflow.com/users/8586227",
"pm_score": 4,
"selected": false,
"text": "<p>One very interesting point about Python's attribute lookup is that it can be used to create \"<a href=\"https://en.wikipedia.org/wiki/Virtual_function\" rel=\"noreferrer\">virtual</a> variables\":</p>\n\n<pre><code>class A(object):\n\n label=\"Amazing\"\n\n def __init__(self,d): \n self.data=d\n\n def say(self): \n print(\"%s %s!\"%(self.label,self.data))\n\nclass B(A):\n label=\"Bold\" # overrides A.label\n\nA(5).say() # Amazing 5!\nB(3).say() # Bold 3!\n</code></pre>\n\n<p>Normally there aren't any assignments to these after they are created. Note that the lookup uses <code>self</code> because, although <code>label</code> is static in the sense of not being associated with a <em>particular</em> instance, the value still depends on the (class of the) instance.</p>\n"
},
{
"answer_id": 53775598,
"author": "Shagun Pruthi",
"author_id": 6136001,
"author_profile": "https://Stackoverflow.com/users/6136001",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, definitely possible to write static variables and methods in python.</p>\n\n<p><strong>Static Variables :</strong>\nVariable declared at class level are called static variable which can be accessed directly using class name.</p>\n\n<pre><code> >>> class A:\n ...my_var = \"shagun\"\n\n >>> print(A.my_var)\n shagun\n</code></pre>\n\n<p><strong>Instance variables:</strong> Variables that are related and accessed by instance of a class are instance variables.</p>\n\n<pre><code> >>> a = A()\n >>> a.my_var = \"pruthi\"\n >>> print(A.my_var,a.my_var)\n shagun pruthi\n</code></pre>\n\n<p><strong>Static Methods:</strong> Similar to variables, static methods can be accessed directly using class Name. No need to create an instance. </p>\n\n<p>But keep in mind, a static method cannot call a non-static method in python.</p>\n\n<pre><code> >>> class A:\n ... @staticmethod\n ... def my_static_method():\n ... print(\"Yippey!!\")\n ... \n >>> A.my_static_method()\n Yippey!!\n</code></pre>\n"
},
{
"answer_id": 58683325,
"author": "Jay",
"author_id": 5387972,
"author_profile": "https://Stackoverflow.com/users/5387972",
"pm_score": 2,
"selected": false,
"text": "<p>You can use a list or a dictionary to get \"static behavior\" between instances.</p>\n\n<pre><code>class Fud:\n\n class_vars = {'origin_open':False}\n\n def __init__(self, origin = True):\n self.origin = origin\n self.opened = True\n if origin:\n self.class_vars['origin_open'] = True\n\n\n def make_another_fud(self):\n ''' Generating another Fud() from the origin instance '''\n\n return Fud(False)\n\n\n def close(self):\n self.opened = False\n if self.origin:\n self.class_vars['origin_open'] = False\n\n\nfud1 = Fud()\nfud2 = fud1.make_another_fud()\n\nprint (f\"is this the original fud: {fud2.origin}\")\nprint (f\"is the original fud open: {fud2.class_vars['origin_open']}\")\n# is this the original fud: False\n# is the original fud open: True\n\nfud1.close()\n\nprint (f\"is the original fud open: {fud2.class_vars['origin_open']}\")\n# is the original fud open: False\n</code></pre>\n"
},
{
"answer_id": 61080153,
"author": "Christopher Hoffman",
"author_id": 7497211,
"author_profile": "https://Stackoverflow.com/users/7497211",
"pm_score": 2,
"selected": false,
"text": "<p>So this is probably a hack, but I've been using <code>eval(str)</code> to obtain an static object, kind of a contradiction, in python 3.</p>\n\n<p>There is an Records.py file that has nothing but <code>class</code> objects defined with static methods and constructors that save some arguments. Then from another .py file I <code>import Records</code> but i need to dynamically select each object and then instantiate it on demand according to the type of data being read in.</p>\n\n<p>So where <code>object_name = 'RecordOne'</code> or the class name, I call <code>cur_type = eval(object_name)</code> and then to instantiate it you do <code>cur_inst = cur_type(args)</code>\nHowever before you instantiate you can call static methods from <code>cur_type.getName()</code> for example, kind of like abstract base class implementation or whatever the goal is. However in the backend, it's probably instantiated in python and is not truly static, because eval is returning an object....which must have been instantiated....that gives static like behavior.</p>\n"
},
{
"answer_id": 61805905,
"author": "Winter Squad",
"author_id": 8566159,
"author_profile": "https://Stackoverflow.com/users/8566159",
"pm_score": 2,
"selected": false,
"text": "<p>If you are attempting to share a static variable for, by example, increasing it across other instances, something like this script works fine:</p>\n\n<pre><code># -*- coding: utf-8 -*-\nclass Worker:\n id = 1\n\n def __init__(self):\n self.name = ''\n self.document = ''\n self.id = Worker.id\n Worker.id += 1\n\n def __str__(self):\n return u\"{}.- {} {}\".format(self.id, self.name, self.document).encode('utf8')\n\n\nclass Workers:\n def __init__(self):\n self.list = []\n\n def add(self, name, doc):\n worker = Worker()\n worker.name = name\n worker.document = doc\n self.list.append(worker)\n\n\nif __name__ == \"__main__\":\n workers = Workers()\n for item in (('Fiona', '0009898'), ('Maria', '66328191'), (\"Sandra\", '2342184'), ('Elvira', '425872')):\n workers.add(item[0], item[1])\n for worker in workers.list:\n print(worker)\n print(\"next id: %i\" % Worker.id)\n</code></pre>\n"
},
{
"answer_id": 62960717,
"author": "ganja",
"author_id": 13864415,
"author_profile": "https://Stackoverflow.com/users/13864415",
"pm_score": 1,
"selected": false,
"text": "<p>Put it this way the static variable is created when a user-defined a class come into existence and the define a static variable it should follow the keyword self,</p>\n<pre><code>class Student:\n\n the correct way of static declaration\n i = 10\n\n incorrect\n self.i = 10\n</code></pre>\n"
},
{
"answer_id": 65918726,
"author": "Vlad Bezden",
"author_id": 30038,
"author_profile": "https://Stackoverflow.com/users/30038",
"pm_score": 4,
"selected": false,
"text": "<p>@dataclass definitions provide class-level names that are used to define the instance variables and the initialization method, <code>__init__()</code>. If you want class-level variable in <code>@dataclass</code> you should use <a href=\"https://docs.python.org/3/library/typing.html#typing.ClassVar\" rel=\"noreferrer\"><code>typing.ClassVar</code></a> type hint. The <code>ClassVar</code> type's parameters define the class-level variable's type.</p>\n<pre><code>from typing import ClassVar\nfrom dataclasses import dataclass\n\n@dataclass\nclass Test:\n i: ClassVar[int] = 10\n x: int\n y: int\n \n def __repr__(self):\n return f"Test({self.x=}, {self.y=}, {Test.i=})"\n</code></pre>\n<p>Usage examples:</p>\n<pre><code>> test1 = Test(5, 6)\n> test2 = Test(10, 11)\n\n> test1\nTest(self.x=5, self.y=6, Test.i=10)\n> test2\nTest(self.x=10, self.y=11, Test.i=10)\n</code></pre>\n"
},
{
"answer_id": 66255775,
"author": "Sunil Garg",
"author_id": 2172547,
"author_profile": "https://Stackoverflow.com/users/2172547",
"pm_score": 0,
"selected": false,
"text": "<p>Not like the <code>@staticmethod</code> but class variables are static method of class and are shared with all the instances.</p>\n<p>Now you can access it like</p>\n<pre><code>instance = MyClass()\nprint(instance.i)\n</code></pre>\n<p>or</p>\n<pre><code>print(MyClass.i)\n</code></pre>\n<p>you have to assign the value to these variables</p>\n<p>I was trying</p>\n<pre><code>class MyClass:\n i: str\n</code></pre>\n<p>and assigning the value in one method call, in that case it will not work and will throw an error</p>\n<pre><code>i is not attribute of MyClass\n</code></pre>\n"
},
{
"answer_id": 68682495,
"author": "alda78",
"author_id": 2161600,
"author_profile": "https://Stackoverflow.com/users/2161600",
"pm_score": 4,
"selected": false,
"text": "<p>With Object datatypes it is possible. But with primitive types like <code>bool</code>, <code>int</code>, <code>float</code> or <code>str</code> bahaviour is different from other OOP languages. Because in inherited class static attribute does not exist. If attribute does not exists in inherited class, Python start to look for it in parent class. If found in parent class, its value will be returned. When you decide to change value in inherited class, static attribute will be created in runtime. In next time of reading inherited static attribute its value will be returned, bacause it is already defined. Objects (lists, dicts) works as a references so it is safe to use them as static attributes and inherit them. Object address is not changed when you change its attribute values.</p>\n<p>Example with integer data type:</p>\n<pre><code>class A:\n static = 1\n\n\nclass B(A):\n pass\n\n\nprint(f"int {A.static}") # get 1 correctly\nprint(f"int {B.static}") # get 1 correctly\n\nA.static = 5\nprint(f"int {A.static}") # get 5 correctly\nprint(f"int {B.static}") # get 5 correctly\n\nB.static = 6\nprint(f"int {A.static}") # expected 6, but get 5 incorrectly\nprint(f"int {B.static}") # get 6 correctly\n\nA.static = 7\nprint(f"int {A.static}") # get 7 correctly\nprint(f"int {B.static}") # get unchanged 6\n</code></pre>\n<p>Solution based on <a href=\"https://pypi.org/project/refdatatypes/\" rel=\"noreferrer\">refdatatypes</a> library:</p>\n<pre><code>from refdatatypes.refint import RefInt\n\n\nclass AAA:\n static = RefInt(1)\n\n\nclass BBB(AAA):\n pass\n\n\nprint(f"refint {AAA.static.value}") # get 1 correctly\nprint(f"refint {BBB.static.value}") # get 1 correctly\n\nAAA.static.value = 5\nprint(f"refint {AAA.static.value}") # get 5 correctly\nprint(f"refint {BBB.static.value}") # get 5 correctly\n\nBBB.static.value = 6\nprint(f"refint {AAA.static.value}") # get 6 correctly\nprint(f"refint {BBB.static.value}") # get 6 correctly\n\nAAA.static.value = 7\nprint(f"refint {AAA.static.value}") # get 7 correctly\nprint(f"refint {BBB.static.value}") # get 7 correctly\n</code></pre>\n"
},
{
"answer_id": 69723203,
"author": "HIMANSHU PANDEY",
"author_id": 14952627,
"author_profile": "https://Stackoverflow.com/users/14952627",
"pm_score": 3,
"selected": false,
"text": "<p>Summarizing others' answers and adding, there are many ways to declare Static Methods or Variables in <strong>python</strong>.<br></p>\n<h1>1. Using <a href=\"https://docs.python.org/3/library/functions.html#staticmethod\" rel=\"noreferrer\">staticmethod()</a> as a decorator:</h1>\n<p>One can simply put a decorator above a method(function) declared to make it a static method. For eg.<br></p>\n<pre><code>class Calculator:\n @staticmethod\n def multiply(n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 * n2 * Res\n\nprint(Calculator.multiply(1, 2, 3, 4)) # 24\n</code></pre>\n<h1>2. Using <a href=\"https://docs.python.org/3/library/functions.html#staticmethod\" rel=\"noreferrer\">staticmethod()</a> as a parameter function:</h1>\n<p>This method can receive an argument which is of function type, and it returns a static version of the function passed. For eg.<br></p>\n<pre><code>class Calculator:\n def add(n1, n2, *args):\n return n1 + n2 + sum(args)\n\nCalculator.add = staticmethod(Calculator.add)\nprint(Calculator.add(1, 2, 3, 4)) # 10\n</code></pre>\n<h1>3. Using <a href=\"https://docs.python.org/3/library/functions.html#classmethod\" rel=\"noreferrer\">classmethod()</a> as a decorator:</h1>\n<p>@classmethod has similar effect on a function as @staticmethod has, but\nthis time, an additional argument is needed to be accepted in the function (similar to self parameter for instance variables). For eg.<br></p>\n<pre><code>class Calculator:\n num = 0\n def __init__(self, digits) -> None:\n Calculator.num = int(''.join(digits))\n\n @classmethod\n def get_digits(cls, num):\n digits = list(str(num))\n calc = cls(digits)\n return calc.num\n\nprint(Calculator.get_digits(314159)) # 314159\n</code></pre>\n<h1>4. Using <a href=\"https://docs.python.org/3/library/functions.html#classmethod\" rel=\"noreferrer\">classmethod()</a> as a parameter function:</h1>\n<p>@classmethod can also be used as a parameter function, in case one doesn't want to modify class definition. For eg.<br></p>\n<pre><code>class Calculator:\n def divide(cls, n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 / n2 / Res\n\nCalculator.divide = classmethod(Calculator.divide)\n\nprint(Calculator.divide(15, 3, 5)) # 1.0\n</code></pre>\n<h1>5. Direct declaration</h1>\n<p>A method/variable declared outside all other methods, but inside a class is automatically static.<br></p>\n<pre><code>class Calculator: \n def subtract(n1, n2, *args):\n return n1 - n2 - sum(args)\n\nprint(Calculator.subtract(10, 2, 3, 4)) # 1\n</code></pre>\n<h1>The whole program<br></h1>\n<pre><code>class Calculator:\n num = 0\n def __init__(self, digits) -> None:\n Calculator.num = int(''.join(digits))\n \n \n @staticmethod\n def multiply(n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 * n2 * Res\n\n\n def add(n1, n2, *args):\n return n1 + n2 + sum(args)\n \n\n @classmethod\n def get_digits(cls, num):\n digits = list(str(num))\n calc = cls(digits)\n return calc.num\n\n\n def divide(cls, n1, n2, *args):\n Res = 1\n for num in args: Res *= num\n return n1 / n2 / Res\n\n\n def subtract(n1, n2, *args):\n return n1 - n2 - sum(args)\n \n\n\n\nCalculator.add = staticmethod(Calculator.add)\nCalculator.divide = classmethod(Calculator.divide)\n\nprint(Calculator.multiply(1, 2, 3, 4)) # 24\nprint(Calculator.add(1, 2, 3, 4)) # 10\nprint(Calculator.get_digits(314159)) # 314159\nprint(Calculator.divide(15, 3, 5)) # 1.0\nprint(Calculator.subtract(10, 2, 3, 4)) # 1\n</code></pre>\n<p>Refer to <a href=\"https://www.python.org/doc/versions/\" rel=\"noreferrer\">Python Documentation</a> for mastering OOP in python.</p>\n"
},
{
"answer_id": 72141879,
"author": "MusicalNinja",
"author_id": 3305998,
"author_profile": "https://Stackoverflow.com/users/3305998",
"pm_score": 0,
"selected": false,
"text": "<h2>Class variable and allow for subclassing</h2>\n<p>Assuming you are not looking for a <em>truly</em> static variable but rather something pythonic that will do the same sort of job for consenting adults, then use a class variable.\nThis will provide you with a variable which all instances can access (and update)</p>\n<p><strong>Beware: Many of the other answers which use a class variable will break subclassing.</strong> You should avoid referencing the class directly by name.</p>\n<pre><code>from contextlib import contextmanager\n\nclass Sheldon(object):\n foo = 73\n\n def __init__(self, n):\n self.n = n\n\n def times(self):\n cls = self.__class__\n return cls.foo * self.n\n #self.foo * self.n would give the same result here but is less readable\n # it will also create a local variable which will make it easier to break your code\n \n def updatefoo(self):\n cls = self.__class__\n cls.foo *= self.n\n #self.foo *= self.n will not work here\n # assignment will try to create a instance variable foo\n\n @classmethod\n @contextmanager\n def reset_after_test(cls):\n originalfoo = cls.foo\n yield\n cls.foo = originalfoo\n #if you don't do this then running a full test suite will fail\n #updates to foo in one test will be kept for later tests\n</code></pre>\n<p>will give you the same functionality as using <code>Sheldon.foo</code> to address the variable and will pass tests like these:</p>\n<pre><code>def test_times():\n with Sheldon.reset_after_test():\n s = Sheldon(2)\n assert s.times() == 146\n\ndef test_update():\n with Sheldon.reset_after_test():\n s = Sheldon(2)\n s.updatefoo()\n assert Sheldon.foo == 146\n\ndef test_two_instances():\n with Sheldon.reset_after_test():\n s = Sheldon(2)\n s3 = Sheldon(3)\n assert s.times() == 146\n assert s3.times() == 219\n s3.updatefoo()\n assert s.times() == 438\n</code></pre>\n<p>It will also allow someone else to simply:</p>\n<pre><code>class Douglas(Sheldon):\n foo = 42\n</code></pre>\n<p>which will also work:</p>\n<pre><code>def test_subclassing():\n with Sheldon.reset_after_test(), Douglas.reset_after_test():\n s = Sheldon(2)\n d = Douglas(2)\n assert d.times() == 84\n assert s.times() == 146\n d.updatefoo()\n assert d.times() == 168 #Douglas.Foo was updated\n assert s.times() == 146 #Seldon.Foo is still 73\n\ndef test_subclassing_reset():\n with Sheldon.reset_after_test(), Douglas.reset_after_test():\n s = Sheldon(2)\n d = Douglas(2)\n assert d.times() == 84 #Douglas.foo was reset after the last test\n assert s.times() == 146 #and so was Sheldon.foo\n</code></pre>\n<p>For great advice on things to watch out for when creating classes check out Raymond Hettinger's video <a href=\"https://www.youtube.com/watch?v=HTLu2DFOdTg\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=HTLu2DFOdTg</a></p>\n"
},
{
"answer_id": 74501446,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "<p>You can create <strong>the class variable <code>x</code></strong>, <strong>the instance variable <code>name</code></strong>, <strong>the instance method <code>test1(self)</code></strong>, <strong>the class method <code>test2(cls)</code></strong> and <strong>the static method <code>test3()</code></strong> as shown below:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Person:\n x = "Hello" # Class variable\n\n def __init__(self, name):\n self.name = name # Instance variable\n \n def test1(self): # Instance method\n print("Test1")\n\n @classmethod\n def test2(cls): # Class method\n print("Test2")\n \n @staticmethod\n def test3(): # Static method\n print("Test3")\n</code></pre>\n<p>I explain about <strong>class variable</strong> in <a href=\"https://stackoverflow.com/questions/707380/how-to-access-static-class-variables-in-python/74493657#74493657\"><strong>my answer</strong></a> and <strong>class method</strong> and <strong>static method</strong> in <a href=\"https://stackoverflow.com/questions/136097/classmethod-vs-staticmethod-in-python/74470227#74470227\"><strong>my answer</strong></a> and <strong>instance method</strong> in <a href=\"https://stackoverflow.com/questions/46230482/what-is-an-instance-method-in-python/74482579#74482579\"><strong>my answer</strong></a>.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2246/"
]
| How do I create class (i.e. [static](https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods)) variables or methods in Python? | Variables declared inside the class definition, but not inside a method are class or static variables:
```
>>> class MyClass:
... i = 3
...
>>> MyClass.i
3
```
As @[millerdev](https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067) points out, this creates a class-level `i` variable, but this is distinct from any instance-level `i` variable, so you could have
```
>>> m = MyClass()
>>> m.i = 4
>>> MyClass.i, m.i
>>> (3, 4)
```
This is different from C++ and Java, but not so different from C#, where a static member can't be accessed using a reference to an instance.
See [what the Python tutorial has to say on the subject of classes and class objects](https://docs.python.org/3/tutorial/classes.html#class-objects).
@Steve Johnson has already answered regarding [static methods](http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod), also documented under ["Built-in Functions" in the Python Library Reference](https://docs.python.org/3/library/functions.html#staticmethod).
```
class C:
@staticmethod
def f(arg1, arg2, ...): ...
```
@beidy recommends [classmethod](https://docs.python.org/3/library/functions.html#classmethod)s over staticmethod, as the method then receives the class type as the first argument. |
68,651 | <p>If I pass PHP variables with <code>.</code> in their names via $_GET PHP auto-replaces them with <code>_</code> characters. For example:</p>
<pre><code><?php
echo "url is ".$_SERVER['REQUEST_URI']."<p>";
echo "x.y is ".$_GET['x.y'].".<p>";
echo "x_y is ".$_GET['x_y'].".<p>";
</code></pre>
<p>... outputs the following:</p>
<pre><code>url is /SpShipTool/php/testGetUrl.php?x.y=a.b
x.y is .
x_y is a.b.
</code></pre>
<p>... my question is this: is there <strong>any</strong> way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this</p>
<p>PHP version I'm running with is 5.2.4-2ubuntu5.3.</p>
| [
{
"answer_id": 68710,
"author": "Jeremy Privett",
"author_id": 560,
"author_profile": "https://Stackoverflow.com/users/560",
"pm_score": 2,
"selected": false,
"text": "<p>The reason this happens is because of PHP's old register_globals functionality. The . character is not a valid character in a variable name, so PHP coverts it to an underscore in order to make sure there's compatibility.</p>\n\n<p>In short, it's not a good practice to do periods in URL variables.</p>\n"
},
{
"answer_id": 68742,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 7,
"selected": true,
"text": "<p>Here's PHP.net's explanation of why it does it:</p>\n<blockquote>\n<h3>Dots in incoming variable names</h3>\n<p>Typically, PHP does not alter the\nnames of variables when they are\npassed into a script. However, it\nshould be noted that the dot (period,\nfull stop) is not a valid character in\na PHP variable name. For the reason,\nlook at it:</p>\n<pre><code><?php\n$varname.ext; /* invalid variable name */\n?>\n</code></pre>\n<p>Now, what\nthe parser sees is a variable named\n$varname, followed by the string\nconcatenation operator, followed by\nthe barestring (i.e. unquoted string\nwhich doesn't match any known key or\nreserved words) 'ext'. Obviously, this\ndoesn't have the intended result.</p>\n<p>For this reason, it is important to\nnote that PHP will automatically\nreplace any dots in incoming variable\nnames with underscores.</p>\n</blockquote>\n<p>That's from <a href=\"http://ca.php.net/variables.external\" rel=\"noreferrer\">http://ca.php.net/variables.external</a>.</p>\n<p>Also, according to <a href=\"http://ca.php.net/manual/en/language.variables.external.php#81080\" rel=\"noreferrer\">this comment</a> these other characters are converted to underscores:</p>\n<blockquote>\n<p>The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):</p>\n<ul>\n<li>chr(32) ( ) (space)</li>\n<li>chr(46) (.) (dot)</li>\n<li>chr(91) ([) (open square bracket)</li>\n<li>chr(128) - chr(159) (various)</li>\n</ul>\n</blockquote>\n<p>So it looks like you're stuck with it, so you'll have to convert the underscores back to dots in your script using <a href=\"https://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays#68667\">dawnerd's suggestion</a> (I'd just use <a href=\"http://php.net/str_replace\" rel=\"noreferrer\">str_replace</a> though.)</p>\n"
},
{
"answer_id": 1939911,
"author": "crb",
"author_id": 51691,
"author_profile": "https://Stackoverflow.com/users/51691",
"pm_score": 6,
"selected": false,
"text": "<p>Long-since answered question, but there is actually a better answer (or work-around). PHP lets you at the <a href=\"http://php.net/manual/en/wrappers.php.php\" rel=\"noreferrer\">raw input stream</a>, so you can do something like this:</p>\n\n<pre><code>$query_string = file_get_contents('php://input');\n</code></pre>\n\n<p>which will give you the $_POST array in query string format, periods as they should be. </p>\n\n<p>You can then parse it if you need (as per <a href=\"http://www.php.net/manual/en/language.variables.external.php#94607\" rel=\"noreferrer\">POSTer's comment</a>)</p>\n\n<pre><code><?php\n// Function to fix up PHP's messing up input containing dots, etc.\n// `$source` can be either 'POST' or 'GET'\nfunction getRealInput($source) {\n $pairs = explode(\"&\", $source == 'POST' ? file_get_contents(\"php://input\") : $_SERVER['QUERY_STRING']);\n $vars = array();\n foreach ($pairs as $pair) {\n $nv = explode(\"=\", $pair);\n $name = urldecode($nv[0]);\n $value = urldecode($nv[1]);\n $vars[$name] = $value;\n }\n return $vars;\n}\n\n// Wrapper functions specifically for GET and POST:\nfunction getRealGET() { return getRealInput('GET'); }\nfunction getRealPOST() { return getRealInput('POST'); }\n?>\n</code></pre>\n\n<p>Hugely useful for OpenID parameters, which contain both '.' and '_', each with a certain meaning!</p>\n"
},
{
"answer_id": 4927461,
"author": "Jason",
"author_id": 607256,
"author_profile": "https://Stackoverflow.com/users/607256",
"pm_score": 2,
"selected": false,
"text": "<p>My solution to this problem was quick and dirty, but I still like it. I simply wanted to post a list of filenames that were checked on the form. I used <code>base64_encode</code> to encode the filenames within the markup and then just decoded it with <code>base64_decode</code> prior to using them.</p>\n"
},
{
"answer_id": 14432765,
"author": "Ja͢ck",
"author_id": 1338292,
"author_profile": "https://Stackoverflow.com/users/1338292",
"pm_score": 3,
"selected": false,
"text": "<p>This happens because a period is an invalid character in a variable's name, the <a href=\"http://php.net/variables.external#language.variables.external.dot-in-names\" rel=\"nofollow\">reason</a> for which lies very deep in the implementation of PHP, so there are no easy fixes (yet). </p>\n\n<p>In the meantime you can work around this issue by:</p>\n\n<ol>\n<li>Accessing the raw query data via either <code>php://input</code> for POST data or <code>$_SERVER['QUERY_STRING']</code> for GET data</li>\n<li>Using a conversion function.</li>\n</ol>\n\n<p>The below conversion function (PHP >= 5.4) encodes the names of each key-value pair into a hexadecimal representation and then performs a regular <code>parse_str()</code>; once done, it reverts the hexadecimal names back into their original form:</p>\n\n<pre><code>function parse_qs($data)\n{\n $data = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function($match) {\n return bin2hex(urldecode($match[0]));\n }, $data);\n\n parse_str($data, $values);\n\n return array_combine(array_map('hex2bin', array_keys($values)), $values);\n}\n\n// work with the raw query string\n$data = parse_qs($_SERVER['QUERY_STRING']);\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>// handle posted data (this only works with application/x-www-form-urlencoded)\n$data = parse_qs(file_get_contents('php://input'));\n</code></pre>\n"
},
{
"answer_id": 18028493,
"author": "El Yobo",
"author_id": 217588,
"author_profile": "https://Stackoverflow.com/users/217588",
"pm_score": 2,
"selected": false,
"text": "<p>After looking at Rok's solution I have come up with a version which addresses the limitations in my answer below, crb's above and Rok's solution as well. See a <a href=\"/questions/68651/get-php-to-stop-replacing-characters-in-get-or-post-arrays/18163411#18163411\">my improved version</a>.</p>\n\n<hr>\n\n<p>@crb's answer <a href=\"/questions/68651/get-php-to-stop-replacing-characters-in-get-or-post-arrays#1939911\">above</a> is a good start, but there are a couple of problems.</p>\n\n<ul>\n<li>It reprocesses everything, which is overkill; only those fields that have a \".\" in the name need to be reprocessed.</li>\n<li>It fails to handle arrays in the same way that native PHP processing does, e.g. for keys like \"foo.bar[]\".</li>\n</ul>\n\n<p>The solution below addresses both of these problems now (note that it has been updated since originally posted). This is about 50% faster than my answer above in my testing, but will not handle situations where the data has the same key (or a key which gets extracted the same, e.g. foo.bar and foo_bar are both extracted as foo_bar).</p>\n\n<pre><code><?php\n\npublic function fix2(&$target, $source, $keep = false) { \n if (!$source) { \n return; \n } \n preg_match_all( \n '/ \n # Match at start of string or & \n (?:^|(?<=&)) \n # Exclude cases where the period is in brackets, e.g. foo[bar.blarg]\n [^=&\\[]* \n # Affected cases: periods and spaces \n (?:\\.|%20) \n # Keep matching until assignment, next variable, end of string or \n # start of an array \n [^=&\\[]* \n /x', \n $source, \n $matches \n ); \n\n foreach (current($matches) as $key) { \n $key = urldecode($key); \n $badKey = preg_replace('/(\\.| )/', '_', $key); \n\n if (isset($target[$badKey])) { \n // Duplicate values may have already unset this \n $target[$key] = $target[$badKey]; \n\n if (!$keep) { \n unset($target[$badKey]); \n } \n } \n } \n} \n</code></pre>\n"
},
{
"answer_id": 18163411,
"author": "El Yobo",
"author_id": 217588,
"author_profile": "https://Stackoverflow.com/users/217588",
"pm_score": 3,
"selected": false,
"text": "<p>This approach is an altered version of Rok Kralj's, but with some tweaking to work, to improve efficiency (avoids unnecessary callbacks, encoding and decoding on unaffected keys) and to correctly handle array keys.</p>\n\n<p>A <a href=\"https://gist.github.com/elyobo/6200838\" rel=\"noreferrer\">gist with tests</a> is available and any feedback or suggestions are welcome here or there.</p>\n\n<pre><code>public function fix(&$target, $source, $keep = false) { \n if (!$source) { \n return; \n } \n $keys = array(); \n\n $source = preg_replace_callback( \n '/ \n # Match at start of string or & \n (?:^|(?<=&)) \n # Exclude cases where the period is in brackets, e.g. foo[bar.blarg]\n [^=&\\[]* \n # Affected cases: periods and spaces \n (?:\\.|%20) \n # Keep matching until assignment, next variable, end of string or \n # start of an array \n [^=&\\[]* \n /x', \n function ($key) use (&$keys) { \n $keys[] = $key = base64_encode(urldecode($key[0])); \n return urlencode($key); \n }, \n $source \n ); \n\n if (!$keep) { \n $target = array(); \n } \n\n parse_str($source, $data); \n foreach ($data as $key => $val) { \n // Only unprocess encoded keys \n if (!in_array($key, $keys)) { \n $target[$key] = $val; \n continue; \n } \n\n $key = base64_decode($key); \n $target[$key] = $val; \n\n if ($keep) { \n // Keep a copy in the underscore key version \n $key = preg_replace('/(\\.| )/', '_', $key); \n $target[$key] = $val; \n } \n } \n} \n</code></pre>\n"
},
{
"answer_id": 18209799,
"author": "Rok Kralj",
"author_id": 924109,
"author_profile": "https://Stackoverflow.com/users/924109",
"pm_score": 4,
"selected": false,
"text": "<p>Do you want a solution that is <strong>standards compliant,</strong> and works with <strong>deep arrays</strong> (for example: <code>?param[2][5]=10</code>) ?</p>\n<p>To fix all possible sources of this problem, you can apply at the very top of your PHP code:</p>\n<pre><code>$_GET = fix( $_SERVER['QUERY_STRING'] );\n$_POST = fix( file_get_contents('php://input') );\n$_COOKIE = fix( $_SERVER['HTTP_COOKIE'] );\n</code></pre>\n<p>The working of this function is a neat idea that I came up during my summer vacation of 2013. Do not be discouraged by a simple regex, it just grabs all query names, encodes them (so dots are preserved), and then uses a normal <code>parse_str()</code> function.</p>\n<pre><code>function fix($source) {\n $source = preg_replace_callback(\n '/(^|(?<=&))[^=[&]+/',\n function($key) { return bin2hex(urldecode($key[0])); },\n $source\n );\n\n parse_str($source, $post);\n \n $result = array();\n foreach ($post as $key => $val) {\n $result[hex2bin($key)] = $val;\n }\n return $result;\n}\n</code></pre>\n"
},
{
"answer_id": 18244502,
"author": "humbletim",
"author_id": 1684079,
"author_profile": "https://Stackoverflow.com/users/1684079",
"pm_score": 2,
"selected": false,
"text": "<p>If looking for <strong>any</strong> way to <em>literally</em> get PHP to stop replacing '.' characters in $_GET or $_POST arrays, then one such way is to modify PHP's source (and in this case it is relatively straightforward).</p>\n\n<p><em>WARNING: Modifying PHP C source is an advanced option!</em></p>\n\n<p>Also see this <a href=\"https://bugs.php.net/bug.php?id=45272\" rel=\"nofollow\">PHP bug report</a> which suggests the same modification.</p>\n\n<p>To explore you'll need to:</p>\n\n<ul>\n<li>download <a href=\"http://www.php.net/downloads.php\" rel=\"nofollow\">PHP's C source code</a></li>\n<li>disable the <code>.</code> replacement check</li>\n<li><em>./configure</em>, <em>make</em> and deploy your customized build of PHP</li>\n</ul>\n\n<p>The source change itself is trivial and involves updating just <a href=\"https://github.com/php/php-src/blob/f01c295d/main/php_variables.c#L94\" rel=\"nofollow\">one half of one line</a> in <code>main/php_variables.c</code>:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>....\n/* ensure that we don't have spaces or dots in the variable name (not binary safe) */\nfor (p = var; *p; p++) {\n if (*p == ' ' /*|| *p == '.'*/) {\n *p='_';\n....\n</code></pre>\n\n<p><em>Note: compared to original <code>|| *p == '.'</code> has been commented-out</em></p>\n\n<hr>\n\n<p>Example Output:</p>\n\n<p>given a QUERY_STRING of <code>a.a[]=bb&a.a[]=BB&c%20c=dd</code>,\nrunning <code><?php print_r($_GET);</code> now produces:</p>\n\n<pre>\nArray\n(\n [a.a] => Array\n (\n [0] => bb\n [1] => BB\n )\n\n [c_c] => dd\n)\n</pre>\n\n<p><em>Notes:</p>\n\n<ul>\n<li>this patch addresses the original question only (it stops replacement of dots, not spaces).</li>\n<li>running on this patch will be faster than script-level solutions, but those pure-.php answers are still generally-preferable (because they avoid changing PHP itself).</li>\n<li>in theory a polyfill approach is possible here and could combine approaches -- test for the C-level change using <code>parse_str()</code> and (if unavailable) fall-back to slower methods.\n</em></li>\n</ul>\n"
},
{
"answer_id": 20365198,
"author": "scipilot",
"author_id": 209288,
"author_profile": "https://Stackoverflow.com/users/209288",
"pm_score": 5,
"selected": false,
"text": "<p>Highlighting an actual answer by Johan in a comment above - I just wrapped my entire post in a top-level array which completely bypasses the problem with no heavy processing required.</p>\n\n<p>In the form you do </p>\n\n<pre><code><input name=\"data[database.username]\"> \n<input name=\"data[database.password]\"> \n<input name=\"data[something.else.really.deep]\"> \n</code></pre>\n\n<p>instead of </p>\n\n<pre><code><input name=\"database.username\"> \n<input name=\"database.password\"> \n<input name=\"something.else.really.deep\"> \n</code></pre>\n\n<p>and in the post handler, just unwrap it:</p>\n\n<pre><code>$posdata = $_POST['data'];\n</code></pre>\n\n<p>For me this was a two-line change, as my views were entirely templated.</p>\n\n<p>FYI. I am using dots in my field names to edit trees of grouped data.</p>\n"
},
{
"answer_id": 25799378,
"author": "ChrisNY",
"author_id": 420274,
"author_profile": "https://Stackoverflow.com/users/420274",
"pm_score": 0,
"selected": false,
"text": "<p>Well, the function I include below, \"getRealPostArray()\", isn't a pretty solution, but it handles arrays and supports both names: \"alpha_beta\" and \"alpha.beta\":</p>\n\n<pre><code> <input type='text' value='First-.' name='alpha.beta[a.b][]' /><br>\n <input type='text' value='Second-.' name='alpha.beta[a.b][]' /><br>\n <input type='text' value='First-_' name='alpha_beta[a.b][]' /><br>\n <input type='text' value='Second-_' name='alpha_beta[a.b][]' /><br>\n</code></pre>\n\n<p>whereas var_dump($_POST) produces:</p>\n\n<pre><code> 'alpha_beta' => \n array (size=1)\n 'a.b' => \n array (size=4)\n 0 => string 'First-.' (length=7)\n 1 => string 'Second-.' (length=8)\n 2 => string 'First-_' (length=7)\n 3 => string 'Second-_' (length=8)\n</code></pre>\n\n<p>var_dump( getRealPostArray()) produces:</p>\n\n<pre><code> 'alpha.beta' => \n array (size=1)\n 'a.b' => \n array (size=2)\n 0 => string 'First-.' (length=7)\n 1 => string 'Second-.' (length=8)\n 'alpha_beta' => \n array (size=1)\n 'a.b' => \n array (size=2)\n 0 => string 'First-_' (length=7)\n 1 => string 'Second-_' (length=8)\n</code></pre>\n\n<p>The function, for what it's worth:</p>\n\n<pre><code>function getRealPostArray() {\n if ($_SERVER['REQUEST_METHOD'] !== 'POST') {#Nothing to do\n return null;\n }\n $neverANamePart = '~#~'; #Any arbitrary string never expected in a 'name'\n $postdata = file_get_contents(\"php://input\");\n $post = [];\n $rebuiltpairs = [];\n $postraws = explode('&', $postdata);\n foreach ($postraws as $postraw) { #Each is a string like: 'xxxx=yyyy'\n $keyvalpair = explode('=',$postraw);\n if (empty($keyvalpair[1])) {\n $keyvalpair[1] = '';\n }\n $pos = strpos($keyvalpair[0],'%5B');\n if ($pos !== false) {\n $str1 = substr($keyvalpair[0], 0, $pos);\n $str2 = substr($keyvalpair[0], $pos);\n $str1 = str_replace('.',$neverANamePart,$str1);\n $keyvalpair[0] = $str1.$str2;\n } else {\n $keyvalpair[0] = str_replace('.',$neverANamePart,$keyvalpair[0]);\n }\n $rebuiltpair = implode('=',$keyvalpair);\n $rebuiltpairs[]=$rebuiltpair;\n }\n $rebuiltpostdata = implode('&',$rebuiltpairs);\n parse_str($rebuiltpostdata, $post);\n $fixedpost = [];\n foreach ($post as $key => $val) {\n $fixedpost[str_replace($neverANamePart,'.',$key)] = $val;\n }\n return $fixedpost;\n}\n</code></pre>\n"
},
{
"answer_id": 26206877,
"author": "John",
"author_id": 606371,
"author_profile": "https://Stackoverflow.com/users/606371",
"pm_score": 0,
"selected": false,
"text": "<p>Using crb's I wanted to recreate the <code>$_POST</code> array as a whole though keep in mind you'll still have to ensure you're encoding and decoding correctly both at the client and the server. It's important to understand when a character is <em>truly</em> invalid and it is truly <em>valid</em>. Additionally people should <em>still</em> and <em>always</em> escape client data before using it with <em>any</em> database command <em>without exception</em>.</p>\n\n<pre><code><?php\nunset($_POST);\n$_POST = array();\n$p0 = explode('&',file_get_contents('php://input'));\nforeach ($p0 as $key => $value)\n{\n $p1 = explode('=',$value);\n $_POST[$p1[0]] = $p1[1];\n //OR...\n //$_POST[urldecode($p1[0])] = urldecode($p1[1]);\n}\nprint_r($_POST);\n?>\n</code></pre>\n\n<p>I recommend using this only for individual cases only, offhand I'm not sure about the negative points of putting this at the top of your primary header file.</p>\n"
},
{
"answer_id": 33735559,
"author": "sasha-ch",
"author_id": 4541523,
"author_profile": "https://Stackoverflow.com/users/4541523",
"pm_score": 0,
"selected": false,
"text": "<p>My current solution (based on prev topic replies):</p>\n\n<pre><code>function parseQueryString($data)\n{\n $data = rawurldecode($data); \n $pattern = '/(?:^|(?<=&))[^=&\\[]*[^=&\\[]*/'; \n $data = preg_replace_callback($pattern, function ($match){\n return bin2hex(urldecode($match[0]));\n }, $data);\n parse_str($data, $values);\n\n return array_combine(array_map('hex2bin', array_keys($values)), $values);\n}\n\n$_GET = parseQueryString($_SERVER['QUERY_STRING']);\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| If I pass PHP variables with `.` in their names via $\_GET PHP auto-replaces them with `_` characters. For example:
```
<?php
echo "url is ".$_SERVER['REQUEST_URI']."<p>";
echo "x.y is ".$_GET['x.y'].".<p>";
echo "x_y is ".$_GET['x_y'].".<p>";
```
... outputs the following:
```
url is /SpShipTool/php/testGetUrl.php?x.y=a.b
x.y is .
x_y is a.b.
```
... my question is this: is there **any** way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this
PHP version I'm running with is 5.2.4-2ubuntu5.3. | Here's PHP.net's explanation of why it does it:
>
> ### Dots in incoming variable names
>
>
> Typically, PHP does not alter the
> names of variables when they are
> passed into a script. However, it
> should be noted that the dot (period,
> full stop) is not a valid character in
> a PHP variable name. For the reason,
> look at it:
>
>
>
> ```
> <?php
> $varname.ext; /* invalid variable name */
> ?>
>
> ```
>
> Now, what
> the parser sees is a variable named
> $varname, followed by the string
> concatenation operator, followed by
> the barestring (i.e. unquoted string
> which doesn't match any known key or
> reserved words) 'ext'. Obviously, this
> doesn't have the intended result.
>
>
> For this reason, it is important to
> note that PHP will automatically
> replace any dots in incoming variable
> names with underscores.
>
>
>
That's from <http://ca.php.net/variables.external>.
Also, according to [this comment](http://ca.php.net/manual/en/language.variables.external.php#81080) these other characters are converted to underscores:
>
> The full list of field-name characters that PHP converts to \_ (underscore) is the following (not just dot):
>
>
> * chr(32) ( ) (space)
> * chr(46) (.) (dot)
> * chr(91) ([) (open square bracket)
> * chr(128) - chr(159) (various)
>
>
>
So it looks like you're stuck with it, so you'll have to convert the underscores back to dots in your script using [dawnerd's suggestion](https://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays#68667) (I'd just use [str\_replace](http://php.net/str_replace) though.) |
68,666 | <p>Why does the following code sometimes causes an Exception with the contents "CLIPBRD_E_CANT_OPEN":</p>
<pre><code>Clipboard.SetText(str);
</code></pre>
<p>This usually occurs the first time the Clipboard is used in the application and not after that.</p>
| [
{
"answer_id": 68857,
"author": "Tadmas",
"author_id": 3750,
"author_profile": "https://Stackoverflow.com/users/3750",
"pm_score": 6,
"selected": true,
"text": "<p>Actually, I think this is the <a href=\"https://cloudblogs.microsoft.com/enterprisemobility/2006/11/20/why-does-my-shared-clipboard-not-work-part-2/\" rel=\"noreferrer\">fault of the Win32 API</a>.</p>\n\n<p>To set data in the clipboard, you have to <a href=\"http://msdn.microsoft.com/en-us/library/ms649048(VS.85).aspx\" rel=\"noreferrer\">open it</a> first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open <em>for any reason</em>, your attempt to open it will fail.</p>\n\n<p>It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again.</p>\n\n<p>It's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem.</p>\n"
},
{
"answer_id": 69081,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 6,
"selected": false,
"text": "<p>This is caused by a bug/feature in Terminal Services clipboard (and possible other things) and the .NET implementation of the clipboard. A delay in opening the clipboard causes the error, which usually passes within a few milliseconds.</p>\n\n<p>The solution is to try multiple times within a loop and sleep in between.</p>\n\n<pre><code>for (int i = 0; i < 10; i++)\n{\n try\n {\n Clipboard.SetText(str);\n return;\n }\n catch { }\n System.Threading.Thread.Sleep(10);\n} \n</code></pre>\n"
},
{
"answer_id": 11726104,
"author": "Yishai Galatzer",
"author_id": 1048066,
"author_profile": "https://Stackoverflow.com/users/1048066",
"pm_score": 3,
"selected": false,
"text": "<p>Actually there could be another issue at hand. The framework call (both the WPF and winform flavors) to something like this (code is from reflector):</p>\n\n<pre><code>private static void SetDataInternal(string format, object data)\n{\n bool flag;\n if (IsDataFormatAutoConvert(format))\n {\n flag = true;\n }\n else\n {\n flag = false;\n }\n IDataObject obj2 = new DataObject();\n obj2.SetData(format, data, flag);\n SetDataObject(obj2, true);\n}\n</code></pre>\n\n<p>Note that SetDataObject is always called with true in this case.</p>\n\n<p>Internally that triggers two calls to the win32 api, one to set the data and one to flush it from your app so it's available after the app closes.</p>\n\n<p>I've seen several apps (some chrome plugin, and a download manager) that listen to the clipboard event. As soon as the first call hits, the app will open the clipboard to look into the data, and the second call to flush will fail.</p>\n\n<p>Haven't found a good solution except to write my own clipboard class that uses direct win32 API or to call setDataObject directly with false for keeping data after the app closes.</p>\n"
},
{
"answer_id": 30165665,
"author": "Mar",
"author_id": 44217,
"author_profile": "https://Stackoverflow.com/users/44217",
"pm_score": 4,
"selected": false,
"text": "<p>I solved this issue for my own app using native Win32 functions: OpenClipboard(), CloseClipboard() and SetClipboardData().</p>\n\n<p>Below the wrapper class I made. Could anyone <strong>please</strong> review it and <strong>tell if it is correct or not</strong>. Especially when the managed code is running as x64 app (I use Any CPU in the project options). <strong>What happens when I link to x86 libraries from x64 app?</strong></p>\n\n<p>Thank you!</p>\n\n<p>Here's the code:</p>\n\n<pre><code>public static class ClipboardNative\n{\n [DllImport(\"user32.dll\")]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport(\"user32.dll\")]\n private static extern bool CloseClipboard();\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetClipboardData(uint uFormat, IntPtr data);\n\n private const uint CF_UNICODETEXT = 13;\n\n public static bool CopyTextToClipboard(string text)\n {\n if (!OpenClipboard(IntPtr.Zero)){\n return false;\n }\n\n var global = Marshal.StringToHGlobalUni(text);\n\n SetClipboardData(CF_UNICODETEXT, global);\n CloseClipboard();\n\n //-------------------------------------------\n // Not sure, but it looks like we do not need \n // to free HGLOBAL because Clipboard is now \n // responsible for the copied data. (?)\n //\n // Otherwise the second call will crash\n // the app with a Win32 exception \n // inside OpenClipboard() function\n //-------------------------------------------\n // Marshal.FreeHGlobal(global);\n\n return true;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 39125098,
"author": "pr0gg3r",
"author_id": 1159244,
"author_profile": "https://Stackoverflow.com/users/1159244",
"pm_score": 5,
"selected": false,
"text": "<p>I know this question is old, but the problem still exists. As mentioned before, this exception occurs when the system clipboard is blocked by another process. Unfortunately, there are many snipping tools, programs for screenshots and file copy tools which can block the Windows clipboard. So you will get the exception every time you try to use <code>Clipboard.SetText(str)</code> when such a tool is installed on your PC.</p>\n<p>Solution:</p>\n<p>never use</p>\n<pre><code>Clipboard.SetText(str);\n</code></pre>\n<p>use instead</p>\n<pre><code>Clipboard.SetDataObject(str);\n</code></pre>\n"
},
{
"answer_id": 43910453,
"author": "Ellix4u",
"author_id": 3690683,
"author_profile": "https://Stackoverflow.com/users/3690683",
"pm_score": 1,
"selected": false,
"text": "<p>This happen to me in my WPF application. I got OpenClipboard Failed (Exception from HRESULT: 0x800401D0 (CLIPBRD_E_CANT_OPEN)).</p>\n\n<p>i use</p>\n\n<pre><code>ApplicationCommands.Copy.Execute(null, myDataGrid);\n</code></pre>\n\n<p>solution is to clear the clipboard first</p>\n\n<pre><code>Clipboard.Clear();\nApplicationCommands.Copy.Execute(null, myDataGrid);\n</code></pre>\n"
},
{
"answer_id": 64685710,
"author": "Bret Pehrson",
"author_id": 7547283,
"author_profile": "https://Stackoverflow.com/users/7547283",
"pm_score": 2,
"selected": false,
"text": "<p>Use the WinForms version (yes, there is no harm using WinForms in WPF applications), it handles everything you need:</p>\n<pre><code>System.Windows.Forms.Clipboard.SetDataObject(yourText, true, 10, 100);\n</code></pre>\n<p>This will attempt to copy yourText to the clipboard, it remains after your app exists, will attempt up to 10 times, and will wait 100ms between each attempt.</p>\n<p>Ref. <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.setdataobject?view=netframework-4.7.2#System_Windows_Forms_Clipboard_SetDataObject_System_Object_System_Boolean_System_Int32_System_Int32\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.clipboard.setdataobject?view=netframework-4.7.2#System_Windows_Forms_Clipboard_SetDataObject_System_Object_System_Boolean_System_Int32_System_Int32</a>_</p>\n"
},
{
"answer_id": 74564870,
"author": "Marek J",
"author_id": 6423994,
"author_profile": "https://Stackoverflow.com/users/6423994",
"pm_score": 0,
"selected": false,
"text": "<p>The difference between Cliboard.SetText and Cliboard.SetDataObject in WPF is that the text is not copied to the clipboard, only the pointer. I checked the source code. If we call SetDataObject(data, true) Clipoard.Flush() will also be called. Thanks to this, text or data is available even after closing the application. I think Windows applications only call Flush() when they are shutting down. Thanks to this, it saves memory and at the same time gives access to data without an active application.</p>\n<p>Copy to clipboard:</p>\n<pre><code>IDataObject CopyStringToClipboard(string s)\n{\n var dataObject = new DataObject(s);\n Clipboard.SetDataObject(dataObject, false);\n return dataObject;\n}\n</code></pre>\n<p>Code when app or window is closed:</p>\n<pre><code>try\n{\n if ((clipboardData != null) && Clipboard.IsCurrent(clipboardData))\n Clipboard.Flush();\n}\ncatch (COMException ex) {}\n</code></pre>\n<p>clipboardData is a window class field or static variable.</p>\n"
},
{
"answer_id": 74679767,
"author": "sarh",
"author_id": 282694,
"author_profile": "https://Stackoverflow.com/users/282694",
"pm_score": 0,
"selected": false,
"text": "<p>That's not a solution, just some additional information on how to reproduce it when all solutions work on your PC and fail somewhere else. As mentioned in the accepted answer - clipboard can be busy by some other app. You just need to handle this failure properly, to explain user somehow why it does not work.</p>\n<p>So, just create a new console app with few lines below and run it. And while it is running - test your primary app on how it is handles busy clipboard:</p>\n<pre><code>class Program\n{\n [DllImport("user32.dll")]\n private static extern bool OpenClipboard(IntPtr hWndNewOwner);\n\n [DllImport("user32.dll")]\n private static extern bool CloseClipboard();\n\n static void Main(string[] args)\n {\n bool res = OpenClipboard(IntPtr.Zero);\n Console.Write(res);\n Console.Read();\n CloseClipboard();\n }\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10784/"
]
| Why does the following code sometimes causes an Exception with the contents "CLIPBRD\_E\_CANT\_OPEN":
```
Clipboard.SetText(str);
```
This usually occurs the first time the Clipboard is used in the application and not after that. | Actually, I think this is the [fault of the Win32 API](https://cloudblogs.microsoft.com/enterprisemobility/2006/11/20/why-does-my-shared-clipboard-not-work-part-2/).
To set data in the clipboard, you have to [open it](http://msdn.microsoft.com/en-us/library/ms649048(VS.85).aspx) first. Only one process can have the clipboard open at a time. So, when you check, if another process has the clipboard open *for any reason*, your attempt to open it will fail.
It just so happens that Terminal Services keeps track of the clipboard, and on older versions of Windows (pre-Vista), you have to open the clipboard to see what's inside... which ends up blocking you. The only solution is to wait until Terminal Services closes the clipboard and try again.
It's important to realize that this is not specific to Terminal Services, though: it can happen with anything. Working with the clipboard in Win32 is a giant race condition. But, since by design you're only supposed to muck around with the clipboard in response to user input, this usually doesn't present a problem. |
68,677 | <p>I'm using SQL Server 2000 to print out some values from a table using <code>PRINT</code>. With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters. For example:</p>
<pre><code>DECLARE @binvalue binary(4)
SET @binvalue = 0x12345678
PRINT CAST(@binvalue AS nvarchar)
</code></pre>
<p>Expected:</p>
<blockquote>
<p>0x12345678</p>
</blockquote>
<p>Instead, it prints two gibberish characters.</p>
<p>How can I print the value of binary data? Is there a built-in or do I need to roll my own?</p>
<p>Update: This isn't the only value on the line, so I can't just PRINT @binvalue. It's something more like PRINT N'other stuff' + ???? + N'more stuff'. Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself.</p>
| [
{
"answer_id": 68858,
"author": "Ricardo C",
"author_id": 232589,
"author_profile": "https://Stackoverflow.com/users/232589",
"pm_score": 2,
"selected": false,
"text": "<pre><code>DECLARE @binvalue binary(4)\nSET @binvalue = 0x61000000\nPRINT @binvalue \nPRINT cast('a' AS binary(4))\nPRINT cast(0x61 AS varchar)\n</code></pre>\n\n<p>Do not cast. </p>\n\n<p>Casting converts the binary to text by value on the corresponding collation setting for the specific database.</p>\n\n<p>[Begin Edit]\nIf you need the printed value in a string variable use the function suggested by Eric Z Beard.</p>\n\n<pre><code>DECLARE @mybin1 binary(16)\nDECLARE @s varchar(100)\nSET @mybin1 = 0x098F6BCD4621D373CADE4E832627B4F6\nSET @s = 'The value of @mybin1 is: ' + sys.fn_varbintohexsubstring(0, @mybin1,1,0)\nPRINT @s\n</code></pre>\n\n<p>If this function is not at your disposal due to server versions or because it needs special permissions, you can create your own function.</p>\n\n<p>To see how that function was implemented in SQL Server 2005 Express edition you can execute:</p>\n\n<pre><code>sp_helptext 'fn_varbintohexsubstring'\n</code></pre>\n"
},
{
"answer_id": 68872,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 6,
"selected": true,
"text": "<p>If you were on Sql Server 2005 you could use this:</p>\n\n<pre><code>print master.sys.fn_varbintohexstr(@binvalue)\n</code></pre>\n\n<p>I don't think that exists on 2000, though, so you might have to roll your own.</p>\n"
},
{
"answer_id": 12016386,
"author": "Ihor B.",
"author_id": 1253118,
"author_profile": "https://Stackoverflow.com/users/1253118",
"pm_score": 6,
"selected": false,
"text": "<blockquote>\n <p>Do not use <code>master.sys.fn_varbintohexstr</code> - it is <em>terribly slow</em>, undocumented, unsupported, and <em>might go away in a future version of SQL Server</em>.</p>\n</blockquote>\n\n<p>If you need to convert <code>binary(16)</code> to hex char, use <code>convert</code>: </p>\n\n<pre><code>convert(char(34), @binvalue, 1)\n</code></pre>\n\n<p>Why 34? because <code>16*2 + 2 = 34</code>, that is \"0x\" - 2 symbols, plus 2 symbols for each char.</p>\n\n<p>We tried to make 2 queries on a table with 200000 rows:</p>\n\n<ol>\n<li><pre><code>select master.sys.fn_varbintohexstr(field)\nfrom table`\n</code></pre></li>\n<li><pre><code>select convert(char(34), field, 1)\nfrom table`\n</code></pre></li>\n</ol>\n\n<p>the first one runs 2 minutes, while second one - 4 seconds.</p>\n"
},
{
"answer_id": 12549880,
"author": "Charlie Affumigato",
"author_id": 1691857,
"author_profile": "https://Stackoverflow.com/users/1691857",
"pm_score": 5,
"selected": false,
"text": "<pre><code>select convert(varchar(max), field , 1) \nfrom table\n</code></pre>\n\n<p>By <code>using varchar(max)</code> you won't have to worry about specifying the size (kind of).</p>\n"
},
{
"answer_id": 17951174,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 4,
"selected": false,
"text": "<p>Adding an answer which shows another example of converting <em>binary</em> data into a hex string, and back again. </p>\n\n<p>i want to convert the highest <code>timestamp</code> value into <code>varchar</code>:</p>\n\n<pre><code>SELECT \n CONVERT(\n varchar(50), \n CAST(MAX(timestamp) AS varbinary(8)), \n 1) AS LastTS\nFROM Users\n</code></pre>\n\n<p>Which returns:</p>\n\n<pre><code>LastTS\n==================\n0x000000000086862C\n</code></pre>\n\n<p><strong>Note</strong>: It's important that you use <code>CONVERT</code> to convert <code>varbinary -> varchar</code>. Using <code>CAST</code> will not work: </p>\n\n<pre><code>SELECT \n CAST(\n CAST(MAX(timestamp) AS varbinary(8)) \n AS varchar(50) ) AS LastTS\nFROM Users\n</code></pre>\n\n<p>will treat the binary data as <em>characters</em> rather than hex values, returning an empty string.</p>\n\n<h1>Reverse it</h1>\n\n<p>To convert the stored hex string back to a timestamp:</p>\n\n<pre><code>SELECT CAST(CONVERT(varbinary(50), '0x000000000086862C', 1) AS timestamp)\n</code></pre>\n\n<blockquote>\n <p><strong>Note</strong>: Any code is released into the public domain. No attribution required.</p>\n</blockquote>\n"
},
{
"answer_id": 19399525,
"author": "David Claughton",
"author_id": 2885723,
"author_profile": "https://Stackoverflow.com/users/2885723",
"pm_score": 2,
"selected": false,
"text": "<p>I came across this question while looking for a solution to a similar problem while printing the hex value returned from the 'hashbytes' function in SQL Server 2005.</p>\n\n<p>Sadly in this version of SQL Server, CONVERT does not seem to work at all, only fn_varbintohexsubstring does the correct thing:</p>\n\n<p>I did:</p>\n\n<pre><code>DECLARE @binvalue binary(4)\nSET @binvalue = 0x12345678\nPRINT 'cast(@binvalue AS nvarchar): ' + CAST(@binvalue AS nvarchar)\nPRINT 'convert(varchar(max), @binvalue, 0): ' + CONVERT(varchar(max), @binvalue, 0)\nPRINT 'convert(varchar(max), @binvalue, 1): ' + CONVERT(varchar(max), @binvalue, 1)\nPRINT 'convert(varchar(max), @binvalue, 2): ' + CONVERT(varchar(max), @binvalue, 2)\nprint 'master.sys.fn_varbintohexstr(@binvalue): ' + master.sys.fn_varbintohexstr(@binvalue)\n</code></pre>\n\n<p>Here is the result I got in SQL Server 2005 (</p>\n\n<pre><code>cast(@binvalue AS nvarchar): 㐒硖\nconvert(varchar(max), @binvalue, 0): 4Vx\nconvert(varchar(max), @binvalue, 1): 4Vx\nconvert(varchar(max), @binvalue, 2): 4Vx\nmaster.sys.fn_varbintohexstr(@binvalue): 0x12345678\n</code></pre>\n\n<p>(there's actually an unprintable character before the '4Vx's - I'd post an image, but I don't have enough points yet).</p>\n\n<hr>\n\n<p><strong>Edit</strong>: Just to add - on SQL Server 2008 R2 the problem with CONVERT is fixed with the following output:</p>\n\n<pre><code>cast(@binvalue AS nvarchar): 㐒硖\nconvert(varchar(max), @binvalue, 0): 4Vx\nconvert(varchar(max), @binvalue, 1): 0x12345678\nconvert(varchar(max), @binvalue, 2): 12345678\nmaster.sys.fn_varbintohexstr(@binvalue): 0x12345678\n</code></pre>\n"
},
{
"answer_id": 65160592,
"author": "Nick Legend",
"author_id": 3868454,
"author_profile": "https://Stackoverflow.com/users/3868454",
"pm_score": 0,
"selected": false,
"text": "<p>Really too much of tl;dr in the topic :( Will try to fix it following <a href=\"https://stackoverflow.com/a/12549880/10815638\">this answer</a>.</p>\n<pre><code>with \nsq1 as (select '41424344' as v), -- this is 'ABCD'\n-- Need binary size, otherwise it sets binary(30) in my case\nsq2 as (select v, convert(binary(4), v, 2) as b from sq1), \nsq3 as (select b, v, convert(varchar, b, 2) as v1 from sq2)\n--\nselect b, v, v1 from sq3\nwhere v = v1\n;\n</code></pre>\n<p>The output is:</p>\n<pre><code>b |v |v1 |\n----|--------|--------|\nABCD|41424344|41424344|\n</code></pre>\n<p>Also see: <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">documentation</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3750/"
]
| I'm using SQL Server 2000 to print out some values from a table using `PRINT`. With most non-string data, I can cast to nvarchar to be able to print it, but binary values attempt to convert using the bit representation of characters. For example:
```
DECLARE @binvalue binary(4)
SET @binvalue = 0x12345678
PRINT CAST(@binvalue AS nvarchar)
```
Expected:
>
> 0x12345678
>
>
>
Instead, it prints two gibberish characters.
How can I print the value of binary data? Is there a built-in or do I need to roll my own?
Update: This isn't the only value on the line, so I can't just PRINT @binvalue. It's something more like PRINT N'other stuff' + ???? + N'more stuff'. Not sure if that makes a difference: I didn't try just PRINT @binvalue by itself. | If you were on Sql Server 2005 you could use this:
```
print master.sys.fn_varbintohexstr(@binvalue)
```
I don't think that exists on 2000, though, so you might have to roll your own. |
68,688 | <p>What is the best solution of defaultButton and "Enter key pressed" for ASP.NET 2.0-3.5 forms?</p>
| [
{
"answer_id": 68700,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 2,
"selected": false,
"text": "<p>Just add the \"defaultbutton\" attribute to the form and set it to the ID of the button you want to be the default. </p>\n\n<pre><form defaultbutton=\"button1\" runat=\"server\">\n <asp:textbox id=\"textbox1\" runat=\"server\"/>\n <asp:button id=\"button1\" text=\"Button1\" runat=\"server\"/>\n</form> </pre>\n\n<p>NOTE: This only works in ASP.NET 2.0+</p>\n"
},
{
"answer_id": 68866,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 2,
"selected": false,
"text": "<p>Since form submission on hitting the enter key is a part of life with HTML, you'll have to trap the Enter key using javascript and only allow it to go through when it's valid (such as within textareas). Check out <a href=\"http://brennan.offwhite.net/blog/2004/08/04/the-single-form-problem-with-aspnet/\" rel=\"nofollow noreferrer\"><a href=\"http://brennan.offwhite.net/blog/2004/08/04/the-single-form-problem-with-aspnet/\" rel=\"nofollow noreferrer\">http://brennan.offwhite.net/blog/2004/08/04/the-single-form-problem-with-aspnet/</a></a> for a good explanation.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10778/"
]
| What is the best solution of defaultButton and "Enter key pressed" for ASP.NET 2.0-3.5 forms? | Just add the "defaultbutton" attribute to the form and set it to the ID of the button you want to be the default.
```
<form defaultbutton="button1" runat="server">
<asp:textbox id="textbox1" runat="server"/>
<asp:button id="button1" text="Button1" runat="server"/>
</form>
```
NOTE: This only works in ASP.NET 2.0+ |
68,711 | <p>any idea how if the following is possible in PHP as a single line ?:</p>
<pre><code><?php
$firstElement = functionThatReturnsAnArray()[0];
</code></pre>
<p>... It doesn't seem to 'take'. I need to do this as a 2-stepper:</p>
<pre><code><?php
$allElements = functionThatReturnsAnArray();
$firstElement = $allElements[0];
</code></pre>
<p>... just curious - other languages I play with allow things like this, and I'm lazy enoug to miss this in PHP ... any insight appreciated ...</p>
| [
{
"answer_id": 68716,
"author": "owenmarshall",
"author_id": 9806,
"author_profile": "https://Stackoverflow.com/users/9806",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately, that is not possible with PHP. You have to use two lines to do it.</p>\n"
},
{
"answer_id": 68719,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": -1,
"selected": false,
"text": "<p>As far as I know this is not possible, I have wanted to do this myself several times.</p>\n"
},
{
"answer_id": 68745,
"author": "calebbrown",
"author_id": 7007,
"author_profile": "https://Stackoverflow.com/users/7007",
"pm_score": 4,
"selected": true,
"text": "<p>Try:</p>\n\n<pre><code><?php\n$firstElement = reset(functionThatReturnsAnArray());\n</code></pre>\n\n<p>If you're just looking for the first element of the array.</p>\n"
},
{
"answer_id": 68789,
"author": "Jack B Nimble",
"author_id": 3800,
"author_profile": "https://Stackoverflow.com/users/3800",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"http://us3.php.net/reset\" rel=\"nofollow noreferrer\">http://us3.php.net/reset</a></p>\n\n<p>Only available in php version 5.</p>\n"
},
{
"answer_id": 68828,
"author": "Scott Reynen",
"author_id": 10837,
"author_profile": "https://Stackoverflow.com/users/10837",
"pm_score": 2,
"selected": false,
"text": "<p>list() is useful here. With any but the first array element, you'll need to pad it with useless variables. For example:</p>\n\n<pre><code>list( $firstElement ) = functionThatReturnsAnArray();\nlist( $firstElement , $secondElement ) = functionThatReturnsAnArray();\n</code></pre>\n\n<p>And so on.</p>\n"
},
{
"answer_id": 68841,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "<p>@Scott Reynen</p>\n\n<p>that's not true. This will work:</p>\n\n<pre><code>list(,,$thirdElement) = $myArray;\n</code></pre>\n"
},
{
"answer_id": 68926,
"author": "Scott Reynen",
"author_id": 10837,
"author_profile": "https://Stackoverflow.com/users/10837",
"pm_score": 0,
"selected": false,
"text": "<p>nickf, good to know, thanks. Unfortunately that has readability problems beyond a few commas.</p>\n"
},
{
"answer_id": 68965,
"author": "neouser99",
"author_id": 10669,
"author_profile": "https://Stackoverflow.com/users/10669",
"pm_score": -1,
"selected": false,
"text": "<p>If it's always the first element, you should probably think about having the function return just the first item in the array. If that is the most common case, you could use a little bit of coolness:</p>\n\n<pre><code>function func($first = false) {\n ...\n if $first return $array[0];\n else return $array;\n}\n\n$array = func();\n$item = func(true);\n</code></pre>\n\n<p>My php is slightly rusty, but i'm pretty sure that works.</p>\n\n<p>You can also look at array_shift() and array_pop().</p>\n\n<p>This is probably also possible:</p>\n\n<pre><code>array(func())[0][i];\n</code></pre>\n\n<p>The 0 is for the function.</p>\n"
},
{
"answer_id": 69303,
"author": "Garrett Albright",
"author_id": 11023,
"author_profile": "https://Stackoverflow.com/users/11023",
"pm_score": 3,
"selected": false,
"text": "<p>You <em>can</em> do this in one line! Use <a href=\"http://us.php.net/array_shift\" rel=\"noreferrer\">array_shift()</a>.</p>\n\n<pre><code><?php\n\necho array_shift(i_return_an_array());\n\nfunction i_return_an_array() {\n return array('foo', 'bar', 'baz');\n}\n</code></pre>\n\n<p>When this is executed, it will echo \"<code>foo</code>\".</p>\n"
},
{
"answer_id": 70092,
"author": "Greg",
"author_id": 1916,
"author_profile": "https://Stackoverflow.com/users/1916",
"pm_score": 1,
"selected": false,
"text": "<p>Either <code>current($array)</code> or <code>array_shift($array)</code> will work, the former will leave the <em>array</em> intact.</p>\n"
},
{
"answer_id": 70310,
"author": "Draco777",
"author_id": 11473,
"author_profile": "https://Stackoverflow.com/users/11473",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I have found a couple of ways to get what you want without calling another function.</p>\n\n<pre><code>$firstElement = ($t = functionThatReturnsAnArray()) ? $t[0] : false;\n</code></pre>\n\n<p>and for strings you could use </p>\n\n<pre><code>$string = (($t = functionThatReturnsAnArray())==0) . $t[0];\n</code></pre>\n\n<p>.. Interesting problem</p>\n\n<p>Draco</p>\n"
},
{
"answer_id": 70699,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>array_slice()</code>, like so:</p>\n\n<pre><code>$elementX = array_slice(functionThatReturnsAnArray(), $x, 1);\n</code></pre>\n\n<p>Also noticed that <code>end()</code> is not mentioned. It returns the last element of an array.</p>\n"
},
{
"answer_id": 72510,
"author": "Adam Hopkinson",
"author_id": 12280,
"author_profile": "https://Stackoverflow.com/users/12280",
"pm_score": 0,
"selected": false,
"text": "<p>I think any of the above would require a comment to explain what you're doing, thus becoming two lines. I find it simpler to do:</p>\n\n<pre><code>$element = functionThatReturnsArray();\n$element = $element[0];\n</code></pre>\n\n<p>This way, you're not using an extra variable and it's obvious what you're doing.</p>\n"
},
{
"answer_id": 72916,
"author": "deceze",
"author_id": 476,
"author_profile": "https://Stackoverflow.com/users/476",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$firstItem = current(returnsArray());\n</code></pre>\n"
},
{
"answer_id": 73923,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": -1,
"selected": false,
"text": "<p>Sometimes I'll change the function, so it can optionally return an element instead of the entire array:</p>\n\n<pre><code><?php\nfunction functionThatReturnsAnArray($n = NULL) {\n return ($n === NULL ? $myArray : $myArray[$n]);\n}\n$firstElement = functionThatReturnsAnArray(0);\n</code></pre>\n"
},
{
"answer_id": 74530,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 1,
"selected": false,
"text": "<p>I actually use a convenience function i wrote for such purposes:</p>\n\n<pre><code>/**\n * Grabs an element from an array using a key much like array_pop\n */\nfunction array_key_value($array, $key) {\n if(!empty($array) && array_key_exists($key, $array)) {\n return $array[$key];\n }\n else {\n return FALSE;\n }\n}\n</code></pre>\n\n<p>then you just call it like so:</p>\n\n<pre><code>$result = array_key_value(getMeAnArray(), 'arrayKey');\n</code></pre>\n"
},
{
"answer_id": 299108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I am guessing that this is a built-in or library function, since it sounds like you cannot edit it directly. I recommend creating a wrapper function to give you the output you need:</p>\n\n<pre><code>function functionThatReturnsOneElement( $arg )\n{\n $result = functionThatReturnsAnArray( $arg );\n return $result[0];\n}\n$firstElement = functionThatReturnsOneElement();\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| any idea how if the following is possible in PHP as a single line ?:
```
<?php
$firstElement = functionThatReturnsAnArray()[0];
```
... It doesn't seem to 'take'. I need to do this as a 2-stepper:
```
<?php
$allElements = functionThatReturnsAnArray();
$firstElement = $allElements[0];
```
... just curious - other languages I play with allow things like this, and I'm lazy enoug to miss this in PHP ... any insight appreciated ... | Try:
```
<?php
$firstElement = reset(functionThatReturnsAnArray());
```
If you're just looking for the first element of the array. |
68,750 | <p>This should hopefully be a simple one.</p>
<p>I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class.</p>
<p>How should this extension method look?</p>
<p>My first intuitive thought is something like this:</p>
<pre><code>namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle(this ViewPage<Type> v)
{
return "";
}
}
}
</code></pre>
<p><strong>Solution</strong></p>
<p>The general solution is <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">this answer</a>.</p>
<p>The specific solution to extending the System.Web.Mvc.ViewPage class is <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802">my answer</a> below, which started from the <a href="https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772">general solution</a>.</p>
<p>The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type.</p>
| [
{
"answer_id": 68772,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 5,
"selected": true,
"text": "<p>I don't have VS installed on my current machine, but I think the syntax would be:</p>\n\n<pre><code>namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<T>(this ViewPage<T> v)\n {\n return \"\";\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68779,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 2,
"selected": false,
"text": "<p>It just needs the generic type specifier on the function:</p>\n\n<pre><code>namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<Type>(this ViewPage<Type> v)\n {\n return \"\";\n }\n }\n}\n</code></pre>\n\n<p>Edit: Just missed it by seconds!</p>\n"
},
{
"answer_id": 68802,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks leddt.\nDoing that yielded the error:</p>\n\n<blockquote>\n <p>The type 'TModel' must be a reference\n type in order to use it as parameter\n 'TModel' in the generic type or method</p>\n</blockquote>\n\n<p>which pointed me to <a href=\"http://forums.asp.net/p/1311022/2581563.aspx\" rel=\"noreferrer\">this page</a>, which yielded this solution:</p>\n\n<pre><code>namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<T>(this ViewPage<T> v) \n where T : class\n {\n return \"\";\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68826,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 1,
"selected": false,
"text": "<p>If you want the extension to only be available for the specified type\nyou simply just need to specify the actual type you will be handling</p>\n\n<p>something like...</p>\n\n<pre><code>public static string GetDefaultPageTitle(this ViewPage<YourSpecificType> v)\n{\n ...\n}\n</code></pre>\n\n<p>Note intellisense will then only display the extension method when you declare your (in this case) ViewPage with the matching type.</p>\n\n<p>Also, best not to use the System.Web.Mvc namespace, I know its convenient to not have to include your namespace in the usings section, but its far more maintainable if you create your own extensions namespace for your extension functions.</p>\n"
},
{
"answer_id": 68864,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://codebetter.com/blogs/glenn.block/archive/2008/08/19/foreach-a-simple-but-very-useful-extension-method.aspx\" rel=\"nofollow noreferrer\">Glenn Block</a> has a good example of implementing a <code>ForEach</code> extension method to <code>IEnumerable<T></code>.</p>\n\n<p>From his <a href=\"http://codebetter.com/blogs/glenn.block/archive/2008/08/19/foreach-a-simple-but-very-useful-extension-method.aspx\" rel=\"nofollow noreferrer\">blog post</a>:</p>\n\n<pre><code>public static class IEnumerableUtils\n{\n public static void ForEach<T>(this IEnumerable<T> collection, Action<T> action)\n {\n foreach(T item in collection)\n action(item);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68935,
"author": "chadmyers",
"author_id": 10862,
"author_profile": "https://Stackoverflow.com/users/10862",
"pm_score": 2,
"selected": false,
"text": "<pre><code>namespace System.Web.Mvc\n{\n public static class ViewPageExtensions\n {\n public static string GetDefaultPageTitle<T>(this ViewPage<T> view)\n where T : class\n {\n return \"\";\n }\n }\n}\n</code></pre>\n\n<p>You may also need/wish to add the \"new()\" qualifier to the generic type (i.e. \"where T : class, new()\" to enforce that T is both a reference type (class) and has a parameterless constructor.</p>\n"
},
{
"answer_id": 11771468,
"author": "Tod Thomson",
"author_id": 372666,
"author_profile": "https://Stackoverflow.com/users/372666",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an example for Razor views:</p>\n\n<pre><code>public static class WebViewPageExtensions\n{\n public static string GetFormActionUrl(this WebViewPage view)\n {\n return string.Format(\"/{0}/{1}/{2}\", view.GetController(), view.GetAction(), view.GetId());\n }\n\n public static string GetController(this WebViewPage view)\n {\n return Get(view, \"controller\");\n }\n\n public static string GetAction(this WebViewPage view)\n {\n return Get(view, \"action\");\n }\n\n public static string GetId(this WebViewPage view)\n {\n return Get(view, \"id\");\n }\n\n private static string Get(WebViewPage view, string key)\n {\n return view.ViewContext.Controller.ValueProvider.GetValue(key).RawValue.ToString();\n }\n}\n</code></pre>\n\n<p>You really don't need to use the Generic version as the generic one extends the non-generic one so just put it in the non-generic base class and you're done :)</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
| This should hopefully be a simple one.
I would like to add an extension method to the System.Web.Mvc.ViewPage< T > class.
How should this extension method look?
My first intuitive thought is something like this:
```
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle(this ViewPage<Type> v)
{
return "";
}
}
}
```
**Solution**
The general solution is [this answer](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772).
The specific solution to extending the System.Web.Mvc.ViewPage class is [my answer](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68802) below, which started from the [general solution](https://stackoverflow.com/questions/68750/how-do-you-write-a-c-extension-method-for-a-generically-typed-class#68772).
The difference is in the specific case you need both a generically typed method declaration AND a statement to enforce the generic type as a reference type. | I don't have VS installed on my current machine, but I think the syntax would be:
```
namespace System.Web.Mvc
{
public static class ViewPageExtensions
{
public static string GetDefaultPageTitle<T>(this ViewPage<T> v)
{
return "";
}
}
}
``` |
68,774 | <p>I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way?</p>
| [
{
"answer_id": 68796,
"author": "The.Anti.9",
"author_id": 2128,
"author_profile": "https://Stackoverflow.com/users/2128",
"pm_score": 7,
"selected": true,
"text": "<p>Opening sockets in python is pretty simple. You really just need something like this:</p>\n\n<pre><code>import socket\nsock = socket.socket()\nsock.connect((address, port))\n</code></pre>\n\n<p>and then you can <code>send()</code> and <code>recv()</code> like any other socket</p>\n"
},
{
"answer_id": 68892,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 3,
"selected": false,
"text": "<p>For developing portable network programs of any sort in Python, <a href=\"http://twistedmatrix.com\" rel=\"noreferrer\">Twisted</a> is quite useful. One of its benefits is providing a convenient layer above low-level socket APIs.</p>\n"
},
{
"answer_id": 68911,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": 4,
"selected": false,
"text": "<p>OK, this code worked</p>\n\n<pre><code>s = socket.socket()\ns.connect((ip,port))\ns.send(\"my request\\r\")\nprint s.recv(256)\ns.close()\n</code></pre>\n\n<p>It was quite difficult to work that out from the Python socket module documentation. So I'll accept The.Anti.9's answer.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5324/"
]
| I want to open a TCP client socket in Python. Do I have to go through all the low-level BSD create-socket-handle / connect-socket stuff or is there a simpler one-line way? | Opening sockets in python is pretty simple. You really just need something like this:
```
import socket
sock = socket.socket()
sock.connect((address, port))
```
and then you can `send()` and `recv()` like any other socket |
68,843 | <p>How does the compiler know the prototype of sleep function or even printf function, when I did not include any header file in the first place?</p>
<p>Moreover, if I specify <code>sleep(1,1,"xyz")</code> or any arbitrary number of arguments, the compiler still compiles it.
But the strange thing is that gcc is able to find the definition of this function at link time, I don't understand how is this possible, because actual <code>sleep()</code> function takes a single argument only, but our program mentioned three arguments.</p>
<pre><code>/********************************/
int main()
{
short int i;
for(i = 0; i<5; i++)
{
printf("%d",i);`print("code sample");`
sleep(1);
}
return 0;
}
</code></pre>
| [
{
"answer_id": 68861,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 2,
"selected": false,
"text": "<p>C will guess int for unknown types. So, it probably thinks sleep has this prototype:</p>\n\n<pre><code>int sleep(int);\n</code></pre>\n\n<p>As for giving multiple parameters and linking...I'm not sure. That does surprise me. If that really worked, then what happened at run-time?</p>\n"
},
{
"answer_id": 68874,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 1,
"selected": false,
"text": "<p>Depends on the compiler, but with gcc (for example, since that's the one you referred to), some of the standard (both C and POSIX) functions have builtin \"compiler intrinsics\". This means that the compiler library shipped with your compiler (libgcc in this case) contains an implementation of the function. The compiler will allow an implicit declaration (i.e., using the function without a header), and the linker will find the implementation in the compiler library because you're probably using the compiler as a linker front-end.</p>\n\n<p>Try compiling your objects with the '-c' flag (compile only, no link), and then link them directly using the linker. You will find that you get the linker errors you expect.</p>\n\n<p>Alternatively, gcc supports options to disable the use of intrinsics: <code>-fno-builtin</code> or for granular control, <code>-fno-builtin-function</code>. There are further options that may be useful if you're doing something like building a homebrew kernel or some other kind of on-the-metal app.</p>\n"
},
{
"answer_id": 68928,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 3,
"selected": false,
"text": "<p>Lacking a more specific prototype, the compiler will assume that the function returns int and takes whatever number of arguments you provide.</p>\n\n<p>Depending on the CPU architecture arguments can be passed in registers (for example, a0 through a3 on MIPS) or by pushing them onto the stack as in the original x86 calling convention. In either case, passing extra arguments is harmless. The called function won't use the registers passed in nor reference the extra arguments on the stack, but nothing bad happens.</p>\n\n<p>Passing in fewer arguments is more problematic. The called function will use whatever garbage happened to be in the appropriate register or stack location, and hijinks may ensue.</p>\n"
},
{
"answer_id": 69147,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 3,
"selected": false,
"text": "<p>In classic C, you don't need a prototype to call a function. The compiler will infer that the function returns an int and takes a unknown number of parameters. This may work on some architectures, but it will fail if the function returns something other than int, like a structure, or if there are any parameter conversions.</p>\n\n<p>In your example, sleep is seen and the compiler assumes a prototype like</p>\n\n<pre><code>int sleep();\n</code></pre>\n\n<p>Note that the argument list is empty. In C, this is NOT the same as void. This actually means \"unknown\". If you were writing K&R C code, you could have unknown parameters through code like</p>\n\n<pre><code>int sleep(t)\nint t;\n{\n /* do something with t */\n}\n</code></pre>\n\n<p>This is all dangerous, especially on some embedded chips where the way parameters are passed for a unprototyped function differs from one with a prototype.</p>\n\n<p>Note: prototypes aren't needed for linking. Usually, the linker automatically links with a C runtime library like glibc on Linux. The association between your use of sleep and the code that implements it happens at link time long after the source code has been processed.</p>\n\n<p>I'd suggest that you use the feature of your compiler to require prototypes to avoid problems like this. With GCC, it's the -Wstrict-prototypes command line argument. In the CodeWarrior tools, it was the \"Require Prototypes\" flag in the C/C++ Compiler panel.</p>\n"
},
{
"answer_id": 69158,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 1,
"selected": false,
"text": "<p>In a non-toy example another file may include the one you missed. Reviewing the output from the pre-processor is a nice way to see what you end up with compiling.</p>\n"
},
{
"answer_id": 69280,
"author": "vrdhn",
"author_id": 414441,
"author_profile": "https://Stackoverflow.com/users/414441",
"pm_score": 2,
"selected": false,
"text": "<p>This is to do with something called 'K & R C' and 'ANSI C'.\nIn good old K & R C, if something is not declared, it is assumed to be int. \nSo any thing that looks like a function call, but not declared as function\nwill automatically take return value of 'int' and argument types depending\non the actuall call.</p>\n\n<p>However people later figured out that this can be very bad sometimes. So \nseveral compilers added warning. C++ made this error. I think gcc has some \nflag ( -ansic or -pedantic? ) , which make this condition an error.</p>\n\n<p>So, In a nutshell, this is historical baggage.</p>\n"
},
{
"answer_id": 71733,
"author": "itj",
"author_id": 888,
"author_profile": "https://Stackoverflow.com/users/888",
"pm_score": 2,
"selected": false,
"text": "<p>Other answers cover the probable mechanics (all guesses as compiler not specified).</p>\n\n<p>The issue that you have is that your compiler and linker have not been set to enable every possible error and warning. For any new project there is (virtually) no excuse for not doing so. <em>for legacy projects more excuse - but should strive to enable as many as possible</em></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How does the compiler know the prototype of sleep function or even printf function, when I did not include any header file in the first place?
Moreover, if I specify `sleep(1,1,"xyz")` or any arbitrary number of arguments, the compiler still compiles it.
But the strange thing is that gcc is able to find the definition of this function at link time, I don't understand how is this possible, because actual `sleep()` function takes a single argument only, but our program mentioned three arguments.
```
/********************************/
int main()
{
short int i;
for(i = 0; i<5; i++)
{
printf("%d",i);`print("code sample");`
sleep(1);
}
return 0;
}
``` | Lacking a more specific prototype, the compiler will assume that the function returns int and takes whatever number of arguments you provide.
Depending on the CPU architecture arguments can be passed in registers (for example, a0 through a3 on MIPS) or by pushing them onto the stack as in the original x86 calling convention. In either case, passing extra arguments is harmless. The called function won't use the registers passed in nor reference the extra arguments on the stack, but nothing bad happens.
Passing in fewer arguments is more problematic. The called function will use whatever garbage happened to be in the appropriate register or stack location, and hijinks may ensue. |
68,993 | <p>Say I have a line in an emacs buffer that looks like this:</p>
<pre><code>foo -option1 value1 -option2 value2 -option3 value3 \
-option4 value4 ...
</code></pre>
<p>I want it to look like this:</p>
<pre><code>foo -option1 value1 \
-option2 value2 \
-option3 value3 \
-option4 value4 \
...
</code></pre>
<p>I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region. </p>
<p>Anybody know of an elisp function to do this? </p>
| [
{
"answer_id": 69032,
"author": "Jason Dagit",
"author_id": 5113,
"author_profile": "https://Stackoverflow.com/users/5113",
"pm_score": 1,
"selected": false,
"text": "<p>In this case I would use a macro. You can start recording a macro with C-x (, and stop recording it with C-x ). When you want to replay the macro type C-x e.</p>\n\n<p>In this case, I would type, C-a C-x ( C-s v a l u e C-f C-f \\ RET SPC SPC SPC SPC C-x )</p>\n\n<p>That would record a macro that searches for \"value\", moves forward 2, inserts a slash and newline, and finally spaces the new line over to line up. Then you could repeat this macro a few times.</p>\n\n<p>EDIT: I just realized, your literal text may not be as easy to search as \"value1\". You could also search for spaces and cycle through the hits. For example, hitting, C-s a few times after the first match to skip over some of the matches.</p>\n\n<p>Note: Since your example is \"ad-hoc\" this solution will be too. Often you use macros when you need an ad-hoc solution. One way to make the macro apply more consistently is to put the original statement all on one line (can also be done by a macro or manually).</p>\n\n<p>EDIT: Thanks for the comment about ( versus C-(, you were right my mistake!</p>\n"
},
{
"answer_id": 69161,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": 0,
"selected": false,
"text": "<p>Personally, I do stuff like this all the time.</p>\n\n<p>But I don't write a function to do it unless I'll be doing it\nevery day for a year.</p>\n\n<p>You can easily do it with query-replace, like this:</p>\n\n<p>m-x (query-replace \" -option\" \"^Q^J -option\")</p>\n\n<p>I say ^Q^J as that is what you'll type to quote a newline and put it in\nthe string.</p>\n\n<p>Then just press 'y' for the strings to replace, and 'n' to skip the wierd\ncorner cases you'd find.</p>\n\n<p>Another workhorse function is query-replace-regexp that can do\nreplacements of regular expressions.</p>\n\n<p>and also grep-query-replace, which will perform query-replace by parsing\nthe output of a grep command. This is useful because you can search\nfor \"foo\" in 100 files, then do the query-replace on each occurrence\nskipping from file to file.</p>\n"
},
{
"answer_id": 69274,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 0,
"selected": false,
"text": "<p>Your mode may support this already. In C mode and Makefile mode, at least, M-q (fill-paragraph) will insert line continuations in the fill-column and wrap your lines.</p>\n\n<p>What mode are you editing this in?</p>\n"
},
{
"answer_id": 76888,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 3,
"selected": true,
"text": "<p>Nobody had what I was looking for so I decided to dust off my elisp manual and do it myself. This seems to work well enough, though the output isn't precisely what I asked for. In this version the first option goes on a line by itself instead of staying on the first line like in my original question.</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(defun tcl-multiline-options ()\n \"spread option/value pairs across multiple lines with continuation characters\"\n (interactive)\n (save-excursion\n (tcl-join-continuations)\n (beginning-of-line)\n (while (re-search-forward \" -[^ ]+ +\" (line-end-position) t)\n (goto-char (match-beginning 0))\n (insert \" \\\\\\n\")\n (goto-char (+(match-end 0) 3))\n (indent-according-to-mode)\n (forward-sexp))))\n\n(defun tcl-join-continuations ()\n \"join multiple continuation lines into a single physical line\"\n (interactive)\n (while (progn (end-of-line) (char-equal (char-before) ?\\\\))\n (forward-line 1))\n (while (save-excursion (end-of-line 0) (char-equal (char-before) ?\\\\))\n (end-of-line 0)\n (delete-char -1)\n (delete-char 1)\n (fixup-whitespace)))\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7432/"
]
| Say I have a line in an emacs buffer that looks like this:
```
foo -option1 value1 -option2 value2 -option3 value3 \
-option4 value4 ...
```
I want it to look like this:
```
foo -option1 value1 \
-option2 value2 \
-option3 value3 \
-option4 value4 \
...
```
I want each option/value pair on a separate line. I also want those subsequent lines indented appropriately according to mode rather than to add a fixed amount of whitespace. I would prefer that the code work on the current block, stopping at the first non-blank line or line that does not contain an option/value pair though I could settle for it working on a selected region.
Anybody know of an elisp function to do this? | Nobody had what I was looking for so I decided to dust off my elisp manual and do it myself. This seems to work well enough, though the output isn't precisely what I asked for. In this version the first option goes on a line by itself instead of staying on the first line like in my original question.
```lisp
(defun tcl-multiline-options ()
"spread option/value pairs across multiple lines with continuation characters"
(interactive)
(save-excursion
(tcl-join-continuations)
(beginning-of-line)
(while (re-search-forward " -[^ ]+ +" (line-end-position) t)
(goto-char (match-beginning 0))
(insert " \\\n")
(goto-char (+(match-end 0) 3))
(indent-according-to-mode)
(forward-sexp))))
(defun tcl-join-continuations ()
"join multiple continuation lines into a single physical line"
(interactive)
(while (progn (end-of-line) (char-equal (char-before) ?\\))
(forward-line 1))
(while (save-excursion (end-of-line 0) (char-equal (char-before) ?\\))
(end-of-line 0)
(delete-char -1)
(delete-char 1)
(fixup-whitespace)))
``` |
68,999 | <p>I'm using a Java socket, connected to a server.
If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?</p>
<p>I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only. </p>
| [
{
"answer_id": 69105,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 4,
"selected": false,
"text": "<p>You can use time and curl and time on the command-line. The -I argument for curl instructs it to only request the header.</p>\n\n<pre><code>time curl -I 'http://server:3000'\n</code></pre>\n"
},
{
"answer_id": 69195,
"author": "Dave Cheney",
"author_id": 6449,
"author_profile": "https://Stackoverflow.com/users/6449",
"pm_score": 3,
"selected": false,
"text": "<p>Something like this might do the trick</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.IOException;\n\nimport org.apache.commons.httpclient.HttpClient;\nimport org.apache.commons.httpclient.HttpMethod;\nimport org.apache.commons.httpclient.URIException;\nimport org.apache.commons.httpclient.methods.HeadMethod;\nimport org.apache.commons.lang.time.StopWatch;\n//import org.apache.commons.lang3.time.StopWatch\n\npublic class Main {\n\n public static void main(String[] args) throws URIException {\n StopWatch watch = new StopWatch();\n HttpClient client = new HttpClient();\n HttpMethod method = new HeadMethod("http://stackoverflow.com/");\n \n try {\n watch.start();\n client.executeMethod(method);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n watch.stop();\n }\n \n System.out.println(String.format("%s %s %d: %s", method.getName(), method.getURI(), method.getStatusCode(), watch.toString()));\n \n }\n}\n</code></pre>\n<pre class=\"lang-text prettyprint-override\"><code>HEAD http://stackoverflow.com/ 200: 0:00:00.404\n</code></pre>\n"
},
{
"answer_id": 69210,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe I'm missing something, but why don't you just use:</p>\n\n<pre><code>// open your connection\nlong start = System.currentTimeMillis();\n// send request, wait for response (the simple socket calls are all blocking)\nlong end = System.currentTimeMillis();\nSystem.out.println(\"Round trip response time = \" + (end-start) + \" millis\");\n</code></pre>\n"
},
{
"answer_id": 69223,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 5,
"selected": true,
"text": "<p>I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only?</p>\n\n<p>If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example:</p>\n\n<pre><code>public void sendHttpRequest(byte[] requestData, Socket connection) {\n long startTime = System.nanoTime();\n writeYourRequestData(connection.getOutputStream(), requestData);\n byte[] responseData = readYourResponseData(connection.getInputStream());\n long elapsedTime = System.nanoTime() - startTime;\n System.out.println(\"Total elapsed http request/response time in nanoseconds: \" + elapsedTime);\n}\n</code></pre>\n\n<p>This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented).</p>\n"
},
{
"answer_id": 69488,
"author": "Adisesha",
"author_id": 11092,
"author_profile": "https://Stackoverflow.com/users/11092",
"pm_score": 0,
"selected": false,
"text": "<p>Use AOP to intercept calls to the socket and measure the response time.</p>\n"
},
{
"answer_id": 12526594,
"author": "A B",
"author_id": 167362,
"author_profile": "https://Stackoverflow.com/users/167362",
"pm_score": 4,
"selected": false,
"text": "<p><code>curl -s -w \"%{time_total}\\n\" -o /dev/null http://server:3000</code></p>\n"
},
{
"answer_id": 54348183,
"author": "Sudabe-Neirizi",
"author_id": 9820210,
"author_profile": "https://Stackoverflow.com/users/9820210",
"pm_score": 0,
"selected": false,
"text": "<pre><code>@Aspect\n@Profile(\"performance\")\n@Component\npublic class MethodsExecutionPerformance {\n private final Logger logger = LoggerFactory.getLogger(getClass());\n\n @Pointcut(\"execution(* it.test.microservice.myService.service.*.*(..))\")\n public void serviceMethods() {\n }\n\n @Around(\"serviceMethods()\")\n public Object monitorPerformance(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {\n StopWatch stopWatch = new StopWatch(getClass().getName());\n stopWatch.start();\n Object output = proceedingJoinPoint.proceed();\n stopWatch.stop();\n logger.info(\"Method execution time\\n{}\", stopWatch.prettyPrint());\n return output;\n }\n}\n</code></pre>\n\n<p>In this way, you can calculate the real response time of your service independent of network speed. </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/68999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10889/"
]
| I'm using a Java socket, connected to a server.
If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?
I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only. | I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only?
If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example:
```
public void sendHttpRequest(byte[] requestData, Socket connection) {
long startTime = System.nanoTime();
writeYourRequestData(connection.getOutputStream(), requestData);
byte[] responseData = readYourResponseData(connection.getInputStream());
long elapsedTime = System.nanoTime() - startTime;
System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime);
}
```
This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented). |
69,000 | <p>I have a WPF application in VS 2008 with some web service references. For varying reasons (max message size, authentication methods) I need to manually define a number of settings in the WPF client's app.config for the service bindings.</p>
<p>Unfortunately, this means that when I update the service references in the project we end up with a mess - multiple bindings and endpoints. Visual Studio creates new bindings and endpoints with a numeric suffix (ie "Service1" as a duplicate of "Service"), resulting in an invalid configuration as there may only be a single binding per service reference in a project.</p>
<p>This is easy to duplicate - just create a simple "Hello World" ASP.Net web service and WPF application in a solution, change the maxBufferSize and maxReceivedMessageSize in the app.config binding and then update the service reference.</p>
<p>At the moment we are working around this by simply undoing checkout on the app.config after updating the references but I can't help but think there must be a better way!</p>
<p>Also, the settings we need to manually change are:</p>
<pre><code><security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
</code></pre>
<p>and:</p>
<pre><code><binding maxBufferSize="655360" maxReceivedMessageSize="655360" />
</code></pre>
<p>We use a service factory class so if these settings are somehow able to be set programmatically that would work, although the properties don't seem to be exposed.</p>
| [
{
"answer_id": 69154,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 0,
"selected": false,
"text": "<p>Somehow I prefer using svcutil.exe directly than to use the \"Add Service Reference\" feature of Visual Studio :P This is what we're doing on our WCF projects.</p>\n"
},
{
"answer_id": 69557,
"author": "Nathan",
"author_id": 10890,
"author_profile": "https://Stackoverflow.com/users/10890",
"pm_score": 0,
"selected": false,
"text": "<p>I take your point, svcutil is definetly the more advanced way of adding and updating service references. Its just a fair bit more manual work when \"right click, update reference\" is so close to just working in a single step.</p>\n\n<p>I guess we could create some batch files or something to just output the reference code. Even then, manually checking out and updating the service code with svcutil will probably be more work than just undoing the check out on the config.</p>\n\n<p>Thanks for the advice in any case.</p>\n"
},
{
"answer_id": 69654,
"author": "Wiren",
"author_id": 2538222,
"author_profile": "https://Stackoverflow.com/users/2538222",
"pm_score": 3,
"selected": true,
"text": "<p>Create a .Bat file which uses svcutil, for proxygeneration, that has the settings that is right for your project. It's fairly easy. Clicking on the batfile, to generate new proxyfiles whenever the interface have been changed is easy.</p>\n\n<p>The batch can then later be used in automated builds. Then you only need to set up the app.config (or web.config) once. We generally separate the different configs for different environments, such as dev, test prod.</p>\n\n<p>Example (watch out for linebreaks):</p>\n\n<pre><code>REM generate meta data\ncall \"SVCUTIL.EXE\" /t:metadata \"MyProject.dll\" /reference:\"MyReference.dll\"\n\nREM making sure the file is writable\nattrib -r \"MyServiceProxy.cs\"\n\nREM create new proxy file\ncall \"SVCUTIL.EXE\" /t:code *.wsdl *.xsd /serializable /serializer:Auto /collectionType:System.Collections.Generic.List`1 /out:\"MyServiceProxy.cs\" /namespace:*,MY.Name.Space /reference:\"MyReference.dll\" \n</code></pre>\n\n<p>:)</p>\n\n<p>//W</p>\n"
},
{
"answer_id": 73154,
"author": "Dylan",
"author_id": 4580,
"author_profile": "https://Stackoverflow.com/users/4580",
"pm_score": 2,
"selected": false,
"text": "<p>Rather than changing the generated endpoint, uou could add a second endpoint and binding definition with the configuration you need, then in your code just put the name of the new endpoint in your service client constructor.</p>\n"
},
{
"answer_id": 80534,
"author": "cruizer",
"author_id": 6441,
"author_profile": "https://Stackoverflow.com/users/6441",
"pm_score": 0,
"selected": false,
"text": "<p>What we do is we check out (from source control) the app.config and *.cs files that are autogenerated by the svcutil.exe utility, then we run a batch file that runs svcutil.exe to retrieve the service metadata. When it's done, we recompile the code, make sure it works, then check the updated app.config and *.cs files back in. It's a whole lot more reliable than using the oft-buggy \"Add Service Reference\" with Visual Studio.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10890/"
]
| I have a WPF application in VS 2008 with some web service references. For varying reasons (max message size, authentication methods) I need to manually define a number of settings in the WPF client's app.config for the service bindings.
Unfortunately, this means that when I update the service references in the project we end up with a mess - multiple bindings and endpoints. Visual Studio creates new bindings and endpoints with a numeric suffix (ie "Service1" as a duplicate of "Service"), resulting in an invalid configuration as there may only be a single binding per service reference in a project.
This is easy to duplicate - just create a simple "Hello World" ASP.Net web service and WPF application in a solution, change the maxBufferSize and maxReceivedMessageSize in the app.config binding and then update the service reference.
At the moment we are working around this by simply undoing checkout on the app.config after updating the references but I can't help but think there must be a better way!
Also, the settings we need to manually change are:
```
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Ntlm" />
</security>
```
and:
```
<binding maxBufferSize="655360" maxReceivedMessageSize="655360" />
```
We use a service factory class so if these settings are somehow able to be set programmatically that would work, although the properties don't seem to be exposed. | Create a .Bat file which uses svcutil, for proxygeneration, that has the settings that is right for your project. It's fairly easy. Clicking on the batfile, to generate new proxyfiles whenever the interface have been changed is easy.
The batch can then later be used in automated builds. Then you only need to set up the app.config (or web.config) once. We generally separate the different configs for different environments, such as dev, test prod.
Example (watch out for linebreaks):
```
REM generate meta data
call "SVCUTIL.EXE" /t:metadata "MyProject.dll" /reference:"MyReference.dll"
REM making sure the file is writable
attrib -r "MyServiceProxy.cs"
REM create new proxy file
call "SVCUTIL.EXE" /t:code *.wsdl *.xsd /serializable /serializer:Auto /collectionType:System.Collections.Generic.List`1 /out:"MyServiceProxy.cs" /namespace:*,MY.Name.Space /reference:"MyReference.dll"
```
:)
//W |
69,030 | <p>I have a script for OS X 10.5 that focuses the Search box in the Help menu of any application. I have it on a key combination and, much like Spotlight, I want it to toggle when I run the script. So, I want to detect if the search box is already focused for typing, and if so, type Esc instead of clicking the Help menu.</p>
<p>Here is the script as it stands now:</p>
<pre><code>tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
click helpMenuItem
end tell
end tell
</code></pre>
<p>And I'm thinking of something like this:</p>
<pre><code>tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
set searchBox to menu item 1 of menu of helpMenuItem
if (searchBox's focused) = true then
key code 53 -- type esc
else
click helpMenuItem
end if
end tell
end tell
</code></pre>
<p>... but I get this error:</p>
<blockquote>
<p>Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.</p>
</blockquote>
<p>So is there a way I can get my script to detect whether the search box is already focused?</p>
<hr>
<p>I solved my problem by <a href="https://stackoverflow.com/questions/69391/">working around it</a>. I still don't know how to check if a menu item is selected though, so I will leave this topic open.</p>
| [
{
"answer_id": 69404,
"author": "tjw",
"author_id": 11029,
"author_profile": "https://Stackoverflow.com/users/11029",
"pm_score": 3,
"selected": true,
"text": "<p>Using /Developer/Applications/Utilities/Accessibility Tools/Accessibility Inspector.app you can use the built-in accessibility system to look at properties of the UI element under the mouse. Take special note of the cmd-F7 action to lock focus on an element and the Refresh button. Sadly the element and property names don't directly match those in the script suite, but you can look at the dictionary for System Events or usually guess the right terminology.</p>\n\n<p>Using this you can determine two things. First, the <code>focused</code> property isn't on the <code>menu item</code>, but rather there is a <code>text field</code> within the <code>menu item</code> that is focused. Second, the menu item has a <code>selected</code> property.</p>\n\n<p>With this, I came up with:</p>\n\n<pre><code>tell application \"System Events\"\n tell (first process whose frontmost is true)\n set helpMenuItem to menu bar item \"Help\" of menu bar 1\n\n -- Use reference form to avoid building intermediate object specifiers, which Accessibility apparently isn't good at resolving after the fact.\n set searchBox to a reference to menu item 1 of menu of helpMenuItem\n set searchField to a reference to text field 1 of searchBox\n\n if searchField's focused is true then\n key code 53 -- type esc\n else\n click helpMenuItem\n end if\n end tell\nend tell\n</code></pre>\n\n<p>Though this still doesn't work. The key event isn't firing as far as I can tell, so something may still be hinky with the <code>focused</code> property on the text field.</p>\n\n<p>Anyway, your <code>click</code> again solution seems much easier.</p>\n"
},
{
"answer_id": 90626,
"author": "Ken",
"author_id": 17320,
"author_profile": "https://Stackoverflow.com/users/17320",
"pm_score": 2,
"selected": false,
"text": "<p>The built in key shortcut <kbd>Cmd-?</kbd> (<kbd>Cmd-Shift-/</kbd>) already behaves like this. It moves key focus to the help menu's search field if it is not already focused, and otherwise dismisses the menu.</p>\n"
},
{
"answer_id": 1545862,
"author": "Steve Jones",
"author_id": 187427,
"author_profile": "https://Stackoverflow.com/users/187427",
"pm_score": 2,
"selected": false,
"text": "<p>I just came across the need to do this myself for some file processing in Illustrator.</p>\n\n<p>Here is what I came up with:</p>\n\n<pre><code>tell application \"Adobe Illustrator\"\nactivate\ntell application \"System Events\"\n tell process \"Illustrator\"\n set frontmost to true\n set activeMenuItem to enabled of menu item \"Unlock All\" of menu \"Object\" of menu bar item \"Object\" of menu bar 1\n if activeMenuItem is true then\n tell me to beep 3\n else\n tell me to beep 2\n end if\n end tell\nend tell\nend tell\n</code></pre>\n\n<p>Done.</p>\n\n<p>This worked with no problem and could be used to iterate a file. I'll probably have to do this many more times in my future automation.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 35948626,
"author": "Chester Rieman",
"author_id": 4821121,
"author_profile": "https://Stackoverflow.com/users/4821121",
"pm_score": 2,
"selected": false,
"text": "<p>You need to use attribute <code>AXMenuItemMarkChar</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>tell application \"System Events\"\n tell process \"Cisco Jabber\"\n set X to (value of attribute \"AXMenuItemMarkChar\" of menu item \"Available\" of menu \"Status\" of menu item \"Status\" of menu \"File\" of menu bar item \"File\" of menu bar 1) is \"✓\" -- check if Status is \"Availible\" \n end tell\nend tell\n</code></pre>\n\n<p>If the menu item is checked, the return value is <code>✓</code>, otherwise it is <code>missing value</code>.</p>\n\n<p>Note: This test only works if the application whose menus are being inspected is currently <em>frontmost</em>.</p>\n"
},
{
"answer_id": 65835776,
"author": "Tao Starbow",
"author_id": 1578589,
"author_profile": "https://Stackoverflow.com/users/1578589",
"pm_score": 0,
"selected": false,
"text": "<p>This worked for me to toggle between two menu items, based on which one is selected, using the "selected" property:</p>\n<pre><code>tell application "System Preferences"\n reveal anchor "keyboardTab" of pane "com.apple.preference.keyboard"\nend tell\ntell application "System Events" to tell process "System Preferences"\n tell pop up button 2 of tab group 1 of window 1\n click\n delay 0.2\n set appControl to menu item "App Controls" of menu 1\n set fKeys to menu item "F1, F2, etc. Keys" of menu 1\n if selected of appControl is true then\n click fKeys\n else\n click appControl\n end if\n end tell\nend tell\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10906/"
]
| I have a script for OS X 10.5 that focuses the Search box in the Help menu of any application. I have it on a key combination and, much like Spotlight, I want it to toggle when I run the script. So, I want to detect if the search box is already focused for typing, and if so, type Esc instead of clicking the Help menu.
Here is the script as it stands now:
```
tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
click helpMenuItem
end tell
end tell
```
And I'm thinking of something like this:
```
tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
set searchBox to menu item 1 of menu of helpMenuItem
if (searchBox's focused) = true then
key code 53 -- type esc
else
click helpMenuItem
end if
end tell
end tell
```
... but I get this error:
>
> Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.
>
>
>
So is there a way I can get my script to detect whether the search box is already focused?
---
I solved my problem by [working around it](https://stackoverflow.com/questions/69391/). I still don't know how to check if a menu item is selected though, so I will leave this topic open. | Using /Developer/Applications/Utilities/Accessibility Tools/Accessibility Inspector.app you can use the built-in accessibility system to look at properties of the UI element under the mouse. Take special note of the cmd-F7 action to lock focus on an element and the Refresh button. Sadly the element and property names don't directly match those in the script suite, but you can look at the dictionary for System Events or usually guess the right terminology.
Using this you can determine two things. First, the `focused` property isn't on the `menu item`, but rather there is a `text field` within the `menu item` that is focused. Second, the menu item has a `selected` property.
With this, I came up with:
```
tell application "System Events"
tell (first process whose frontmost is true)
set helpMenuItem to menu bar item "Help" of menu bar 1
-- Use reference form to avoid building intermediate object specifiers, which Accessibility apparently isn't good at resolving after the fact.
set searchBox to a reference to menu item 1 of menu of helpMenuItem
set searchField to a reference to text field 1 of searchBox
if searchField's focused is true then
key code 53 -- type esc
else
click helpMenuItem
end if
end tell
end tell
```
Though this still doesn't work. The key event isn't firing as far as I can tell, so something may still be hinky with the `focused` property on the text field.
Anyway, your `click` again solution seems much easier. |
69,068 | <p>How can I split long commands over multiple lines in a batch file?</p>
| [
{
"answer_id": 69079,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 11,
"selected": true,
"text": "<p>You can break up long lines with the caret <code>^</code> as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. <em>(<a href=\"https://stackoverflow.com/a/21000752/157247\">More on that below.</a>)</em></p>\n\n<p>Example:</p>\n\n<pre><code>copy file1.txt file2.txt\n</code></pre>\n\n<p>would be written as:</p>\n\n<pre><code>copy file1.txt^\n file2.txt\n</code></pre>\n"
},
{
"answer_id": 4455750,
"author": "jeb",
"author_id": 463115,
"author_profile": "https://Stackoverflow.com/users/463115",
"pm_score": 8,
"selected": false,
"text": "<p>The rule for the caret is:</p>\n\n<p>A caret at the line end, appends the next line, the first character of the appended line will be escaped.</p>\n\n<p>You can use the caret multiple times, but the complete line must not exceed the maximum line length of ~8192 characters (Windows XP, Windows Vista, and Windows 7).</p>\n\n<pre><code>echo Test1\necho one ^\ntwo ^\nthree ^\nfour^\n*\n--- Output ---\nTest1\none two three four*\n\necho Test2\necho one & echo two\n--- Output ---\nTest2\none\ntwo\n\necho Test3\necho one & ^\necho two\n--- Output ---\nTest3\none\ntwo\n\necho Test4\necho one ^\n& echo two\n--- Output ---\nTest4\none & echo two\n</code></pre>\n\n<p>To suppress the escaping of the next character you can use a redirection.</p>\n\n<p>The redirection has to be just before the caret.\nBut there exist one curiosity with redirection before the caret.</p>\n\n<p>If you place a token at the caret the token is removed.</p>\n\n<pre><code>echo Test5\necho one <nul ^\n& echo two\n--- Output ---\nTest5\none\ntwo\n\n\necho Test6\necho one <nul ThisTokenIsLost^\n& echo two\n--- Output ---\nTest6\none\ntwo\n</code></pre>\n\n<p>And it is also possible to <strong>embed line feeds</strong> into the string:</p>\n\n<pre><code>setlocal EnableDelayedExpansion\nset text=This creates ^\n\na line feed\necho Test7: %text%\necho Test8: !text!\n--- Output ---\nTest7: This creates\nTest8: This creates\na line feed\n</code></pre>\n\n<p>The empty line is important for the success. This works only with delayed expansion, else the rest of the line is ignored after the line feed.</p>\n\n<p>It works, because the caret at the line end ignores the next line feed and escapes the next character, even if the next character is also a line feed (carriage returns are always ignored in this phase).</p>\n"
},
{
"answer_id": 21000752,
"author": "T.J. Crowder",
"author_id": 157247,
"author_profile": "https://Stackoverflow.com/users/157247",
"pm_score": 7,
"selected": false,
"text": "<p><em>(This is basically a rewrite of <a href=\"https://stackoverflow.com/a/69079/157247\">Wayne's answer</a> but with the confusion around the caret cleared up. So I've posted it as a CW. I'm not shy about editing answers, but <strong>completely rewriting them</strong> seems inappropriate.)</em></p>\n<p>You can break up long lines with the caret (<code>^</code>), just remember that the caret and the newline that follows it <em>are removed entirely</em> from the command, so if you put it where a space would be required (such as between parameters), be sure to include the space as well (either before the <code>^</code>, or at the beginning of the next line — that latter choice may help make it clearer it's a continuation).</p>\n<p>⚠ Note: The first character of the next line is escaped. So if it carries any special meaning (like <code>&</code> or <code>|</code>), that meaning will be lost and it will be interpreted as a pure text character (see last example at bottom).</p>\n<p>Examples: <em>(all tested on Windows XP and Windows 7)</em></p>\n<pre><code>xcopy file1.txt file2.txt\n</code></pre>\n<p>can be written as:</p>\n<pre><code>xcopy^\n file1.txt^\n file2.txt\n</code></pre>\n<p>or</p>\n<pre><code>xcopy ^\nfile1.txt ^\nfile2.txt\n</code></pre>\n<p>or even</p>\n<pre><code>xc^\nopy ^\nfile1.txt ^\nfile2.txt\n</code></pre>\n<p>(That last works because there are no spaces betwen the <code>xc</code> and the <code>^</code>, and no spaces at the beginning of the next line. So when you remove the <code>^</code> and the newline, you get...<code>xcopy</code>.)</p>\n<p>For readability and sanity, it's probably best breaking only between parameters (be sure to include the space).</p>\n<p>Be sure that the <code>^</code> is <strong>not</strong> the last thing in a batch file, as there <a href=\"https://stackoverflow.com/questions/15466298/simple-caret-in-batch-file-consumes-all-memory\">appears to be a major issue with that</a>.</p>\n<p>Here's an example of character escaped at the start of the next line:</p>\n<pre><code>xcopy file1.txt file2.txt ^\n& echo copied successfully\n</code></pre>\n<p>This will not work because <code>&</code> will be escaped and lose its special meaning, thus sending all of "file1.txt file2.txt & echo copied successfully" as parameters to <code>xcopy</code>, causing an error (in this example).</p>\n<p>To circumvent, <strong>add a space</strong> at the beginning of the next line.</p>\n"
},
{
"answer_id": 25471056,
"author": "Mohammed Safwat",
"author_id": 493119,
"author_profile": "https://Stackoverflow.com/users/493119",
"pm_score": 4,
"selected": false,
"text": "<p>It seems however that splitting in the middle of the values of a for loop doesn't need a caret(and actually trying to use one will be considered a syntax error). For example,</p>\n\n<pre><code>for %n in (hello\nbye) do echo %n\n</code></pre>\n\n<p>Note that no space is even needed after hello or before bye.</p>\n"
},
{
"answer_id": 35371129,
"author": "Todd Partridge",
"author_id": 4515565,
"author_profile": "https://Stackoverflow.com/users/4515565",
"pm_score": 5,
"selected": false,
"text": "<p>Multiple commands can be put in parenthesis and spread over numerous lines; so something like <code>echo hi && echo hello</code> can be put like this:</p>\n\n<pre><code>( echo hi\n echo hello )\n</code></pre>\n\n<p>Also variables can help:</p>\n\n<pre><code>set AFILEPATH=\"C:\\SOME\\LONG\\PATH\\TO\\A\\FILE\"\nif exist %AFILEPATH% (\n start \"\" /b %AFILEPATH% -option C:\\PATH\\TO\\SETTING...\n) else (\n...\n</code></pre>\n\n<p>Also I noticed with carets (<code>^</code>) that the <code>if</code> conditionals liked them to follow only if a space was present:</p>\n\n<pre><code>if exist ^\n</code></pre>\n"
},
{
"answer_id": 64752041,
"author": "npocmaka",
"author_id": 388389,
"author_profile": "https://Stackoverflow.com/users/388389",
"pm_score": 3,
"selected": false,
"text": "<p>Though the carret will be preferable way to do this here's one more approach using macro that constructs a command by the passed arguments:</p>\n<pre><code>@echo off\n::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\nset "{{=setlocal enableDelayedExpansion&for %%a in (" & set "}}="::end::" ) do if "%%~a" neq "::end::" (set command=!command! %%a) else (call !command! & endlocal)"\n:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::\n\n%{{%\n echo\n "command"\n written\n on a\n few lines\n%}}%\n</code></pre>\n<p>command is easier to read without the carets but using special symbols e.g. brackets,redirection and so on will break it. So you can this for more simpler cases. Though you can still enclose parameters in double quotes</p>\n"
},
{
"answer_id": 68470236,
"author": "Simon H",
"author_id": 7071220,
"author_profile": "https://Stackoverflow.com/users/7071220",
"pm_score": 3,
"selected": false,
"text": "<p>One thing I did not find when searching for 'how to split a long DOS batch file line' was how to split something containing long quoted text.\nIn fact it IS covered in the answers above, but is not obvious. Use Caret to escape them.\ne.g.</p>\n<pre><code>myprog "needs this to be quoted"\n</code></pre>\n<p>can be written as:</p>\n<pre><code>myprog ^"needs this ^\nto be quoted^"\n</code></pre>\n<p>but beware of starting a line with Caret after ending a line with caret - because it will come out as caret..?:</p>\n<pre><code>echo ^"^\nneeds this ^\nto be quoted^\n^"\n</code></pre>\n<p>-> "needs this to be quoted^"</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How can I split long commands over multiple lines in a batch file? | You can break up long lines with the caret `^` as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. *([More on that below.](https://stackoverflow.com/a/21000752/157247))*
Example:
```
copy file1.txt file2.txt
```
would be written as:
```
copy file1.txt^
file2.txt
``` |
69,089 | <p>We have a web application that uses SQL Server 2008 as the database. Our users are able to do full-text searches on particular columns in the database. SQL Server's full-text functionality does not seem to provide support for hit highlighting. Do we need to build this ourselves or is there perhaps some library or knowledge around on how to do this? </p>
<p>BTW the application is written in C# so a .Net solution would be ideal but not necessary as we could translate.</p>
| [
{
"answer_id": 74932,
"author": "WIDBA",
"author_id": 10868,
"author_profile": "https://Stackoverflow.com/users/10868",
"pm_score": 1,
"selected": false,
"text": "<p>You might be missing the point of the database in this instance. Its job is to return the data to you that satisfies the conditions you gave it. I think you will want to implement the highlighting probably using regex in your web control.</p>\n\n<p>Here is something a quick search would reveal.</p>\n\n<p><a href=\"http://www.dotnetjunkies.com/PrintContent.aspx?type=article&id=195E323C-78F3-4884-A5AA-3A1081AC3B35\" rel=\"nofollow noreferrer\">http://www.dotnetjunkies.com/PrintContent.aspx?type=article&id=195E323C-78F3-4884-A5AA-3A1081AC3B35</a></p>\n"
},
{
"answer_id": 127080,
"author": "xnagyg",
"author_id": 2622295,
"author_profile": "https://Stackoverflow.com/users/2622295",
"pm_score": 1,
"selected": false,
"text": "<p>Some details:</p>\n\n<pre><code> search_kiemeles=replace(lcase(search),\"\"\"\",\"\")\n do while not rs.eof 'The search result loop\n hirdetes=rs(\"hirdetes\")\n data=RegExpValueA(\"([A-Za-zöüóőúéáűíÖÜÓŐÚÉÁŰÍ0-9]+)\",search_kiemeles) 'Give back all the search words in an array, I need non-english characters also\n For i=0 to Ubound(data,1)\n hirdetes = RegExpReplace(hirdetes,\"(\"&NoAccentRE(data(i))&\")\",\"<em>$1</em>\")\n Next\n response.write hirdetes\n rs.movenext\n Loop\n ...\n</code></pre>\n\n<p>Functions</p>\n\n<pre><code>'All Match to Array\nFunction RegExpValueA(patrn, strng)\n Dim regEx\n Set regEx = New RegExp ' Create a regular expression.\n regEx.IgnoreCase = True ' Set case insensitivity.\n regEx.Global = True\n Dim Match, Matches, RetStr\n Dim data()\n Dim count\n count = 0\n Redim data(-1) 'VBSCript Ubound array bug workaround\n if isnull(strng) or strng=\"\" then\n RegExpValueA = data\n exit function\n end if\n regEx.Pattern = patrn ' Set pattern.\n Set Matches = regEx.Execute(strng) ' Execute search.\n For Each Match in Matches ' Iterate Matches collection.\n count = count + 1\n Redim Preserve data(count-1)\n data(count-1) = Match.Value\n Next\n set regEx = nothing\n RegExpValueA = data\nEnd Function\n\n'Replace non-english chars\nFunction NoAccentRE(accent_string)\n NoAccentRE=accent_string\n NoAccentRE=Replace(NoAccentRE,\"a\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"á\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[aá]\")\n NoAccentRE=Replace(NoAccentRE,\"e\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"é\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[eé]\")\n NoAccentRE=Replace(NoAccentRE,\"i\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"í\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[ií]\")\n NoAccentRE=Replace(NoAccentRE,\"o\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ó\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ö\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ő\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[oóöő]\")\n NoAccentRE=Replace(NoAccentRE,\"u\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ú\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ü\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"ű\",\"§\")\n NoAccentRE=Replace(NoAccentRE,\"§\",\"[uúüű]\")\nend function\n</code></pre>\n"
},
{
"answer_id": 619964,
"author": "Ishmael",
"author_id": 8930,
"author_profile": "https://Stackoverflow.com/users/8930",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you could parse the output of the new <a href=\"http://msdn.microsoft.com/en-us/library/cc280463.aspx\" rel=\"nofollow noreferrer\">SQL Server 2008 stored procedure sys.dm_fts_parser</a> and use regex, but I haven't looked at it too closely.</p>\n"
},
{
"answer_id": 3338113,
"author": "Shagglez",
"author_id": 369166,
"author_profile": "https://Stackoverflow.com/users/369166",
"pm_score": 3,
"selected": true,
"text": "<p>Expanding on Ishmael's idea, it's not the final solution, but I think it's a good way to start. </p>\n\n<p>Firstly we need to get the list of words that have been retrieved with the full-text engine: </p>\n\n<pre><code>declare @SearchPattern nvarchar(1000) = 'FORMSOF (INFLECTIONAL, \" ' + @SearchString + ' \")' \ndeclare @SearchWords table (Word varchar(100), Expansion_type int)\ninsert into @SearchWords\nselect distinct display_term, expansion_type\nfrom sys.dm_fts_parser(@SearchPattern, 1033, 0, 0)\nwhere special_term = 'Exact Match'\n</code></pre>\n\n<p>There is already quite a lot one can expand on, for example the search pattern is quite basic; also there are probably better ways to filter out the words you don't need, but it least it gives you a list of stem words etc. that would be matched by full-text search.</p>\n\n<p>After you get the results you need, you can use RegEx to parse through the result set (or preferably only a subset to speed it up, although I haven't yet figured out a good way to do so). For this I simply use two while loops and a bunch of temporary table and variables:</p>\n\n<pre><code>declare @FinalResults table \nwhile (select COUNT(*) from @PrelimResults) > 0\nbegin\n select top 1 @CurrID = [UID], @Text = Text from @PrelimResults\n declare @TextLength int = LEN(@Text )\n declare @IndexOfDot int = CHARINDEX('.', REVERSE(@Text ), @TextLength - dbo.RegExIndexOf(@Text, '\\b' + @FirstSearchWord + '\\b') + 1)\n set @Text = SUBSTRING(@Text, case @IndexOfDot when 0 then 0 else @TextLength - @IndexOfDot + 3 end, 300)\n\n while (select COUNT(*) from @TempSearchWords) > 0\n begin\n select top 1 @CurrWord = Word from @TempSearchWords\n set @Text = dbo.RegExReplace(@Text, '\\b' + @CurrWord + '\\b', '<b>' + SUBSTRING(@Text, dbo.RegExIndexOf(@Text, '\\b' + @CurrWord + '\\b'), LEN(@CurrWord) + 1) + '</b>')\n delete from @TempSearchWords where Word = @CurrWord\n end\n\n insert into @FinalResults\n select * from @PrelimResults where [UID] = @CurrID\n delete from @PrelimResults where [UID] = @CurrID\nend\n</code></pre>\n\n<p><strong>Several notes:</strong><br>\n1. Nested while loops probably aren't the most efficient way of doing it, however nothing else comes to mind. If I were to use cursors, it would essentially be the same thing?<br>\n2. <code>@FirstSearchWord</code> here to refers to the first instance in the text of one of the original search words, so essentially the text you are replacing is only going to be in the summary. Again, it's quite a basic method, some sort of text cluster finding algorithm would probably be handy.<br>\n3. To get RegEx in the first place, you need CLR user-defined functions.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899/"
]
| We have a web application that uses SQL Server 2008 as the database. Our users are able to do full-text searches on particular columns in the database. SQL Server's full-text functionality does not seem to provide support for hit highlighting. Do we need to build this ourselves or is there perhaps some library or knowledge around on how to do this?
BTW the application is written in C# so a .Net solution would be ideal but not necessary as we could translate. | Expanding on Ishmael's idea, it's not the final solution, but I think it's a good way to start.
Firstly we need to get the list of words that have been retrieved with the full-text engine:
```
declare @SearchPattern nvarchar(1000) = 'FORMSOF (INFLECTIONAL, " ' + @SearchString + ' ")'
declare @SearchWords table (Word varchar(100), Expansion_type int)
insert into @SearchWords
select distinct display_term, expansion_type
from sys.dm_fts_parser(@SearchPattern, 1033, 0, 0)
where special_term = 'Exact Match'
```
There is already quite a lot one can expand on, for example the search pattern is quite basic; also there are probably better ways to filter out the words you don't need, but it least it gives you a list of stem words etc. that would be matched by full-text search.
After you get the results you need, you can use RegEx to parse through the result set (or preferably only a subset to speed it up, although I haven't yet figured out a good way to do so). For this I simply use two while loops and a bunch of temporary table and variables:
```
declare @FinalResults table
while (select COUNT(*) from @PrelimResults) > 0
begin
select top 1 @CurrID = [UID], @Text = Text from @PrelimResults
declare @TextLength int = LEN(@Text )
declare @IndexOfDot int = CHARINDEX('.', REVERSE(@Text ), @TextLength - dbo.RegExIndexOf(@Text, '\b' + @FirstSearchWord + '\b') + 1)
set @Text = SUBSTRING(@Text, case @IndexOfDot when 0 then 0 else @TextLength - @IndexOfDot + 3 end, 300)
while (select COUNT(*) from @TempSearchWords) > 0
begin
select top 1 @CurrWord = Word from @TempSearchWords
set @Text = dbo.RegExReplace(@Text, '\b' + @CurrWord + '\b', '<b>' + SUBSTRING(@Text, dbo.RegExIndexOf(@Text, '\b' + @CurrWord + '\b'), LEN(@CurrWord) + 1) + '</b>')
delete from @TempSearchWords where Word = @CurrWord
end
insert into @FinalResults
select * from @PrelimResults where [UID] = @CurrID
delete from @PrelimResults where [UID] = @CurrID
end
```
**Several notes:**
1. Nested while loops probably aren't the most efficient way of doing it, however nothing else comes to mind. If I were to use cursors, it would essentially be the same thing?
2. `@FirstSearchWord` here to refers to the first instance in the text of one of the original search words, so essentially the text you are replacing is only going to be in the summary. Again, it's quite a basic method, some sort of text cluster finding algorithm would probably be handy.
3. To get RegEx in the first place, you need CLR user-defined functions. |
69,104 | <p>A J2ME client is sending HTTP POST requests with chunked transfer encoding.</p>
<p>When ASP.NET (in both IIS6 and WebDev.exe.server) tries to read the request it sets the Content-Length to 0. I guess this is ok because the Content-length is unknown when the request is loaded.</p>
<p>However, when I read the Request.InputStream to the end, it returns 0.</p>
<p>Here's the code I'm using to read the input stream.</p>
<pre><code>using (var reader = new StreamReader(httpRequestBodyStream, BodyTextEncoding)) {
string readString = reader.ReadToEnd();
Console.WriteLine("CharSize:" + readString.Length);
return BodyTextEncoding.GetBytes(readString);
}
</code></pre>
<p>I can simulate the behaiviour of the client with Fiddler, e.g.</p>
<p><strong>URL</strong>
<a href="http://localhost:15148/page.aspx" rel="nofollow noreferrer">http://localhost:15148/page.aspx</a></p>
<p><strong>Headers:</strong>
User-Agent: Fiddler
Transfer-Encoding: Chunked
Host: somesite.com:15148</p>
<p><strong>Body</strong>
rabbits rabbits rabbits rabbits. thanks for coming, it's been very useful!</p>
<p>My body reader from above will return a zero length byte array...lame...</p>
<p>Does anyone know how to enable chunked encoding on IIS and ASP.NET Development Server (cassini)?</p>
<p>I found <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;278998" rel="nofollow noreferrer">this script</a> for IIS but it isn't working.</p>
| [
{
"answer_id": 80576,
"author": "Andrew",
"author_id": 15127,
"author_profile": "https://Stackoverflow.com/users/15127",
"pm_score": 1,
"selected": false,
"text": "<p>That url does not work any more, so it's hard to test this directly. I wondered if this would work, and google turned up someone who has experience with it at <a href=\"http://bytes.com/forum/thread246706.html\" rel=\"nofollow noreferrer\">bytes.com</a>. If you put your website up again, I can see if this really works there. </p>\n\n<p><strong>Joerg Jooss</strong> wrote: (<em>slightly modified for brevity</em> )</p>\n\n<pre><code>string responseText = null;\nWebRequest rabbits= WebRequest.Create(uri);\nusing (Stream resp = rabbits.GetResponse().GetResponseStream()) {\n MemoryStream memoryStream = new MemoryStream(0x10000);\n byte[] buffer = new byte[0x1000];\n int bytes;\n while ((bytes = resp.Read(buffer, 0, buffer.Length)) > 0) {\n memoryStream.Write(buffer, 0, bytes);\n }\n // use the encoding to match the data source.\n Encoding enc = Encoding.UTF8;\n reponseText = enc.GetString(memoryStream.ToArray());\n}\n</code></pre>\n"
},
{
"answer_id": 4294031,
"author": "Anton Tykhyy",
"author_id": 77724,
"author_profile": "https://Stackoverflow.com/users/77724",
"pm_score": 2,
"selected": false,
"text": "<p>Seems to be official: <a href=\"http://msdn.microsoft.com/en-us/library/ee960144.aspx\" rel=\"nofollow\">Cassini does not support <code>Transfer-Encoding: chunked</code> requests.</a></p>\n\n<blockquote>\n <p>By default, the client sends large\n binary streams by using a chunked HTTP\n Transfer-Encoding. <strong>Because the ASP.NET\n Development Server does not support\n this kind of encoding</strong>, you cannot use\n this Web server to host a streaming\n data service that must accept large\n binary streams.</p>\n</blockquote>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
]
| A J2ME client is sending HTTP POST requests with chunked transfer encoding.
When ASP.NET (in both IIS6 and WebDev.exe.server) tries to read the request it sets the Content-Length to 0. I guess this is ok because the Content-length is unknown when the request is loaded.
However, when I read the Request.InputStream to the end, it returns 0.
Here's the code I'm using to read the input stream.
```
using (var reader = new StreamReader(httpRequestBodyStream, BodyTextEncoding)) {
string readString = reader.ReadToEnd();
Console.WriteLine("CharSize:" + readString.Length);
return BodyTextEncoding.GetBytes(readString);
}
```
I can simulate the behaiviour of the client with Fiddler, e.g.
**URL**
<http://localhost:15148/page.aspx>
**Headers:**
User-Agent: Fiddler
Transfer-Encoding: Chunked
Host: somesite.com:15148
**Body**
rabbits rabbits rabbits rabbits. thanks for coming, it's been very useful!
My body reader from above will return a zero length byte array...lame...
Does anyone know how to enable chunked encoding on IIS and ASP.NET Development Server (cassini)?
I found [this script](http://support.microsoft.com/default.aspx?scid=kb;en-us;278998) for IIS but it isn't working. | Seems to be official: [Cassini does not support `Transfer-Encoding: chunked` requests.](http://msdn.microsoft.com/en-us/library/ee960144.aspx)
>
> By default, the client sends large
> binary streams by using a chunked HTTP
> Transfer-Encoding. **Because the ASP.NET
> Development Server does not support
> this kind of encoding**, you cannot use
> this Web server to host a streaming
> data service that must accept large
> binary streams.
>
>
> |
69,107 | <p>What is the best way to refactor the attached code to accommodate multiple email addresses?</p>
<p>The attached HTML/jQuery is complete and works for the first email address. I can setup the other two by copy/pasting and changing the code. But I would like to just refactor the existing code to handle multiple email address fields.</p>
<pre><code><html>
<head>
<script src="includes/jquery/jquery-1.2.6.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
var validateUsername = $('#Email_Address_Status_Icon_1');
$('#Email_Address_1').keyup(function() {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('Validating Email');
this.timer = setTimeout(function() {
if (IsEmail(t.value)) {
validateUsername.html('Valid Email');
} else {
validateUsername.html('Not a valid Email');
};
}, 200);
this.lastValue = this.value;
}
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (regex.test(email)) return true;
else return false;
}
</script>
</head>
<body>
<div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" ID="Email_Address_1">
<span id="Email_Address_Status_Icon_1"></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" id="Email_Address_2">
<span id="Email_Address_Status_Icon_2"></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" id="Email_Address_3">
<span id="Email_Address_Status_Icon_3"></span>
</div>
</form>
</body>
</html>
</code></pre>
| [
{
"answer_id": 69148,
"author": "Pandincus",
"author_id": 2273,
"author_profile": "https://Stackoverflow.com/users/2273",
"pm_score": 3,
"selected": true,
"text": "<p>Instead of using IDs for your email fields, you can give them each a class:</p>\n\n<pre><code><div>\n <label for=\"Email_Address_1\">Friend #1</label></div>\n <input type=\"text\" class=\"email\">\n <span></span>\n</div>\n<div>\n <label for=\"Email_Address_2\">Friend #2</label></div>\n <input type=\"text\" class=\"email\">\n <span></span>\n</div>\n<div>\n <label for=\"Email_Address_3\">Friend #3</label></div>\n <input type=\"text\" class=\"email\">\n <span></span>\n</div>\n</code></pre>\n\n<p>Then, instead of selecting $(\"#Email_Address_Status_Icon_1\"), you can select $(\"input.email\"), which would give you a jQuery wrapped set of all input elements of class email.</p>\n\n<p>Finally, instead of referring to the status icon explicitly with an id, you could simply say:</p>\n\n<pre><code>$(this).next(\"span\").removeClass('error').html('Validating Email');\n</code></pre>\n\n<p>'this' would be the email field, so 'this.next()' would give you its next sibling. We apply the \"span\" selector on top of that just to be sure we're getting what we intend to. $(this).next() would work the same way.</p>\n\n<p>This way, you are referring to the status icon in a relative manner.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 69241,
"author": "Brian Boatright",
"author_id": 3747,
"author_profile": "https://Stackoverflow.com/users/3747",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks! Here is the completed refactor with your suggested changes.</p>\n\n<pre><code><script language=\"javascript\">\n $(document).ready(function() {\n $('#Email_Address_1').keyup(function(){Update_Email_Validate_Status(this)});\n $('#Email_Address_2').keyup(function() { Update_Email_Validate_Status(this)});\n $('#Email_Address_3').keyup(function() { Update_Email_Validate_Status(this)}); \n });\n\n function Update_Email_Validate_Status(field) {\n var t = field;\n if (t.value != t.lastValue) {\n if (t.timer) clearTimeout(t.timer);\n $(t).next(\"span\").removeClass('error').html('Validating Email');\n\n t.timer = setTimeout(function() {\n if (IsEmail(t.value)) {\n $(t).next(\"span\").removeClass('error').html('Valid Email');\n } else {\n $(t).next(\"span\").removeClass('error').html('Not a valid Email');\n };\n }, 200);\n\n t.lastValue = t.value;\n }\n }\n\n function IsEmail(email) {\n var regex = /^([a-zA-Z0-9_\\.\\-\\+])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$/;\n if (regex.test(email)) return true;\n else return false;\n } \n </script>\n</code></pre>\n"
},
{
"answer_id": 69299,
"author": "Geoff",
"author_id": 10427,
"author_profile": "https://Stackoverflow.com/users/10427",
"pm_score": 0,
"selected": false,
"text": "<p>I would do :</p>\n\n<pre><code>$(document).ready(function() {\n $('.validateEmail').keyup(function(){Update_Email_Validate_Status(this)}); \n });\n</code></pre>\n\n<p>Then add class='validateEmail' to all your email inputs.</p>\n\n<p>Alternatively look into <a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-validation/\" rel=\"nofollow noreferrer\">Form Validation Plugin</a> i have used this a lot and it is very flexible and nice to use. Saves you re-inventing...</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3747/"
]
| What is the best way to refactor the attached code to accommodate multiple email addresses?
The attached HTML/jQuery is complete and works for the first email address. I can setup the other two by copy/pasting and changing the code. But I would like to just refactor the existing code to handle multiple email address fields.
```
<html>
<head>
<script src="includes/jquery/jquery-1.2.6.min.js" type="text/javascript"></script>
<script language="javascript">
$(document).ready(function() {
var validateUsername = $('#Email_Address_Status_Icon_1');
$('#Email_Address_1').keyup(function() {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('Validating Email');
this.timer = setTimeout(function() {
if (IsEmail(t.value)) {
validateUsername.html('Valid Email');
} else {
validateUsername.html('Not a valid Email');
};
}, 200);
this.lastValue = this.value;
}
});
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (regex.test(email)) return true;
else return false;
}
</script>
</head>
<body>
<div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" ID="Email_Address_1">
<span id="Email_Address_Status_Icon_1"></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" id="Email_Address_2">
<span id="Email_Address_Status_Icon_2"></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" id="Email_Address_3">
<span id="Email_Address_Status_Icon_3"></span>
</div>
</form>
</body>
</html>
``` | Instead of using IDs for your email fields, you can give them each a class:
```
<div>
<label for="Email_Address_1">Friend #1</label></div>
<input type="text" class="email">
<span></span>
</div>
<div>
<label for="Email_Address_2">Friend #2</label></div>
<input type="text" class="email">
<span></span>
</div>
<div>
<label for="Email_Address_3">Friend #3</label></div>
<input type="text" class="email">
<span></span>
</div>
```
Then, instead of selecting $("#Email\_Address\_Status\_Icon\_1"), you can select $("input.email"), which would give you a jQuery wrapped set of all input elements of class email.
Finally, instead of referring to the status icon explicitly with an id, you could simply say:
```
$(this).next("span").removeClass('error').html('Validating Email');
```
'this' would be the email field, so 'this.next()' would give you its next sibling. We apply the "span" selector on top of that just to be sure we're getting what we intend to. $(this).next() would work the same way.
This way, you are referring to the status icon in a relative manner.
Hope this helps! |
69,115 | <p>Below is my current char* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?</p>
<p>How can I make this faster?</p>
<p>Compiled with -O3 in g++</p>
<pre><code>static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} };
std::string char_to_hex( const unsigned char* _pArray, unsigned int _len )
{
std::string str;
str.resize(_len*2);
char* pszHex = &str[0];
const unsigned char* pEnd = _pArray + _len;
clock_t stick, etick;
stick = clock();
for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {
pszHex[0] = _hex2asciiU_value[*pChar][0];
pszHex[1] = _hex2asciiU_value[*pChar][1];
}
etick = clock();
std::cout << "ticks to hexify " << etick - stick << std::endl;
return str;
}
</code></pre>
<p><strong>Updates</strong></p>
<p>Added timing code</p>
<p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69126">Brian R. Bondy</a>: replace the std::string with a heap alloc'd buffer and change ofs*16 to ofs << 4 - however the heap allocated buffer seems to slow it down? - result ~11ms</p>
<p><a href="https://stackoverflow.com/questions/69115/#69305">Antti Sykäri</a>:replace inner loop with </p>
<pre><code> int upper = *pChar >> 4;
int lower = *pChar & 0x0f;
pszHex[0] = pHex[upper];
pszHex[1] = pHex[lower];
</code></pre>
<p>result ~8ms</p>
<p><a href="https://stackoverflow.com/questions/69115?sort=votes#69218">Robert</a>: replace <code>_hex2asciiU_value</code> with a full 256-entry table, sacrificing memory space but result ~7ms!</p>
<p><a href="https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#70254">HoyHoy</a>: Noted it was producing incorrect results</p>
| [
{
"answer_id": 69126,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 2,
"selected": false,
"text": "<p>For one, instead of multiplying by <code>16</code> do a <code>bitshift << 4</code></p>\n\n<p>Also don't use the <code>std::string</code>, instead just create a buffer on the heap and then <code>delete</code> it. It will be more efficient than the object destruction that is needed from the string.</p>\n"
},
{
"answer_id": 69132,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "<p>Operate on 32 bits at a time (4 chars), then deal with the tail if needed. When I did this exercise with url encoding a full table lookup for each char was slightly faster than logic constructs, so you may want to test this in context as well to take caching issues into account.</p>\n"
},
{
"answer_id": 69139,
"author": "Keith Nicholas",
"author_id": 10431,
"author_profile": "https://Stackoverflow.com/users/10431",
"pm_score": 1,
"selected": false,
"text": "<p>not going to make a lot of difference... *pChar-(ofs*16) can be done with [*pCHar & 0x0F]</p>\n"
},
{
"answer_id": 69197,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 1,
"selected": false,
"text": "<p>This is my version, which, unlike the OP's version, doesn't assume that <code>std::basic_string</code> has its data in contiguous region:</p>\n\n<pre><code>#include <string>\n\nusing std::string;\n\nstatic char const* digits(\"0123456789ABCDEF\");\n\nstring\ntohex(string const& data)\n{\n string result(data.size() * 2, 0);\n string::iterator ptr(result.begin());\n for (string::const_iterator cur(data.begin()), end(data.end()); cur != end; ++cur) {\n unsigned char c(*cur);\n *ptr++ = digits[c >> 4];\n *ptr++ = digits[c & 15];\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 69213,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure your compiler optimization is turned on to the highest working level.</p>\n\n<p>You know, flags like '-O1' to '-03' in gcc.</p>\n"
},
{
"answer_id": 69218,
"author": "Robert Groves",
"author_id": 3534,
"author_profile": "https://Stackoverflow.com/users/3534",
"pm_score": 3,
"selected": true,
"text": "<p>At the cost of more memory you can create a full 256-entry table of the hex codes:</p>\n\n<pre><code>static const char _hex2asciiU_value[256][2] =\n { {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} };\n</code></pre>\n\n<p>Then direct index into the table, no bit fiddling required.</p>\n\n<pre><code>const char *pHexVal = pHex[*pChar];\npszHex[0] = pHexVal[0];\npszHex[1] = pHexVal[1];\n</code></pre>\n"
},
{
"answer_id": 69305,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 1,
"selected": false,
"text": "<p>Changing</p>\n\n<pre><code> ofs = *pChar >> 4;\n pszHex[0] = pHex[ofs];\n pszHex[1] = pHex[*pChar-(ofs*16)];\n</code></pre>\n\n<p>to</p>\n\n<pre><code> int upper = *pChar >> 4;\n int lower = *pChar & 0x0f;\n pszHex[0] = pHex[upper];\n pszHex[1] = pHex[lower];\n</code></pre>\n\n<p>results in roughly 5% speedup.</p>\n\n<p>Writing the result two bytes at time as suggested by <a href=\"https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69218\">Robert</a> results in about 18% speedup. The code changes to:</p>\n\n<pre><code>_result.resize(_len*2);\nshort* pszHex = (short*) &_result[0];\nconst unsigned char* pEnd = _pArray + _len;\n\nconst char* pHex = _hex2asciiU_value;\nfor(const unsigned char* pChar = _pArray;\n pChar != pEnd;\n pChar++, ++pszHex )\n{\n *pszHex = bytes_to_chars[*pChar];\n}\n</code></pre>\n\n<p>Required initialization:</p>\n\n<pre><code>short short_table[256];\n\nfor (int i = 0; i < 256; ++i)\n{\n char* pc = (char*) &short_table[i];\n pc[0] = _hex2asciiU_value[i >> 4];\n pc[1] = _hex2asciiU_value[i & 0x0f];\n}\n</code></pre>\n\n<p>Doing it 2 bytes at a time or 4 bytes at a time will probably result in even greater speedups, as pointed out by <a href=\"https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69132\">Allan Wind</a>, but then it gets trickier when you have to deal with the odd characters.</p>\n\n<p>If you're feeling adventurous, you might try to adapt <a href=\"http://en.wikipedia.org/wiki/Duff's_device\" rel=\"nofollow noreferrer\">Duff's device</a> to do this.</p>\n\n<p>Results are on an Intel Core Duo 2 processor and <code>gcc -O3</code>.</p>\n\n<p><strong>Always measure</strong> that you actually get faster results — a pessimization pretending to be an optimization is less than worthless.</p>\n\n<p><strong>Always test</strong> that you get the correct results — a bug pretending to be an optimization is downright dangerous.</p>\n\n<p>And <strong>always keep in mind</strong> the tradeoff between speed and readability — life is too short for anyone to maintain unreadable code.</p>\n\n<p>(<a href=\"http://c2.com/cgi/wiki?CodeForTheMaintainer\" rel=\"nofollow noreferrer\">Obligatory reference</a> to coding for the <a href=\"https://blog.codinghorror.com/coding-for-violent-psychopaths/\" rel=\"nofollow noreferrer\">violent psychopath who knows where you live</a>.)</p>\n"
},
{
"answer_id": 69499,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 0,
"selected": false,
"text": "<p>I have found that using an index into an array, rather than a pointer, can speed things up a tick. It all depends on how your compiler chooses to optimize. The key is that the processor has instructions to do complex things like [i*2+1] in a single instruction.</p>\n"
},
{
"answer_id": 70254,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 0,
"selected": false,
"text": "<p>The function as it is shown when I'm writing this produces incorrect output even when _hex2asciiU_value is fully specified. The following code works, and on my 2.33GHz Macbook Pro runs in about 1.9 seconds for 200,000,000 million characters. </p>\n\n<pre><code>#include <iostream>\n\nusing namespace std;\n\nstatic const size_t _h2alen = 256;\nstatic char _hex2asciiU_value[_h2alen][3];\n\nstring char_to_hex( const unsigned char* _pArray, unsigned int _len )\n{\n string str;\n str.resize(_len*2);\n char* pszHex = &str[0];\n const unsigned char* pEnd = _pArray + _len;\n const char* pHex = _hex2asciiU_value[0];\n for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {\n pszHex[0] = _hex2asciiU_value[*pChar][0];\n pszHex[1] = _hex2asciiU_value[*pChar][1];\n }\n return str;\n}\n\n\nint main() {\n for(int i=0; i<_h2alen; i++) {\n snprintf(_hex2asciiU_value[i], 3,\"%02X\", i);\n }\n size_t len = 200000000;\n char* a = new char[len];\n string t1;\n string t2;\n clock_t start;\n srand(time(NULL));\n for(int i=0; i<len; i++) a[i] = rand()&0xFF;\n start = clock();\n t1=char_to_hex((const unsigned char*)a, len);\n cout << \"char_to_hex conversion took ---> \" << (clock() - start)/(double)CLOCKS_PER_SEC << \" seconds\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 70275,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 0,
"selected": false,
"text": "<p>If you're rather obsessive about speed here, you can do the following:</p>\n\n<p>Each character is one byte, representing two hex values. Thus, each character is really two four-bit values.</p>\n\n<p>So, you can do the following:</p>\n\n<ol>\n<li>Unpack the four-bit values to 8-bit values using a multiplication or similar instruction.</li>\n<li>Use pshufb, the SSSE3 instruction (Core2-only though). It takes an array of 16 8-bit input values and shuffles them based on the 16 8-bit indices in a second vector. Since you have only 16 possible characters, this fits perfectly; the input array is a vector of 0 through F characters, and the index array is your unpacked array of 4-bit values.</li>\n</ol>\n\n<p>Thus, in a <em>single instruction</em>, you will have performed <strong>16 table lookups</strong> in fewer clocks than it normally takes to do just one (pshufb is 1 clock latency on Penryn).</p>\n\n<p>So, in computational steps:</p>\n\n<ol>\n<li>A B C D E F G H I J K L M N O P (64-bit vector of input values, \"Vector A\") -> 0A 0B 0C 0D 0E 0F 0G 0H 0I 0J 0K 0L 0M 0N 0O 0P (128-bit vector of indices, \"Vector B\"). The easiest way is probably two 64-bit multiplies.</li>\n<li>pshub [0123456789ABCDEF], Vector B</li>\n</ol>\n"
},
{
"answer_id": 70348,
"author": "slicedlime",
"author_id": 11230,
"author_profile": "https://Stackoverflow.com/users/11230",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure doing it more bytes at a time will be better... you'll probably just get tons of cache misses and slow it down significantly.</p>\n\n<p>What you might try is to unroll the loop though, take larger steps and do more characters each time through the loop, to remove some of the loop overhead.</p>\n"
},
{
"answer_id": 72055,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Consistently getting ~4ms on my Athlon 64 4200+ (~7ms with original code)</p>\n\n<pre><code>for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++) {\n const char* pchars = _hex2asciiU_value[*pChar];\n *pszHex++ = *pchars++;\n *pszHex++ = *pchars;\n}\n</code></pre>\n"
},
{
"answer_id": 78611,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Faster C Implmentation</strong></p>\n\n<p>This runs nearly 3x faster than the C++ implementation. Not sure why as it's pretty similar. For the last C++ implementation that I posted it took 6.8 seconds to run through a 200,000,000 character array. The implementation took only 2.2 seconds. </p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n\nchar* char_to_hex(const unsigned char* p_array, \n unsigned int p_array_len,\n char** hex2ascii)\n{\n unsigned char* str = malloc(p_array_len*2+1);\n const unsigned char* p_end = p_array + p_array_len;\n size_t pos=0;\n const unsigned char* p;\n for( p = p_array; p != p_end; p++, pos+=2 ) {\n str[pos] = hex2ascii[*p][0];\n str[pos+1] = hex2ascii[*p][1];\n }\n return (char*)str;\n}\n\nint main()\n{\n size_t hex2ascii_len = 256;\n char** hex2ascii;\n int i;\n hex2ascii = malloc(hex2ascii_len*sizeof(char*));\n for(i=0; i<hex2ascii_len; i++) {\n hex2ascii[i] = malloc(3*sizeof(char)); \n snprintf(hex2ascii[i], 3,\"%02X\", i);\n }\n size_t len = 8;\n const unsigned char a[] = \"DO NOT WANT\";\n printf(\"%s\\n\", char_to_hex((const unsigned char*)a, len, (char**)hex2ascii));\n}\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/3m8Hb.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 78892,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 3,
"selected": false,
"text": "<p>This assembly function (based off my previous post here, but I had to modify the concept a bit to get it to actually work) processes 3.3 billion input characters per second (6.6 billion output characters) on one core of a Core 2 Conroe 3Ghz. Penryn is probably faster.</p>\n\n<pre><code>%include \"x86inc.asm\"\n\nSECTION_RODATA\npb_f0: times 16 db 0xf0\npb_0f: times 16 db 0x0f\npb_hex: db 48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70\n\nSECTION .text\n\n; int convert_string_to_hex( char *input, char *output, int len )\n\ncglobal _convert_string_to_hex,3,3\n movdqa xmm6, [pb_f0 GLOBAL]\n movdqa xmm7, [pb_0f GLOBAL]\n.loop:\n movdqa xmm5, [pb_hex GLOBAL]\n movdqa xmm4, [pb_hex GLOBAL]\n movq xmm0, [r0+r2-8]\n movq xmm2, [r0+r2-16]\n movq xmm1, xmm0\n movq xmm3, xmm2\n pand xmm0, xmm6 ;high bits\n pand xmm2, xmm6\n psrlq xmm0, 4\n psrlq xmm2, 4\n pand xmm1, xmm7 ;low bits\n pand xmm3, xmm7\n punpcklbw xmm0, xmm1\n punpcklbw xmm2, xmm3\n pshufb xmm4, xmm0\n pshufb xmm5, xmm2\n movdqa [r1+r2*2-16], xmm4\n movdqa [r1+r2*2-32], xmm5\n sub r2, 16\n jg .loop\n REP_RET\n</code></pre>\n\n<p>Note it uses x264 assembly syntax, which makes it more portable (to 32-bit vs 64-bit, etc). To convert this into the syntax of your choice is trivial: r0, r1, r2 are the three arguments to the functions in registers. Its a bit like pseudocode. Or you can just get common/x86/x86inc.asm from the x264 tree and include that to run it natively.</p>\n\n<p>P.S. Stack Overflow, am I wrong for wasting time on such a trivial thing? Or is this awesome?</p>\n"
},
{
"answer_id": 4431837,
"author": "Mihai Vrinceanu",
"author_id": 540864,
"author_profile": "https://Stackoverflow.com/users/540864",
"pm_score": 1,
"selected": false,
"text": "<p>I assume this is Windows+IA32.<br>\nTry to use short int instead of the two hexadecimal letters.</p>\n\n<pre><code>short int hex_table[256] = {'0'*256+'0', '1'*256+'0', '2'*256+'0', ..., 'E'*256+'F', 'F'*256+'F'};\nunsigned short int* pszHex = &str[0];\n\nstick = clock();\n\nfor (const unsigned char* pChar = _pArray; pChar != pEnd; pChar++) \n *pszHex++ = hex_table[*pChar];\n\netick = clock();\n</code></pre>\n"
},
{
"answer_id": 8838619,
"author": "Sergey Zhukov",
"author_id": 1145960,
"author_profile": "https://Stackoverflow.com/users/1145960",
"pm_score": 2,
"selected": false,
"text": "<p>It works for me with <code>unsigned char</code>:</p>\n\n<pre><code>unsigned char c1 = byteVal >> 4;\nunsigned char c2 = byteVal & 0x0f;\n\nc1 += c1 <= 9 ? '0' : ('a' - 10);\nc2 += c2 <= 9 ? '0' : ('a' - 10);\n\nstd::string sHex(\" \");\nsHex[0] = c1 ;\nsHex[1] = c2 ;\n\n\n//sHex - contain what we need. For example \"0f\"\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
]
| Below is my current char\* to hex string function. I wrote it as an exercise in bit manipulation. It takes ~7ms on a AMD Athlon MP 2800+ to hexify a 10 million byte array. Is there any trick or other way that I am missing?
How can I make this faster?
Compiled with -O3 in g++
```
static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* snip..., */ {'F','E'},{'F','F'} };
std::string char_to_hex( const unsigned char* _pArray, unsigned int _len )
{
std::string str;
str.resize(_len*2);
char* pszHex = &str[0];
const unsigned char* pEnd = _pArray + _len;
clock_t stick, etick;
stick = clock();
for( const unsigned char* pChar = _pArray; pChar != pEnd; pChar++, pszHex += 2 ) {
pszHex[0] = _hex2asciiU_value[*pChar][0];
pszHex[1] = _hex2asciiU_value[*pChar][1];
}
etick = clock();
std::cout << "ticks to hexify " << etick - stick << std::endl;
return str;
}
```
**Updates**
Added timing code
[Brian R. Bondy](https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#69126): replace the std::string with a heap alloc'd buffer and change ofs\*16 to ofs << 4 - however the heap allocated buffer seems to slow it down? - result ~11ms
[Antti Sykäri](https://stackoverflow.com/questions/69115/#69305):replace inner loop with
```
int upper = *pChar >> 4;
int lower = *pChar & 0x0f;
pszHex[0] = pHex[upper];
pszHex[1] = pHex[lower];
```
result ~8ms
[Robert](https://stackoverflow.com/questions/69115?sort=votes#69218): replace `_hex2asciiU_value` with a full 256-entry table, sacrificing memory space but result ~7ms!
[HoyHoy](https://stackoverflow.com/questions/69115/char-to-hex-string-exercise#70254): Noted it was producing incorrect results | At the cost of more memory you can create a full 256-entry table of the hex codes:
```
static const char _hex2asciiU_value[256][2] =
{ {'0','0'}, {'0','1'}, /* ..., */ {'F','E'},{'F','F'} };
```
Then direct index into the table, no bit fiddling required.
```
const char *pHexVal = pHex[*pChar];
pszHex[0] = pHexVal[0];
pszHex[1] = pHexVal[1];
``` |
69,159 | <p>I'm using MediaTemple's Grid Server (shared/grid hosting) to run some MySQL/PHP sites I'm writing and noticed that I wasn't closing one of my MySQL connections, which caused my site to error out: </p>
<pre><code>"Too Many Connections"
</code></pre>
<p>I can't log in anywhere to close the connections manually. </p>
<p><strong>Is that any way to close open connections using a script or other type of command?.</strong> </p>
<p>Should I just wait?</p>
| [
{
"answer_id": 69171,
"author": "owenmarshall",
"author_id": 9806,
"author_profile": "https://Stackoverflow.com/users/9806",
"pm_score": 1,
"selected": false,
"text": "<p>If you can't log into MySQL at all, you will probably have to contact your hosting provider to kill the connections.</p>\n\n<p>If you can use the MySQL shell, you can use the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/show-processlist.html\" rel=\"nofollow noreferrer\">show processlist</a> command to view connections, then use the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/kill.html\" rel=\"nofollow noreferrer\">kill</a> command to remove the connections.</p>\n\n<p>It's been my experience that hung SQL connections tend to stay that way, unfortunately.</p>\n"
},
{
"answer_id": 69179,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure that you're closing the connections with your PHP code. Also, you could increase the maximum connections allowed in /etc/my.cnf.</p>\n\n<pre><code>max_connections=500\n</code></pre>\n\n<p>Finally, you can login to a mysql prompt and type <code>show status</code> or <code>show processlist</code> to view various statistics with your server.</p>\n\n<p>If all else fails, restarting the server daemon should clear the persistent connections.</p>\n"
},
{
"answer_id": 69244,
"author": "Larry OBrien",
"author_id": 10116,
"author_profile": "https://Stackoverflow.com/users/10116",
"pm_score": 0,
"selected": false,
"text": "<p>Well, if you cannot ever sneak in with a connection, I dunno', but if you can occasionally sneak in, in Ruby it would be close to:</p>\n\n<pre><code>require 'mysql'\n\nmysql = Mysql.new(ip, user, pass)\nprocesslist = mysql.query(\"show full processlist\")\nkilled = 0\nprocesslist.each { | process |\n mysql.query(\"KILL #{process[0].to_i}\")\n} \nputs \"#{Time.new} -- killed: #{killed} connections\"\n</code></pre>\n"
},
{
"answer_id": 69376,
"author": "Grey Panther",
"author_id": 1265,
"author_profile": "https://Stackoverflow.com/users/1265",
"pm_score": 0,
"selected": false,
"text": "<p>If you can access the command line with enough privileges, restart the MySQL server or the Apache (assuming that you use Apache) server - because probably it is keeping the connections open. After you successfully closed the connections, make sure that you are not using persistent connections from PHP (the general opinion seems to be that it doesn't create any significant performance gain, but it has all kinds of problems - like you've experienced - and in some cases - like using it PostgreSQL - it can even significantly slow down your site!).</p>\n"
},
{
"answer_id": 72386,
"author": "longneck",
"author_id": 8250,
"author_profile": "https://Stackoverflow.com/users/8250",
"pm_score": 1,
"selected": false,
"text": "<p>blindly going in an terminating connections is not the way to solve this problem. first you need to understand why you are running out of connections. is your max_connections setting selected to correctly match the number of max/anticipated users? are you using persistent connections when you really don't need them? etc.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9803/"
]
| I'm using MediaTemple's Grid Server (shared/grid hosting) to run some MySQL/PHP sites I'm writing and noticed that I wasn't closing one of my MySQL connections, which caused my site to error out:
```
"Too Many Connections"
```
I can't log in anywhere to close the connections manually.
**Is that any way to close open connections using a script or other type of command?.**
Should I just wait? | If you can't log into MySQL at all, you will probably have to contact your hosting provider to kill the connections.
If you can use the MySQL shell, you can use the [show processlist](http://dev.mysql.com/doc/refman/5.0/en/show-processlist.html) command to view connections, then use the [kill](http://dev.mysql.com/doc/refman/5.0/en/kill.html) command to remove the connections.
It's been my experience that hung SQL connections tend to stay that way, unfortunately. |
69,188 | <p><a href="http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx" rel="nofollow noreferrer">http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx</a></p>
<p>This post shows how to test setting a cookie and then seeing it in ViewData. What I what to do is see if the correct cookies were written (values and name). Any reply, blog post or article will be greatly appreciated.</p>
| [
{
"answer_id": 69535,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": -1,
"selected": false,
"text": "<pre><code>function ReadCookie(cookieName) {\n var theCookie=\"\"+document.cookie;\n var ind=theCookie.indexOf(cookieName);\n if (ind==-1 || cookieName==\"\") return \"\"; \n var ind1=theCookie.indexOf(';',ind);\n if (ind1==-1) ind1=theCookie.length; \n return unescape(theCookie.substring(ind+cookieName.length+1,ind1));\n}\n</code></pre>\n"
},
{
"answer_id": 69563,
"author": "White Dragon",
"author_id": 11049,
"author_profile": "https://Stackoverflow.com/users/11049",
"pm_score": 3,
"selected": false,
"text": "<p>Are you looking for something more like this? (untested, just typed it up in the reply box)</p>\n\n<pre><code>var cookies = new HttpCookieCollection();\ncontroller.ControllerContext = new FakeControllerContext(controller, cookies);\nvar result = controller.TestCookie() as ViewResult;\nAssert.AreEqual(\"somevaluethatshouldbethere\", cookies[\"somecookieitem\"].Value);\n</code></pre>\n\n<p>As in, did you mean you want to test the writing of a cookie instead of reading one?\nPlease make your request clearer if possible :)</p>\n"
},
{
"answer_id": 69582,
"author": "peterorum",
"author_id": 4449,
"author_profile": "https://Stackoverflow.com/users/4449",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps you need to pass in a Fake Response object that the cookies are written to, and you test what is returned in that from the Controller.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
]
| <http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx>
This post shows how to test setting a cookie and then seeing it in ViewData. What I what to do is see if the correct cookies were written (values and name). Any reply, blog post or article will be greatly appreciated. | Are you looking for something more like this? (untested, just typed it up in the reply box)
```
var cookies = new HttpCookieCollection();
controller.ControllerContext = new FakeControllerContext(controller, cookies);
var result = controller.TestCookie() as ViewResult;
Assert.AreEqual("somevaluethatshouldbethere", cookies["somecookieitem"].Value);
```
As in, did you mean you want to test the writing of a cookie instead of reading one?
Please make your request clearer if possible :) |
69,192 | <p>Suppose we have two stacks and no other temporary variable.</p>
<p>Is to possible to "construct" a queue data structure using only the two stacks?</p>
| [
{
"answer_id": 69206,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 4,
"selected": false,
"text": "<p>The time complexities would be worse, though. A good queue implementation does everything in constant time.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>Not sure why my answer has been downvoted here. If we program, we care about time complexity, and using two standard stacks to make a queue is inefficient. It's a very valid and relevant point. If someone else feels the need to downvote this more, I would be interested to know why.</p>\n\n<p><em>A little more detail</em>: on why using two stacks is worse than just a queue: if you use two stacks, and someone calls dequeue while the outbox is empty, you need linear time to get to the bottom of the inbox (as you can see in Dave's code).</p>\n\n<p>You can implement a queue as a singly-linked list (each element points to the next-inserted element), keeping an extra pointer to the last-inserted element for pushes (or making it a cyclic list). Implementing queue and dequeue on this data structure is very easy to do in constant time. That's worst-case constant time, not amortized. And, as the comments seem to ask for this clarification, worst-case constant time is strictly better than amortized constant time.</p>\n"
},
{
"answer_id": 69377,
"author": "user11055",
"author_id": 11055,
"author_profile": "https://Stackoverflow.com/users/11055",
"pm_score": 2,
"selected": false,
"text": "<p>You'll have to pop everything off the first stack to get the bottom element. Then put them all back onto the second stack for every \"dequeue\" operation.</p>\n"
},
{
"answer_id": 69436,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 10,
"selected": false,
"text": "<p>Keep 2 stacks, let's call them <code>inbox</code> and <code>outbox</code>.</p>\n\n<p><strong>Enqueue</strong>:</p>\n\n<ul>\n<li>Push the new element onto <code>inbox</code></li>\n</ul>\n\n<p><strong>Dequeue</strong>:</p>\n\n<ul>\n<li><p>If <code>outbox</code> is empty, refill it by popping each element from <code>inbox</code> and pushing it onto <code>outbox</code></p></li>\n<li><p>Pop and return the top element from <code>outbox</code></p></li>\n</ul>\n\n<p>Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.</p>\n\n<p>Here's an implementation in Java:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Queue<E>\n{\n\n private Stack<E> inbox = new Stack<E>();\n private Stack<E> outbox = new Stack<E>();\n\n public void queue(E item) {\n inbox.push(item);\n }\n\n public E dequeue() {\n if (outbox.isEmpty()) {\n while (!inbox.isEmpty()) {\n outbox.push(inbox.pop());\n }\n }\n return outbox.pop();\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 77010,
"author": "pythonquick",
"author_id": 6225,
"author_profile": "https://Stackoverflow.com/users/6225",
"pm_score": 6,
"selected": false,
"text": "<p>You can even simulate a queue using only one stack. The second (temporary) stack can be simulated by the call stack of recursive calls to the insert method. </p>\n\n<p>The principle stays the same when inserting a new element into the queue: </p>\n\n<ul>\n<li>You need to transfer elements from one stack to another temporary stack, to reverse their order. </li>\n<li>Then push the new element to be inserted, onto the temporary stack</li>\n<li>Then transfer the elements back to the original stack</li>\n<li>The new element will be on the bottom of the stack, and the oldest element is on top (first to be popped)</li>\n</ul>\n\n<p>A Queue class using only one Stack, would be as follows:</p>\n\n<pre><code>public class SimulatedQueue<E> {\n private java.util.Stack<E> stack = new java.util.Stack<E>();\n\n public void insert(E elem) {\n if (!stack.empty()) {\n E topElem = stack.pop();\n insert(elem);\n stack.push(topElem);\n }\n else\n stack.push(elem);\n }\n\n public E remove() {\n return stack.pop();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 10111315,
"author": "PradGar",
"author_id": 1028292,
"author_profile": "https://Stackoverflow.com/users/1028292",
"pm_score": -1,
"selected": false,
"text": "<pre class=\"lang-java prettyprint-override\"><code>public class QueueUsingStacks<T>\n{\n private LinkedListStack<T> stack1;\n private LinkedListStack<T> stack2;\n\n public QueueUsingStacks()\n {\n stack1=new LinkedListStack<T>();\n stack2 = new LinkedListStack<T>();\n\n }\n public void Copy(LinkedListStack<T> source,LinkedListStack<T> dest )\n {\n while(source.Head!=null)\n {\n dest.Push(source.Head.Data);\n source.Head = source.Head.Next;\n }\n }\n public void Enqueue(T entry)\n {\n\n stack1.Push(entry);\n }\n public T Dequeue()\n {\n T obj;\n if (stack2 != null)\n {\n Copy(stack1, stack2);\n obj = stack2.Pop();\n Copy(stack2, stack1);\n }\n else\n {\n throw new Exception(\"Stack is empty\");\n }\n return obj;\n }\n\n public void Display()\n {\n stack1.Display();\n }\n\n\n}\n</code></pre>\n\n<p>For every enqueue operation, we add to the top of the stack1. For every dequeue, we empty the content's of stack1 into stack2, and remove the element at top of the stack.Time complexity is O(n) for dequeue, as we have to copy the stack1 to stack2. time complexity of enqueue is the same as a regular stack</p>\n"
},
{
"answer_id": 14078077,
"author": "Harry He",
"author_id": 1092195,
"author_profile": "https://Stackoverflow.com/users/1092195",
"pm_score": 2,
"selected": false,
"text": "<p>Two stacks in the queue are defined as <i>stack1</i> and <i>stack2</i>.</p>\n\n<p><strong>Enqueue:</strong>\nThe euqueued elements are always pushed into <i>stack1</i></p>\n\n<p><strong>Dequeue:</strong>\nThe top of <i>stack2</i> can be popped out since it is the first element inserted into queue when <i>stack2</i> is not empty. When <i>stack2</i> is empty, we pop all elements from <i>stack1</i> and push them into <i>stack2</i> one by one. The first element in a queue is pushed into the bottom of <i>stack1</i>. It can be popped out directly after popping and pushing operations since it is on the top of <i>stack2</i>.</p>\n\n<p>The following is same C++ sample code:</p>\n\n<pre><code>template <typename T> class CQueue\n{\npublic:\n CQueue(void);\n ~CQueue(void);\n\n void appendTail(const T& node); \n T deleteHead(); \n\nprivate:\n stack<T> stack1;\n stack<T> stack2;\n};\n\ntemplate<typename T> void CQueue<T>::appendTail(const T& element) {\n stack1.push(element);\n} \n\ntemplate<typename T> T CQueue<T>::deleteHead() {\n if(stack2.size()<= 0) {\n while(stack1.size()>0) {\n T& data = stack1.top();\n stack1.pop();\n stack2.push(data);\n }\n }\n\n\n if(stack2.size() == 0)\n throw new exception(\"queue is empty\");\n\n\n T head = stack2.top();\n stack2.pop();\n\n\n return head;\n}\n</code></pre>\n\n<p>This solution is borrowed from <a href=\"http://codercareer.blogspot.com/2011/10/no-17-queue-implemented-with-two-stacks.html\" rel=\"nofollow\">my blog</a>. More detailed analysis with step-by-step operation simulations is available in my blog webpage.</p>\n"
},
{
"answer_id": 22750794,
"author": "Rahul Gandhi",
"author_id": 2860486,
"author_profile": "https://Stackoverflow.com/users/2860486",
"pm_score": 3,
"selected": false,
"text": "<p>Let queue to be implemented be q and stacks used to implement q be stack1 and stack2. </p>\n\n<p>q can be implemented in <strong>two</strong> ways:</p>\n\n<p><strong>Method 1 (By making enQueue operation costly)</strong></p>\n\n<p>This method makes sure that newly entered element is always at the top of stack 1, so that deQueue operation just pops from stack1. To put the element at top of stack1, stack2 is used.</p>\n\n<pre><code>enQueue(q, x)\n1) While stack1 is not empty, push everything from stack1 to stack2.\n2) Push x to stack1 (assuming size of stacks is unlimited).\n3) Push everything back to stack1.\ndeQueue(q)\n1) If stack1 is empty then error\n2) Pop an item from stack1 and return it.\n</code></pre>\n\n<p><strong>Method 2 (By making deQueue operation costly)</strong></p>\n\n<p>In this method, in en-queue operation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is empty then all the elements are moved to stack2 and finally top of stack2 is returned.</p>\n\n<pre><code>enQueue(q, x)\n 1) Push x to stack1 (assuming size of stacks is unlimited).\n\ndeQueue(q)\n 1) If both stacks are empty then error.\n 2) If stack2 is empty\n While stack1 is not empty, push everything from stack1 to stack2.\n 3) Pop the element from stack2 and return it.\n</code></pre>\n\n<p>Method 2 is definitely better than method 1. Method 1 moves all the elements twice in enQueue operation, while method 2 (in deQueue operation) moves the elements once and moves elements only if stack2 empty.</p>\n"
},
{
"answer_id": 33095936,
"author": "imvp",
"author_id": 4092635,
"author_profile": "https://Stackoverflow.com/users/4092635",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// Two stacks s1 Original and s2 as Temp one\n private Stack<Integer> s1 = new Stack<Integer>();\n private Stack<Integer> s2 = new Stack<Integer>();\n\n /*\n * Here we insert the data into the stack and if data all ready exist on\n * stack than we copy the entire stack s1 to s2 recursively and push the new\n * element data onto s1 and than again recursively call the s2 to pop on s1.\n * \n * Note here we can use either way ie We can keep pushing on s1 and than\n * while popping we can remove the first element from s2 by copying\n * recursively the data and removing the first index element.\n */\n public void insert( int data )\n {\n if( s1.size() == 0 )\n {\n s1.push( data );\n }\n else\n {\n while( !s1.isEmpty() )\n {\n s2.push( s1.pop() );\n }\n s1.push( data );\n while( !s2.isEmpty() )\n {\n s1.push( s2.pop() );\n }\n }\n }\n\n public void remove()\n {\n if( s1.isEmpty() )\n {\n System.out.println( \"Empty\" );\n }\n else\n {\n s1.pop();\n\n }\n }\n</code></pre>\n"
},
{
"answer_id": 37376579,
"author": "John Leidegren",
"author_id": 58961,
"author_profile": "https://Stackoverflow.com/users/58961",
"pm_score": 0,
"selected": false,
"text": "<p>I'll answer this question in Go because Go does not have a rich a lot of collections in its standard library.</p>\n\n<p>Since a stack is really easy to implement I thought I'd try and use two stacks to accomplish a double ended queue. To better understand how I arrived at my answer I've split the implementation in two parts, the first part is hopefully easier to understand but it's incomplete.</p>\n\n<pre><code>type IntQueue struct {\n front []int\n back []int\n}\n\nfunc (q *IntQueue) PushFront(v int) {\n q.front = append(q.front, v)\n}\n\nfunc (q *IntQueue) Front() int {\n if len(q.front) > 0 {\n return q.front[len(q.front)-1]\n } else {\n return q.back[0]\n }\n}\n\nfunc (q *IntQueue) PopFront() {\n if len(q.front) > 0 {\n q.front = q.front[:len(q.front)-1]\n } else {\n q.back = q.back[1:]\n }\n}\n\nfunc (q *IntQueue) PushBack(v int) {\n q.back = append(q.back, v)\n}\n\nfunc (q *IntQueue) Back() int {\n if len(q.back) > 0 {\n return q.back[len(q.back)-1]\n } else {\n return q.front[0]\n }\n}\n\nfunc (q *IntQueue) PopBack() {\n if len(q.back) > 0 {\n q.back = q.back[:len(q.back)-1]\n } else {\n q.front = q.front[1:]\n }\n}\n</code></pre>\n\n<p>It's basically two stacks where we allow the bottom of the stacks to be manipulated by each other. I've also used the STL naming conventions, where the traditional push, pop, peek operations of a stack have a front/back prefix whether they refer to the front or back of the queue.</p>\n\n<p>The issue with the above code is that it doesn't use memory very efficiently. Actually, it grows endlessly until you run out of space. That's really bad. The fix for this is to simply reuse the bottom of the stack space whenever possible. We have to introduce an offset to track this since a slice in Go cannot grow in the front once shrunk.</p>\n\n<pre><code>type IntQueue struct {\n front []int\n frontOffset int\n back []int\n backOffset int\n}\n\nfunc (q *IntQueue) PushFront(v int) {\n if q.backOffset > 0 {\n i := q.backOffset - 1\n q.back[i] = v\n q.backOffset = i\n } else {\n q.front = append(q.front, v)\n }\n}\n\nfunc (q *IntQueue) Front() int {\n if len(q.front) > 0 {\n return q.front[len(q.front)-1]\n } else {\n return q.back[q.backOffset]\n }\n}\n\nfunc (q *IntQueue) PopFront() {\n if len(q.front) > 0 {\n q.front = q.front[:len(q.front)-1]\n } else {\n if len(q.back) > 0 {\n q.backOffset++\n } else {\n panic(\"Cannot pop front of empty queue.\")\n }\n }\n}\n\nfunc (q *IntQueue) PushBack(v int) {\n if q.frontOffset > 0 {\n i := q.frontOffset - 1\n q.front[i] = v\n q.frontOffset = i\n } else {\n q.back = append(q.back, v)\n }\n}\n\nfunc (q *IntQueue) Back() int {\n if len(q.back) > 0 {\n return q.back[len(q.back)-1]\n } else {\n return q.front[q.frontOffset]\n }\n}\n\nfunc (q *IntQueue) PopBack() {\n if len(q.back) > 0 {\n q.back = q.back[:len(q.back)-1]\n } else {\n if len(q.front) > 0 {\n q.frontOffset++\n } else {\n panic(\"Cannot pop back of empty queue.\")\n }\n }\n}\n</code></pre>\n\n<p>It's a lot of small functions but of the 6 functions 3 of them are just mirrors of the other.</p>\n"
},
{
"answer_id": 38801986,
"author": "realPK",
"author_id": 853001,
"author_profile": "https://Stackoverflow.com/users/853001",
"pm_score": -1,
"selected": false,
"text": "<p>Queue implementation using two java.util.Stack objects:</p>\n\n<pre><code>public final class QueueUsingStacks<E> {\n\n private final Stack<E> iStack = new Stack<>();\n private final Stack<E> oStack = new Stack<>();\n\n public void enqueue(E e) {\n iStack.push(e);\n }\n\n public E dequeue() {\n if (oStack.isEmpty()) {\n if (iStack.isEmpty()) {\n throw new NoSuchElementException(\"No elements present in Queue\");\n }\n while (!iStack.isEmpty()) {\n oStack.push(iStack.pop());\n }\n }\n return oStack.pop();\n }\n\n public boolean isEmpty() {\n if (oStack.isEmpty() && iStack.isEmpty()) {\n return true;\n }\n return false;\n }\n\n public int size() {\n return iStack.size() + oStack.size();\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 39089983,
"author": "Levent Divilioglu",
"author_id": 3128926,
"author_profile": "https://Stackoverflow.com/users/3128926",
"pm_score": 8,
"selected": false,
"text": "<h1>A - How To Reverse A Stack</h1>\n\n<p>To understand how to construct a queue using two stacks, you should understand how to reverse a stack crystal clear. Remember how stack works, it is very similar to the dish stack on your kitchen. The last washed dish will be on the top of the clean stack, which is called as <strong>L</strong>ast <strong>I</strong>n <strong>F</strong>irst <strong>O</strong>ut (LIFO) in computer science.</p>\n\n<p>Lets imagine our stack like a bottle as below;</p>\n\n<p><a href=\"https://i.stack.imgur.com/MwjaI.png\"><img src=\"https://i.stack.imgur.com/MwjaI.png\" alt=\"enter image description here\"></a></p>\n\n<p>If we push integers 1,2,3 respectively, then 3 will be on the top of the stack. Because 1 will be pushed first, then 2 will be put on the top of 1. Lastly, 3 will be put on the top of the stack and latest state of our stack represented as a bottle will be as below;</p>\n\n<p><a href=\"https://i.stack.imgur.com/J7ec0.png\"><img src=\"https://i.stack.imgur.com/J7ec0.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now we have our stack represented as a bottle is populated with values 3,2,1. And we want to reverse the stack so that the top element of the stack will be 1 and bottom element of the stack will be 3. What we can do ? We can take the bottle and hold it upside down so that all the values should reverse in order ?</p>\n\n<p><a href=\"https://i.stack.imgur.com/WZNxS.png\"><img src=\"https://i.stack.imgur.com/WZNxS.png\" alt=\"enter image description here\"></a></p>\n\n<p>Yes we can do that, but that's a bottle. To do the same process, we need to have a second stack that which is going to store the first stack elements in reverse order. Let's put our populated stack to the left and our new empty stack to the right. To reverse the order of the elements, we are going to pop each element from left stack, and push them to the right stack. You can see what happens as we do so on the image below;</p>\n\n<p><a href=\"https://i.stack.imgur.com/1YfMo.png\"><img src=\"https://i.stack.imgur.com/1YfMo.png\" alt=\"enter image description here\"></a></p>\n\n<p>So we know how to reverse a stack.</p>\n\n<h1>B - Using Two Stacks As A Queue</h1>\n\n<p>On previous part, I've explained how can we reverse the order of stack elements. This was important, because if we push and pop elements to the stack, the output will be exactly in reverse order of a queue. Thinking on an example, let's push the array of integers <code>{1, 2, 3, 4, 5}</code> to a stack. If we pop the elements and print them until the stack is empty, we will get the array in the reverse order of pushing order, which will be <code>{5, 4, 3, 2, 1}</code> Remember that for the same input, if we dequeue the queue until the queue is empty, the output will be <code>{1, 2, 3, 4, 5}</code>. So it is obvious that for the same input order of elements, output of the queue is exactly reverse of the output of a stack. As we know how to reverse a stack using an extra stack, we can construct a queue using two stacks.</p>\n\n<p>Our queue model will consist of two stacks. One stack will be used for <code>enqueue</code> operation (stack #1 on the left, will be called as Input Stack), another stack will be used for the <code>dequeue</code> operation (stack #2 on the right, will be called as Output Stack). Check out the image below;</p>\n\n<p><a href=\"https://i.stack.imgur.com/xyWPR.png\"><img src=\"https://i.stack.imgur.com/xyWPR.png\" alt=\"enter image description here\"></a></p>\n\n<p>Our pseudo-code is as below;</p>\n\n<hr>\n\n<h3>Enqueue Operation</h3>\n\n<pre><code>Push every input element to the Input Stack\n</code></pre>\n\n<h3>Dequeue Operation</h3>\n\n<pre><code>If ( Output Stack is Empty)\n pop every element in the Input Stack\n and push them to the Output Stack until Input Stack is Empty\n\npop from Output Stack\n</code></pre>\n\n<hr>\n\n<p>Let's enqueue the integers <code>{1, 2, 3}</code> respectively. Integers will be pushed on the <strong>Input Stack</strong> (<strong>Stack #1</strong>) which is located on the left;</p>\n\n<p><a href=\"https://i.stack.imgur.com/lX1EP.png\"><img src=\"https://i.stack.imgur.com/lX1EP.png\" alt=\"enter image description here\"></a></p>\n\n<p>Then what will happen if we execute a dequeue operation? Whenever a dequeue operation is executed, queue is going to check if the Output Stack is empty or not(see the pseudo-code above) If the Output Stack is empty, then the Input Stack is going to be extracted on the output so the elements of Input Stack will be reversed. Before returning a value, the state of the queue will be as below;</p>\n\n<p><a href=\"https://i.stack.imgur.com/9f03R.png\"><img src=\"https://i.stack.imgur.com/9f03R.png\" alt=\"enter image description here\"></a></p>\n\n<p>Check out the order of elements in the Output Stack (Stack #2). It's obvious that we can pop the elements from the Output Stack so that the output will be same as if we dequeued from a queue. Thus, if we execute two dequeue operations, first we will get <code>{1, 2}</code> respectively. Then element 3 will be the only element of the Output Stack, and the Input Stack will be empty. If we enqueue the elements 4 and 5, then the state of the queue will be as follows;</p>\n\n<p><a href=\"https://i.stack.imgur.com/CXQZB.png\"><img src=\"https://i.stack.imgur.com/CXQZB.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now the Output Stack is not empty, and if we execute a dequeue operation, only 3 will be popped out from the Output Stack. Then the state will be seen as below;</p>\n\n<p><a href=\"https://i.stack.imgur.com/hOPu3.png\"><img src=\"https://i.stack.imgur.com/hOPu3.png\" alt=\"enter image description here\"></a></p>\n\n<p>Again, if we execute two more dequeue operations, on the first dequeue operation, queue will check if the Output Stack is empty, which is true. Then pop out the elements of the Input Stack and push them to the Output Stack unti the Input Stack is empty, then the state of the Queue will be as below;</p>\n\n<p><a href=\"https://i.stack.imgur.com/vuLsw.png\"><img src=\"https://i.stack.imgur.com/vuLsw.png\" alt=\"enter image description here\"></a></p>\n\n<p>Easy to see, the output of the two dequeue operations will be <code>{4, 5}</code></p>\n\n<h1>C - Implementation Of Queue Constructed with Two Stacks</h1>\n\n<p>Here is an implementation in Java. I'm not going to use the existing implementation of Stack so the example here is going to reinvent the wheel;</p>\n\n<h1>C - 1) MyStack class : A Simple Stack Implementation</h1>\n\n<pre><code>public class MyStack<T> {\n\n // inner generic Node class\n private class Node<T> {\n T data;\n Node<T> next;\n\n public Node(T data) {\n this.data = data;\n }\n }\n\n private Node<T> head;\n private int size;\n\n public void push(T e) {\n Node<T> newElem = new Node(e);\n\n if(head == null) {\n head = newElem;\n } else {\n newElem.next = head;\n head = newElem; // new elem on the top of the stack\n }\n\n size++;\n }\n\n public T pop() {\n if(head == null)\n return null;\n\n T elem = head.data;\n head = head.next; // top of the stack is head.next\n\n size--;\n\n return elem;\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public void printStack() {\n System.out.print(\"Stack: \");\n\n if(size == 0)\n System.out.print(\"Empty !\");\n else\n for(Node<T> temp = head; temp != null; temp = temp.next)\n System.out.printf(\"%s \", temp.data);\n\n System.out.printf(\"\\n\");\n }\n}\n</code></pre>\n\n<h1>C - 2) MyQueue class : Queue Implementation Using Two Stacks</h1>\n\n<pre><code>public class MyQueue<T> {\n\n private MyStack<T> inputStack; // for enqueue\n private MyStack<T> outputStack; // for dequeue\n private int size;\n\n public MyQueue() {\n inputStack = new MyStack<>();\n outputStack = new MyStack<>();\n }\n\n public void enqueue(T e) {\n inputStack.push(e);\n size++;\n }\n\n public T dequeue() {\n // fill out all the Input if output stack is empty\n if(outputStack.isEmpty())\n while(!inputStack.isEmpty())\n outputStack.push(inputStack.pop());\n\n T temp = null;\n if(!outputStack.isEmpty()) {\n temp = outputStack.pop();\n size--;\n }\n\n return temp;\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n}\n</code></pre>\n\n<h1>C - 3) Demo Code</h1>\n\n<pre><code>public class TestMyQueue {\n\n public static void main(String[] args) {\n MyQueue<Integer> queue = new MyQueue<>();\n\n // enqueue integers 1..3\n for(int i = 1; i <= 3; i++)\n queue.enqueue(i);\n\n // execute 2 dequeue operations \n for(int i = 0; i < 2; i++)\n System.out.println(\"Dequeued: \" + queue.dequeue());\n\n // enqueue integers 4..5\n for(int i = 4; i <= 5; i++)\n queue.enqueue(i);\n\n // dequeue the rest\n while(!queue.isEmpty())\n System.out.println(\"Dequeued: \" + queue.dequeue());\n }\n\n}\n</code></pre>\n\n<h1>C - 4) Sample Output</h1>\n\n<pre><code>Dequeued: 1\nDequeued: 2\nDequeued: 3\nDequeued: 4\nDequeued: 5\n</code></pre>\n"
},
{
"answer_id": 40602980,
"author": "Jaydeep Shil",
"author_id": 3428626,
"author_profile": "https://Stackoverflow.com/users/3428626",
"pm_score": 2,
"selected": false,
"text": "<p><strong>for c# developer here is the complete program :</strong></p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace QueueImplimentationUsingStack\n{\n class Program\n {\n public class Stack<T>\n {\n public int size;\n public Node<T> head;\n public void Push(T data)\n {\n Node<T> node = new Node<T>();\n node.data = data;\n if (head == null)\n head = node;\n else\n {\n node.link = head;\n head = node;\n }\n size++;\n Display();\n }\n public Node<T> Pop()\n {\n if (head == null)\n return null;\n else\n {\n Node<T> temp = head;\n //temp.link = null;\n head = head.link;\n size--;\n Display();\n return temp;\n }\n }\n public void Display()\n {\n if (size == 0)\n Console.WriteLine(\"Empty\");\n else\n {\n Console.Clear();\n Node<T> temp = head;\n while (temp!= null)\n {\n Console.WriteLine(temp.data);\n temp = temp.link;\n }\n }\n }\n }\n\n public class Queue<T>\n {\n public int size;\n public Stack<T> inbox;\n public Stack<T> outbox;\n public Queue()\n {\n inbox = new Stack<T>();\n outbox = new Stack<T>();\n }\n public void EnQueue(T data)\n {\n inbox.Push(data);\n size++;\n }\n public Node<T> DeQueue()\n {\n if (outbox.size == 0)\n {\n while (inbox.size != 0)\n {\n outbox.Push(inbox.Pop().data);\n }\n }\n Node<T> temp = new Node<T>();\n if (outbox.size != 0)\n {\n temp = outbox.Pop();\n size--;\n }\n return temp;\n }\n\n }\n public class Node<T>\n {\n public T data;\n public Node<T> link;\n }\n\n static void Main(string[] args)\n {\n Queue<int> q = new Queue<int>();\n for (int i = 1; i <= 3; i++)\n q.EnQueue(i);\n // q.Display();\n for (int i = 1; i < 3; i++)\n q.DeQueue();\n //q.Display();\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 44273758,
"author": "Santhosh",
"author_id": 6851131,
"author_profile": "https://Stackoverflow.com/users/6851131",
"pm_score": 2,
"selected": false,
"text": "<p>A solution in c#</p>\n\n<pre><code>public class Queue<T> where T : class\n{\n private Stack<T> input = new Stack<T>();\n private Stack<T> output = new Stack<T>();\n public void Enqueue(T t)\n {\n input.Push(t);\n }\n\n public T Dequeue()\n {\n if (output.Count == 0)\n {\n while (input.Count != 0)\n {\n output.Push(input.Pop());\n }\n }\n\n return output.Pop();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46390588,
"author": "Irshad ck",
"author_id": 8276943,
"author_profile": "https://Stackoverflow.com/users/8276943",
"pm_score": -1,
"selected": false,
"text": "<p>here is my solution in Java using linkedlist.</p>\n<pre class=\"lang-java prettyprint-override\"><code>class queue<T>{\n static class Node<T>{\n private T data;\n private Node<T> next;\n Node(T data){\n this.data = data;\n next = null;\n }\n }\n Node firstTop;\n Node secondTop;\n \n void push(T data){\n Node temp = new Node(data);\n temp.next = firstTop;\n firstTop = temp;\n }\n \n void pop(){\n if(firstTop == null){\n return;\n }\n Node temp = firstTop;\n while(temp != null){\n Node temp1 = new Node(temp.data);\n temp1.next = secondTop;\n secondTop = temp1;\n temp = temp.next;\n }\n secondTop = secondTop.next;\n firstTop = null;\n while(secondTop != null){\n Node temp3 = new Node(secondTop.data);\n temp3.next = firstTop;\n firstTop = temp3;\n secondTop = secondTop.next;\n }\n }\n \n}\n</code></pre>\n<p><strong>Note:</strong> In this case, pop operation is very time consuming. So I won't suggest to create a queue using two stacks.</p>\n"
},
{
"answer_id": 46724770,
"author": "hIpPy",
"author_id": 58678,
"author_profile": "https://Stackoverflow.com/users/58678",
"pm_score": 0,
"selected": false,
"text": "<p>With <code>O(1)</code> <code>dequeue()</code>, which is same as pythonquick's <a href=\"https://stackoverflow.com/a/77010/58678\">answer</a>:</p>\n\n<pre><code>// time: O(n), space: O(n)\nenqueue(x):\n if stack.isEmpty():\n stack.push(x)\n return\n temp = stack.pop()\n enqueue(x)\n stack.push(temp)\n\n// time: O(1)\nx dequeue():\n return stack.pop()\n</code></pre>\n\n<p>With <code>O(1)</code> <code>enqueue()</code> (this is not mentioned in this post so this answer), which also uses backtracking to bubble up and return the bottommost item.</p>\n\n<pre><code>// O(1)\nenqueue(x):\n stack.push(x)\n\n// time: O(n), space: O(n)\nx dequeue():\n temp = stack.pop()\n if stack.isEmpty():\n x = temp\n else:\n x = dequeue()\n stack.push(temp)\n return x\n</code></pre>\n\n<p>Obviously, it's a good coding exercise as it inefficient but elegant nevertheless.</p>\n"
},
{
"answer_id": 46796061,
"author": "davejlin",
"author_id": 5464788,
"author_profile": "https://Stackoverflow.com/users/5464788",
"pm_score": 1,
"selected": false,
"text": "<p>An implementation of a queue using two stacks in Swift:</p>\n\n<pre class=\"lang-swift prettyprint-override\"><code>struct Stack<Element> {\n var items = [Element]()\n\n var count : Int {\n return items.count\n }\n\n mutating func push(_ item: Element) {\n items.append(item)\n }\n\n mutating func pop() -> Element? {\n return items.removeLast()\n }\n\n func peek() -> Element? {\n return items.last\n }\n}\n\nstruct Queue<Element> {\n var inStack = Stack<Element>()\n var outStack = Stack<Element>()\n\n mutating func enqueue(_ item: Element) {\n inStack.push(item)\n }\n\n mutating func dequeue() -> Element? {\n fillOutStack() \n return outStack.pop()\n }\n\n mutating func peek() -> Element? {\n fillOutStack()\n return outStack.peek()\n }\n\n private mutating func fillOutStack() {\n if outStack.count == 0 {\n while inStack.count != 0 {\n outStack.push(inStack.pop()!)\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 50548677,
"author": "Radioactive",
"author_id": 5670939,
"author_profile": "https://Stackoverflow.com/users/5670939",
"pm_score": 1,
"selected": false,
"text": "<p>While you will get a lot of posts related to implementing a queue with two stacks :\n1. Either by making the enQueue process a lot more costly\n2. Or by making the deQueue process a lot more costly</p>\n\n<p><a href=\"https://www.geeksforgeeks.org/queue-using-stacks/\" rel=\"nofollow noreferrer\">https://www.geeksforgeeks.org/queue-using-stacks/</a></p>\n\n<p>One important way I found out from the above post was constructing queue with only stack data structure and the recursion call stack.</p>\n\n<p>While one can argue that literally this is still using two stacks, but then ideally this is using only one stack data structure.</p>\n\n<p>Below is the explanation of the problem:</p>\n\n<ol>\n<li><p>Declare a single stack for enQueuing and deQueing the data and push the data into the stack.</p></li>\n<li><p>while deQueueing have a base condition where the element of the stack is poped when the size of the stack is 1. This will ensure that there is no stack overflow during the deQueue recursion.</p></li>\n<li><p>While deQueueing first pop the data from the top of the stack. Ideally this element will be the element which is present at the top of the stack. Now once this is done, recursively call the deQueue function and then push the element popped above back into the stack.</p></li>\n</ol>\n\n<p>The code will look like below:</p>\n\n<pre><code>if (s1.isEmpty())\nSystem.out.println(\"The Queue is empty\");\n else if (s1.size() == 1)\n return s1.pop();\n else {\n int x = s1.pop();\n int result = deQueue();\n s1.push(x);\n return result;\n</code></pre>\n\n<p>This way you can create a queue using a single stack data structure and the recursion call stack.</p>\n"
},
{
"answer_id": 54274637,
"author": "Jyoti Prasad Pal",
"author_id": 3173123,
"author_profile": "https://Stackoverflow.com/users/3173123",
"pm_score": 1,
"selected": false,
"text": "<p>Below is the solution in javascript language using ES6 syntax.</p>\n\n<p><strong>Stack.js</strong></p>\n\n<pre><code>//stack using array\nclass Stack {\n constructor() {\n this.data = [];\n }\n\n push(data) {\n this.data.push(data);\n }\n\n pop() {\n return this.data.pop();\n }\n\n peek() {\n return this.data[this.data.length - 1];\n }\n\n size(){\n return this.data.length;\n }\n}\n\nexport { Stack };\n</code></pre>\n\n<p><strong>QueueUsingTwoStacks.js</strong></p>\n\n<pre><code>import { Stack } from \"./Stack\";\n\nclass QueueUsingTwoStacks {\n constructor() {\n this.stack1 = new Stack();\n this.stack2 = new Stack();\n }\n\n enqueue(data) {\n this.stack1.push(data);\n }\n\n dequeue() {\n //if both stacks are empty, return undefined\n if (this.stack1.size() === 0 && this.stack2.size() === 0)\n return undefined;\n\n //if stack2 is empty, pop all elements from stack1 to stack2 till stack1 is empty\n if (this.stack2.size() === 0) {\n while (this.stack1.size() !== 0) {\n this.stack2.push(this.stack1.pop());\n }\n }\n\n //pop and return the element from stack 2\n return this.stack2.pop();\n }\n}\n\nexport { QueueUsingTwoStacks };\n</code></pre>\n\n<p>Below is the usage:</p>\n\n<p><strong>index.js</strong></p>\n\n<pre><code>import { StackUsingTwoQueues } from './StackUsingTwoQueues';\n\nlet que = new QueueUsingTwoStacks();\nque.enqueue(\"A\");\nque.enqueue(\"B\");\nque.enqueue(\"C\");\n\nconsole.log(que.dequeue()); //output: \"A\"\n</code></pre>\n"
},
{
"answer_id": 58008554,
"author": "Girish Rathi",
"author_id": 9785149,
"author_profile": "https://Stackoverflow.com/users/9785149",
"pm_score": 3,
"selected": false,
"text": "<p>Implement the following operations of a queue using stacks.</p>\n\n<p>push(x) -- Push element x to the back of queue.</p>\n\n<p>pop() -- Removes the element from in front of queue.</p>\n\n<p>peek() -- Get the front element.</p>\n\n<p>empty() -- Return whether the queue is empty. </p>\n\n<p><a href=\"https://i.stack.imgur.com/LQJBQ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LQJBQ.png\" alt=\"enter image description here\"></a></p>\n\n<pre><code>class MyQueue {\n\n Stack<Integer> input;\n Stack<Integer> output;\n\n /** Initialize your data structure here. */\n public MyQueue() {\n input = new Stack<Integer>();\n output = new Stack<Integer>();\n }\n\n /** Push element x to the back of queue. */\n public void push(int x) {\n input.push(x);\n }\n\n /** Removes the element from in front of queue and returns that element. */\n public int pop() {\n peek();\n return output.pop();\n }\n\n /** Get the front element. */\n public int peek() {\n if(output.isEmpty()) {\n while(!input.isEmpty()) {\n output.push(input.pop());\n }\n }\n return output.peek();\n }\n\n /** Returns whether the queue is empty. */\n public boolean empty() {\n return input.isEmpty() && output.isEmpty();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 62305888,
"author": "ASHISH R",
"author_id": 4259659,
"author_profile": "https://Stackoverflow.com/users/4259659",
"pm_score": 1,
"selected": false,
"text": "<p>**Easy JS solution **</p>\n\n<ul>\n<li>Note: I took ideas from other people comment </li>\n</ul>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>/*\r\n\r\nenQueue(q, x)\r\n 1) Push x to stack1 (assuming size of stacks is unlimited).\r\n\r\ndeQueue(q)\r\n 1) If both stacks are empty then error.\r\n 2) If stack2 is empty\r\n While stack1 is not empty, push everything from stack1 to stack2.\r\n 3) Pop the element from stack2 and return it.\r\n\r\n*/\r\nclass myQueue {\r\n constructor() {\r\n this.stack1 = [];\r\n this.stack2 = [];\r\n }\r\n\r\n push(item) {\r\n this.stack1.push(item)\r\n }\r\n\r\n remove() {\r\n if (this.stack1.length == 0 && this.stack2.length == 0) {\r\n return \"Stack are empty\"\r\n }\r\n\r\n if (this.stack2.length == 0) {\r\n\r\n while (this.stack1.length != 0) {\r\n this.stack2.push(this.stack1.pop())\r\n }\r\n }\r\n return this.stack2.pop()\r\n }\r\n\r\n\r\n peek() {\r\n if (this.stack2.length == 0 && this.stack1.length == 0) {\r\n return 'Empty list'\r\n }\r\n\r\n if (this.stack2.length == 0) {\r\n while (this.stack1.length != 0) {\r\n this.stack2.push(this.stack1.pop())\r\n }\r\n }\r\n\r\n return this.stack2[0]\r\n }\r\n\r\n isEmpty() {\r\n return this.stack2.length === 0 && this.stack1.length === 0;\r\n }\r\n\r\n}\r\n\r\nconst q = new myQueue();\r\nq.push(1);\r\nq.push(2);\r\nq.push(3);\r\nq.remove()\r\n\r\nconsole.log(q)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 67205990,
"author": "Sarang",
"author_id": 1278758,
"author_profile": "https://Stackoverflow.com/users/1278758",
"pm_score": 0,
"selected": false,
"text": "<p>My Solution with PHP</p>\n<pre><code><?php\n$_fp = fopen("php://stdin", "r");\n/* Enter your code here. Read input from STDIN. Print output to STDOUT */\n $queue = array();\n $count = 0;\n while($line = fgets($_fp)) {\n if($count == 0) {\n $noOfElement = $line;\n $count++;\n continue;\n }\n $action = explode(" ",$line);\n $case = $action[0];\n switch($case) {\n case 1:\n $enqueueValue = $action[1];\n array_push($queue, $enqueueValue);\n break;\n case 2:\n array_shift($queue);\n break;\n case 3:\n $show = reset($queue);\n print_r($show);\n break;\n default:\n break;\n }\n }\n?>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
]
| Suppose we have two stacks and no other temporary variable.
Is to possible to "construct" a queue data structure using only the two stacks? | Keep 2 stacks, let's call them `inbox` and `outbox`.
**Enqueue**:
* Push the new element onto `inbox`
**Dequeue**:
* If `outbox` is empty, refill it by popping each element from `inbox` and pushing it onto `outbox`
* Pop and return the top element from `outbox`
Using this method, each element will be in each stack exactly once - meaning each element will be pushed twice and popped twice, giving amortized constant time operations.
Here's an implementation in Java:
```java
public class Queue<E>
{
private Stack<E> inbox = new Stack<E>();
private Stack<E> outbox = new Stack<E>();
public void queue(E item) {
inbox.push(item);
}
public E dequeue() {
if (outbox.isEmpty()) {
while (!inbox.isEmpty()) {
outbox.push(inbox.pop());
}
}
return outbox.pop();
}
}
``` |
69,209 | <p>Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to the previous node?After deletion the previous node should point to the node next to deleted node. </p>
| [
{
"answer_id": 69214,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>yes, but you can't delink it. If you don't care about corrupting memory, go ahead ;-)</p>\n"
},
{
"answer_id": 69220,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 1,
"selected": false,
"text": "<p>Not if you want to maintain the traversability of the list. You need to update the previous node to link to the next one.</p>\n\n<p>How'd you end up in this situation, anyway? What are you trying to do that makes you ask this question?</p>\n"
},
{
"answer_id": 69229,
"author": "owenmarshall",
"author_id": 9806,
"author_profile": "https://Stackoverflow.com/users/9806",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, but your list will be broken after you remove it.</p>\n\n<p>In this specific case, traverse the list again and get that pointer! In general, if you are asking this question, there probably exists a bug in what you are doing.</p>\n"
},
{
"answer_id": 69232,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "<p>The initial suggestion was to transform:</p>\n\n<p>a -> b -> c</p>\n\n<p>to:</p>\n\n<p>a ->, c</p>\n\n<p>If you keep the information around, say, a map from address of node to address of the next node then you can fix the chain the next time to traverse the list. If need to delete multiple items before the next traversal then you need to keep track of the order of deletes (i.e. a change list).</p>\n\n<p>The standard solution is consider other data structures like a skip list.</p>\n"
},
{
"answer_id": 69234,
"author": "Kimbo",
"author_id": 10960,
"author_profile": "https://Stackoverflow.com/users/10960",
"pm_score": 1,
"selected": false,
"text": "<p>You'll have to march down the list to find the previous node. That will make deleting in general O(n**2). If you are the only code doing deletes, you may do better in practice by caching the previous node, and starting your search there, but whether this helps depends on the pattern of deletes.</p>\n"
},
{
"answer_id": 69235,
"author": "Eltariel",
"author_id": 584,
"author_profile": "https://Stackoverflow.com/users/584",
"pm_score": 0,
"selected": false,
"text": "<p>In order to get to the previous list item, you would need to traverse the list from the beginning until you find an entry with a <code>next</code> pointer that points to your current item. Then you'd have a pointer to each of the items that you'd have to modify to remove the current item from the list - simply set <code>previous->next</code> to <code>current->next</code> then delete <code>current</code>.</p>\n\n<p>edit: Kimbo beat me to it by less than a minute!</p>\n"
},
{
"answer_id": 69236,
"author": "perimosocordiae",
"author_id": 10601,
"author_profile": "https://Stackoverflow.com/users/10601",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe do a soft delete? (i.e., set a \"deleted\" flag on the node) You can clean up the list later if you need to.</p>\n"
},
{
"answer_id": 69240,
"author": "Joe Hildebrand",
"author_id": 8388,
"author_profile": "https://Stackoverflow.com/users/8388",
"pm_score": 2,
"selected": false,
"text": "<p>One approach would be to insert a null for the data. Whenever you traverse the list, you keep track of the previous node. If you find null data, you fix up the list, and go to the next node.</p>\n"
},
{
"answer_id": 69247,
"author": "DJ Capelis",
"author_id": 10943,
"author_profile": "https://Stackoverflow.com/users/10943",
"pm_score": 0,
"selected": false,
"text": "<p>You could do delayed delinking where you set nodes to be delinked out of the list with a flag and then delete them on the next proper traversal. Nodes set to be delinked would need to be properly handled by the code that crawls the list.</p>\n\n<p>I suppose you could also just traverse the list again from the beginning until you find the thing that points to your item in the list. Hardly optimal, but at least a much better idea than delayed delinking.</p>\n\n<p>In general, you should know the pointer to the item you just came from and you should be passing that around.</p>\n\n<p>(Edit: Ick, with the time it took me to type out a fullish answer three gazillion people covered almost all the points I was going to mention. :()</p>\n"
},
{
"answer_id": 69289,
"author": "Paul",
"author_id": 11012,
"author_profile": "https://Stackoverflow.com/users/11012",
"pm_score": 0,
"selected": false,
"text": "<p>The only sensible way to do this is to traverse the list with a couple of pointers until the leading one finds the node to be deleted, then update the next field using the trailing pointer.</p>\n\n<p>If you want to delete random items from a list efficiently, it needs to be doubly linked. If you want take items from the head of the list and add them at the tail, however, you don't need to doubly link the whole list. Singly link the list but make the next field of the last item on the list point to the first item on the list. Then make the list \"head\" point to the tail item (not the head). It is then easy to add to the tail of the list or remove from the head.</p>\n"
},
{
"answer_id": 69306,
"author": "Ben Combee",
"author_id": 1323,
"author_profile": "https://Stackoverflow.com/users/1323",
"pm_score": 5,
"selected": false,
"text": "<p>Let's assume a list with the structure</p>\n\n<p>A -> B -> C -> D</p>\n\n<p>If you only had a pointer to B and wanted to delete it, you could do something like</p>\n\n<pre><code>tempList = B->next;\n*B = *tempList;\nfree(tempList);\n</code></pre>\n\n<p>The list would then look like</p>\n\n<p>A -> B -> D</p>\n\n<p>but B would hold the old contents of C, effectively deleting what was in B. This won't work if some other piece of code is holding a pointer to C. It also won't work if you were trying to delete node D. If you want to do this kind of operation, you'll need to build the list with a dummy tail node that's not really used so you guarantee that no useful node will have a NULL next pointer. This also works better for lists where the amount of data stored in a node is small. A structure like</p>\n\n<pre><code>struct List { struct List *next; MyData *data; };\n</code></pre>\n\n<p>would be OK, but one where it's</p>\n\n<pre><code>struct HeavyList { struct HeavyList *next; char data[8192]; };\n</code></pre>\n\n<p>would be a bit burdensome.</p>\n"
},
{
"answer_id": 69321,
"author": "Charles Graham",
"author_id": 7705,
"author_profile": "https://Stackoverflow.com/users/7705",
"pm_score": 0,
"selected": false,
"text": "<p>You have the head of the list, right? You just traverse it.</p>\n\n<p>Let's say that your list is pointed to by \"head\" and the node to delete it \"del\".</p>\n\n<p>C style pseudo-code (dots would be -> in C):</p>\n\n<pre><code>prev = head\nnext = prev.link\n\nwhile(next != null)\n{\n if(next == del)\n {\n prev.link = next.link;\n free(del);\n del = null;\n return 0;\n }\n prev = next;\n next = next.link;\n}\n\nreturn 1;\n</code></pre>\n"
},
{
"answer_id": 69333,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "<p>It's definitely more a quiz rather than a real problem. However, if we are allowed to make some assumption, it can be solved in O(1) time. To do it, the strictures the list points to must be copyable. The algorithm is as the following:</p>\n\n<p>We have a list looking like: ... -> Node(i-1) -> Node(i) -> Node(i+1) -> ... and we need to delete Node(i).</p>\n\n<ol>\n<li>Copy data (not pointer, the data itself) from Node(i+1) to Node(i), the list will look like: ... -> Node(i-1) -> Node(i+1) -> Node(i+1) -> ...</li>\n<li>Copy the NEXT of second Node(i+1) into a temporary variable.</li>\n<li>Now Delete the second Node(i+1), it doesn't require pointer to the previous node.</li>\n</ol>\n\n<p>Pseudocode:</p>\n\n<pre><code>void delete_node(Node* pNode)\n{\n pNode->Data = pNode->Next->Data; // Assume that SData::operator=(SData&) exists.\n Node* pTemp = pNode->Next->Next;\n delete(pNode->Next);\n pNode->Next = pTemp;\n}\n</code></pre>\n\n<p>Mike.</p>\n"
},
{
"answer_id": 69401,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 1,
"selected": false,
"text": "<p>Given</p>\n\n<p>A -> B -> C -> D</p>\n\n<p>and a pointer to, say, item B, you would delete it by<br>\n1. free any memory belonging to members of B<br>\n2. copy the contents of C into B (this includes its \"next\" pointer)<br>\n3. delete the entire item C </p>\n\n<p>Of course, you'll have to be careful about edge cases, such as working on lists of one item.</p>\n\n<p>Now where there was B, you have C and the storage that used to be C is freed.</p>\n"
},
{
"answer_id": 1000807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>The following code will create a LL, n then ask the user to give the pointer to the node to be deleted. it will the print the list after deletion\nIt does the same thing as is done by copying the node after the node to be deleted, over the node to be deleted and then delete the next node of the node to be deleted.\ni.e</p>\n\n<p>a-b-c-d</p>\n\n<p>copy c to b and free c so that result is</p>\n\n<p>a-c-d</p>\n\n<pre><code>struct node \n{\n int data;\n struct node *link;\n };\n\nvoid populate(struct node **,int);\n\nvoid delete(struct node **);\n\nvoid printlist(struct node **);\n\nvoid populate(struct node **n,int num)\n{\n\n struct node *temp,*t;\n if(*n==NULL)\n {\n t=*n;\n t=malloc(sizeof(struct node));\n t->data=num;\n t->link=NULL;\n *n=t;\n }\n else\n {\n t=*n;\n temp=malloc(sizeof(struct node));\n while(t->link!=NULL)\n t=t->link;\n temp->data=num;\n temp->link=NULL;\n t->link=temp;\n }\n}\n\nvoid printlist(struct node **n)\n{\n struct node *t;\n t=*n;\n if(t==NULL)\n printf(\"\\nEmpty list\");\n\n while(t!=NULL)\n {\n printf(\"\\n%d\",t->data);\n printf(\"\\t%u address=\",t);\n t=t->link;\n }\n}\n\n\nvoid delete(struct node **n)\n{\n struct node *temp,*t;\n temp=*n;\n temp->data=temp->link->data;\n t=temp->link;\n temp->link=temp->link->link;\n free(t);\n} \n\nint main()\n{\n struct node *ty,*todelete;\n ty=NULL;\n populate(&ty,1);\n populate(&ty,2);\n populate(&ty,13);\n populate(&ty,14);\n populate(&ty,12);\n populate(&ty,19);\n\n printf(\"\\nlist b4 delete\\n\");\n printlist(&ty);\n\n printf(\"\\nEnter node pointer to delete the node====\");\n scanf(\"%u\",&todelete);\n delete(&todelete);\n\n printf(\"\\nlist after delete\\n\");\n printlist(&ty);\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 2306642,
"author": "Aneesh",
"author_id": 278188,
"author_profile": "https://Stackoverflow.com/users/278188",
"pm_score": 0,
"selected": false,
"text": "<pre><code>void delself(list *list)\n{\n /*if we got a pointer to itself how to remove it...*/\n int n;\n\n printf(\"Enter the num:\");\n\n scanf(\"%d\",&n);\n\n while(list->next!=NULL)\n {\n if(list->number==n) /*now pointer in node itself*/\n {\n list->number=list->next->number;\n /*copy all(name,rollnum,mark..) data of next to current, disconect its next*/\n list->next=list->next->next;\n }\n list=list->next;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2306670,
"author": "Aneesh",
"author_id": 278188,
"author_profile": "https://Stackoverflow.com/users/278188",
"pm_score": 0,
"selected": false,
"text": "<pre><code>void delself(list *list)\n{\n /*if we got a pointer to itself how to remove it...*/\n int n;\n\n printf(\"Enter the num:\");\n scanf(\"%d\",&n);\n\n while(list->next!=NULL)\n {\n if(list->number==n) /*now pointer in node itself*/\n {\n list->number=list->next->number; /*copy all(name,rollnum,mark..)\n data of next to current, disconnect its next*/\n list->next=list->next->next;\n }\n list=list->next;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3635670,
"author": "Smitha",
"author_id": 438945,
"author_profile": "https://Stackoverflow.com/users/438945",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a linked list A -> B -> C -> D and a pointer to node B. If you have to delete this node you can copy the contents of node C into B, node D into C and delete D. But we cannot delete the node as such in case of a singly linked list since if we do so, node A will also be lost. Though we can backtrack to A in case of doubly linked list.</p>\n\n<p>Am I right? </p>\n"
},
{
"answer_id": 4545555,
"author": "codaddict",
"author_id": 227665,
"author_profile": "https://Stackoverflow.com/users/227665",
"pm_score": 4,
"selected": false,
"text": "<p>Not possible.</p>\n\n<p>There are hacks to mimic the deletion. </p>\n\n<p>But none of then will actually delete the node the pointer is pointing to.</p>\n\n<p>The popular solution of deleting the <strong>following</strong> node and copying its contents to the <strong>actual</strong> node to be deleted has side-effects if you have <strong>external pointers</strong> pointing to nodes in the list, in which case an external pointer pointing to the following node will become dangling.</p>\n"
},
{
"answer_id": 8527869,
"author": "Alex B",
"author_id": 583972,
"author_profile": "https://Stackoverflow.com/users/583972",
"pm_score": 3,
"selected": false,
"text": "<p>I appreciate the ingenuity of this solution (deleting the next node), but it does not answer the problem's question. If this is the actual solution, the correct question should be \"delete from the linked list the VALUE contained in a node on which the pointer is given\". But of course, the correct question gives you a hint on solution.\nThe problem as it is formulated, is intended to confuse the person (which in fact has happened to me, especially because the interviewer did not even mention that the node is in the middle).</p>\n"
},
{
"answer_id": 11534729,
"author": "Sandeep Mathias",
"author_id": 1533689,
"author_profile": "https://Stackoverflow.com/users/1533689",
"pm_score": 2,
"selected": false,
"text": "<p>The best approach is still to copy the data of the next node into the node to be deleted, set the next pointer of the node to the next node's next pointer, and delete the next node.</p>\n\n<p>The issues of external pointers pointing to the node to be deleted, while true, would also hold for the next node. Consider the following linked lists:</p>\n\n<p>A->B->C->D->E->F and G->H->I->D->E->F</p>\n\n<p>In case you have to delete node C (in the first linked list), by the approach mentioned, you will delete node D after copying the contents to node C. This will result in the following lists:</p>\n\n<p>A->B->D->E->F and G->H->I->dangling pointer.</p>\n\n<p>In case you delete the NODE C completely, the resulting lists will be:</p>\n\n<p>A->B->D->E->F and G->H->I->D->E->F.</p>\n\n<p>However, if you are to delete the node D, and you use the earlier approach, the issue of external pointers is still there.</p>\n"
},
{
"answer_id": 13522571,
"author": "Vinay Kumar Baghel",
"author_id": 685692,
"author_profile": "https://Stackoverflow.com/users/685692",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Void deleteMidddle(Node* head)\n{\n Node* slow_ptr = head;\n Node* fast_ptr = head;\n Node* tmp = head;\n while(slow_ptr->next != NULL && fast_ptr->next != NULL)\n {\n tmp = slow_ptr;\n slow_ptr = slow_ptr->next;\n fast_ptr = fast_ptr->next->next;\n }\n tmp->next = slow_ptr->next;\n free(slow_ptr);\n enter code here\n\n}\n</code></pre>\n"
},
{
"answer_id": 15356392,
"author": "Desyn8686",
"author_id": 2159985,
"author_profile": "https://Stackoverflow.com/users/2159985",
"pm_score": 0,
"selected": false,
"text": "<p>This is a piece of code I put together that does what the OP was asking for, and can even delete the last element in the list (not in the most elegant way, but it gets it done). Wrote it while learning how to use linked lists. Hope it helps.</p>\n\n<pre><code>#include <cstdlib>\n#include <ctime>\n#include <iostream>\n#include <string>\n\nusing namespace std;\n\n\nstruct node\n{\n int nodeID;\n node *next;\n};\n\nvoid printList(node* p_nodeList, int removeID);\nvoid removeNode(node* p_nodeList, int nodeID);\nvoid removeLastNode(node* p_nodeList, int nodeID ,node* p_lastNode);\n\nnode* addNewNode(node* p_nodeList, int id)\n{\n node* p_node = new node;\n p_node->nodeID = id;\n p_node->next = p_nodeList;\n return p_node;\n}\n\nint main()\n{\n node* p_nodeList = NULL;\n int nodeID = 1;\n int removeID;\n int listLength;\n cout << \"Pick a list length: \";\n cin >> listLength;\n for (int i = 0; i < listLength; i++)\n {\n p_nodeList = addNewNode(p_nodeList, nodeID);\n nodeID++;\n }\n cout << \"Pick a node from 1 to \" << listLength << \" to remove: \";\n cin >> removeID;\n while (removeID <= 0 || removeID > listLength)\n {\n if (removeID == 0)\n {\n return 0;\n }\n cout << \"Please pick a number from 1 to \" << listLength << \": \";\n cin >> removeID;\n }\n removeNode(p_nodeList, removeID);\n printList(p_nodeList, removeID);\n}\n\nvoid printList(node* p_nodeList, int removeID)\n{\n node* p_currentNode = p_nodeList;\n if (p_currentNode != NULL)\n {\n p_currentNode = p_currentNode->next;\n printList(p_currentNode, removeID);\n if (removeID != 1)\n {\n if (p_nodeList->nodeID != 1)\n {\n cout << \", \";\n }\n\n cout << p_nodeList->nodeID;\n }\n else\n {\n if (p_nodeList->nodeID !=2)\n {\n cout << \", \";\n }\n cout << p_nodeList->nodeID;\n }\n }\n}\n\nvoid removeNode(node* p_nodeList, int nodeID)\n{\n node* p_currentNode = p_nodeList;\n if (p_currentNode->nodeID == nodeID)\n {\n if(p_currentNode->next != NULL)\n {\n p_currentNode->nodeID = p_currentNode->next->nodeID;\n node* p_temp = p_currentNode->next->next;\n delete(p_currentNode->next);\n p_currentNode->next = p_temp;\n }\n else\n {\n delete(p_currentNode);\n }\n }\n else if(p_currentNode->next->next == NULL)\n {\n removeLastNode(p_currentNode->next, nodeID, p_currentNode);\n }\n else\n {\n removeNode(p_currentNode->next, nodeID);\n }\n}\n\nvoid removeLastNode(node* p_nodeList, int nodeID ,node* p_lastNode)\n{\n node* p_currentNode = p_nodeList;\n p_lastNode->next = NULL;\n delete (p_currentNode);\n}\n</code></pre>\n"
},
{
"answer_id": 58032707,
"author": "Ankit Raj",
"author_id": 5494644,
"author_profile": "https://Stackoverflow.com/users/5494644",
"pm_score": 1,
"selected": false,
"text": "<p>Considering below linked list</p>\n\n<blockquote>\n <p>1 -> 2 -> 3 -> NULL</p>\n \n <p>Pointer to node 2 is given say \"ptr\".</p>\n</blockquote>\n\n<p>We can have pseudo-code which looks something like this:</p>\n\n<pre><code>struct node* temp = ptr->next;\nptr->data = temp->data;\nptr->next = temp->next;\nfree(temp);\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7086/"
]
| Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to the previous node?After deletion the previous node should point to the node next to deleted node. | It's definitely more a quiz rather than a real problem. However, if we are allowed to make some assumption, it can be solved in O(1) time. To do it, the strictures the list points to must be copyable. The algorithm is as the following:
We have a list looking like: ... -> Node(i-1) -> Node(i) -> Node(i+1) -> ... and we need to delete Node(i).
1. Copy data (not pointer, the data itself) from Node(i+1) to Node(i), the list will look like: ... -> Node(i-1) -> Node(i+1) -> Node(i+1) -> ...
2. Copy the NEXT of second Node(i+1) into a temporary variable.
3. Now Delete the second Node(i+1), it doesn't require pointer to the previous node.
Pseudocode:
```
void delete_node(Node* pNode)
{
pNode->Data = pNode->Next->Data; // Assume that SData::operator=(SData&) exists.
Node* pTemp = pNode->Next->Next;
delete(pNode->Next);
pNode->Next = pTemp;
}
```
Mike. |
69,250 | <p>In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.<br>
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.<br>
In "release" mode, you usually have all sorts of optimizations turned on.<br>
Why the difference?</p>
| [
{
"answer_id": 69252,
"author": "Benoit",
"author_id": 10703,
"author_profile": "https://Stackoverflow.com/users/10703",
"pm_score": 6,
"selected": true,
"text": "<p>Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.<br>\nFor example:</p>\n\n<pre><code>\nvoid foo() {\n1: int i;\n2: for(i = 0; i < 2; )\n3: i++;\n4: return;\n</code></pre>\n\n<p>In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4</p>\n\n<p>With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)</p>\n\n<p>Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.</p>\n\n<p>Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.</p>\n\n<p>While the optimized and non-optimized code should be \"functionally\" equivalent, under certain circumstances, the behavior will change.<br>\nHere is a simplistic example:<br>\n<code><pre>\n int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device\n *ptr = 0; // setup hardware device\n while(*ptr == 1) { // loop until hardware device is done\n // do something\n }\n</pre></code></p>\n\n<p>With optimization off, this is straightforward, and you kinda know what to expect.\nHowever, if you turn optimization on, a couple of things might happen:</p>\n\n<ul>\n<li>The compiler might optimize the while block away (we init to 0, it'll never be 1)</li>\n<li>Instead of accessing memory, pointer access might be moved to a register->No I/O Update</li>\n<li>memory access might be cached (not necessarily compiler optimization related)</li>\n</ul>\n\n<p>In all these cases, the behavior would be drastically different and most likely wrong.</p>\n"
},
{
"answer_id": 69313,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "<p>Another crucial difference between debug and release is how local variables are stored. Conceptually local variables are allocated storage in a functions stack frame. The symbol file generated by the compiler tells the debugger the offset of the variable in the stack frame, so the debugger can show it to you. The debugger peeks at the memory location to do this.</p>\n\n<p>However, this means every time a local variable is changed the generated code for that source line has to write the value back to the correct location on the stack. This is very inefficient due to the memory overhead.</p>\n\n<p>In a release build the compiler may assign a local variable to a register for a portion of a function. In some cases it may not assign stack storage for it at all (the more registers a machine has the easier this is to do).</p>\n\n<p>However, the debugger doesn't know how registers map to local variables for a particular point in the code (I'm not aware of any symbol format that includes this information), so it can't show it to you accurately as it doesn't know where to go looking for it.</p>\n\n<p>Another optimization would be function inlining. In optimized builds the compiler may replace a call to foo() with the actual code for foo everywhere it is used because the function is small enough. However, when you try to set a breakpoint on foo() the debugger wants to know the address of the instructions for foo(), and there is no longer a simple answer to this -- there may be thousands of copies of the foo() code bytes spread over your program. A debug build will guarantee that there is somewhere for you to put the breakpoint.</p>\n"
},
{
"answer_id": 69318,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 2,
"selected": false,
"text": "<p>The expectation is for the debug version to be - debugged! Setting breakpoints, single-stepping while watching variables, stack traces, and everything else you do in a debugger (IDE or otherwise) make sense if every line of non-empty, non-comment source code matches some machine code instruction. </p>\n\n<p>Most optimizations mess with the order of machine codes. Loop unrolling is a good example. Common subexpressions can be lifted out of loops. With optimization turned on, even the simplest level, you may be trying to set a breakpoint on a line that, at the machine code level, doesn't exist. Sometime you can't monitor a local variable due to it being kept in a CPU register, or perhaps even optimized out of existence!</p>\n"
},
{
"answer_id": 69650,
"author": "George V. Reilly",
"author_id": 6364,
"author_profile": "https://Stackoverflow.com/users/6364",
"pm_score": 1,
"selected": false,
"text": "<p>If you're debugging at the instruction level rather than the source level, it's an awful lot for you easier to map unoptimized instructions back to the source. Also, compilers are occasionally buggy in their optimizers.</p>\n\n<p>In the Windows division at Microsoft, all release binaries are built with debugging symbols and full optimizations. The symbols are stored in separate PDB files and do not affect the performance of the code. They don't ship with the product, but most of them are available at the <a href=\"http://support.microsoft.com/kb/311503\" rel=\"nofollow noreferrer\">Microsoft Symbol Server</a>.</p>\n"
},
{
"answer_id": 69697,
"author": "mxg",
"author_id": 11157,
"author_profile": "https://Stackoverflow.com/users/11157",
"pm_score": 2,
"selected": false,
"text": "<p>Optimizing code is an automated process that improves the runtime performance of the code while preserving semantics. This process can remove intermediate results which are unncessary to complete an expression or function evaluation, but may be of interest to you when debugging. Similarly, optimizations can alter the apparent control flow so that things may happen in a slightly different order than what appears in the source code. This is done to skip unnecessary or redundant calculations. This rejiggering of code can mess with the mapping between source code line numbers and object code addresses making it hard for a debugger to follow the flow of control as you wrote it.</p>\n\n<p>Debugging in unoptimized mode allows you to see everything you've written as you've written it without the optimizer removing or reordering things.</p>\n\n<p>Once you are happy that your program is working correctly you can turn on optimizations to get improved performance. Even though optimizers are pretty trustworthy these days, it's still a good idea to build a good quality test suite to ensure that your program runs identically (from a functional point of view, not considering performance) in both optimized and unoptimized mode.</p>\n"
},
{
"answer_id": 433681,
"author": "Blaisorblade",
"author_id": 53974,
"author_profile": "https://Stackoverflow.com/users/53974",
"pm_score": 1,
"selected": false,
"text": "<p>Another of the issues with optimizations are inline functions, also in the sense that you will always single-step through them.</p>\n\n<p>With GCC, with debugging and optimizations enabled together, if you don't know what to expect you will think that the code is misbehaving and re-executing the same statement multiple times - it happened to a couple of my colleagues.\nAlso debugging info given by GCC with optimizations on tend to be of poorer quality than they could, actually.</p>\n\n<p>However, in languages hosted by a Virtual Machine like Java, optimizations and debugging can coexist - even during debugging, JIT compilation to native code continues, and only the code of debugged methods is transparently converted to an unoptimized version.</p>\n\n<p>I would like to emphasize that optimization should not change the behaviour of the code, unless the used optimizer is buggy, or the code itself is buggy and relies on partially undefined semantics; the latter is more common in multithreaded programming or when inline assembly is also used.</p>\n\n<blockquote>\n <p>Code with debugging symbols are larger which may mean more cache misses, i.e. slower, which may be an issue for server software.</p>\n</blockquote>\n\n<p>At least on Linux (and there's no reason why Windows should be different) debug info are packaged in a separate section of the binary, and are not loaded during normal execution. They can be split into a different file to be used for debugging.\nAlso, on some compilers (including Gcc, I guess also with Microsoft's C compiler) debugging info and optimizations can be both enabled together. If not, obviously the code is going to be slower.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10703/"
]
| In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.
In "release" mode, you usually have all sorts of optimizations turned on.
Why the difference? | Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.
For example:
```
void foo() {
1: int i;
2: for(i = 0; i < 2; )
3: i++;
4: return;
```
In this example, without optimization, you could single step through the code and hit lines 1, 2, 3, 2, 3, 2, 4
With optimization on, you might get an execution path that looks like: 2, 3, 3, 4 or even just 4! (The function does nothing after all...)
Bottom line, debugging code with optimization enabled can be a royal pain! Especially if you have large functions.
Note that turning on optimization changes the code! In certain environment (safety critical systems), this is unacceptable and the code being debugged has to be the code shipped. Gotta debug with optimization on in that case.
While the optimized and non-optimized code should be "functionally" equivalent, under certain circumstances, the behavior will change.
Here is a simplistic example:
````
int* ptr = 0xdeadbeef; // some address to memory-mapped I/O device
*ptr = 0; // setup hardware device
while(*ptr == 1) { // loop until hardware device is done
// do something
}
````
With optimization off, this is straightforward, and you kinda know what to expect.
However, if you turn optimization on, a couple of things might happen:
* The compiler might optimize the while block away (we init to 0, it'll never be 1)
* Instead of accessing memory, pointer access might be moved to a register->No I/O Update
* memory access might be cached (not necessarily compiler optimization related)
In all these cases, the behavior would be drastically different and most likely wrong. |
69,262 | <p>I am wondering if there is a method or format string I'm missing in .NET to convert the following:</p>
<pre><code> 1 to 1st
2 to 2nd
3 to 3rd
4 to 4th
11 to 11th
101 to 101st
111 to 111th
</code></pre>
<p><a href="http://www.dotnet-friends.com/fastcode/csharp/fastcodeincsc3bd4149-03d0-40fe-90fd-63bcee77b43e.aspx" rel="noreferrer">This link</a> has a bad example of the basic principle involved in writing your own function, but I am more curious if there is an inbuilt capacity I'm missing.</p>
<p><strong>Solution</strong></p>
<p>Scott Hanselman's answer is the accepted one because it answers the question directly.</p>
<p>For a solution however, see <a href="https://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-numbers#69284">this great answer</a>.</p>
| [
{
"answer_id": 69279,
"author": "Scott Hanselman",
"author_id": 6380,
"author_profile": "https://Stackoverflow.com/users/6380",
"pm_score": 7,
"selected": true,
"text": "<p>No, there is no inbuilt capability in the .NET Base Class Library.</p>\n"
},
{
"answer_id": 69284,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": false,
"text": "<p>It's a function which is a lot simpler than you think. Though there might be a .NET function already in existence for this, the following function (written in PHP) does the job. It shouldn't be too hard to port it over.</p>\n\n<pre><code>function ordinal($num) {\n $ones = $num % 10;\n $tens = floor($num / 10) % 10;\n if ($tens == 1) {\n $suff = \"th\";\n } else {\n switch ($ones) {\n case 1 : $suff = \"st\"; break;\n case 2 : $suff = \"nd\"; break;\n case 3 : $suff = \"rd\"; break;\n default : $suff = \"th\";\n }\n }\n return $num . $suff;\n}\n</code></pre>\n"
},
{
"answer_id": 69287,
"author": "mjallday",
"author_id": 6084,
"author_profile": "https://Stackoverflow.com/users/6084",
"pm_score": 4,
"selected": false,
"text": "<p>This has already been covered but I'm unsure how to link to it. Here is the code snippit:</p>\n\n<pre><code> public static string Ordinal(this int number)\n {\n var ones = number % 10;\n var tens = Math.Floor (number / 10f) % 10;\n if (tens == 1)\n {\n return number + \"th\";\n }\n\n switch (ones)\n {\n case 1: return number + \"st\";\n case 2: return number + \"nd\";\n case 3: return number + \"rd\";\n default: return number + \"th\";\n }\n }\n</code></pre>\n\n<p>FYI: This is as an extension method. If your .NET version is less than 3.5 just remove the this keyword</p>\n\n<p>[EDIT]: Thanks for pointing that it was incorrect, that's what you get for copy / pasting code :)</p>\n"
},
{
"answer_id": 69293,
"author": "Hugh Buchanan",
"author_id": 9307,
"author_profile": "https://Stackoverflow.com/users/9307",
"pm_score": -1,
"selected": false,
"text": "<p>I think the ordinal suffix is hard to get... you basically have to write a function that uses a switch to test the numbers and add the suffix.</p>\n\n<p>There's no reason for a language to provide this internally, especially when it's locale specific.</p>\n\n<p>You can do a bit better than that link when it comes to the amount of code to write, but you have to code a function for this...</p>\n"
},
{
"answer_id": 69328,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 6,
"selected": false,
"text": "<p>@nickf: Here is the PHP function in C#:</p>\n\n<pre><code>public static string Ordinal(int number)\n{\n string suffix = String.Empty;\n\n int ones = number % 10;\n int tens = (int)Math.Floor(number / 10M) % 10;\n\n if (tens == 1)\n {\n suffix = \"th\";\n }\n else\n {\n switch (ones)\n {\n case 1:\n suffix = \"st\";\n break;\n\n case 2:\n suffix = \"nd\";\n break;\n\n case 3:\n suffix = \"rd\";\n break;\n\n default:\n suffix = \"th\";\n break;\n }\n }\n return String.Format(\"{0}{1}\", number, suffix);\n}\n</code></pre>\n"
},
{
"answer_id": 386318,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>else if (choice=='q')\n{\n qtr++;\n\n switch (qtr)\n {\n case(2): strcpy(qtrs,\"nd\");break;\n case(3):\n {\n strcpy(qtrs,\"rd\");\n cout<<\"End of First Half!!!\";\n cout<<\" hteam \"<<\"[\"<<hteam<<\"] \"<<hs;\n cout<<\" vteam \"<<\" [\"<<vteam;\n cout<<\"] \";\n cout<<vs;dwn=1;yd=10;\n\n if (beginp=='H') team='V';\n else team='H';\n break;\n }\n case(4): strcpy(qtrs,\"th\");break;\n</code></pre>\n"
},
{
"answer_id": 611179,
"author": "redcalx",
"author_id": 15703,
"author_profile": "https://Stackoverflow.com/users/15703",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a Microsoft SQL Server Function version:</p>\n\n<pre><code>CREATE FUNCTION [Internal].[GetNumberAsOrdinalString]\n(\n @num int\n)\nRETURNS nvarchar(max)\nAS\nBEGIN\n\n DECLARE @Suffix nvarchar(2);\n DECLARE @Ones int; \n DECLARE @Tens int;\n\n SET @Ones = @num % 10;\n SET @Tens = FLOOR(@num / 10) % 10;\n\n IF @Tens = 1\n BEGIN\n SET @Suffix = 'th';\n END\n ELSE\n BEGIN\n\n SET @Suffix = \n CASE @Ones\n WHEN 1 THEN 'st'\n WHEN 2 THEN 'nd'\n WHEN 3 THEN 'rd'\n ELSE 'th'\n END\n END\n\n RETURN CONVERT(nvarchar(max), @num) + @Suffix;\nEND\n</code></pre>\n"
},
{
"answer_id": 9290324,
"author": "avenmore",
"author_id": 37660,
"author_profile": "https://Stackoverflow.com/users/37660",
"pm_score": 2,
"selected": false,
"text": "<p>I know this isn't an answer to the OP's question, but because I found it useful to lift the SQL Server function from this thread, here is a Delphi (Pascal) equivalent:</p>\n\n<pre><code>function OrdinalNumberSuffix(const ANumber: integer): string;\nbegin\n Result := IntToStr(ANumber);\n if(((Abs(ANumber) div 10) mod 10) = 1) then // Tens = 1\n Result := Result + 'th'\n else\n case(Abs(ANumber) mod 10) of\n 1: Result := Result + 'st';\n 2: Result := Result + 'nd';\n 3: Result := Result + 'rd';\n else\n Result := Result + 'th';\n end;\nend;\n</code></pre>\n\n<p>Does ..., -1st, 0th make sense?</p>\n"
},
{
"answer_id": 19553611,
"author": "Shahzad Qureshi",
"author_id": 2719563,
"author_profile": "https://Stackoverflow.com/users/2719563",
"pm_score": 6,
"selected": false,
"text": "<p>Simple, clean, quick</p>\n\n<pre><code> private static string GetOrdinalSuffix(int num)\n {\n string number = num.ToString();\n if (number.EndsWith(\"11\")) return \"th\";\n if (number.EndsWith(\"12\")) return \"th\";\n if (number.EndsWith(\"13\")) return \"th\";\n if (number.EndsWith(\"1\")) return \"st\";\n if (number.EndsWith(\"2\")) return \"nd\";\n if (number.EndsWith(\"3\")) return \"rd\";\n return \"th\";\n }\n</code></pre>\n\n<p>Or better yet, as an extension method</p>\n\n<pre><code>public static class IntegerExtensions\n{\n public static string DisplayWithSuffix(this int num)\n {\n string number = num.ToString();\n if (number.EndsWith(\"11\")) return number + \"th\";\n if (number.EndsWith(\"12\")) return number + \"th\";\n if (number.EndsWith(\"13\")) return number + \"th\";\n if (number.EndsWith(\"1\")) return number + \"st\";\n if (number.EndsWith(\"2\")) return number + \"nd\";\n if (number.EndsWith(\"3\")) return number + \"rd\";\n return number + \"th\";\n }\n}\n</code></pre>\n\n<p>Now you can just call </p>\n\n<pre><code>int a = 1;\na.DisplayWithSuffix(); \n</code></pre>\n\n<p>or even as direct as </p>\n\n<pre><code>1.DisplayWithSuffix();\n</code></pre>\n"
},
{
"answer_id": 20550095,
"author": "Frank Hoffman",
"author_id": 747173,
"author_profile": "https://Stackoverflow.com/users/747173",
"pm_score": 1,
"selected": false,
"text": "<p>Another flavor:</p>\n\n<pre><code>/// <summary>\n/// Extension methods for numbers\n/// </summary>\npublic static class NumericExtensions\n{\n /// <summary>\n /// Adds the ordinal indicator to an integer\n /// </summary>\n /// <param name=\"number\">The number</param>\n /// <returns>The formatted number</returns>\n public static string ToOrdinalString(this int number)\n {\n // Numbers in the teens always end with \"th\"\n\n if((number % 100 > 10 && number % 100 < 20))\n return number + \"th\";\n else\n {\n // Check remainder\n\n switch(number % 10)\n {\n case 1:\n return number + \"st\";\n\n case 2:\n return number + \"nd\";\n\n case 3:\n return number + \"rd\";\n\n default:\n return number + \"th\";\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 20610293,
"author": "Faust",
"author_id": 613004,
"author_profile": "https://Stackoverflow.com/users/613004",
"pm_score": 0,
"selected": false,
"text": "<pre><code>public static string OrdinalSuffix(int ordinal)\n{\n //Because negatives won't work with modular division as expected:\n var abs = Math.Abs(ordinal); \n\n var lastdigit = abs % 10; \n\n return \n //Catch 60% of cases (to infinity) in the first conditional:\n lastdigit > 3 || lastdigit == 0 || (abs % 100) - lastdigit == 10 ? \"th\" \n : lastdigit == 1 ? \"st\" \n : lastdigit == 2 ? \"nd\" \n : \"rd\";\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
| I am wondering if there is a method or format string I'm missing in .NET to convert the following:
```
1 to 1st
2 to 2nd
3 to 3rd
4 to 4th
11 to 11th
101 to 101st
111 to 111th
```
[This link](http://www.dotnet-friends.com/fastcode/csharp/fastcodeincsc3bd4149-03d0-40fe-90fd-63bcee77b43e.aspx) has a bad example of the basic principle involved in writing your own function, but I am more curious if there is an inbuilt capacity I'm missing.
**Solution**
Scott Hanselman's answer is the accepted one because it answers the question directly.
For a solution however, see [this great answer](https://stackoverflow.com/questions/69262/is-there-an-easy-way-in-net-to-get-st-nd-rd-and-th-endings-for-numbers#69284). | No, there is no inbuilt capability in the .NET Base Class Library. |
69,275 | <p>I'm trying to draw a graph on an ASP webpage. I'm hoping an API can be helpful, but so far I have not been able to find one. </p>
<p>The graph contains labeled nodes and unlabeled directional edges.
The ideal output would be something like <a href="http://en.wikipedia.org/wiki/Image:6n-graf.svg" rel="noreferrer">this</a>. </p>
<p>Anybody know of anything pre-built than can help?</p>
| [
{
"answer_id": 69285,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "<p>I am not sure about ASP interface, but you may want to check out <a href=\"http://www.graphviz.org/\" rel=\"nofollow noreferrer\">graphviz</a>.</p>\n\n<p>/Allan</p>\n"
},
{
"answer_id": 69301,
"author": "Brian",
"author_id": 700,
"author_profile": "https://Stackoverflow.com/users/700",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to pull this off with <a href=\"http://code.google.com/apis/chart/\" rel=\"nofollow noreferrer\">Google's Chart API</a>. It is very easy to get started with.</p>\n"
},
{
"answer_id": 70585,
"author": "Paul Dolphin",
"author_id": 10186,
"author_profile": "https://Stackoverflow.com/users/10186",
"pm_score": 1,
"selected": false,
"text": "<p>I would recommend <a href=\"http://zedgraph.org/wiki/index.php?title=Main_Page\" rel=\"nofollow noreferrer\">zedgraph</a></p>\n"
},
{
"answer_id": 74815,
"author": "wxs",
"author_id": 12981,
"author_profile": "https://Stackoverflow.com/users/12981",
"pm_score": 4,
"selected": true,
"text": "<p>Definitely <a href=\"http://graphviz.org\" rel=\"nofollow noreferrer\">graphviz</a>. The image on the wikipedia link you are pointing at was made in graphviz. From its description page the graph description file looked like this:</p>\n\n<pre><code>graph untitled {\n graph[bgcolor=\"transparent\"];\n node [fontname=\"Bitstream Vera Sans\", fontsize=\"22.00\", shape=circle, style=\"bold,filled\" fillcolor=white];\n edge [style=bold];\n 1;2;3;4;5;6;\n 6 -- 4 -- 5 -- 1 -- 2 -- 3 -- 4;\n 2 -- 5;\n}\n</code></pre>\n\n<p>If that code were saved into a file input.dot, the command they would have used to actually generate the graph would probably have been:</p>\n\n<pre><code>neato -Tsvg input.dot > graph.svg\n</code></pre>\n"
},
{
"answer_id": 556780,
"author": "ЯegDwight",
"author_id": 58792,
"author_profile": "https://Stackoverflow.com/users/58792",
"pm_score": 1,
"selected": false,
"text": "<p>GraphViz does a nice job for tiny graphs, but not for huge ones. If your graph is reasonlably large, try <a href=\"http://www.aisee.com/\" rel=\"nofollow noreferrer\" title=\"aiSee\">aiSee</a> or have a look at the alternatives on <a href=\"http://www.dmoz.org/Science/Math/Combinatorics/Software/Graph_Drawing/\" rel=\"nofollow noreferrer\" title=\"this list\">this list</a>.</p>\n"
},
{
"answer_id": 1781064,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 1,
"selected": false,
"text": "<p>You could use <a href=\"http://quickgraph.codeplex.com/\" rel=\"nofollow noreferrer\">QuickGraph</a> to easily model the graph programatically, then export it to <a href=\"http://quickgraph.codeplex.com/wikipage?title=Visualization%20Using%20Graphviz&referringTitle=Documentation\" rel=\"nofollow noreferrer\">GraphViz</a> or <a href=\"http://quickgraph.codeplex.com/wikipage?title=Visualization%20Using%20Glee&referringTitle=Documentation\" rel=\"nofollow noreferrer\">GLEE</a>, then render it to PNG.</p>\n"
},
{
"answer_id": 3051234,
"author": "wxs",
"author_id": 12981,
"author_profile": "https://Stackoverflow.com/users/12981",
"pm_score": 1,
"selected": false,
"text": "<p>Well, here's another answer 2 years later. Protovis now does force-directed graph layouts rendered in browser:\n<a href=\"http://vis.stanford.edu/protovis/ex/force.html\" rel=\"nofollow noreferrer\">http://vis.stanford.edu/protovis/ex/force.html</a>\nMight be easier if you can't install client-side software. Also it's fun and interactive!</p>\n"
},
{
"answer_id": 5028691,
"author": "Frodo Baggins",
"author_id": 226469,
"author_profile": "https://Stackoverflow.com/users/226469",
"pm_score": 2,
"selected": false,
"text": "<p>We produce <a href=\"http://www.jgraph.com/mxgraph.html\" rel=\"nofollow\">mxGraph</a>, which supports ASP.NET, and most other mainstream server-side technologies. It's entirely JavaScript client-side, with just a thin layer to communicate written in .NET, so there isn't much ASP.NET required. But we do supply a ASP project for visual studio as one of the examples.</p>\n"
},
{
"answer_id": 52329563,
"author": "FGRibreau",
"author_id": 745121,
"author_profile": "https://Stackoverflow.com/users/745121",
"pm_score": 0,
"selected": false,
"text": "<p><em>Disclaimer: I'm Image-Charts founder.</em></p>\n\n<p>If you are looking for an <a href=\"https://documentation.image-charts.com/graph-viz-charts/\" rel=\"nofollow noreferrer\">web API</a>:</p>\n\n<pre><code>https://image-charts.com/chart\n?cht=gv\n&chl=graph g{1;2;3;4;5;6; 6 -- 4 -- 5 -- 1 -- 2 -- 3 -- 4; 2 -- 5;)\n</code></pre>\n\n<p><img src=\"https://image-charts.com/chart?cht=gv&chl=graph%20g%20%7B1;2;3;4;5;6;%206%20--%204%20--%205%20--%201%20--%202%20--%203%20--%204;%202%20--%205;%20%7D\" alt=\"\"></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/165305/"
]
| I'm trying to draw a graph on an ASP webpage. I'm hoping an API can be helpful, but so far I have not been able to find one.
The graph contains labeled nodes and unlabeled directional edges.
The ideal output would be something like [this](http://en.wikipedia.org/wiki/Image:6n-graf.svg).
Anybody know of anything pre-built than can help? | Definitely [graphviz](http://graphviz.org). The image on the wikipedia link you are pointing at was made in graphviz. From its description page the graph description file looked like this:
```
graph untitled {
graph[bgcolor="transparent"];
node [fontname="Bitstream Vera Sans", fontsize="22.00", shape=circle, style="bold,filled" fillcolor=white];
edge [style=bold];
1;2;3;4;5;6;
6 -- 4 -- 5 -- 1 -- 2 -- 3 -- 4;
2 -- 5;
}
```
If that code were saved into a file input.dot, the command they would have used to actually generate the graph would probably have been:
```
neato -Tsvg input.dot > graph.svg
``` |
69,277 | <p>I have an Enumerable array</p>
<pre><code>int meas[] = new double[] {3, 6, 9, 12, 15, 18};
</code></pre>
<p>On each successive call to the mock's method that I'm testing I want to return a value from that array.</p>
<pre><code>using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(meas);
}
using(_mocks.Playback()) {
foreach(var i in meas)
Assert.AreEqual(i, mocked_class.GetValue();
}
</code></pre>
<p>Does anyone have an idea how I can do this?</p>
| [
{
"answer_id": 69382,
"author": "vrdhn",
"author_id": 414441,
"author_profile": "https://Stackoverflow.com/users/414441",
"pm_score": 0,
"selected": false,
"text": "<p>IMHO, yield will handle this.\n<a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0%28VS.80%29.aspx\" rel=\"nofollow noreferrer\">Link</a>.</p>\n\n<p>Something like:</p>\n\n<pre><code>get_next() {\n foreach( float x in meas ) {\n yield x;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69426,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>Any reason why you must have a mock here...<br>\nIf not, I would go for a fake class.. Much Simpler and I know how to get it to do this :) \nI don't know if mock frameworks provide this kind of custom behavior.</p>\n"
},
{
"answer_id": 69642,
"author": "Darren",
"author_id": 6065,
"author_profile": "https://Stackoverflow.com/users/6065",
"pm_score": 1,
"selected": false,
"text": "<p>If the functionality is the GetValue() returns each array element in succession then you should be able to set up multiple expectations eg</p>\n\n<pre><code>using(_mocks.Record()) {\n Expect.Call(mocked_class.GetValue()).Return(3); \n Expect.Call(mocked_class.GetValue()).Return(6); \n Expect.Call(mocked_class.GetValue()).Return(9); \n Expect.Call(mocked_class.GetValue()).Return(12); \n Expect.Call(mocked_class.GetValue()).Return(15); \n Expect.Call(mocked_class.GetValue()).Return(18); \n}\nusing(_mocks.Playback()) {\n foreach(var i in meas)\n Assert.AreEqual(i, mocked_class.GetValue(); \n}\n</code></pre>\n\n<p>The mock repository will apply the expectations in order.</p>\n"
},
{
"answer_id": 69985,
"author": "bahadorn",
"author_id": 6476,
"author_profile": "https://Stackoverflow.com/users/6476",
"pm_score": 3,
"selected": true,
"text": "<p>There is alway static fake object, but this question is about rhino-mocks, so I present you with the way I'll do it.\nThe trick is that you create a local variable as the counter, and use it in your anonymous delegate/lambda to keep track of where you are on the array. Notice that I didn't handle the case that GetValue() is called more than 6 times.</p>\n\n<pre><code>var meas = new int[] { 3, 6, 9, 12, 15, 18 };\nusing (mocks.Record())\n{\n int forMockMethod = 0;\n SetupResult.For(mocked_class.GetValue()).Do(\n new Func<int>(() => meas[forMockMethod++])\n );\n}\n\nusing(mocks.Playback())\n{\n foreach (var i in meas)\n Assert.AreEqual(i, mocked_class.GetValue());\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69277",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| I have an Enumerable array
```
int meas[] = new double[] {3, 6, 9, 12, 15, 18};
```
On each successive call to the mock's method that I'm testing I want to return a value from that array.
```
using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(meas);
}
using(_mocks.Playback()) {
foreach(var i in meas)
Assert.AreEqual(i, mocked_class.GetValue();
}
```
Does anyone have an idea how I can do this? | There is alway static fake object, but this question is about rhino-mocks, so I present you with the way I'll do it.
The trick is that you create a local variable as the counter, and use it in your anonymous delegate/lambda to keep track of where you are on the array. Notice that I didn't handle the case that GetValue() is called more than 6 times.
```
var meas = new int[] { 3, 6, 9, 12, 15, 18 };
using (mocks.Record())
{
int forMockMethod = 0;
SetupResult.For(mocked_class.GetValue()).Do(
new Func<int>(() => meas[forMockMethod++])
);
}
using(mocks.Playback())
{
foreach (var i in meas)
Assert.AreEqual(i, mocked_class.GetValue());
}
``` |
69,296 | <p>I have a a property defined as:</p>
<pre><code>[XmlArray("delete", IsNullable = true)]
[XmlArrayItem("contact", typeof(ContactEvent)),
XmlArrayItem("sms", typeof(SmsEvent))]
public List<Event> Delete { get; set; }
</code></pre>
<p>If the List<> Delete has no items</p>
<pre><code><delete />
</code></pre>
<p>is emitted. If the List<> Delete is set to null</p>
<pre><code><delete xsi:nil="true" />
</code></pre>
<p>is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?</p>
<p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69407">Greg</a> - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.</p>
<p><a href="https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69518">Rob Cooper</a> - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization.</p>
| [
{
"answer_id": 69315,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": 0,
"selected": false,
"text": "<p>You could always implement IXmlSerializer and perform the serialization manually.</p>\n\n<p>See <a href=\"http://www.codeproject.com/KB/cs/IXmlSerializable.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/IXmlSerializable.aspx</a> for an example.</p>\n"
},
{
"answer_id": 69407,
"author": "GregK",
"author_id": 8653,
"author_profile": "https://Stackoverflow.com/users/8653",
"pm_score": 4,
"selected": true,
"text": "<p>If you set IsNullable=false or just remove it (it is false by default), then the \"delete\" element will not be emitted. This will work only if the collection equals to null.</p>\n\n<p>My guess is that there is a confusion between \"nullability\" in terms of .NET, and the one related to nullable elements in XML -- those that are marked by xml:nil attribute. XmlArrayAttribute.IsNullable property controls the latter.</p>\n"
},
{
"answer_id": 69518,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "<p>First off, I would say ask yourself \"<strong>What is Serialization?</strong>\".</p>\n\n<p>The <em>XmlSerializer</em> is doing exactly what it is supposed to be doing, persisting the current state of the object to XML. Now, I am not sure why the current behaviour is not \"right\" for you, since if you have initialized the List, then it <em>is</em> initialized.</p>\n\n<p>I think you have three options here:</p>\n\n<ol>\n<li>Add code to the Getter to return null if the collection has 0 items. This may mess up other code you have though.</li>\n<li>Implement the <em>IXmlSerializable</em> interface and do all the work yourself.</li>\n<li>If this is a common process, then you may want to look at my question \"<a href=\"https://stackoverflow.com/questions/20084/xml-serialization-and-inherited-types\">XML Serialization and Inherited Types</a>\" - Yes, I know it deals with another issue, but it shows you how to create a generic intermediary serialization class that can then be \"bolted on\" to allow a serilization process to be encapsulated. You could create a similar class to deal with overriding the default process for null/zero-item collections.</li>\n</ol>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 811038,
"author": "theahuramazda",
"author_id": 99290,
"author_profile": "https://Stackoverflow.com/users/99290",
"pm_score": 4,
"selected": false,
"text": "<p>I've had the same issue where I did not want an element outputted if the field is empty or 0.\nThe XML outputted could not use xsi:null=\"true\" (by design).</p>\n\n<p>I've read somewhere that if you include a property of type bool with the same name as the field you want to control but appended with 'Specified', the XMLSerializer will check the return value of this property to determine if the corresponding field should be included.</p>\n\n<p>To achieve this without implementing IXMLSerializer:</p>\n\n<pre><code>public List<Event> Delete { get; set; }\n[XMLIgnore]\npublic bool DeleteSpecified\n{\n get\n {\n bool isRendered = false;\n if (Delete != null)\n {\n isRendered = (Delete.Count > 0);\n } \n\n return isRendered;\n }\n set\n {\n }\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2281/"
]
| I have a a property defined as:
```
[XmlArray("delete", IsNullable = true)]
[XmlArrayItem("contact", typeof(ContactEvent)),
XmlArrayItem("sms", typeof(SmsEvent))]
public List<Event> Delete { get; set; }
```
If the List<> Delete has no items
```
<delete />
```
is emitted. If the List<> Delete is set to null
```
<delete xsi:nil="true" />
```
is emitted. Is there a way using attributes to get the delete element not to be emitted if the collection has no items?
[Greg](https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69407) - Perfect thanks, I didn't even read the IsNullable documentation just assumed it was signalling it as not required.
[Rob Cooper](https://stackoverflow.com/questions/69296/xml-serialization-and-empty-collections#69518) - I was trying to avoid ISerializable, but Gregs suggestion works. I did run into the problem you outlined in (1), I broke a bunch of code by just returning null if the collection was zero length. To get around this I created a EventsBuilder class (the class I am serializing is called Events) that managed all the lifetime/creation of the underlying objects of the Events class that spits our Events classes for serialization. | If you set IsNullable=false or just remove it (it is false by default), then the "delete" element will not be emitted. This will work only if the collection equals to null.
My guess is that there is a confusion between "nullability" in terms of .NET, and the one related to nullable elements in XML -- those that are marked by xml:nil attribute. XmlArrayAttribute.IsNullable property controls the latter. |
69,352 | <p>What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form.</p>
| [
{
"answer_id": 69359,
"author": "JP Richardson",
"author_id": 10333,
"author_profile": "https://Stackoverflow.com/users/10333",
"pm_score": 5,
"selected": false,
"text": "<pre><code>FormName.WindowState = FormWindowState.Minimized;\n</code></pre>\n"
},
{
"answer_id": 69362,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": 4,
"selected": false,
"text": "<pre><code><form>.WindowState = FormWindowState.Minimized;\n</code></pre>\n"
},
{
"answer_id": 69363,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Form myForm;\nmyForm.WindowState = FormWindowState.Minimized;\n</code></pre>\n"
},
{
"answer_id": 69372,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": true,
"text": "<pre><code>private void Form1_KeyPress(object sender, KeyPressEventArgs e)\n{\n if(e.KeyChar == 'm')\n this.WindowState = FormWindowState.Minimized;\n}\n</code></pre>\n"
},
{
"answer_id": 362666,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>in c#.net</p>\n\n<pre><code>this.WindowState = FormWindowState.Minimized\n</code></pre>\n"
},
{
"answer_id": 10916569,
"author": "profnotime",
"author_id": 1286381,
"author_profile": "https://Stackoverflow.com/users/1286381",
"pm_score": 2,
"selected": false,
"text": "<p>There's no point minimizing an already minimized form. So here we go:</p>\n\n<pre><code>if (form_Name.WindowState != FormWindowState.Minimized) form_Name.WindowState = FormWindowState.Minimized;\n</code></pre>\n"
},
{
"answer_id": 19263211,
"author": "Tech Initiator",
"author_id": 2861211,
"author_profile": "https://Stackoverflow.com/users/2861211",
"pm_score": -1,
"selected": false,
"text": "<pre><code>this.MdiParent.WindowState = FormWindowState.Minimized;\n</code></pre>\n"
},
{
"answer_id": 23004359,
"author": "GoroundoVipa",
"author_id": 3471643,
"author_profile": "https://Stackoverflow.com/users/3471643",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click\n\nMe.Hide()\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 56264532,
"author": "Thailor Souza",
"author_id": 11433219,
"author_profile": "https://Stackoverflow.com/users/11433219",
"pm_score": 0,
"selected": false,
"text": "<p>-- c#.net</p>\n\n<p>NORMALIZE\n this.WindowState = FormWindowState.Normal;</p>\n\n<p>this.WindowState = FormWindowState.Minimized;</p>\n"
},
{
"answer_id": 56512081,
"author": "Abdul Moiz",
"author_id": 11519549,
"author_profile": "https://Stackoverflow.com/users/11519549",
"pm_score": 0,
"selected": false,
"text": "<p><code>this.WindowState = FormWindowState.Minimized;</code></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7516/"
]
| What I'm doing is I have a full-screen form, with no title bar, and consequently lacks the minimize/maximize/close buttons found in the upper-right hand corner. I'm wanting to replace that functionality with a keyboard short-cut and a context menu item, but I can't seem to find an event to trigger to minimize the form. | ```
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
if(e.KeyChar == 'm')
this.WindowState = FormWindowState.Minimized;
}
``` |
69,391 | <p>In OS X, in order to quickly get at menu items from the keyboard, I want to be able to type a key combination, have it run a script, and have the script focus the Search field in the Help menu. It should work just like the key combination for Spotlight, so if I run it again, it should dismiss the menu. I can run the script with Quicksilver, but how can I write the script?</p>
| [
{
"answer_id": 69393,
"author": "easeout",
"author_id": 10906,
"author_profile": "https://Stackoverflow.com/users/10906",
"pm_score": 2,
"selected": true,
"text": "<p>Here is the script I came up with.</p>\n\n<pre><code>tell application \"System Events\"\n tell (first process whose frontmost is true)\n click menu \"Help\" of menu bar 1\n end tell\nend tell\n</code></pre>\n"
},
{
"answer_id": 90610,
"author": "Ken",
"author_id": 17320,
"author_profile": "https://Stackoverflow.com/users/17320",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively, hit cmd-? and don't mess with the script. :-) That puts key focus in the help menu's search field.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10906/"
]
| In OS X, in order to quickly get at menu items from the keyboard, I want to be able to type a key combination, have it run a script, and have the script focus the Search field in the Help menu. It should work just like the key combination for Spotlight, so if I run it again, it should dismiss the menu. I can run the script with Quicksilver, but how can I write the script? | Here is the script I came up with.
```
tell application "System Events"
tell (first process whose frontmost is true)
click menu "Help" of menu bar 1
end tell
end tell
``` |
69,398 | <p>i have scenario where i have to provide my own control template for a few WPF controls - i.e. GridViewHeader. when you take a look at control template for GridViewHEader in blend, it is agregated from several other controls, which in some cases are styled for that control only - i.e. this splitter between columns.
those templates, obviously are resources hidden somewhere in system...dll (or somewhwere in themes dll's).
so, my question is - is there a way to reference those predefined templates? so far, i've ended up having my own copies of them in my resources, but i don't like that approach.</p>
<p>here is sample scenario:
i have a GridViewColumnHeader:</p>
<pre><code> <Style TargetType="{x:Type GridViewColumnHeader}" x:Key="gridViewColumnStyle">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Background" Value="{StaticResource GridViewHeaderBackgroundColor}"/>
<Setter Property="BorderBrush" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="2,0,2,0"/>
<Setter Property="Foreground" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Grid SnapsToDevicePixels="true" Tag="Header" Name="Header">
<ContentPresenter Name="HeaderContent" Margin="0,0,0,1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<Canvas>
<Thumb x:Name="PART_HeaderGripper" Style="{StaticResource GridViewColumnHeaderGripper}"/>
</Canvas>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="HeaderContent" Property="Margin" Value="1,1,0,0"/>
</Trigger>
<Trigger Property="Height" Value="Auto">
<Setter Property="MinHeight" Value="20"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>so far - nothing interesting, but say, i want to add some extra functionality straight in the template - i'd leave cotnent presenter as is, add my controls next to it and i'd like to leave Thumb with defaults from framework. i've found themes provided by microsoft <a href="http://msdn.microsoft.com/en-us/library/aa358533.aspx" rel="nofollow noreferrer">here</a>:</p>
<p>the theme for Thumb looks like that:</p>
<pre><code><Style x:Key="GridViewColumnHeaderGripper"
TargetType="{x:Type Thumb}">
<Setter Property="Canvas.Right"
Value="-9"/>
<Setter Property="Width"
Value="18"/>
<Setter Property="Height"
Value="{Binding Path=ActualHeight,RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter Property="Padding"
Value="0"/>
<Setter Property="Background"
Value="{StaticResource GridViewColumnHeaderBorderBackground}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Padding="{TemplateBinding Padding}"
Background="Transparent">
<Rectangle HorizontalAlignment="Center"
Width="1"
Fill="{TemplateBinding Background}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</code></pre>
<p>so far - i have to copy & paste that style, while i'd prefer to get reference to it from resources.</p>
| [
{
"answer_id": 69427,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 2,
"selected": false,
"text": "<p>Referencing internal resources that are 100% subject to change isn't serviceable - better to just copy it. </p>\n"
},
{
"answer_id": 71725,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 0,
"selected": false,
"text": "<p>It is possible to reference them, but as paulbetts said, its not recommended as they could change. Also consider if what you are doing is truely 'correct'. Can you edit your question to explain why you need to do this exactly?</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11013/"
]
| i have scenario where i have to provide my own control template for a few WPF controls - i.e. GridViewHeader. when you take a look at control template for GridViewHEader in blend, it is agregated from several other controls, which in some cases are styled for that control only - i.e. this splitter between columns.
those templates, obviously are resources hidden somewhere in system...dll (or somewhwere in themes dll's).
so, my question is - is there a way to reference those predefined templates? so far, i've ended up having my own copies of them in my resources, but i don't like that approach.
here is sample scenario:
i have a GridViewColumnHeader:
```
<Style TargetType="{x:Type GridViewColumnHeader}" x:Key="gridViewColumnStyle">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="Background" Value="{StaticResource GridViewHeaderBackgroundColor}"/>
<Setter Property="BorderBrush" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="2,0,2,0"/>
<Setter Property="Foreground" Value="{StaticResource GridViewHeaderForegroundColor}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
<Grid SnapsToDevicePixels="true" Tag="Header" Name="Header">
<ContentPresenter Name="HeaderContent" Margin="0,0,0,1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
<Canvas>
<Thumb x:Name="PART_HeaderGripper" Style="{StaticResource GridViewColumnHeaderGripper}"/>
</Canvas>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="HeaderContent" Property="Margin" Value="1,1,0,0"/>
</Trigger>
<Trigger Property="Height" Value="Auto">
<Setter Property="MinHeight" Value="20"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
so far - nothing interesting, but say, i want to add some extra functionality straight in the template - i'd leave cotnent presenter as is, add my controls next to it and i'd like to leave Thumb with defaults from framework. i've found themes provided by microsoft [here](http://msdn.microsoft.com/en-us/library/aa358533.aspx):
the theme for Thumb looks like that:
```
<Style x:Key="GridViewColumnHeaderGripper"
TargetType="{x:Type Thumb}">
<Setter Property="Canvas.Right"
Value="-9"/>
<Setter Property="Width"
Value="18"/>
<Setter Property="Height"
Value="{Binding Path=ActualHeight,RelativeSource={RelativeSource TemplatedParent}}"/>
<Setter Property="Padding"
Value="0"/>
<Setter Property="Background"
Value="{StaticResource GridViewColumnHeaderBorderBackground}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Thumb}">
<Border Padding="{TemplateBinding Padding}"
Background="Transparent">
<Rectangle HorizontalAlignment="Center"
Width="1"
Fill="{TemplateBinding Background}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
```
so far - i have to copy & paste that style, while i'd prefer to get reference to it from resources. | Referencing internal resources that are 100% subject to change isn't serviceable - better to just copy it. |
69,411 | <p>What is the best way to copy a directory (with sub-dirs and files) from one remote Linux server to another remote Linux server? I have connected to both using SSH client (like Putty). I have root access to both. </p>
| [
{
"answer_id": 69418,
"author": "Ana Betts",
"author_id": 5728,
"author_profile": "https://Stackoverflow.com/users/5728",
"pm_score": 3,
"selected": false,
"text": "<p>rsync -avlzp /path/to/folder [email protected]:/path/to/remote/folder</p>\n"
},
{
"answer_id": 69419,
"author": "John Douthat",
"author_id": 2774,
"author_profile": "https://Stackoverflow.com/users/2774",
"pm_score": 2,
"selected": false,
"text": "<p>Check out <a href=\"https://en.wikipedia.org/wiki/Secure_copy\" rel=\"nofollow noreferrer\">scp</a> or <a href=\"https://en.wikipedia.org/wiki/Rsync\" rel=\"nofollow noreferrer\">rsync</a>, \n<code>man scp</code>\n<code>man rsync</code></p>\n\n<pre><code>scp file1 file2 dir3 user@remotehost:path\n</code></pre>\n"
},
{
"answer_id": 69420,
"author": "Ady Romantika",
"author_id": 67775,
"author_profile": "https://Stackoverflow.com/users/67775",
"pm_score": 2,
"selected": false,
"text": "<p>Use rsync so that you can continue if the connection gets broken. And if something changes you can copy them much faster too!</p>\n\n<p>Rsync works with SSH so your copy operation is secure.</p>\n"
},
{
"answer_id": 69421,
"author": "Serafina Brocious",
"author_id": 4977,
"author_profile": "https://Stackoverflow.com/users/4977",
"pm_score": 3,
"selected": false,
"text": "<pre><code>scp -r <directory> <username>@<targethost>:<targetdir>\n</code></pre>\n"
},
{
"answer_id": 69422,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 1,
"selected": false,
"text": "<p>Well, quick answer would to take a look at the 'scp' manpage, or perhaps rsync - depending exactly on what you need to copy. If you had to, you could even do tar-over-ssh:</p>\n\n<pre><code>tar cvf - | ssh server tar xf -\n</code></pre>\n"
},
{
"answer_id": 69423,
"author": "Flame",
"author_id": 5387,
"author_profile": "https://Stackoverflow.com/users/5387",
"pm_score": 3,
"selected": false,
"text": "<p>Log in to one machine</p>\n\n<blockquote>\n <p>$ scp -r /path/to/top/directory user@server:/path/to/copy</p>\n</blockquote>\n"
},
{
"answer_id": 69424,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 0,
"selected": false,
"text": "<p>As non-root user ideally:</p>\n\n<p>scp -r src $host:$path</p>\n\n<p>If you already some of the content on $host consider using rsync with ssh as a tunnel.</p>\n\n<p>/Allan</p>\n"
},
{
"answer_id": 69433,
"author": "Ycros",
"author_id": 10495,
"author_profile": "https://Stackoverflow.com/users/10495",
"pm_score": 6,
"selected": false,
"text": "<p>There are two ways I usually do this, both use ssh:</p>\n\n<pre><code>scp -r sourcedir/ [email protected]:/dest/dir/\n</code></pre>\n\n<p>or, the more robust and faster (in terms of transfer speed) method:</p>\n\n<pre><code>rsync -auv -e ssh --progress sourcedir/ [email protected]:/dest/dir/\n</code></pre>\n\n<p>Read the man pages for each command if you want more details about how they work.</p>\n"
},
{
"answer_id": 69566,
"author": "user11104",
"author_id": 11104,
"author_profile": "https://Stackoverflow.com/users/11104",
"pm_score": 2,
"selected": false,
"text": "<p>Try unison if the task is recurring.\n<a href=\"http://www.cis.upenn.edu/~bcpierce/unison/\" rel=\"nofollow noreferrer\">http://www.cis.upenn.edu/~bcpierce/unison/</a></p>\n"
},
{
"answer_id": 74328,
"author": "Ram Prasad",
"author_id": 6361,
"author_profile": "https://Stackoverflow.com/users/6361",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can try with:</p>\n\n<pre><code>rsync -azvu -e ssh user@host1:/directory/ user@host2:/directory2/\n</code></pre>\n\n<p>(and I assume you are on host0 and you want to copy from host1 to host2 directly)</p>\n\n<p>If the above does not work, you could try:</p>\n\n<pre><code>ssh user@host1 \"/usr/bin/rsync -azvu -e ssh /directory/ user@host2:/directory2/\"\n</code></pre>\n\n<p>in the this, it would work, if you already have setup passwordless SSH login from host1 to host2</p>\n"
},
{
"answer_id": 82302,
"author": "Gunstick",
"author_id": 15653,
"author_profile": "https://Stackoverflow.com/users/15653",
"pm_score": 2,
"selected": false,
"text": "<p>I used rdiffbackup <a href=\"http://www.nongnu.org/rdiff-backup/index.html\" rel=\"nofollow noreferrer\">http://www.nongnu.org/rdiff-backup/index.html</a> because it does all you need without any fancy options. It's based on the rsync algorithm.\nIf you only need to copy one time, you can later remove the rdiff-backup-data directory on the destination host.</p>\n\n<pre><code>rdiff-backup user1@host1::/source-dir user2@host2::/dest-dir\n</code></pre>\n\n<p>from the doc:</p>\n\n<blockquote>\n <p>rdiff-backup also preserves \n subdirectories, hard links, dev files,\n permissions, uid/gid ownership, \n modification times, extended\n attributes, acls, and resource forks.</p>\n</blockquote>\n\n<p>which is an bonus to the scp -p proposals as the -p option does not preserve all (e.g. rights on directories are set badly)</p>\n\n<p>install on ubuntu:</p>\n\n<pre><code>sudo apt-get install rdiff-backup\n</code></pre>\n"
},
{
"answer_id": 82493,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you are serious about wanting an exact copy, you probably also want to use the -p switch to scp, if you're using that. I've found that scp <strong>reads from devices</strong>, and I've had problems with cpio, so I personally always use <em>tar</em>, like this:</p>\n\n<pre><code>cd /origin; find . -xdev -depth -not -path ./lost+found -print0 \\\n| tar --create --atime-preserve=system --null --files-from=- --format=posix \\\n--no-recursion --sparse | ssh targethost 'cd /target; tar --extract \\\n--overwrite --preserve-permissions --sparse'\n</code></pre>\n\n<p>I keep this incantation around in a file with various other means of copying files around. This one is for copying over SSH; the other ones are for copying to a compressed archive, for copying within the same computer, and for copying over an unencrypted TCP socket when SSH is too slow.</p>\n"
},
{
"answer_id": 83539,
"author": "Sergey Stolyarov",
"author_id": 15958,
"author_profile": "https://Stackoverflow.com/users/15958",
"pm_score": 0,
"selected": false,
"text": "<p>scp as mentioned above is usually a best way, but don't forget colon in the remote directory spec otherwise you'll get copy of source directory on local machine.</p>\n"
},
{
"answer_id": 102494,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I like to pipe tar through ssh. </p>\n\n<p>tar cf - [directory] | ssh [username]@[hostname] tar xf - -C [destination on remote box]</p>\n\n<p>This method gives you lots of options. Since you should have root ssh disabled copying files for multiple user accounts is hard since you are logging into the remote server as a normal user. To get around this you can create a tar file on the remote box that still hold that preserves ownership.</p>\n\n<p>tar cf - [directory] | ssh [username]@[hostname] \"cat > output.tar\"</p>\n\n<p>For slow connections you can add compression, z for gzip or j for bzip2.</p>\n\n<p>tar cjf - [directory] | ssh [username]@[hostname] \"cat > output.tar.bz2\"</p>\n\n<p>tar czf - [directory] | ssh [username]@[hostname] \"cat > output.tar.gz\"</p>\n\n<p>tar czf - [directory] | ssh [username]@[hostname] tar xzf - -C [destination on remote box]</p>\n"
},
{
"answer_id": 104727,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>scp will do the job, but there is one wrinkle: the connection to the second remote destination will use the configuration on the first remote destination, so if you use .ssh/config on the local environment, and you expect rsa and dsa keys to work, you have to forward your agent to the first remote host.</p>\n"
},
{
"answer_id": 104897,
"author": "user19218",
"author_id": 19218,
"author_profile": "https://Stackoverflow.com/users/19218",
"pm_score": 5,
"selected": false,
"text": "<p>I would modify a previously suggested reply:</p>\n\n<pre><code>rsync -avlzp /path/to/sfolder [email protected]:/path/to/remote/dfolder\n</code></pre>\n\n<p>as follows:</p>\n\n<p>-a (for archive) implies -rlptgoD so the l and p above are superfluous. I also like to include -H, which copies hard links. It is not part of -a by default because it's expensive. So now we have this:</p>\n\n<pre><code>rsync -aHvz /path/to/sfolder [email protected]:/path/to/remote/dfolder\n</code></pre>\n\n<p>You also have to be careful about trailing slashes. You probably want</p>\n\n<pre><code>rsync -aHvz /path/to/sfolder/ [email protected]:/path/to/remote/dfolder\n</code></pre>\n\n<p>if the desire is for the contents of the source \"sfolder\" to appear in the destination \"dfolder\". Without the trailing slash, an \"sfolder\" subdirectory would be created in the destination \"dfolder\".</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69411",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| What is the best way to copy a directory (with sub-dirs and files) from one remote Linux server to another remote Linux server? I have connected to both using SSH client (like Putty). I have root access to both. | There are two ways I usually do this, both use ssh:
```
scp -r sourcedir/ [email protected]:/dest/dir/
```
or, the more robust and faster (in terms of transfer speed) method:
```
rsync -auv -e ssh --progress sourcedir/ [email protected]:/dest/dir/
```
Read the man pages for each command if you want more details about how they work. |
69,430 | <p>I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.</p>
<p>I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers.</p>
| [
{
"answer_id": 69474,
"author": "Dave Rutledge",
"author_id": 2486915,
"author_profile": "https://Stackoverflow.com/users/2486915",
"pm_score": 3,
"selected": false,
"text": "<p>Absolutely position divs over the text area with a z-index higher and give these divs a transparent <a href=\"http://en.wikipedia.org/wiki/Graphics_Interchange_Format\" rel=\"nofollow noreferrer\">GIF</a> background graphic.</p>\n\n<p>Note after a bit more thought - You'd need to have these 'covers' be linked so clicking on them would take you to where the tab was supposed to, which means you could/should do this with the anchor element set to <code>display:box</code>, width and height set as well as the transparent background image.</p>\n"
},
{
"answer_id": 69476,
"author": "Kinjal Dixit",
"author_id": 6629,
"author_profile": "https://Stackoverflow.com/users/6629",
"pm_score": 1,
"selected": false,
"text": "<p>Images can be selected too.</p>\n\n<p>There are limits to using JavaScript to deselect text, as it might happen even in places where you want to select. To ensure a rich and successful career, steer clear of all requirements that need ability to influence or manage the browser beyond the ordinary... unless, of course, they are paying you extremely well.</p>\n"
},
{
"answer_id": 69486,
"author": "Jorge Alves",
"author_id": 6195,
"author_profile": "https://Stackoverflow.com/users/6195",
"pm_score": 4,
"selected": false,
"text": "<p>For Firefox you can apply the CSS declaration \"-moz-user-select\" to \"none\".\nCheck out their documentation, <em><a href=\"http://developer.mozilla.org/En/CSS/-moz-user-select\" rel=\"nofollow noreferrer\">user-select</a></em>.</p>\n\n<p>It's a \"preview\" of the future \"user-select\" as they say, so maybe <a href=\"http://en.wikipedia.org/wiki/Opera_%28web_browser%29\" rel=\"nofollow noreferrer\">Opera</a> or <a href=\"http://en.wikipedia.org/wiki/WebKit\" rel=\"nofollow noreferrer\">WebKit</a>-based browsers will support that. I also recall finding something for Internet Explorer, but I don't remember what :).</p>\n\n<p>Anyway, unless it's a specific situation where text-selecting makes some dynamic functionality fail, you shouldn't really override what users are expecting from a webpage, and that is being able to select any text they want.</p>\n"
},
{
"answer_id": 69494,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 5,
"selected": false,
"text": "<pre><code><script type=\"text/javascript\">\n\n/***********************************************\n* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)\n* This notice MUST stay intact for legal use\n* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code\n\n***********************************************/\n\n\nfunction disableSelection(target){\n\n if (typeof target.onselectstart!=\"undefined\") //IE route\n target.onselectstart=function(){return false}\n\n else if (typeof target.style.MozUserSelect!=\"undefined\") //Firefox route\n target.style.MozUserSelect=\"none\"\n\n else //All other route (ie: Opera)\n target.onmousedown=function(){return false}\n\n target.style.cursor = \"default\"\n}\n\n\n\n//Sample usages\n//disableSelection(document.body) //Disable text selection on entire body\n//disableSelection(document.getElementById(\"mydiv\")) //Disable text selection on element with id=\"mydiv\"\n\n\n</script>\n</code></pre>\n\n<p><strong>EDIT</strong></p>\n\n<p>Code apparently comes from <a href=\"http://www.dynamicdrive.com\" rel=\"noreferrer\">http://www.dynamicdrive.com</a></p>\n"
},
{
"answer_id": 69500,
"author": "Stephen M. Redd",
"author_id": 10115,
"author_profile": "https://Stackoverflow.com/users/10115",
"pm_score": 4,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code><div onselectstart=\"return false\">some stuff</div>\n</code></pre>\n\n<p>Simple, but effective... works in current versions of all major browsers.</p>\n"
},
{
"answer_id": 69671,
"author": "Wedge",
"author_id": 332,
"author_profile": "https://Stackoverflow.com/users/332",
"pm_score": 1,
"selected": false,
"text": "<p>If it looks bad you can use CSS to change the appearance of selected sections.</p>\n"
},
{
"answer_id": 72244,
"author": "pdc",
"author_id": 8925,
"author_profile": "https://Stackoverflow.com/users/8925",
"pm_score": 2,
"selected": false,
"text": "<p>For an example of why it might be desirable to suppress selection, see <a href=\"http://simile.mit.edu/timeline/\" rel=\"nofollow noreferrer\">SIMILE TImeline</a>, which uses drag-and-drop to explore the timeline, during which accidental vertical mouse movement causes the labels to be highlighted unexpectedly, which looks weird.</p>\n"
},
{
"answer_id": 541719,
"author": "jlleblanc",
"author_id": 586,
"author_profile": "https://Stackoverflow.com/users/586",
"pm_score": 3,
"selected": false,
"text": "<p>I'm finding some level of success with the CSS described here <a href=\"http://www.quirksmode.org/css/selection.html\" rel=\"nofollow noreferrer\">http://www.quirksmode.org/css/selection.html</a>:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>::selection {\n background-color: transparent;\n}\n</code></pre>\n\n<p>It took care of most of the issues I was having with some ThemeRoller <code>ul</code> elements in an AIR application (WebKit engine). Still getting a small (approx. 15 x 15) patch of nothingness that gets selected, but half the page was being selected before.</p>\n"
},
{
"answer_id": 668706,
"author": "Alan Hensel",
"author_id": 14532,
"author_profile": "https://Stackoverflow.com/users/14532",
"pm_score": 2,
"selected": false,
"text": "<p>For Safari, <code>-khtml-user-select: none</code>, just like Mozilla's <code>-moz-user-select</code> (or, in JavaScript, <code>target.style.KhtmlUserSelect=\"none\";</code>).</p>\n"
},
{
"answer_id": 3320442,
"author": "hbtdev",
"author_id": 400478,
"author_profile": "https://Stackoverflow.com/users/400478",
"pm_score": 0,
"selected": false,
"text": "<p>The following works in Firefox interestingly enough if I remove the write line it doesn't work.\nAnyone have any insight why the write line is needed.</p>\n\n<pre><code><script type=\"text/javascript\">\ndocument.write(\".\");\ndocument.body.style.MozUserSelect='none';\n</script>\n</code></pre>\n"
},
{
"answer_id": 3320495,
"author": "Taylor D. Edmiston",
"author_id": 149428,
"author_profile": "https://Stackoverflow.com/users/149428",
"pm_score": 1,
"selected": false,
"text": "<p>Any JavaScript or CSS method is easily circumvented with Firebug (like Flickr's case).</p>\n\n<p>You can use the <a href=\"http://www.quirksmode.org/css/selection.html\" rel=\"nofollow noreferrer\"><code>::selection</code> pseudo-element</a> in CSS to alter the highlight color.</p>\n\n<p>If the tabs are links and the <a href=\"https://stackoverflow.com/questions/71074/how-to-remove-firefoxs-dotted-outline-on-buttons-as-well-as-links\">dotted rectangle in active state</a> is of concern, you can remove that too (consider usability of course).</p>\n"
},
{
"answer_id": 4448972,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 9,
"selected": true,
"text": "<p>In most browsers, this can be achieved using CSS:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>*.unselectable {\n -moz-user-select: -moz-none;\n -khtml-user-select: none;\n -webkit-user-select: none;\n\n /*\n Introduced in IE 10.\n See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/\n */\n -ms-user-select: none;\n user-select: none;\n}\n</code></pre>\n\n<p>For IE < 10 and Opera, you will need to use the <code>unselectable</code> attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:</p>\n\n<pre><code><div id=\"foo\" unselectable=\"on\" class=\"unselectable\">...</div>\n</code></pre>\n\n<p>Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <code><div></code>. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:</p>\n\n<pre><code>function makeUnselectable(node) {\n if (node.nodeType == 1) {\n node.setAttribute(\"unselectable\", \"on\");\n }\n var child = node.firstChild;\n while (child) {\n makeUnselectable(child);\n child = child.nextSibling;\n }\n}\n\nmakeUnselectable(document.getElementById(\"foo\"));\n</code></pre>\n"
},
{
"answer_id": 6382503,
"author": "Blowsie",
"author_id": 370286,
"author_profile": "https://Stackoverflow.com/users/370286",
"pm_score": 5,
"selected": false,
"text": "<p>All of the correct CSS variations are:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>-webkit-touch-callout: none;\n-webkit-user-select: none;\n-khtml-user-select: none;\n-moz-user-select: none;\n-ms-user-select: none;\nuser-select: none;\n</code></pre>\n"
},
{
"answer_id": 6805102,
"author": "Big Bill",
"author_id": 859966,
"author_profile": "https://Stackoverflow.com/users/859966",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>\"If your content is really interesting, then there is little you can\n ultimately do to protect it\"</p>\n</blockquote>\n\n<p>That's true, but most copying, in my experience, has nothing to do with \"ultimately\" or geeks or determined plagiarists or anything like that. It's usually casual copying by clueless people, and even a simple, easily defeated protection (easily defeated by folks like us, that is) works quite well to stop them. They don't know anything about \"view source\" or caches or anything else... heck, they don't even know what a web browser is or that they're using one.</p>\n"
},
{
"answer_id": 8219833,
"author": "kbcom",
"author_id": 1058758,
"author_profile": "https://Stackoverflow.com/users/1058758",
"pm_score": 1,
"selected": false,
"text": "<p>There are many occasions when turning off selectability enhances the user experience.</p>\n\n<p>For instance allowing the user to copy a block of text on the page without copying the text of any interface elements associated with it (that would become interspersed within the text being copied).</p>\n"
},
{
"answer_id": 12577113,
"author": "rgb",
"author_id": 738957,
"author_profile": "https://Stackoverflow.com/users/738957",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a <a href=\"http://en.wikipedia.org/wiki/Sass_%28stylesheet_language%29\" rel=\"nofollow\">Sass</a> mixin (scss) for those interested. <a href=\"http://en.wikipedia.org/wiki/Compass_Project\" rel=\"nofollow\">Compass</a>/CSS 3 doesn't seem to have a user-select mixin.</p>\n\n<pre><code>// @usage use within a rule\n// ex. img {@include user-select(none);}\n// @param assumed valid user-select value\n@mixin user-select($value)\n{\n & {\n -webkit-touch-callout: $value;\n -webkit-user-select: $value;\n -khtml-user-select: $value;\n -moz-user-select: $value;\n -ms-user-select: $value;\n user-select: $value;\n }\n}\n</code></pre>\n\n<p>Though Compass would do it in a more robust way, i.e. only add support for vendors you've chosen.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3561/"
]
| I'm building an HTML UI with some text elements, such as tab names, which look bad when selected. Unfortunately, it's very easy for a user to double-click a tab name, which selects it by default in many browsers.
I might be able to solve this with a JavaScript trick (I'd like to see those answers, too) -- but I'm really hoping there's something in CSS/HTML directly that works across all browsers. | In most browsers, this can be achieved using CSS:
```css
*.unselectable {
-moz-user-select: -moz-none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in IE 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
```
For IE < 10 and Opera, you will need to use the `unselectable` attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:
```
<div id="foo" unselectable="on" class="unselectable">...</div>
```
Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the `<div>`. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:
```
function makeUnselectable(node) {
if (node.nodeType == 1) {
node.setAttribute("unselectable", "on");
}
var child = node.firstChild;
while (child) {
makeUnselectable(child);
child = child.nextSibling;
}
}
makeUnselectable(document.getElementById("foo"));
``` |
69,440 | <p>I'm wondering if there's any way to write CSS specifically for Safari using only CSS. I know there has to be something out there, but I haven't found it yet.</p>
| [
{
"answer_id": 69446,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>So wait, you want to write CSS for Safari using only CSS? I think you answered your own question. Webkit has really good CSS support. If you are looking for webkit only styles, try <a href=\"http://qooxdoo.org/documentation/general/webkit_css_styles\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 69485,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 0,
"selected": false,
"text": "<p>You'd have to use JavaScript or your server to do user-agent sniffing in order to send CSS specifically to Safari/WebKit.</p>\n"
},
{
"answer_id": 70827,
"author": "Rich Adams",
"author_id": 10018,
"author_profile": "https://Stackoverflow.com/users/10018",
"pm_score": 3,
"selected": false,
"text": "<p>There are some hacks you can use in the CSS to target only Safari, such as putting a hash/pound (#) after the semi-colon, which causes Safari to ignore it. For example</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.blah { color: #fff; }\n.blah { color: #000;# }\n</code></pre>\n\n<p>In Safari the colour will be white, in everything else it will be black. </p>\n\n<p>However, you shouldn't use hacks, as it could cause problems with browsers in the future, and it may have undesired effects in older browsers. The safest way is to either use a server side language (such as PHP) which detects the browser and then serves up a different CSS file depending upon the browser the user is using, or you can use JavaScript to do the same, and switch to a different CSS file.</p>\n\n<p>The server-side language is the better option here, as not everyone has JavaScript enabled in their browser, which means they wouldn't see the correct style. Also JavaScript adds an overhead to the amount of information which needs to load before the page is properly displayed.</p>\n\n<p>Safari uses WebKit, which is very good with rendering CSS. I've never come across anything which doesn't work in Safari, but does in other modern browsers (not counting IE, which has it's own issues all together). I would suggest making sure your CSS is <a href=\"http://jigsaw.w3.org/css-validator/\" rel=\"nofollow noreferrer\">standards compliant</a>, as the issue may lie in the CSS, and not in Safari.</p>\n"
},
{
"answer_id": 71750,
"author": "Bryan M.",
"author_id": 4636,
"author_profile": "https://Stackoverflow.com/users/4636",
"pm_score": 6,
"selected": true,
"text": "<p>I think the question is valid. I agree with the other responses, but it doesn't mean it's a terrible question. I've only ever had to use a Safari CSS hack once as a temporary solution and later got rid of it. I agree that you shouldn't have to target just Safari, but no harm in knowing how to do it.</p>\n\n<p>FYI, this hack only targets Safari 3, and also targets Opera 9.</p>\n\n<pre><code>@media screen and (-webkit-min-device-pixel-ratio:0) {\n /* Safari 3.0 and Opera 9 rules here */\n}\n</code></pre>\n"
},
{
"answer_id": 71892,
"author": "Matt Farina",
"author_id": 11910,
"author_profile": "https://Stackoverflow.com/users/11910",
"pm_score": -1,
"selected": false,
"text": "<p>This really depends on what you are trying to do. Are you trying to do something special just in safari using some of the CSS3 features included or are you trying to make a site cross browser compliant?</p>\n\n<p>If you are trying to make a site cross browser compliant I'd recommend writing the site to look good in safari/firefox/opera using correct CSS and then making changes for IE using conditional CSS includes in IE. This should (hopefully) give you compatibility for the future of browsers, which are getting better at following the CSS rules, and provide cross browser compatibility. <a href=\"http://creativebits.org/webdev/ie_conditional_css\" rel=\"nofollow noreferrer\">This is an example.</a></p>\n\n<p>By using conditional stylesheets you can avoid hacks all together and target browsers.</p>\n\n<p>If you are looking to do something special in safari check out <a href=\"http://trac.webkit.org/wiki/WebDevelopers\" rel=\"nofollow noreferrer\">this</a>.</p>\n"
},
{
"answer_id": 18700779,
"author": "Kald",
"author_id": 1726044,
"author_profile": "https://Stackoverflow.com/users/1726044",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>@media screen and (-webkit-min-device-pixel-ratio:0) {}</p>\n</blockquote>\n\n<p>This seems to target webkit(including Chrome)... or is this truly Safari-only?</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8970/"
]
| I'm wondering if there's any way to write CSS specifically for Safari using only CSS. I know there has to be something out there, but I haven't found it yet. | I think the question is valid. I agree with the other responses, but it doesn't mean it's a terrible question. I've only ever had to use a Safari CSS hack once as a temporary solution and later got rid of it. I agree that you shouldn't have to target just Safari, but no harm in knowing how to do it.
FYI, this hack only targets Safari 3, and also targets Opera 9.
```
@media screen and (-webkit-min-device-pixel-ratio:0) {
/* Safari 3.0 and Opera 9 rules here */
}
``` |
69,445 | <p>I'm using the After Effects CS3 Javascript API to dynamically create and change text layers in a composition.</p>
<p>Or at least I'm trying to because I can't seem to find the right property to change to alter the actual text of the TextLayer object.</p>
| [
{
"answer_id": 69462,
"author": "dawnerd",
"author_id": 69503,
"author_profile": "https://Stackoverflow.com/users/69503",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not an expert with After Effects, but I have messed around with it. I think <a href=\"http://library.creativecow.net/articles/ebberts_dan/ae6_exp.php\" rel=\"nofollow noreferrer\">reading this</a> might help you out.</p>\n"
},
{
"answer_id": 73071,
"author": "Gareth Simpson",
"author_id": 147,
"author_profile": "https://Stackoverflow.com/users/147",
"pm_score": 3,
"selected": true,
"text": "<p>Hmm, must read docs harder next time.</p>\n\n<pre><code>var theComposition = app.project.item(1);\nvar theTextLayer = theComposition.layers[1];\ntheTextLayer.property(\"Source Text\").setValue(\"This text is from code\");\n</code></pre>\n"
},
{
"answer_id": 28845462,
"author": "Chris",
"author_id": 5073,
"author_profile": "https://Stackoverflow.com/users/5073",
"pm_score": 1,
"selected": false,
"text": "<p>This is how I'm changing the text.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var comp = app.project.item(23);\r\nvar layer = comp.layer('some_layer_name');\r\nvar textProp = layer.property(\"Source Text\");\r\nvar textDocument = textProp.value;\r\n\r\ntextDocument.text = \"This is the new text\";\r\ntextProp.setValue(textDocument);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 59913842,
"author": "Myzel394",
"author_id": 9878135,
"author_profile": "https://Stackoverflow.com/users/9878135",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a simple function for myself to change properties. Here it is:</p>\n\n<pre><code>function change_prop(prop, name, value){\n var doc = prop.value;\n\n doc[name] = value;\n prop.setValue(doc);\n\n return prop;\n}\n</code></pre>\n\n<p>Example use:</p>\n\n<pre><code>// Changing source text\nchange_prop(text_layer.property(\"Source Text\"), \"text\", \"That's the source text\");\n\n// Changing font size\nchange_prop(text_layer.property(\"ADBE Text Properties\").property(\"ADBE Text Document\"), \"fontSize\", 10)\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/147/"
]
| I'm using the After Effects CS3 Javascript API to dynamically create and change text layers in a composition.
Or at least I'm trying to because I can't seem to find the right property to change to alter the actual text of the TextLayer object. | Hmm, must read docs harder next time.
```
var theComposition = app.project.item(1);
var theTextLayer = theComposition.layers[1];
theTextLayer.property("Source Text").setValue("This text is from code");
``` |
69,470 | <p>Is there a way to get the current xml data when we make our own custom XPath function (see here).</p>
<p>I know you have access to an <code>XPathContext</code> but is this enough?</p>
<p><strong>Example:</strong></p>
<p>Our XML:</p>
<pre><code><foo>
<bar>smang</bar>
<fizz>buzz</fizz>
</foo>
</code></pre>
<p>Our XSL:</p>
<pre><code><xsl:template match="/">
<xsl:value-of select="ourFunction()" />
</xsl:template>
</code></pre>
<p>How do we get the entire XML tree?</p>
<p><strong>Edit:</strong> To clarify: I'm creating a custom function that ends up executing static Java code (it's a Saxon feature). So, in this Java code, I wish to be able to get elements from the XML tree, such as bar and fizz, and their CDATA, such as smang and buzz.</p>
| [
{
"answer_id": 69478,
"author": "Yann Ramin",
"author_id": 9167,
"author_profile": "https://Stackoverflow.com/users/9167",
"pm_score": 2,
"selected": false,
"text": "<p>There is the classic 'ab' (apachebench) program. More power comes from <a href=\"http://jakarta.apache.org/jmeter/\" rel=\"nofollow noreferrer\">JMmeter</a>. For server health, I recommend Munin, which can painlessly capture data from several systems and aggregate it on one page. </p>\n"
},
{
"answer_id": 69543,
"author": "Ryan Doherty",
"author_id": 956,
"author_profile": "https://Stackoverflow.com/users/956",
"pm_score": 1,
"selected": false,
"text": "<p>Try <a href=\"http://www.nagios.org/\" rel=\"nofollow noreferrer\">Nagios</a>, it's the default tool to monitor servers. You can write plugins to report just about any data. </p>\n"
},
{
"answer_id": 70334,
"author": "Kristian J.",
"author_id": 4588,
"author_profile": "https://Stackoverflow.com/users/4588",
"pm_score": 1,
"selected": false,
"text": "<p>For profiling your code, there's <a href=\"http://xdebug.org/docs/profiler\" rel=\"nofollow noreferrer\">Xdebug</a>. Doing regression testing with <a href=\"http://www.joedog.org/JoeDog/Siege\" rel=\"nofollow noreferrer\">Siege</a> can also be quite useful.</p>\n"
},
{
"answer_id": 71136,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can also try <a href=\"http://www.hpl.hp.com/research/linux/httperf/\" rel=\"nofollow noreferrer\">httperf</a>. It's a very flexible tool and if you want to test how your application and webserver can deal with various traffic loads you should definitely give it a go.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
]
| Is there a way to get the current xml data when we make our own custom XPath function (see here).
I know you have access to an `XPathContext` but is this enough?
**Example:**
Our XML:
```
<foo>
<bar>smang</bar>
<fizz>buzz</fizz>
</foo>
```
Our XSL:
```
<xsl:template match="/">
<xsl:value-of select="ourFunction()" />
</xsl:template>
```
How do we get the entire XML tree?
**Edit:** To clarify: I'm creating a custom function that ends up executing static Java code (it's a Saxon feature). So, in this Java code, I wish to be able to get elements from the XML tree, such as bar and fizz, and their CDATA, such as smang and buzz. | There is the classic 'ab' (apachebench) program. More power comes from [JMmeter](http://jakarta.apache.org/jmeter/). For server health, I recommend Munin, which can painlessly capture data from several systems and aggregate it on one page. |
69,480 | <p>I have a script that renders graphs in gnuplot. The graphs all end up with an ugly white background. How do I change this? (Ideally, with a command that goes into a gnuplot script, as opposed to a command-line option or something in a settings file)</p>
| [
{
"answer_id": 69510,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 2,
"selected": false,
"text": "<p>It is a setting for some terminal (windows use background). Check out colorbox including its bdefault.</p>\n\n<p>/Allan</p>\n"
},
{
"answer_id": 69512,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 4,
"selected": true,
"text": "<p>Ooh, found it. It's along the lines of:</p>\n\n<pre><code>set terminal png x222222 xffffff\n</code></pre>\n"
},
{
"answer_id": 7334137,
"author": "hsxz",
"author_id": 932735,
"author_profile": "https://Stackoverflow.com/users/932735",
"pm_score": 5,
"selected": false,
"text": "<p>You can change the background color by command <code>set object 1 rectangle from screen 0,0 to screen 1,1 fillcolor rgb\"green\" behind</code> to set the background color to the the color you specified (here is green).</p>\n\n<p>To get more knowledge about setting the background in gnuplot, you can visit this <a href=\"http://gnuplot-surprising.blogspot.com/\" rel=\"noreferrer\" title=\"blog\">blog</a>. There are even provided methods to set a gradient color background and background pictures. Good luck!</p>\n"
},
{
"answer_id": 64352284,
"author": "Marco Righele",
"author_id": 162945,
"author_profile": "https://Stackoverflow.com/users/162945",
"pm_score": 1,
"selected": false,
"text": "<p>According to the <a href=\"http://www.gnuplot.info/documentation.html\" rel=\"nofollow noreferrer\">official documentation</a>, as of version 5.4 the right way to set the background color in a gnuplot script is something like the following:</p>\n<pre><code>set term wxt background rgb "gray75"\n</code></pre>\n<p>Note that the color must be quoted. Beside color names you can use hex values with the format "#AARRGGBB" or "0xAARRGGBB</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
| I have a script that renders graphs in gnuplot. The graphs all end up with an ugly white background. How do I change this? (Ideally, with a command that goes into a gnuplot script, as opposed to a command-line option or something in a settings file) | Ooh, found it. It's along the lines of:
```
set terminal png x222222 xffffff
``` |
69,546 | <p>I have a multi-frame layout. One of the frames contains a form, which I am submitting through XMLHttpRequest. Now when I use document.write() to rewrite the frame with the form, and the new page I am adding contains any javascript then the javascript is not exectuted in IE6?</p>
<p>For example:</p>
<pre><code>document.write("<html><head><script>alert(1);</script></head><body>test</body></html>");
</code></pre>
<p>In the above case the page content is replaced with test but the alert() isn't executed. This works fine in Firefox.</p>
<p>What is a workaround to the above problem? </p>
| [
{
"answer_id": 69655,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 1,
"selected": false,
"text": "<p>Workaround is to programmatically add <code><script></code> blocks to head DOM element in JavaScript at Callback function or call eval() method. It's only way you can make this work in IE 6.</p>\n"
},
{
"answer_id": 69662,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": 0,
"selected": false,
"text": "<p>Another possible alternative is to use JSON, dynamically adding scripts references which will be automatically processed by browser. </p>\n\n<p>Cheers.</p>\n"
},
{
"answer_id": 159789,
"author": "Armin Ronacher",
"author_id": 19990,
"author_profile": "https://Stackoverflow.com/users/19990",
"pm_score": 0,
"selected": false,
"text": "<p>In short: You can't really do that. However JavaScript libraries such as jQuery provide functionality to do exactly that. If you depend on that, give jQuery a try.</p>\n"
},
{
"answer_id": 159830,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 0,
"selected": false,
"text": "<p>Eval and/or executing scripts dynamically is bad practice. Very bad practice. Very, very, very bad practice. I can't stress enough, how bad practice it is.</p>\n\n<p>AKA.: Sounds like bad design. What problem are you trying to solve again?</p>\n"
},
{
"answer_id": 159840,
"author": "Ates Goral",
"author_id": 23501,
"author_profile": "https://Stackoverflow.com/users/23501",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of having the JS code out in the open, enclose it in a function (let's call it \"<code>doIt</code>\"). Your frame window (let's say it's name is \"formFrame\") has a parent window (even if it's not visible) in which you can execute JS code. Do the actual frame rewrite operation in that scope:</p>\n\n<pre><code>window.parent.rewriteFormFrame(theHtml);\n</code></pre>\n\n<p>Where <code>rewriteFormFrame</code> function in the parent window looks something like this:</p>\n\n<pre><code>function rewriteFormFrame(html) {\n formFrame.document.body.innerHTML = html;\n formFrame.doIt();\n}\n</code></pre>\n"
},
{
"answer_id": 1575755,
"author": "Ollie Saunders",
"author_id": 113019,
"author_profile": "https://Stackoverflow.com/users/113019",
"pm_score": 0,
"selected": false,
"text": "<p>You could use an onload attribute in the body tag (<code><body onload=\"jsWrittenLoaded()\"></code>).</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have a multi-frame layout. One of the frames contains a form, which I am submitting through XMLHttpRequest. Now when I use document.write() to rewrite the frame with the form, and the new page I am adding contains any javascript then the javascript is not exectuted in IE6?
For example:
```
document.write("<html><head><script>alert(1);</script></head><body>test</body></html>");
```
In the above case the page content is replaced with test but the alert() isn't executed. This works fine in Firefox.
What is a workaround to the above problem? | Workaround is to programmatically add `<script>` blocks to head DOM element in JavaScript at Callback function or call eval() method. It's only way you can make this work in IE 6. |
69,561 | <p>gnuplot is giving the error: "sh: kpsexpand: not found." </p>
<p>I feel like the guy in Office Space when he saw "PC LOAD LETTER". What the heck is kpsexpand?</p>
<p>I searched Google, and there were a lot of pages that make reference to kpsexpand, and say not to worry about it, but I can't find anything, anywhere that actually explains <em>what it is.</em></p>
<p>Even the man page stinks:</p>
<pre><code>$ man kpsexpand
kpsetool - script to make teTeX-style kpsetool, kpsexpand, and kpsepath available
</code></pre>
<p>Edit: Again, I'm not asking what to do -- I know what to do, thanks to Google. What I'm wondering is what the darn thing <em>is.</em></p>
| [
{
"answer_id": 69575,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>This is on the first page of google search results for \"kpexpand gnuplot\":</p>\n\n<p><a href=\"http://dschneller.blogspot.com/2007/06/visualize-hard-disk-temperature-with.html\" rel=\"nofollow noreferrer\">http://dschneller.blogspot.com/2007/06/visualize-hard-disk-temperature-with.html</a></p>\n\n<p>It says that you do not need to care about the error-messages.</p>\n\n<p>Here is the manual page for kpsexpand:</p>\n\n<p><a href=\"http://linux.die.net/man/1/kpsexpand\" rel=\"nofollow noreferrer\">http://linux.die.net/man/1/kpsexpand</a></p>\n"
},
{
"answer_id": 2538565,
"author": "Born2Smile",
"author_id": 250287,
"author_profile": "https://Stackoverflow.com/users/250287",
"pm_score": 2,
"selected": false,
"text": "<p>kpsexpand, kpsetool and kpsepath are all wrappers for kpsewhich that deals with finding tex-related files\nkpsexpand is used to expand environment varibles.\nSay $VAR1 is \"Hello World\" and $VAR2 is \"/home/where/I/belong\" then</p>\n\n<pre><code>$ kpsexpand $VAR1</code></pre>\n\n<p>will return</p>\n\n<pre><code>Hello World</code></pre>\n\n<p>and <pre><code>$ kpsexpand $VAR2</code></pre> will return</p>\n\n<pre>/home/where/I/belong</pre>\n\n<p><code>kpsewhich</code> is reminiscent to <code>which</code> just like <code>which progname</code> will search the directories in the $PATH environment variable and return the path of the first found progname, <code>kpsewhich filename</code> will search the directories in the various tex-paths, fonts, packages, etc. for filename.</p>\n\n<p>to find out more lookup kpsewhich either in man or on google, and check out the source of kpsexpand</p>\n\n<pre><code>less `which kpsexpand`</code></pre>\n\n<p>Cheers\n/B2S</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7598/"
]
| gnuplot is giving the error: "sh: kpsexpand: not found."
I feel like the guy in Office Space when he saw "PC LOAD LETTER". What the heck is kpsexpand?
I searched Google, and there were a lot of pages that make reference to kpsexpand, and say not to worry about it, but I can't find anything, anywhere that actually explains *what it is.*
Even the man page stinks:
```
$ man kpsexpand
kpsetool - script to make teTeX-style kpsetool, kpsexpand, and kpsepath available
```
Edit: Again, I'm not asking what to do -- I know what to do, thanks to Google. What I'm wondering is what the darn thing *is.* | kpsexpand, kpsetool and kpsepath are all wrappers for kpsewhich that deals with finding tex-related files
kpsexpand is used to expand environment varibles.
Say $VAR1 is "Hello World" and $VAR2 is "/home/where/I/belong" then
```
$ kpsexpand $VAR1
```
will return
```
Hello World
```
and
```
$ kpsexpand $VAR2
```
will return
```
/home/where/I/belong
```
`kpsewhich` is reminiscent to `which` just like `which progname` will search the directories in the $PATH environment variable and return the path of the first found progname, `kpsewhich filename` will search the directories in the various tex-paths, fonts, packages, etc. for filename.
to find out more lookup kpsewhich either in man or on google, and check out the source of kpsexpand
```
less `which kpsexpand`
```
Cheers
/B2S |
69,591 | <p>I want to create a regexp in Emacs that matches exactly 3 digits. For example, I want to match the following:</p>
<pre><code>123
345
789
</code></pre>
<p>But not</p>
<pre><code>1234
12
12 23
</code></pre>
<p>If I use <code>[0-9]+</code> I match any single string of digits. I thought <code>[0-9]{3}</code> would work, but when tested in re-builder it doesn't match anything.</p>
| [
{
"answer_id": 69593,
"author": "mike511",
"author_id": 9593,
"author_profile": "https://Stackoverflow.com/users/9593",
"pm_score": -1,
"selected": false,
"text": "<p>It's pretty simple:</p>\n\n<pre><code>[0-9][0-9][0-9]\n</code></pre>\n"
},
{
"answer_id": 69615,
"author": "Joe Hildebrand",
"author_id": 8388,
"author_profile": "https://Stackoverflow.com/users/8388",
"pm_score": 7,
"selected": true,
"text": "<p>If you're entering the regex interactively, and want to use <code>{3}</code>, you need to use backslashes to escape the curly braces. If you don't want to match any part of the longer strings of numbers, use <code>\\b</code> to match word boundaries around the numbers. This leaves:</p>\n\n<pre><code>\\b[0-9]\\{3\\}\\b\n</code></pre>\n\n<p>For those wanting more information about <code>\\b</code>, see <a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Backslash.html#Regexp-Backslash\" rel=\"noreferrer\">the docs</a>:</p>\n\n<blockquote>\n <p>matches the empty string, but only at the beginning or end of a word. Thus, <code>\\bfoo\\b</code>\n matches any occurrence of <code>foo</code> as a separate word. \n <code>\\bballs?\\b</code> matches <code>ball</code> or <code>balls</code> as a separate word.\n <code>\\b</code> matches at the beginning or end of the buffer regardless of what text appears next to it. </p>\n</blockquote>\n\n<p>If you do want to use this regex from elisp code, as always, you must escape the backslashes one more time. For example:</p>\n\n<pre><code>(highlight-regexp \"\\\\b[0-9]\\\\{3\\\\}\\\\b\")\n</code></pre>\n"
},
{
"answer_id": 69622,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 3,
"selected": false,
"text": "<p><code>[0-9][0-9][0-9]</code>, <code>[0-9]{3}</code> or <code>\\d{3}</code> don't work because they also match \"1234\".</p>\n\n<p>So it depends on what the delimiter is.</p>\n\n<p>If it's in a variable, then you can do <code>^/[0-9]{3}/$</code>. If it's delimited by whitespace you could do <code>\\w+[0-9]{3}\\w+</code></p>\n"
},
{
"answer_id": 69624,
"author": "decibel",
"author_id": 11116,
"author_profile": "https://Stackoverflow.com/users/11116",
"pm_score": 0,
"selected": false,
"text": "<p>[0-9][0-9][0-9] will match a <em>minimum</em> of 3 numbers, so as Joe mentioned, you have to (at a minimum) include \\b or anything else that will delimit the numbers. Probably the most sure-fire method is:</p>\n\n<p>[^0-9][0-9][0-9][0-9][^0-9]</p>\n"
},
{
"answer_id": 69636,
"author": "Lukas Šalkauskas",
"author_id": 5369,
"author_profile": "https://Stackoverflow.com/users/5369",
"pm_score": 2,
"selected": false,
"text": "<p>You should use this: </p>\n\n<pre><code>\"^\\d{3}$\"\n</code></pre>\n"
},
{
"answer_id": 69644,
"author": "Antti Rasinen",
"author_id": 8570,
"author_profile": "https://Stackoverflow.com/users/8570",
"pm_score": 2,
"selected": false,
"text": "<p>As others point out, you need to match more than just the three digits. Before the digits you have to have either a line-start or something that is not a digit. If emacs supports \\D, use it. Otherwise use the set [^0-9].</p>\n\n<p>In a nutshell:</p>\n\n<pre><code>(^|\\D)\\d{3}(\\D|$)\n</code></pre>\n"
},
{
"answer_id": 78021,
"author": "Chopmo",
"author_id": 13747,
"author_profile": "https://Stackoverflow.com/users/13747",
"pm_score": 2,
"selected": false,
"text": "<p>When experimenting with regular expressions in Emacs, I find <strong>regex-tool</strong> quite useful: </p>\n\n<p><a href=\"ftp://ftp.newartisans.com/pub/emacs/regex-tool.el\" rel=\"nofollow noreferrer\">ftp://ftp.newartisans.com/pub/emacs/regex-tool.el</a></p>\n\n<p>Not an answer (the question is answered already), just a general tip. </p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6180/"
]
| I want to create a regexp in Emacs that matches exactly 3 digits. For example, I want to match the following:
```
123
345
789
```
But not
```
1234
12
12 23
```
If I use `[0-9]+` I match any single string of digits. I thought `[0-9]{3}` would work, but when tested in re-builder it doesn't match anything. | If you're entering the regex interactively, and want to use `{3}`, you need to use backslashes to escape the curly braces. If you don't want to match any part of the longer strings of numbers, use `\b` to match word boundaries around the numbers. This leaves:
```
\b[0-9]\{3\}\b
```
For those wanting more information about `\b`, see [the docs](http://www.gnu.org/software/emacs/manual/html_node/emacs/Regexp-Backslash.html#Regexp-Backslash):
>
> matches the empty string, but only at the beginning or end of a word. Thus, `\bfoo\b`
> matches any occurrence of `foo` as a separate word.
> `\bballs?\b` matches `ball` or `balls` as a separate word.
> `\b` matches at the beginning or end of the buffer regardless of what text appears next to it.
>
>
>
If you do want to use this regex from elisp code, as always, you must escape the backslashes one more time. For example:
```
(highlight-regexp "\\b[0-9]\\{3\\}\\b")
``` |
69,645 | <p>I want to take a screenshot via a python script and unobtrusively save it.</p>
<p>I'm only interested in the Linux solution, and should support any X based environment.</p>
| [
{
"answer_id": 70237,
"author": "Slava V",
"author_id": 37141,
"author_profile": "https://Stackoverflow.com/users/37141",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import ImageGrab\nimg = ImageGrab.grab()\nimg.save('test.jpg','JPEG')\n</code></pre>\n\n<p>this requires Python Imaging Library</p>\n"
},
{
"answer_id": 769221,
"author": "Juliano",
"author_id": 55078,
"author_profile": "https://Stackoverflow.com/users/55078",
"pm_score": 4,
"selected": false,
"text": "<p>This one works on X11, and perhaps on Windows too (someone, please check). Needs <a href=\"http://www.riverbankcomputing.co.uk/software/pyqt/intro\" rel=\"noreferrer\">PyQt4</a>:</p>\n\n<pre><code>import sys\nfrom PyQt4.QtGui import QPixmap, QApplication\napp = QApplication(sys.argv)\nQPixmap.grabWindow(QApplication.desktop().winId()).save('test.png', 'png')\n</code></pre>\n"
},
{
"answer_id": 782768,
"author": "Rusty",
"author_id": 95083,
"author_profile": "https://Stackoverflow.com/users/95083",
"pm_score": 7,
"selected": true,
"text": "<p>This works without having to use scrot or ImageMagick.</p>\n\n<pre><code>import gtk.gdk\n\nw = gtk.gdk.get_default_root_window()\nsz = w.get_size()\nprint \"The size of the window is %d x %d\" % sz\npb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])\npb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])\nif (pb != None):\n pb.save(\"screenshot.png\",\"png\")\n print \"Screenshot saved to screenshot.png.\"\nelse:\n print \"Unable to get the screenshot.\"\n</code></pre>\n\n<p>Borrowed from <a href=\"http://ubuntuforums.org/showpost.php?p=2681009&postcount=5\" rel=\"noreferrer\">http://ubuntuforums.org/showpost.php?p=2681009&postcount=5</a></p>\n"
},
{
"answer_id": 6380186,
"author": "Snowball",
"author_id": 802490,
"author_profile": "https://Stackoverflow.com/users/802490",
"pm_score": 3,
"selected": false,
"text": "<p>Cross platform solution using <a href=\"http://wxpython.org\" rel=\"noreferrer\">wxPython</a>:</p>\n\n<pre><code>import wx\nwx.App() # Need to create an App instance before doing anything\nscreen = wx.ScreenDC()\nsize = screen.GetSize()\nbmp = wx.EmptyBitmap(size[0], size[1])\nmem = wx.MemoryDC(bmp)\nmem.Blit(0, 0, size[0], size[1], screen, 0, 0)\ndel mem # Release bitmap\nbmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)\n</code></pre>\n"
},
{
"answer_id": 7711106,
"author": "Alex Raeder",
"author_id": 244382,
"author_profile": "https://Stackoverflow.com/users/244382",
"pm_score": 6,
"selected": false,
"text": "<p>Compile all answers in one class.\nOutputs PIL image.</p>\n\n<pre><code>#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\nscreengrab.py\n\nCreated by Alex Snet on 2011-10-10.\nCopyright (c) 2011 CodeTeam. All rights reserved.\n\"\"\"\n\nimport sys\nimport os\n\nimport Image\n\n\nclass screengrab:\n def __init__(self):\n try:\n import gtk\n except ImportError:\n pass\n else:\n self.screen = self.getScreenByGtk\n\n try:\n import PyQt4\n except ImportError:\n pass\n else:\n self.screen = self.getScreenByQt\n\n try:\n import wx\n except ImportError:\n pass\n else:\n self.screen = self.getScreenByWx\n\n try:\n import ImageGrab\n except ImportError:\n pass\n else:\n self.screen = self.getScreenByPIL\n\n\n def getScreenByGtk(self):\n import gtk.gdk \n w = gtk.gdk.get_default_root_window()\n sz = w.get_size()\n pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])\n pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])\n if pb is None:\n return False\n else:\n width,height = pb.get_width(),pb.get_height()\n return Image.fromstring(\"RGB\",(width,height),pb.get_pixels() )\n\n def getScreenByQt(self):\n from PyQt4.QtGui import QPixmap, QApplication\n from PyQt4.Qt import QBuffer, QIODevice\n import StringIO\n app = QApplication(sys.argv)\n buffer = QBuffer()\n buffer.open(QIODevice.ReadWrite)\n QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')\n strio = StringIO.StringIO()\n strio.write(buffer.data())\n buffer.close()\n del app\n strio.seek(0)\n return Image.open(strio)\n\n def getScreenByPIL(self):\n import ImageGrab\n img = ImageGrab.grab()\n return img\n\n def getScreenByWx(self):\n import wx\n wx.App() # Need to create an App instance before doing anything\n screen = wx.ScreenDC()\n size = screen.GetSize()\n bmp = wx.EmptyBitmap(size[0], size[1])\n mem = wx.MemoryDC(bmp)\n mem.Blit(0, 0, size[0], size[1], screen, 0, 0)\n del mem # Release bitmap\n #bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)\n myWxImage = wx.ImageFromBitmap( myBitmap )\n PilImage = Image.new( 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )\n PilImage.fromstring( myWxImage.GetData() )\n return PilImage\n\nif __name__ == '__main__':\n s = screengrab()\n screen = s.screen()\n screen.show()\n</code></pre>\n"
},
{
"answer_id": 7817506,
"author": "ponty",
"author_id": 700820,
"author_profile": "https://Stackoverflow.com/users/700820",
"pm_score": 4,
"selected": false,
"text": "<p>I have a wrapper project (<a href=\"https://github.com/ponty/pyscreenshot\" rel=\"noreferrer\">pyscreenshot</a>) for scrot, imagemagick, pyqt, wx and pygtk.\nIf you have one of them, you can use it.\nAll solutions are included from this discussion.</p>\n\n<p>Install:</p>\n\n<pre><code>easy_install pyscreenshot\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>import pyscreenshot as ImageGrab\n\n# fullscreen\nim=ImageGrab.grab()\nim.show()\n\n# part of the screen\nim=ImageGrab.grab(bbox=(10,10,500,500))\nim.show()\n\n# to file\nImageGrab.grab_to_file('im.png')\n</code></pre>\n"
},
{
"answer_id": 16141058,
"author": "b0bz",
"author_id": 1149259,
"author_profile": "https://Stackoverflow.com/users/1149259",
"pm_score": 6,
"selected": false,
"text": "<p>Just for completeness:\nXlib - But it's somewhat slow when capturing the whole screen:</p>\n<pre><code>from Xlib import display, X\nimport Image #PIL\n\nW,H = 200,200\ndsp = display.Display()\ntry:\n root = dsp.screen().root\n raw = root.get_image(0, 0, W,H, X.ZPixmap, 0xffffffff)\n image = Image.fromstring("RGB", (W, H), raw.data, "raw", "BGRX")\n image.show()\nfinally:\n dsp.close()\n</code></pre>\n<p>One could try to trow some types in the bottleneck-files in PyXlib, and then compile it using Cython. That could increase the speed a bit.</p>\n<hr />\n<p><strong>Edit:</strong>\nWe can write the core of the function in C, and then use it in python from ctypes, here is something I hacked together:</p>\n<pre><code>#include <stdio.h>\n#include <X11/X.h>\n#include <X11/Xlib.h>\n//Compile hint: gcc -shared -O3 -lX11 -fPIC -Wl,-soname,prtscn -o prtscn.so prtscn.c\n\nvoid getScreen(const int, const int, const int, const int, unsigned char *);\nvoid getScreen(const int xx,const int yy,const int W, const int H, /*out*/ unsigned char * data) \n{\n Display *display = XOpenDisplay(NULL);\n Window root = DefaultRootWindow(display);\n\n XImage *image = XGetImage(display,root, xx,yy, W,H, AllPlanes, ZPixmap);\n\n unsigned long red_mask = image->red_mask;\n unsigned long green_mask = image->green_mask;\n unsigned long blue_mask = image->blue_mask;\n int x, y;\n int ii = 0;\n for (y = 0; y < H; y++) {\n for (x = 0; x < W; x++) {\n unsigned long pixel = XGetPixel(image,x,y);\n unsigned char blue = (pixel & blue_mask);\n unsigned char green = (pixel & green_mask) >> 8;\n unsigned char red = (pixel & red_mask) >> 16;\n\n data[ii + 2] = blue;\n data[ii + 1] = green;\n data[ii + 0] = red;\n ii += 3;\n }\n }\n XDestroyImage(image);\n XDestroyWindow(display, root);\n XCloseDisplay(display);\n}\n</code></pre>\n<p>And then the python-file:</p>\n<pre><code>import ctypes\nimport os\nfrom PIL import Image\n\nLibName = 'prtscn.so'\nAbsLibPath = os.path.dirname(os.path.abspath(__file__)) + os.path.sep + LibName\ngrab = ctypes.CDLL(AbsLibPath)\n\ndef grab_screen(x1,y1,x2,y2):\n w, h = x2-x1, y2-y1\n size = w * h\n objlength = size * 3\n\n grab.getScreen.argtypes = []\n result = (ctypes.c_ubyte*objlength)()\n\n grab.getScreen(x1,y1, w, h, result)\n return Image.frombuffer('RGB', (w, h), result, 'raw', 'RGB', 0, 1)\n \nif __name__ == '__main__':\n im = grab_screen(0,0,1440,900)\n im.show()\n</code></pre>\n"
},
{
"answer_id": 20219666,
"author": "Anand",
"author_id": 2659276,
"author_profile": "https://Stackoverflow.com/users/2659276",
"pm_score": -1,
"selected": false,
"text": "<p>Try it:</p>\n\n<pre><code>#!/usr/bin/python\n\nimport gtk.gdk\nimport time\nimport random\nimport socket\nimport fcntl\nimport struct\nimport getpass\nimport os\nimport paramiko \n\nwhile 1:\n # generate a random time between 120 and 300 sec\n random_time = random.randrange(20,25)\n # wait between 120 and 300 seconds (or between 2 and 5 minutes) \n\n print \"Next picture in: %.2f minutes\" % (float(random_time) / 60)\n\n time.sleep(random_time)\n w = gtk.gdk.get_default_root_window() \n sz = w.get_size()\n print \"The size of the window is %d x %d\" % sz\n pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])\n pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])\n ts = time.asctime( time.localtime(time.time()) )\n date = time.strftime(\"%d-%m-%Y\")\n timer = time.strftime(\"%I:%M:%S%p\")\n filename = timer\n filename += \".png\"\n\n if (pb != None):\n username = getpass.getuser() #Get username\n newpath = r'screenshots/'+username+'/'+date #screenshot save path\n if not os.path.exists(newpath): os.makedirs(newpath)\n saveas = os.path.join(newpath,filename)\n print saveas\n pb.save(saveas,\"png\")\n else:\n print \"Unable to get the screenshot.\"\n</code></pre>\n"
},
{
"answer_id": 23609424,
"author": "ouille",
"author_id": 2761803,
"author_profile": "https://Stackoverflow.com/users/2761803",
"pm_score": 2,
"selected": false,
"text": "<p>There is a python package for this <a href=\"http://www.autopy.org/\" rel=\"nofollow\">Autopy</a></p>\n\n<p>The bitmap module can to screen grabbing (bitmap.capture_screen)\nIt is multiplateform (Windows, Linux, Osx).</p>\n"
},
{
"answer_id": 25805492,
"author": "rominf",
"author_id": 2108548,
"author_profile": "https://Stackoverflow.com/users/2108548",
"pm_score": 0,
"selected": false,
"text": "<p>It's an old question. I would like to answer it using new tools.</p>\n\n<p>Works with python 3 (should work with python 2, but I haven't test it) and PyQt5.</p>\n\n<p>Minimal working example. Copy it to the python shell and get the result.</p>\n\n<pre><code>from PyQt5.QtWidgets import QApplication\napp = QApplication([])\nscreen = app.primaryScreen()\nscreenshot = screen.grabWindow(QApplication.desktop().winId())\nscreenshot.save('/tmp/screenshot.png')\n</code></pre>\n"
},
{
"answer_id": 29136548,
"author": "anderstood",
"author_id": 1555099,
"author_profile": "https://Stackoverflow.com/users/1555099",
"pm_score": 1,
"selected": false,
"text": "<p>From <a href=\"http://ubuntuforums.org/showthread.php?t=448160\" rel=\"nofollow\">this thread</a>:</p>\n\n<pre><code> import os\n os.system(\"import -window root temp.png\")\n</code></pre>\n"
},
{
"answer_id": 30503686,
"author": "pkm",
"author_id": 2490439,
"author_profile": "https://Stackoverflow.com/users/2490439",
"pm_score": 2,
"selected": false,
"text": "<p>bit late but nevermind easy one is</p>\n\n<pre><code>import autopy\nimport time\ntime.sleep(2)\nb = autopy.bitmap.capture_screen()\nb.save(\"C:/Users/mak/Desktop/m.png\")\n</code></pre>\n"
},
{
"answer_id": 45579657,
"author": "cyera",
"author_id": 8436827,
"author_profile": "https://Stackoverflow.com/users/8436827",
"pm_score": 2,
"selected": false,
"text": "<p>I couldn't take screenshot in Linux with pyscreenshot or scrot because output of <code>pyscreenshot</code> was just a black screen png image file.</p>\n\n<p>but thank god there was another very easy way for taking screenshot in Linux without installing anything. just put below code in your directory and run with <code>python demo.py</code></p>\n\n<pre><code>import os\nos.system(\"gnome-screenshot --file=this_directory.png\")\n</code></pre>\n\n<p>also there is many available options for <code>gnome-screenshot --help</code></p>\n\n<pre><code>Application Options:\n -c, --clipboard Send the grab directly to the clipboard\n -w, --window Grab a window instead of the entire screen\n -a, --area Grab an area of the screen instead of the entire screen\n -b, --include-border Include the window border with the screenshot\n -B, --remove-border Remove the window border from the screenshot\n -p, --include-pointer Include the pointer with the screenshot\n -d, --delay=seconds Take screenshot after specified delay [in seconds]\n -e, --border-effect=effect Effect to add to the border (shadow, border, vintage or none)\n -i, --interactive Interactively set options\n -f, --file=filename Save screenshot directly to this file\n --version Print version information and exit\n --display=DISPLAY X display to use\n</code></pre>\n"
},
{
"answer_id": 52549704,
"author": "Jack Sparrow",
"author_id": 3293019,
"author_profile": "https://Stackoverflow.com/users/3293019",
"pm_score": 3,
"selected": false,
"text": "<p>You can use this</p>\n\n<pre><code>import os\nos.system(\"import -window root screen_shot.png\")\n</code></pre>\n"
},
{
"answer_id": 64236518,
"author": "Matheus K.",
"author_id": 14391919,
"author_profile": "https://Stackoverflow.com/users/14391919",
"pm_score": 2,
"selected": false,
"text": "<p>for ubuntu this work for me, you can take a screenshot of select window with this:</p>\n<pre><code>import gi\ngi.require_version('Gtk', '3.0')\ngi.require_version('Gdk', '3.0')\n\nfrom gi.repository import Gdk\nfrom gi.repository import GdkPixbuf\nimport numpy as np\nfrom Xlib.display import Display\n\n#define the window name\nwindow_name = 'Spotify'\n\n#define xid of your select 'window'\ndef locate_window(stack,window):\n disp = Display()\n NET_WM_NAME = disp.intern_atom('_NET_WM_NAME')\n WM_NAME = disp.intern_atom('WM_NAME') \n name= []\n for i, w in enumerate(stack):\n win_id =w.get_xid()\n window_obj = disp.create_resource_object('window', win_id)\n for atom in (NET_WM_NAME, WM_NAME):\n window_name=window_obj.get_full_property(atom, 0)\n name.append(window_name.value)\n for l in range(len(stack)):\n if(name[2*l]==window):\n return stack[l]\n\nwindow = Gdk.get_default_root_window()\nscreen = window.get_screen()\nstack = screen.get_window_stack()\nmyselectwindow = locate_window(stack,window_name)\nimg_pixbuf = Gdk.pixbuf_get_from_window(myselectwindow,*myselectwindow.get_geometry()) \n</code></pre>\n<p>to transform pixbuf into array</p>\n<pre><code>def pixbuf_to_array(p):\n w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())\n assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB\n assert p.get_bits_per_sample() == 8\n if p.get_has_alpha():\n assert c == 4\n else:\n assert c == 3\n assert r >= w * c\n a=np.frombuffer(p.get_pixels(),dtype=np.uint8)\n if a.shape[0] == w*c*h:\n return a.reshape( (h, w, c) )\n else:\n b=np.zeros((h,w*c),'uint8')\n for j in range(h):\n b[j,:]=a[r*j:r*j+w*c]\n return b.reshape( (h, w, c) )\n\nbeauty_print = pixbuf_to_array(img_pixbuf)\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1724701/"
]
| I want to take a screenshot via a python script and unobtrusively save it.
I'm only interested in the Linux solution, and should support any X based environment. | This works without having to use scrot or ImageMagick.
```
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
print "The size of the window is %d x %d" % sz
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if (pb != None):
pb.save("screenshot.png","png")
print "Screenshot saved to screenshot.png."
else:
print "Unable to get the screenshot."
```
Borrowed from <http://ubuntuforums.org/showpost.php?p=2681009&postcount=5> |
69,676 | <p>How do I get Asterisk to forward incoming calls based on matching the incoming call number with a number to forward to? Both numbers are stored in a MySQL database.</p>
| [
{
"answer_id": 69689,
"author": "willurd",
"author_id": 1943957,
"author_profile": "https://Stackoverflow.com/users/1943957",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://scottstuff.net/blog/articles/2004/08/09/database-driven-call-forwarding-with-asterisk\" rel=\"nofollow noreferrer\">This article</a> should do the trick. It's about 3 lines of code and some simple queries to add and remove forwarding rules.</p>\n"
},
{
"answer_id": 75492,
"author": "Jeremy Wadhams",
"author_id": 8995,
"author_profile": "https://Stackoverflow.com/users/8995",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry for the long code sample, but more than half of it is debugging code to help you get it set up.</p>\n\n<p>I'm assuming your server already has a modern version of PHP (at <code>/usr/bin/php</code>) with the PDO library, and that you have a database table named <code>fwd_table</code> with columns <code>caller_id</code> and <code>destination</code>.</p>\n\n<p>In /var/lib/asterisk/agi-bin get a copy of the <a href=\"http://sourceforge.net/projects/phpagi/\" rel=\"nofollow noreferrer\">PHP AGI</a> library. Then create a file named something like <code>forward_by_callerid.agi</code> that contains:</p>\n\n<pre><code>#!/usr/bin/php\n<?php\nini_set('display_errors','false'); //Supress errors getting sent to the Asterisk process\n\nrequire('phpagi.php');\n$agi = new AGI();\n\ntry {\n $pdo = new PDO('mysql:host='.$db_hostname.';dbname='.$db_database.';charset=UTF-8', $db_user, $db_pass);\n} catch (PDOException $e) {\n $agi->conlog(\"FAIL: Error connecting to the database! \" . $e->getMessage());\n die();\n}\n\n$find_fwd_by_callerid = $pdo->prepare('SELECT destination FROM fwd_table WHERE caller_id=? ');\n\n$caller_id = $agi->request['agi_callerid'];\n\nif($callerid==\"unknown\" or $callerid==\"private\" or $callerid==\"\"){\n $agi->conlog(\"Call came in without caller id, I give up\");\n exit;\n}else{\n $agi->conlog(\"Call came in with caller id number $caller_id.\");\n}\n\nif($find_fwd_by_callerid->execute(array($caller_id)) === false){\n $agi->conlog(\"Database problem searching for forward destination (find_fwd_by_callerid), croaking\");\n exit;\n} \n$found_fwds = $find_fwd_by_callerid->fetchAll();\nif(count($found_fwds) > 0){\n $destination = $found_contacts[0]['destination'];\n $agi->set_variable('FWD_TO', $destination);\n\n $agi->conlog(\"Caller ID matched, setting FWD_TO variable to ''\");\n}\n\n?>\n</code></pre>\n\n<p>Then from the dial plan you can call it like this:</p>\n\n<pre><code>AGI(forward_by_callerid.agi)\n</code></pre>\n\n<p>And if your database has a match, it will set the variable <code>FWD_TO</code> with goodness. Please edit your question if you need more help getting this integrated into your dial plan.</p>\n"
},
{
"answer_id": 1869230,
"author": "Aaron",
"author_id": 11176,
"author_profile": "https://Stackoverflow.com/users/11176",
"pm_score": 2,
"selected": true,
"text": "<p>The solution I was looking for ended up looking like this:</p>\n\n<pre><code>[default]\nexten => _X.,1,Set(ARRAY(${EXTEN}_phone)=${DTC_ICF(phone_number,${EXTEN})})\nexten => _X.,n(callphone),Dial(SIP/metaswitch/${${EXTEN}_phone},26)\nexten => _X.,n(end),Hangup()\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11176/"
]
| How do I get Asterisk to forward incoming calls based on matching the incoming call number with a number to forward to? Both numbers are stored in a MySQL database. | The solution I was looking for ended up looking like this:
```
[default]
exten => _X.,1,Set(ARRAY(${EXTEN}_phone)=${DTC_ICF(phone_number,${EXTEN})})
exten => _X.,n(callphone),Dial(SIP/metaswitch/${${EXTEN}_phone},26)
exten => _X.,n(end),Hangup()
``` |
69,695 | <p>I am trying to use a stringstream object in VC++ (VStudio 2003) butI am getting an error when I use the overloaded << operator to try and set some manipulators. </p>
<p>I am trying the following: </p>
<pre><code>int SomeInt = 1;
stringstream StrStream;
StrStream << std::setw(2) << SomeInt;
</code></pre>
<p>This will not compile (error C2593: 'operator <<' is ambiguous).<br>
Does VStudio 2003 support using manipulators in this way?<br>
I know that I can just set the width directly on the stringstream object e.g. StrStream.width(2);<br>
I was wondering why the more usual method doesn't work?</p>
| [
{
"answer_id": 69721,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 2,
"selected": true,
"text": "<p>Are you sure you included all of the right headers? The following compiles for me in VS2003:</p>\n\n<pre><code>#include <iostream>\n#include <sstream>\n#include <iomanip>\n\nint main()\n{\n int SomeInt = 1;\n std::stringstream StrStream;\n StrStream << std::setw(2) << SomeInt;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 69732,
"author": "Allan Wind",
"author_id": 9706,
"author_profile": "https://Stackoverflow.com/users/9706",
"pm_score": 1,
"selected": false,
"text": "<p>I love this <a href=\"http://www.cplusplus.com/reference/\" rel=\"nofollow noreferrer\">reference site</a> for stream questions like this.</p>\n\n<p>/Allan</p>\n"
},
{
"answer_id": 69779,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You probably just forgot to include iomanip, but I can't be sure because you didn't include code for a complete program there.</p>\n\n<p>This complete program works fine over here using VS 2003:</p>\n\n<pre><code>#include <sstream>\n#include <iomanip>\n\nint main()\n{\n int SomeInt = 1;\n std::stringstream StrStream;\n StrStream << std::setw(2) << SomeInt;\n}\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1682/"
]
| I am trying to use a stringstream object in VC++ (VStudio 2003) butI am getting an error when I use the overloaded << operator to try and set some manipulators.
I am trying the following:
```
int SomeInt = 1;
stringstream StrStream;
StrStream << std::setw(2) << SomeInt;
```
This will not compile (error C2593: 'operator <<' is ambiguous).
Does VStudio 2003 support using manipulators in this way?
I know that I can just set the width directly on the stringstream object e.g. StrStream.width(2);
I was wondering why the more usual method doesn't work? | Are you sure you included all of the right headers? The following compiles for me in VS2003:
```
#include <iostream>
#include <sstream>
#include <iomanip>
int main()
{
int SomeInt = 1;
std::stringstream StrStream;
StrStream << std::setw(2) << SomeInt;
return 0;
}
``` |
69,702 | <pre><code>public static void main(String[] args) {
List<? extends Object> mylist = new ArrayList<Object>();
mylist.add("Java"); // compile error
}
</code></pre>
<p>The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing.
In this case what purpose does the above fulfil ??</p>
| [
{
"answer_id": 69797,
"author": "Ren",
"author_id": 11188,
"author_profile": "https://Stackoverflow.com/users/11188",
"pm_score": 1,
"selected": false,
"text": "<p>With java generics using wildcards, you are allowed the above declaration assuming you are only going to read from it. </p>\n\n<p>You aren't allowed to add/write to it, because all generic types must be stripped at compile time, and at compile time there isn't a way the compiler knows List are only strings, (it could be any object including strings!) </p>\n\n<p>You are however allowed to read from it since they are going to be at least objects. Mixing different types are not allowed in java collections to keep things clean and understandable, and this helps ensure it.</p>\n"
},
{
"answer_id": 69815,
"author": "Henning",
"author_id": 7034,
"author_profile": "https://Stackoverflow.com/users/7034",
"pm_score": 1,
"selected": false,
"text": "<p>The point of bounded wildcard types is their use in method signatures to increase API flexibility. If, for example, you implement a generic <code>Stack<E></code>, you could provide a method to push a number of elements to the stack like so: </p>\n\n<pre><code>public void pushAll(Iterable<? extends E> elements) {\n for(E element : elements){\n push(e);\n }\n}\n</code></pre>\n\n<p>Compared to a <code>pushAll(Iterable<E> elements)</code> signature without a wildcard, this has the advantage that it allows collections of subtypes of <code>E</code> to be passed to the method - normally that would not be allowed because an <code>Iterable<String></code> is, somewhat counterintuitively, not a subclass of <code>Iterable<Object></code>.</p>\n"
},
{
"answer_id": 69825,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 0,
"selected": false,
"text": "<p>This works:</p>\n\n<pre><code>List<? super Object> mylist = new ArrayList<Object>();\nmylist.add(\"Java\"); // no compile error\n</code></pre>\n\n<p>From O'Reilly's <a href=\"http://oreilly.com/catalog/9780596527754/\" rel=\"nofollow noreferrer\">Java Generics</a>:</p>\n\n<blockquote>\n <p>The Get and Put Principle: use an extends wildcard when you only get values our of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard you both get and put.</p>\n</blockquote>\n"
},
{
"answer_id": 69855,
"author": "Frank Grimm",
"author_id": 903,
"author_profile": "https://Stackoverflow.com/users/903",
"pm_score": 3,
"selected": false,
"text": "<p>In his book great 'Effective Java' (Second Edition) Joshua Bloch explains what he calls the producer/consumer principle for using generics. Josh's explaination should tell you why your example does not work (compile) ...</p>\n\n<p>Chapter 5 (Generics) is freely available here: <a href=\"http://java.sun.com/docs/books/effective/generics.pdf\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/effective/generics.pdf</a></p>\n\n<p>More information about the book (and the author) are available: <a href=\"http://java.sun.com/docs/books/effective/\" rel=\"nofollow noreferrer\">http://java.sun.com/docs/books/effective/</a></p>\n"
},
{
"answer_id": 69893,
"author": "Bruno De Fraine",
"author_id": 6918,
"author_profile": "https://Stackoverflow.com/users/6918",
"pm_score": 0,
"selected": false,
"text": "<p><code>List<? extends Object></code>, which is the same as <code>List<?></code>, fulfills the purpose of generalizing all types <code>List<String></code>, <code>List<Number></code>, <code>List<Object></code>, etc. (so all types with a proper type in place of the <code>?</code>). Values of all of these types can be assigned to a variable of type <code>List<?></code> (which is where it differs from <code>List<Object></code>!).</p>\n\n<p>In general, you cannot add a string to such a list. However, you can read <code>Object</code> from the list and you can add <code>null</code> to it. You can also calculate the length of the list, etc. These are operations that are guaranteed to work for each of these types.</p>\n\n<p>For a good introduction to wildcards, see the paper <a href=\"http://bracha.org/wildcards.pdf\" rel=\"nofollow noreferrer\">Adding Wildcards to the Java Programming Language</a>. It is an academic paper, but still very accessible.</p>\n"
},
{
"answer_id": 70393,
"author": "rmaruszewski",
"author_id": 6856,
"author_profile": "https://Stackoverflow.com/users/6856",
"pm_score": 4,
"selected": true,
"text": "<p>Let's say you have an interface and two classes:</p>\n\n<pre><code>interface IResult {}\nclass AResult implements IResult {}\nclass BResult implements IResult {}\n</code></pre>\n\n<p>Then you have classes that return a list as a result:</p>\n\n<pre><code>interface ITest<T extends IResult> {\n List<T> getResult();\n}\n\nclass ATest implements ITest<AResult> {\n // look, overridden!\n List<AResult> getResult();\n}\n\nclass BTest implements ITest<BResult> {\n // overridden again!\n List<BResult> getResult();\n}\n</code></pre>\n\n<p>It's a good solution, when you need \"covariant returns\", but you return collections instead of your own objects. The big plus is that you don't have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned - as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List<AResult> (returned as List<? extends T>), which doesn't make any sense.</p>\n\n<p>So you have to remember this: List<? extends X> defines a list that could be easily overridden, but which is read-only.</p>\n"
},
{
"answer_id": 36215658,
"author": "stackinfostack",
"author_id": 6088524,
"author_profile": "https://Stackoverflow.com/users/6088524",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Java Generics : Wild Cards in Collections</strong></p>\n\n<ol>\n<li>extends</li>\n<li>super</li>\n<li>?</li>\n</ol>\n\n<p>Today I am going to explain you how the wild cards are useful. To understand this concept is bit difficult</p>\n\n<p>Now Suppose you have abstract class and in that you have abstract method called paintObject().</p>\n\n<pre><code>Now you want to use different type of collection in every child class.\n</code></pre>\n\n<p>This below is AbstractMain Method.</p>\n\n<p><strong>Here Steps we have taken for this Abstract Main method</strong></p>\n\n<p><strong>1.</strong> We have created abstract class</p>\n\n<p><strong>2.</strong> In Parameter we have define T(you can use any character)\n --In this case whichever class implement this method it can used any type of class.\n ex. Class can implement method like \n public void paintObject(ArrayList object) or public void paintObject(HashSet object)</p>\n\n<p><strong>3.</strong> And We have also used E extends MainColorTO\n -- In this case E extends MainColorTo\n -- It's clearly means whichever class you want to use that must be sub class of MainColorTo</p>\n\n<p><strong>4.</strong> We have define abstract method called paintObject(T object,E objectTO)\n --Now here whichever class is implement method that method can use any class on first argument and second parameter that method has to use type of MainColorTO </p>\n\n<pre><code>public abstract class AbstractMain<T,E extends MainColorTO> {\n public abstract void paintObject(T Object,E TO); \n}\n</code></pre>\n\n<p>Now we will extend above abstract class and implement method on below class\n ex.</p>\n\n<pre><code>public class MainColorTO { \n public void paintColor(){\n System.out.println(\"Paint Color........\");\n } \n }\n\npublic class RedTO extends MainColorTO {\n @Override\n public void paintColor() {\n System.out.println(\"RedTO......\");\n }\n}\npublic class WhiteTO extends MainColorTO {\n @Override\n public void paintColor() {\n System.out.println(\"White TO......\");\n }\n }\n</code></pre>\n\n<p>Now we will take two example.</p>\n\n<p><strong>1.PaintHome.java</strong> </p>\n\n<pre><code>public class PaintHome extends AbstractMain<ArrayList, RedTO> {\n @Override\n public void paintObject(ArrayList arrayList,RedTO red) {\n System.out.println(arrayList);\n\n }\n }\n</code></pre>\n\n<p>Now in above PaintHome.java you can check that we have used ArrayList in first argument(As we can take any class) and in second argument we have used RedTO(Which is extending MainColorTO)</p>\n\n<p><strong>2.PaintCar.java</strong></p>\n\n<pre><code>public class PaintCar extends AbstractMain<HashSet, WhiteTO>{\n @Override\n public void paintObject(HashSet Object,WhiteTO white) {\n System.out.println(Object);\n\n }\n }\n</code></pre>\n\n<p>Now in above PaintCar.java you can check that we have used HashSet in first argument(As We Can take any class) and in second argument we have used WhiteTO(Which is extending MainColorTO)</p>\n\n<p><strong>Ponint to Remember</strong>\n You can not use super keyword at class level you can only use extends keyword at class level defination</p>\n\n<pre><code>public abstract class AbstractMain<P,E super MainColorTO> {\n\n public abstract void paintObject(P Object,E TO);\n\n}\n</code></pre>\n\n<p>Above code will give you compiler error.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
| ```
public static void main(String[] args) {
List<? extends Object> mylist = new ArrayList<Object>();
mylist.add("Java"); // compile error
}
```
The above code does not allow you to add elements to the list and wild cards can only be used as a signature in methods, again not for adding but only for accessing.
In this case what purpose does the above fulfil ?? | Let's say you have an interface and two classes:
```
interface IResult {}
class AResult implements IResult {}
class BResult implements IResult {}
```
Then you have classes that return a list as a result:
```
interface ITest<T extends IResult> {
List<T> getResult();
}
class ATest implements ITest<AResult> {
// look, overridden!
List<AResult> getResult();
}
class BTest implements ITest<BResult> {
// overridden again!
List<BResult> getResult();
}
```
It's a good solution, when you need "covariant returns", but you return collections instead of your own objects. The big plus is that you don't have to cast objects when using ATest and BTest independently from the ITest interface. However, when using ITest interface, you cannot add anything to the list that was returned - as you cannot determine, what object types the list really contains! If it would be allowed, you would be able to add BResult to List<AResult> (returned as List<? extends T>), which doesn't make any sense.
So you have to remember this: List<? extends X> defines a list that could be easily overridden, but which is read-only. |
69,722 | <p>I have a dl containing some input boxes that I "clone" with a bit of JavaScript like: </p>
<pre><code>var newBox = document.createElement('dl');
var sourceBox = document.getElementById(oldkey);
newBox.innerHTML = sourceBox.innerHTML;
newBox.id = newkey;
document.getElementById('boxes').appendChild(columnBox);
</code></pre>
<p>In IE, the form in sourceBox is duplicated in newBox, complete with user-supplied values. In Firefox, last value entered in the orginal sourceBox is not present in newBox. How do I make this "stick?"</p>
| [
{
"answer_id": 69795,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 1,
"selected": false,
"text": "<p>You could try the <code>cloneNode</code> method. It might do a better job of copying the contents. It should also be faster in most cases</p>\n\n<pre><code>var newBox;\nvar sourceBox = document.getElementById(oldkey);\nif (sourceBox.cloneNode) \n newBox = sourceBox.cloneNode(true);\nelse {\n newBox = document.createElement(sourceBox.tagName); \n newBox.innerHTML = sourceBox.innerHTML; \n}\nnewBox.id = newkey; \ndocument.getElementById('boxes').appendChild(newBox);\n</code></pre>\n"
},
{
"answer_id": 70774,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 1,
"selected": true,
"text": "<p><a href=\"https://stackoverflow.com/questions/36778/firefox-vs-ie-innerhtml-handling#36793\">Firefox vs. IE: innerHTML handling</a> ?</p>\n"
},
{
"answer_id": 80723,
"author": "Ross Morrissey",
"author_id": 6997,
"author_profile": "https://Stackoverflow.com/users/6997",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks folks. </p>\n\n<p>I got things to work by using <strong><a href=\"http://www.prototypejs.org/\" rel=\"nofollow noreferrer\" title=\"Prototype Javascript Framework\">prototype</a></strong> and changing <code>document.getElementById(oldkey)</code>\nto <code>$(oldkey)</code>.</p>\n\n<pre><code><script src=\"j/prototype.js\" type=\"text/javascript\"></script> \n\nvar newBox; \nvar sourceBox = $(oldkey); \nif (sourceBox.cloneNode) \n newBox = sourceBox.cloneNode(true); \nelse { \n newBox = document.createElement(sourceBox.tagName); \n newBox.innerHTML = sourceBox.innerHTML; \n} \nnewBox.id = newkey; \ndocument.getElementById('boxes').appendChild(newBox);\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6997/"
]
| I have a dl containing some input boxes that I "clone" with a bit of JavaScript like:
```
var newBox = document.createElement('dl');
var sourceBox = document.getElementById(oldkey);
newBox.innerHTML = sourceBox.innerHTML;
newBox.id = newkey;
document.getElementById('boxes').appendChild(columnBox);
```
In IE, the form in sourceBox is duplicated in newBox, complete with user-supplied values. In Firefox, last value entered in the orginal sourceBox is not present in newBox. How do I make this "stick?" | [Firefox vs. IE: innerHTML handling](https://stackoverflow.com/questions/36778/firefox-vs-ie-innerhtml-handling#36793) ? |
69,738 | <p>I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred.</p>
<p>Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to_str() member function for A.</p>
<p>In pseudocode:</p>
<pre><code>class A {
public:
...
void print(FILE* f);
B b;
...
};
...
void A::print(FILE *f)
{
std::string s = "stuff";
fprintf(f, "some %s", s);
b.print(f);
}
class C {
...
std::string foo;
bool set_foo(std::str);
...
}
...
A a = new A();
C c = new C();
...
// wish i knew how to write A's to_str()
c.set_foo(a.to_str());
</code></pre>
<p>I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE* F) interface also needs to be preserved. I have considered several approaches to implementing A::to_str(), each with advantages and disadvantages:</p>
<ol>
<li><p>Change the calls to fprintf() to sprintf()</p>
<ul>
<li>I wouldn't have to rewrite any format strings</li>
<li>print() could be reimplemented as: fprint(f, this.to_str());</li>
<li>But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string</li>
</ul></li>
<li><p>Try to catch the results of a.print() in a string stream</p>
<ul>
<li>I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{</li>
<li>print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though <a href="http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html" rel="nofollow noreferrer">this guy says it may be possible</a>).</li>
</ul></li>
<li><p>Use Boost's string <a href="http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html" rel="nofollow noreferrer">format library</a></p>
<ul>
<li>More external dependencies. Yuck.</li>
<li>Format's syntax is different enough from printf() to be annoying: </li>
</ul>
<p>printf(format_str, args) -> cout << boost::format(format_str) % arg1 % arg2 % etc</p></li>
<li><p>Use Qt's <a href="https://doc.qt.io/qt-5/qstring.html#asprintf%3E" rel="nofollow noreferrer">QString::asprintf()</a></p>
<ul>
<li>A different external dependency.</li>
</ul></li>
</ol>
<p>So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?</p>
<p>Thanks.</p>
| [
{
"answer_id": 69762,
"author": "Assaf Lavie",
"author_id": 11208,
"author_profile": "https://Stackoverflow.com/users/11208",
"pm_score": 0,
"selected": false,
"text": "<p>Is this about serialization? Or printing proper?\nIf the former, consider boost::serialization as well. It's all about \"recursive\" serialization of objects and sub-object.</p>\n"
},
{
"answer_id": 69765,
"author": "bernhardrusch",
"author_id": 3056,
"author_profile": "https://Stackoverflow.com/users/3056",
"pm_score": 5,
"selected": true,
"text": "<p>I am using #3: the boost string format library - but I have to admit that I've never had any problem with the differences in format specifications.</p>\n\n<p>Works like a charm for me - and the external dependencies could be worse (a very stable library)</p>\n\n<p>Edited: adding an example how to use boost::format instead of printf:</p>\n\n<pre><code>sprintf(buffer, \"This is a string with some %s and %d numbers\", \"strings\", 42);\n</code></pre>\n\n<p>would be something like this with the boost::format library:</p>\n\n<pre><code>string = boost::str(boost::format(\"This is a string with some %s and %d numbers\") %\"strings\" %42);\n</code></pre>\n\n<p>Hope this helps clarify the usage of boost::format </p>\n\n<p>I've used boost::format as a sprintf / printf replacement in 4 or 5 applications (writing formatted strings to files, or custom output to logfiles) and never had problems with format differences. There may be some (more or less obscure) format specifiers which are differently - but I never had a problem.</p>\n\n<p>In contrast I had some format specifications I couldn't really do with streams (as much as I remember)</p>\n"
},
{
"answer_id": 69767,
"author": "Yann Ramin",
"author_id": 9167,
"author_profile": "https://Stackoverflow.com/users/9167",
"pm_score": 2,
"selected": false,
"text": "<p>You can use std::string and iostreams with formatting, such as the setw() call and others in iomanip</p>\n"
},
{
"answer_id": 69911,
"author": "Larry Gritz",
"author_id": 3832,
"author_profile": "https://Stackoverflow.com/users/3832",
"pm_score": 5,
"selected": false,
"text": "<p>Here's the idiom I like for making functionality identical to 'sprintf', but returning a std::string, and immune to buffer overflow problems. This code is part of an open source project that I'm writing (BSD license), so everybody feel free to use this as you wish.</p>\n\n<pre><code>#include <string>\n#include <cstdarg>\n#include <vector>\n#include <string>\n\nstd::string\nformat (const char *fmt, ...)\n{\n va_list ap;\n va_start (ap, fmt);\n std::string buf = vformat (fmt, ap);\n va_end (ap);\n return buf;\n}\n\n\n\nstd::string\nvformat (const char *fmt, va_list ap)\n{\n // Allocate a buffer on the stack that's big enough for us almost\n // all the time.\n size_t size = 1024;\n char buf[size];\n\n // Try to vsnprintf into our buffer.\n va_list apcopy;\n va_copy (apcopy, ap);\n int needed = vsnprintf (&buf[0], size, fmt, ap);\n // NB. On Windows, vsnprintf returns -1 if the string didn't fit the\n // buffer. On Linux & OSX, it returns the length it would have needed.\n\n if (needed <= size && needed >= 0) {\n // It fit fine the first time, we're done.\n return std::string (&buf[0]);\n } else {\n // vsnprintf reported that it wanted to write more characters\n // than we allotted. So do a malloc of the right size and try again.\n // This doesn't happen very often if we chose our initial size\n // well.\n std::vector <char> buf;\n size = needed;\n buf.resize (size);\n needed = vsnprintf (&buf[0], size, fmt, apcopy);\n return std::string (&buf[0]);\n }\n}\n</code></pre>\n\n<p>EDIT: when I wrote this code, I had no idea that this required C99 conformance and that Windows (as well as older glibc) had different vsnprintf behavior, in which it returns -1 for failure, rather than a definitive measure of how much space is needed. Here is my revised code, could everybody look it over and if you think it's ok, I will edit again to make that the only cost listed:</p>\n\n<pre><code>std::string\nStrutil::vformat (const char *fmt, va_list ap)\n{\n // Allocate a buffer on the stack that's big enough for us almost\n // all the time. Be prepared to allocate dynamically if it doesn't fit.\n size_t size = 1024;\n char stackbuf[1024];\n std::vector<char> dynamicbuf;\n char *buf = &stackbuf[0];\n va_list ap_copy;\n\n while (1) {\n // Try to vsnprintf into our buffer.\n va_copy(ap_copy, ap);\n int needed = vsnprintf (buf, size, fmt, ap);\n va_end(ap_copy);\n\n // NB. C99 (which modern Linux and OS X follow) says vsnprintf\n // failure returns the length it would have needed. But older\n // glibc and current Windows return -1 for failure, i.e., not\n // telling us how much was needed.\n\n if (needed <= (int)size && needed >= 0) {\n // It fit fine so we're done.\n return std::string (buf, (size_t) needed);\n }\n\n // vsnprintf reported that it wanted to write more characters\n // than we allotted. So try again using a dynamic buffer. This\n // doesn't happen very often if we chose our initial size well.\n size = (needed > 0) ? (needed+1) : (size*2);\n dynamicbuf.resize (size);\n buf = &dynamicbuf[0];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69915,
"author": "Jan de Vos",
"author_id": 11215,
"author_profile": "https://Stackoverflow.com/users/11215",
"pm_score": 1,
"selected": false,
"text": "<p>The following might be an alternative solution:</p>\n\n<pre><code>void A::printto(ostream outputstream) {\n char buffer[100];\n string s = \"stuff\";\n sprintf(buffer, \"some %s\", s);\n outputstream << buffer << endl;\n b.printto(outputstream);\n}\n</code></pre>\n\n<p>(<code>B::printto</code> similar), and define</p>\n\n<pre><code>void A::print(FILE *f) {\n printto(ofstream(f));\n}\n\nstring A::to_str() {\n ostringstream os;\n printto(os);\n return os.str();\n}\n</code></pre>\n\n<p>Of course, you should really use snprintf instead of sprintf to avoid buffer overflows. You could also selectively change the more risky sprintfs to << format, to be safer and yet change as little as possible.</p>\n"
},
{
"answer_id": 70233,
"author": "Kevin",
"author_id": 6386,
"author_profile": "https://Stackoverflow.com/users/6386",
"pm_score": 1,
"selected": false,
"text": "<p>You should try the Loki library's SafeFormat header file (<a href=\"http://loki-lib.sourceforge.net/index.php?n=Idioms.Printf\" rel=\"nofollow noreferrer\">http://loki-lib.sourceforge.net/index.php?n=Idioms.Printf</a>). It's similar to boost's string format library, but keeps the syntax of the printf(...) functions.</p>\n\n<p>I hope this helps!</p>\n"
},
{
"answer_id": 56267043,
"author": "vitaut",
"author_id": 471164,
"author_profile": "https://Stackoverflow.com/users/471164",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://github.com/fmtlib/fmt\" rel=\"nofollow noreferrer\">The {fmt} library</a> provides <code>fmt::sprintf</code> function that performs <code>printf</code>-compatible formatting (including positional arguments according to <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/printf.html\" rel=\"nofollow noreferrer\">POSIX specification</a>) and returns the result as <code>std::string</code>:</p>\n\n<pre><code>std::string s = fmt::sprintf(\"The answer is %d.\", 42);\n</code></pre>\n\n<p><strong>Disclaimer</strong>: I'm the author of this library.</p>\n"
},
{
"answer_id": 73359248,
"author": "dgnuff",
"author_id": 4022617,
"author_profile": "https://Stackoverflow.com/users/4022617",
"pm_score": 0,
"selected": false,
"text": "<p>Very very late to the party, but here's how I'd attack this problem.</p>\n<p>1: Use <code>pipe(2)</code> to open a pipe.</p>\n<p>2: Use <code>fdopen(3)</code> to convert the write fd from the pipe to a <code>FILE *</code>.</p>\n<p>3: Hand that <code>FILE *</code> to <code>A::print()</code>.</p>\n<p>4: Use <code>read(2)</code> to pull bufferloads of data, e.g. 1K or more at a time from the read fd.</p>\n<p>5: Append each bufferload of data to the target <code>std::string</code></p>\n<p>6: Repeat steps 4 and 5 as needed to complete the task.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8146/"
]
| I am working with an open-source UNIX tool that is implemented in C++, and I need to change some code to get it to do what I want. I would like to make the smallest possible change in hopes of getting my patch accepted upstream. Solutions that are implementable in standard C++ and do not create more external dependencies are preferred.
Here is my problem. I have a C++ class -- let's call it "A" -- that currently uses fprintf() to print its heavily formatted data structures to a file pointer. In its print function, it also recursively calls the identically defined print functions of several member classes ("B" is an example). There is another class C that has a member std::string "foo" that needs to be set to the print() results of an instance of A. Think of it as a to\_str() member function for A.
In pseudocode:
```
class A {
public:
...
void print(FILE* f);
B b;
...
};
...
void A::print(FILE *f)
{
std::string s = "stuff";
fprintf(f, "some %s", s);
b.print(f);
}
class C {
...
std::string foo;
bool set_foo(std::str);
...
}
...
A a = new A();
C c = new C();
...
// wish i knew how to write A's to_str()
c.set_foo(a.to_str());
```
I should mention that C is fairly stable, but A and B (and the rest of A's dependents) are in a state of flux, so the less code changes necessary the better. The current print(FILE\* F) interface also needs to be preserved. I have considered several approaches to implementing A::to\_str(), each with advantages and disadvantages:
1. Change the calls to fprintf() to sprintf()
* I wouldn't have to rewrite any format strings
* print() could be reimplemented as: fprint(f, this.to\_str());
* But I would need to manually allocate char[]s, merge a lot of c strings , and finally convert the character array to a std::string
2. Try to catch the results of a.print() in a string stream
* I would have to convert all of the format strings to << output format. There are hundreds of fprintf()s to convert :-{
* print() would have to be rewritten because there is no standard way that I know of to create an output stream from a UNIX file handle (though [this guy says it may be possible](http://synflood.at/blog/index.php?/archives/456-One-word-of-warning-about-stdio_filebuf.html)).
3. Use Boost's string [format library](http://www.boost.org/doc/libs/1_36_0/libs/format/doc/format.html)
* More external dependencies. Yuck.
* Format's syntax is different enough from printf() to be annoying:printf(format\_str, args) -> cout << boost::format(format\_str) % arg1 % arg2 % etc
4. Use Qt's [QString::asprintf()](https://doc.qt.io/qt-5/qstring.html#asprintf%3E)
* A different external dependency.
So, have I exhausted all possible options? If so, which do you think is my best bet? If not, what have I overlooked?
Thanks. | I am using #3: the boost string format library - but I have to admit that I've never had any problem with the differences in format specifications.
Works like a charm for me - and the external dependencies could be worse (a very stable library)
Edited: adding an example how to use boost::format instead of printf:
```
sprintf(buffer, "This is a string with some %s and %d numbers", "strings", 42);
```
would be something like this with the boost::format library:
```
string = boost::str(boost::format("This is a string with some %s and %d numbers") %"strings" %42);
```
Hope this helps clarify the usage of boost::format
I've used boost::format as a sprintf / printf replacement in 4 or 5 applications (writing formatted strings to files, or custom output to logfiles) and never had problems with format differences. There may be some (more or less obscure) format specifiers which are differently - but I never had a problem.
In contrast I had some format specifications I couldn't really do with streams (as much as I remember) |
69,743 | <p>I am trying to populate a string with a double value using a <code>sprintf</code> like this:</p>
<pre><code>sprintf(S, "%f", val);
</code></pre>
<p>But the precision is being cut off to six decimal places. I need about 10 decimal places for the precision.</p>
<p>How can that be achieved?</p>
| [
{
"answer_id": 69747,
"author": "Yann Ramin",
"author_id": 9167,
"author_profile": "https://Stackoverflow.com/users/9167",
"pm_score": 3,
"selected": false,
"text": "<p>What you want is a modifier:</p>\n\n<pre><code>sprintf(S, \"%.10f\", val);\n</code></pre>\n\n<p>man sprintf will have many more details on format specifiers. </p>\n"
},
{
"answer_id": 69758,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 4,
"selected": true,
"text": "<p>%[width].[precision]</p>\n\n<p>Width should include the decimal point.</p>\n\n<p>%8.2 means 8 characters wide; 5 digits before the point and 2 after. One character is reserved for the point.</p>\n\n<p>5 + 1 + 2 = 8</p>\n"
},
{
"answer_id": 69771,
"author": "Jegschemesch",
"author_id": 1586,
"author_profile": "https://Stackoverflow.com/users/1586",
"pm_score": 1,
"selected": false,
"text": "<p>For a more complete reference, see the <a href=\"http://en.wikipedia.org/wiki/Printf#printf_format_placeholders\" rel=\"nofollow noreferrer\">Wikipedia <em>printf</em> article, section \"printf format placeholders\"</a> and <a href=\"http://en.wikipedia.org/wiki/Printf#1970s:_C.2C_Lisp\" rel=\"nofollow noreferrer\">a good example on the same page</a>.</p>\n"
},
{
"answer_id": 69775,
"author": "dajobe",
"author_id": 11177,
"author_profile": "https://Stackoverflow.com/users/11177",
"pm_score": 1,
"selected": false,
"text": "<p>Take care - the output of sprintf will vary via C locale. This may or may not be what you want. See LC_NUMERIC in the locale docs/man pages.</p>\n"
},
{
"answer_id": 75791,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 1,
"selected": false,
"text": "<p><code>%f</code> is for float values.</p>\n\n<p>Try using <code>%lf</code> instead. It is designed for doubles (which used to be called long floats).</p>\n\n<p><strong>double x = 3.14159265</strong>; <br/>\n<strong>printf(\"15.10lf\\n\", x);</strong></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11212/"
]
| I am trying to populate a string with a double value using a `sprintf` like this:
```
sprintf(S, "%f", val);
```
But the precision is being cut off to six decimal places. I need about 10 decimal places for the precision.
How can that be achieved? | %[width].[precision]
Width should include the decimal point.
%8.2 means 8 characters wide; 5 digits before the point and 2 after. One character is reserved for the point.
5 + 1 + 2 = 8 |
69,748 | <p>Another easy one hopefully.</p>
<p>Let's say I have a collection like this:</p>
<pre><code>List<DateTime> allDates;
</code></pre>
<p>I want to turn that into </p>
<pre><code>List<List<DateTime>> dividedDates;
</code></pre>
<p>where each List in 'dividedDates' contains all of the dates in 'allDates' that belong to a distinct year.</p>
<p>Is there a bit of LINQ trickery that my tired mind can't pick out right now?</p>
<p><strong>Solution</strong></p>
<p>The Accepted Answer is correct.</p>
<p>Thanks, I don't think I was aware of the 'into' bit of GroupBy and I was trying to use the .GroupBy() sort of methods rather than the SQL like syntax. And thanks for confirming the ToList() amendment and including it in the Accepted Answer :-)</p>
| [
{
"answer_id": 69769,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<pre><code>var q = from date in allDates \n group date by date.Year into datesByYear\n select datesByYear.ToList();\nq.ToList(); //returns List<List<DateTime>>\n</code></pre>\n"
},
{
"answer_id": 72171,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 3,
"selected": false,
"text": "<p>Here's the methods form.</p>\n\n<pre>\nallDates\n .GroupBy(d => d.Year)\n .Select(g => g.ToList())\n .ToList();\n</pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
]
| Another easy one hopefully.
Let's say I have a collection like this:
```
List<DateTime> allDates;
```
I want to turn that into
```
List<List<DateTime>> dividedDates;
```
where each List in 'dividedDates' contains all of the dates in 'allDates' that belong to a distinct year.
Is there a bit of LINQ trickery that my tired mind can't pick out right now?
**Solution**
The Accepted Answer is correct.
Thanks, I don't think I was aware of the 'into' bit of GroupBy and I was trying to use the .GroupBy() sort of methods rather than the SQL like syntax. And thanks for confirming the ToList() amendment and including it in the Accepted Answer :-) | ```
var q = from date in allDates
group date by date.Year into datesByYear
select datesByYear.ToList();
q.ToList(); //returns List<List<DateTime>>
``` |
69,761 | <p>I'd like to to associate a file extension to the current executable in C#.
This way when the user clicks on the file afterwards in explorer, it'll run my executable with the given file as the first argument.
Ideally it'd also set the icon for the given file extensions to the icon for my executable.
Thanks all.</p>
| [
{
"answer_id": 69805,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 2,
"selected": false,
"text": "<p>The file associations are defined in the registry under HKEY_CLASSES_ROOT.</p>\n\n<p>There's a VB.NET example <a href=\"http://www.devx.com/vb2themax/Tip/19554?type=kbArticle&trk=MSCP\" rel=\"nofollow noreferrer\">here</a> that I'm you can port easily to C#.</p>\n"
},
{
"answer_id": 69826,
"author": "X-Cubed",
"author_id": 10808,
"author_profile": "https://Stackoverflow.com/users/10808",
"pm_score": 5,
"selected": false,
"text": "<p>There doesn't appear to be a .Net API for directly managing file associations but you can use the Registry classes for reading and writing the keys you need to.</p>\n\n<p>You'll need to create a key under HKEY_CLASSES_ROOT with the name set to your file extension (eg: \".txt\"). Set the default value of this key to a unique name for your file type, such as \"Acme.TextFile\". Then create another key under HKEY_CLASSES_ROOT with the name set to \"Acme.TextFile\". Add a subkey called \"DefaultIcon\" and set the default value of the key to the file containing the icon you wish to use for this file type. Add another sibling called \"shell\". Under the \"shell\" key, add a key for each action you wish to have available via the Explorer context menu, setting the default value for each key to the path to your executable followed by a space and \"%1\" to represent the path to the file selected.</p>\n\n<p>For instance, here's a sample registry file to create an association between .txt files and EmEditor:</p>\n\n<pre>\nWindows Registry Editor Version 5.00\n\n[HKEY_CLASSES_ROOT\\.txt]\n@=\"emeditor.txt\"\n\n[HKEY_CLASSES_ROOT\\emeditor.txt]\n@=\"Text Document\"\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\DefaultIcon]\n@=\"%SystemRoot%\\\\SysWow64\\\\imageres.dll,-102\"\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell]\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\open]\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\open\\command]\n@=\"\\\"C:\\\\Program Files\\\\EmEditor\\\\EMEDITOR.EXE\\\" \\\"%1\\\"\"\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\print]\n\n[HKEY_CLASSES_ROOT\\emeditor.txt\\shell\\print\\command]\n@=\"\\\"C:\\\\Program Files\\\\EmEditor\\\\EMEDITOR.EXE\\\" /p \\\"%1\\\"\"\n</pre>\n"
},
{
"answer_id": 69863,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 5,
"selected": false,
"text": "<p>Also, if you decide to go the registry way, keep in mind that current user associations are under <strong>HKEY_CURRENT_USER\\Software\\Classes</strong>. It might be better to add your application there instead of local machine classes.</p>\n\n<p>If your program will be run by limited users, you won't be able to modify CLASSES_ROOT anyway.</p>\n"
},
{
"answer_id": 899360,
"author": "Paul J",
"author_id": 111237,
"author_profile": "https://Stackoverflow.com/users/111237",
"pm_score": 3,
"selected": false,
"text": "<p>There may be specific reasons why you choose not to use an install package for your project but an install package is a great place to easily perform application configuration tasks such registering file extensions, adding desktop shortcuts, etc.</p>\n\n<p>Here's how to create file extension association using the built-in Visual Studio Install tools:</p>\n\n<ol>\n<li><p>Within your existing C# solution, add a new project and select project type as <code>Other Project Types</code> -> <code>Setup and Deployment</code> -> <code>Setup Project</code> (or try the Setup Wizard)</p></li>\n<li><p>Configure your installer (plenty of existing docs for this if you need help)</p></li>\n<li><p>Right-click the setup project in the Solution explorer, select <code>View</code> -> <code>File Types</code>, and then add the extension that you want to register along with the program to run it.</p></li>\n</ol>\n\n<p>This method has the added benefit of cleaning up after itself if a user runs the uninstall for your application.</p>\n"
},
{
"answer_id": 1327322,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "<p>If you use ClickOnce deployment, this is all handled for you (at least, in VS2008 SP1); simply:</p>\n\n<ul>\n<li>Project Properties</li>\n<li>Publish</li>\n<li>Options</li>\n<li>File Associatons</li>\n<li>(add whatever you need)</li>\n</ul>\n\n<p>(note that it must be full-trust, target .NET 3.5, and be set for offline usage)</p>\n\n<p>See also MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/bb892924.aspx\" rel=\"noreferrer\">How to: Create File Associations For a ClickOnce Application</a></p>\n"
},
{
"answer_id": 28585998,
"author": "Strong84",
"author_id": 1422691,
"author_profile": "https://Stackoverflow.com/users/1422691",
"pm_score": 3,
"selected": false,
"text": "<p>To be specific about the \"Windows Registry\" way:</p>\n\n<p>I create keys under <strong>HKEY_CURRENT_USER\\Software\\Classes</strong> (like Ishmaeel said)</p>\n\n<p>and follow the instruction answered by X-Cubed.</p>\n\n<p>The sample code looks like:</p>\n\n<pre><code>private void Create_abc_FileAssociation()\n{\n /***********************************/\n /**** Key1: Create \".abc\" entry ****/\n /***********************************/\n Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\"Software\", true);\n\n key1.CreateSubKey(\"Classes\");\n key1 = key1.OpenSubKey(\"Classes\", true);\n\n key1.CreateSubKey(\".abc\");\n key1 = key1.OpenSubKey(\".abc\", true);\n key1.SetValue(\"\", \"DemoKeyValue\"); // Set default key value\n\n key1.Close();\n\n /*******************************************************/\n /**** Key2: Create \"DemoKeyValue\\DefaultIcon\" entry ****/\n /*******************************************************/\n Microsoft.Win32.RegistryKey key2 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\"Software\", true);\n\n key2.CreateSubKey(\"Classes\");\n key2 = key2.OpenSubKey(\"Classes\", true);\n\n key2.CreateSubKey(\"DemoKeyValue\");\n key2 = key2.OpenSubKey(\"DemoKeyValue\", true);\n\n key2.CreateSubKey(\"DefaultIcon\");\n key2 = key2.OpenSubKey(\"DefaultIcon\", true);\n key2.SetValue(\"\", \"\\\"\" + \"(The icon path you desire)\" + \"\\\"\"); // Set default key value\n\n key2.Close();\n\n /**************************************************************/\n /**** Key3: Create \"DemoKeyValue\\shell\\open\\command\" entry ****/\n /**************************************************************/\n Microsoft.Win32.RegistryKey key3 = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(\"Software\", true);\n\n key3.CreateSubKey(\"Classes\");\n key3 = key3.OpenSubKey(\"Classes\", true);\n\n key3.CreateSubKey(\"DemoKeyValue\");\n key3 = key3.OpenSubKey(\"DemoKeyValue\", true);\n\n key3.CreateSubKey(\"shell\");\n key3 = key3.OpenSubKey(\"shell\", true);\n\n key3.CreateSubKey(\"open\");\n key3 = key3.OpenSubKey(\"open\", true);\n\n key3.CreateSubKey(\"command\");\n key3 = key3.OpenSubKey(\"command\", true);\n key3.SetValue(\"\", \"\\\"\" + \"(The application path you desire)\" + \"\\\"\" + \" \\\"%1\\\"\"); // Set default key value\n\n key3.Close();\n}\n</code></pre>\n\n<p>Just show you guys a quick demo, very easy to understand. You could modify those key values and everything is good to go.</p>\n"
},
{
"answer_id": 44816888,
"author": "Kirill Osenkov",
"author_id": 37899,
"author_profile": "https://Stackoverflow.com/users/37899",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a complete example:</p>\n\n<pre><code>public class FileAssociation\n{\n public string Extension { get; set; }\n public string ProgId { get; set; }\n public string FileTypeDescription { get; set; }\n public string ExecutableFilePath { get; set; }\n}\n\npublic class FileAssociations\n{\n // needed so that Explorer windows get refreshed after the registry is updated\n [System.Runtime.InteropServices.DllImport(\"Shell32.dll\")]\n private static extern int SHChangeNotify(int eventId, int flags, IntPtr item1, IntPtr item2);\n\n private const int SHCNE_ASSOCCHANGED = 0x8000000;\n private const int SHCNF_FLUSH = 0x1000;\n\n public static void EnsureAssociationsSet()\n {\n var filePath = Process.GetCurrentProcess().MainModule.FileName;\n EnsureAssociationsSet(\n new FileAssociation\n {\n Extension = \".binlog\",\n ProgId = \"MSBuildBinaryLog\",\n FileTypeDescription = \"MSBuild Binary Log\",\n ExecutableFilePath = filePath\n },\n new FileAssociation\n {\n Extension = \".buildlog\",\n ProgId = \"MSBuildStructuredLog\",\n FileTypeDescription = \"MSBuild Structured Log\",\n ExecutableFilePath = filePath\n });\n }\n\n public static void EnsureAssociationsSet(params FileAssociation[] associations)\n {\n bool madeChanges = false;\n foreach (var association in associations)\n {\n madeChanges |= SetAssociation(\n association.Extension,\n association.ProgId,\n association.FileTypeDescription,\n association.ExecutableFilePath);\n }\n\n if (madeChanges)\n {\n SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_FLUSH, IntPtr.Zero, IntPtr.Zero);\n }\n }\n\n public static bool SetAssociation(string extension, string progId, string fileTypeDescription, string applicationFilePath)\n {\n bool madeChanges = false;\n madeChanges |= SetKeyDefaultValue(@\"Software\\Classes\\\" + extension, progId);\n madeChanges |= SetKeyDefaultValue(@\"Software\\Classes\\\" + progId, fileTypeDescription);\n madeChanges |= SetKeyDefaultValue($@\"Software\\Classes\\{progId}\\shell\\open\\command\", \"\\\"\" + applicationFilePath + \"\\\" \\\"%1\\\"\");\n return madeChanges;\n }\n\n private static bool SetKeyDefaultValue(string keyPath, string value)\n {\n using (var key = Registry.CurrentUser.CreateSubKey(keyPath))\n {\n if (key.GetValue(null) as string != value)\n {\n key.SetValue(null, value);\n return true;\n }\n }\n\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 46900103,
"author": "Mike",
"author_id": 1943229,
"author_profile": "https://Stackoverflow.com/users/1943229",
"pm_score": 0,
"selected": false,
"text": "<p>There are two cmd tools that have been around since Windows 7 which make it very easy to create simple file associations. They are <a href=\"https://technet.microsoft.com/en-us/library/cc770920(v=ws.11).aspx\" rel=\"nofollow noreferrer\">assoc</a> and <a href=\"https://technet.microsoft.com/en-us/library/cc771394(v=ws.11).aspx\" rel=\"nofollow noreferrer\">ftype</a>. Here's a basic explanation of each command.</p>\n\n<ul>\n<li><a href=\"https://technet.microsoft.com/en-us/library/cc770920(v=ws.11).aspx\" rel=\"nofollow noreferrer\">Assoc</a> - associates a file extension (like '.txt') with a \"file type.\"</li>\n<li><a href=\"https://technet.microsoft.com/en-us/library/cc771394(v=ws.11).aspx\" rel=\"nofollow noreferrer\">FType</a> - defines an executable to run when the user opens a given \"file type.\"</li>\n</ul>\n\n<p>Note that these are cmd tools and not executable files (exe). This means that they can only be run in a cmd window, or by using ShellExecute with \"cmd /c assoc.\" You can learn more about them at the links or by typing \"assoc /?\" and \"ftype /?\" at a cmd prompt. </p>\n\n<p>So to associate an application with a .bob extension, you could open a cmd window (WindowKey+R, type cmd, press enter) and run the following:</p>\n\n<pre><code>assoc .bob=BobFile\nftype BobFile=c:\\temp\\BobView.exe \"%1\"\n</code></pre>\n\n<p>This is much simpler than messing with the registry and it is more likely to work in future windows version. </p>\n\n<p>Wrapping it up, here is a C# function to create a file association:</p>\n\n<pre><code>public static int setFileAssociation(string[] extensions, string fileType, string openCommandString) {\n int v = execute(\"cmd\", \"/c ftype \" + fileType + \"=\" + openCommandString);\n foreach (string ext in extensions) {\n v = execute(\"cmd\", \"/c assoc \" + ext + \"=\" + fileType);\n if (v != 0) return v;\n }\n return v;\n}\npublic static int execute(string exeFilename, string arguments) {\n ProcessStartInfo startInfo = new ProcessStartInfo();\n startInfo.CreateNoWindow = false;\n startInfo.UseShellExecute = true;\n startInfo.FileName = exeFilename;\n startInfo.WindowStyle = ProcessWindowStyle.Hidden;\n startInfo.Arguments = arguments;\n try {\n using (Process exeProcess = Process.Start(startInfo)) {\n exeProcess.WaitForExit();\n return exeProcess.ExitCode;\n }\n } catch {\n return 1;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46902772,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The code below is a function the should work, it adds the required values in the windows registry. Usually i run SelfCreateAssociation(\".abc\") in my executable. (form constructor or onload or onshown) It will update the registy entry for the current user, everytime the executable is executed. (good for debugging, if you have some changes).\nIf you need detailed information about the registry keys involved check out this MSDN link.</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/dd758090(v=vs.85).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/windows/desktop/dd758090(v=vs.85).aspx</a> </p>\n\n<p>To get more information about the general ClassesRoot registry key. See this MSDN article.</p>\n\n<p><a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/ms724475(v=vs.85).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/windows/desktop/ms724475(v=vs.85).aspx</a></p>\n\n<pre><code>public enum KeyHiveSmall\n{\n ClassesRoot,\n CurrentUser,\n LocalMachine,\n}\n\n/// <summary>\n/// Create an associaten for a file extension in the windows registry\n/// CreateAssociation(@\"vendor.application\",\".tmf\",\"Tool file\",@\"C:\\Windows\\SYSWOW64\\notepad.exe\",@\"%SystemRoot%\\SYSWOW64\\notepad.exe,0\");\n/// </summary>\n/// <param name=\"ProgID\">e.g. vendor.application</param>\n/// <param name=\"extension\">e.g. .tmf</param>\n/// <param name=\"description\">e.g. Tool file</param>\n/// <param name=\"application\">e.g. @\"C:\\Windows\\SYSWOW64\\notepad.exe\"</param>\n/// <param name=\"icon\">@\"%SystemRoot%\\SYSWOW64\\notepad.exe,0\"</param>\n/// <param name=\"hive\">e.g. The user-specific settings have priority over the computer settings. KeyHive.LocalMachine need admin rights</param>\npublic static void CreateAssociation(string ProgID, string extension, string description, string application, string icon, KeyHiveSmall hive = KeyHiveSmall.CurrentUser)\n{\n RegistryKey selectedKey = null;\n\n switch (hive)\n {\n case KeyHiveSmall.ClassesRoot:\n Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(extension).SetValue(\"\", ProgID);\n selectedKey = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey(ProgID);\n break;\n\n case KeyHiveSmall.CurrentUser:\n Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@\"Software\\Classes\\\" + extension).SetValue(\"\", ProgID);\n selectedKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(@\"Software\\Classes\\\" + ProgID);\n break;\n\n case KeyHiveSmall.LocalMachine:\n Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@\"Software\\Classes\\\" + extension).SetValue(\"\", ProgID);\n selectedKey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@\"Software\\Classes\\\" + ProgID);\n break;\n }\n\n if (selectedKey != null)\n {\n if (description != null)\n {\n selectedKey.SetValue(\"\", description);\n }\n if (icon != null)\n {\n selectedKey.CreateSubKey(\"DefaultIcon\").SetValue(\"\", icon, RegistryValueKind.ExpandString);\n selectedKey.CreateSubKey(@\"Shell\\Open\").SetValue(\"icon\", icon, RegistryValueKind.ExpandString);\n }\n if (application != null)\n {\n selectedKey.CreateSubKey(@\"Shell\\Open\\command\").SetValue(\"\", \"\\\"\" + application + \"\\\"\" + \" \\\"%1\\\"\", RegistryValueKind.ExpandString);\n }\n }\n selectedKey.Flush();\n selectedKey.Close();\n}\n\n /// <summary>\n /// Creates a association for current running executable\n /// </summary>\n /// <param name=\"extension\">e.g. .tmf</param>\n /// <param name=\"hive\">e.g. KeyHive.LocalMachine need admin rights</param>\n /// <param name=\"description\">e.g. Tool file. Displayed in explorer</param>\n public static void SelfCreateAssociation(string extension, KeyHiveSmall hive = KeyHiveSmall.CurrentUser, string description = \"\")\n {\n string ProgID = System.Reflection.Assembly.GetExecutingAssembly().EntryPoint.DeclaringType.FullName;\n string FileLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;\n CreateAssociation(ProgID, extension, description, FileLocation, FileLocation + \",0\", hive);\n }\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'd like to to associate a file extension to the current executable in C#.
This way when the user clicks on the file afterwards in explorer, it'll run my executable with the given file as the first argument.
Ideally it'd also set the icon for the given file extensions to the icon for my executable.
Thanks all. | There doesn't appear to be a .Net API for directly managing file associations but you can use the Registry classes for reading and writing the keys you need to.
You'll need to create a key under HKEY\_CLASSES\_ROOT with the name set to your file extension (eg: ".txt"). Set the default value of this key to a unique name for your file type, such as "Acme.TextFile". Then create another key under HKEY\_CLASSES\_ROOT with the name set to "Acme.TextFile". Add a subkey called "DefaultIcon" and set the default value of the key to the file containing the icon you wish to use for this file type. Add another sibling called "shell". Under the "shell" key, add a key for each action you wish to have available via the Explorer context menu, setting the default value for each key to the path to your executable followed by a space and "%1" to represent the path to the file selected.
For instance, here's a sample registry file to create an association between .txt files and EmEditor:
```
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.txt]
@="emeditor.txt"
[HKEY_CLASSES_ROOT\emeditor.txt]
@="Text Document"
[HKEY_CLASSES_ROOT\emeditor.txt\DefaultIcon]
@="%SystemRoot%\\SysWow64\\imageres.dll,-102"
[HKEY_CLASSES_ROOT\emeditor.txt\shell]
[HKEY_CLASSES_ROOT\emeditor.txt\shell\open]
[HKEY_CLASSES_ROOT\emeditor.txt\shell\open\command]
@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" \"%1\""
[HKEY_CLASSES_ROOT\emeditor.txt\shell\print]
[HKEY_CLASSES_ROOT\emeditor.txt\shell\print\command]
@="\"C:\\Program Files\\EmEditor\\EMEDITOR.EXE\" /p \"%1\""
``` |
69,766 | <p>I'm working on VS 2005 and something has gone wrong on my machine. Suddenly, out of the blue, I can no longer build deployment files.
The build message is:</p>
<pre><code>ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
</code></pre>
<p>A quick Google search brings up the last 2 lines, but nobody in cyberspace has ever reported the first message before. (Hooray! I'm first at SOMETHING on the 'net!)</p>
<p>Other machines in my office are able to do the build.
My machine has been able to do the build before. I have no idea what changed that upset the delicate balance of things on my box.
I have also tried all the traditional rituals i.e. closing Visual Studio, blowing away all the bin and obj folders, rebooting, etc. to no avail.</p>
<p>For simplicity's sake, I created a little "Hello World" app with a deployment file.
Herewith the build output:</p>
<pre><code>------ Build started: Project: HelloWorld, Configuration: Debug Any CPU ------
HelloWorld -> C:\Vault\Multi Client\Tests\HelloWorld\HelloWorld\bin\Debug\HelloWorld.exe
------ Starting pre-build validation for project 'HelloWorldSetup' ------
------ Pre-build validation for project 'HelloWorldSetup' completed ------
------ Build started: Project: HelloWorldSetup, Configuration: Debug ------
Building file 'C:\Vault\Multi Client\Tests\HelloWorld\HelloWorldSetup\Debug\HelloWorldSetup.msi'...
ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
========== Build: 1 succeeded or up-to-date, 1 failed, 0 skipped ==========
</code></pre>
<p>I am using:</p>
<ul>
<li>MS Visual Studio 2005 Version 8.0.50727.762 (SP .050727-7600) </li>
<li>.NET Framework Version 2.0.50727 </li>
<li>OS: Windows XP Pro</li>
</ul>
<p>Again, I have no idea what changed. All I know is that one day everything was working fine; the next day I suddenly can't do any deployment builds at all (though all other projects still compile fine).</p>
<p>I posted <a href="http://social.msdn.microsoft.com/forums/en-US/vssetup/thread/240c82e9-1696-4618-846c-aaae21427a52/" rel="nofollow noreferrer">this on MSDN</a> about a month ago, and they don't seem to know what's going on, either.</p>
<p>Anyone have any idea what this is about?</p>
<hr>
<p>@Brad Wilson: Thanks, but if you read my original post, you'll see that I already did start an entire solution from scratch, and that didn't help.</p>
<hr>
<p>@deemer: I went through all the pain of uninstalling and reinstalling, even though I didn't have your recommended reading while waiting... and - Misery! - still the same error reappears. It seems that my computer has somehow been branded as unsuitable for doing deployment builds ever again.</p>
<p>Does anyone have any idea where this "secret switch" might be?</p>
| [
{
"answer_id": 69809,
"author": "deemer",
"author_id": 11192,
"author_profile": "https://Stackoverflow.com/users/11192",
"pm_score": 1,
"selected": false,
"text": "<p>If it doesn't build only on the one machine, then either you've managed to make that machine different, or the VS2005 install is corrupted. If you take the error message at face-value, then the problem is probably the latter. Try running the repair feature of the VS2005 installer, or failing that, reinstall VS2005. Ender's Game is a good book to read while you're waiting :-|.</p>\n"
},
{
"answer_id": 69810,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, that error is the general catch-all error handler for setup projects. As a wild guess, I'd say that maybe the setup project got corrupted somehow, which is causing the \"Invalid Syntax\" error.</p>\n\n<p>Try creating a new setup project and start by doing things one step at a time, and see if you can reproduce the problem (or, hopefully, avoid it altogether).</p>\n"
},
{
"answer_id": 126566,
"author": "Shaul Behr",
"author_id": 7850,
"author_profile": "https://Stackoverflow.com/users/7850",
"pm_score": 2,
"selected": true,
"text": "<p><strong>SOLUTION!</strong><br>\nThanks to Michael Bleifer of Microsoft support - I installed .NET 2.0 SP1, and the problem was solved!</p>\n"
},
{
"answer_id": 8539010,
"author": "Adam Caviness",
"author_id": 9130,
"author_profile": "https://Stackoverflow.com/users/9130",
"pm_score": 1,
"selected": false,
"text": "<p>I had a similar issue (<code>An error occurred generating a bootstrapper: Unable to finish updating resource for [YourAssemblyPath] with error 80070005</code>). This error occurred on subsequent builds of the a setup project (first build after setup project creation always worked for me). It turned out to be related to both my source control client(Sourcegear Vault) and MS Security Essentials. I added Sourcegear's VaultGUIClient.exe as an Excluded Process in Security Essentials.</p>\n\n<hr>\n\n<ul>\n<li>Win 7 Ult x64 </li>\n<li>VS2010 Prem SP1 </li>\n<li>Sourcegear Vault 5.0.4 (18845) </li>\n<li>Security Essentials Version: 2.1.1116.0</li>\n</ul>\n"
},
{
"answer_id": 15834006,
"author": "Rama",
"author_id": 1620537,
"author_profile": "https://Stackoverflow.com/users/1620537",
"pm_score": 2,
"selected": false,
"text": "<p>Disable bootstrapping</p>\n\n<pre><code>In Solution Explorer, select the deployment project.\n\nOn the Project menu, click Properties.\n\nIn the Property Pages dialog box, expand the Configuration Properties node, and then select the Build property page.\n\nClick the Prerequisites button.\n\nIn the Prerequisites dialog box, clear the Create setup program to install prerequisite components check box, and then click OK. \n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7850/"
]
| I'm working on VS 2005 and something has gone wrong on my machine. Suddenly, out of the blue, I can no longer build deployment files.
The build message is:
```
ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
```
A quick Google search brings up the last 2 lines, but nobody in cyberspace has ever reported the first message before. (Hooray! I'm first at SOMETHING on the 'net!)
Other machines in my office are able to do the build.
My machine has been able to do the build before. I have no idea what changed that upset the delicate balance of things on my box.
I have also tried all the traditional rituals i.e. closing Visual Studio, blowing away all the bin and obj folders, rebooting, etc. to no avail.
For simplicity's sake, I created a little "Hello World" app with a deployment file.
Herewith the build output:
```
------ Build started: Project: HelloWorld, Configuration: Debug Any CPU ------
HelloWorld -> C:\Vault\Multi Client\Tests\HelloWorld\HelloWorld\bin\Debug\HelloWorld.exe
------ Starting pre-build validation for project 'HelloWorldSetup' ------
------ Pre-build validation for project 'HelloWorldSetup' completed ------
------ Build started: Project: HelloWorldSetup, Configuration: Debug ------
Building file 'C:\Vault\Multi Client\Tests\HelloWorld\HelloWorldSetup\Debug\HelloWorldSetup.msi'...
ERROR: An error occurred generating a bootstrapper: Invalid syntax.
ERROR: General failure building bootstrapper
ERROR: Unrecoverable build error
========== Build: 1 succeeded or up-to-date, 1 failed, 0 skipped ==========
```
I am using:
* MS Visual Studio 2005 Version 8.0.50727.762 (SP .050727-7600)
* .NET Framework Version 2.0.50727
* OS: Windows XP Pro
Again, I have no idea what changed. All I know is that one day everything was working fine; the next day I suddenly can't do any deployment builds at all (though all other projects still compile fine).
I posted [this on MSDN](http://social.msdn.microsoft.com/forums/en-US/vssetup/thread/240c82e9-1696-4618-846c-aaae21427a52/) about a month ago, and they don't seem to know what's going on, either.
Anyone have any idea what this is about?
---
@Brad Wilson: Thanks, but if you read my original post, you'll see that I already did start an entire solution from scratch, and that didn't help.
---
@deemer: I went through all the pain of uninstalling and reinstalling, even though I didn't have your recommended reading while waiting... and - Misery! - still the same error reappears. It seems that my computer has somehow been branded as unsuitable for doing deployment builds ever again.
Does anyone have any idea where this "secret switch" might be? | **SOLUTION!**
Thanks to Michael Bleifer of Microsoft support - I installed .NET 2.0 SP1, and the problem was solved! |
69,768 | <p>Mac OS X ships with apache pre-installed, but the files are in non-standard locations. This question is a place to collect information about where configuration files live, and how to tweak the apache installation to do things like serve php pages.</p>
| [
{
"answer_id": 69784,
"author": "ctcherry",
"author_id": 10322,
"author_profile": "https://Stackoverflow.com/users/10322",
"pm_score": 5,
"selected": true,
"text": "<p>Apache Config file is: /private/etc/apache2/httpd.conf</p>\n\n<p>Default DocumentRoot is: /Library/Webserver/Documents/</p>\n\n<p>To enable PHP, at around line 114 (maybe) in the /private/etc/apache2/httpd.conf file is the following line:</p>\n\n<pre><code>#LoadModule php5_module libexec/apache2/libphp5.so\n</code></pre>\n\n<p>Remove the pound sign to uncomment the line so now it looks like this:</p>\n\n<pre><code>LoadModule php5_module libexec/apache2/libphp5.so\n</code></pre>\n\n<p>Restart Apache: System Preferences -> Sharing -> Un-check \"Web Sharing\" and re-check it. \n<strong>OR</strong> </p>\n\n<pre><code>$ sudo apachectl restart\n</code></pre>\n"
},
{
"answer_id": 69798,
"author": "Larry OBrien",
"author_id": 10116,
"author_profile": "https://Stackoverflow.com/users/10116",
"pm_score": 1,
"selected": false,
"text": "<p>httpd.conf is in /private/etc/apache2</p>\n\n<p>Enable PHP by uncommenting line:</p>\n\n<pre><code> LoadModule php5_module libexec/apache2/libphp5.so\n</code></pre>\n"
},
{
"answer_id": 71560,
"author": "Patrick",
"author_id": 11884,
"author_profile": "https://Stackoverflow.com/users/11884",
"pm_score": 4,
"selected": false,
"text": "<p>Running </p>\n\n<p>$ httpd -V</p>\n\n<p>will show you lots of useful server information, including where the httpd.conf file can be found.</p>\n"
},
{
"answer_id": 72143,
"author": "Michael Cramer",
"author_id": 1496728,
"author_profile": "https://Stackoverflow.com/users/1496728",
"pm_score": 1,
"selected": false,
"text": "<p><strong>/etc/httpd/users</strong> contains user-specific configuration files which can be used to override the global configuration. For example, adding \"<strong>AddHandler server-parsed html</strong>\" to the <strong><Directory></strong> block in the <strong>/etc/httpd/users/*.conf</strong> file that corresponds to one user will enable mod_include parsing of HTML files for that particular user's <strong>$HOME/Sites</strong> directory, but nowhere else.</p>\n"
},
{
"answer_id": 6964273,
"author": "Scott Willeke",
"author_id": 51061,
"author_profile": "https://Stackoverflow.com/users/51061",
"pm_score": 2,
"selected": false,
"text": "<p>To get SSI/includes (mod_include) to work I found I had to edit <code>/private/etc/apache2/users/myusername.conf</code> and change <code>AllowOverride None</code> to <code>AllowOverride All</code>.</p>\n\n<p>Then add the following in a .htaccess file in the root of your site:</p>\n\n<pre><code>Options +Includes\nAddType text/html .html\nAddOutputFilter INCLUDES .html\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3575/"
]
| Mac OS X ships with apache pre-installed, but the files are in non-standard locations. This question is a place to collect information about where configuration files live, and how to tweak the apache installation to do things like serve php pages. | Apache Config file is: /private/etc/apache2/httpd.conf
Default DocumentRoot is: /Library/Webserver/Documents/
To enable PHP, at around line 114 (maybe) in the /private/etc/apache2/httpd.conf file is the following line:
```
#LoadModule php5_module libexec/apache2/libphp5.so
```
Remove the pound sign to uncomment the line so now it looks like this:
```
LoadModule php5_module libexec/apache2/libphp5.so
```
Restart Apache: System Preferences -> Sharing -> Un-check "Web Sharing" and re-check it.
**OR**
```
$ sudo apachectl restart
``` |
69,843 | <p>Does anybody have useful example of <code>this</code> assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself. </p>
| [
{
"answer_id": 69851,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": -1,
"selected": false,
"text": "<p>You cannot overwrite \"this\". It points to the current object instance.</p>\n"
},
{
"answer_id": 69878,
"author": "dimarzionist",
"author_id": 10778,
"author_profile": "https://Stackoverflow.com/users/10778",
"pm_score": -1,
"selected": false,
"text": "<p>only correct place for this from syntax point of view, is Extension methods in C# 3.0 when you specify first parameter of method as foo(ftype this, ...). and then can use this extension for any instance of ftype. But is's just syntax and not real this ovveride operation.</p>\n"
},
{
"answer_id": 69880,
"author": "Kimoz",
"author_id": 7753,
"author_profile": "https://Stackoverflow.com/users/7753",
"pm_score": 0,
"selected": false,
"text": "<p>using the <strong>this</strong> keyword ensures that only variables and methods scoped in the current type are accessed. This can be used when you have a naming conflict between a field/property and a local variable or method parameter.</p>\n\n<p>Typically used in constructors:</p>\n\n<pre><code>private readonly IProvider provider;\npublic MyClass(IProvider provider)\n{\n this.provider = provider;\n}\n</code></pre>\n\n<p>In this example we assign the parameter provider to the private field provider.</p>\n"
},
{
"answer_id": 69910,
"author": "LohanJ",
"author_id": 11286,
"author_profile": "https://Stackoverflow.com/users/11286",
"pm_score": -1,
"selected": false,
"text": "<p>if you're asked to assign something to <em>this</em>, there's quite a few examples. One that comes to mind is telling a control who his daddy is:</p>\n\n<pre><code>class frmMain\n{\n void InitializeComponents()\n {\n btnOK = new Button();\n btnOK.Parent = this;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 69988,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 7,
"selected": true,
"text": "<p>The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you <em>can</em> for a struct type:</p>\n\n<pre><code>public struct MyValueType\n{\n public int Id;\n public void Swap(ref MyValueType other)\n {\n MyValueType temp = this;\n this = other;\n other = temp;\n }\n}\n</code></pre>\n\n<p>At any point a struct can alter itself by assigning to 'this' like so.</p>\n"
},
{
"answer_id": 23914965,
"author": "mhand",
"author_id": 1582922,
"author_profile": "https://Stackoverflow.com/users/1582922",
"pm_score": -1,
"selected": false,
"text": "<p>I know this question has long been answered and discussion has stopped, but here's a case I didn't see mentioned anywhere on the interwebs and thought it may be useful to share here.</p>\n\n<p>I've used this to maintain immutability of members while still supporting serialization. Consider a <code>struct</code> defined like this:</p>\n\n<pre><code>public struct SampleStruct : IXmlSerializable\n{\n private readonly int _data;\n\n public int Data { get { return _data; } }\n\n public SampleStruct(int data)\n {\n _data = data;\n }\n\n #region IXmlSerializableMembers\n\n public XmlSchema GetSchema() { return null; }\n\n public void ReadXml(XmlReader reader)\n {\n this = new SampleStruct(int.Parse(reader.ReadString()));\n }\n\n public void WriteXml(XmlWriter writer\n {\n writer.WriteString(data.ToString());\n }\n\n #endregion\n}\n</code></pre>\n\n<p>Since we're allowed to overwrite <code>this</code>, we can maintain the immutability of <code>_data</code> held within a single instance. This has the added benefit of when deserializing new values you're guaranteed a fresh instance, which is sometimes a nice guarantee!\n }</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11256/"
]
| Does anybody have useful example of `this` assignment inside a C# method? I have been asked for it once during job interview, and I am still interested in answer myself. | The other answers are incorrect when they say you cannot assign to 'this'. True, you can't for a class type, but you *can* for a struct type:
```
public struct MyValueType
{
public int Id;
public void Swap(ref MyValueType other)
{
MyValueType temp = this;
this = other;
other = temp;
}
}
```
At any point a struct can alter itself by assigning to 'this' like so. |
69,849 | <p>When is it a good idea to use factory methods within an object instead of a Factory class?</p>
| [
{
"answer_id": 69861,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 3,
"selected": false,
"text": "<p>It's really a matter of taste. Factory classes can be abstracted/interfaced away as necessary, whereas factory methods are lighter weight (and also tend to be testable, since they don't have a defined type, but they will require a well-known registration point, akin to a service locator but for locating factory methods).</p>\n"
},
{
"answer_id": 70179,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 2,
"selected": false,
"text": "<p>Factory classes are useful for when the object type that they return has a private constructor, when different factory classes set different properties on the returning object, or when a specific factory type is coupled with its returning concrete type. </p>\n\n<p><strong>WCF</strong> uses ServiceHostFactory classes to retrieve ServiceHost objects in different situations. The standard ServiceHostFactory is used by IIS to retrieve ServiceHost instances for <em>.svc</em> files, but a WebScriptServiceHostFactory is used for services that return serializations to JavaScript clients. ADO.NET Data Services has its own special DataServiceHostFactory and ASP.NET has its ApplicationServicesHostFactory since its services have private constructors.</p>\n\n<p>If you only have one class that's consuming the factory, then you can just use a factory method within that class.</p>\n"
},
{
"answer_id": 70298,
"author": "jonfm",
"author_id": 6924,
"author_profile": "https://Stackoverflow.com/users/6924",
"pm_score": 0,
"selected": false,
"text": "<p>Factory classes are more heavyweight, but give you certain advantages. In cases when you need to build your objects from multiple, raw data sources they allow you to encapsulate only the building logic (and maybe the aggregation of the data) in one place. There it can be tested in abstract without being concerned with the object interface.</p>\n\n<p>I have found this a useful pattern, particularly where I am unable to replace and inadequate ORM and want to efficiently instantiate many objects from DB table joins or stored procedures.</p>\n"
},
{
"answer_id": 71394,
"author": "Rik",
"author_id": 5409,
"author_profile": "https://Stackoverflow.com/users/5409",
"pm_score": 4,
"selected": false,
"text": "<p>They're also useful when you need several \"constructors\" with the same parameter type but with different behavior. </p>\n"
},
{
"answer_id": 399988,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 7,
"selected": false,
"text": "<p>Factory methods should be considered as an alternative to constructors - mostly when constructors aren't expressive enough, ie.</p>\n\n<pre><code>class Foo{\n public Foo(bool withBar);\n}\n</code></pre>\n\n<p>is not as expressive as:</p>\n\n<pre><code>class Foo{\n public static Foo withBar();\n public static Foo withoutBar();\n}\n</code></pre>\n\n<p>Factory classes are useful when you need a complicated process for constructing the object, when the construction need a dependency that you do not want for the actual class, when you need to construct different objects etc.</p>\n"
},
{
"answer_id": 2430719,
"author": "kyoryu",
"author_id": 129175,
"author_profile": "https://Stackoverflow.com/users/129175",
"pm_score": 9,
"selected": false,
"text": "<p>I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.</p>\n\n<p>So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.</p>\n\n<p>So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually <em>hire</em> someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.</p>\n\n<p>In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.</p>\n\n<pre><code>public interface IThingFactory\n{\n Thing GetThing(string theString);\n}\n\npublic class ThingFactory : IThingFactory\n{\n public Thing GetThing(string theString)\n {\n return new Thing(theString, firstDependency, secondDependency);\n }\n}\n</code></pre>\n\n<p>So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer.</p>\n"
},
{
"answer_id": 10559506,
"author": "Mahn",
"author_id": 1329367,
"author_profile": "https://Stackoverflow.com/users/1329367",
"pm_score": 7,
"selected": false,
"text": "<p>One situation where I personally find separate Factory classes to make sense is when the final object you are trying to create relies on several other objects. E.g, in PHP: Suppose you have a <code>House</code> object, which in turn has a <code>Kitchen</code> and a <code>LivingRoom</code> object, and the <code>LivingRoom</code> object has a <code>TV</code> object inside as well. </p>\n\n<p>The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your <code>House</code> fails creating you will probably spend some time trying to isolate exactly what is failing.</p>\n\n<p>The alternative is to do the following (dependency injection, if you like the fancy term):</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>$TVObj = new TV($param1, $param2, $param3);\n$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);\n$KitchenroomObj = new Kitchen($param1, $param2);\n$HouseObj = new House($LivingroomObj, $KitchenroomObj);\n</code></pre>\n\n<p>Here if the process of creating a <code>House</code> fails there is only one place to look, but having to use this chunk every time one wants a new <code>House</code> is far from convenient. Enter the Factories:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>class HouseFactory {\n public function create() {\n $TVObj = new TV($param1, $param2, $param3);\n $LivingroomObj = new LivingRoom($TVObj, $param1, $param2);\n $KitchenroomObj = new Kitchen($param1, $param2);\n $HouseObj = new House($LivingroomObj, $KitchenroomObj);\n\n return $HouseObj;\n }\n}\n\n$houseFactory = new HouseFactory();\n$HouseObj = $houseFactory->create();\n</code></pre>\n\n<p>Thanks to the factory here the process of creating a <code>House</code> is abstracted (in that you don't need to create and set up every single dependency when you just want to create a <code>House</code>) and at the same time centralized which makes it easier to maintain. There are other reasons why using separate Factories can be beneficial (e.g. testability) but I find this specific use case to illustrate best how Factory classes can be useful.</p>\n"
},
{
"answer_id": 17668707,
"author": "Prakash Chhipa",
"author_id": 2251992,
"author_profile": "https://Stackoverflow.com/users/2251992",
"pm_score": 4,
"selected": false,
"text": "<p>It is important to clearly differentiate the idea behind using factory or factory method.\nBoth are meant to address mutually exclusive different kind of object creation problems.</p>\n\n<p>Let's be specific about \"factory method\":</p>\n\n<p>First thing is that, when you are developing library or APIs which in turn will be used for further application development, then factory method is one of the best selections for creation pattern. Reason behind; <strong>We know that when to create an object of required functionality(s) but type of object will remain undecided or it will be decided ob dynamic parameters being passed</strong>.</p>\n\n<p>Now the point is, approximately same can be achieved by using factory pattern itself but one huge drawback will introduce into the system if factory pattern will be used for above highlighted problem, it is that your logic of crating different objects(sub classes objects) will be specific to some business condition so in future when you need to extend your library's functionality for other platforms(In more technically, you need to add more sub classes of basic interface or abstract class so factory will return those objects also in addition to existing one based on some dynamic parameters) then every time you need to change(extend) the logic of factory class which will be costly operation and not good from design perspective.\nOn the other side, if \"factory method\" pattern will be used to perform the same thing then you just need to create additional functionality(sub classes) and get it registered dynamically by injection which doesn't require changes in your base code.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>interface Deliverable \n{\n /*********/\n}\n\nabstract class DefaultProducer \n{\n\n public void taskToBeDone() \n { \n Deliverable deliverable = factoryMethodPattern();\n }\n protected abstract Deliverable factoryMethodPattern();\n}\n\nclass SpecificDeliverable implements Deliverable \n{\n /***SPECIFIC TASK CAN BE WRITTEN HERE***/\n}\n\nclass SpecificProducer extends DefaultProducer \n{\n protected Deliverable factoryMethodPattern() \n {\n return new SpecificDeliverable();\n }\n}\n\npublic class MasterApplicationProgram \n{\n public static void main(String arg[]) \n {\n DefaultProducer defaultProducer = new SpecificProducer();\n defaultProducer.taskToBeDone();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 27735620,
"author": "Robert",
"author_id": 1798677,
"author_profile": "https://Stackoverflow.com/users/1798677",
"pm_score": 0,
"selected": false,
"text": "<p>I liken factories to the concept of libraries. For example you can have a library for working with numbers and another for working with shapes. You can store the functions of these libraries in logically named directories as <code>Numbers</code> or <code>Shapes</code>. These are generic types that could include integers, floats, dobules, longs or rectangles, circles, triangles, pentagons in the case of shapes.</p>\n\n<p>The factory petter uses polymorphism, dependency injection and Inversion of control.</p>\n\n<p>The stated purpose of the Factory Patterns is: <code>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.</code></p>\n\n<p>So let's say that you are building an Operating System or Framework and you are building all the discrete components.</p>\n\n<p>Here is a simple example of the concept of the Factory Pattern in PHP. I may not be 100% on all of it but it's intended to serve as a simple example. I am not an expert.</p>\n\n<pre><code>class NumbersFactory {\n public static function makeNumber( $type, $number ) {\n $numObject = null;\n $number = null;\n\n switch( $type ) {\n case 'float':\n $numObject = new Float( $number );\n break;\n case 'integer':\n $numObject = new Integer( $number );\n break;\n case 'short':\n $numObject = new Short( $number );\n break;\n case 'double':\n $numObject = new Double( $number );\n break;\n case 'long':\n $numObject = new Long( $number );\n break;\n default:\n $numObject = new Integer( $number );\n break;\n }\n\n return $numObject;\n }\n}\n\n/* Numbers interface */\nabstract class Number {\n protected $number;\n\n public function __construct( $number ) {\n $this->number = $number;\n }\n\n abstract public function add();\n abstract public function subtract();\n abstract public function multiply();\n abstract public function divide();\n}\n/* Float Implementation */\nclass Float extends Number {\n public function add() {\n // implementation goes here\n }\n\n public function subtract() {\n // implementation goes here\n }\n\n public function multiply() {\n // implementation goes here\n }\n\n public function divide() {\n // implementation goes here\n }\n}\n/* Integer Implementation */\nclass Integer extends Number {\n public function add() {\n // implementation goes here\n }\n\n public function subtract() {\n // implementation goes here\n }\n\n public function multiply() {\n // implementation goes here\n }\n\n public function divide() {\n // implementation goes here\n }\n}\n/* Short Implementation */\nclass Short extends Number {\n public function add() {\n // implementation goes here\n }\n\n public function subtract() {\n // implementation goes here\n }\n\n public function multiply() {\n // implementation goes here\n }\n\n public function divide() {\n // implementation goes here\n }\n}\n/* Double Implementation */\nclass Double extends Number {\n public function add() {\n // implementation goes here\n }\n\n public function subtract() {\n // implementation goes here\n }\n\n public function multiply() {\n // implementation goes here\n }\n\n public function divide() {\n // implementation goes here\n }\n}\n/* Long Implementation */\nclass Long extends Number {\n public function add() {\n // implementation goes here\n }\n\n public function subtract() {\n // implementation goes here\n }\n\n public function multiply() {\n // implementation goes here\n }\n\n public function divide() {\n // implementation goes here\n }\n}\n\n$number = NumbersFactory::makeNumber( 'float', 12.5 );\n</code></pre>\n"
},
{
"answer_id": 30465141,
"author": "Dzianis Yafimau",
"author_id": 3877717,
"author_profile": "https://Stackoverflow.com/users/3877717",
"pm_score": 4,
"selected": false,
"text": "<p>It is good idea to use <strong>factory methods</strong> inside object when:</p>\n\n<ol>\n<li>Object's class doesn't know what exact sub-classes it have to create</li>\n<li>Object's class is designed so that objects it creates were specified by sub-classes</li>\n<li>Object's class delegates its duties to auxiliary sub-classes and doesn't know what exact class will take these duties</li>\n</ol>\n\n<p>It is good idea to use <strong>abstract factory</strong> class when:</p>\n\n<ol>\n<li>Your object shouldn't depend on how its inner objects are created and designed</li>\n<li>Group of linked objects should be used together and you need to serve this constraint</li>\n<li>Object should be configured by one of several possible families of linked objects that will be a part of your parent object</li>\n<li>It is required to share child objects showing interfaces only but not an implementation</li>\n</ol>\n"
},
{
"answer_id": 32471927,
"author": "Muhammad Awais",
"author_id": 4296800,
"author_profile": "https://Stackoverflow.com/users/4296800",
"pm_score": 2,
"selected": false,
"text": "<p>Consider a scenario when you have to design an Order and Customer class. For simplicity and initial requirements you do not feel need of factory for Order class and fill your application with many 'new Order()' statements. Things are working well.</p>\n\n<p>Now a new requirement comes into picture that Order object cannot be instantiated without Customer association (new dependency). Now You have following considerations.</p>\n\n<p>1- You create constructor overload which will work only for new implementations. (Not acceptable).\n2- You change Order() signatures and change each and every invokation. (Not a good practice and real pain).</p>\n\n<p>Instead If you have created a factory for Order Class you only have to change one line of code and you are good to go. I suggest Factory class for almost every aggregate association. Hope that helps.</p>\n"
},
{
"answer_id": 35857241,
"author": "Ravindra babu",
"author_id": 4999394,
"author_profile": "https://Stackoverflow.com/users/4999394",
"pm_score": 4,
"selected": false,
"text": "<p>UML from </p>\n\n<p><a href=\"https://i.stack.imgur.com/LUIor.gif\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LUIor.gif\" alt=\"enter image description here\"></a></p>\n\n<p><em>Product:</em> It defines an interface of the objects the Factory method creates.</p>\n\n<p><em>ConcreteProduct:</em> Implements Product interface</p>\n\n<p><em>Creator:</em> Declares the Factory method</p>\n\n<p><em>ConcreateCreator:</em> Implements the Factory method to return an instance of a ConcreteProduct</p>\n\n<p><strong>Problem statement:</strong> Create a Factory of Games by using Factory Methods, which defines the game interface.</p>\n\n<p>Code snippet:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.HashMap;\n\n\n/* Product interface as per UML diagram */\ninterface Game{\n /* createGame is a complex method, which executes a sequence of game steps */\n public void createGame();\n}\n\n/* ConcreteProduct implementation as per UML diagram */\nclass Chess implements Game{\n public Chess(){\n\n }\n public void createGame(){\n System.out.println(\"---------------------------------------\");\n System.out.println(\"Create Chess game\");\n System.out.println(\"Opponents:2\");\n System.out.println(\"Define 64 blocks\");\n System.out.println(\"Place 16 pieces for White opponent\");\n System.out.println(\"Place 16 pieces for Black opponent\");\n System.out.println(\"Start Chess game\");\n System.out.println(\"---------------------------------------\");\n }\n}\nclass Checkers implements Game{\n public Checkers(){\n\n }\n public void createGame(){\n System.out.println(\"---------------------------------------\");\n System.out.println(\"Create Checkers game\");\n System.out.println(\"Opponents:2 or 3 or 4 or 6\");\n System.out.println(\"For each opponent, place 10 coins\");\n System.out.println(\"Start Checkers game\");\n System.out.println(\"---------------------------------------\");\n }\n}\nclass Ludo implements Game{\n public Ludo(){\n\n }\n public void createGame(){\n System.out.println(\"---------------------------------------\");\n System.out.println(\"Create Ludo game\");\n System.out.println(\"Opponents:2 or 3 or 4\");\n System.out.println(\"For each opponent, place 4 coins\");\n System.out.println(\"Create two dices with numbers from 1-6\");\n System.out.println(\"Start Ludo game\");\n System.out.println(\"---------------------------------------\");\n }\n}\n\n/* Creator interface as per UML diagram */\ninterface IGameFactory {\n public Game getGame(String gameName);\n}\n\n/* ConcreteCreator implementation as per UML diagram */\nclass GameFactory implements IGameFactory {\n\n HashMap<String,Game> games = new HashMap<String,Game>();\n /* \n Since Game Creation is complex process, we don't want to create game using new operator every time.\n Instead we create Game only once and store it in Factory. When client request a specific game, \n Game object is returned from Factory instead of creating new Game on the fly, which is time consuming\n */\n\n public GameFactory(){\n\n games.put(Chess.class.getName(),new Chess());\n games.put(Checkers.class.getName(),new Checkers());\n games.put(Ludo.class.getName(),new Ludo()); \n }\n public Game getGame(String gameName){\n return games.get(gameName);\n }\n}\n\npublic class NonStaticFactoryDemo{\n public static void main(String args[]){\n if ( args.length < 1){\n System.out.println(\"Usage: java FactoryDemo gameName\");\n return;\n }\n\n GameFactory factory = new GameFactory();\n Game game = factory.getGame(args[0]);\n if ( game != null ){ \n game.createGame();\n System.out.println(\"Game=\"+game.getClass().getName());\n }else{\n System.out.println(args[0]+ \" Game does not exists in factory\");\n } \n }\n}\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>java NonStaticFactoryDemo Chess\n---------------------------------------\nCreate Chess game\nOpponents:2\nDefine 64 blocks\nPlace 16 pieces for White opponent\nPlace 16 pieces for Black opponent\nStart Chess game\n---------------------------------------\nGame=Chess\n</code></pre>\n\n<p>This example shows a <code>Factory</code> class by implementing a <code>FactoryMethod</code>.</p>\n\n<ol>\n<li><p><code>Game</code> is the interface for all type of games. It defines complex method: <code>createGame()</code></p></li>\n<li><p><code>Chess, Ludo, Checkers</code> are different variants of games, which provide implementation to <code>createGame()</code></p></li>\n<li><p><code>public Game getGame(String gameName)</code> is <code>FactoryMethod</code> in <code>IGameFactory</code> class</p></li>\n<li><p><code>GameFactory</code> pre-creates different type of games in constructor. It implements <code>IGameFactory</code> factory method. </p></li>\n<li><p>game Name is passed as command line argument to <code>NotStaticFactoryDemo</code></p></li>\n<li><p><code>getGame</code> in <code>GameFactory</code> accepts a game name and returns corresponding <code>Game</code> object.</p></li>\n</ol>\n\n<p><strong>Factory:</strong></p>\n\n<blockquote>\n <p>Creates objects without exposing the instantiation logic to the client.</p>\n</blockquote>\n\n<p><strong>FactoryMethod</strong></p>\n\n<blockquote>\n <p>Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses</p>\n</blockquote>\n\n<p><strong>Use case:</strong></p>\n\n<p>When to use: <code>Client</code> doesn't know what concrete classes it will be required to create at runtime, but just wants to get a class that will do the job.</p>\n"
},
{
"answer_id": 45575361,
"author": "Samet ÖZTOPRAK",
"author_id": 6717610,
"author_profile": "https://Stackoverflow.com/users/6717610",
"pm_score": 1,
"selected": false,
"text": "<p>if you want to create a different object in terms of using. It is useful.</p>\n\n<pre><code>public class factoryMethodPattern {\n static String planName = \"COMMERCIALPLAN\";\n static int units = 3;\n public static void main(String args[]) {\n GetPlanFactory planFactory = new GetPlanFactory();\n Plan p = planFactory.getPlan(planName);\n System.out.print(\"Bill amount for \" + planName + \" of \" + units\n + \" units is: \");\n p.getRate();\n p.calculateBill(units);\n }\n}\n\nabstract class Plan {\n protected double rate;\n\n abstract void getRate();\n\n public void calculateBill(int units) {\n System.out.println(units * rate);\n }\n}\n\nclass DomesticPlan extends Plan {\n // @override\n public void getRate() {\n rate = 3.50;\n }\n}\n\nclass CommercialPlan extends Plan {\n // @override\n public void getRate() {\n rate = 7.50;\n }\n}\n\nclass InstitutionalPlan extends Plan {\n // @override\n public void getRate() {\n rate = 5.50;\n }\n}\n\nclass GetPlanFactory {\n\n // use getPlan method to get object of type Plan\n public Plan getPlan(String planType) {\n if (planType == null) {\n return null;\n }\n if (planType.equalsIgnoreCase(\"DOMESTICPLAN\")) {\n return new DomesticPlan();\n } else if (planType.equalsIgnoreCase(\"COMMERCIALPLAN\")) {\n return new CommercialPlan();\n } else if (planType.equalsIgnoreCase(\"INSTITUTIONALPLAN\")) {\n return new InstitutionalPlan();\n }\n return null;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49159679,
"author": "nits.kk",
"author_id": 504133,
"author_profile": "https://Stackoverflow.com/users/504133",
"pm_score": 1,
"selected": false,
"text": "<p>Any class deferring the object creation to its sub class for the object it needs to work with can be seen as an example of Factory pattern.</p>\n\n<p>I have mentioned in detail in an another answer at <a href=\"https://stackoverflow.com/a/49110001/504133\">https://stackoverflow.com/a/49110001/504133</a></p>\n"
},
{
"answer_id": 59073313,
"author": "tagus",
"author_id": 6081899,
"author_profile": "https://Stackoverflow.com/users/6081899",
"pm_score": 1,
"selected": false,
"text": "<p>I think it will depend of loose coupling degree that you want to bring to your code.</p>\n\n<p>Factory method decouples things very well but factory class no.</p>\n\n<p>In other words, it's easier to change things if you use factory method than if you use a simple factory (known as factory class).</p>\n\n<p>Look into this example: <a href=\"https://connected2know.com/programming/java-factory-pattern/\" rel=\"nofollow noreferrer\">https://connected2know.com/programming/java-factory-pattern/</a> . Now, imagine that you want to bring a new Animal. In Factory class you need to change the Factory but in the factory method, no, you only need to add a new subclass. </p>\n"
},
{
"answer_id": 68110309,
"author": "Mykola Tokariev",
"author_id": 10220374,
"author_profile": "https://Stackoverflow.com/users/10220374",
"pm_score": -1,
"selected": false,
"text": "<p><a href=\"https://i.stack.imgur.com/wAQvR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wAQvR.png\" alt=\"enter image description here\" /></a>\nImagine you have a different customers with different preferences. Someone need Volkswagen another one Audi and so on. One thing is common - it's a car.</p>\n<p>To make our customer happy we need a factory. The factory only should know which car the customer want and will deliver such car to customer. If later we have some another car we can easily extend our car park and our factory.</p>\n<p>Below you can see an example (ABAP):\n<a href=\"https://i.stack.imgur.com/i2AFy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/i2AFy.png\" alt=\"enter image description here\" /></a></p>\n<p>Now we will create an instance of the factory and listening for the customers wishes.\n<a href=\"https://i.stack.imgur.com/tUNVw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/tUNVw.png\" alt=\"enter image description here\" /></a></p>\n<p>We created three different cars with only one create( ) method.</p>\n<p>Result:</p>\n<p><a href=\"https://i.stack.imgur.com/6WM4W.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/6WM4W.png\" alt=\"enter image description here\" /></a></p>\n<p>Quite often is factory pattern very usefull if you want to make the logic more clean and the program more extensible.</p>\n"
},
{
"answer_id": 70043790,
"author": "Krasimir",
"author_id": 642670,
"author_profile": "https://Stackoverflow.com/users/642670",
"pm_score": 0,
"selected": false,
"text": "<p>My short explanation will be that we use the factory pattern when we don't have enough information to create a concrete object. We either don't know the dependencies or we don't know the type of the object. And almost always we don't know them because this is information that comes at runtime.</p>\n<p>Example: we know that we have to create a vehicle object but we don't know if it flies or it works on ground.</p>\n"
},
{
"answer_id": 71321528,
"author": "Lunatic",
"author_id": 15758781,
"author_profile": "https://Stackoverflow.com/users/15758781",
"pm_score": 2,
"selected": false,
"text": "<p><strong>GOF</strong> Definition :</p>\n<p>Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.</p>\n<p><strong>Generic</strong> example :</p>\n<pre><code>public abstract class Factory<T> {\n\n public abstract T instantiate(Supplier<? extends T> supplier);\n\n}\n</code></pre>\n<p>The concrete class</p>\n<pre><code>public class SupplierFactory<T> extends Factory<T> {\n\n @Override\n public T instantiate(Supplier<? extends T> supplier) {\n return supplier.get();\n }\n}\n</code></pre>\n<p>The Implementation</p>\n<pre><code>public class Alpha implements BaseInterface {\n @Override\n public void doAction() {\n System.out.println("The Alpha executed");\n }\n}\n\npublic class Beta implements BaseInterface {\n @Override\n public void doAction() {\n System.out.println("The Beta executed");\n }\n}\n\npublic interface BaseInterface {\n void doAction();\n}\n\npublic class Main {\n public static void main(String[] args) {\n Factory<BaseInterface> secondFactory = new SupplierFactory<>();\n secondFactory.instantiate(Beta::new).doAction();\n secondFactory.instantiate(Alpha::new).doAction();\n }\n}\n</code></pre>\n<p><strong>Brief</strong> advantages</p>\n<ul>\n<li>You are separating code that can vary from the code that does not vary (i.e., the advantages of using a simple factory pattern is still present). This technique helps you easily maintain code.</li>\n<li>Your code is not tightly coupled; so, you can add new classes like Lion, Beer, and so forth, at any time in the system without modifying the existing architecture. So, you have followed the “closed for modification but open for extension” principle.</li>\n</ul>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69849",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| When is it a good idea to use factory methods within an object instead of a Factory class? | I like thinking about design pattens in terms of my classes being 'people,' and the patterns are the ways that the people talk to each other.
So, to me the factory pattern is like a hiring agency. You've got someone that will need a variable number of workers. This person may know some info they need in the people they hire, but that's it.
So, when they need a new employee, they call the hiring agency and tell them what they need. Now, to actually *hire* someone, you need to know a lot of stuff - benefits, eligibility verification, etc. But the person hiring doesn't need to know any of this - the hiring agency handles all of that.
In the same way, using a Factory allows the consumer to create new objects without having to know the details of how they're created, or what their dependencies are - they only have to give the information they actually want.
```
public interface IThingFactory
{
Thing GetThing(string theString);
}
public class ThingFactory : IThingFactory
{
public Thing GetThing(string theString)
{
return new Thing(theString, firstDependency, secondDependency);
}
}
```
So, now the consumer of the ThingFactory can get a Thing, without having to know about the dependencies of the Thing, except for the string data that comes from the consumer. |
69,913 | <p>What is the reason browsers do not correctly recognize:</p>
<pre><code><script src="foobar.js" /> <!-- self-closing script element -->
</code></pre>
<p>Only this is recognized:</p>
<pre><code><script src="foobar.js"></script>
</code></pre>
<p>Does this break the concept of XHTML support?</p>
<p>Note: This statement is correct at least for all IE (6-8 beta 2).</p>
| [
{
"answer_id": 69984,
"author": "squadette",
"author_id": 7754,
"author_profile": "https://Stackoverflow.com/users/7754",
"pm_score": 10,
"selected": true,
"text": "<p>The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:</p>\n<p><a href=\"http://www.w3.org/TR/xhtml1/#C_3\" rel=\"noreferrer\">С.3. Element Minimization and Empty Element Content</a></p>\n<blockquote>\n<p>Given an empty instance of an element whose content model is not <code>EMPTY</code> (for example, an empty title or paragraph) do not use the minimized form (e.g. use <code><p> </p></code> and not <code><p /></code>).</p>\n</blockquote>\n<p><a href=\"http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict\" rel=\"noreferrer\">XHTML DTD</a> specifies script elements as:</p>\n<pre><code><!-- script statements, which may include CDATA sections -->\n<!ELEMENT script (#PCDATA)>\n</code></pre>\n"
},
{
"answer_id": 69996,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 5,
"selected": false,
"text": "<p>Unlike XML and XHTML, HTML has no knowledge of the self-closing syntax. Browsers that interpret XHTML as HTML don't know that the <code>/</code> character indicates that the tag should be self-closing; instead they interpret it like an empty attribute and the parser still thinks the tag is 'open'.</p>\n\n<p>Just as <code><script defer></code> is treated as <code><script defer=\"defer\"></code>, <code><script /></code> is treated as <code><script /=\"/\"></code>.</p>\n"
},
{
"answer_id": 70235,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 6,
"selected": false,
"text": "<p>Internet Explorer 8 and earlier do not support XHTML parsing. Even if you use an XML declaration and/or an XHTML doctype, old IE still parse the document as plain HTML. And in plain HTML, the self-closing syntax is not supported. The trailing slash is just ignored, you have to use an explicit closing tag.</p>\n<p>Even browsers with support for XHTML parsing, such as <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ie/xhtml-in-ie9\" rel=\"nofollow noreferrer\">IE 9 and later</a>, will still parse the document as HTML unless you serve the document with a XML content type. But in that case old IE will not display the document at all!</p>\n"
},
{
"answer_id": 70288,
"author": "joelhardi",
"author_id": 11438,
"author_profile": "https://Stackoverflow.com/users/11438",
"pm_score": 8,
"selected": false,
"text": "<p>To add to what Brad and squadette have said, the self-closing XML syntax <code><script /></code> actually <strong>is</strong> correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like <code>application/xhtml+xml</code> in the HTTP Content-Type header (and <em>not</em> as <code>text/html</code>).</p>\n\n<p>However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes <code>text/html</code>.</p>\n\n<p>From <a href=\"http://www.w3.org/TR/xhtml-media-types/\" rel=\"noreferrer\">w3</a>:</p>\n\n<blockquote>\n <p>In summary, 'application/xhtml+xml'\n SHOULD be used for XHTML Family\n documents, and the use of 'text/html'\n SHOULD be limited to HTML-compatible\n XHTML 1.0 documents. 'application/xml'\n and 'text/xml' MAY also be used, but\n whenever appropriate,\n 'application/xhtml+xml' SHOULD be used\n rather than those generic XML media\n types.</p>\n</blockquote>\n\n<p>I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old <code><script></script></code> syntax with <code>text/html</code> (HTML syntax + HTML mimetype).</p>\n\n<p>If your server sends the <code>text/html</code> type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that <code><script /></code> will not work (this is a change, Firefox was previously less strict).</p>\n\n<p>This will happen regardless of any fiddling with <code>http-equiv</code> meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the <code>text/html</code> header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand <code><script /></code>.</p>\n"
},
{
"answer_id": 71836,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 4,
"selected": false,
"text": "<p>Internet Explorer 8 and older don't support the proper MIME type for XHTML, <code>application/xhtml+xml</code>. If you're serving XHTML as <code>text/html</code>, which you have to for these older versions of Internet Explorer to do anything, it will be interpreted as HTML 4.01. You can only use the short syntax with any element that permits the closing tag to be omitted. See the <a href=\"https://www.w3.org/TR/html401/\" rel=\"nofollow noreferrer\">HTML 4.01 Specification</a>.</p>\n<p>The XML 'short form' is interpreted as an attribute named /, which (because there is no equals sign) is interpreted as having an implicit value of "/". This is strictly wrong in HTML 4.01 - undeclared attributes are not permitted - but browsers will ignore it.</p>\n<p>IE9 and later <a href=\"https://learn.microsoft.com/en-us/archive/blogs/ie/xhtml-in-ie9\" rel=\"nofollow noreferrer\">support XHTML 5</a> served with <code>application/xhtml+xml</code>.</p>\n"
},
{
"answer_id": 71998,
"author": "Marijn",
"author_id": 12038,
"author_profile": "https://Stackoverflow.com/users/12038",
"pm_score": 5,
"selected": false,
"text": "<p>The people above have already pretty much explained the issue, but one thing that might make things clear is that, though people use <code><br/></code> and such all the time in HTML documents, any <code>/</code> in such a position is basically ignored, and only used when trying to make something both parseable as XML and HTML. Try <code><p/>foo</p></code>, for example, and you get a regular paragraph.</p>\n"
},
{
"answer_id": 3327807,
"author": "greim",
"author_id": 127040,
"author_profile": "https://Stackoverflow.com/users/127040",
"pm_score": 7,
"selected": false,
"text": "<p>In case anyone's curious, the ultimate reason is that HTML was originally a dialect of SGML, which is XML's weird older brother. In SGML-land, elements can be specified in the DTD as either self-closing (e.g. BR, HR, INPUT), implicitly closeable (e.g. P, LI, TD), or explicitly closeable (e.g. TABLE, DIV, SCRIPT). XML, of course, has no concept of this.</p>\n\n<p>The tag-soup parsers used by modern browsers evolved out of this legacy, although their parsing model isn't pure SGML anymore. And of course, your carefully-crafted XHTML is being treated as badly-written SGML-inspired tag-soup unless you send it with an XML mime type. This is also why...</p>\n\n<pre><code><p><div>hello</div></p>\n</code></pre>\n\n<p>...gets interpreted by the browser as:</p>\n\n<pre><code><p></p><div>hello</div><p></p>\n</code></pre>\n\n<p>...which is the recipe for a lovely obscure bug that can throw you into fits as you try to code against the DOM.</p>\n"
},
{
"answer_id": 13098915,
"author": "defau1t",
"author_id": 724764,
"author_profile": "https://Stackoverflow.com/users/724764",
"pm_score": 5,
"selected": false,
"text": "<p>The self closing script tag won't work, because the script tag can contain inline code, and HTML is not smart enough to turn on or off that feature based on the presence of an attribute.</p>\n\n<blockquote>\n <p>On the other hand, HTML does have an excellent tag for including\n references to outside resources: the <code><link></code> tag, and it can be\n self-closing. It's already used to include stylesheets, RSS and Atom\n feeds, canonical URIs, and all sorts of other goodies. Why not\n JavaScript?</p>\n</blockquote>\n\n<p>If you want the script tag to be self enclosed you can't do that as I said, but there is an alternative, though not a smart one. You can use the self closing link tag and link to your JavaScript by giving it a type of text/javascript and rel as script, something like below:</p>\n\n<pre><code><link type=\"text/javascript\" rel =\"script\" href=\"/path/tp/javascript\" />\n</code></pre>\n"
},
{
"answer_id": 28719226,
"author": "Sheepy",
"author_id": 893578,
"author_profile": "https://Stackoverflow.com/users/893578",
"pm_score": 8,
"selected": false,
"text": "<p>Others have answered \"how\" and quoted spec. Here is the real story of \"why no <code><script/></code>\", after many hours digging into bug reports and mailing lists.</p>\n\n<hr>\n\n<p><strong>HTML 4</strong></p>\n\n<p>HTML 4 is based on <a href=\"http://www.iso.org/iso/catalogue_detail.htm?csnumber=16387\" rel=\"noreferrer\">SGML</a>.</p>\n\n<p>SGML has some <a href=\"https://en.wikipedia.org/wiki/Standard_Generalized_Markup_Language#SHORTTAG\" rel=\"noreferrer\">shorttags</a>, such as <code><BR//</code>, <code><B>text</></code>, <code><B/text/</code>, or <code><OL<LI>item</LI</OL></code>.\nXML takes the first form, redefines the ending as \">\" (SGML is flexible), so that it becomes <code><BR/></code>.</p>\n\n<p>However, HTML did not redfine, so <code><SCRIPT/></code> <a href=\"https://stackoverflow.com/a/3201889/893578\"><em>should</em> mean</a> <code><SCRIPT>></code>. <br>\n(Yes, the '>' should be part of content, and the tag is still <em>not</em> closed.)</p>\n\n<p>Obviously, this is incompatible with XHTML and <em>will</em> break many sites (by the time browsers were mature enough <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=47522\" rel=\"noreferrer\">to care</a> <a href=\"https://bugs.webkit.org/show_bug.cgi?id=6393\" rel=\"noreferrer\">about this</a>), so <a href=\"https://stackoverflow.com/a/9619296/893578\">nobody implemented shorttags</a> and the specification <a href=\"http://www.w3.org/TR/html401/appendix/notes.html#h-B.3.3\" rel=\"noreferrer\">advises against them</a>.</p>\n\n<p>Effectively, all 'working' self-ended tags are tags with prohibited end tag on technically non-conformant parsers and are in fact invalid.\nIt was W3C which <a href=\"https://www.webkit.org/blog/68/understanding-html-xml-and-xhtml/\" rel=\"noreferrer\">came up with this hack</a> to help transitioning to XHTML by making it <a href=\"http://www.w3.org/TR/xhtml1/#guidelines\" rel=\"noreferrer\">HTML-compatible</a>.</p>\n\n<p>And <code><script></code>'s end tag is <a href=\"http://www.w3.org/TR/html401/interact/scripts.html#h-18.2.1\" rel=\"noreferrer\">not prohibited</a>.</p>\n\n<p><strong>\"Self-ending\" tag is a hack in HTML 4 and is meaningless.</strong></p>\n\n<hr>\n\n<p><strong>HTML 5</strong></p>\n\n<p>HTML5 has <a href=\"https://html.spec.whatwg.org/multipage/syntax.html#elements-2\" rel=\"noreferrer\">five types of tags</a> and only 'void' and 'foreign' tags are <a href=\"https://html.spec.whatwg.org/multipage/syntax.html#syntax-tags\" rel=\"noreferrer\">allowed to be self-closing</a>.</p>\n\n<p>Because <code><script></code> is not void (it <em>may</em> have content) and is not foreign (like MathML or SVG), <code><script></code> cannot be self-closed, regardless of how you use it.</p>\n\n<p>But why? Can't they regard it as foreign, make special case, or something?</p>\n\n<p>HTML 5 aims to be <a href=\"https://html.spec.whatwg.org/multipage/introduction.html#history-2\" rel=\"noreferrer\">backward-compatible</a> with <em>implementations</em> of HTML 4 and XHTML 1.\nIt is not based on SGML or XML; its syntax is mainly concerned with documenting and uniting the implementations.\n(This is why <code><br/></code> <code><hr/></code> etc. are <a href=\"https://html.spec.whatwg.org/multipage/syntax.html#start-tags\" rel=\"noreferrer\">valid HTML 5</a> despite being invalid HTML4.)</p>\n\n<p>Self-closing <code><script></code> is one of the tags where implementations used to differ.\nIt <a href=\"https://www.webkit.org/blog/1273/the-html5-parsing-algorithm/\" rel=\"noreferrer\">used to work in Chrome, Safari</a>, <a href=\"http://www.opera.com/docs/changelogs/windows/900b1/\" rel=\"noreferrer\">and Opera</a>; to my knowledge it never worked in Internet Explorer or Firefox.</p>\n\n<p><a href=\"http://lists.w3.org/Archives/Public/public-whatwg-archive/2009Aug/0101.html\" rel=\"noreferrer\">This was discussed</a> when HTML 5 was being drafted and got rejected because it <a href=\"http://lists.w3.org/Archives/Public/public-whatwg-archive/2009Aug/0104.html\" rel=\"noreferrer\">breaks</a> <a href=\"http://lists.w3.org/Archives/Public/public-whatwg-archive/2009Aug/0117.html\" rel=\"noreferrer\">browser</a> <a href=\"http://lists.w3.org/Archives/Public/public-whatwg-archive/2009Aug/0119.html\" rel=\"noreferrer\">compatibility</a>.\nWebpages that self-close script tag may not render correctly (if at all) in old browsers.\nThere were <a href=\"http://lists.w3.org/Archives/Public/public-whatwg-archive/2009Aug/0384.html\" rel=\"noreferrer\">other proposals</a>, but they can't solve the compatibility problem either.</p>\n\n<p>After the draft was released, WebKit updated the parser to be in conformance.</p>\n\n<p><strong>Self-closing <code><script></code> does not happen in HTML 5 because of backward compatibility to HTML 4 and XHTML 1.</strong></p>\n\n<hr>\n\n<p><strong>XHTML 1 / XHTML 5</strong></p>\n\n<p>When <em>really</em> served as XHTML, <code><script/></code> is really closed, as <a href=\"https://stackoverflow.com/a/70288/893578\">other answers</a> have stated.</p>\n\n<p>Except that <a href=\"http://www.w3.org/TR/xhtml1/#media\" rel=\"noreferrer\">the spec says</a> it <em>should</em> have worked when served as HTML:</p>\n\n<blockquote>\n <p>XHTML Documents ... may be labeled with the Internet Media Type \"text/html\" [RFC2854], as they are compatible with most HTML browsers.</p>\n</blockquote>\n\n<p>So, what happened?</p>\n\n<p>People <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=67646\" rel=\"noreferrer\">asked Mozilla</a> to <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=107904\" rel=\"noreferrer\">let Firefox parse</a> conforming documents as <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=109837\" rel=\"noreferrer\">XHTML</a> regardless of the specified content header (known as <a href=\"https://en.wikipedia.org/wiki/Content_sniffing\" rel=\"noreferrer\">content sniffing</a>).\nThis would have allowed self-closing scripts, and content sniffing <a href=\"http://blogs.msdn.com/b/ie/archive/2005/02/01/364581.aspx\" rel=\"noreferrer\">was necessary</a> anyway because web hosters were not mature enough to serve the correct header; IE was <a href=\"https://msdn.microsoft.com/en-us/library/ie/ms775147%28v=vs.85%29.aspx\" rel=\"noreferrer\">good at it</a>.</p>\n\n<p>If the <a href=\"https://en.wikipedia.org/wiki/Browser_wars#First_browser_war\" rel=\"noreferrer\">first browser war</a> didn't end with IE 6, XHTML may have been on the list, too. But it did end. And IE 6 <a href=\"http://blog.isotoma.com/2008/01/xhtml-ccs-crashes-ie6/\" rel=\"noreferrer\">has a problem</a> with XHTML.\nIn fact IE <a href=\"https://stackoverflow.com/questions/268526/blank-page-in-ie6\">did not support</a> the correct MIME type <a href=\"http://blogs.msdn.com/b/ie/archive/2005/09/15/467901.aspx\" rel=\"noreferrer\">at all</a>, forcing <em>everyone</em> to use <code>text/html</code> for XHTML because IE held <a href=\"https://en.wikipedia.org/wiki/Usage_share_of_web_browsers#TheCounter.com_.282000_to_2009.29\" rel=\"noreferrer\">major market share</a> for a whole decade.</p>\n\n<p>And also content sniffing <a href=\"http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx\" rel=\"noreferrer\">can be</a> <a href=\"http://www.h-online.com/security/features/Risky-MIME-sniffing-in-Internet-Explorer-746229.html\" rel=\"noreferrer\">really bad</a> and people are saying <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=68421\" rel=\"noreferrer\">it should be stopped</a>.</p>\n\n<p>Finally, it turns out that the W3C <a href=\"http://lists.w3.org/Archives/Public/www-html/2000Sep/0024.html\" rel=\"noreferrer\">didn't mean XHTML to be sniffable</a>: the document is <em>both</em>, HTML and XHTML, and <code>Content-Type</code> rules.\nOne can say they were standing firm on \"just follow our spec\" and <a href=\"http://lemire.me/blog/archives/2006/10/30/reinventing-html-or-yes-we-admit-it-xhtml-failed/\" rel=\"noreferrer\">ignoring what was practical</a>. A mistake that <a href=\"https://www.cnet.com/news/an-epitaph-for-the-web-standard-xhtml-2/\" rel=\"noreferrer\">continued</a> into later XHTML versions.</p>\n\n<p>Anyway, this decision <a href=\"https://bugzilla.mozilla.org/show_bug.cgi?id=109837#c11\" rel=\"noreferrer\">settled the matter</a> for Firefox.\nIt was 7 years before Chrome <a href=\"https://en.wikipedia.org/wiki/Google_Chrome#Public_release\" rel=\"noreferrer\">was born</a>; there were no other significant browser. Thus it was decided.</p>\n\n<p><strong>Specifying the doctype alone does not trigger XML parsing because of following specifications.</strong></p>\n"
},
{
"answer_id": 45746061,
"author": "Bekim Bacaj",
"author_id": 5896426,
"author_profile": "https://Stackoverflow.com/users/5896426",
"pm_score": 3,
"selected": false,
"text": "<h2>That's because SCRIPT TAG is not a VOID ELEMENT.</h2>\n\n<p>In an <em>HTML Document</em> - VOID ELEMENTS <strong>do not</strong> need a \"closing tag\" at all!</p>\n\n<p>In <em>xhtml</em>, everything is Generic, therefore they all need <strong>termination</strong> e.g. a \"closing tag\"; Including br, a simple line-break, as <code><br></br></code> or its <em>shorthand</em> <code><br /></code>.</p>\n\n<p>However, a Script Element is never a void or a parametric Element, because <em>script tag</em> before anything else, is a Browser Instruction, not a Data Description declaration.</p>\n\n<p>Principally, a Semantic Termination Instruction e.g., a \"closing tag\" is only needed for processing instructions who's semantics cannot be terminated by a succeeding tag. For instance: </p>\n\n<p><code><H1></code> semantics cannot be terminated by a following <code><P></code> because it doesn't carry enough of its own semantics to override and therefore terminate the previous H1 instruction set. Although it will be able to break the <strong>stream</strong> into a new paragraph line, it is not \"strong enough\" to override the present font size & style line-height <em>pouring down the stream</em>, i.e leaking from H1 (because P doesn't have it). </p>\n\n<p>This is how and why the \"/\" (termination) signalling has been invented. </p>\n\n<p>A generic <em>no-description</em> termination Tag like <code>< /></code>, would have sufficed for any single fall off the encountered cascade, e.g.: <code><H1>Title< /></code> but that's not always the case, because we also want to be capable of \"nesting\", multiple intermediary tagging of the Stream: split into torrents before wrapping / falling onto another cascade. As a consequence a generic terminator such as <code>< /></code> would not be able to determine the target of a property to terminate. For example: <code><b></code><strong>bold</strong> <code><i></code><strong><em>bold-italic</em></strong> <code>< /></code> <em>italic</em> <code></></code>normal. Would undoubtedly fail to get our intention right and would most probably interpret it as <strong>bold <em>bold-itallic</em> bold</strong> normal.</p>\n\n<p>This is how the <strong>notion</strong> of a wrapper ie., container was born. (These notions are so similar that it is impossible to discern and sometimes the same element may have both. <code><H1></code> is both wrapper and container at the same time. Whereas <code><B></code> only a semantic wrapper). We'll need a plain, no semantics container. And of course the invention of a DIV Element came by. </p>\n\n<p>The DIV element is actually a 2BR-Container. Of course the coming of CSS made the whole situation weirder than it would otherwise have been and caused a great confusion with many great consequences - indirectly!</p>\n\n<p>Because with CSS you could easily override the native pre&after BR behavior of a newly invented DIV, it is often referred to, as a \"do nothing container\". Which is, naturally wrong! DIVs are block elements and will natively break the line of the stream both before and after the end signalling. Soon the WEB started suffering from page DIV-itis. Most of them still are.</p>\n\n<p>The coming of CSS with its capability to fully override and completely redefine the native behavior of any HTML Tag, somehow managed to confuse and blur the whole meaning of HTML existence...</p>\n\n<p>Suddenly all HTML tags appeared as if obsolete, they were defaced, stripped of all their original meaning, identity and purpose. Somehow you'd gain the impression that they're no longer needed. Saying: A single container-wrapper tag would suffice for all the data presentation. Just add the required attributes. Why not have meaningful tags instead; Invent tag names as you go and let the CSS bother with the rest.</p>\n\n<p>This is how xhtml was born and of course the great blunt, paid so dearly by new comers and a distorted vision of what is what, and what's the damn purpose of it all. W3C went from World Wide Web to What Went Wrong, Comrades?!!</p>\n\n<p>The purpose of HTML is <strong>to stream</strong> meaningful data to the human recipient.</p>\n\n<p>To deliver Information.</p>\n\n<p>The formal part is there to only assist the clarity of information delivery.\nxhtml doesn't give the slightest consideration to the information. - To it, the information is absolutely irrelevant.</p>\n\n<p>The most important thing in the matter is to know and be able to understand that <strong>xhtml is not just a version of some extended HTML</strong>, xhtml is a completely different beast; grounds up; and therefore <strong>it is wise to keep them separate.</strong> </p>\n"
},
{
"answer_id": 47424940,
"author": "myf",
"author_id": 540955,
"author_profile": "https://Stackoverflow.com/users/540955",
"pm_score": 2,
"selected": false,
"text": "<p>Difference between 'true XHTML', 'faux XHTML' and 'ordinary HTML' as well as importance of the server-sent MIME type had been <a href=\"https://stackoverflow.com/a/70288/540955\">already described here well</a>.</p>\n<p>If you want to try it out right now, here is simple editable snippet with live preview including self-closed script tag (see <code><script src="data:text/javascript,/*functionality*/" /></code>) and XML entity (unrelated, see <code>&x;</code>).</p>\n<p>As you can see, depending on the MIME type of embedding document the data-URI JavaScript functionality is either executed and consecutive text displayed (in <code>application/xhtml+xml</code> mode) or not executed and consecutive text 'devoured' by the script (in <code>text/html</code> mode).</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>div { display: flex; }\ndiv + div {flex-direction: column; }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div>Mime type: <label><input type=\"radio\" onchange=\"t.onkeyup()\" id=\"x\" checked name=\"mime\"> application/xhtml+xml</label>\n<label><input type=\"radio\" onchange=\"t.onkeyup()\" name=\"mime\"> text/html</label></div>\n<div><textarea id=\"t\" rows=\"4\" \nonkeyup=\"i.src='data:'+(x.checked?'application/xhtml+xml':'text/html')+','+encodeURIComponent(t.value)\"\n><?xml version=\"1.0\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"\n[<!ENTITY x \"true XHTML\">]>\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<body>\n <p>\n <span id=\"greet\" swapto=\"Hello\">Hell, NO :(</span> &x;.\n <script src=\"data:text/javascript,(g=document.getElementById('greet')).innerText=g.getAttribute('swapto')\" />\n Nice to meet you!\n <!-- \n Previous text node and all further content falls into SCRIPT element content in text/html mode, so is not rendered. Because no end script tag is found, no script runs in text/html\n -->\n </p>\n</body>\n</html></textarea>\n\n<iframe id=\"i\" height=\"80\"></iframe>\n\n<script>t.onkeyup()</script>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>You should see <code>Hello, true XHTML. Nice to meet you!</code> below textarea.</p>\n<p>For incapable browsers you can copy content of the textarea and save it as a file with <code>.xhtml</code> (or <code>.xht</code>) extension (<a href=\"https://stackoverflow.com/questions/69913/why-dont-self-closing-script-tags-work?rq=1#comment44088198_70288\">thanks Alek for this hint</a>).</p>\n"
},
{
"answer_id": 58789694,
"author": "Mark Schultheiss",
"author_id": 125981,
"author_profile": "https://Stackoverflow.com/users/125981",
"pm_score": 2,
"selected": false,
"text": "<p>Simply modern answer is because the tag is denoted as mandatory that way</p>\n\n<blockquote>\n <p>Tag omission None, both the starting and ending tag are mandatory.</p>\n</blockquote>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script</a></p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10778/"
]
| What is the reason browsers do not correctly recognize:
```
<script src="foobar.js" /> <!-- self-closing script element -->
```
Only this is recognized:
```
<script src="foobar.js"></script>
```
Does this break the concept of XHTML support?
Note: This statement is correct at least for all IE (6-8 beta 2). | The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:
[С.3. Element Minimization and Empty Element Content](http://www.w3.org/TR/xhtml1/#C_3)
>
> Given an empty instance of an element whose content model is not `EMPTY` (for example, an empty title or paragraph) do not use the minimized form (e.g. use `<p> </p>` and not `<p />`).
>
>
>
[XHTML DTD](http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict) specifies script elements as:
```
<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
``` |
69,928 | <p>The company has the traditional complex organizational structure, defining the amount of levels using the letter 'n' rather than an actual number. I will try and express the structure I'm trying to achieve in mono-spaced font: </p>
<pre><code> Alice
,--------|-------,------,------,
Bob Fred Jack Kim Lucy
| |
Charlie Greg
Darren Henry
Eric
</code></pre>
<p>As you can see it's not symmetrical, as Jack, Kim and Lucy report to Alice but have no reports of their own. </p>
<p>Using a <code>TreeView</code> with an <code>ItemsPanel</code> containing a <code>StackPanel</code> and <code>Orientation="Horizontal"</code> is <a href="http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx" rel="nofollow noreferrer">easy enough</a>, but this can result in a very large <code>TreeView</code> once some people have 20 others reporting to them! You can <a href="http://www.codeproject.com/KB/WPF/AdvancedCustomTreeViewLyt.aspx" rel="nofollow noreferrer">also use</a> <code>Triggers</code> to peek into whether a <code>TreeViewItem</code> has children with <code>Property="TreeViewItem.HasItems"</code>, but this is not in the same context as the before-mentioned <code>ItemsPanel</code>. <em>Eg: I can tell that Fred has reports, but not whether they have reports of their own.</em> </p>
<p>So, can you conditionally format <code>TreeViewItems</code> to be Vertical if they have no children of their own?</p>
| [
{
"answer_id": 69952,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 2,
"selected": false,
"text": "<p>Josh Smith has a excecllent CodeProject article about TreeView. Read it <a href=\"http://www.codeproject.com/KB/WPF/AdvancedCustomTreeViewLyt.aspx\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 113120,
"author": "Mark Glorie",
"author_id": 952,
"author_profile": "https://Stackoverflow.com/users/952",
"pm_score": 1,
"selected": true,
"text": "<p>I did end up using tips from the linked article, which I'd already read through but didn't think would help me. </p>\n\n<p>The meat of it happens here, in a converter: </p>\n\n<pre><code><ValueConversion(GetType(ItemsPresenter), GetType(Orientation))> _\nPublic Class ItemsPanelOrientationConverter\nImplements IValueConverter\n\nPublic Function Convert(ByVal value As Object, ByVal targetType As System.Type, _\nByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _\nAs Object Implements System.Windows.Data.IValueConverter.Convert\n\n 'The 'value' argument should reference an ItemsPresenter.'\n Dim itemsPresenter As ItemsPresenter = TryCast(value, ItemsPresenter)\n If itemsPresenter Is Nothing Then\n Return Binding.DoNothing\n End If\n\n 'The ItemsPresenter''s templated parent should be a TreeViewItem.'\n Dim item As TreeViewItem = TryCast(itemsPresenter.TemplatedParent, TreeViewItem)\n If item Is Nothing Then\n Return Binding.DoNothing\n End If\n\n For Each i As Object In item.Items\n Dim element As StaffMember = TryCast(i, StaffMember)\n If element.IsManager Then\n 'If this element has children, then return Horizontal'\n Return Orientation.Horizontal\n End If\n Next\n\n 'Must be a stub ItemPresenter'\n Return Orientation.Vertical\n\nEnd Function\n</code></pre>\n\n<p>Which in turn gets consumed in a style I created for the TreeView: </p>\n\n<pre><code> <Setter Property=\"ItemsPanel\">\n <Setter.Value>\n <ItemsPanelTemplate >\n <ItemsPanelTemplate.Resources>\n <local:ItemsPanelOrientationConverter x:Key=\"conv\" />\n </ItemsPanelTemplate.Resources>\n <StackPanel IsItemsHost=\"True\" \n Orientation=\"{Binding \n RelativeSource={x:Static RelativeSource.TemplatedParent}, \n Converter={StaticResource conv}}\" />\n </ItemsPanelTemplate>\n </Setter.Value>\n </Setter>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/952/"
]
| The company has the traditional complex organizational structure, defining the amount of levels using the letter 'n' rather than an actual number. I will try and express the structure I'm trying to achieve in mono-spaced font:
```
Alice
,--------|-------,------,------,
Bob Fred Jack Kim Lucy
| |
Charlie Greg
Darren Henry
Eric
```
As you can see it's not symmetrical, as Jack, Kim and Lucy report to Alice but have no reports of their own.
Using a `TreeView` with an `ItemsPanel` containing a `StackPanel` and `Orientation="Horizontal"` is [easy enough](http://www.codeproject.com/KB/WPF/CustomTreeViewLayout.aspx), but this can result in a very large `TreeView` once some people have 20 others reporting to them! You can [also use](http://www.codeproject.com/KB/WPF/AdvancedCustomTreeViewLyt.aspx) `Triggers` to peek into whether a `TreeViewItem` has children with `Property="TreeViewItem.HasItems"`, but this is not in the same context as the before-mentioned `ItemsPanel`. *Eg: I can tell that Fred has reports, but not whether they have reports of their own.*
So, can you conditionally format `TreeViewItems` to be Vertical if they have no children of their own? | I did end up using tips from the linked article, which I'd already read through but didn't think would help me.
The meat of it happens here, in a converter:
```
<ValueConversion(GetType(ItemsPresenter), GetType(Orientation))> _
Public Class ItemsPanelOrientationConverter
Implements IValueConverter
Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, _
ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) _
As Object Implements System.Windows.Data.IValueConverter.Convert
'The 'value' argument should reference an ItemsPresenter.'
Dim itemsPresenter As ItemsPresenter = TryCast(value, ItemsPresenter)
If itemsPresenter Is Nothing Then
Return Binding.DoNothing
End If
'The ItemsPresenter''s templated parent should be a TreeViewItem.'
Dim item As TreeViewItem = TryCast(itemsPresenter.TemplatedParent, TreeViewItem)
If item Is Nothing Then
Return Binding.DoNothing
End If
For Each i As Object In item.Items
Dim element As StaffMember = TryCast(i, StaffMember)
If element.IsManager Then
'If this element has children, then return Horizontal'
Return Orientation.Horizontal
End If
Next
'Must be a stub ItemPresenter'
Return Orientation.Vertical
End Function
```
Which in turn gets consumed in a style I created for the TreeView:
```
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate >
<ItemsPanelTemplate.Resources>
<local:ItemsPanelOrientationConverter x:Key="conv" />
</ItemsPanelTemplate.Resources>
<StackPanel IsItemsHost="True"
Orientation="{Binding
RelativeSource={x:Static RelativeSource.TemplatedParent},
Converter={StaticResource conv}}" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
``` |
69,934 | <p>I've been unsuccessful in getting Emacs to switch from 8 space tabs to 4 space tabs when pressing the <kbd>TAB</kbd> in buffers with the major mode <code>text-mode</code>. I've added the following to my <code>.emacs</code>:</p>
<pre><code>(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
;;; And I have tried
(setq indent-tabs-mode nil)
(setq tab-width 4)
</code></pre>
<p>No matter how I change my <code>.emacs</code> file (or my buffer's local variables) the <kbd>TAB</kbd> button always does the same thing.</p>
<ol>
<li>If there is no text above, indent <strong>8</strong> spaces</li>
<li>If there is text on the previous line, indent to the beginning of the second word</li>
</ol>
<p>As much as I love Emacs this is getting annoying. Is there a way to make Emacs to at least indent 4 space when there's not text in the previous line?</p>
| [
{
"answer_id": 69992,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried</p>\n\n<pre><code>(setq tab-width 4)\n</code></pre>\n"
},
{
"answer_id": 70027,
"author": "Bert F",
"author_id": 11296,
"author_profile": "https://Stackoverflow.com/users/11296",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n<p>Do not confuse variable <code>tab-width</code> with variable <code>tab-stop-list</code>.\nThe former is used for the display of literal <code>TAB</code> characters.\nThe latter controls what characters are inserted when you press the <code>TAB</code> character in certain modes.</p>\n</blockquote>\n<p>-- <a href=\"https://www.gnu.org/software/emacs/manual/html_node/efaq/Changing-the-length-of-a-Tab.html\" rel=\"nofollow noreferrer\">GNU Emacs Manual</a></p>\n<pre><code>(customize-variable (quote tab-stop-list))\n</code></pre>\n<p>or add <em>tab-stop-list</em> entry to <em>custom-set-variables</em> in <em>.emacs</em> file:</p>\n<pre><code>(custom-set-variables\n ;; custom-set-variables was added by Custom.\n ;; If you edit it by hand, you could mess it up, so be careful.\n ;; Your init file should contain only one such instance.\n ;; If there is more than one, they won't work right.\n '(tab-stop-list (quote (4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120))))\n</code></pre>\n<p>Another way to edit the tab behavior is with with <code>M-x edit-tab-stops</code>.</p>\n<p>See the <a href=\"https://www.gnu.org/software/emacs/manual/html_node/emacs/Tab-Stops.html\" rel=\"nofollow noreferrer\">GNU Emacs Manual on Tab Stops</a> for more information on <code>edit-tab-stops</code>.</p>\n"
},
{
"answer_id": 70205,
"author": "cjm",
"author_id": 8355,
"author_profile": "https://Stackoverflow.com/users/8355",
"pm_score": 3,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>(add-hook 'text-mode-hook\n (function\n (lambda ()\n (setq tab-width 4)\n (define-key text-mode-map \"\\C-i\" 'self-insert-command)\n )))\n</code></pre>\n\n<p>That will make TAB always insert a literal TAB character with tab stops every 4 characters (but only in Text mode). If that's not what you're asking for, please describe the behavior you'd like to see.</p>\n"
},
{
"answer_id": 70329,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 4,
"selected": false,
"text": "<p>You may find it easier to set up your tabs as follows:</p>\n\n<pre><code>M-x customize-group\n</code></pre>\n\n<p>At the <code>Customize group:</code> prompt enter <code>indent</code>.</p>\n\n<p>You'll see a screen where you can set all you indenting options and set them for the current session or save them for all future sessions.</p>\n\n<p>If you do it this way you'll want to <a href=\"http://www.gnu.org/software/emacs/manual/html_node/emacs/Saving-Customizations.html\" rel=\"noreferrer\">set up a customisations file</a>.</p>\n"
},
{
"answer_id": 471916,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>(setq tab-width 4)\n(setq tab-stop-list '(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80))\n(setq indent-tabs-mode nil)\n</code></pre>\n"
},
{
"answer_id": 741020,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>This problem isn't caused by missing tab stops; it's that emacs has a (new?) tab method called indent-relative that seems designed to line up tabular data. The TAB key is mapped to the method indent-for-tab-command, which calls whatever method the variable indent-line-function is set to, which is indent-relative method for text mode. I havn't figured out a good way to override the indent-line-function variable (text mode hook isn't working, so maybe it is getting reset after the mode-hooks run?) but one simple way to get rid of this behavior is to just chuck the intent-for-tab-command method by setting TAB to the simpler tab-to-tab-stop method:</p>\n\n<p>(define-key text-mode-map (kbd \"TAB\") 'tab-to-tab-stop)</p>\n"
},
{
"answer_id": 1301711,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>(setq-default tab-width 4)\n(setq-default indent-tabs-mode nil)\n</code></pre>\n"
},
{
"answer_id": 1309654,
"author": "dividebyzero",
"author_id": 160466,
"author_profile": "https://Stackoverflow.com/users/160466",
"pm_score": 2,
"selected": false,
"text": "<p>Just changing the style with c-set-style was enough for me.</p>\n"
},
{
"answer_id": 1819405,
"author": "alcortes",
"author_id": 102532,
"author_profile": "https://Stackoverflow.com/users/102532",
"pm_score": 7,
"selected": false,
"text": "<h2>Short answer:</h2>\n\n<p>The key point is to tell emacs to insert whatever you want when indenting, this is done by changing the indent-line-function. It is easier to change it to insert a tab and then change tabs into 4 spaces than change it to insert 4 spaces. The following configuration will solve your problem:</p>\n\n<pre><code>(setq-default indent-tabs-mode nil)\n(setq-default tab-width 4)\n(setq indent-line-function 'insert-tab)\n</code></pre>\n\n<h2>Explanation:</h2>\n\n<p>From <a href=\"http://www.gnu.org/s/emacs/manual/html_node/elisp/Mode_002dSpecific-Indent.html#Mode_002dSpecific-Indent\" rel=\"noreferrer\">Indentation Controlled by Major Mode @ emacs manual</a>:</p>\n\n<blockquote>\n <p>An important function of each major\n mode is to customize the key to\n indent properly for the language being\n edited.</p>\n \n <p>[...]</p>\n \n <p>The indent-line-function variable is\n the function to be used by (and\n various commands, like when calling\n indent-region) to indent the current\n line. The command\n indent-according-to-mode does no more\n than call this function.</p>\n \n <p>[...]</p>\n \n <p>The default value is indent-relative\n for many modes.</p>\n</blockquote>\n\n<p>From indent-relative @ emacs manual:</p>\n\n<blockquote>\n <p>Indent-relative Space out to under next\n indent point in previous nonblank line.</p>\n \n <p>[...]</p>\n \n <p>If the previous nonblank line has no\n indent points beyond the column point\n starts at, `tab-to-tab-stop' is done\n instead.</p>\n</blockquote>\n\n<p>Just change the value of indent-line-function to the insert-tab function and configure tab insertion as 4 spaces.</p>\n"
},
{
"answer_id": 10438585,
"author": "qwerty9967",
"author_id": 1305559,
"author_profile": "https://Stackoverflow.com/users/1305559",
"pm_score": 2,
"selected": false,
"text": "<p>Add this to your .emacs file:</p>\n\n<p>This will set the width that a tab is displayed to 2 characters (change the number 2 to whatever you want)</p>\n\n<pre><code>(setq default-tab-width 2)\n</code></pre>\n\n<p>To make sure that emacs is actually using tabs instead of spaces:</p>\n\n<pre><code>(global-set-key (kbd \"TAB\") 'self-insert-command)\n</code></pre>\n\n<p>As an aside, the default for emacs when backspacing over a tab is to convert it to spaces and then delete a space. This can be annoying. If you want it to just delete the tab, you can do this:</p>\n\n<pre><code>(setq c-backspace-function 'backward-delete-char)\n</code></pre>\n\n<p>Enjoy!</p>\n"
},
{
"answer_id": 10439239,
"author": "phils",
"author_id": 324105,
"author_profile": "https://Stackoverflow.com/users/324105",
"pm_score": 6,
"selected": false,
"text": "<p><em>Update:</em> Since Emacs 24.4:</p>\n\n<blockquote>\n <p><code>tab-stop-list</code> is now implicitly extended to infinity. Its default value is changed to <code>nil</code> which means a tab stop every <code>tab-width</code> columns.</p>\n</blockquote>\n\n<p>which means that there's no longer any need to be setting <code>tab-stop-list</code> in the way shown below, as you can keep it set to <code>nil</code>.</p>\n\n<p><em>Original answer follows...</em></p>\n\n<hr/>\n\n<p>It always pains me slightly seeing things like <code>(setq tab-stop-list 4 8 12 ................)</code> when the <code>number-sequence</code> function is sitting there waiting to be used.</p>\n\n<pre class=\"lang-el prettyprint-override\"><code>(setq tab-stop-list (number-sequence 4 200 4))\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-el prettyprint-override\"><code>(defun my-generate-tab-stops (&optional width max)\n \"Return a sequence suitable for `tab-stop-list'.\"\n (let* ((max-column (or max 200))\n (tab-width (or width tab-width))\n (count (/ max-column tab-width)))\n (number-sequence tab-width (* tab-width count) tab-width)))\n\n(setq tab-width 4)\n(setq tab-stop-list (my-generate-tab-stops))\n</code></pre>\n"
},
{
"answer_id": 13114566,
"author": "gigilibala",
"author_id": 1775441,
"author_profile": "https://Stackoverflow.com/users/1775441",
"pm_score": 3,
"selected": false,
"text": "<p>You can add these lines of code to your .emacs file.\nIt adds a hook for text mode to use insert-tab instead of indent-relative.</p>\n\n<pre><code>(custom-set-variables\n '(indent-line-function 'insert-tab)\n '(indent-tabs-mode t)\n '(tab-width 4))\n(add-hook 'text-mode-hook\n (lambda() (setq indent-line-function 'insert-tab)))\n</code></pre>\n\n<p>I hope it helps.</p>\n"
},
{
"answer_id": 16127986,
"author": "lawlist",
"author_id": 2112489,
"author_profile": "https://Stackoverflow.com/users/2112489",
"pm_score": 3,
"selected": false,
"text": " <pre class=\"lang-lisp prettyprint-override\"><code>(defun my-custom-settings-fn ()\n (setq indent-tabs-mode t)\n (setq tab-stop-list (number-sequence 2 200 2))\n (setq tab-width 2)\n (setq indent-line-function 'insert-tab))\n\n(add-hook 'text-mode-hook 'my-custom-settings-fn)\n</code></pre>\n"
},
{
"answer_id": 16210873,
"author": "user2318996",
"author_id": 2318996,
"author_profile": "https://Stackoverflow.com/users/2318996",
"pm_score": 3,
"selected": false,
"text": "<pre><code>(setq-default indent-tabs-mode nil)\n(setq-default tab-width 4)\n(setq indent-line-function 'insert-tab)\n(setq c-default-style \"linux\") \n(setq c-basic-offset 4) \n(c-set-offset 'comment-intro 0)\n</code></pre>\n\n<p>this works for C++ code and the comment inside too</p>\n"
},
{
"answer_id": 18887294,
"author": "flyrain",
"author_id": 933856,
"author_profile": "https://Stackoverflow.com/users/933856",
"pm_score": 0,
"selected": false,
"text": "<p>By the way, for <strong>C-mode</strong>, I add <strong><code>(setq-default c-basic-offset 4)</code></strong> to .emacs. See <a href=\"http://www.emacswiki.org/emacs/IndentingC\" rel=\"nofollow\">http://www.emacswiki.org/emacs/IndentingC</a> for details.</p>\n"
},
{
"answer_id": 26288992,
"author": "forkandwait",
"author_id": 2554948,
"author_profile": "https://Stackoverflow.com/users/2554948",
"pm_score": 0,
"selected": false,
"text": "<p>From my init file, different because I wanted spaces instead of tabs:</p>\n\n<pre>\n\n(add-hook 'sql-mode-hook\n (lambda ()\n (progn\n (setq-default tab-width 4)\n (setq indent-tabs-mode nil)\n (setq indent-line-function 'tab-to-tab-stop) \n (modify-syntax-entry ?_ \"w\") ; now '_' is not considered a word-delimiter\n (modify-syntax-entry ?- \"w\") ; now '-' is not considered a word-delimiter \n )))\n</pre>\n"
},
{
"answer_id": 31124271,
"author": "user1009285",
"author_id": 1009285,
"author_profile": "https://Stackoverflow.com/users/1009285",
"pm_score": 2,
"selected": false,
"text": "<p>The best answers did not work for until I wrote this in the .emacs file:</p>\n\n<pre><code>(global-set-key (kbd \"TAB\") 'self-insert-command)\n</code></pre>\n"
},
{
"answer_id": 42148697,
"author": "ryanpcmcquen",
"author_id": 2662028,
"author_profile": "https://Stackoverflow.com/users/2662028",
"pm_score": 2,
"selected": false,
"text": "<p>This is the only solution that keeps a tab from ever getting inserted for me, without a sequence or conversion of tabs to spaces. Both of those seemed adequate, but wasteful:</p>\n\n<pre><code>(setq-default\n indent-tabs-mode nil\n tab-width 4\n tab-stop-list (quote (4 8))\n)\n</code></pre>\n\n<p>Note that <code>quote</code> needs two numbers to work (but not more!).</p>\n\n<p>Also, in most major modes (<code>Python</code> for instance), indentation is automatic in Emacs. If you need to indent outside of the auto indent, use:</p>\n\n<p><kbd>M</kbd>-<kbd>i</kbd></p>\n"
},
{
"answer_id": 42841185,
"author": "Yary",
"author_id": 379333,
"author_profile": "https://Stackoverflow.com/users/379333",
"pm_score": 2,
"selected": false,
"text": "<p>Customizations can shadow <code>(setq tab width 4)</code> so either use <code>setq-default</code> or let Customize know what you're doing. I also had issues similar to the OP and fixed it with this alone, did not need to adjust <code>tab-stop-list</code> or any <code>insert</code> functions:</p>\n\n<pre><code>(custom-set-variables\n '(tab-width 4 't)\n )\n</code></pre>\n\n<p>Found it useful to add this immediately after (a tip from emacsWiki):</p>\n\n<pre><code>(defvaralias 'c-basic-offset 'tab-width)\n(defvaralias 'cperl-indent-level 'tab-width)\n</code></pre>\n"
},
{
"answer_id": 61216979,
"author": "Saurabh",
"author_id": 13055097,
"author_profile": "https://Stackoverflow.com/users/13055097",
"pm_score": 0,
"selected": false,
"text": "<p>Modified <a href=\"https://stackoverflow.com/a/16127986/13055097\">this answer</a> without any hook:</p>\n\n<pre><code>(setq-default\n indent-tabs-mode t\n tab-stop-list (number-sequence 4 200 4)\n tab-width 4\n indent-line-function 'insert-tab)\n</code></pre>\n"
},
{
"answer_id": 69657718,
"author": "alex_1948511",
"author_id": 1948511,
"author_profile": "https://Stackoverflow.com/users/1948511",
"pm_score": 0,
"selected": false,
"text": "<p>To make in text-mode pressing <code>Tab</code> does indent then tabbing/spacing by fixed values (NOT by previous line words)</p>\n<p>see also: indent-relative-first-indent-point, tab-width indent-tabs-mode</p>\n<pre><code>(add-hook 'text-mode-hook\n (lambda()\n (progn\n (setq tab-always-indent nil) \n ;(setq electric-indent-mode nil)\n (setq indent-line-function \n (lambda()\n (indent-relative 't) \n )\n ) \n (setq tab-always-indent nil)\n )))\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
]
| I've been unsuccessful in getting Emacs to switch from 8 space tabs to 4 space tabs when pressing the `TAB` in buffers with the major mode `text-mode`. I've added the following to my `.emacs`:
```
(setq-default indent-tabs-mode nil)
(setq-default tab-width 4)
;;; And I have tried
(setq indent-tabs-mode nil)
(setq tab-width 4)
```
No matter how I change my `.emacs` file (or my buffer's local variables) the `TAB` button always does the same thing.
1. If there is no text above, indent **8** spaces
2. If there is text on the previous line, indent to the beginning of the second word
As much as I love Emacs this is getting annoying. Is there a way to make Emacs to at least indent 4 space when there's not text in the previous line? | >
> Do not confuse variable `tab-width` with variable `tab-stop-list`.
> The former is used for the display of literal `TAB` characters.
> The latter controls what characters are inserted when you press the `TAB` character in certain modes.
>
>
>
-- [GNU Emacs Manual](https://www.gnu.org/software/emacs/manual/html_node/efaq/Changing-the-length-of-a-Tab.html)
```
(customize-variable (quote tab-stop-list))
```
or add *tab-stop-list* entry to *custom-set-variables* in *.emacs* file:
```
(custom-set-variables
;; custom-set-variables was added by Custom.
;; If you edit it by hand, you could mess it up, so be careful.
;; Your init file should contain only one such instance.
;; If there is more than one, they won't work right.
'(tab-stop-list (quote (4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80 84 88 92 96 100 104 108 112 116 120))))
```
Another way to edit the tab behavior is with with `M-x edit-tab-stops`.
See the [GNU Emacs Manual on Tab Stops](https://www.gnu.org/software/emacs/manual/html_node/emacs/Tab-Stops.html) for more information on `edit-tab-stops`. |
69,959 | <p>After successfully building dblink on solaris 10 using Sun C 5.9
SunOS_sparc 2007/05/03 and gmake.</p>
<p>I ran gmake installcheck and got the following output:</p>
<pre><code>========== running regression test queries ==========
test dblink ... FAILED
======================
1 of 1 tests failed.
</code></pre>
<p>The differences that caused some tests to fail can be viewed in the
file "./regression.diffs". A copy of the test summary that you see
above is saved in the file "./regression.out".</p>
<p>First error in regression.diffs file:</p>
<blockquote>
<p>psql:dblink.sql:11: ERROR: could not load library "/apps/postgresql/
lib/dblink.so": ld.so.1: postgre
s: fatal: relocation error: file /apps/postgresql/lib/dblink.so:
symbol PG_GETARG_TEXT_PP: referenced symbol not found</p>
</blockquote>
<p>I am running postgreSQL version 8.2.4 with the latest dblink source.</p>
<p>Has anyone got any idea what I need to do to solve this problem.
Thanks. </p>
| [
{
"answer_id": 73275,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 0,
"selected": false,
"text": "<p>Does the file it is looking for actually exist? Is it in that location?</p>\n\n<p>It may be one of a few things I can think of:\n1) The thing did not compile, and therefore does not exist.\n2) It exists, but somewhere else, and the environment variable that tells it where to find it is set wrong.\n3) The permissions are such that the ID that the postmaster is running as cannot traverse to that directory.</p>\n\n<p>To check if it is somewhere else:</p>\n\n<pre><code>find / -type f|grep dblink.so\n</code></pre>\n\n<p>To check the permissions:</p>\n\n<pre><code>su - \nsu - postgres\nless /apps/postgresql/ lib/dblink.so\n</code></pre>\n"
},
{
"answer_id": 78444,
"author": "Simon",
"author_id": 5385,
"author_profile": "https://Stackoverflow.com/users/5385",
"pm_score": 2,
"selected": true,
"text": "<p>To solve this issue I tried using the 8.2 dblink sources, instead of the latest version.</p>\n\n<p>You also need to make sure you use gnu make not the sun make.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69959",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5385/"
]
| After successfully building dblink on solaris 10 using Sun C 5.9
SunOS\_sparc 2007/05/03 and gmake.
I ran gmake installcheck and got the following output:
```
========== running regression test queries ==========
test dblink ... FAILED
======================
1 of 1 tests failed.
```
The differences that caused some tests to fail can be viewed in the
file "./regression.diffs". A copy of the test summary that you see
above is saved in the file "./regression.out".
First error in regression.diffs file:
>
> psql:dblink.sql:11: ERROR: could not load library "/apps/postgresql/
> lib/dblink.so": ld.so.1: postgre
> s: fatal: relocation error: file /apps/postgresql/lib/dblink.so:
> symbol PG\_GETARG\_TEXT\_PP: referenced symbol not found
>
>
>
I am running postgreSQL version 8.2.4 with the latest dblink source.
Has anyone got any idea what I need to do to solve this problem.
Thanks. | To solve this issue I tried using the 8.2 dblink sources, instead of the latest version.
You also need to make sure you use gnu make not the sun make. |
69,998 | <p>How do I prevent vim from replacing spaces with tabs when autoindent is on?</p>
<p>An example: if I have two tabs and 7 spaces in the beginning of the line, and <code>tabstop=3</code>, and I press Enter, the next line has four tabs and 1 space in the beginning, but I don't want that...</p>
| [
{
"answer_id": 70034,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.jwz.org/doc/tabs-vs-spaces.html\" rel=\"nofollow noreferrer\">Maybe the bottom of this can help you?</a></p>\n<blockquote>\n<p>Standard vi interprets the tab key literally, but there are popular vi-derived alternatives that are smarter, like vim. To get vim to interpret tab as an ``indent'' command instead of an insert-a-tab command, do this:</p>\n<pre><code>set softtabstop=2\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 70049,
"author": "user11211",
"author_id": 11211,
"author_profile": "https://Stackoverflow.com/users/11211",
"pm_score": 7,
"selected": true,
"text": "<p>It is perhaps a good idea not to use tabs at all.</p>\n\n<pre><code>:set expandtab\n</code></pre>\n\n<p>If you want to replace all the tabs in your file to 3 spaces (which will look pretty similar to <code>tabstop=3</code>):</p>\n\n<pre><code>:%s/^I/ /\n</code></pre>\n\n<p>(where <code>^I</code> is the <kbd>TAB</kbd> character)</p>\n\n<p>From the VIM online help:</p>\n\n<pre><code>'tabstop' 'ts' number (default 8)\n local to buffer\nNumber of spaces that a <Tab> in the file counts for. Also see\n|:retab| command, and 'softtabstop' option.\n\nNote: Setting 'tabstop' to any other value than 8 can make your file\nappear wrong in many places (e.g., when printing it).\n\nThere are four main ways to use tabs in Vim:\n1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4\n (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim\n will use a mix of tabs and spaces, but typing <Tab> and <BS> will\n behave like a tab appears every 4 (or 3) characters.\n2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use\n 'expandtab'. This way you will always insert spaces. The\n formatting will never be messed up when 'tabstop' is changed.\n3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a\n |modeline| to set these values when editing the file again. Only\n works when using Vim to edit the file.\n4. Always set 'tabstop' and 'shiftwidth' to the same value, and\n 'noexpandtab'. This should then work (for initial indents only)\n for any tabstop setting that people use. It might be nice to have\n tabs after the first non-blank inserted as spaces if you do this\n though. Otherwise aligned comments will be wrong when 'tabstop' is\n changed.\n</code></pre>\n"
},
{
"answer_id": 70054,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 5,
"selected": false,
"text": "<p>Here's part of my <code>.vimrc</code>:</p>\n\n<pre><code>set autoindent\nset expandtab\nset softtabstop=4\nset shiftwidth=4\n</code></pre>\n\n<p>This works well for me because I absolutely do not want tabs in my source code. It seems from your question that you do want to keep two tabs and seven spaces on the next line, and I'm not sure there's a way to teach vim to accommodate that style.</p>\n"
},
{
"answer_id": 71422,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>all I want is the autoindented line to have exactly the same indentation characters as the previous line.</p>\n</blockquote>\n\n<h1><a href=\"http://www.vim.org/htmldoc/options.html#%27copyindent%27\" rel=\"noreferrer\"><code>:help copyindent</code></a></h1>\n\n<blockquote>\n <h2><a href=\"http://www.vim.org/htmldoc/options.html#%27copyindent%27\" rel=\"noreferrer\">'copyindent'</a> <a href=\"http://www.vim.org/htmldoc/options.html#%27ci%27\" rel=\"noreferrer\">'ci'</a> <a href=\"http://www.vim.org/htmldoc/options.html#boolean\" rel=\"noreferrer\">boolean</a> (default off); local to buffer; {not in Vi}</h2>\n \n <p>Copy the structure of the existing lines indent when autoindenting a\n new line. Normally the new indent is reconstructed by a series of\n tabs followed by spaces as required (unless <a href=\"http://www.vim.org/htmldoc/options.html#%27expandtab%27\" rel=\"noreferrer\">'expandtab'</a> is enabled,\n in which case only spaces are used). Enabling this option makes the\n new line copy whatever characters were used for indenting on the\n existing line. If the new indent is greater than on the existing\n line, the remaining space is filled in the normal manner.</p>\n \n <p>NOTE: <a href=\"http://www.vim.org/htmldoc/options.html#%27copyindent%27\" rel=\"noreferrer\">'copyindent'</a> is reset when <a href=\"http://www.vim.org/htmldoc/options.html#%27compatible%27\" rel=\"noreferrer\">'compatible'</a> is set.<br>\n Also see <a href=\"http://www.vim.org/htmldoc/options.html#%27preserveindent%27\" rel=\"noreferrer\">'preserveindent'</a>.</p>\n</blockquote>\n\n<h1><a href=\"http://www.vim.org/htmldoc/options.html#%27preserveindent%27\" rel=\"noreferrer\"><code>:help preserveindent</code></a></h1>\n\n<blockquote>\n <h2><a href=\"http://www.vim.org/htmldoc/options.html#%27preserveindent%27\" rel=\"noreferrer\">'preserveindent'</a> <a href=\"http://www.vim.org/htmldoc/options.html#%27pi%27\" rel=\"noreferrer\">'pi'</a> <a href=\"http://www.vim.org/htmldoc/options.html#boolean\" rel=\"noreferrer\">boolean</a> (default off); local to buffer; {not in Vi}</h2>\n \n <p>When changing the indent of the current line, preserve as much of the\n indent structure as possible. Normally the indent is replaced by a\n series of tabs followed by spaces as required (unless <a href=\"http://www.vim.org/htmldoc/options.html#%27expandtab%27\" rel=\"noreferrer\">'expandtab'</a> is\n enabled, in which case only spaces are used). Enabling this option\n means the indent will preserve as many existing characters as possible\n for indenting, and only add additional tabs or spaces as required.</p>\n \n <p>NOTE: When using \">>\" multiple times the resulting indent is a mix of\n tabs and spaces. You might not like this.<br>\n NOTE: <a href=\"http://www.vim.org/htmldoc/options.html#%27preserveindent%27\" rel=\"noreferrer\">'preserveindent'</a> is reset when <a href=\"http://www.vim.org/htmldoc/options.html#%27compatible%27\" rel=\"noreferrer\">'compatible'</a> is set.<br>\n Also see <a href=\"http://www.vim.org/htmldoc/options.html#%27copyindent%27\" rel=\"noreferrer\">'copyindent'</a>.<br>\n Use :retab to clean up white space.</p>\n</blockquote>\n"
},
{
"answer_id": 159130,
"author": "graywh",
"author_id": 18038,
"author_profile": "https://Stackoverflow.com/users/18038",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to replace all the tabs with spaces based on the setting of 'ts', you can use :retab. It can also do the reverse.</p>\n"
},
{
"answer_id": 5790967,
"author": "kev",
"author_id": 348785,
"author_profile": "https://Stackoverflow.com/users/348785",
"pm_score": 6,
"selected": false,
"text": "<p>You can convert all <code>TAB</code> to <code>SPACE</code></p>\n\n<pre><code>:set et\n:ret!\n</code></pre>\n\n<p>or convert all <code>SPACE</code> to <code>TAB</code></p>\n\n<pre><code>:set et!\n:ret!\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/69998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How do I prevent vim from replacing spaces with tabs when autoindent is on?
An example: if I have two tabs and 7 spaces in the beginning of the line, and `tabstop=3`, and I press Enter, the next line has four tabs and 1 space in the beginning, but I don't want that... | It is perhaps a good idea not to use tabs at all.
```
:set expandtab
```
If you want to replace all the tabs in your file to 3 spaces (which will look pretty similar to `tabstop=3`):
```
:%s/^I/ /
```
(where `^I` is the `TAB` character)
From the VIM online help:
```
'tabstop' 'ts' number (default 8)
local to buffer
Number of spaces that a <Tab> in the file counts for. Also see
|:retab| command, and 'softtabstop' option.
Note: Setting 'tabstop' to any other value than 8 can make your file
appear wrong in many places (e.g., when printing it).
There are four main ways to use tabs in Vim:
1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4
(or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim
will use a mix of tabs and spaces, but typing <Tab> and <BS> will
behave like a tab appears every 4 (or 3) characters.
2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use
'expandtab'. This way you will always insert spaces. The
formatting will never be messed up when 'tabstop' is changed.
3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a
|modeline| to set these values when editing the file again. Only
works when using Vim to edit the file.
4. Always set 'tabstop' and 'shiftwidth' to the same value, and
'noexpandtab'. This should then work (for initial indents only)
for any tabstop setting that people use. It might be nice to have
tabs after the first non-blank inserted as spaces if you do this
though. Otherwise aligned comments will be wrong when 'tabstop' is
changed.
``` |
70,013 | <p>Is there any way to know if I'm compiling under a specific Microsoft Visual Studio version?</p>
| [
{
"answer_id": 70021,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": -1,
"selected": false,
"text": "<p>In visual studio, go to help | about and look at the version of Visual Studio that you're using to compile your app.</p>\n"
},
{
"answer_id": 70028,
"author": "DJ Capelis",
"author_id": 10943,
"author_profile": "https://Stackoverflow.com/users/10943",
"pm_score": 4,
"selected": false,
"text": "<p>_MSC_VER should be defined to a specific version number. You can either #ifdef on it, or you can use the actual define and do a runtime test. (If for some reason you wanted to run different code based on what compiler it was compiled with? Yeah, probably you were looking for the #ifdef. :))</p>\n"
},
{
"answer_id": 70041,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 3,
"selected": false,
"text": "<p>By using the <code>_MSC_VER</code> macro.</p>\n"
},
{
"answer_id": 70630,
"author": "jilles de wit",
"author_id": 7531,
"author_profile": "https://Stackoverflow.com/users/7531",
"pm_score": 10,
"selected": true,
"text": "<p><code>_MSC_VER</code> and possibly <code>_MSC_FULL_VER</code> is what you need. You can also examine <a href=\"https://www.boost.org/doc/libs/master/boost/config/compiler/visualc.hpp\" rel=\"noreferrer\">visualc.hpp</a> in any recent boost install for some usage examples.</p>\n\n<p>Some values for the more recent versions of the compiler are:</p>\n\n<pre><code>MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)\nMSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)\nMSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)\nMSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)\nMSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)\nMSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)\nMSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)\nMSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)\nMSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)\nMSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)\nMSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)\nMSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)\nMSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)\nMSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)\nMSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)\nMSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)\nMSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)\nMSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)\nMSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)\nMSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)\nMSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)\nMSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)\nMSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0)\n</code></pre>\n\n<p>The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found <a href=\"https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering\" rel=\"noreferrer\">here</a>. <a href=\"https://blogs.msdn.microsoft.com/vcblog/2016/10/05/visual-c-compiler-version/\" rel=\"noreferrer\">Starting recently</a>, Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.</p>\n\n<p><code>cl.exe /?</code> will give a hint of the used version, e.g.:</p>\n\n<pre><code>c:\\program files (x86)\\microsoft visual studio 11.0\\vc\\bin>cl /?\nMicrosoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86\n.....\n</code></pre>\n"
},
{
"answer_id": 81262,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This is a little old but should get you started:</p>\n\n<pre><code>//******************************************************************************\n// Automated platform detection\n//******************************************************************************\n\n// _WIN32 is used by\n// Visual C++\n#ifdef _WIN32\n#define __NT__\n#endif\n\n// Define __MAC__ platform indicator\n#ifdef macintosh\n#define __MAC__\n#endif\n\n// Define __OSX__ platform indicator\n#ifdef __APPLE__\n#define __OSX__\n#endif\n\n// Define __WIN16__ platform indicator \n#ifdef _Windows_\n#ifndef __NT__\n#define __WIN16__\n#endif\n#endif\n\n// Define Windows CE platform indicator\n#ifdef WIN32_PLATFORM_HPCPRO\n#define __WINCE__\n#endif\n\n#if (_WIN32_WCE == 300) // for Pocket PC\n#define __POCKETPC__\n#define __WINCE__\n//#if (_WIN32_WCE == 211) // for Palm-size PC 2.11 (Wyvern)\n//#if (_WIN32_WCE == 201) // for Palm-size PC 2.01 (Gryphon) \n//#ifdef WIN32_PLATFORM_HPC2000 // for H/PC 2000 (Galileo)\n#endif\n</code></pre>\n"
},
{
"answer_id": 3786113,
"author": "display101",
"author_id": 167899,
"author_profile": "https://Stackoverflow.com/users/167899",
"pm_score": 6,
"selected": false,
"text": "<p>Yep _MSC_VER is the macro that'll get you the compiler version. The last number of releases of Visual C++ have been of the form <code><compiler-major-version>.00.<build-number></code>, where 00 is the minor number. So <code>_MSC_VER</code> will evaluate to <code><major-version><minor-version></code>.</p>\n\n<p>You can use code like this:</p>\n\n<pre><code>#if (_MSC_VER == 1500)\n // ... Do VC9/Visual Studio 2008 specific stuff\n#elif (_MSC_VER == 1600)\n // ... Do VC10/Visual Studio 2010 specific stuff\n#elif (_MSC_VER == 1700)\n // ... Do VC11/Visual Studio 2012 specific stuff\n#endif\n</code></pre>\n\n<p>It appears updates between successive releases of the compiler, have not modified the <code>compiler-minor-version</code>, so the following code is not required:</p>\n\n<pre><code>#if (_MSC_VER >= 1500 && _MSC_VER <= 1600)\n // ... Do VC9/Visual Studio 2008 specific stuff\n#endif\n</code></pre>\n\n<p>Access to more detailed versioning information (such as compiler build number) can be found using other builtin pre-processor variables <a href=\"http://msdn.microsoft.com/en-us/library/b0084kay.aspx\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 16699310,
"author": "Clifford",
"author_id": 168986,
"author_profile": "https://Stackoverflow.com/users/168986",
"pm_score": 2,
"selected": false,
"text": "<p>As a more general answer <a href=\"http://sourceforge.net/p/predef/wiki/Home/\" rel=\"nofollow\">http://sourceforge.net/p/predef/wiki/Home/</a> maintains a list of macros for detecting specicic compilers, operating systems, architectures, standards and more.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
]
| Is there any way to know if I'm compiling under a specific Microsoft Visual Studio version? | `_MSC_VER` and possibly `_MSC_FULL_VER` is what you need. You can also examine [visualc.hpp](https://www.boost.org/doc/libs/master/boost/config/compiler/visualc.hpp) in any recent boost install for some usage examples.
Some values for the more recent versions of the compiler are:
```
MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)
MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)
MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)
MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)
MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)
MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)
MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)
MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)
MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)
MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)
MSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)
MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)
MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)
MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)
MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)
MSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)
MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)
MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)
MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)
MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)
MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)
MSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0)
```
The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found [here](https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering). [Starting recently](https://blogs.msdn.microsoft.com/vcblog/2016/10/05/visual-c-compiler-version/), Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.
`cl.exe /?` will give a hint of the used version, e.g.:
```
c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
.....
``` |
70,074 | <p>I'm new to Ruby, so I'm having some trouble understanding this weird exception problem I'm having. I'm using the ruby-aaws gem to access Amazon ECS: <a href="http://www.caliban.org/ruby/ruby-aws/" rel="nofollow noreferrer">http://www.caliban.org/ruby/ruby-aws/</a>. This defines a class Amazon::AWS:Error:</p>
<pre><code>module Amazon
module AWS
# All dynamically generated exceptions occur within this namespace.
#
module Error
# An exception generator class.
#
class AWSError
attr_reader :exception
def initialize(xml)
err_class = xml.elements['Code'].text.sub( /^AWS.*\./, '' )
err_msg = xml.elements['Message'].text
unless Amazon::AWS::Error.const_defined?( err_class )
Amazon::AWS::Error.const_set( err_class,
Class.new( StandardError ) )
end
ex_class = Amazon::AWS::Error.const_get( err_class )
@exception = ex_class.new( err_msg )
end
end
end
end
end
</code></pre>
<p>This means that if you get an errorcode like <code>AWS.InvalidParameterValue</code>, this will produce (in its exception variable) a new class <code>Amazon::AWS::Error::InvalidParameterValue</code> which is a subclass of <code>StandardError</code>.</p>
<p>Now here's where it gets weird. I have some code that looks like this:</p>
<pre><code>begin
do_aws_stuff
rescue Amazon::AWS::Error => error
puts "Got an AWS error"
end
</code></pre>
<p>Now, if <code>do_aws_stuff</code> throws a <code>NameError</code>, my rescue block gets triggered. It seems that Amazon::AWS::Error isn't the superclass of the generated error - I guess since it's a module everything is a subclass of it? Certainly if I do:</p>
<pre><code>irb(main):007:0> NameError.new.kind_of?(Amazon::AWS::Error)
=> true
</code></pre>
<p>It says <code>true</code>, which I find confusing, especially given this:</p>
<pre><code>irb(main):009:0> NameError.new.kind_of?(Amazon::AWS)
=> false
</code></pre>
<p>What's going on, and how am I supposed to separate out AWS errors from other type of errors? Should I do something like:</p>
<pre><code>begin
do_aws_stuff
rescue => error
if error.class.to_s =~ /^Amazon::AWS::Error/
puts "Got an AWS error"
else
raise error
end
end
</code></pre>
<p>That seems exceptionally janky. The errors thrown aren't class AWSError either - they're raised like this:</p>
<pre><code>error = Amazon::AWS::Error::AWSError.new( xml )
raise error.exception
</code></pre>
<p>So the exceptions I'm looking to <code>rescue</code> from are the generated exception types that only inherit from StandardError.</p>
<p>To clarify, I have two questions:</p>
<ol>
<li><p>Why is NameError, a Ruby built in exception, a <code>kind_of?(Amazon::AWS::Error)</code>, which is a module?<br>
<strong>Answer:</strong> I had said <code>include Amazon::AWS::Error</code> at the top of my file, thinking it was kind of like a Java import or C++ include. What this actually did was add everything defined in <code>Amazon::AWS::Error</code> (present and future) to the implicit Kernel class, which is an ancestor of every class. This means <strong>anything</strong> would pass <code>kind_of?(Amazon::AWS::Error)</code>.</p></li>
<li><p>How can I best distinguish the dynamically-created exceptions in <code>Amazon::AWS::Error</code> from random other exceptions from elsewhere?</p></li>
</ol>
| [
{
"answer_id": 70127,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>Well, from what I can tell:</p>\n\n<pre><code>Class.new( StandardError )\n</code></pre>\n\n<p>Is creating a new class with StandardError as the base class, so it is not going to be a Amazon::AWS::Error at all. It is just defined in that module, which is probably why it is a kind_of? Amazon::AWS::Error. It probably isn't a kind_of? Amazon::AWS because maybe modules don't nest for purposes of kind_of? ?</p>\n\n<p>Sorry, I don't know modules very well in Ruby, but most definitely the base class is going to be StandardError.</p>\n\n<p><strong>UPDATE</strong>: By the way, <a href=\"http://www.ruby-doc.org/core/classes/Object.html#M000370\" rel=\"nofollow noreferrer\">from the ruby docs</a>:</p>\n\n<blockquote>\n <p>obj.kind_of?(class) => true or false</p>\n \n <p>Returns true if class is the class of obj, or if class is one of the superclasses of obj or modules included in obj.</p>\n</blockquote>\n"
},
{
"answer_id": 70231,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 4,
"selected": true,
"text": "<p>Ok, I'll try to help here : </p>\n\n<p>First a module is not a class, it allows you to mix behaviour in a class. second see the following example : </p>\n\n<pre><code>module A\n module B\n module Error\n def foobar\n puts \"foo\"\n end\n end\n end\nend\n\nclass StandardError\n include A::B::Error\nend\n\nStandardError.new.kind_of?(A::B::Error)\nStandardError.new.kind_of?(A::B)\nStandardError.included_modules #=> [A::B::Error,Kernel]\n</code></pre>\n\n<p>kind_of? tells you that yes, Error does possess All of A::B::Error behaviour (which is normal since it includes A::B::Error) however it does not include all the behaviour from A::B and therefore is not of the A::B kind. (duck typing)</p>\n\n<p>Now there is a very good chance that ruby-aws reopens one of the superclass of NameError and includes Amazon::AWS:Error in there. (monkey patching)</p>\n\n<p>You can find out programatically where the module is included in the hierarchy with the following :</p>\n\n<pre><code>class Class\n def has_module?(module_ref)\n if self.included_modules.include?(module_ref) and not self.superclass.included_modules.include?(module_ref) \n puts self.name+\" has module \"+ module_ref.name \n else\n self.superclass.nil? ? false : self.superclass.has_module?(module_ref)\n end \n end\nend\nStandardError.has_module?(A::B::Error)\nNameError.has_module?(A::B::Error)\n</code></pre>\n\n<p>Regarding your second question I can't see anything better than </p>\n\n<pre><code>begin \n#do AWS error prone stuff\nrescue Exception => e\n if Amazon::AWS::Error.constants.include?(e.class.name)\n #awsError\n else\n whatever\n end \nend\n</code></pre>\n\n<p>(edit -- above code doesn't work as is : name includes module prefix which is not the case of the constants arrays. You should definitely contact the lib maintainer the AWSError class looks more like a factory class to me :/ )</p>\n\n<p>I don't have ruby-aws here and the caliban site is blocked by the company's firewall so I can't test much further. </p>\n\n<p>Regarding the include : that might be the thing doing the monkey patching on the StandardError hierarchy. I am not sure anymore but most likely doing it at the root of a file outside every context is including the module on Object or on the Object metaclass. (this is what would happen in IRB, where the default context is Object, not sure about in a file)</p>\n\n<p>from the <a href=\"http://www.rubycentral.com/pickaxe/tut_modules.html\" rel=\"nofollow noreferrer\">pickaxe on modules</a> :</p>\n\n<p><code>A couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require to drag that file in before using include.</code></p>\n\n<p>(edit -- I can't seem to be able to comment using this browser :/ yay for locked in platforms) </p>\n"
},
{
"answer_id": 71517,
"author": "0124816",
"author_id": 11521,
"author_profile": "https://Stackoverflow.com/users/11521",
"pm_score": 1,
"selected": false,
"text": "<p>Just wanted to chime in: I would agree this is a bug in the lib code. It should probably read:</p>\n\n<pre><code> unless Amazon::AWS::Error.const_defined?( err_class )\n kls = Class.new( StandardError )\n Amazon::AWS::Error.const_set(err_class, kls)\n kls.include Amazon::AWS::Error\n end\n</code></pre>\n"
},
{
"answer_id": 1517791,
"author": "Peter Wagenet",
"author_id": 181916,
"author_profile": "https://Stackoverflow.com/users/181916",
"pm_score": 0,
"selected": false,
"text": "<p>One issue you're running into is that <code>Amazon::AWS::Error::AWSError</code> is not actually an exception. When <code>raise</code> is called, it looks to see if the first parameter responds to the <code>exception</code> method and will use the result of that instead. Anything that is a subclass of <code>Exception</code> will return itself when <code>exception</code> is called so you can do things like <code>raise Exception.new(\"Something is wrong\")</code>.</p>\n\n<p>In this case, <code>AWSError</code> has <code>exception</code> set up as an attribute reader which it defines the value to on initialization to something like <code>Amazon::AWS::Error::SOME_ERROR</code>. This means that when you call <code>raise Amazon::AWS::Error::AWSError.new(SOME_XML)</code> Ruby ends up calling <code>Amazon::AWS::Error::AWSError.new(SOME_XML).exception</code> which will returns an instance of <code>Amazon::AWS::Error::SOME_ERROR</code>. As was pointed out by one of the other responders, this class is a direct subclass of <code>StandardError</code> instead of being a subclass of a common Amazon error. Until this is rectified, Jean's solution is probably your best bet.</p>\n\n<p>I hope that helped explain more of what's actually going on behind the scenes.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11284/"
]
| I'm new to Ruby, so I'm having some trouble understanding this weird exception problem I'm having. I'm using the ruby-aaws gem to access Amazon ECS: <http://www.caliban.org/ruby/ruby-aws/>. This defines a class Amazon::AWS:Error:
```
module Amazon
module AWS
# All dynamically generated exceptions occur within this namespace.
#
module Error
# An exception generator class.
#
class AWSError
attr_reader :exception
def initialize(xml)
err_class = xml.elements['Code'].text.sub( /^AWS.*\./, '' )
err_msg = xml.elements['Message'].text
unless Amazon::AWS::Error.const_defined?( err_class )
Amazon::AWS::Error.const_set( err_class,
Class.new( StandardError ) )
end
ex_class = Amazon::AWS::Error.const_get( err_class )
@exception = ex_class.new( err_msg )
end
end
end
end
end
```
This means that if you get an errorcode like `AWS.InvalidParameterValue`, this will produce (in its exception variable) a new class `Amazon::AWS::Error::InvalidParameterValue` which is a subclass of `StandardError`.
Now here's where it gets weird. I have some code that looks like this:
```
begin
do_aws_stuff
rescue Amazon::AWS::Error => error
puts "Got an AWS error"
end
```
Now, if `do_aws_stuff` throws a `NameError`, my rescue block gets triggered. It seems that Amazon::AWS::Error isn't the superclass of the generated error - I guess since it's a module everything is a subclass of it? Certainly if I do:
```
irb(main):007:0> NameError.new.kind_of?(Amazon::AWS::Error)
=> true
```
It says `true`, which I find confusing, especially given this:
```
irb(main):009:0> NameError.new.kind_of?(Amazon::AWS)
=> false
```
What's going on, and how am I supposed to separate out AWS errors from other type of errors? Should I do something like:
```
begin
do_aws_stuff
rescue => error
if error.class.to_s =~ /^Amazon::AWS::Error/
puts "Got an AWS error"
else
raise error
end
end
```
That seems exceptionally janky. The errors thrown aren't class AWSError either - they're raised like this:
```
error = Amazon::AWS::Error::AWSError.new( xml )
raise error.exception
```
So the exceptions I'm looking to `rescue` from are the generated exception types that only inherit from StandardError.
To clarify, I have two questions:
1. Why is NameError, a Ruby built in exception, a `kind_of?(Amazon::AWS::Error)`, which is a module?
**Answer:** I had said `include Amazon::AWS::Error` at the top of my file, thinking it was kind of like a Java import or C++ include. What this actually did was add everything defined in `Amazon::AWS::Error` (present and future) to the implicit Kernel class, which is an ancestor of every class. This means **anything** would pass `kind_of?(Amazon::AWS::Error)`.
2. How can I best distinguish the dynamically-created exceptions in `Amazon::AWS::Error` from random other exceptions from elsewhere? | Ok, I'll try to help here :
First a module is not a class, it allows you to mix behaviour in a class. second see the following example :
```
module A
module B
module Error
def foobar
puts "foo"
end
end
end
end
class StandardError
include A::B::Error
end
StandardError.new.kind_of?(A::B::Error)
StandardError.new.kind_of?(A::B)
StandardError.included_modules #=> [A::B::Error,Kernel]
```
kind\_of? tells you that yes, Error does possess All of A::B::Error behaviour (which is normal since it includes A::B::Error) however it does not include all the behaviour from A::B and therefore is not of the A::B kind. (duck typing)
Now there is a very good chance that ruby-aws reopens one of the superclass of NameError and includes Amazon::AWS:Error in there. (monkey patching)
You can find out programatically where the module is included in the hierarchy with the following :
```
class Class
def has_module?(module_ref)
if self.included_modules.include?(module_ref) and not self.superclass.included_modules.include?(module_ref)
puts self.name+" has module "+ module_ref.name
else
self.superclass.nil? ? false : self.superclass.has_module?(module_ref)
end
end
end
StandardError.has_module?(A::B::Error)
NameError.has_module?(A::B::Error)
```
Regarding your second question I can't see anything better than
```
begin
#do AWS error prone stuff
rescue Exception => e
if Amazon::AWS::Error.constants.include?(e.class.name)
#awsError
else
whatever
end
end
```
(edit -- above code doesn't work as is : name includes module prefix which is not the case of the constants arrays. You should definitely contact the lib maintainer the AWSError class looks more like a factory class to me :/ )
I don't have ruby-aws here and the caliban site is blocked by the company's firewall so I can't test much further.
Regarding the include : that might be the thing doing the monkey patching on the StandardError hierarchy. I am not sure anymore but most likely doing it at the root of a file outside every context is including the module on Object or on the Object metaclass. (this is what would happen in IRB, where the default context is Object, not sure about in a file)
from the [pickaxe on modules](http://www.rubycentral.com/pickaxe/tut_modules.html) :
`A couple of points about the include statement before we go on. First, it has nothing to do with files. C programmers use a preprocessor directive called #include to insert the contents of one file into another during compilation. The Ruby include statement simply makes a reference to a named module. If that module is in a separate file, you must use require to drag that file in before using include.`
(edit -- I can't seem to be able to comment using this browser :/ yay for locked in platforms) |
70,090 | <p>How can I visually customize autocomplete fields in Wicket (change colors, fonts, etc.)?</p>
| [
{
"answer_id": 77292,
"author": "Loren_",
"author_id": 13703,
"author_profile": "https://Stackoverflow.com/users/13703",
"pm_score": 4,
"selected": true,
"text": "<p>You can use CSS to modify the look of this component. For the Ajax auto-complete component in 1.3 the element you want to override is div.wicket-aa, so for example you might do:</p>\n\n<pre><code>div.wicket-aa {\n background-color:white;\n border:1px solid #CCCCCC;\n color:black;\n}\ndiv.wicket-aa ul {\n list-style-image:none;\n list-style-position:outside;\n list-style-type:none;\n margin:0pt;\n padding:5px;\n}\ndiv.wicket-aa ul li.selected {\n background-color:#CCCCCC;\n}\n</code></pre>\n"
},
{
"answer_id": 77333,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 1,
"selected": false,
"text": "<p>Perilandmishap has probably the most usefull answer for your needs. Personally, I always found the default Ajax auto complete control in Wicket to be woefully insufficient for my needs. If you really want a professional \"feel\" to your auto complete, roll your an using Wicket's Ajax libraries.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11384/"
]
| How can I visually customize autocomplete fields in Wicket (change colors, fonts, etc.)? | You can use CSS to modify the look of this component. For the Ajax auto-complete component in 1.3 the element you want to override is div.wicket-aa, so for example you might do:
```
div.wicket-aa {
background-color:white;
border:1px solid #CCCCCC;
color:black;
}
div.wicket-aa ul {
list-style-image:none;
list-style-position:outside;
list-style-type:none;
margin:0pt;
padding:5px;
}
div.wicket-aa ul li.selected {
background-color:#CCCCCC;
}
``` |
70,096 | <p>I've been looking for a way to convert an mp3 to aac programmatically or via the command line with no luck. Ideally, I'd have a snippet of code that I could call from my rails app that converts an mp3 to an aac. I installed ffmpeg and libfaac and was able to create an aac file with the following command:</p>
<p><code>ffmpeg -i test.mp3 -acodec libfaac -ab 163840 dest.aac</code></p>
<p>When i change the output file's name to dest.m4a, it doesn't play in iTunes. </p>
<p>Thanks! </p>
| [
{
"answer_id": 70117,
"author": "Dark Shikari",
"author_id": 11206,
"author_profile": "https://Stackoverflow.com/users/11206",
"pm_score": 2,
"selected": false,
"text": "<p>There are only three free AAC encoders that I know of that are available through a commandline interface:</p>\n\n<ol>\n<li><p>FAAC (LPGL), which is honestly pretty bad (the quality is going to be significantly worse than LAME at the same bitrate). Its fine though if you're willing to go for higher bitrates (>>128kbps) and need AAC for compatibility, not quality reasons. The most common way to use FAAC is through ffmpeg, as libfaac.</p></li>\n<li><p>Nero AAC, the commandline encoder for which is available for free under Windows and Linux, but only for noncommercial use (and is correspondingly closed-source).</p></li>\n<li><p>ffmpeg's AAC encoder, which is still under development and while I believe it does technically work, it is not at all stable or good or even fast, since its still in the initial stages. Its also not available in trunk, as far as I know.</p></li>\n</ol>\n\n<p>(Edit: Seems iTunes might have one too, I suspect its terms of use are similar to Nero's. AFAIK its quality is comparable.)</p>\n"
},
{
"answer_id": 70122,
"author": "Sev",
"author_id": 83819,
"author_profile": "https://Stackoverflow.com/users/83819",
"pm_score": 1,
"selected": false,
"text": "<p>After installing the converting app on the linux/window machine you're running your Rails application on, use the \"system()\" command in Ruby to invoke the converting application on the system. system(\"command_here\");</p>\n"
},
{
"answer_id": 70138,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Ffmpeg\" rel=\"noreferrer\">FFmpeg</a> provides AAC encoding facilities if you've compiled them in. If you are using Windows you can grab full binaries from <a href=\"http://arrozcru.no-ip.org/ffmpeg_builds/\" rel=\"noreferrer\">here</a></p>\n\n<pre><code>ffmpeg -i source.mp3 -acodec libfaac -ab 128k dest.aac\n</code></pre>\n\n<p>I'm not sure how you would call this from ruby.</p>\n\n<p>Also, be sure to set the bitrate appropriately.</p>\n"
},
{
"answer_id": 72678,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 0,
"selected": false,
"text": "<p>I've had good luck using mplayer (which I believe uses ffmpeg...) and lame. To the point that I've wrapped it up in a script:</p>\n\n<pre><code>#!/bin/sh\n\nTARGET=$1\n\nBASE=`basename \"${TARGET}\"`\necho TARGET: \"${TARGET}\"\necho BASE: \"${BASE}\" .m4a\n\n# Warning! Race condition vulnerability here! Should use a mktemp\n# variant or something...\nmkfifo encode\nmplayer -quiet -ao pcm -aofile encode \"${TARGET}\" &\nlame --silent encode \"${BASE}\".mp3\nrm encode\n</code></pre>\n\n<p>Sorry for the security issues, I banged this out on the train one day...</p>\n\n<p>My mplayer and lame come from <a href=\"http://www.finkproject.org/\" rel=\"nofollow noreferrer\">fink</a></p>\n"
},
{
"answer_id": 154619,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 2,
"selected": false,
"text": "<p>I realize I'm late to this party, but I'm questioning the premise of this question. Why do you even want to convert an MP3 to an \"itunes playable\" format? iTunes already handles MP3s natively. </p>\n\n<p>It seems like you are doing an unnecessary conversion, and since you are converting from one lossy format to another, you are losing some quality in the process.</p>\n"
},
{
"answer_id": 2518567,
"author": "Jacek Glinkowski",
"author_id": 301982,
"author_profile": "https://Stackoverflow.com/users/301982",
"pm_score": 2,
"selected": false,
"text": "<p>in ffmpeg 0.5 or later use\nffmpeg -i source.mp3 target.m4a</p>\n\n<p>for better results to transfer metadata and to override default bitrate ffmpeg applies</p>\n\n<p>ffmpeg -i \"input.mp3\" -ab 256k -map_meta_data input.mp3:output.m4a output.m4a</p>\n\n<p>best do not convert as ipod plays mp3 fine (I know there is such answer but my low standing does not allow voting)</p>\n"
},
{
"answer_id": 23302325,
"author": "user62107",
"author_id": 3574313,
"author_profile": "https://Stackoverflow.com/users/3574313",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, syntax is ffmpeg -i input.mp3 -c:a aac -strict -2 -b:a 256k output.m4a; more correct if one is emulating \"correct\" bitrate. \ncf.:<a href=\"http://ffmpeg.gusari.org/viewtopic.php?f=25&t=38\" rel=\"nofollow\">link</a> for a compilation scheme. (rpmfusion package works fine too:</p>\n\n<p>configuration: --prefix=/usr --bindir=/usr/bin --datadir=/usr/share/ffmpeg --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --optflags='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic' --enable-bzlib --disable-crystalhd --enable-frei0r --enable-gnutls --enable-libass --enable-libcdio --enable-libcelt --enable-libdc1394 --disable-indev=jack --enable-libfreetype --enable-libgsm --enable-libmp3lame --enable-openal --enable-libopencv --enable-libopenjpeg --enable-libopus --enable-libpulse --enable-libschroedinger --enable-libsoxr --enable-libspeex --enable-libtheora --enable-libvorbis --enable-libv4l2 --enable-libvpx --enable-libx264 --enable-libxvid --enable-x11grab --enable-avfilter --enable-avresample --enable-postproc --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-stripping --shlibdir=/usr/lib64 --enable-runtime-cpudetect</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I've been looking for a way to convert an mp3 to aac programmatically or via the command line with no luck. Ideally, I'd have a snippet of code that I could call from my rails app that converts an mp3 to an aac. I installed ffmpeg and libfaac and was able to create an aac file with the following command:
`ffmpeg -i test.mp3 -acodec libfaac -ab 163840 dest.aac`
When i change the output file's name to dest.m4a, it doesn't play in iTunes.
Thanks! | [FFmpeg](http://en.wikipedia.org/wiki/Ffmpeg) provides AAC encoding facilities if you've compiled them in. If you are using Windows you can grab full binaries from [here](http://arrozcru.no-ip.org/ffmpeg_builds/)
```
ffmpeg -i source.mp3 -acodec libfaac -ab 128k dest.aac
```
I'm not sure how you would call this from ruby.
Also, be sure to set the bitrate appropriately. |
70,123 | <p>If I have a table structure that is: </p>
<pre><code>code, description, isdeleted
</code></pre>
<p>where <code>code</code> is the primary key.</p>
<p>The user creates a record, then later on deletes it. Because I am using soft deletes the <code>isdeleted</code> will be set to true. Then in my queries I would be doing a select with the where clause <code>and not isdeleted</code></p>
<p>Now if a user goes to create a new record they may see that code 'ABC' doesn't exist so they tried to recreate it. The select statement won't find it because of the where clause. But there will be a primary key index error.</p>
<p>Should the user be allowed to re-use the record? I would think not since the idea of the soft delete is to keep the record for queries on older data so that joins to the 'deleted' record still work. If the user was allowed to re-use the code then they could change the description which might change the view of the historical data. But is it too harsh to stop them from using that code at all?</p>
<p>Or should I be using a completely hidden primary key and then the 'code' field can be re-used?</p>
| [
{
"answer_id": 70149,
"author": "Wayne",
"author_id": 8236,
"author_profile": "https://Stackoverflow.com/users/8236",
"pm_score": 2,
"selected": false,
"text": "<p>I know many people have argued that the data should be natural, but you should be using a primary key that is completely separate from your data if you're going to be supporting soft deletes without the intention of always re-using the previous record when this situation arises.</p>\n\n<p>Having a divorced primary key will allow you to have multiple records with the same 'code' value, and it will allow you to \"undelete\" (otherwise, why bother with a soft delete?) a value without worrying about overwriting something else.</p>\n\n<p>Personally, I prefer the numeric auto-incremented style of ID, but there are many proponents of GUIDs.</p>\n"
},
{
"answer_id": 70152,
"author": "deemer",
"author_id": 11192,
"author_profile": "https://Stackoverflow.com/users/11192",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Or should I be using a completely\n hidden primary key and then the 'code'\n field can be re-used?</p>\n</blockquote>\n\n<p>I think you have answered this pretty well yourself. If you want the user to be able to re-use the deleted codes, then you should have a separate primary key not visisble to the user. If it is important that the codes be unique, then the users should generally not be entering them anyway.</p>\n"
},
{
"answer_id": 70214,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 1,
"selected": false,
"text": "<p>I think it depends on the specific data you're talking about.</p>\n\n<p>If the user is trying to recreate code 'ABC', is it the SAME 'ABC' that was in use last time that has now come out of retirement, or is it a completely different 'ABC'?</p>\n\n<p>If it actually refers to the same real-world 'thing', then there may be no harm in simply 'undeleting' it. After all - it's the same thing, so logically speaking it should show up as the same thing in historical and new queries. If your user decides they don't need it any more, then they can delete it and it'll go away. If at some point in the future they need it again, they can effectively un-delete it by adding it in again.</p>\n\n<p>If, however, the new 'ABC' refers to something (in the real world) which is different to the old 'ABC', then you could argue that the 'code' isn't <em>actually</em> a primary key, in which case, if your data doesn't provide any other natural choice, you may just as well create an arbitrary key. </p>\n\n<p>A big downside of this is that you'll have to be pretty careful not to let the user create two active records with the same 'code', of course.</p>\n"
},
{
"answer_id": 70230,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "<p>When you select records (excluding soft-deletes) to display them in user interface/ output file, use where not isdeleted.</p>\n\n<p>But when the user requests an insert operation, perform two queries.</p>\n\n<ol>\n<li><p>Lookup all records (ignoring isdeleted value).</p></li>\n<li><p>Based on first query result, perform an UPDATE if it exists (and reverse isdeleted flag) or perform a true INSERT if it does not exist.</p></li>\n</ol>\n\n<p>The nuances of the business logic are up to you.</p>\n"
},
{
"answer_id": 70243,
"author": "user10479",
"author_id": 10479,
"author_profile": "https://Stackoverflow.com/users/10479",
"pm_score": 0,
"selected": false,
"text": "<p>I've done this with user tables, where the email is a unique constraint. If someone cancels there account, their information is still needed for referential integrity, so what I to is set is_deteled to true, and add '_deleted' to the email field. In this way, if the user decides to sign up again in the future, there is no problem for the user and the unique constraint is not broken.</p>\n\n<p>I think soft delete is good in some situations. For example, if someone deleted their account from this site and you delete their user then all their posts and answers would be lost. I think it is much better to soft delete and display their user as \"deleted user\" or something similar... oh, I also believe in divorced primary keys</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11355/"
]
| If I have a table structure that is:
```
code, description, isdeleted
```
where `code` is the primary key.
The user creates a record, then later on deletes it. Because I am using soft deletes the `isdeleted` will be set to true. Then in my queries I would be doing a select with the where clause `and not isdeleted`
Now if a user goes to create a new record they may see that code 'ABC' doesn't exist so they tried to recreate it. The select statement won't find it because of the where clause. But there will be a primary key index error.
Should the user be allowed to re-use the record? I would think not since the idea of the soft delete is to keep the record for queries on older data so that joins to the 'deleted' record still work. If the user was allowed to re-use the code then they could change the description which might change the view of the historical data. But is it too harsh to stop them from using that code at all?
Or should I be using a completely hidden primary key and then the 'code' field can be re-used? | I know many people have argued that the data should be natural, but you should be using a primary key that is completely separate from your data if you're going to be supporting soft deletes without the intention of always re-using the previous record when this situation arises.
Having a divorced primary key will allow you to have multiple records with the same 'code' value, and it will allow you to "undelete" (otherwise, why bother with a soft delete?) a value without worrying about overwriting something else.
Personally, I prefer the numeric auto-incremented style of ID, but there are many proponents of GUIDs. |
70,143 | <p>I have a xslt stylesheet with multiple <code>xsl:import</code>s and I want to merge them all into the one xslt file.</p>
<p>It is a limitation of the system we are using where it passes around the xsl stylesheet as a string object stored in memory. This is transmitted to remote machine where it performs the transformation. Since it is not being loaded from disk the href links are broken, so we need to remove the <code>xsl:import</code>s from the stylesheet.</p>
<p>Are there any tools out there which can do this?</p>
| [
{
"answer_id": 70180,
"author": "chrisb",
"author_id": 8262,
"author_profile": "https://Stackoverflow.com/users/8262",
"pm_score": 0,
"selected": false,
"text": "<p>Why would you want to? They're usually seperated for a reason afterall (often maintainability)</p>\n\n<p>You could always write the merge yourself - read the XSL files in, select the template items you're interested in and write to a new master XSL file...</p>\n"
},
{
"answer_id": 70279,
"author": "Robert Christie",
"author_id": 11069,
"author_profile": "https://Stackoverflow.com/users/11069",
"pm_score": 1,
"selected": false,
"text": "<p>A Manual merge is probably going to be the best option. </p>\n\n<p>The main consideration will probably be to make sure that the logic for matching templates works in the combined stylesheet.</p>\n"
},
{
"answer_id": 70357,
"author": "Azat Razetdinov",
"author_id": 9649,
"author_profile": "https://Stackoverflow.com/users/9649",
"pm_score": 2,
"selected": false,
"text": "<p>It is impossible to include imported stylsheets into the main file without breaking <a href=\"http://www.w3.org/TR/xslt#dt-import-precedence\" rel=\"nofollow noreferrer\">import precedence</a>. For example, you define a top-level variable in an imported stylesheet and redefine it in the main file. If you merge two files into one, you’ll get two variables with the same name and import precedence, which will result in an error.</p>\n\n<p>The workaround is two replace xsl:import’s with xsl:include’s and resolve any <a href=\"http://www.w3.org/TR/xslt#conflict\" rel=\"nofollow noreferrer\">conflicts</a>. After that you are safe to replace xsl:include instructions with the corresponding files’ contents, because that is what <a href=\"http://www.w3.org/TR/xslt#include\" rel=\"nofollow noreferrer\">XSLT-processor does</a>:</p>\n\n<blockquote>\n <p>The inclusion works at the XML tree level. The resource located by the href attribute value is parsed as an XML document, and the children of the xsl:stylesheet element in this document replace the xsl:include element in the including document. The fact that template rules or definitions are included does not affect the way they are processed.</p>\n</blockquote>\n"
},
{
"answer_id": 70591,
"author": "Christian Berg",
"author_id": 5035,
"author_profile": "https://Stackoverflow.com/users/5035",
"pm_score": 5,
"selected": true,
"text": "<p>You can use an XSL stylesheet to merge your stylesheets. However, this is equivalent to using the xsl:include element, not xsl:import (as Azat Razetdinov has already pointed out). You can read up on the difference <a href=\"http://www.w3.org/TR/xslt#section-Combining-Stylesheets\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Therefore you should first replace the xsl:import's with xsl:include's, resolve any conflicts and test whether you still get the correct results. After that, you could use the following stylesheet to merge your existing stylesheets into one. Just apply it to your master stylesheet:</p>\n\n<pre><code><?xml version=\"1.0\" ?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" \n version=\"1.0\">\n\n<xsl:template match=\"xsl:include\">\n <xsl:copy-of select=\"document(@href)/xsl:stylesheet/*\"/>\n</xsl:template>\n\n<xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n\n</xsl:stylesheet>\n</code></pre>\n\n<p>The first template replaces all xsl:include's with the included stylesheets by using the document function, which reads in the file referenced in the href attribute. The second template is the <a href=\"https://stackoverflow.com/questions/56837/how-can-i-make-an-exact-copy-of-a-xml-nodes-children-with-xslt\">identity transformation</a>.</p>\n\n<p>I've tested it with Xalan and it seems to work fine.</p>\n"
},
{
"answer_id": 1031921,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code> import multiple xsl in single xsl\n\n <xsl:import href=\"FpML_FXOption_Trade_Template1.xsl\"/>\n <xsl:apply-imports/>\n\n<calypso:keyword>\n <calypso:name>DisplayOptionStyle</calypso:name>\n<calypso:value>Vanilla</calypso:value>\n</calypso:keyword>\n\n <xsl:import href=\"FpML_FXOption_Trade_Template2.xsl\"/>\n <xsl:apply-imports/>\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70143",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
]
| I have a xslt stylesheet with multiple `xsl:import`s and I want to merge them all into the one xslt file.
It is a limitation of the system we are using where it passes around the xsl stylesheet as a string object stored in memory. This is transmitted to remote machine where it performs the transformation. Since it is not being loaded from disk the href links are broken, so we need to remove the `xsl:import`s from the stylesheet.
Are there any tools out there which can do this? | You can use an XSL stylesheet to merge your stylesheets. However, this is equivalent to using the xsl:include element, not xsl:import (as Azat Razetdinov has already pointed out). You can read up on the difference [here](http://www.w3.org/TR/xslt#section-Combining-Stylesheets).
Therefore you should first replace the xsl:import's with xsl:include's, resolve any conflicts and test whether you still get the correct results. After that, you could use the following stylesheet to merge your existing stylesheets into one. Just apply it to your master stylesheet:
```
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="xsl:include">
<xsl:copy-of select="document(@href)/xsl:stylesheet/*"/>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
```
The first template replaces all xsl:include's with the included stylesheets by using the document function, which reads in the file referenced in the href attribute. The second template is the [identity transformation](https://stackoverflow.com/questions/56837/how-can-i-make-an-exact-copy-of-a-xml-nodes-children-with-xslt).
I've tested it with Xalan and it seems to work fine. |
70,150 | <p>I am looking for attributes I can use to ensure the best runtime performance for my .Net application by giving hints to the loader, JIT compiler or ngen.</p>
<p>For example we have <a href="http://msdn.microsoft.com/en-us/library/k2wxda47.aspx" rel="noreferrer">DebuggableAttribute</a> which should be set to not debug and not disable optimization for optimal performance.</p>
<pre><code>[Debuggable(false, false)]
</code></pre>
<p>Are there any others I should know about?</p>
| [
{
"answer_id": 70168,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 1,
"selected": false,
"text": "<p>I found another: <a href=\"http://msdn.microsoft.com/en-us/library/system.resources.neutralresourceslanguageattribute.aspx\" rel=\"nofollow noreferrer\">NeutralResourcesLanguageAttribute</a>. According to <a href=\"http://blogs.msdn.com/bclteam/archive/2005/10/11/479330.aspx\" rel=\"nofollow noreferrer\">this</a> blog post it helps the loader in finding the right satellite assemblies faster by specifying the culture if the current (neutral) assembly.</p>\n\n<pre><code>[NeutralResourcesLanguageAttribute(\"nl\", UltimateResourceFallbackLocation.MainAssembly)]\n</code></pre>\n"
},
{
"answer_id": 74912,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 2,
"selected": false,
"text": "<p>And another: Literal strings (strings declared in source code) are by default <a href=\"http://msdn.microsoft.com/en-us/library/system.string.intern.aspx\" rel=\"nofollow noreferrer\">interned</a> into a pool to save memory. </p>\n\n<pre><code>string s1 = \"MyTest\"; \nstring s2 = new StringBuilder().Append(\"My\").Append(\"Test\").ToString(); \nstring s3 = String.Intern(s2); \nConsole.WriteLine((Object)s2==(Object)s1); // Different references.\nConsole.WriteLine((Object)s3==(Object)s1); // The same reference.\n</code></pre>\n\n<p>Although it saves memory when the same literal string is used multiple times, it costs some cpu to maintaining the pool and once a string is put into the pool it stays there until the process is stopped.</p>\n\n<p>Using <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.compilationrelaxationsattribute.aspx\" rel=\"nofollow noreferrer\">CompilationRelaxationsAttribute</a> you can tell the JIT compiler that you really don't want it to intern all the literal strings.</p>\n\n<pre><code>[assembly: CompilationRelaxations(CompilationRelaxations.NoStringInterning)]\n</code></pre>\n"
},
{
"answer_id": 78260,
"author": "Thomas Danecker",
"author_id": 9632,
"author_profile": "https://Stackoverflow.com/users/9632",
"pm_score": 4,
"selected": true,
"text": "<p>Ecma-335 specifies some more CompilationRelaxations for relaxed exception handling (so-called e-relaxed calls) in Annex F \"Imprecise faults\", but they have not been exposed by Microsoft.</p>\n\n<p>Specifically CompilationRelaxations.RelaxedArrayExceptions and CompilationRelaxations.RelaxedNullReferenceException are mentioned there.</p>\n\n<p>It'd be intersting what happens when you just try some integers in the CompilationRelaxationsAttribute's ctor ;)</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1242/"
]
| I am looking for attributes I can use to ensure the best runtime performance for my .Net application by giving hints to the loader, JIT compiler or ngen.
For example we have [DebuggableAttribute](http://msdn.microsoft.com/en-us/library/k2wxda47.aspx) which should be set to not debug and not disable optimization for optimal performance.
```
[Debuggable(false, false)]
```
Are there any others I should know about? | Ecma-335 specifies some more CompilationRelaxations for relaxed exception handling (so-called e-relaxed calls) in Annex F "Imprecise faults", but they have not been exposed by Microsoft.
Specifically CompilationRelaxations.RelaxedArrayExceptions and CompilationRelaxations.RelaxedNullReferenceException are mentioned there.
It'd be intersting what happens when you just try some integers in the CompilationRelaxationsAttribute's ctor ;) |
70,161 | <p>As we all know numbers can be written either in numerics, or called by their names. While there are a lot of examples to be found that convert 123 into one hundred twenty three, I could not find good examples of how to convert it the other way around.</p>
<p>Some of the caveats:</p>
<ol>
<li>cardinal/nominal or ordinal: "one" and "first"</li>
<li>common spelling mistakes: "forty"/"fourty"</li>
<li>hundreds/thousands: 2100 -> "twenty one hundred" and also "two thousand and one hundred"</li>
<li>separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot</li>
<li>colloquialisms: "thirty-something"</li>
<li>fractions: 'one third', 'two fifths'</li>
<li>common names: 'a dozen', 'half'</li>
</ol>
<p>And there are probably more caveats possible that are not yet listed.
Suppose the algorithm needs to be very robust, and even understand spelling mistakes.</p>
<p>What fields/papers/studies/algorithms should I read to learn how to write all this?
Where is the information?</p>
<blockquote>
<p>PS: My final parser should actually understand 3 different languages, English, Russian and Hebrew. And maybe at a later stage more languages will be added. Hebrew also has male/female numbers, like "one man" and "one woman" have a different "one" — "ehad" and "ahat". Russian also has some of its own complexities.</p>
</blockquote>
<p>Google does a great job at this. For example:</p>
<p><a href="http://www.google.com/search?q=two+thousand+and+one+hundred+plus+five+dozen+and+four+fifths+in+decimal" rel="noreferrer">http://www.google.com/search?q=two+thousand+and+one+hundred+plus+five+dozen+and+four+fifths+in+decimal</a></p>
<p>(the reverse is also possible <a href="http://www.google.com/search?q=999999999999+in+english" rel="noreferrer">http://www.google.com/search?q=999999999999+in+english</a>)</p>
| [
{
"answer_id": 70198,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 4,
"selected": false,
"text": "<p>I have some code I wrote a while ago: <a href=\"https://github.com/ghewgill/text2num\" rel=\"nofollow noreferrer\">text2num</a>. This does some of what you want, except it does not handle ordinal numbers. I haven't actually used this code for anything, so it's largely untested!</p>\n"
},
{
"answer_id": 88903,
"author": "Aleksandar Dimitrov",
"author_id": 11797,
"author_profile": "https://Stackoverflow.com/users/11797",
"pm_score": 4,
"selected": false,
"text": "<p>It's not an easy issue, and I know of no library to do it. I might sit down and try to write something like this sometime. I'd do it in either Prolog, Java or Haskell, though. As far as I can see, there are several issues:</p>\n\n<ul>\n<li>Tokenization: sometimes, numbers are written eleven hundred fifty two, but I've seen elevenhundred fiftytwo or eleven-hundred-fifty-two and whatnot. One would have to conduct a survey on what forms are actually in use. This might be especially tricky for Hebrew.</li>\n<li>Spelling mistakes: that's not so hard. You have a limited amount of words, and a bit of Levenshtein-distance magic should do the trick.</li>\n<li>Alternate forms, like you already mentioned, exist. This includes ordinal/cardinal numbers, as well as forty/fourty and...</li>\n<li>... common names or commonly used phrases and NEs (named entities). Would you want to extract 30 from the Thirty Years War or 2 from World War II?</li>\n<li>Roman numerals, too?</li>\n<li>Colloqialisms, such as \"thirty-something\" and \"three Euro and shrapnel\", which I wouldn't know how to treat.</li>\n</ul>\n\n<p>If you are interested in this, I could give it a shot this weekend. My idea is probably using UIMA and tokenizing with it, then going on to further tokenize/disambiguate and finally translate. There might be more issues, let's see if I can come up with some more interesting things.</p>\n\n<p>Sorry, this is not a real answer yet, just an extension to your question. I'll let you know if I find/write something.</p>\n\n<p>By the way, if you are interested in the semantics of numerals, I just found an <a href=\"http://semanticsarchive.net/Archive/WVlYTRkO/\" rel=\"noreferrer\">interesting paper</a> by Friederike Moltmann, discussing some issues regarding the logic interpretation of numerals.</p>\n"
},
{
"answer_id": 645106,
"author": "Fraser",
"author_id": 74861,
"author_profile": "https://Stackoverflow.com/users/74861",
"pm_score": 2,
"selected": false,
"text": "<p>Ordinal numbers are not applicable because they cant be joined in meaningful ways with other numbers in language (...at least in English)</p>\n\n<p>e.g. one hundred and first, eleven second, etc...</p>\n\n<p>However, there is another English/American caveat with the word 'and'</p>\n\n<p>i.e.</p>\n\n<p>one hundred and one (English)\none hundred one (American)</p>\n\n<p>Also, the use of 'a' to mean one in English</p>\n\n<p>a thousand = one thousand </p>\n\n<p>...On a side note Google's calculator does an amazing job of this.</p>\n\n<p><a href=\"http://www.google.co.uk/search?hl=en&rlz=1C1GGLS_en-GBGB316GB316&ei=jAC7SbzoCYzFjAfNsPClCA&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=one%20hundred%20and%20three%20thousand%20times%20the%20speed%20of%20light&spell=1\" rel=\"nofollow noreferrer\">one hundred and three thousand times the speed of light</a></p>\n\n<p>And even...</p>\n\n<p><a href=\"http://www.google.co.uk/search?hl=en&rlz=1C1GGLS_en-GBGB316GB316&ei=OAG7SaGmONzFjAeHjpCVCA&sa=X&oi=spell&resnum=0&ct=result&cd=1&q=two%20thousand%20and%20one%20hundred%20plus%20a%20dozen&spell=1\" rel=\"nofollow noreferrer\">two thousand and one hundred plus a dozen</a></p>\n\n<p>...wtf?!? <a href=\"http://www.google.co.uk/search?hl=en&rlz=1C1GGLS_en-GBGB316GB316&q=a%20score%20plus%20a%20dozen%20in%20roman%20numerals&btnG=Search&meta=\" rel=\"nofollow noreferrer\">a score plus a dozen in roman numerals</a></p>\n"
},
{
"answer_id": 653098,
"author": "MarkusQ",
"author_id": 62970,
"author_profile": "https://Stackoverflow.com/users/62970",
"pm_score": 7,
"selected": true,
"text": "<p>I was playing around with a PEG parser to do what you wanted (and may post that as a separate answer later) when I noticed that there's a very simple algorithm that does a remarkably good job with common forms of numbers in English, Spanish, and German, at the very least.</p>\n\n<p>Working with English for example, you need a dictionary that maps words to values in the obvious way:</p>\n\n<pre><code>\"one\" -> 1, \"two\" -> 2, ... \"twenty\" -> 20,\n\"dozen\" -> 12, \"score\" -> 20, ...\n\"hundred\" -> 100, \"thousand\" -> 1000, \"million\" -> 1000000\n</code></pre>\n\n<p>...and so forth</p>\n\n<p>The algorithm is just:</p>\n\n<pre><code>total = 0\nprior = null\nfor each word w\n v <- value(w) or next if no value defined\n prior <- case\n when prior is null: v\n when prior > v: prior+v\n else prior*v\n else\n if w in {thousand,million,billion,trillion...}\n total <- total + prior\n prior <- null\ntotal = total + prior unless prior is null\n</code></pre>\n\n<p>For example, this progresses as follows:</p>\n\n<pre><code>total prior v unconsumed string\n 0 _ four score and seven \n 4 score and seven \n 0 4 \n 20 and seven \n 0 80 \n _ seven \n 0 80 \n 7 \n 0 87 \n 87\n\ntotal prior v unconsumed string\n 0 _ two million four hundred twelve thousand eight hundred seven\n 2 million four hundred twelve thousand eight hundred seven\n 0 2\n 1000000 four hundred twelve thousand eight hundred seven\n2000000 _\n 4 hundred twelve thousand eight hundred seven\n2000000 4\n 100 twelve thousand eight hundred seven\n2000000 400\n 12 thousand eight hundred seven\n2000000 412\n 1000 eight hundred seven\n2000000 412000\n 1000 eight hundred seven\n2412000 _\n 8 hundred seven\n2412000 8\n 100 seven\n2412000 800\n 7\n2412000 807\n2412807\n</code></pre>\n\n<p>And so on. I'm not saying it's perfect, but for a quick and dirty it does quite well.</p>\n\n<hr>\n\n<p>Addressing your specific list on edit:</p>\n\n<ol>\n<li>cardinal/nominal or ordinal: \"one\" and \"first\" -- <strong>just put them in the dictionary</strong></li>\n<li>english/british: \"fourty\"/\"forty\" -- <strong>ditto</strong></li>\n<li>hundreds/thousands: \n 2100 -> \"twenty one hundred\" and also \"two thousand and one hundred\" -- <strong>works as is</strong></li>\n<li>separators: \"eleven hundred fifty two\", but also \"elevenhundred fiftytwo\" or \"eleven-hundred fifty-two\" and whatnot -- <strong>just define \"next word\" to be the longest prefix that matches a defined word, or up to the next non-word if none do, for a start</strong></li>\n<li>colloqialisms: \"thirty-something\" -- <strong>works</strong></li>\n<li>fragments: 'one third', 'two fifths' -- <strong>uh, not yet...</strong></li>\n<li>common names: 'a dozen', 'half' -- <strong>works; you can even do things like \"a half dozen\"</strong></li>\n</ol>\n\n<p>Number 6 is the only one I don't have a ready answer for, and that's because of the ambiguity between ordinals and fractions (in English at least) added to the fact that my last cup of coffee was <em>many</em> hours ago.</p>\n"
},
{
"answer_id": 653113,
"author": "chaos",
"author_id": 47529,
"author_profile": "https://Stackoverflow.com/users/47529",
"pm_score": 2,
"selected": false,
"text": "<p>My LPC implementation of some of your requirements (American English only):</p>\n\n<pre><code>internal mapping inordinal = ([]);\ninternal mapping number = ([]);\n\n#define Numbers ([\\\n \"zero\" : 0, \\\n \"one\" : 1, \\\n \"two\" : 2, \\\n \"three\" : 3, \\\n \"four\" : 4, \\\n \"five\" : 5, \\\n \"six\" : 6, \\\n \"seven\" : 7, \\\n \"eight\" : 8, \\\n \"nine\" : 9, \\\n \"ten\" : 10, \\\n \"eleven\" : 11, \\\n \"twelve\" : 12, \\\n \"thirteen\" : 13, \\\n \"fourteen\" : 14, \\\n \"fifteen\" : 15, \\\n \"sixteen\" : 16, \\\n \"seventeen\" : 17, \\\n \"eighteen\" : 18, \\\n \"nineteen\" : 19, \\\n \"twenty\" : 20, \\\n \"thirty\" : 30, \\\n \"forty\" : 40, \\\n \"fifty\" : 50, \\\n \"sixty\" : 60, \\\n \"seventy\" : 70, \\\n \"eighty\" : 80, \\\n \"ninety\" : 90, \\\n \"hundred\" : 100, \\\n \"thousand\" : 1000, \\\n \"million\" : 1000000, \\\n \"billion\" : 1000000000, \\\n])\n\n#define Ordinals ([\\\n \"zeroth\" : 0, \\\n \"first\" : 1, \\\n \"second\" : 2, \\\n \"third\" : 3, \\\n \"fourth\" : 4, \\\n \"fifth\" : 5, \\\n \"sixth\" : 6, \\\n \"seventh\" : 7, \\\n \"eighth\" : 8, \\\n \"ninth\" : 9, \\\n \"tenth\" : 10, \\\n \"eleventh\" : 11, \\\n \"twelfth\" : 12, \\\n \"thirteenth\" : 13, \\\n \"fourteenth\" : 14, \\\n \"fifteenth\" : 15, \\\n \"sixteenth\" : 16, \\\n \"seventeenth\" : 17, \\\n \"eighteenth\" : 18, \\\n \"nineteenth\" : 19, \\\n \"twentieth\" : 20, \\\n \"thirtieth\" : 30, \\\n \"fortieth\" : 40, \\\n \"fiftieth\" : 50, \\\n \"sixtieth\" : 60, \\\n \"seventieth\" : 70, \\\n \"eightieth\" : 80, \\\n \"ninetieth\" : 90, \\\n \"hundredth\" : 100, \\\n \"thousandth\" : 1000, \\\n \"millionth\" : 1000000, \\\n \"billionth\" : 1000000000, \\\n])\n\nvarargs int denumerical(string num, status ordinal) {\n if(ordinal) {\n if(member(inordinal, num))\n return inordinal[num];\n } else {\n if(member(number, num))\n return number[num];\n }\n int sign = 1;\n int total = 0;\n int sub = 0;\n int value;\n string array parts = regexplode(num, \" |-\");\n if(sizeof(parts) >= 2 && parts[0] == \"\" && parts[1] == \"-\")\n sign = -1;\n for(int ix = 0, int iix = sizeof(parts); ix < iix; ix++) {\n string part = parts[ix];\n switch(part) {\n case \"negative\" :\n case \"minus\" :\n sign = -1;\n continue;\n case \"\" :\n continue;\n }\n if(ordinal && ix == iix - 1) {\n if(part[0] >= '0' && part[0] <= '9' && ends_with(part, \"th\"))\n value = to_int(part[..<3]);\n else if(member(Ordinals, part))\n value = Ordinals[part];\n else\n continue;\n } else {\n if(part[0] >= '0' && part[0] <= '9')\n value = to_int(part);\n else if(member(Numbers, part))\n value = Numbers[part];\n else\n continue;\n }\n if(value < 0) {\n sign = -1;\n value = - value;\n }\n if(value < 10) {\n if(sub >= 1000) {\n total += sub;\n sub = value;\n } else {\n sub += value;\n }\n } else if(value < 100) {\n if(sub < 10) {\n sub = 100 * sub + value;\n } else if(sub >= 1000) {\n total += sub;\n sub = value;\n } else {\n sub *= value;\n }\n } else if(value < sub) {\n total += sub;\n sub = value;\n } else if(sub == 0) {\n sub = value;\n } else {\n sub *= value;\n }\n }\n total += sub;\n return sign * total;\n}\n</code></pre>\n"
},
{
"answer_id": 654386,
"author": "ʞɔıu",
"author_id": 41613,
"author_profile": "https://Stackoverflow.com/users/41613",
"pm_score": -1,
"selected": false,
"text": "<p>One place to start looking is the <a href=\"http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html\" rel=\"nofollow noreferrer\">gnu get_date lib</a>, which can parse <a href=\"http://php-date.com/#strtotime\" rel=\"nofollow noreferrer\">just about any</a> English textual date into a timestamp. While not exactly what you're looking for, their solution to a similar problem could provide a lot of useful clues.</p>\n"
},
{
"answer_id": 654409,
"author": "fmsf",
"author_id": 26004,
"author_profile": "https://Stackoverflow.com/users/26004",
"pm_score": 3,
"selected": false,
"text": "<p>You should keep in mind that Europe and America count differently.</p>\n<h3>European standard:</h3>\n<pre><code>One Thousand\nOne Million\nOne Thousand Millions (British also use Milliard)\nOne Billion\nOne Thousand Billions\nOne Trillion\nOne Thousand Trillions\n</code></pre>\n<p><a href=\"http://www.jimloy.com/math/billion.htm\" rel=\"nofollow noreferrer\">Here</a> is a small reference on it.</p>\n<hr />\n<p>A simple way to see the difference is the following:</p>\n<pre><code>(American counting Trillion) == (European counting Billion)\n</code></pre>\n"
},
{
"answer_id": 663741,
"author": "DrFloyd5",
"author_id": 1736623,
"author_profile": "https://Stackoverflow.com/users/1736623",
"pm_score": -1,
"selected": false,
"text": "<p>Try</p>\n\n<ol>\n<li><p>Open an HTTP Request to \"<a href=\"http://www.google.com/search?q=\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=</a>\" + number + \"+in+decimal\".</p></li>\n<li><p>Parse the result for your number.</p></li>\n<li><p>Cache the number / result pairs to lesson the requests over time.</p></li>\n</ol>\n"
},
{
"answer_id": 668360,
"author": "LarryF",
"author_id": 18518,
"author_profile": "https://Stackoverflow.com/users/18518",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I was too late on the answer for this question, but I was working a little test scenario that seems to have worked very well for me. I used a (simple, but ugly, and large) regular expression to locate all the words for me. The expression is as follows:</p>\n\n<pre><code>(?<Value>(?:zero)|(?:one|first)|(?:two|second)|(?:three|third)|(?:four|fourth)|\n(?:five|fifth)|(?:six|sixth)|(?:seven|seventh)|(?:eight|eighth)|(?:nine|ninth)|\n(?:ten|tenth)|(?:eleven|eleventh)|(?:twelve|twelfth)|(?:thirteen|thirteenth)|\n(?:fourteen|fourteenth)|(?:fifteen|fifteenth)|(?:sixteen|sixteenth)|\n(?:seventeen|seventeenth)|(?:eighteen|eighteenth)|(?:nineteen|nineteenth)|\n(?:twenty|twentieth)|(?:thirty|thirtieth)|(?:forty|fortieth)|(?:fifty|fiftieth)|\n(?:sixty|sixtieth)|(?:seventy|seventieth)|(?:eighty|eightieth)|(?:ninety|ninetieth)|\n(?<Magnitude>(?:hundred|hundredth)|(?:thousand|thousandth)|(?:million|millionth)|\n(?:billion|billionth)))\n</code></pre>\n\n<p>Shown here with line breaks for formatting purposes..</p>\n\n<p>Anyways, my method was to execute this RegEx with a library like PCRE, and then read back the named matches. And it worked on all of the different examples listed in this question, minus the \"One Half\", types, as I didn't add them in, but as you can see, it wouldn't be hard to do so. This addresses a lot of issues. For example, it addresses the following items in the original question and other answers:</p>\n\n<ol>\n<li>cardinal/nominal or ordinal: \"one\" and \"first\"</li>\n<li>common spelling mistakes: \"forty\"/\"fourty\" (Note that it does not EXPLICITLY address this, that would be something you'd want to do before you passed the string to this parser. This parser sees this example as \"FOUR\"...)</li>\n<li>hundreds/thousands: 2100 -> \"twenty one hundred\" and also \"two thousand and one hundred\"</li>\n<li>separators: \"eleven hundred fifty two\", but also \"elevenhundred fiftytwo\" or \"eleven-hundred fifty-two\" and whatnot</li>\n<li>colloqialisms: \"thirty-something\" (This also is not TOTALLY addressed, as what IS \"something\"? Well, this code finds this number as simply \"30\").**</li>\n</ol>\n\n<p>Now, rather than store this monster of a regular expression in your source, I was considering building this RegEx at runtime, using something like the following:</p>\n\n<pre><code>char *ones[] = {\"zero\", \"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\", \"ten\", \"eleven\", \"twelve\",\n \"thirteen\", \"fourteen\", \"fifteen\", \"sixteen\", \"seventeen\", \"eighteen\", \"nineteen\"};\nchar *tens[] = {\"\", \"\", \"twenty\", \"thirty\", \"forty\", \"fifty\", \"sixty\", \"seventy\", \"eighty\", \"ninety\"};\nchar *ordinalones[] = { \"\", \"first\", \"second\", \"third\", \"fourth\", \"fifth\", \"\", \"\", \"\", \"\", \"\", \"\", \"twelfth\" };\nchar *ordinaltens[] = { \"\", \"\", \"twentieth\", \"thirtieth\", \"fortieth\", \"fiftieth\", \"sixtieth\", \"seventieth\", \"eightieth\", \"ninetieth\" };\nand so on...\n</code></pre>\n\n<p>The easy part here is we are only storing the words that matter. In the case of SIXTH, you'll notice that there isn't an entry for it, because it's just it's normal number with TH tacked on... But ones like TWELVE need different attention.</p>\n\n<p>Ok, so now we have the code to build our (ugly) RegEx, now we just execute it on our number strings.</p>\n\n<p>One thing I would recommend, is to filter, or eat the word \"AND\". It's not necessary, and only leads to other issues.</p>\n\n<p>So, what you are going to want to do is setup a function that passes the named matches for \"Magnitude\" into a function that looks at all the possible magnitude values, and multiplies your current result by that value of magnitude. Then, you create a function that looks at the \"Value\" named matches, and returns an int (or whatever you are using), based on the value discovered there.</p>\n\n<p>All VALUE matches are ADDED to your result, while magnitutde matches multiply the result by the mag value. So, Two Hundred Fifty Thousand becomes \"2\", then \"2 * 100\", then \"200 + 50\", then \"250 * 1000\", ending up with 250000...</p>\n\n<p>Just for fun, I wrote a vbScript version of this and it worked great with all the examples provided. Now, it doesn't support named matches, so I had to work a little harder getting the correct result, but I got it. Bottom line is, if it's a \"VALUE\" match, add it your accumulator. If it's a magnitude match, multiply your accumulator by 100, 1000, 1000000, 1000000000, etc... This will provide you with some pretty amazing results, and all you have to do to adjust for things like \"one half\" is add them to your RegEx, put in a code marker for them, and handle them.</p>\n\n<p>Well, I hope this post helps SOMEONE out there. If anyone want, I can post by vbScript pseudo code that I used to test this with, however, it's not pretty code, and NOT production code.</p>\n\n<p>If I may.. What is the final language this will be written in? C++, or something like a scripted language? Greg Hewgill's source will go a long way in helping understand how all of this comes together.</p>\n\n<p>Let me know if I can be of any other help. Sorry, I only know English/American, so I can't help you with the other languages.</p>\n"
},
{
"answer_id": 6925837,
"author": "Alex Brooks",
"author_id": 177674,
"author_profile": "https://Stackoverflow.com/users/177674",
"pm_score": 3,
"selected": false,
"text": "<p>Use the Python <a href=\"http://www.clips.ua.ac.be/pages/pattern-en\" rel=\"nofollow\">pattern-en</a> library: </p>\n\n<pre><code>>>> from pattern.en import number\n>>> number('two thousand fifty and a half') => 2050.5\n</code></pre>\n"
},
{
"answer_id": 8112142,
"author": "Mike Mattie",
"author_id": 1044238,
"author_profile": "https://Stackoverflow.com/users/1044238",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an extremely robust solution in Clojure.</p>\n\n<p>AFAIK it is a unique implementation approach.</p>\n\n<pre><code>;----------------------------------------------------------------------\n; numbers.clj\n; written by: Mike Mattie [email protected]\n;----------------------------------------------------------------------\n(ns operator.numbers\n (:use compojure.core)\n\n (:require\n [clojure.string :as string] ))\n\n(def number-word-table {\n \"zero\" 0\n \"one\" 1\n \"two\" 2\n \"three\" 3\n \"four\" 4\n \"five\" 5\n \"six\" 6\n \"seven\" 7\n \"eight\" 8\n \"nine\" 9\n \"ten\" 10\n \"eleven\" 11\n \"twelve\" 12\n \"thirteen\" 13\n \"fourteen\" 14\n \"fifteen\" 15\n \"sixteen\" 16\n \"seventeen\" 17\n \"eighteen\" 18\n \"nineteen\" 19\n \"twenty\" 20\n \"thirty\" 30\n \"fourty\" 40\n \"fifty\" 50\n \"sixty\" 60\n \"seventy\" 70\n \"eighty\" 80\n \"ninety\" 90\n})\n\n(def multiplier-word-table {\n \"hundred\" 100\n \"thousand\" 1000\n})\n\n(defn sum-words-to-number [ words ]\n (apply + (map (fn [ word ] (number-word-table word)) words)) )\n\n; are you down with the sickness ?\n(defn words-to-number [ words ]\n (let\n [ n (count words)\n\n multipliers (filter (fn [x] (not (false? x))) (map-indexed\n (fn [ i word ]\n (if (contains? multiplier-word-table word)\n (vector i (multiplier-word-table word))\n false))\n words) )\n\n x (ref 0) ]\n\n (loop [ indices (reverse (conj (reverse multipliers) (vector n 1)))\n left 0\n combine + ]\n (let\n [ right (first indices) ]\n\n (dosync (alter x combine (* (if (> (- (first right) left) 0)\n (sum-words-to-number (subvec words left (first right)))\n 1)\n (second right)) ))\n\n (when (> (count (rest indices)) 0)\n (recur (rest indices) (inc (first right))\n (if (= (inc (first right)) (first (second indices)))\n *\n +))) ) )\n @x ))\n</code></pre>\n\n<p>Here are some examples</p>\n\n<pre><code>(operator.numbers/words-to-number [\"six\" \"thousand\" \"five\" \"hundred\" \"twenty\" \"two\"])\n(operator.numbers/words-to-number [\"fifty\" \"seven\" \"hundred\"])\n(operator.numbers/words-to-number [\"hundred\"])\n</code></pre>\n"
},
{
"answer_id": 41387461,
"author": "duhaime",
"author_id": 1727392,
"author_profile": "https://Stackoverflow.com/users/1727392",
"pm_score": 0,
"selected": false,
"text": "<p>I was converting ordinal edition statements from early modern books (e.g. \"2nd edition\", \"Editio quarta\") to integers and needed support for ordinals 1-100 in English and ordinals 1-10 in a few Romance languages. Here's what I came up with in Python:</p>\n\n<pre><code>def get_data_mapping():\n data_mapping = {\n \"1st\": 1,\n \"2nd\": 2,\n \"3rd\": 3,\n\n \"tenth\": 10,\n \"eleventh\": 11,\n \"twelfth\": 12,\n \"thirteenth\": 13,\n \"fourteenth\": 14,\n \"fifteenth\": 15,\n \"sixteenth\": 16,\n \"seventeenth\": 17,\n \"eighteenth\": 18,\n \"nineteenth\": 19,\n \"twentieth\": 20,\n\n \"new\": 2,\n \"newly\": 2,\n \"nova\": 2,\n \"nouvelle\": 2,\n \"altera\": 2,\n \"andere\": 2,\n\n # latin\n \"primus\": 1,\n \"secunda\": 2,\n \"tertia\": 3,\n \"quarta\": 4,\n \"quinta\": 5,\n \"sexta\": 6,\n \"septima\": 7,\n \"octava\": 8,\n \"nona\": 9,\n \"decima\": 10,\n\n # italian\n \"primo\": 1,\n \"secondo\": 2,\n \"terzo\": 3,\n \"quarto\": 4,\n \"quinto\": 5,\n \"sesto\": 6,\n \"settimo\": 7,\n \"ottavo\": 8,\n \"nono\": 9,\n \"decimo\": 10,\n\n # french\n \"premier\": 1,\n \"deuxième\": 2,\n \"troisième\": 3,\n \"quatrième\": 4,\n \"cinquième\": 5,\n \"sixième\": 6,\n \"septième\": 7,\n \"huitième\": 8,\n \"neuvième\": 9,\n \"dixième\": 10,\n\n # spanish\n \"primero\": 1,\n \"segundo\": 2,\n \"tercero\": 3,\n \"cuarto\": 4,\n \"quinto\": 5,\n \"sexto\": 6,\n \"septimo\": 7,\n \"octavo\": 8,\n \"noveno\": 9,\n \"decimo\": 10\n }\n\n # create 4th, 5th, ... 20th\n for i in xrange(16):\n data_mapping[str(4+i) + \"th\"] = 4+i\n\n # create 21st, 22nd, ... 99th\n for i in xrange(79):\n last_char = str(i)[-1]\n\n if last_char == \"0\":\n data_mapping[str(20+i) + \"th\"] = 20+i\n\n elif last_char == \"1\":\n data_mapping[str(20+i) + \"st\"] = 20+i\n\n elif last_char == \"2\":\n data_mapping[str(20+i) + \"nd\"] = 20+i\n\n elif last_char == \"3\":\n data_mapping[str(20+i) + \"rd\"] = 20+i\n\n else:\n data_mapping[str(20+i) + \"th\"] = 20+i\n\n ordinals = [\n \"first\", \"second\", \"third\", \n \"fourth\", \"fifth\", \"sixth\", \n \"seventh\", \"eighth\", \"ninth\"\n ]\n\n # create first, second ... ninth\n for c, i in enumerate(ordinals):\n data_mapping[i] = c+1\n\n # create twenty-first, twenty-second ... ninty-ninth\n for ci, i in enumerate([\n \"twenty\", \"thirty\", \"forty\", \n \"fifty\", \"sixty\", \"seventy\", \n \"eighty\", \"ninety\"\n ]):\n for cj, j in enumerate(ordinals):\n data_mapping[i + \"-\" + j] = 20 + (ci*10) + (cj+1)\n data_mapping[i.replace(\"y\", \"ieth\")] = 20 + (ci*10)\n\n return data_mapping\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11414/"
]
| As we all know numbers can be written either in numerics, or called by their names. While there are a lot of examples to be found that convert 123 into one hundred twenty three, I could not find good examples of how to convert it the other way around.
Some of the caveats:
1. cardinal/nominal or ordinal: "one" and "first"
2. common spelling mistakes: "forty"/"fourty"
3. hundreds/thousands: 2100 -> "twenty one hundred" and also "two thousand and one hundred"
4. separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot
5. colloquialisms: "thirty-something"
6. fractions: 'one third', 'two fifths'
7. common names: 'a dozen', 'half'
And there are probably more caveats possible that are not yet listed.
Suppose the algorithm needs to be very robust, and even understand spelling mistakes.
What fields/papers/studies/algorithms should I read to learn how to write all this?
Where is the information?
>
> PS: My final parser should actually understand 3 different languages, English, Russian and Hebrew. And maybe at a later stage more languages will be added. Hebrew also has male/female numbers, like "one man" and "one woman" have a different "one" — "ehad" and "ahat". Russian also has some of its own complexities.
>
>
>
Google does a great job at this. For example:
<http://www.google.com/search?q=two+thousand+and+one+hundred+plus+five+dozen+and+four+fifths+in+decimal>
(the reverse is also possible <http://www.google.com/search?q=999999999999+in+english>) | I was playing around with a PEG parser to do what you wanted (and may post that as a separate answer later) when I noticed that there's a very simple algorithm that does a remarkably good job with common forms of numbers in English, Spanish, and German, at the very least.
Working with English for example, you need a dictionary that maps words to values in the obvious way:
```
"one" -> 1, "two" -> 2, ... "twenty" -> 20,
"dozen" -> 12, "score" -> 20, ...
"hundred" -> 100, "thousand" -> 1000, "million" -> 1000000
```
...and so forth
The algorithm is just:
```
total = 0
prior = null
for each word w
v <- value(w) or next if no value defined
prior <- case
when prior is null: v
when prior > v: prior+v
else prior*v
else
if w in {thousand,million,billion,trillion...}
total <- total + prior
prior <- null
total = total + prior unless prior is null
```
For example, this progresses as follows:
```
total prior v unconsumed string
0 _ four score and seven
4 score and seven
0 4
20 and seven
0 80
_ seven
0 80
7
0 87
87
total prior v unconsumed string
0 _ two million four hundred twelve thousand eight hundred seven
2 million four hundred twelve thousand eight hundred seven
0 2
1000000 four hundred twelve thousand eight hundred seven
2000000 _
4 hundred twelve thousand eight hundred seven
2000000 4
100 twelve thousand eight hundred seven
2000000 400
12 thousand eight hundred seven
2000000 412
1000 eight hundred seven
2000000 412000
1000 eight hundred seven
2412000 _
8 hundred seven
2412000 8
100 seven
2412000 800
7
2412000 807
2412807
```
And so on. I'm not saying it's perfect, but for a quick and dirty it does quite well.
---
Addressing your specific list on edit:
1. cardinal/nominal or ordinal: "one" and "first" -- **just put them in the dictionary**
2. english/british: "fourty"/"forty" -- **ditto**
3. hundreds/thousands:
2100 -> "twenty one hundred" and also "two thousand and one hundred" -- **works as is**
4. separators: "eleven hundred fifty two", but also "elevenhundred fiftytwo" or "eleven-hundred fifty-two" and whatnot -- **just define "next word" to be the longest prefix that matches a defined word, or up to the next non-word if none do, for a start**
5. colloqialisms: "thirty-something" -- **works**
6. fragments: 'one third', 'two fifths' -- **uh, not yet...**
7. common names: 'a dozen', 'half' -- **works; you can even do things like "a half dozen"**
Number 6 is the only one I don't have a ready answer for, and that's because of the ambiguity between ordinals and fractions (in English at least) added to the fact that my last cup of coffee was *many* hours ago. |
70,216 | <p>In Java, you often see a META-INF folder containing some meta files. What is the purpose of this folder and what can I put there?</p>
| [
{
"answer_id": 70221,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 8,
"selected": false,
"text": "<p>From <a href=\"http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html\" rel=\"noreferrer\">the official JAR File Specification</a> (link goes to the Java 7 version, but the text hasn't changed since at least v1.3):</p>\n<blockquote>\n<h2>The META-INF directory</h2>\n<p>The following files/directories in the META-INF directory are recognized and interpreted by the Java 2 Platform to configure applications, extensions, class loaders and services:</p>\n<ul>\n<li><code>MANIFEST.MF</code></li>\n</ul>\n<p>The manifest file that is used to define extension and package related data.</p>\n<ul>\n<li><code>INDEX.LIST</code></li>\n</ul>\n<p>This file is generated by the new "<code>-i</code>" option of the jar tool, which contains location information for packages defined in an application or extension. It is part of the JarIndex implementation and used by class loaders to speed up their class loading process.</p>\n<ul>\n<li><code>x.SF</code></li>\n</ul>\n<p>The signature file for the JAR file. 'x' stands for the base file name.</p>\n<ul>\n<li><code>x.DSA</code></li>\n</ul>\n<p>The signature block file associated with the signature file with the same base file name. This file stores the digital signature of the corresponding signature file.</p>\n<ul>\n<li><code>services/</code></li>\n</ul>\n<p>This directory stores all the service provider configuration files.</p>\n</blockquote>\n<p>New since Java 9 implementing <a href=\"https://openjdk.java.net/jeps/238\" rel=\"noreferrer\">JEP 238</a> are multi-release JARs. One will see a sub folder <code>versions</code>. This is a feature which allows to package classes which are meant for different Java version in one jar.</p>\n"
},
{
"answer_id": 70236,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 4,
"selected": false,
"text": "<p>The META-INF folder is the home for the <a href=\"http://java.sun.com/developer/Books/javaprogramming/JAR/basics/manifest.html\" rel=\"noreferrer\">MANIFEST.MF</a> file. This file contains meta data about the contents of the JAR. For example, there is an entry called Main-Class that specifies the name of the Java class with the static main() for executable JAR files.</p>\n"
},
{
"answer_id": 70253,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 7,
"selected": true,
"text": "<p>Generally speaking, you should not put anything into META-INF yourself. Instead, you should rely upon whatever you use to package up your JAR. This is one of the areas where I think Ant really excels: specifying JAR file manifest attributes. It's very easy to say something like:</p>\n\n<pre><code><jar ...>\n <manifest>\n <attribute name=\"Main-Class\" value=\"MyApplication\"/>\n </manifest>\n</jar>\n</code></pre>\n\n<p>At least, I think that's easy... :-)</p>\n\n<p>The point is that META-INF should be considered an internal Java <em>meta</em> directory. Don't mess with it! Any files you want to include with your JAR should be placed in some other sub-directory or at the root of the JAR itself.</p>\n"
},
{
"answer_id": 315588,
"author": "user38748",
"author_id": 38748,
"author_profile": "https://Stackoverflow.com/users/38748",
"pm_score": 5,
"selected": false,
"text": "<p>I've noticed that some Java libraries have started using META-INF as a directory in which to include configuration files that should be packaged and included in the CLASSPATH along with JARs. For example, Spring allows you to import XML Files that are on the classpath using:</p>\n\n<pre><code><import resource=\"classpath:/META-INF/cxf/cxf.xml\" />\n<import resource=\"classpath:/META-INF/cxf/cxf-extensions-*.xml\" />\n</code></pre>\n\n<p>In this example, I'm quoting straight out of the <a href=\"http://docs.huihoo.com/apache/cxf/2.0/configuration.html\" rel=\"noreferrer\">Apache CXF User Guide</a>. On a project I worked on in which we had to allow multiple levels of configuration via Spring, we followed this convention and put our configuration files in META-INF.</p>\n\n<p>When I reflect on this decision, I don't know what exactly would be wrong with simply including the configuration files in a specific Java package, rather than in META-INF. But it seems to be an emerging de facto standard; either that, or an emerging anti-pattern :-)</p>\n"
},
{
"answer_id": 1601585,
"author": "sasuke",
"author_id": 99463,
"author_profile": "https://Stackoverflow.com/users/99463",
"pm_score": 3,
"selected": false,
"text": "<p>Just to add to the information here, in case of a WAR file, the META-INF/MANIFEST.MF file provides the developer a facility to initiate a deploy time check by the container which ensures that the container can find all the classes your application depends on. This ensures that in case you missed a JAR, you don't have to wait till your application blows at runtime to realize that it's missing.</p>\n"
},
{
"answer_id": 1609825,
"author": "f0ster",
"author_id": 157460,
"author_profile": "https://Stackoverflow.com/users/157460",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using JPA1, you might have to drop a <code>persistence.xml</code> file in there which specifies the name of a persistence-unit you might want to use. A persistence-unit provides a convenient way of specifying a set of metadata files, and classes, and jars that contain all classes to be persisted in a grouping.</p>\n\n<pre><code>import javax.persistence.EntityManagerFactory;\nimport javax.persistence.Persistence;\n\n// ...\n\nEntityManagerFactory emf =\n Persistence.createEntityManagerFactory(persistenceUnitName);\n</code></pre>\n\n<p>See more here:\n<a href=\"http://www.datanucleus.org/products/datanucleus/jpa/emf.html\" rel=\"nofollow noreferrer\">http://www.datanucleus.org/products/datanucleus/jpa/emf.html</a></p>\n"
},
{
"answer_id": 7721172,
"author": "Steve Cohen",
"author_id": 811299,
"author_profile": "https://Stackoverflow.com/users/811299",
"pm_score": 3,
"selected": false,
"text": "<p>I have been thinking about this issue recently. There really doesn't seem to be any restriction on use of META-INF. There are certain strictures, of course, about the necessity of putting the manifest there, but there don't appear to be any prohibitions about putting other stuff there.</p>\n\n<p>Why is this the case?</p>\n\n<p>The cxf case may be legit. Here's another place where this non-standard is recommended to get around a nasty bug in JBoss-ws that prevents server-side validation against the schema of a wsdl.</p>\n\n<p><a href=\"http://community.jboss.org/message/570377#570377\" rel=\"noreferrer\">http://community.jboss.org/message/570377#570377</a></p>\n\n<p>But there really don't seem to be any standards, any thou-shalt-nots. Usually these things are very rigorously defined, but for some reason, it seems there are no standards here. Odd. It seems like META-INF has become a catchall place for any needed configuration that can't easily be handled some other way.</p>\n"
},
{
"answer_id": 14340251,
"author": "Grim",
"author_id": 843943,
"author_profile": "https://Stackoverflow.com/users/843943",
"pm_score": 4,
"selected": false,
"text": "<p>You can also place static resources in there.</p>\n<p>In example:</p>\n<pre><code>META-INF/resources/button.jpg \n</code></pre>\n<p>and get them in web3.0-container via</p>\n<pre><code>http://localhost/myapp/button.jpg\n</code></pre>\n<p><a href=\"https://web.archive.org/web/20150918224750/https://blogs.oracle.com/alexismp/entry/web_inf_lib_jar_meta\" rel=\"nofollow noreferrer\">> Read more</a></p>\n<p>The /META-INF/MANIFEST.MF has a special meaning:</p>\n<ol>\n<li>If you run a jar using <code>java -jar myjar.jar org.myserver.MyMainClass</code> you can move the main class definition into the jar so you can shrink the call into <code>java -jar myjar.jar</code>.</li>\n<li>You can define Metainformations to packages if you use <code>java.lang.Package.getPackage("org.myserver").getImplementationTitle()</code>.</li>\n<li>You can reference digital certificates you like to use in Applet/Webstart mode.</li>\n</ol>\n"
},
{
"answer_id": 27905756,
"author": "EliuX",
"author_id": 3233398,
"author_profile": "https://Stackoverflow.com/users/3233398",
"pm_score": 4,
"selected": false,
"text": "<h2>META-INF in Maven</h2>\n<p>In Maven the <strong>META-INF</strong> folder is understood because of the <a href=\"http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html\" rel=\"nofollow noreferrer\">Standard Directory Layout</a>, which by name convention package your project resources within JARs: any directories or files placed within the <em>${basedir}/src/main/resources</em> directory are packaged into your JAR with the exact same structure starting at the base of the JAR.</p>\n<p>The Folder <em>${basedir}/src/main/resources/META-INF</em> usually contains <em>.properties</em> files while in the jar contains a generated <strong>MANIFEST.MF</strong>, <strong>pom.properties</strong>, the <strong>pom.xml</strong>, among other files. Also frameworks like <a href=\"https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot\" rel=\"nofollow noreferrer\">Spring</a> use <code>classpath:/META-INF/resources/</code> to serve web resources.</p>\n<p>For more information see <a href=\"http://maven.apache.org/guides/getting-started/#How_do_I_add_resources_to_my_JAR\" rel=\"nofollow noreferrer\">How do I add resources to my Maven Project</a>.</p>\n"
},
{
"answer_id": 27925121,
"author": "Tugrul",
"author_id": 1172945,
"author_profile": "https://Stackoverflow.com/users/1172945",
"pm_score": 2,
"selected": false,
"text": "<p>All answers are correct. Meta-inf has many purposes. In addition, here is an example about using tomcat container.</p>\n\n<p>Go to \n<a href=\"http://tomcat.apache.org/tomcat-7.0-doc/config/context.html\" rel=\"nofollow\">Tomcat Doc</a> and check\n\" <strong>Standard Implementation > copyXML</strong> \" attribute.</p>\n\n<p>Description is below.</p>\n\n<blockquote>\n <p>Set to true if you want a context XML descriptor embedded inside the application (located at /META-INF/context.xml) to be copied to the owning Host's xmlBase when the application is deployed. On subsequent starts, the copied context XML descriptor will be used in preference to any context XML descriptor embedded inside the application even if the descriptor embedded inside the application is more recent. The flag's value defaults to false. Note if the deployXML attribute of the owning Host is false or if the copyXML attribute of the owning Host is true, this attribute will have no effect.</p>\n</blockquote>\n"
},
{
"answer_id": 33640221,
"author": "Prateek Joshi",
"author_id": 4281711,
"author_profile": "https://Stackoverflow.com/users/4281711",
"pm_score": 0,
"selected": false,
"text": "<p>You have MANIFEST.MF file inside your META-INF folder. You can <strong>define optional or external dependencies</strong> that you must have access to.</p>\n\n<p><strong>Example:</strong></p>\n\n<p>Consider you have deployed your app and your container(at run time) found out that your app requires a newer version of a library which is not inside lib folder, in that case if you have defined the optional newer version in <code>MANIFEST.MF</code> then your app will refer to dependency from there (and will not crash).</p>\n\n<p><code>Source:</code> Head First Jsp & Servlet</p>\n"
},
{
"answer_id": 36800847,
"author": "Readren",
"author_id": 1154271,
"author_profile": "https://Stackoverflow.com/users/1154271",
"pm_score": 3,
"selected": false,
"text": "<p>Adding to the information here, the META-INF is a special folder which the <code>ClassLoader</code> treats differently from other folders in the jar.\nElements nested inside the META-INF folder are not mixed with the elements outside of it. </p>\n\n<p>Think of it like another root. From the <code>Enumerator<URL> ClassLoader#getSystemResources(String path)</code> method et al perspective:</p>\n\n<p><em>When the given path starts with \"META-INF\", the method searches for resources that are nested inside the META-INF folders of all the jars in the class path.</em></p>\n\n<p>When the given path doesn't start with \"META-INF\", the method searches for resources in all the other folders (outside the META-INF) of all the jars and directories in the class path.</p>\n\n<p>If you know about another folder name that the <code>getSystemResources</code> method treats specially, please comment about it.</p>\n"
},
{
"answer_id": 70407970,
"author": "k_o_",
"author_id": 3351474,
"author_profile": "https://Stackoverflow.com/users/3351474",
"pm_score": 0,
"selected": false,
"text": "<p>As an addition the META-INF folder is now also used for <a href=\"https://openjdk.java.net/jeps/238\" rel=\"nofollow noreferrer\">multi-release jars</a>. This is a feature which allows to package classes which are meant for different Java version in one jar, e.g. include a class for Java 11 with new features offered by Java 11 in a jar also working for Java 8, where a different class for Java 8 with less features in contained. E.g this can be useful if a newer Java version is offering enhanced, different or new API methods which would not work in earlier version due to API violations. One will see a sub folder <code>versions</code> then.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11429/"
]
| In Java, you often see a META-INF folder containing some meta files. What is the purpose of this folder and what can I put there? | Generally speaking, you should not put anything into META-INF yourself. Instead, you should rely upon whatever you use to package up your JAR. This is one of the areas where I think Ant really excels: specifying JAR file manifest attributes. It's very easy to say something like:
```
<jar ...>
<manifest>
<attribute name="Main-Class" value="MyApplication"/>
</manifest>
</jar>
```
At least, I think that's easy... :-)
The point is that META-INF should be considered an internal Java *meta* directory. Don't mess with it! Any files you want to include with your JAR should be placed in some other sub-directory or at the root of the JAR itself. |
70,272 | <p>I have an application with one form in it, and on the Load method I need to hide the form. </p>
<p>The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 70282,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": -1,
"selected": false,
"text": "<p>Here is a simple approach:<br>\nIt's in C# (I don't have VB compiler at the moment)</p>\n\n<pre><code>public Form1()\n{\n InitializeComponent();\n Hide(); // Also Visible = false can be used\n}\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n Thread.Sleep(10000);\n Show(); // Or visible = true;\n}\n</code></pre>\n"
},
{
"answer_id": 70283,
"author": "deemer",
"author_id": 11192,
"author_profile": "https://Stackoverflow.com/users/11192",
"pm_score": -1,
"selected": false,
"text": "<p>In the designer, set the form's Visible property to false. Then avoid calling Show() until you need it. </p>\n\n<p>A better paradigm is to not create an instance of the form until you need it.</p>\n"
},
{
"answer_id": 70296,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 8,
"selected": true,
"text": "<p>I'm coming at this from C#, but should be very similar in vb.net.</p>\n\n<p>In your main program file, in the Main method, you will have something like:</p>\n\n<pre><code>Application.Run(new MainForm());\n</code></pre>\n\n<p>This creates a new main form and limits the lifetime of the application to the lifetime of the main form.</p>\n\n<p>However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.</p>\n\n<p>Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling <code>Form.Show()</code> or <code>Form.Hide()</code> from handlers of NotifyIcon events will show and hide the form respectively.</p>\n"
},
{
"answer_id": 70462,
"author": "Roger Willcocks",
"author_id": 11511,
"author_profile": "https://Stackoverflow.com/users/11511",
"pm_score": 0,
"selected": false,
"text": "<p>Launching an app without a form means you're going to have to manage the application startup/shutdown yourself.</p>\n\n<p>Starting the form off invisible is a better option.</p>\n"
},
{
"answer_id": 189045,
"author": "Tute",
"author_id": 4386,
"author_profile": "https://Stackoverflow.com/users/4386",
"pm_score": 5,
"selected": false,
"text": "<p>I use this:</p>\n\n<pre><code>private void MainForm_Load(object sender, EventArgs e)\n{\n if (Settings.Instance.HideAtStartup)\n {\n BeginInvoke(new MethodInvoker(delegate\n {\n Hide();\n }));\n }\n}\n</code></pre>\n\n<p>Obviously you have to change the if condition with yours.</p>\n"
},
{
"answer_id": 398051,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This example supports total invisibility as well as only NotifyIcon in the System tray and no clicks and much more.</p>\n\n<p>More here: <a href=\"http://code.msdn.microsoft.com/TheNotifyIconExample\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/TheNotifyIconExample</a></p>\n"
},
{
"answer_id": 398528,
"author": "Benjamin Autin",
"author_id": 1440933,
"author_profile": "https://Stackoverflow.com/users/1440933",
"pm_score": -1,
"selected": false,
"text": "<p>Why do it like that at all?</p>\n\n<p>Why not just start like a console app and show the form when necessary? There's nothing but a few references separating a console app from a forms app.</p>\n\n<p>No need in being greedy and taking the memory needed for the form when you may not even need it.</p>\n"
},
{
"answer_id": 403898,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Extend your main form with this one:</p>\n\n<pre><code>using System.Windows.Forms;\n\nnamespace HideWindows\n{\n public class HideForm : Form\n {\n public HideForm()\n {\n Opacity = 0;\n ShowInTaskbar = false;\n }\n\n public new void Show()\n {\n Opacity = 100;\n ShowInTaskbar = true;\n\n Show(this);\n }\n }\n}\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>namespace HideWindows\n{\n public partial class Form1 : HideForm\n {\n public Form1()\n {\n InitializeComponent();\n }\n }\n}\n</code></pre>\n\n<p>More info in this article (spanish):</p>\n\n<p><a href=\"http://codelogik.net/2008/12/30/primer-form-oculto/\" rel=\"noreferrer\">http://codelogik.net/2008/12/30/primer-form-oculto/</a></p>\n"
},
{
"answer_id": 1173347,
"author": "Jon Onstott",
"author_id": 132374,
"author_profile": "https://Stackoverflow.com/users/132374",
"pm_score": -1,
"selected": false,
"text": "<p>Based on various suggestions, all I had to do was this:</p>\n\n<p>To hide the form:</p>\n\n<pre><code>Me.Opacity = 0\nMe.ShowInTaskbar = false\n</code></pre>\n\n<p>To show the form:</p>\n\n<pre><code>Me.Opacity = 100\nMe.ShowInTaskbar = true\n</code></pre>\n"
},
{
"answer_id": 2447201,
"author": "kilsek",
"author_id": 293971,
"author_profile": "https://Stackoverflow.com/users/293971",
"pm_score": 0,
"selected": false,
"text": "<pre><code>static void Main()\n{\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n MainUIForm mainUiForm = new MainUIForm();\n mainUiForm.Visible = false;\n Application.Run();\n}\n</code></pre>\n"
},
{
"answer_id": 4210040,
"author": "Paul Aicher",
"author_id": 511439,
"author_profile": "https://Stackoverflow.com/users/511439",
"pm_score": 7,
"selected": false,
"text": "<p>Usually you would only be doing this when you are using a tray icon or some other method to display the form later, but it will work nicely even if you never display your main form.</p>\n\n<p>Create a bool in your Form class that is defaulted to false:</p>\n\n<pre><code>private bool allowshowdisplay = false;\n</code></pre>\n\n<p>Then override the SetVisibleCore method</p>\n\n<pre><code>protected override void SetVisibleCore(bool value)\n{ \n base.SetVisibleCore(allowshowdisplay ? value : allowshowdisplay);\n}\n</code></pre>\n\n<p>Because Application.Run() sets the forms .Visible = true after it loads the form this will intercept that and set it to false. In the above case, it will always set it to false until you enable it by setting allowshowdisplay to true.</p>\n\n<p>Now that will keep the form from displaying on startup, now you need to re-enable the SetVisibleCore to function properly by setting the allowshowdisplay = true. You will want to do this on whatever user interface function that displays the form. In my example it is the left click event in my notiyicon object:</p>\n\n<pre><code>private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)\n{\n if (e.Button == System.Windows.Forms.MouseButtons.Left)\n {\n this.allowshowdisplay = true;\n this.Visible = !this.Visible; \n }\n}\n</code></pre>\n"
},
{
"answer_id": 5342362,
"author": "Jeff",
"author_id": 556470,
"author_profile": "https://Stackoverflow.com/users/556470",
"pm_score": 4,
"selected": false,
"text": "<p>At form construction time (Designer, program Main, or Form constructor, depending on your goals),</p>\n\n<pre><code> this.WindowState = FormWindowState.Minimized;\n this.ShowInTaskbar = false;\n</code></pre>\n\n<p>When you need to show the form, presumably on event from your NotifyIcon, reverse as necessary,</p>\n\n<pre><code> if (!this.ShowInTaskbar)\n this.ShowInTaskbar = true;\n\n if (this.WindowState == FormWindowState.Minimized)\n this.WindowState = FormWindowState.Normal;\n</code></pre>\n\n<p>Successive show/hide events can more simply use the Form's Visible property or Show/Hide methods.</p>\n"
},
{
"answer_id": 5516790,
"author": "Eugenio Miró",
"author_id": 41236,
"author_profile": "https://Stackoverflow.com/users/41236",
"pm_score": 0,
"selected": false,
"text": "<p>As a complement to <a href=\"https://stackoverflow.com/questions/70272/single-form-hide-on-startup/70296#70296\">Groky's response</a> (which is actually the best response by far in my perspective) we could also mention the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext.aspx?appId=Dev10IDEF1&l=EN-US&k=k%28%22SYSTEM.WINDOWS.FORMS.APPLICATIONCONTEXT.#CTOR%22%29;k%28APPLICATIONCONTEXT%29;k%28SOLUTIONITEMSPROJECT%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK&k=VERSION=V4.0%22%29;k%28DevLang-CSHARP%29&rd=true\" rel=\"nofollow noreferrer\">ApplicationContext</a> class, which allows also (as it's shown in the article's sample) the ability to open two (or even more) Forms on application startup, and control the application lifetime with all of them.</p>\n"
},
{
"answer_id": 11831856,
"author": "Chriz",
"author_id": 1579761,
"author_profile": "https://Stackoverflow.com/users/1579761",
"pm_score": 4,
"selected": false,
"text": "<pre><code> protected override void OnLoad(EventArgs e)\n {\n Visible = false; // Hide form window.\n ShowInTaskbar = false; // Remove from taskbar.\n Opacity = 0;\n\n base.OnLoad(e);\n }\n</code></pre>\n"
},
{
"answer_id": 13785671,
"author": "echoen",
"author_id": 1889095,
"author_profile": "https://Stackoverflow.com/users/1889095",
"pm_score": 2,
"selected": false,
"text": "<p>I have struggled with this issue a lot and the solution is much simpler than i though.\nI first tried all the suggestions here but then i was not satisfied with the result and investigated it a little more.\nI found that if I add the:<br></p>\n\n<pre><code> this.visible=false;\n /* to the InitializeComponent() code just before the */\n this.Load += new System.EventHandler(this.DebugOnOff_Load);\n</code></pre>\n\n<p>It is working just fine.\nbut I wanted a more simple solution and it turn out that if you add the: </p>\n\n<pre><code>this.visible=false;\n/* to the start of the load event, you get a\nsimple perfect working solution :) */ \nprivate void\nDebugOnOff_Load(object sender, EventArgs e)\n{\nthis.Visible = false;\n}\n</code></pre>\n"
},
{
"answer_id": 17342392,
"author": "steve_k",
"author_id": 1577871,
"author_profile": "https://Stackoverflow.com/users/1577871",
"pm_score": -1,
"selected": false,
"text": "<p>I do it like this - from my point of view the easiest way:</p>\n\n<p>set the form's 'StartPosition' to 'Manual', and add this to the form's designer:</p>\n\n<pre><code>Private Sub InitializeComponent()\n.\n.\n.\nMe.Location=New Point(-2000,-2000)\n.\n.\n.\nEnd Sub\n</code></pre>\n\n<p>Make sure that the location is set to something beyond or below the screen's dimensions. Later, when you want to show the form, set the Location to something within the screen's dimensions.</p>\n"
},
{
"answer_id": 36010671,
"author": "George",
"author_id": 4365852,
"author_profile": "https://Stackoverflow.com/users/4365852",
"pm_score": 2,
"selected": false,
"text": "<p>You're going to want to set the window state to minimized, and show in taskbar to false. Then at the end of your forms Load set window state to maximized and show in taskbar to true</p>\n\n<pre><code> public frmMain()\n {\n Program.MainForm = this;\n InitializeComponent();\n\n this.WindowState = FormWindowState.Minimized;\n this.ShowInTaskbar = false;\n }\n\nprivate void frmMain_Load(object sender, EventArgs e)\n {\n //Do heavy things here\n\n //At the end do this\n this.WindowState = FormWindowState.Maximized;\n this.ShowInTaskbar = true;\n }\n</code></pre>\n"
},
{
"answer_id": 40298412,
"author": "Metallic Skeleton",
"author_id": 4002198,
"author_profile": "https://Stackoverflow.com/users/4002198",
"pm_score": 3,
"selected": false,
"text": "<p>Try to hide the app from the task bar as well.</p>\n\n<p>To do that please use this code.</p>\n\n<pre><code> protected override void OnLoad(EventArgs e)\n {\n Visible = false; // Hide form window.\n ShowInTaskbar = false; // Remove from taskbar.\n Opacity = 0;\n\n base.OnLoad(e);\n }\n</code></pre>\n\n<p>Thanks.\n Ruhul</p>\n"
},
{
"answer_id": 42573333,
"author": "Willy David Jr",
"author_id": 6542896,
"author_profile": "https://Stackoverflow.com/users/6542896",
"pm_score": 1,
"selected": false,
"text": "<p>This works perfectly for me:</p>\n\n<pre><code>[STAThread]\n static void Main()\n {\n try\n {\n frmBase frm = new frmBase(); \n Application.Run();\n }\n</code></pre>\n\n<p>When I launch the project, everything was hidden including in the taskbar unless I need to show it..</p>\n"
},
{
"answer_id": 44384424,
"author": "LKane",
"author_id": 8118322,
"author_profile": "https://Stackoverflow.com/users/8118322",
"pm_score": 1,
"selected": false,
"text": "<p>Override OnVisibleChanged in Form</p>\n\n<pre><code>protected override void OnVisibleChanged(EventArgs e)\n{\n this.Visible = false;\n\n base.OnVisibleChanged(e);\n}\n</code></pre>\n\n<p>You can add trigger if you may need to show it at some point</p>\n\n<pre><code>public partial class MainForm : Form\n{\npublic bool hideForm = true;\n...\npublic MainForm (bool hideForm)\n {\n this.hideForm = hideForm;\n InitializeComponent();\n }\n...\nprotected override void OnVisibleChanged(EventArgs e)\n {\n if (this.hideForm)\n this.Visible = false;\n\n base.OnVisibleChanged(e);\n }\n...\n}\n</code></pre>\n"
},
{
"answer_id": 52763389,
"author": "Plague",
"author_id": 10490551,
"author_profile": "https://Stackoverflow.com/users/10490551",
"pm_score": 2,
"selected": false,
"text": "<p>Put this in your Program.cs:</p>\n\n<pre><code>FormName FormName = new FormName ();\n\nFormName.ShowInTaskbar = false;\nFormName.Opacity = 0;\nFormName.Show();\nFormName.Hide();\n</code></pre>\n\n<p>Use this when you want to display the form:</p>\n\n<pre><code>var principalForm = Application.OpenForms.OfType<FormName>().Single();\nprincipalForm.ShowInTaskbar = true;\nprincipalForm.Opacity = 100;\nprincipalForm.Show();\n</code></pre>\n"
},
{
"answer_id": 55231693,
"author": "blind Skwirl",
"author_id": 5271220,
"author_profile": "https://Stackoverflow.com/users/5271220",
"pm_score": 0,
"selected": false,
"text": "<p>I had an issue similar to the poster's where the code to hide the form in the form_Load event was firing before the form was completely done loading, making the Hide() method fail (not crashing, just wasn't working as expected).</p>\n\n<p>The other answers are great and work but I've found that in general, the form_Load event often has such issues and what you want to put in there can easily go in the constructor or the form_Shown event. </p>\n\n<p>Anyways, when I moved that same code that checks some things then hides the form when its not needed (a login form when single sign on fails), its worked as expected.</p>\n"
},
{
"answer_id": 56698263,
"author": "Muhammad Rashed Nadeem",
"author_id": 1161905,
"author_profile": "https://Stackoverflow.com/users/1161905",
"pm_score": 0,
"selected": false,
"text": "<pre><code> static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Form1 form1 = new Form1();\n form1.Visible = false;\n Application.Run();\n\n }\n private void ExitToolStripMenuItem_Click(object sender, EventArgs e)\n {\n this.Close();\n Application.Exit();\n }\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1500/"
]
| I have an application with one form in it, and on the Load method I need to hide the form.
The form will display itself when it has a need to (think along the lines of a outlook 2003 style popup), but I can' figure out how to hide the form on load without something messy.
Any suggestions? | I'm coming at this from C#, but should be very similar in vb.net.
In your main program file, in the Main method, you will have something like:
```
Application.Run(new MainForm());
```
This creates a new main form and limits the lifetime of the application to the lifetime of the main form.
However, if you remove the parameter to Application.Run(), then the application will be started with no form shown and you will be free to show and hide forms as much as you like.
Rather than hiding the form in the Load method, initialize the form before calling Application.Run(). I'm assuming the form will have a NotifyIcon on it to display an icon in the task bar - this can be displayed even if the form itself is not yet visible. Calling `Form.Show()` or `Form.Hide()` from handlers of NotifyIcon events will show and hide the form respectively. |
70,303 | <p>I have a structure in C#:</p>
<pre><code>public struct UserInfo
{
public string str1
{
get;
set;
}
public string str2
{
get;
set;
}
}
</code></pre>
<p>The only rule is that <code>UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))</code></p>
<p>How to override the GetHashCode function for this structure? </p>
| [
{
"answer_id": 70323,
"author": "VolkerK",
"author_id": 4833,
"author_profile": "https://Stackoverflow.com/users/4833",
"pm_score": 0,
"selected": false,
"text": "<p>Many possibilities. E.g.<br /></p>\n\n<p><code>\nreturn str1.GetHashCode() ^ str1.GetHashCode()\n</code></p>\n"
},
{
"answer_id": 70326,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps something like str1.GetHashCode() + str2.GetHashCode()? or (str1.GetHashCode() + str2.GetHashCode()) / 2? This way it would be the same regardless of whether str1 and str2 are swapped....</p>\n"
},
{
"answer_id": 70336,
"author": "Artem Tikhomirov",
"author_id": 2313,
"author_profile": "https://Stackoverflow.com/users/2313",
"pm_score": 1,
"selected": false,
"text": "<p>Try out this one:</p>\n\n<pre><code>(((long)str1.GetHashCode()) + ((long)str2.GetHashCode())).GetHashCode()\n</code></pre>\n"
},
{
"answer_id": 70353,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 0,
"selected": false,
"text": "<p>Sort them, then concatenate them:</p>\n\n<pre>\nreturn ((str1.CompareTo(str2) < 1) ? str1 + str2 : str2 + str1)\n .GetHashCode();\n</pre>\n"
},
{
"answer_id": 70373,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 0,
"selected": false,
"text": "<p>GetHashCode's result is supposed to be:</p>\n\n<ol>\n<li>As fast as possible.</li>\n<li>As unique as possible.</li>\n</ol>\n\n<p>Bearing those in mind, I would go with something like this:</p>\n\n<pre><code>if (str1 == null)\n if (str2 == null)\n return 0;\n else\n return str2.GetHashCode();\nelse\n if (str2 == null)\n return str1.GetHashCode();\n else\n return ((ulong)str1.GetHashCode() | ((ulong)str2.GetHashCode() << 32)).GetHashCode();\n</code></pre>\n\n<p><strong>Edit:</strong> Forgot the nulls. Code fixed.</p>\n"
},
{
"answer_id": 70375,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 7,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<p>A hash function must have the following properties:</p>\n\n<blockquote>\n <ul>\n <li>If two objects compare as equal, the <code>GetHashCode</code> method for each object must return the same value. However, if two objects do not compare as equal, the <code>GetHashCode</code> methods for the two object do not have to return different values.</li>\n <li>The <code>GetHashCode</code> method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's <code>Equals</code> method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.</li>\n <li>For the best performance, a hash function must generate a random distribution for all input. </li>\n </ul>\n</blockquote>\n\n<p>Taking it into account correct way is:</p>\n\n<pre><code>return str1.GetHashCode() ^ str2.GetHashCode() \n</code></pre>\n\n<p><code>^</code> can be substituted with other commutative operation</p>\n"
},
{
"answer_id": 70383,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 2,
"selected": false,
"text": "<p>Ah yes, as Gary Shutler pointed out:</p>\n\n<pre><code>return str1.GetHashCode() + str2.GetHashCode();\n</code></pre>\n\n<p>Can overflow. You could try casting to long as Artem suggested, or you could surround the statement in the unchecked keyword:</p>\n\n<pre><code>return unchecked(str1.GetHashCode() + str2.GetHashCode());\n</code></pre>\n"
},
{
"answer_id": 70512,
"author": "Roger Willcocks",
"author_id": 11511,
"author_profile": "https://Stackoverflow.com/users/11511",
"pm_score": -1,
"selected": false,
"text": "<p>Too complicated, and forgets nulls, etc. This is used for things like bucketing, so you can get away with something like</p>\n\n<pre><code>if (null != str1) {\n return str1.GetHashCode();\n}\nif (null != str2) {\n return str2.GetHashCode();\n}\n//Not sure what you would put here, some constant value will do\nreturn 0;\n</code></pre>\n\n<p>This is biased by assuming that str1 is not likely to be common in an unusually large proportion of instances.</p>\n"
},
{
"answer_id": 70615,
"author": "user11556",
"author_id": 11556,
"author_profile": "https://Stackoverflow.com/users/11556",
"pm_score": 2,
"selected": false,
"text": "<pre><code>public override int GetHashCode() \n{ \n unchecked \n { \n return(str1 != null ? str1.GetHashCode() : 0) ^ (str2 != null ? str2.GetHashCode() : 0); \n } \n}\n</code></pre>\n"
},
{
"answer_id": 70739,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public override int GetHashCode()\n{\n unchecked\n {\n return (str1 ?? String.Empty).GetHashCode() +\n (str2 ?? String.Empty).GetHashCode();\n }\n}\n</code></pre>\n\n<p>Using the '+' operator might be better than using '^', because although you explicitly want ('AA', 'BB') and ('BB', 'AA') to explicitly be the same, you may not want ('AA', 'AA') and ('BB', 'BB') to be the same (or all equal pairs for that matter).</p>\n\n<p>The 'as fast as possible' rule is not entirely adhered to in this solution because in the case of nulls this performs a 'GetHashCode()' on the empty string rather than immediately return a known constant, but even without explicitly measuring I am willing to hazard a guess that the difference wouldn't be big enough to worry about unless you expect a lot of nulls.</p>\n"
},
{
"answer_id": 74820,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li><p>As a general rule, a simple way to generate a hashcode for a class is to XOR all the data fields that can participate in generating the hash code (being careful to check for null as pointed out by others). This also meets the (artificial?) requirement that the hashcodes for UserInfo(\"AA\", \"BB\") and UserInfo(\"BB\", \"AA\") are the same.</p></li>\n<li><p>If you can make assumptions about the use of your class, you can perhaps improve your hash function. For example, if it is common for str1 and str2 to be the same, XOR may not be a good choice. But if str1 and str2 represent, say, first and last name, XOR is probably a good choice.</p></li>\n</ol>\n\n<p>Although this is clearly not meant to be a real-world example, it may be worth pointing out that: \n- This is probably a poor example of use of a struct: A struct should normally have value semantics, which doesn't seem to be the case here.\n- Using properties with setters to generate a hash code is also asking for trouble. </p>\n"
},
{
"answer_id": 1027782,
"author": "Tomáš Kafka",
"author_id": 38729,
"author_profile": "https://Stackoverflow.com/users/38729",
"pm_score": 5,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode\">Jon Skeet's answer</a> - binary operations like <code>^</code> are not good, they will often generate colliding hash!</p>\n"
},
{
"answer_id": 21604191,
"author": "Jani Hyytiäinen",
"author_id": 611056,
"author_profile": "https://Stackoverflow.com/users/611056",
"pm_score": 2,
"selected": false,
"text": "<p>Going along the lines ReSharper is suggesting:</p>\n\n<pre><code>public int GetHashCode()\n{\n unchecked\n {\n int hashCode;\n\n // String properties\n hashCode = (hashCode * 397) ^ (str1!= null ? str1.GetHashCode() : 0);\n hashCode = (hashCode * 397) ^ (str2!= null ? str1.GetHashCode() : 0);\n\n // int properties\n hashCode = (hashCode * 397) ^ intProperty;\n return hashCode;\n }\n}\n</code></pre>\n\n<p>397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. Otherwise there's nothing special in 397 that distinguishes it from other primes of the same magnitude.</p>\n"
},
{
"answer_id": 23545115,
"author": "Daniel Lidström",
"author_id": 286406,
"author_profile": "https://Stackoverflow.com/users/286406",
"pm_score": 2,
"selected": false,
"text": "<p>A simple <em>general</em> way is to do this:</p>\n\n<pre><code>return string.Format(\"{0}/{1}\", str1, str2).GetHashCode();\n</code></pre>\n\n<p>Unless you have strict performance requirements, this is the easiest I can think of and I frequently use this method when I need a composite key. It handles the <code>null</code> cases just fine and won't cause (m)any hash collisions (in general). If you expect '/' in your strings, just choose another separator that you don't expect.</p>\n"
},
{
"answer_id": 67469888,
"author": "Pablo Retyk",
"author_id": 30729,
"author_profile": "https://Stackoverflow.com/users/30729",
"pm_score": 1,
"selected": false,
"text": "<p>Since C# 7, we can take advantage of ValueTuple for that:</p>\n<pre><code>return (str1, str2).GetHashCode();\n</code></pre>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
| I have a structure in C#:
```
public struct UserInfo
{
public string str1
{
get;
set;
}
public string str2
{
get;
set;
}
}
```
The only rule is that `UserInfo(str1="AA", str2="BB").Equals(UserInfo(str1="BB", str2="AA"))`
How to override the GetHashCode function for this structure? | [MSDN](http://msdn.microsoft.com/en-us/library/system.object.gethashcode.aspx):
A hash function must have the following properties:
>
> * If two objects compare as equal, the `GetHashCode` method for each object must return the same value. However, if two objects do not compare as equal, the `GetHashCode` methods for the two object do not have to return different values.
> * The `GetHashCode` method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's `Equals` method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
> * For the best performance, a hash function must generate a random distribution for all input.
>
>
>
Taking it into account correct way is:
```
return str1.GetHashCode() ^ str2.GetHashCode()
```
`^` can be substituted with other commutative operation |
70,318 | <p>Experienced with Rails / ActiveRecord 2.1.1</p>
<ul>
<li>You create a first version with (for example) ruby script\generate scaffold product title:string description:text image_url:string</li>
<li>This create (for example) a migration file called 20080910122415_create_products.rb</li>
<li>You apply the migration with rake db:migrate</li>
<li>Now, you add a field to the product table with ruby script\generate migration add_price_to_product price:decimal</li>
<li>This create a migration file called 20080910125745_add_price_to_product.rb</li>
<li>If you try to run rake db:migrate, it will actually revert the first migration, not apply the next one! So your product table will get destroyed!</li>
<li>But if you ran rake alone, it would have told you that one migration was pending</li>
</ul>
<p>Pls note that applying rake db:migrate (once the table has been destroyed) will apply all migrations in order.</p>
<p>The only workaround I found is to specify the version of the new migration as in: </p>
<pre><code>rake db:migrate version=20080910125745
</code></pre>
<p>So I'm wondering: is this an expected new behavior?</p>
| [
{
"answer_id": 70771,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 2,
"selected": true,
"text": "<p>You should be able to use </p>\n\n<pre><code>rake db:migrate:up \n</code></pre>\n\n<p>to force it to go forward, but then you risk missing interleaved migrations from other people on your team</p>\n\n<p>if you run </p>\n\n<pre><code>rake db:migrate \n</code></pre>\n\n<p>twice, it will reapply all your migrations.</p>\n\n<p>I encounter the same behavior on windows with SQLite, it might be a bug specific to such an environment.</p>\n\n<p><strong>Edit</strong> -- I found why. In the railstie database.rake task you have the following code :</p>\n\n<pre><code>desc \"Migrate the database through scripts in db/migrate. Target specific version with VERSION=x. Turn off output with VERBOSE=false.\"\ntask :migrate => :environment do\n ActiveRecord::Migration.verbose = ENV[\"VERBOSE\"] ? ENV[\"VERBOSE\"] == \"true\" : true\n ActiveRecord::Migrator.migrate(\"db/migrate/\", ENV[\"VERSION\"] ? ENV[\"VERSION\"].to_i : nil)\n Rake::Task[\"db:schema:dump\"].invoke if ActiveRecord::Base.schema_format == :ruby\nend\n</code></pre>\n\n<p>Then in my environment variables I have </p>\n\n<pre><code>echo %Version% #=> V3.5.0f\n</code></pre>\n\n<p>in Ruby</p>\n\n<pre><code>ENV[\"VERSION\"] # => V3.5.0f\nENV[\"VERSION\"].to_i #=>0 not nil !\n</code></pre>\n\n<p>thus the rake task calls </p>\n\n<pre><code>ActiveRecord::Migrator.migrate(\"db/migrate/\", 0)\n</code></pre>\n\n<p>and in ActiveRecord::Migrator we have : </p>\n\n<pre><code>class Migrator#:nodoc:\n class << self\n def migrate(migrations_path, target_version = nil)\n case\n when target_version.nil? then up(migrations_path, target_version)\n when current_version > target_version then down(migrations_path, target_version)\n else up(migrations_path, target_version)\n end\n end\n</code></pre>\n\n<p>Yes, <code>rake db:migrate VERSION=0</code> is the long version for <code>rake db:migrate:down</code> </p>\n\n<p><strong>Edit</strong> - I would go update the lighthouse bug but I the super company proxy forbids that I connect there</p>\n\n<p>In the meantime you may try to unset Version before you call migrate ...</p>\n"
},
{
"answer_id": 70830,
"author": "tomafro",
"author_id": 7126,
"author_profile": "https://Stackoverflow.com/users/7126",
"pm_score": 0,
"selected": false,
"text": "<p>This is not the expected behaviour. I was going to suggest reporting this as a bug on lighthouse, but I see you've <a href=\"http://rails.lighthouseapp.com/projects/8994/tickets/1021-rake-dbmigrate-doesnt-detect-new-migration\" rel=\"nofollow noreferrer\">already done so</a>! If you provide some more information (including OS/database/ruby version) I will take a look at it. </p>\n"
},
{
"answer_id": 71016,
"author": "Jean",
"author_id": 7898,
"author_profile": "https://Stackoverflow.com/users/7898",
"pm_score": 0,
"selected": false,
"text": "<p>I respectfully disagree Tom! this <em>is</em> a bug !! V3.5.0f is not a valid version for rake migrations. Rake should not use it to migrate:down just because ruby chose to consider that \"V3.5.0f\".to_i is 0 ... </p>\n\n<p>Rake should loudly complain that VERSION is not valid so that users know what is up\n(between you and me, checking that the version is a YYYYMMDD formated timestamp by converting to integer is a bit light)</p>\n\n<p>[Damn IE6 that won't allow me to comment ! and no I can't change browser thanks corporate]</p>\n"
},
{
"answer_id": 71104,
"author": "Rollo Tomazzi",
"author_id": 11477,
"author_profile": "https://Stackoverflow.com/users/11477",
"pm_score": 0,
"selected": false,
"text": "<p>Jean,</p>\n\n<p>Thanks a lot for your investigation. You're right, and actually I think you've uncovered a more severe bug, of species 'design bug'.</p>\n\n<p>What's happening is that rake will grab whatever value you pass to the command line and store them as environment variables. The rake tasks that will eventually get called will just pull this values from the environment variable.\nWhen db:migrate queries ENV[\"VERSION\"], it actually requests the version parameter which you set calling rake. When you call rake db:migrate, you don't pass any version.</p>\n\n<p>But we do have an environment variable called VERSION that has been set for other purposes by some other program (I don't which one yet). And the guys behind rake (or behind database.rake) haven't figured this would happen. That's a design bug. At least, they could have used more specific variable names like \"RAKE_VERSION\" or \"RAKE_PARAM_VERSION\" instead of just \"VERSION\".</p>\n\n<p>Tom, I will definitely not close but edit my bug report on lighthouse to reflect these new findings.</p>\n\n<p>And thanks again Jean for your help. I've posted this bug on lighthouse like 5 days agao and still got no answer!</p>\n\n<p>Rollo</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11477/"
]
| Experienced with Rails / ActiveRecord 2.1.1
* You create a first version with (for example) ruby script\generate scaffold product title:string description:text image\_url:string
* This create (for example) a migration file called 20080910122415\_create\_products.rb
* You apply the migration with rake db:migrate
* Now, you add a field to the product table with ruby script\generate migration add\_price\_to\_product price:decimal
* This create a migration file called 20080910125745\_add\_price\_to\_product.rb
* If you try to run rake db:migrate, it will actually revert the first migration, not apply the next one! So your product table will get destroyed!
* But if you ran rake alone, it would have told you that one migration was pending
Pls note that applying rake db:migrate (once the table has been destroyed) will apply all migrations in order.
The only workaround I found is to specify the version of the new migration as in:
```
rake db:migrate version=20080910125745
```
So I'm wondering: is this an expected new behavior? | You should be able to use
```
rake db:migrate:up
```
to force it to go forward, but then you risk missing interleaved migrations from other people on your team
if you run
```
rake db:migrate
```
twice, it will reapply all your migrations.
I encounter the same behavior on windows with SQLite, it might be a bug specific to such an environment.
**Edit** -- I found why. In the railstie database.rake task you have the following code :
```
desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
task :migrate => :environment do
ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
```
Then in my environment variables I have
```
echo %Version% #=> V3.5.0f
```
in Ruby
```
ENV["VERSION"] # => V3.5.0f
ENV["VERSION"].to_i #=>0 not nil !
```
thus the rake task calls
```
ActiveRecord::Migrator.migrate("db/migrate/", 0)
```
and in ActiveRecord::Migrator we have :
```
class Migrator#:nodoc:
class << self
def migrate(migrations_path, target_version = nil)
case
when target_version.nil? then up(migrations_path, target_version)
when current_version > target_version then down(migrations_path, target_version)
else up(migrations_path, target_version)
end
end
```
Yes, `rake db:migrate VERSION=0` is the long version for `rake db:migrate:down`
**Edit** - I would go update the lighthouse bug but I the super company proxy forbids that I connect there
In the meantime you may try to unset Version before you call migrate ... |
70,324 | <p>What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these?</p>
| [
{
"answer_id": 70339,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 3,
"selected": false,
"text": "<p>Ummm… An inner class <em>is</em> a nested class… Do you mean anonymous class and inner class?</p>\n<p>Edit: If you actually meant inner v.s. anonymous: an inner class is just a class defined within a class, such as:</p>\n<pre><code>public class A {\n public class B {\n }\n}\n</code></pre>\n<p>…whereas an anonymous class is an extension of a class defined anonymously, so no actual "class" is defined, as in:</p>\n<pre><code>public class A {\n}\n\nA anon = new A() { /* You could change behavior of A here */ };\n</code></pre>\n<p>Further edit:</p>\n<p>Wikipedia <a href=\"http://en.wikipedia.org/wiki/Inner_class\" rel=\"nofollow noreferrer\">claims there is a difference</a> in Java, but I've been working with Java for eight years, and it's the first time I heard such a distinction – not to mention there are no references there to back up the claim… Bottom line, an inner class is a class defined within a class (static or not), and nested is just another term to mean the same thing.</p>\n<p>There is a subtle difference between static and non-static nested classes… Basically, non-static inner classes have implicit access to instance fields and methods of the enclosing class (thus they cannot be constructed in a static context, it will be a compiler error). On the other hand, static nested classes don't have implicit access to instance fields and methods and <em>can</em> be constructed in a static context.</p>\n"
},
{
"answer_id": 70349,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 3,
"selected": false,
"text": "<p>The terms are used interchangeably. If you want to be really pedantic about it, then you <em>could</em> define \"nested class\" to refer to a static inner class, one which has no enclosing instance. In code, you might have something like this:</p>\n\n<pre><code>public class Outer {\n public class Inner {}\n\n public static class Nested {}\n}\n</code></pre>\n\n<p>That's not really a widely accepted definition though.</p>\n"
},
{
"answer_id": 70358,
"author": "Martin",
"author_id": 11357,
"author_profile": "https://Stackoverflow.com/users/11357",
"pm_score": 12,
"selected": true,
"text": "<p>From the <a href=\"http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html\" rel=\"noreferrer\">Java Tutorial</a>:</p>\n\n<blockquote>\n <p>Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes. </p>\n</blockquote>\n\n<p>Static nested classes are accessed using the enclosing class name:</p>\n\n<pre><code>OuterClass.StaticNestedClass\n</code></pre>\n\n<p>For example, to create an object for the static nested class, use this syntax:</p>\n\n<pre><code>OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();\n</code></pre>\n\n<p>Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:</p>\n\n<pre><code>class OuterClass {\n ...\n class InnerClass {\n ...\n }\n}\n</code></pre>\n\n<p>An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.</p>\n\n<p>To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:</p>\n\n<pre><code>OuterClass outerObject = new OuterClass()\nOuterClass.InnerClass innerObject = outerObject.new InnerClass();\n</code></pre>\n\n<p>see: <a href=\"http://download.oracle.com/javase/tutorial/java/javaOO/nested.html\" rel=\"noreferrer\">Java Tutorial - Nested Classes</a></p>\n\n<p>For completeness note that there is also such a thing as an <a href=\"https://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance\">inner class <em>without</em> an enclosing instance</a>:</p>\n\n<pre><code>class A {\n int t() { return 1; }\n static A a = new A() { int t() { return 2; } };\n}\n</code></pre>\n\n<p>Here, <code>new A() { ... }</code> is an <em>inner class defined in a static context</em> and does not have an enclosing instance.</p>\n"
},
{
"answer_id": 70394,
"author": "Wouter Coekaerts",
"author_id": 3432,
"author_profile": "https://Stackoverflow.com/users/3432",
"pm_score": 3,
"selected": false,
"text": "<p>Nested class is a very general term: every class which is not top level is a nested class.\nAn inner class is a non-static nested class.\nJoseph Darcy wrote a very nice explanation about <a href=\"http://blogs.oracle.com/darcy/entry/nested_inner_member_and_top\" rel=\"noreferrer\">Nested, Inner, Member, and Top-Level Classes</a>.</p>\n"
},
{
"answer_id": 70522,
"author": "rmaruszewski",
"author_id": 6856,
"author_profile": "https://Stackoverflow.com/users/6856",
"pm_score": 4,
"selected": false,
"text": "<p>The instance of the inner class is created when instance of the outer class is created. Therefore the members and methods of the inner class have access to the members and methods of the instance (object) of the outer class. When the instance of the outer class goes out of scope, also the inner class instances cease to exist.</p>\n\n<p>The static nested class doesn't have a concrete instance. It's just loaded when it's used for the first time (just like the static methods). It's a completely independent entity, whose methods and variables doesn't have any access to the instances of the outer class.</p>\n\n<p>The static nested classes are not coupled with the outer object, they are faster, and they don't take heap/stack memory, because its not necessary to create instance of such class. Therefore the rule of thumb is to try to define static nested class, with as limited scope as possible (private >= class >= protected >= public), and then convert it to inner class (by removing \"static\" identifier) and loosen the scope, if it's really necessary.</p>\n"
},
{
"answer_id": 70613,
"author": "jrudolph",
"author_id": 7647,
"author_profile": "https://Stackoverflow.com/users/7647",
"pm_score": 7,
"selected": false,
"text": "<p>I don't think the real difference became clear in the above answers. </p>\n\n<p>First to get the terms right: </p>\n\n<ul>\n<li>A nested class is a class which is contained in another class at the source code level.</li>\n<li>It is static if you declare it with the <strong>static</strong> modifier.</li>\n<li>A non-static nested class is called inner class. (I stay with non-static nested class.)</li>\n</ul>\n\n<p>Martin's answer is right so far. However, the actual question is: What is the purpose of declaring a nested class static or not?</p>\n\n<p>You use <strong>static nested classes</strong> if you just want to keep your classes together if they belong topically together or if the nested class is exclusively used in the enclosing class. There is no semantic difference between a static nested class and every other class.</p>\n\n<p><strong>Non-static nested classes</strong> are a different beast. Similar to anonymous inner classes, such nested classes are actually closures. That means they capture their surrounding scope and their enclosing instance and make that accessible. Perhaps an example will clarify that. See this stub of a Container:</p>\n\n<pre><code>public class Container {\n public class Item{\n Object data;\n public Container getContainer(){\n return Container.this;\n }\n public Item(Object data) {\n super();\n this.data = data;\n }\n\n }\n\n public static Item create(Object data){\n // does not compile since no instance of Container is available\n return new Item(data);\n }\n public Item createSubItem(Object data){\n // compiles, since 'this' Container is available\n return new Item(data);\n }\n}\n</code></pre>\n\n<p>In this case you want to have a reference from a child item to the parent container. Using a non-static nested class, this works without some work. You can access the enclosing instance of Container with the syntax <code>Container.this</code>.</p>\n\n<p>More hardcore explanations following:</p>\n\n<p>If you look at the Java bytecodes the compiler generates for an (non-static) nested class it might become even clearer:</p>\n\n<pre><code>// class version 49.0 (49)\n// access flags 33\npublic class Container$Item {\n\n // compiled from: Container.java\n // access flags 1\n public INNERCLASS Container$Item Container Item\n\n // access flags 0\n Object data\n\n // access flags 4112\n final Container this$0\n\n // access flags 1\n public getContainer() : Container\n L0\n LINENUMBER 7 L0\n ALOAD 0: this\n GETFIELD Container$Item.this$0 : Container\n ARETURN\n L1\n LOCALVARIABLE this Container$Item L0 L1 0\n MAXSTACK = 1\n MAXLOCALS = 1\n\n // access flags 1\n public <init>(Container,Object) : void\n L0\n LINENUMBER 12 L0\n ALOAD 0: this\n ALOAD 1\n PUTFIELD Container$Item.this$0 : Container\n L1\n LINENUMBER 10 L1\n ALOAD 0: this\n INVOKESPECIAL Object.<init>() : void\n L2\n LINENUMBER 11 L2\n ALOAD 0: this\n ALOAD 2: data\n PUTFIELD Container$Item.data : Object\n RETURN\n L3\n LOCALVARIABLE this Container$Item L0 L3 0\n LOCALVARIABLE data Object L0 L3 2\n MAXSTACK = 2\n MAXLOCALS = 3\n}\n</code></pre>\n\n<p>As you can see the compiler creates a hidden field <code>Container this$0</code>. This is set in the constructor which has an additional parameter of type Container to specify the enclosing instance. You can't see this parameter in the source but the compiler implicitly generates it for a nested class. </p>\n\n<p>Martin's example</p>\n\n<pre><code>OuterClass.InnerClass innerObject = outerObject.new InnerClass();\n</code></pre>\n\n<p>would so be compiled to a call of something like (in bytecodes)</p>\n\n<pre><code>new InnerClass(outerObject)\n</code></pre>\n\n<p>For the sake of completeness:</p>\n\n<p>An anonymous class <strong>is</strong> a perfect example of a non-static nested class which just has no name associated with it and can't be referenced later.</p>\n"
},
{
"answer_id": 70687,
"author": "Jegschemesch",
"author_id": 1586,
"author_profile": "https://Stackoverflow.com/users/1586",
"pm_score": 9,
"selected": false,
"text": "<p>The <a href=\"http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html\" rel=\"noreferrer\">Java tutorial says</a>:</p>\n\n<blockquote>\n <p>Terminology: Nested classes are\n divided into two categories: static\n and non-static. Nested classes that\n are declared static are simply called\n static nested classes. Non-static\n nested classes are called inner\n classes.</p>\n</blockquote>\n\n<p>In common parlance, the terms \"nested\" and \"inner\" are used interchangeably by most programmers, but I'll use the correct term \"nested class\" which covers both inner and static.</p>\n\n<p>Classes can be nested <em>ad infinitum</em>, e.g. class A can contain class B which contains class C which contains class D, etc. However, more than one level of class nesting is rare, as it is generally bad design.</p>\n\n<p>There are three reasons you might create a nested class:</p>\n\n<ul>\n<li>organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won't be used in any other context</li>\n<li>access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).</li>\n<li>convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context</li>\n</ul>\n\n<p>There are <strong>four kinds of nested class in Java</strong>. In brief, they are:</p>\n\n<ul>\n<li><strong>static class</strong>: declared as a static member of another class</li>\n<li><strong>inner class</strong>: declared as an instance member of another class</li>\n<li><strong>local inner class</strong>: declared inside an instance method of another class</li>\n<li><strong>anonymous inner class</strong>: like a local inner class, but written as an expression which returns a one-off object</li>\n</ul>\n\n<p>Let me elaborate in more details.</p>\n\n<p><br></p>\n\n<h2>Static Classes</h2>\n\n<p>Static classes are the easiest kind to understand because they have nothing to do with instances of the containing class.</p>\n\n<p>A static class is a class declared as a static member of another class. Just like other static members, such a class is really just a hanger on that uses the containing class as its namespace, <em>e.g.</em> the class <em>Goat</em> declared as a static member of class <em>Rhino</em> in the package <em>pizza</em> is known by the name <em>pizza.Rhino.Goat</em>.</p>\n\n<pre><code>package pizza;\n\npublic class Rhino {\n\n ...\n\n public static class Goat {\n ...\n }\n}\n</code></pre>\n\n<p>Frankly, static classes are a pretty worthless feature because classes are already divided into namespaces by packages. The only real conceivable reason to create a static class is that such a class has access to its containing class's private static members, but I find this to be a pretty lame justification for the static class feature to exist.</p>\n\n<p><br></p>\n\n<h2>Inner Classes</h2>\n\n<p>An inner class is a class declared as a non-static member of another class:</p>\n\n<pre><code>package pizza;\n\npublic class Rhino {\n\n public class Goat {\n ...\n }\n\n private void jerry() {\n Goat g = new Goat();\n }\n}\n</code></pre>\n\n<p>Like with a static class, the inner class is known as qualified by its containing class name, <em>pizza.Rhino.Goat</em>, but inside the containing class, it can be known by its simple name. However, every instance of an inner class is tied to a particular instance of its containing class: above, the <em>Goat</em> created in <em>jerry</em>, is implicitly tied to the <em>Rhino</em> instance <em>this</em> in <em>jerry</em>. Otherwise, we make the associated <em>Rhino</em> instance explicit when we instantiate <em>Goat</em>:</p>\n\n<pre><code>Rhino rhino = new Rhino();\nRhino.Goat goat = rhino.new Goat();\n</code></pre>\n\n<p>(Notice you refer to the inner type as just <em>Goat</em> in the weird <em>new</em> syntax: Java infers the containing type from the <em>rhino</em> part. And, yes <em>new rhino.Goat()</em> would have made more sense to me too.)</p>\n\n<p>So what does this gain us? Well, the inner class instance has access to the instance members of the containing class instance. These enclosing instance members are referred to inside the inner class <em>via</em> just their simple names, not <em>via</em> <em>this</em> (<em>this</em> in the inner class refers to the inner class instance, not the associated containing class instance): </p>\n\n<pre><code>public class Rhino {\n\n private String barry;\n\n public class Goat {\n public void colin() {\n System.out.println(barry);\n }\n }\n}\n</code></pre>\n\n<p>In the inner class, you can refer to <em>this</em> of the containing class as <em>Rhino.this</em>, and you can use <em>this</em> to refer to its members, <em>e.g. Rhino.this.barry</em>.</p>\n\n<p><br></p>\n\n<h2>Local Inner Classes</h2>\n\n<p>A local inner class is a class declared in the body of a method. Such a class is only known within its containing method, so it can only be instantiated and have its members accessed within its containing method. The gain is that a local inner class instance is tied to and can access the final local variables of its containing method. When the instance uses a final local of its containing method, the variable retains the value it held at the time of the instance's creation, even if the variable has gone out of scope (this is effectively Java's crude, limited version of closures).</p>\n\n<p>Because a local inner class is neither the member of a class or package, it is not declared with an access level. (Be clear, however, that its own members have access levels like in a normal class.)</p>\n\n<p>If a local inner class is declared in an instance method, an instantiation of the inner class is tied to the instance held by the containing method's <em>this</em> at the time of the instance's creation, and so the containing class's instance members are accessible like in an instance inner class. A local inner class is instantiated simply <em>via</em> its name, <em>e.g.</em> local inner class <em>Cat</em> is instantiated as <em>new Cat()</em>, not new this.Cat() as you might expect.</p>\n\n<p><br></p>\n\n<h2>Anonymous Inner Classes</h2>\n\n<p>An anonymous inner class is a syntactically convenient way of writing a local inner class. Most commonly, a local inner class is instantiated at most just once each time its containing method is run. It would be nice, then, if we could combine the local inner class definition and its single instantiation into one convenient syntax form, and it would also be nice if we didn't have to think up a name for the class (the fewer unhelpful names your code contains, the better). An anonymous inner class allows both these things:</p>\n\n<pre><code>new *ParentClassName*(*constructorArgs*) {*members*}\n</code></pre>\n\n<p>This is an expression returning a new instance of an unnamed class which extends <em>ParentClassName</em>. You cannot supply your own constructor; rather, one is implicitly supplied which simply calls the super constructor, so the arguments supplied must fit the super constructor. (If the parent contains multiple constructors, the “simplest” one is called, “simplest” as determined by a rather complex set of rules not worth bothering to learn in detail--just pay attention to what NetBeans or Eclipse tell you.)</p>\n\n<p>Alternatively, you can specify an interface to implement:</p>\n\n<pre><code>new *InterfaceName*() {*members*}\n</code></pre>\n\n<p>Such a declaration creates a new instance of an unnamed class which extends Object and implements <em>InterfaceName</em>. Again, you cannot supply your own constructor; in this case, Java implicitly supplies a no-arg, do-nothing constructor (so there will never be constructor arguments in this case).</p>\n\n<p>Even though you can't give an anonymous inner class a constructor, you can still do any setup you want using an initializer block (a {} block placed outside any method).</p>\n\n<p>Be clear that an anonymous inner class is simply a less flexible way of creating a local inner class with one instance. If you want a local inner class which implements multiple interfaces or which implements interfaces while extending some class other than <em>Object</em> or which specifies its own constructor, you're stuck creating a regular named local inner class.</p>\n"
},
{
"answer_id": 2523233,
"author": "HippoMan",
"author_id": 302506,
"author_profile": "https://Stackoverflow.com/users/302506",
"pm_score": 4,
"selected": false,
"text": "<p>There is a subtlety about the use of nested static classes that might be useful in certain situations.</p>\n\n<p>Whereas static attributes get instantiated before the class gets instantiated via its constructor,\nstatic attributes inside of nested static classes don't seem to get instantiated until after the\nclass's constructor gets invoked, or at least not until after the attributes are first referenced,\neven if they are marked as 'final'.</p>\n\n<p>Consider this example:</p>\n\n<pre><code>public class C0 {\n\n static C0 instance = null;\n\n // Uncomment the following line and a null pointer exception will be\n // generated before anything gets printed.\n //public static final String outerItem = instance.makeString(98.6);\n\n public C0() {\n instance = this;\n }\n\n public String makeString(int i) {\n return ((new Integer(i)).toString());\n }\n\n public String makeString(double d) {\n return ((new Double(d)).toString());\n }\n\n public static final class nested {\n public static final String innerItem = instance.makeString(42);\n }\n\n static public void main(String[] argv) {\n System.out.println(\"start\");\n // Comment out this line and a null pointer exception will be\n // generated after \"start\" prints and before the following\n // try/catch block even gets entered.\n new C0();\n try {\n System.out.println(\"retrieve item: \" + nested.innerItem);\n }\n catch (Exception e) {\n System.out.println(\"failed to retrieve item: \" + e.toString());\n }\n System.out.println(\"finish\");\n }\n}\n</code></pre>\n\n<p>Even though 'nested' and 'innerItem' are both declared as 'static final'. the setting\nof nested.innerItem doesn't take place until after the class is instantiated (or at least\nnot until after the nested static item is first referenced), as you can see for yourself\nby commenting and uncommenting the lines that I refer to, above. The same does not hold\ntrue for 'outerItem'.</p>\n\n<p>At least this is what I'm seeing in Java 6.0.</p>\n"
},
{
"answer_id": 2574123,
"author": "tejas",
"author_id": 308651,
"author_profile": "https://Stackoverflow.com/users/308651",
"pm_score": 4,
"selected": false,
"text": "<p>Nested class: class inside class</p>\n\n<p>Types:</p>\n\n<ol>\n<li>Static nested class</li>\n<li>Non-static nested class [Inner class]</li>\n</ol>\n\n<p>Difference:</p>\n\n<p><strong>Non-static nested class [Inner class]</strong></p>\n\n<p>In non-static nested class object of inner class exist within object of outer class. So that data member of outer class is accessible to inner class. So to create object of inner class we must create object of outer class first.</p>\n\n<pre><code>outerclass outerobject=new outerobject();\nouterclass.innerclass innerobjcet=outerobject.new innerclass(); \n</code></pre>\n\n<p><strong>Static nested class</strong></p>\n\n<p>In static nested class object of inner class don't need object of outer class, because the word \"static\" indicate no need to create object.</p>\n\n<pre><code>class outerclass A {\n static class nestedclass B {\n static int x = 10;\n }\n}\n</code></pre>\n\n<p>If you want to access x, then write the following inside method</p>\n\n<pre><code> outerclass.nestedclass.x; i.e. System.out.prinltn( outerclass.nestedclass.x);\n</code></pre>\n"
},
{
"answer_id": 4460365,
"author": "sactiw",
"author_id": 416369,
"author_profile": "https://Stackoverflow.com/users/416369",
"pm_score": 5,
"selected": false,
"text": "<p>I think, the convention that is generally followed is this:</p>\n\n<ul>\n<li><strong>static class</strong> within a top level class is a <strong>nested class</strong></li>\n<li><strong>non static class</strong> within a top level class is a <strong>inner class</strong>, which further\nhas two more form:\n<ul>\n<li><strong>local class</strong> - named classes declared inside of a block like a method or constructor body</li>\n<li><strong>anonymous class</strong> - unnamed classes whose instances are created in expressions and statements</li>\n</ul></li>\n</ul>\n\n<p>However, few other <strong>points to remembers</strong> are:</p>\n\n<ul>\n<li><p>Top level classes and static nested class are semantically same except that in case of static nested class it can make static reference to private static fields/methods of its Outer [parent] class and vice versa.</p></li>\n<li><p>Inner classes have access to instance variables of the enclosing instance of the Outer [parent] class. However, not all inner classes have enclosing instances, for example inner classes in static contexts, like an anonymous class used in a static initializer block, do not.</p></li>\n<li><p>Anonymous class by default extends the parent class or implements the parent interface and there is no further clause to extend any other class or implement any more interfaces. So,</p>\n\n<ul>\n<li><code>new YourClass(){};</code> means <code>class [Anonymous] extends YourClass {}</code></li>\n<li><code>new YourInterface(){};</code> means <code>class [Anonymous] implements YourInterface {}</code></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>I feel that the bigger question that remains open which one to use and when? Well that mostly depends on what scenario you are dealing with but reading the reply given by @jrudolph may help you making some decision.</p>\n"
},
{
"answer_id": 9904357,
"author": "hqt",
"author_id": 1192728,
"author_profile": "https://Stackoverflow.com/users/1192728",
"pm_score": 2,
"selected": false,
"text": "<p>I think people here should notice to Poster that : Static Nest Class just only the first inner class.\nFor example:</p>\n\n<pre><code> public static class A {} //ERROR\n\n public class A {\n public class B {\n public static class C {} //ERROR\n }\n }\n\n public class A {\n public static class B {} //COMPILE !!!\n\n }\n</code></pre>\n\n<p>So, summarize, static class doesn't depend which class its contains. So, they cannot in normal class. (because normal class need an instance).</p>\n"
},
{
"answer_id": 10772428,
"author": "aleroot",
"author_id": 330280,
"author_profile": "https://Stackoverflow.com/users/330280",
"pm_score": 7,
"selected": false,
"text": "<p>I think that none of the above answers explain to you the real difference between a nested class and a static nested class in term of application design : </p>\n\n<h2>OverView</h2>\n\n<p><strong>A nested class</strong> could be nonstatic or static and in each case <strong>is a class defined within another class</strong>. <strong>A nested class should exist only to serve is enclosing class</strong>, if a nested class is useful by other classes (not only the enclosing), should be declared as a top level class.</p>\n\n<h2>Difference</h2>\n\n<p><strong>Nonstatic Nested class</strong> : is implicitly associated with the enclosing instance of the containing class, this means that it is possible to invoke methods and access variables of the enclosing instance. One common use of a nonstatic nested class is to define an Adapter class.</p>\n\n<p><strong>Static Nested Class</strong> : can't access enclosing class instance and invoke methods on it, so should be used when the nested class doesn't require access to an instance of the enclosing class . A common use of static nested class is to implement a components of the outer object.</p>\n\n<h2>Conclusion</h2>\n\n<p>So the main difference between the two from a design standpoint is : <em>nonstatic nested class can access instance of the container class, while static can't</em>.</p>\n"
},
{
"answer_id": 18721137,
"author": "Sohi",
"author_id": 1802850,
"author_profile": "https://Stackoverflow.com/users/1802850",
"pm_score": 0,
"selected": false,
"text": "<p>First of all There is no such class called Static class.The Static modifier use with inner class (called as Nested Class) says that it is a static member of Outer Class which means we can access it as with other static members and without having any instance of Outer class. (Which is benefit of static originally.) </p>\n\n<p>Difference between using Nested class and regular Inner class is:</p>\n\n<pre><code>OuterClass.InnerClass inner = new OuterClass().new InnerClass();\n</code></pre>\n\n<p>First We can to instantiate Outerclass then we Can access Inner.</p>\n\n<p>But if Class is Nested then syntax is:</p>\n\n<pre><code>OuterClass.InnerClass inner = new OuterClass.InnerClass();\n</code></pre>\n\n<p>Which uses the static Syntax as normal implementation of static keyword.</p>\n"
},
{
"answer_id": 19438489,
"author": "Thalaivar",
"author_id": 337128,
"author_profile": "https://Stackoverflow.com/users/337128",
"pm_score": 5,
"selected": false,
"text": "<p>In simple terms we need nested classes primarily because Java does not provide closures.</p>\n\n<p>Nested Classes are classes defined inside the body of another enclosing class. They are of two types - static and non-static.</p>\n\n<p>They are treated as members of the enclosing class, hence you can specify any of the four access specifiers - <code>private, package, protected, public</code>. We don't have this luxury with top-level classes, which can only be declared <code>public</code> or package-private.</p>\n\n<p>Inner classes aka Non-stack classes have access to other members of the top class, even if they are declared private while Static nested classes do not have access to other members of the top class.</p>\n\n<pre><code>public class OuterClass {\n public static class Inner1 {\n }\n public class Inner2 {\n }\n}\n</code></pre>\n\n<p><code>Inner1</code> is our static inner class and <code>Inner2</code> is our inner class which is not static. The key difference between them, you can't create an <code>Inner2</code> instance without an Outer where as you can create an <code>Inner1</code> object independently.</p>\n\n<p>When would you use Inner class?</p>\n\n<p>Think of a situation where <code>Class A</code> and <code>Class B</code> are related, <code>Class B</code> needs to access <code>Class A</code> members, and <code>Class B</code> is related only to <code>Class A</code>. Inner classes comes into the picture.</p>\n\n<p>For creating an instance of inner class, you need to create an instance of your outer class.</p>\n\n<pre><code>OuterClass outer = new OuterClass();\nOuterClass.Inner2 inner = outer.new Inner2();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>OuterClass.Inner2 inner = new OuterClass().new Inner2();\n</code></pre>\n\n<p>When would you use static Inner class?</p>\n\n<p>You would define a static inner class when you know that it does not have any relationship with the instance of the enclosing class/top class. If your inner class doesn't use methods or fields of the outer class, it's just a waste of space, so make it static.</p>\n\n<p>For example, to create an object for the static nested class, use this syntax:</p>\n\n<pre><code>OuterClass.Inner1 nestedObject = new OuterClass.Inner1();\n</code></pre>\n\n<p>The advantage of a static nested class is that it doesn't need an object of the containing class/top class to work. This can help you to reduce the number of objects your application creates at runtime.</p>\n"
},
{
"answer_id": 19977690,
"author": "Ankit Jain",
"author_id": 1423581,
"author_profile": "https://Stackoverflow.com/users/1423581",
"pm_score": 3,
"selected": false,
"text": "<p>In the case of creating instance, the instance of non \nstatic inner class is created with the reference of\nobject of outer class in which it is defined. This\nmeans it have inclosing instance.\nBut the instance of static inner class\nis created with the reference of Outer class, not with\nthe reference of object of outer class. This means it\nhave not inclosing instance.</p>\n\n<p>For example:</p>\n\n<pre><code>class A\n{\n class B\n {\n // static int x; not allowed here….. \n }\n static class C\n {\n static int x; // allowed here\n }\n}\n\nclass Test\n{\n public static void main(String… str)\n {\n A o=new A();\n A.B obj1 =o.new B();//need of inclosing instance\n\n A.C obj2 =new A.C();\n\n // not need of reference of object of outer class….\n }\n}\n</code></pre>\n"
},
{
"answer_id": 31537275,
"author": "VeKe",
"author_id": 1878022,
"author_profile": "https://Stackoverflow.com/users/1878022",
"pm_score": 3,
"selected": false,
"text": "<p><em>Targeting learner, who are novice to Java and/or Nested Classes</em> </p>\n\n<p>Nested classes can be either:\n<br> 1. Static Nested classes.<br>\n 2. Non Static Nested classes. (also known as <strong>Inner classes</strong>) =>Please remember this<br></p>\n\n<p><br>\n<strong>1.Inner classes</strong><br>\nExample:</p>\n\n<pre><code>class OuterClass {\n/* some code here...*/\n class InnerClass { }\n/* some code here...*/\n}\n</code></pre>\n\n<p><br><strong>Inner classes are subsets of nested classes:</strong></p>\n\n<ul>\n<li>inner class is a specific type of nested class</li>\n<li>inner classes are subsets of nested classes</li>\n<li>You can say that an <em>inner class is also a nested class, but you can <strong>NOT</strong> say that a nested class is also an inner class</em>. </li>\n</ul>\n\n<p><strong>Specialty of Inner class:</strong></p>\n\n<ul>\n<li>instance of an inner class has <strong>access to all</strong> of the members of the outer class, even those that are marked “private”</li>\n</ul>\n\n<p><br>\n<strong>2.Static Nested Classes:</strong><br>\nExample:</p>\n\n<pre><code>class EnclosingClass {\n static class Nested {\n void someMethod() { System.out.println(\"hello SO\"); }\n }\n}\n</code></pre>\n\n<p><strong>Case 1:Instantiating a static nested class from a non-enclosing class</strong></p>\n\n<pre><code>class NonEnclosingClass {\n\n public static void main(String[] args) {\n /*instantiate the Nested class that is a static\n member of the EnclosingClass class:\n */\n\n EnclosingClass.Nested n = new EnclosingClass.Nested(); \n n.someMethod(); //prints out \"hello\"\n }\n}\n</code></pre>\n\n<p><strong>Case 2:Instantiating a static nested class from an enclosing class</strong></p>\n\n<pre><code>class EnclosingClass {\n\n static class Nested {\n void anotherMethod() { System.out.println(\"hi again\"); } \n }\n\n public static void main(String[] args) {\n //access enclosed class:\n\n Nested n = new Nested(); \n n.anotherMethod(); //prints out \"hi again\"\n }\n\n}\n</code></pre>\n\n<p><strong>Specialty of Static classes:</strong></p>\n\n<ul>\n<li>Static inner class would only have access to the static members of the outer class, and have no access to non-static members.</li>\n</ul>\n\n<p><strong>Conclusion:</strong><br>\n<em>Question:</em> What is the main difference between a inner class and a static nested class in Java?<br>\n<em>Answer:</em> just go through specifics of each class mentioned above.</p>\n"
},
{
"answer_id": 33781508,
"author": "Adelin",
"author_id": 1170677,
"author_profile": "https://Stackoverflow.com/users/1170677",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think there is much to add here, most of the answers perfectly explain the differences between static nested class and Inner classes. However, consider the following issue when using nested classes vs inner classes. \nAs mention in a couple of answers inner classes can not be instantiated without and instance of their enclosing class which mean that they <strong>HOLD</strong> a <strong>pointer</strong> to the instance of their enclosing class which can lead to memory overflow or stack overflow exception due to the fact the GC will not be able to garbage collect the enclosing classes even if they are not used any more. To make this clear check the following code out: </p>\n\n<pre><code>public class Outer {\n\n\n public class Inner {\n\n }\n\n\n public Inner inner(){\n return new Inner();\n }\n\n @Override\n protected void finalize() throws Throwable {\n // as you know finalize is called by the garbage collector due to destroying an object instance\n System.out.println(\"I am destroyed !\");\n }\n}\n\n\npublic static void main(String arg[]) {\n\n Outer outer = new Outer();\n Outer.Inner inner = outer.new Inner();\n\n // out instance is no more used and should be garbage collected !!!\n // However this will not happen as inner instance is still alive i.e used, not null !\n // and outer will be kept in memory until inner is destroyed\n outer = null;\n\n //\n // inner = null;\n\n //kick out garbage collector\n System.gc();\n\n}\n</code></pre>\n\n<p>If you remove the comment on <code>// inner = null;</code> The program will out put \n\"<strong>I am destroyed !</strong>\", but keeping this commented it will not.<br>\nThe reason is that white inner instance is still referenced GC cannot collect it and because it references (has a pointer to) the outer instance it is not collected too. Having enough of these objects in your project and can run out of memory.<br>\nCompared to static inner classes which does not hold a point to inner class instance because it is not instance related but class related. \nThe above program can print \"<strong>I am destroyed !</strong>\" if you make Inner class static and instantiated with <code>Outer.Inner i = new Outer.Inner();</code> </p>\n"
},
{
"answer_id": 34551507,
"author": "Behzad Bahmanyar",
"author_id": 5079879,
"author_profile": "https://Stackoverflow.com/users/5079879",
"pm_score": 5,
"selected": false,
"text": "<p>Here is key differences and similarities between Java inner class and static nested class.</p>\n\n<p>Hope it helps!</p>\n\n<h3>Inner class</h3>\n\n<ul>\n<li><strong>Can access</strong> to outer class <strong>both instance and static</strong> methods and fields</li>\n<li><p><strong>Associated with instance of enclosing class</strong> so to instantiate it first needs an instance of outer class (note <em>new</em> keyword place):</p>\n\n<pre><code>Outerclass.InnerClass innerObject = outerObject.new Innerclass();\n</code></pre></li>\n<li><p><strong>Cannot</strong> define any <strong>static members</strong> itself</p></li>\n<li><strong>Cannot</strong> have <strong>Class</strong> or <strong>Interface</strong> declaration</li>\n</ul>\n\n<h3>Static nested class</h3>\n\n<ul>\n<li><p><strong>Cannot access</strong> outer class <strong>instance</strong> methods or fields</p></li>\n<li><p><strong>Not associated with any instance of enclosing class</strong> So to instantiate it:</p>\n\n<pre><code>OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();\n</code></pre></li>\n</ul>\n\n<h3>Similarities</h3>\n\n<ul>\n<li>Both <strong>Inner classes</strong> can access even <strong>private fields and methods</strong> of <strong>outer class</strong></li>\n<li>Also the <strong>Outer class</strong> have access to <strong>private fields and methods</strong> of <strong>inner classes</strong></li>\n<li>Both classes can have private, protected or public access modifier</li>\n</ul>\n\n<h3>Why Use Nested Classes?</h3>\n\n<p>According to Oracle documentation there're several reasons (<a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html\" rel=\"noreferrer\">full documentation</a>):</p>\n\n<blockquote>\n <ul>\n <li><p><strong>It is a way of logically grouping classes that are only used in one place:</strong> If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such \"helper classes\" makes their package more streamlined.</p></li>\n <li><p><strong>It increases encapsulation:</strong> Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.</p></li>\n <li><p><strong>It can lead to more readable and maintainable code:</strong> Nesting small classes within top-level classes places the code closer to where it is used.</p></li>\n </ul>\n</blockquote>\n"
},
{
"answer_id": 39669941,
"author": "DigitalRoss",
"author_id": 140740,
"author_profile": "https://Stackoverflow.com/users/140740",
"pm_score": -1,
"selected": false,
"text": "<p>The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.</p>\n\n<p>When you have a nested class declaration that is <em>not</em> static, also known as an <em>inner class</em>, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.</p>\n\n<p>But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.</p>\n"
},
{
"answer_id": 40937372,
"author": "Pankti",
"author_id": 5095067,
"author_profile": "https://Stackoverflow.com/users/5095067",
"pm_score": 2,
"selected": false,
"text": "<p>When we declare static member class inside a class, it is known as top level nested class or a static nested class. It can be demonstrated as below : </p>\n\n<pre><code>class Test{\n private static int x = 1;\n static class A{\n private static int y = 2;\n public static int getZ(){\n return B.z+x;\n }\n }\n static class B{\n private static int z = 3;\n public static int getY(){\n return A.y;\n }\n }\n}\n\nclass TestDemo{\n public static void main(String[] args){\n Test t = new Test();\n System.out.println(Test.A.getZ());\n System.out.println(Test.B.getY());\n }\n}\n</code></pre>\n\n<p>When we declare non-static member class inside a class it is known as inner class. Inner class can be demonstrated as below : </p>\n\n<pre><code> class Test{\n private int i = 10;\n class A{\n private int i =20;\n void display(){\n int i = 30;\n System.out.println(i);\n System.out.println(this.i);\n System.out.println(Test.this.i);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 41453771,
"author": "Pritam Banerjee",
"author_id": 1475228,
"author_profile": "https://Stackoverflow.com/users/1475228",
"pm_score": 2,
"selected": false,
"text": "<p>The following is an example of <code>static nested class</code> and <code>inner class</code>:</p>\n\n<p><strong>OuterClass.java</strong></p>\n\n<pre><code>public class OuterClass {\n private String someVariable = \"Non Static\";\n\n private static String anotherStaticVariable = \"Static\"; \n\n OuterClass(){\n\n }\n\n //Nested classes are static\n static class StaticNestedClass{\n private static String privateStaticNestedClassVariable = \"Private Static Nested Class Variable\"; \n\n //can access private variables declared in the outer class\n public static void getPrivateVariableofOuterClass(){\n System.out.println(anotherStaticVariable);\n }\n }\n\n //non static\n class InnerClass{\n\n //can access private variables of outer class\n public String getPrivateNonStaticVariableOfOuterClass(){\n return someVariable;\n }\n }\n\n public static void accessStaticClass(){\n //can access any variable declared inside the Static Nested Class \n //even if it private\n String var = OuterClass.StaticNestedClass.privateStaticNestedClassVariable; \n System.out.println(var);\n }\n\n}\n</code></pre>\n\n<p><strong>OuterClassTest:</strong></p>\n\n<pre><code>public class OuterClassTest {\n public static void main(String[] args) {\n\n //access the Static Nested Class\n OuterClass.StaticNestedClass.getPrivateVariableofOuterClass();\n\n //test the private variable declared inside the static nested class\n OuterClass.accessStaticClass();\n /*\n * Inner Class Test\n * */\n\n //Declaration\n\n //first instantiate the outer class\n OuterClass outerClass = new OuterClass();\n\n //then instantiate the inner class\n OuterClass.InnerClass innerClassExample = outerClass. new InnerClass();\n\n //test the non static private variable\n System.out.println(innerClassExample.getPrivateNonStaticVariableOfOuterClass()); \n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 42949189,
"author": "roottraveller",
"author_id": 5167682,
"author_profile": "https://Stackoverflow.com/users/5167682",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Inner class</strong> and <strong>nested static class</strong> in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non static nested class are simply referred as Inner Class. </p>\n\n<p><strong>What is Inner Class in Java?</strong></p>\n\n<p>Any class which is not a top level or declared inside another class is known as nested class and out of those nested classes, class which are declared non static are known as Inner class in Java. there are three kinds of Inner class in Java:</p>\n\n<p>1) Local inner class - is declared inside a code block or method.<br>\n2) Anonymous inner class - is a class which doesn't have name to reference and initialized at same place where it gets created.<br>\n3) Member inner class - is declared as non static member of outer class.</p>\n\n<pre><code>public class InnerClassTest {\n public static void main(String args[]) { \n //creating local inner class inside method i.e. main() \n class Local {\n public void name() {\n System.out.println(\"Example of Local class in Java\");\n\n }\n } \n //creating instance of local inner class\n Local local = new Local();\n local.name(); //calling method from local inner class\n\n //Creating anonymous inner class in Java for implementing thread\n Thread anonymous = new Thread(){\n @Override\n public void run(){\n System.out.println(\"Anonymous class example in java\");\n }\n };\n anonymous.start();\n\n //example of creating instance of inner class\n InnerClassTest test = new InnerClassTest();\n InnerClassTest.Inner inner = test.new Inner();\n inner.name(); //calling method of inner class\n }\n\n //Creating Inner class in Java\n private class Inner{\n public void name(){\n System.out.println(\"Inner class example in java\");\n }\n }\n}\n</code></pre>\n\n<p><strong>What is nested static class in Java?</strong></p>\n\n<p>Nested static class is another class which is declared inside a class as member and made static. Nested static class is also declared as member of outer class and can be make private, public or protected like any other member. One of the main benefit of nested static class over inner class is that instance of nested static class is not attached to any enclosing instance of Outer class. <em>You also don't need any instance of Outer class to create instance of nested static class in Java</em>.</p>\n\n<p>1) It can access <em>static data members</em> of outer class including private.<br>\n2) Static nested class cannot access <em>non-static (instance) data member</em> or <em>method</em>.</p>\n\n<pre><code>public class NestedStaticExample {\n public static void main(String args[]){ \n StaticNested nested = new StaticNested();\n nested.name();\n } \n //static nested class in java\n private static class StaticNested{\n public void name(){\n System.out.println(\"static nested class example in java\");\n }\n }\n}\n</code></pre>\n\n<p>Ref: <a href=\"http://javarevisited.blogspot.in/2012/12/inner-class-and-nested-static-class-in-java-difference.html\" rel=\"noreferrer\">Inner class and nested Static Class in Java with Example</a></p>\n"
},
{
"answer_id": 46664397,
"author": "Ashish Sharma",
"author_id": 7503961,
"author_profile": "https://Stackoverflow.com/users/7503961",
"pm_score": -1,
"selected": false,
"text": "<p>I have illustrated various possible correct and error scenario which can occur in java code.</p>\n\n<pre><code> class Outter1 {\n\n String OutStr;\n\n Outter1(String str) {\n OutStr = str;\n }\n\n public void NonStaticMethod(String st) {\n\n String temp1 = \"ashish\";\n final String tempFinal1 = \"ashish\"; \n\n // below static attribute not permitted\n // static String tempStatic1 = \"static\"; \n\n // below static with final attribute not permitted \n // static final String tempStatic1 = \"ashish\"; \n\n // synchronized keyword is not permitted below \n class localInnerNonStatic1 { \n\n synchronized public void innerMethod(String str11) {\n str11 = temp1 +\" sharma\";\n System.out.println(\"innerMethod ===> \"+str11);\n }\n\n /* \n // static method with final not permitted\n public static void innerStaticMethod(String str11) { \n\n str11 = temp1 +\" india\";\n System.out.println(\"innerMethod ===> \"+str11);\n }*/\n }\n\n // static class not permitted below\n // static class localInnerStatic1 { } \n\n }\n\n public static void StaticMethod(String st) {\n\n String temp1 = \"ashish\";\n final String tempFinal1 = \"ashish\"; \n\n // static attribute not permitted below\n //static String tempStatic1 = \"static\"; \n\n // static with final attribute not permitted below\n // static final String tempStatic1 = \"ashish\"; \n\n class localInnerNonStatic1 {\n public void innerMethod(String str11) {\n str11 = temp1 +\" sharma\";\n System.out.println(\"innerMethod ===> \"+str11);\n }\n\n /*\n // static method with final not permitted\n public static void innerStaticMethod(String str11) { \n str11 = temp1 +\" india\";\n System.out.println(\"innerMethod ===> \"+str11);\n }*/\n }\n\n // static class not permitted below\n // static class localInnerStatic1 { } \n\n }\n\n // synchronized keyword is not permitted\n static class inner1 { \n\n static String temp1 = \"ashish\";\n String tempNonStatic = \"ashish\";\n // class localInner1 {\n\n public void innerMethod(String str11) {\n str11 = temp1 +\" sharma\";\n str11 = str11+ tempNonStatic +\" sharma\";\n System.out.println(\"innerMethod ===> \"+str11);\n }\n\n public static void innerStaticMethod(String str11) {\n // error in below step\n str11 = temp1 +\" india\"; \n //str11 = str11+ tempNonStatic +\" sharma\";\n System.out.println(\"innerMethod ===> \"+str11);\n }\n //}\n }\n\n //synchronized keyword is not permitted below\n class innerNonStatic1 { \n\n//This is important we have to keep final with static modifier in non\n// static innerclass below\n static final String temp1 = \"ashish\"; \n String tempNonStatic = \"ashish\";\n // class localInner1 {\n\n synchronized public void innerMethod(String str11) {\n tempNonStatic = tempNonStatic +\" ...\";\n str11 = temp1 +\" sharma\";\n str11 = str11+ tempNonStatic +\" sharma\";\n System.out.println(\"innerMethod ===> \"+str11);\n }\n\n /*\n // error in below step\n public static void innerStaticMethod(String str11) { \n // error in below step\n // str11 = tempNonStatic +\" india\"; \n str11 = temp1 +\" india\";\n System.out.println(\"innerMethod ===> \"+str11);\n }*/\n //}\n }\n }\n</code></pre>\n"
},
{
"answer_id": 53737273,
"author": "Mithun Debnath",
"author_id": 4046145,
"author_profile": "https://Stackoverflow.com/users/4046145",
"pm_score": 1,
"selected": false,
"text": "<p>The Java programming language allows you to define a class within another class. Such a class is called a nested class and is illustrated here:</p>\n\n<pre><code>class OuterClass {\n...\nclass NestedClass {\n ...\n }\n}\n</code></pre>\n\n<p>Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes.\nOne thing that we should keep in mind is Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes only have access to other members of the enclosing class if those are static. It can not access non static members of the outer class.\nAs with class methods and variables, a static nested class is associated with its outer class. \nFor example, to create an object for the static nested class, use this syntax:</p>\n\n<pre><code>OuterClass.StaticNestedClass nestedObject =\n new OuterClass.StaticNestedClass(); \n</code></pre>\n\n<p>To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:</p>\n\n<pre><code>OuterClass.InnerClass innerObject = new OuterClass().new InnerClass();\n</code></pre>\n\n<p>Why we use nested classes</p>\n\n<ol>\n<li>It is a way of logically grouping classes that are only used in one place.</li>\n<li>It increases encapsulation.</li>\n<li>It can lead to more readable and maintainable code.</li>\n</ol>\n\n<p>Source: <a href=\"https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html\" rel=\"nofollow noreferrer\">The Java™ Tutorials - Nested Classes</a></p>\n"
},
{
"answer_id": 55014075,
"author": "Leogao",
"author_id": 10312263,
"author_profile": "https://Stackoverflow.com/users/10312263",
"pm_score": 3,
"selected": false,
"text": "<p>I think that none of the above answers give the real example to you the difference between a nested class and a static nested class in term of application design. And the main difference between static nested class and inner class is the ability to access the outer class instance field. </p>\n\n<p>Let us take a look at the two following examples.</p>\n\n<p>Static nest class: An good example of using static nested classes is builder pattern (<a href=\"https://dzone.com/articles/design-patterns-the-builder-pattern\" rel=\"noreferrer\">https://dzone.com/articles/design-patterns-the-builder-pattern</a>).</p>\n\n<p>For BankAccount we use a static nested class, mainly because </p>\n\n<ol>\n<li><p>Static nest class instance could be created before the outer class.</p></li>\n<li><p>In the builder pattern, the builder is a helper class which is used to create the BankAccount.</p></li>\n<li>BankAccount.Builder is only associated with BankAccount. No other classes are related to BankAccount.Builder. so it is better to organize them together without using name convention.</li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class BankAccount {\n\n private long accountNumber;\n private String owner;\n ...\n\n public static class Builder {\n\n private long accountNumber;\n private String owner;\n ...\n\n static public Builder(long accountNumber) {\n this.accountNumber = accountNumber;\n }\n\n public Builder withOwner(String owner){\n this.owner = owner;\n return this; \n }\n\n ...\n public BankAccount build(){\n BankAccount account = new BankAccount(); \n account.accountNumber = this.accountNumber;\n account.owner = this.owner;\n ...\n return account;\n }\n }\n}\n\n</code></pre>\n\n<p>Inner class: A common use of inner classes is to define an event handler.\n<a href=\"https://docs.oracle.com/javase/tutorial/uiswing/events/generalrules.html\" rel=\"noreferrer\">https://docs.oracle.com/javase/tutorial/uiswing/events/generalrules.html</a></p>\n\n<p>For MyClass, we use the inner class, mainly because: </p>\n\n<ol>\n<li><p>Inner class MyAdapter need to access the outer class member.</p></li>\n<li><p>In the example, MyAdapter is only associated with MyClass. No other classes are related to MyAdapter. so it is better to organize them together without using a name convention</p></li>\n</ol>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MyClass extends Applet {\n ...\n someObject.addMouseListener(new MyAdapter());\n ...\n class MyAdapter extends MouseAdapter {\n public void mouseClicked(MouseEvent e) {\n ...// Event listener implementation goes here...\n ...// change some outer class instance property depend on the event\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59220181,
"author": "yoAlex5",
"author_id": 4770877,
"author_profile": "https://Stackoverflow.com/users/4770877",
"pm_score": 3,
"selected": false,
"text": "<p>A diagram</p>\n\n<p><a href=\"https://i.stack.imgur.com/4zgFn.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4zgFn.png\" alt=\"enter image description here\"></a></p>\n\n<p>The main difference between <code>static nested</code> and <code>non-static nested</code> classes is that <code>static nested</code> <strong>does not have</strong> an access to non-static outer class members</p>\n"
},
{
"answer_id": 67084223,
"author": "JCvanDamme",
"author_id": 4275167,
"author_profile": "https://Stackoverflow.com/users/4275167",
"pm_score": 0,
"selected": false,
"text": "<p>Another use case for nested classes, in addition to those that already have been mentioned, is when the nested class has methods that should only be accessible from the outer class. This is possible because the outer class has access to the private constructors, fields and methods of the nested class.</p>\n<p>In the example below, the <code>Bank</code> can issue a <code>Bank.CreditCard</code>, which has a private constructor, and can change a credit card's limit according to the current bank policy using the private <code>setLimit(...)</code> instance method of <code>Bank.CreditCard</code>. (A direct field access to the instance variable <code>limit</code> would also work in this case). From any other class only the public methods of <code>Bank.CreditCard</code> are accessible.</p>\n<pre><code>public class Bank {\n\n // maximum limit as per current bank policy\n // is subject to change\n private int maxLimit = 7000;\n\n // ------- PUBLIC METHODS ---------\n\n public CreditCard issueCard(\n final String firstName,\n final String lastName\n ) {\n final String number = this.generateNumber();\n final int expiryDate = this.generateExpiryDate();\n final int CVV = this.generateCVV();\n return new CreditCard(firstName, lastName, number, expiryDate, CVV);\n }\n\n\n public boolean setLimit(\n final CreditCard creditCard,\n final int limit\n ) {\n if (limit <= this.maxLimit) { // check against current bank policy limit\n creditCard.setLimit(limit); // access private method Bank.CreditCard.setLimit(int)\n return true;\n }\n return false;\n }\n\n // ------- PRIVATE METHODS ---------\n\n private String generateNumber() {\n return "1234-5678-9101-1123"; // the numbers should be unique for each card\n }\n\n\n private int generateExpiryDate() {\n return 202405; // date is YYYY=2024, MM=05\n }\n\n\n private int generateCVV() {\n return 123; // is in real-life less predictable\n }\n\n\n // ------- PUBLIC STATIC NESTED CLASS ---------\n\n public static final class CreditCard {\n private final String firstName;\n private final String lastName;\n private final String number;\n private final int expiryDate;\n private final int CVV;\n\n private int balance;\n private int limit = 100; // default limit\n\n // the constructor is final but is accessible from outer class\n private CreditCard(\n final String firstName,\n final String lastName,\n final String number,\n final int expiryDate,\n final int CVV\n ) {\n this.firstName = firstName;\n this.lastName = lastName;\n this.number = number;\n this.expiryDate = expiryDate;\n this.CVV = CVV;\n }\n\n // ------- PUBLIC METHODS ---------\n\n public String getFirstName() {\n return this.firstName;\n }\n\n public String getLastName() {\n return this.lastName;\n }\n\n public String getNumber() {\n return this.number;\n }\n\n public int getExpiryDate() {\n return this.expiryDate;\n }\n\n // returns true if financial transaction is successful\n // otherwise false\n public boolean charge(final int amount) {\n final int newBalance = this.balance - amount;\n if (newBalance < -this.limit) {\n return false;\n }\n this.balance = newBalance;\n return true;\n }\n\n // ------- PRIVATE METHODS ---------\n\n private int getCVV() {\n return this.CVV;\n }\n\n private int getBalance() {\n return this.balance;\n }\n\n private void setBalance(final int balance) {\n this.balance = balance;\n }\n\n private int getLimit() {\n return limit;\n }\n\n private void setLimit(final int limit) {\n this.limit = limit;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 71098085,
"author": "Jonathan Cole",
"author_id": 2592155,
"author_profile": "https://Stackoverflow.com/users/2592155",
"pm_score": 0,
"selected": false,
"text": "<p>Static nested classes access PRIVATE class-level static variables of the class they are defined in. That can be huge from an architectural standpoint (i.e. Service Locator pattern employing nested static helper classes in Services), and may help OP see why they exist along with inner classes.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70324",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11193/"
]
| What is the main difference between an inner class and a static nested class in Java? Does design / implementation play a role in choosing one of these? | From the [Java Tutorial](http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html):
>
> Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.
>
>
>
Static nested classes are accessed using the enclosing class name:
```
OuterClass.StaticNestedClass
```
For example, to create an object for the static nested class, use this syntax:
```
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
```
Objects that are instances of an inner class exist within an instance of the outer class. Consider the following classes:
```
class OuterClass {
...
class InnerClass {
...
}
}
```
An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance.
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
```
OuterClass outerObject = new OuterClass()
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
```
see: [Java Tutorial - Nested Classes](http://download.oracle.com/javase/tutorial/java/javaOO/nested.html)
For completeness note that there is also such a thing as an [inner class *without* an enclosing instance](https://stackoverflow.com/questions/20468856/is-it-true-that-every-inner-class-requires-an-enclosing-instance):
```
class A {
int t() { return 1; }
static A a = new A() { int t() { return 2; } };
}
```
Here, `new A() { ... }` is an *inner class defined in a static context* and does not have an enclosing instance. |
70,366 | <p>When trying to commit to a cvs branch after adding a new file I get this error</p>
<pre><code>Assertion failed: key != NULL, file hash.c, line 317
</code></pre>
<p>Any idea how to fix it so I can check my code in?<br>
Both server and client are Linux and there are pre-commits involved.</p>
| [
{
"answer_id": 70441,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps there is some kind of pre-commit check on your repository, see <a href=\"http://ximbiot.com/cvs/manual/cvs-1.12.13/cvs_18.html#SEC188\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 70576,
"author": "Bert F",
"author_id": 11296,
"author_profile": "https://Stackoverflow.com/users/11296",
"pm_score": 1,
"selected": false,
"text": "<p>Are you on Windows and did you rename a file to the same name with different case (e.g. MAKEFILE vs Makefile vs makefile)? CVS used to have a problem with this (and maybe still does?):</p>\n\n<p>OSDir/mailarchive - <a href=\"http://osdir.com/ml/version-control.cvs.bugs/2003-01/msg00092.html\" rel=\"nofollow noreferrer\">Subject: Re: hash.c.312: findnode:</a></p>\n\n<blockquote>\n <p>Manu writes:</p>\n \n <blockquote>\n <p>I try to rename \"makefile\" to \"Makefile\" in my cvs tree, then:</p>\n </blockquote>\n</blockquote>\n\n<pre><code>cvs: hash.c:312: findnode: Assertion `key != ((void *)0)' failed.\ncvs [server aborted]: received abort signal\n</code></pre>\n\n<blockquote>\n <p>CVS was never designed to cope with case insensitive file systems. It\n has been patched to the point where it mostly works, but there are still\n some places where it doesn't. This is one of them.</p>\n</blockquote>\n\n<p>You might want to read the rest of the messages in the thread as well.</p>\n"
},
{
"answer_id": 70725,
"author": "sleep-er",
"author_id": 7873,
"author_profile": "https://Stackoverflow.com/users/7873",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure what the issue was but I solved it by going onto the server and deleting the file Attic/newfile.v in the repository and adding it again.</p>\n"
},
{
"answer_id": 70884,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>sleep-er writes:</p>\n \n <blockquote>\n <p>Not sure what the issue was but I solved it by going onto the server and deleting the file Attic/newfile.v in the repository and adding it again.</p>\n </blockquote>\n</blockquote>\n\n<p>The \"Attic\" is the place where deleted files go in CVS. At some point in the past, someone checked in newfile.v, and at some later point it was deleted, hence moved to the Attic.</p>\n\n<p>By deleting the ,v file from the repository you corrupted older commits that included the file \"newfile\". Do not do this.</p>\n\n<p>The correct way is to restore the deleted file, then replace its content by the new file.</p>\n\n<p>According to <a href=\"http://www.cs.indiana.edu/~machrist/notes/cvs.html\" rel=\"nofollow noreferrer\">http://www.cs.indiana.edu/~machrist/notes/cvs.html</a></p>\n\n<blockquote>\n <p>To recover a file that has been removed from the repository, you essentially need to update that file to its last revision number (before it was actually deleted). For example:</p>\n \n <p>cvs update -r 1.7 deleted_file</p>\n \n <p>This will recover deleted_file in your working repository. To find deleted files and their last revision number, issue cvs log at the command prompt.</p>\n</blockquote>\n\n<p>Edited in reply to comment to explain what the ,v file in the Attic means.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70366",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7873/"
]
| When trying to commit to a cvs branch after adding a new file I get this error
```
Assertion failed: key != NULL, file hash.c, line 317
```
Any idea how to fix it so I can check my code in?
Both server and client are Linux and there are pre-commits involved. | >
> sleep-er writes:
>
>
>
> >
> > Not sure what the issue was but I solved it by going onto the server and deleting the file Attic/newfile.v in the repository and adding it again.
> >
> >
> >
>
>
>
The "Attic" is the place where deleted files go in CVS. At some point in the past, someone checked in newfile.v, and at some later point it was deleted, hence moved to the Attic.
By deleting the ,v file from the repository you corrupted older commits that included the file "newfile". Do not do this.
The correct way is to restore the deleted file, then replace its content by the new file.
According to <http://www.cs.indiana.edu/~machrist/notes/cvs.html>
>
> To recover a file that has been removed from the repository, you essentially need to update that file to its last revision number (before it was actually deleted). For example:
>
>
> cvs update -r 1.7 deleted\_file
>
>
> This will recover deleted\_file in your working repository. To find deleted files and their last revision number, issue cvs log at the command prompt.
>
>
>
Edited in reply to comment to explain what the ,v file in the Attic means. |
70,371 | <p>I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing?</p>
<p>The routing code in global.asax:</p>
<pre><code>public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Pages", // Route name
"Admin/Pages/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Pages", action = "Index", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Home", action = "Index", id = "" }
);
}
</code></pre>
<p>Thanks!</p>
| [
{
"answer_id": 70396,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 4,
"selected": true,
"text": "<p>I'd suggest adding an explicit route for /Pages/ at the beginning.</p>\n\n<p>The problem is that it's being handled by the Default route and deriving:</p>\n\n<p>controller = \"Pages\"\naction = \"Index\"\nid = \"\"</p>\n\n<p>which are exactly the same as the parameters for your Admin route.</p>\n"
},
{
"answer_id": 70481,
"author": "Garry Shutler",
"author_id": 6369,
"author_profile": "https://Stackoverflow.com/users/6369",
"pm_score": 2,
"selected": false,
"text": "<p>You could add a constraint to the default rule so that the {Controller} tag cannot be \"Pages\".</p>\n"
},
{
"answer_id": 80676,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 0,
"selected": false,
"text": "<p>You have in you first route {action} token/parameter which gets in conflict with setting of default action. Try changing parameter name in your route, or remove default action name.</p>\n"
},
{
"answer_id": 93920,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 3,
"selected": false,
"text": "<p>For routing issues like this, you should try out my <a href=\"http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx\" rel=\"noreferrer\">Route Debugger</a> assembly (use only in testing). It can help figure out these types of issues.</p>\n\n<p>P.S. If you're trying to secure the Pages controller, make sure to use the [Authorize] attribute. Don't just rely on URL authorization.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11334/"
]
| I'm trying out ASP.NET MVC routing and have of course stumbled across a problem. I have a section, /Admin/Pages/, and this is also accessible through /Pages/, which it shouldn't. What could I be missing?
The routing code in global.asax:
```
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Pages", // Route name
"Admin/Pages/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Pages", action = "Index", id = "" }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
// Parameter defaults
new { controller = "Home", action = "Index", id = "" }
);
}
```
Thanks! | I'd suggest adding an explicit route for /Pages/ at the beginning.
The problem is that it's being handled by the Default route and deriving:
controller = "Pages"
action = "Index"
id = ""
which are exactly the same as the parameters for your Admin route. |
70,386 | <p>There are three places where menus show up in the new MFC functionality (Feature Pack):</p>
<ul>
<li>In menu bars (CMFCMenuBar)</li>
<li>In popup menus (CMFCPopupMenu)</li>
<li>In the 'dropdown menu' version of CMFCButton</li>
</ul>
<p>I want to put icons (high-color and with transparancy) in the menus in all of them. I have found CFrameWndEx::OnDrawMenuImage() which I can use to custom draw the icons in front of the menu bar items. It's not very convenient, having to implement icon drawing in 2008, but it works. For the others I haven't found a solution yet. Is there an automagic way to set icons for menus?</p>
| [
{
"answer_id": 72654,
"author": "Nevermind",
"author_id": 12366,
"author_profile": "https://Stackoverflow.com/users/12366",
"pm_score": 2,
"selected": false,
"text": "<p>I believe (but I may be wrong) that these classes are the same as the BCGToolbar classes that were included in MFC when Microsoft bought BCG. If so, you can create a toolbar with and use the same ID on a toolbar button as in the menu items you want to create icons for, and they should appear automatically. Of course, you don't have to actually display the toolbars.</p>\n"
},
{
"answer_id": 92995,
"author": "Nevermind",
"author_id": 12366,
"author_profile": "https://Stackoverflow.com/users/12366",
"pm_score": 2,
"selected": false,
"text": "<p>In BCGToolbar, it's enough to create a toolbar in the resources & load it (but not display the window), but the toolbar button must have the same ID as the menu item you want to link it to.</p>\n"
},
{
"answer_id": 783923,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>One thing that can catch a person by surprise is that for customizable (ie, non-locked) toolbars, the first toolbar you make, the framework splits up and turns into some sort of palette bitmap of all icons in the program. If you try to add more toolbars later (or different toolbars) that have bitmaps (or pngs) with a different color depth than that first one, they seem to fail because it can't add them to the same palette.</p>\n"
},
{
"answer_id": 1213583,
"author": "foraidt",
"author_id": 27596,
"author_profile": "https://Stackoverflow.com/users/27596",
"pm_score": 3,
"selected": true,
"text": "<p>This is how I got it to work:</p>\n\n<h3>First</h3>\n\n<p>, as the others said, create an invisible toolbar next to your main toolbar (I'm using the usual names based on AppWizard's names):</p>\n\n<pre><code>MainFrm.h:\nclass CMainFrame\n{\n //... \n CMFCToolBar m_wndToolBar;\n CMFCToolBar m_wndInvisibleToolBar;\n //...\n};\n\nMainFrm.cpp:\nint CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)\n{\n //...\n\n // Normal, visible toolbar\n if(m_wndToolBar.Create(this,\n TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC))\n {\n VERIFY( m_wndToolBar.LoadToolBar(\n theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME) );\n\n // Only the docking makes the toolbar visible\n m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);\n DockPane(&m_wndToolBar);\n }\n\n // Invisible toolbar; simply calling Create(this) seems to be enough\n if(m_wndInvisibleToolBar.Create(this))\n {\n // Just load, no docking and stuff\n VERIFY( m_wndInvisibleToolBar.LoadToolBar(IDR_OTHERTOOLBAR) );\n }\n}\n</code></pre>\n\n<h3>Second: The images and toolbar resources</h3>\n\n<p><code>IDR_MAINFRAME</code> and <code>IDR_MAINFRAME_256</code> were generated by AppWizard. The former is the ugly 16 color version and the latter is the interesting high color version.<br>\nDespite its name, if I remember correctly, even the AppWizard-generated image has 24bit color depth. The cool thing: Just replace it with a 32bit image and that'll work, too. </p>\n\n<p>There is the invisible toolbar <code>IDR_OTHERTOOLBAR</code>: I created a toolbar with the resource editor. Just some dummy icons and the command IDs. VS then generated a bitmap which I replaced with my high color version. Done!</p>\n\n<h3>Note</h3>\n\n<p>Don't open the toolbars with the resource editor: It may have to convert it to 4bit before it can do anything with it. And even <em>if</em> you let it do that (because, behind Visual Studio's back, wou're going to replace the result with the high color image again, ha!), I found that it (sometimes?) simply cannot edit the toolbar. Very strange.<br>\nIn that case I advise to directly edit the .rc file.</p>\n"
},
{
"answer_id": 1239950,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Try using this function:</p>\n\n<pre><code>CMFCToolBar::AddToolBarForImageCollection(UINT uiResID,\n UINT uiBmpResID=0,\n UINT uiColdResID=0,\n UINT uiMenuResID=0,\n UINT uiDisabledResID=0,\n UINT uiMenuDisabledResID=0);\n</code></pre>\n\n<p>So e.g.: </p>\n\n<pre><code>CMFCToolBar::AddToolBarForImageCollection(IDR_TOOLBAROWNBITMAP_256);\n</code></pre>\n\n<p>Worked very well for me.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11449/"
]
| There are three places where menus show up in the new MFC functionality (Feature Pack):
* In menu bars (CMFCMenuBar)
* In popup menus (CMFCPopupMenu)
* In the 'dropdown menu' version of CMFCButton
I want to put icons (high-color and with transparancy) in the menus in all of them. I have found CFrameWndEx::OnDrawMenuImage() which I can use to custom draw the icons in front of the menu bar items. It's not very convenient, having to implement icon drawing in 2008, but it works. For the others I haven't found a solution yet. Is there an automagic way to set icons for menus? | This is how I got it to work:
### First
, as the others said, create an invisible toolbar next to your main toolbar (I'm using the usual names based on AppWizard's names):
```
MainFrm.h:
class CMainFrame
{
//...
CMFCToolBar m_wndToolBar;
CMFCToolBar m_wndInvisibleToolBar;
//...
};
MainFrm.cpp:
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
//...
// Normal, visible toolbar
if(m_wndToolBar.Create(this,
TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC))
{
VERIFY( m_wndToolBar.LoadToolBar(
theApp.m_bHiColorIcons ? IDR_MAINFRAME_256 : IDR_MAINFRAME) );
// Only the docking makes the toolbar visible
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
DockPane(&m_wndToolBar);
}
// Invisible toolbar; simply calling Create(this) seems to be enough
if(m_wndInvisibleToolBar.Create(this))
{
// Just load, no docking and stuff
VERIFY( m_wndInvisibleToolBar.LoadToolBar(IDR_OTHERTOOLBAR) );
}
}
```
### Second: The images and toolbar resources
`IDR_MAINFRAME` and `IDR_MAINFRAME_256` were generated by AppWizard. The former is the ugly 16 color version and the latter is the interesting high color version.
Despite its name, if I remember correctly, even the AppWizard-generated image has 24bit color depth. The cool thing: Just replace it with a 32bit image and that'll work, too.
There is the invisible toolbar `IDR_OTHERTOOLBAR`: I created a toolbar with the resource editor. Just some dummy icons and the command IDs. VS then generated a bitmap which I replaced with my high color version. Done!
### Note
Don't open the toolbars with the resource editor: It may have to convert it to 4bit before it can do anything with it. And even *if* you let it do that (because, behind Visual Studio's back, wou're going to replace the result with the high color image again, ha!), I found that it (sometimes?) simply cannot edit the toolbar. Very strange.
In that case I advise to directly edit the .rc file. |
70,389 | <p>I have apache 2.2 and tomcat 5.5 running on a Windows XP machine.</p>
<p>Which tomcat/apache connector is the easiest to set up and is well documented? </p>
| [
{
"answer_id": 70432,
"author": "Chris Broadfoot",
"author_id": 3947,
"author_profile": "https://Stackoverflow.com/users/3947",
"pm_score": 0,
"selected": false,
"text": "<p><code>mod_jk</code>, or simply just use <code>mod_proxy</code> even though it's not really a Tomcat connector.</p>\n"
},
{
"answer_id": 70553,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 4,
"selected": true,
"text": "<p><code><a href=\"http://httpd.apache.org/docs/2.2/mod/mod_proxy.html\" rel=\"noreferrer\">mod_proxy_ajp</a></code> would be the easiest to use if you are using Apache 2.2. It is part of the Apache distribution so you don't need to install any additional software.</p>\n\n<p>In your <code>httpd.conf</code> you need to make sure that <code>mod_proxy</code> and <code>mod_proxy_ajp</code> are loaded:</p>\n\n<pre>\nLoadModule proxy_module modules/mod_proxy.so\nLoadModule proxy_ajp_module modules/mod_proxy_ajp.so\n</pre>\n\n<p>Then you can use the <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass\" rel=\"noreferrer\">ProxyPass</a> and <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypassreverse\" rel=\"noreferrer\">ProxyPassReverse</a> directives as follows:</p>\n\n<pre>\nProxyPass /portal ajp://localhost:8009/portal\nProxyPassReverse /portal ajp://localhost:8009/portal\n</pre>\n\n<p>You should consult the Apache 2.2 documentation for a full catalog of the directives available.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8633/"
]
| I have apache 2.2 and tomcat 5.5 running on a Windows XP machine.
Which tomcat/apache connector is the easiest to set up and is well documented? | `[mod\_proxy\_ajp](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html)` would be the easiest to use if you are using Apache 2.2. It is part of the Apache distribution so you don't need to install any additional software.
In your `httpd.conf` you need to make sure that `mod_proxy` and `mod_proxy_ajp` are loaded:
```
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
```
Then you can use the [ProxyPass](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypass) and [ProxyPassReverse](http://httpd.apache.org/docs/2.2/mod/mod_proxy.html#proxypassreverse) directives as follows:
```
ProxyPass /portal ajp://localhost:8009/portal
ProxyPassReverse /portal ajp://localhost:8009/portal
```
You should consult the Apache 2.2 documentation for a full catalog of the directives available. |
70,397 | <p>So I'm working on a Rails app to get the feeling for the whole thing. I've got a <code>Product</code> model that's a standard ActiveRecord model. However, I also want to get some additional product info from Amazon ECS. So my complete model gets some of its info from the database and some from the web service. My question is, should I:</p>
<ol>
<li><p>Make two models a Product and a ProductAWS, and then tie them together at the controller level.</p></li>
<li><p>Have the Product ActiveRecord model contain a ProductAWS object that does all the AWS stuff?</p></li>
<li><p>Just add all the AWS functionality to my Product model.</p></li>
<li><p>???</p></li>
</ol>
| [
{
"answer_id": 70457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the <code>composed_of</code> relationship in ActiveRecord. You make a regular class with all the attributes that you manage through AWS and specify that your Product-class is composed_of this class. ActiveRecord will handle the delegation of the mapped attributes to and from this class.</p>\n\n<p>See <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Aggregations/ClassMethods.html#M001265\" rel=\"nofollow noreferrer\">the documentation of composed_of</a></p>\n"
},
{
"answer_id": 70499,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<p>@Menno</p>\n\n<p>What about using <a href=\"http://wiki.rubyonrails.org/rails/pages/ActiveResource\" rel=\"nofollow noreferrer\">ActiveResource</a> for the AWS-attributes class?</p>\n"
},
{
"answer_id": 76143,
"author": "Pete",
"author_id": 13472,
"author_profile": "https://Stackoverflow.com/users/13472",
"pm_score": 2,
"selected": true,
"text": "<p>As with most things: it depends. Each of your ideas have merit. If it were me, I'd start out this way: </p>\n\n<pre><code> class Product < ActiveRecord::Base\n has_one :aws_item\n end \n class AWSItem \n belongs_to :product\n end\n</code></pre>\n\n<p>The key questions you want to ask yourself are: </p>\n\n<p><strong>Are you only going to be offering AWS ECS items, or will you have other products?</strong> If you'll have products that have nothing to do with Amazon, don't care about ASIN, etc, then a has_one could be the way to go. Or, even better, a polymorphic relationship to a :vendable interface so you can later plug in different extension types. </p>\n\n<p><strong>Is it just behavior that is different, or is the data going to be largely different too?</strong> Because you might want to consider: </p>\n\n<blockquote>\n<pre><code>class Product < ActiveRecord::Base\nend \nclass AWSItem < Product\n def do_amazon_stuff\n ... \n end\nend\n</code></pre>\n</blockquote>\n\n<p><strong>How do you want the system to perform when Amazon ECS isn't available?</strong> Should it throw exceptions? Or should you rely on a local cached version of the catalog?</p>\n\n<blockquote>\n<pre><code>class Product < ActiveRecord::Base\n\nend\n\nclass ItemFetcher < BackgrounDRb::Rails\n def do_work\n # .... Make a cached copy of your ECS catalog here. \n # Copy the Amazon stuff into your local model\n end\nend\n</code></pre>\n</blockquote>\n\n<p>Walk through these questions slowly and the answer will become clearer. If it doesn't, start prototyping it out. Good luck!</p>\n"
},
{
"answer_id": 77984,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you are retrieving data from two completely different sources (ActiveRecord on one hand and the Internet on the other), there are many benefits to keeping these as separate models. As the above poster wrote, Product has_one (or has_many) :aws_item.</p>\n"
}
]
| 2008/09/16 | [
"https://Stackoverflow.com/questions/70397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11284/"
]
| So I'm working on a Rails app to get the feeling for the whole thing. I've got a `Product` model that's a standard ActiveRecord model. However, I also want to get some additional product info from Amazon ECS. So my complete model gets some of its info from the database and some from the web service. My question is, should I:
1. Make two models a Product and a ProductAWS, and then tie them together at the controller level.
2. Have the Product ActiveRecord model contain a ProductAWS object that does all the AWS stuff?
3. Just add all the AWS functionality to my Product model.
4. ??? | As with most things: it depends. Each of your ideas have merit. If it were me, I'd start out this way:
```
class Product < ActiveRecord::Base
has_one :aws_item
end
class AWSItem
belongs_to :product
end
```
The key questions you want to ask yourself are:
**Are you only going to be offering AWS ECS items, or will you have other products?** If you'll have products that have nothing to do with Amazon, don't care about ASIN, etc, then a has\_one could be the way to go. Or, even better, a polymorphic relationship to a :vendable interface so you can later plug in different extension types.
**Is it just behavior that is different, or is the data going to be largely different too?** Because you might want to consider:
>
>
> ```
> class Product < ActiveRecord::Base
> end
> class AWSItem < Product
> def do_amazon_stuff
> ...
> end
> end
>
> ```
>
>
**How do you want the system to perform when Amazon ECS isn't available?** Should it throw exceptions? Or should you rely on a local cached version of the catalog?
>
>
> ```
> class Product < ActiveRecord::Base
>
> end
>
> class ItemFetcher < BackgrounDRb::Rails
> def do_work
> # .... Make a cached copy of your ECS catalog here.
> # Copy the Amazon stuff into your local model
> end
> end
>
> ```
>
>
Walk through these questions slowly and the answer will become clearer. If it doesn't, start prototyping it out. Good luck! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.