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
|
---|---|---|---|---|---|---|
257,658 |
<p>I've automated my Ubuntu installation - I've got Python code that runs automatically (after a clean install, but before the first user login - it's in a temporary /etc/init.d/ script) that sets up everything from Apache & its configuration to my personal Gnome preferences. It's the latter that's giving me trouble.</p>
<p>This worked fine in Ubuntu 8.04 (Hardy), but when I use this with 8.10 (Intrepid), the first time I try to access gconf, I get this exception:</p>
<p>Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See <a href="http://www.gnome.org/projects/gconf/" rel="nofollow noreferrer">http://www.gnome.org/projects/gconf/</a> for information. (Details - 1: <strong>Not running within active session</strong>)</p>
<p>Yes, right, there's no Gnome session when this is running, because the user hasn't logged in yet - however, this worked before; this appears to be new with Intrepid's Gnome (2.24?).</p>
<p>Short of modifying the gconf's XML files directly, is there a way to make some sort of proxy Gnome session? Or, any other suggestions?</p>
<p>(More details: this is python code that runs as root, but setuid's & setgid's to be me before setting my preferences using the "gconf" module from the python-gconf package.)</p>
|
[
{
"answer_id": 257833,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 1,
"selected": false,
"text": "<p>Well, I think I understand the question. Looks like your script just needs to start the dbus daemon, or make sure its started. I believe \"session\" here refers to a dbus session. <a href=\"http://mail.gnome.org/archives/svn-commits-list/2008-May/msg01997.html\" rel=\"nofollow noreferrer\">(here is some evidence)</a>, not a Gnome session. Dbus and gconf both run fine without Gnome.</p>\n\n<p>Either way, faking an \"active session\" sounds like a pretty bad idea. It would only look for it if it needed it.</p>\n\n<p>Perhaps we could see the script in a pastebin? I should have really seen it before making any comment.</p>\n"
},
{
"answer_id": 260731,
"author": "Jeremy Visser",
"author_id": 10839,
"author_profile": "https://Stackoverflow.com/users/10839",
"pm_score": 3,
"selected": false,
"text": "<p>I can reproduce this by installing GConf 2.24 on my machine. GConf 2.22 works fine, but 2.24 breaks it.</p>\n\n<p>GConf is failing to launch because D-Bus is not running. Manually spawning D-Bus and the GConf daemon makes this work again.</p>\n\n<p>I tried to spawn the D-Bus session bus by doing the following:</p>\n\n<pre><code>import dbus\ndummy_bus = dbus.SessionBus()\n</code></pre>\n\n<p>...but got this:</p>\n\n<pre><code>dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: dbus-launch failed to autolaunch D-Bus session: Autolaunch error: X11 initialization failed.\n</code></pre>\n\n<p>Weird. Looks like it doesn't like to come up if X isn't running. To work around that, start dbus-launch manually (IIRC use the <a href=\"http://www.python.org/doc/2.5.2/lib/os-process.html\" rel=\"noreferrer\">os.system()</a> call):</p>\n\n<pre><code>$ dbus-launch \nDBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-eAmT3q94u0,guid=c250f62d3c4739dcc9a12d48490fc268\nDBUS_SESSION_BUS_PID=15836\n</code></pre>\n\n<p>You'll need to parse the output somehow and inject them into environment variables (you'll probably want to use <a href=\"http://www.python.org/doc/2.5.2/lib/os-procinfo.html\" rel=\"noreferrer\">os.putenv</a>). For my testing, I just used the shell, and set the environment vars manually with <code>export DBUS_SESSION_BUS_ADDRESS=blahblah...</code>, etc.</p>\n\n<p>Next, you need to launch <code>gconftool-2 --spawn</code> with those environment variables you received from <code>dbus-launch</code>. This will launch the GConf daemon. If the D-Bus environment vars are not set, the daemon will not launch.</p>\n\n<p>Then, run your GConf code. Provided you set the D-Bus session bus environment variables for your own script, you will now be able to communicate with the GConf daemon.</p>\n\n<p>I know it's complicated.</p>\n\n<p><code>gconftool-2</code> provides a <code>--direct</code> option that enables you to set GConf variables without needing to communicate with the server, but I haven't been able to find an equivalent option for the Python bindings (short of outputting XML manually).</p>\n\n<p><em>Edit:</em> For future reference, if anybody wants to run <code>dbus-launch</code> from within a normal <code>bash</code> script (as opposed to a Python script, as this thread is discussing), it is quite easy to retrieve the session bus address for use within the script:</p>\n\n<pre><code>#!/bin/bash\n\neval `dbus-launch --sh-syntax`\n\nexport DBUS_SESSION_BUS_ADDRESS\nexport DBUS_SESSION_BUS_PID\n\ndo_other_stuff_here\n</code></pre>\n"
},
{
"answer_id": 261180,
"author": "Bryan Stearns",
"author_id": 1452,
"author_profile": "https://Stackoverflow.com/users/1452",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks, Ali & Jeremy - both your answers were a big help. I'm still working on this (though I've stopped for the evening).</p>\n\n<p>First, I took the hint from Ali and was trying part of Jeremy's suggestion: I was using dbus-launch to run \"gconftool-2 --spawn\". It didn't work for me; I now understand why (thx, Jeremy) -- I was trying to use gconf from within the same python program that was launching dbus & gconftool, but its environment didn't have the environment variables - duh.</p>\n\n<p>I set that strategy aside when I noticed gconftool-2's --direct option; internally, gconftool-2 is using API that isn't exposed by the gconf python bindings. So, I modified python-gconf to expose the extra method, and once that builds (I had some unrelated problems getting this to work), we'll see if that fixes things - if it doesn't (and maybe if it does, because building those bindings seems to build all of gnome!), I'll find a better way to manage the environment variables in that first strategy.</p>\n\n<p>(I'll add another answer here tomorrow either way)</p>\n\n<p>And it's the next day: I ran into a little trouble with my modified python-gconf, which inspired me to try Jeremy's simpler idea, which worked fine - before doing the first gconf operation, I simply ran \"dbus-launch\", parsed the resulting name-value pairs, and added them directly to python's environment. Having done that, I ran \"gconftool-2 --spawn\". Problem solved.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1452/"
] |
I've automated my Ubuntu installation - I've got Python code that runs automatically (after a clean install, but before the first user login - it's in a temporary /etc/init.d/ script) that sets up everything from Apache & its configuration to my personal Gnome preferences. It's the latter that's giving me trouble.
This worked fine in Ubuntu 8.04 (Hardy), but when I use this with 8.10 (Intrepid), the first time I try to access gconf, I get this exception:
Failed to contact configuration server; some possible causes are that you need to enable TCP/IP networking for ORBit, or you have stale NFS locks due to a system crash. See <http://www.gnome.org/projects/gconf/> for information. (Details - 1: **Not running within active session**)
Yes, right, there's no Gnome session when this is running, because the user hasn't logged in yet - however, this worked before; this appears to be new with Intrepid's Gnome (2.24?).
Short of modifying the gconf's XML files directly, is there a way to make some sort of proxy Gnome session? Or, any other suggestions?
(More details: this is python code that runs as root, but setuid's & setgid's to be me before setting my preferences using the "gconf" module from the python-gconf package.)
|
I can reproduce this by installing GConf 2.24 on my machine. GConf 2.22 works fine, but 2.24 breaks it.
GConf is failing to launch because D-Bus is not running. Manually spawning D-Bus and the GConf daemon makes this work again.
I tried to spawn the D-Bus session bus by doing the following:
```
import dbus
dummy_bus = dbus.SessionBus()
```
...but got this:
```
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.Spawn.ExecFailed: dbus-launch failed to autolaunch D-Bus session: Autolaunch error: X11 initialization failed.
```
Weird. Looks like it doesn't like to come up if X isn't running. To work around that, start dbus-launch manually (IIRC use the [os.system()](http://www.python.org/doc/2.5.2/lib/os-process.html) call):
```
$ dbus-launch
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-eAmT3q94u0,guid=c250f62d3c4739dcc9a12d48490fc268
DBUS_SESSION_BUS_PID=15836
```
You'll need to parse the output somehow and inject them into environment variables (you'll probably want to use [os.putenv](http://www.python.org/doc/2.5.2/lib/os-procinfo.html)). For my testing, I just used the shell, and set the environment vars manually with `export DBUS_SESSION_BUS_ADDRESS=blahblah...`, etc.
Next, you need to launch `gconftool-2 --spawn` with those environment variables you received from `dbus-launch`. This will launch the GConf daemon. If the D-Bus environment vars are not set, the daemon will not launch.
Then, run your GConf code. Provided you set the D-Bus session bus environment variables for your own script, you will now be able to communicate with the GConf daemon.
I know it's complicated.
`gconftool-2` provides a `--direct` option that enables you to set GConf variables without needing to communicate with the server, but I haven't been able to find an equivalent option for the Python bindings (short of outputting XML manually).
*Edit:* For future reference, if anybody wants to run `dbus-launch` from within a normal `bash` script (as opposed to a Python script, as this thread is discussing), it is quite easy to retrieve the session bus address for use within the script:
```
#!/bin/bash
eval `dbus-launch --sh-syntax`
export DBUS_SESSION_BUS_ADDRESS
export DBUS_SESSION_BUS_PID
do_other_stuff_here
```
|
257,659 |
<p>I am wondering how to get a process run at the command line to use less processing power. The problem I'm having is the the process is basically taking over the CPU and taking MySQL and the rest of the server with it. Everything is becoming very slow.</p>
<p>I have used <code>nice</code> before but haven't had much luck with it. If it is the answer, how would you use it?</p>
<p>I have also thought of putting in <code>sleep</code> commands, but it'll still be using up memory so it's not the best option.</p>
<p>Is there another solution?</p>
<p>It doesn't matter to me how long it runs for, within reason.</p>
<p>If it makes a difference, the script is a PHP script, but I'm running it at the command line as it already takes 30+ minutes to run.</p>
<p>Edit: the process is a migration script, so I really don't want to spend too much time optimizing it as it only needs to be run for testing purposes and once to go live. Just for testing, it keeps bring the server to pretty much a halt...and it's a shared server.</p>
|
[
{
"answer_id": 257667,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>Using CPU cycles alone shouldn't take over the rest of the system. You can show this by doing:</p>\n\n<pre><code>while true; do done\n</code></pre>\n\n<p>This is an infinite loop and will use as much of the CPU cycles it can get (stop it with ^C). You can use <code>top</code> to verify that it is doing its job. I am quite sure that this won't significantly affect the overall performance of your system to the point where MySQL dies.</p>\n\n<p>However, if your PHP script is allocating a lot of memory, that certainly <em>can</em> make a difference. Linux has a tendency to go around killing processes when the system starts to run out of memory.</p>\n\n<p>I would narrow down the problem and be sure of the cause, before looking for a solution.</p>\n"
},
{
"answer_id": 257669,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "<p>The best you can really do without modifying the program is to change the nice value to the maximum value using <code>nice</code> or <code>renice</code>. Your best bet is probably to profile the program to find out where it is spending most of its time/using most of its memory and try to find a more efficient algorithm for what you are trying to do. For example, if your are operating on a large result set from MySQL you may want to process records one at a time instead of loading the entire result set into memory or perhaps you can optimize your queries or the processing being performed on the results.</p>\n"
},
{
"answer_id": 257670,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 3,
"selected": true,
"text": "<p>You should use nice with 19 \"niceness\" this makes the process very unlikely to run if there are other processes waiting for the cpu.</p>\n\n<pre><code> nice -n 19 <command>\n</code></pre>\n\n<p>Be sure that the program does not have busy waits and also check the I/O wait time.</p>\n"
},
{
"answer_id": 257674,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 1,
"selected": false,
"text": "<p>Which process is actually taking up the CPU? PHP or MySQL? If it's MySQL, 'nice' won't help at all (since the server is not 'nice'd up).</p>\n\n<p>If it's MySQL in general you have to look at your queries and MySQL tuning as to why those queries are slamming the server.</p>\n\n<p>Slamming your MySQL server process can show as \"the whole system being slow\" if your primary view of the system through MySQL.</p>\n"
},
{
"answer_id": 257681,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 0,
"selected": false,
"text": "<p>You could mount your server's interesting directory/filesystem/whatever on another machine via NFS and run the script there (I know, this means avoiding the problem and is not really practical :| ). </p>\n"
},
{
"answer_id": 257719,
"author": "Nathan Neulinger",
"author_id": 33531,
"author_profile": "https://Stackoverflow.com/users/33531",
"pm_score": 1,
"selected": false,
"text": "<p>You should also consider whether the cmd line process is IO intensive. That can be adjusted on some linux distros using the 'ionice' command, though it's usage is not nearly as simplistic as the cpu 'nice' command.</p>\n\n<p>Basic usage:</p>\n\n<p>ionice -n7 cmd</p>\n\n<p>will run 'cmd' using 'best effort' scheduler at the lowest priority. See the man page for more usage details.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257659",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
I am wondering how to get a process run at the command line to use less processing power. The problem I'm having is the the process is basically taking over the CPU and taking MySQL and the rest of the server with it. Everything is becoming very slow.
I have used `nice` before but haven't had much luck with it. If it is the answer, how would you use it?
I have also thought of putting in `sleep` commands, but it'll still be using up memory so it's not the best option.
Is there another solution?
It doesn't matter to me how long it runs for, within reason.
If it makes a difference, the script is a PHP script, but I'm running it at the command line as it already takes 30+ minutes to run.
Edit: the process is a migration script, so I really don't want to spend too much time optimizing it as it only needs to be run for testing purposes and once to go live. Just for testing, it keeps bring the server to pretty much a halt...and it's a shared server.
|
You should use nice with 19 "niceness" this makes the process very unlikely to run if there are other processes waiting for the cpu.
```
nice -n 19 <command>
```
Be sure that the program does not have busy waits and also check the I/O wait time.
|
257,685 |
<p>I have a program that uses save files. It needs to load the newest save file, but fall back on the next newest if that one is unavailable or corrupted. Can I use the windows file creation timestamp to tell the order of when they were created, or is this unreliable? I am asking because the "changed" timestamps seem unreliable. I can embed the creation time/date in the name if I have to, but it would be easier to use the file system dates if possible.</p>
|
[
{
"answer_id": 257704,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "<p>If you have a directory full of arbitrary and randomly named files and 'time' is the only factor, it may be more pointful to establish a filename that matches the timestamp to eliminate need for using tools to view it. </p>\n\n<pre><code>2008_12_31_24_60_60_1000 \n</code></pre>\n\n<p>Would be my recommendation for a flatfile system. </p>\n\n<p>Sometimes if you have a lot of files, you may want to group them, ie:</p>\n\n<pre><code>2008/\n2008/12/\n2008/12/31\n2008/12/31/00-12/\n2008/12/31/13-24/24_60_60_1000 \n</code></pre>\n\n<p>or something larger </p>\n\n<pre><code>2008/\n2008/12_31/\n</code></pre>\n\n<p>etc etc etc. </p>\n\n<p>( Moreover, if you're not embedding the time, what is your other distinguishing characteritics, you cant have a null file name, and creating monotonically increasing sequences is way harder ? need info ) </p>\n"
},
{
"answer_id": 257751,
"author": "user8032",
"author_id": 8032,
"author_profile": "https://Stackoverflow.com/users/8032",
"pm_score": 2,
"selected": false,
"text": "<p>What do you mean by \"reliable\"? When you create a file, it gets a timestamp, and that works. Now, the resolution of that timestamp is not necessarily high -- on FAT16 it was 2 seconds, I think. On FAT32 and NTFS it probably is 1 second. So if you are saving your files at a rate of less then one per second, you should be good there. Keep in mind, that user can change the timestamp value arbitrarily. If you are concerned about that, you'll have to embed the timestamp into the file itself (although in my opinion that would be ovekill)</p>\n"
},
{
"answer_id": 277222,
"author": "Larry Osterman",
"author_id": 761503,
"author_profile": "https://Stackoverflow.com/users/761503",
"pm_score": 2,
"selected": false,
"text": "<p>Of course if the user of the machine is an administrator, they can set the current time to whatever they want it to be, and the system will happily timestamp files with that time.</p>\n\n<p>So it all depends on what you're trying to do with the information.</p>\n"
},
{
"answer_id": 604566,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Windows timestamps are in UTC. So if your timezone changes (ie. when daylight savings starts or ends) the timestamp will move forward/back an hour. Apart from that, and the accuracy of about 2 seconds, there is no reason to think that the timestamps are invalid, and its certainly ok to use them. But I think its bad practice, when you can simply put the timestamp in the name, or in the file itself even.</p>\n"
},
{
"answer_id": 604637,
"author": "Kim Reece",
"author_id": 1911072,
"author_profile": "https://Stackoverflow.com/users/1911072",
"pm_score": 1,
"selected": false,
"text": "<p>What if the system time is changed for some reason? It seems handy, but perhaps some other version number counting up would be better.</p>\n\n<p>Added: A similar question, but with databases, <a href=\"https://stackoverflow.com/questions/600693/why-not-use-the-creation-time-of-a-record-as-a-primary-key\">here</a>.</p>\n"
},
{
"answer_id": 24974744,
"author": "mzzzzb",
"author_id": 1285431,
"author_profile": "https://Stackoverflow.com/users/1285431",
"pm_score": 1,
"selected": false,
"text": "<p>I faced some issues with created time of a file after deletion and recreation under same name. </p>\n\n<p>Something similar to this comment in <a href=\"http://msdn.microsoft.com/en-us/library/aa364946.aspx\" rel=\"nofollow\">GetFileInfoEx docs</a></p>\n\n<blockquote>\n <p>Problem getting correct Creation Time after file was recreated </p>\n \n <p>I tried to use GetFileAttributesEx and then get ftCreationTime field of\n the resulting WIN32_FILE_ATTRIBUTE_DATA structure. It works just fine\n at first, but after I delete file and recreate again, it keeps giving\n me the original already incorrect value until I restart the process\n again. The same problem happens for FindFirstFile API, as well. I use\n Window 2003.</p>\n</blockquote>\n\n<p>this is said to be related to something called <a href=\"http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B172190\" rel=\"nofollow\">tunnelling</a></p>\n"
},
{
"answer_id": 54534266,
"author": "lewis",
"author_id": 10895985,
"author_profile": "https://Stackoverflow.com/users/10895985",
"pm_score": 0,
"selected": false,
"text": "<p>try usining this when you want to rename the file </p>\n\n<pre><code>Path.Combine(ArchivedPath, currentDate + \" \" + fileInfo.Name))\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a program that uses save files. It needs to load the newest save file, but fall back on the next newest if that one is unavailable or corrupted. Can I use the windows file creation timestamp to tell the order of when they were created, or is this unreliable? I am asking because the "changed" timestamps seem unreliable. I can embed the creation time/date in the name if I have to, but it would be easier to use the file system dates if possible.
|
If you have a directory full of arbitrary and randomly named files and 'time' is the only factor, it may be more pointful to establish a filename that matches the timestamp to eliminate need for using tools to view it.
```
2008_12_31_24_60_60_1000
```
Would be my recommendation for a flatfile system.
Sometimes if you have a lot of files, you may want to group them, ie:
```
2008/
2008/12/
2008/12/31
2008/12/31/00-12/
2008/12/31/13-24/24_60_60_1000
```
or something larger
```
2008/
2008/12_31/
```
etc etc etc.
( Moreover, if you're not embedding the time, what is your other distinguishing characteritics, you cant have a null file name, and creating monotonically increasing sequences is way harder ? need info )
|
257,735 |
<p>I'm looking to create a Visual Studio 2008 template that will create a basic project and based on remove certain files/folders based on options the user enters.</p>
<p>Right now, I have followed some tutorials online which have let me create the form to query the user and pass the data into an IWizard class, but I don't know what to do from there.</p>
<p>The tutorials provide a sample to do some simple substitution:
code:</p>
<pre><code>Form1 form = new Form1();
DialogResult dlg = form.ShowDialog();
if (dlg == DialogResult.OK)
{
foreach (KeyValuePair<string, string> pair in form.Parameters)
{
if (!replacementsDictionary.ContainsKey(pair.Key))
replacementsDictionary.Add(pair.Key, pair.Value);
else
replacementsDictionary[pair.Key] = pair.Value;
}
}
form.Close();
</code></pre>
<p>but I'm looking to selectively include files based on the user settings, and if possible, selectively include code sections in a file based on settings.</p>
<p>Is there a clever way to do this, or will I manually have to delete project files in the IWizard:ProjectFinishedGenerating()?</p>
|
[
{
"answer_id": 257978,
"author": "Erik",
"author_id": 33315,
"author_profile": "https://Stackoverflow.com/users/33315",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand correctly, you want to be able to determine whether or not you should add project items to a project.</p>\n\n<p>If so, you can implement IWizard.ShouldAddProjectItem and return whether or not you want the file to be added or not.</p>\n"
},
{
"answer_id": 666235,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 3,
"selected": true,
"text": "<p>In my experience, <code>ShouldAddProjectItem</code> only gets called for <em>folders</em> in the template project. As such, it's pretty much useless. </p>\n\n<p>Instead, you would need to put code in your <code>ProjectFinishedGenerating</code> implementation that uses the VS API to remove ProjectItems.</p>\n\n<p>In there, you can remove items like this:</p>\n\n<pre><code>ProjectItem file = project.ProjectItems.Item(\"File.cs\");\nfile.Remove();\n</code></pre>\n"
},
{
"answer_id": 2922315,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 1,
"selected": false,
"text": "<p>You can selectively include parts of a file by using <code>$if$</code> with replacements. See, for example, this bit in the default C# Class Library template:</p>\n\n<pre><code><ItemGroup>\n <Reference Include=\"System\"/>\n $if$ ($targetframeworkversion$ >= 3.5)\n <Reference Include=\"System.Core\"/>\n <Reference Include=\"System.Xml.Linq\"/>\n <Reference Include=\"System.Data.DataSetExtensions\"/>\n $endif$\n</code></pre>\n\n<p>...etc.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33536/"
] |
I'm looking to create a Visual Studio 2008 template that will create a basic project and based on remove certain files/folders based on options the user enters.
Right now, I have followed some tutorials online which have let me create the form to query the user and pass the data into an IWizard class, but I don't know what to do from there.
The tutorials provide a sample to do some simple substitution:
code:
```
Form1 form = new Form1();
DialogResult dlg = form.ShowDialog();
if (dlg == DialogResult.OK)
{
foreach (KeyValuePair<string, string> pair in form.Parameters)
{
if (!replacementsDictionary.ContainsKey(pair.Key))
replacementsDictionary.Add(pair.Key, pair.Value);
else
replacementsDictionary[pair.Key] = pair.Value;
}
}
form.Close();
```
but I'm looking to selectively include files based on the user settings, and if possible, selectively include code sections in a file based on settings.
Is there a clever way to do this, or will I manually have to delete project files in the IWizard:ProjectFinishedGenerating()?
|
In my experience, `ShouldAddProjectItem` only gets called for *folders* in the template project. As such, it's pretty much useless.
Instead, you would need to put code in your `ProjectFinishedGenerating` implementation that uses the VS API to remove ProjectItems.
In there, you can remove items like this:
```
ProjectItem file = project.ProjectItems.Item("File.cs");
file.Remove();
```
|
257,740 |
<p>Basically I'm trying to change the <code>Canvas.Left</code> property of an Ellipse Silverlight control in C#. Here is how I'm accessing the control:</p>
<pre><code>Ellipse c1 = this.FindName("Circle1") as Ellipse;
</code></pre>
<p>How would I then set the <code>Canvas.Left</code> property?</p>
<p>Thanks,</p>
<p>Jeff</p>
|
[
{
"answer_id": 257747,
"author": "JSmyth",
"author_id": 54794,
"author_profile": "https://Stackoverflow.com/users/54794",
"pm_score": 3,
"selected": true,
"text": "<p>The answer lies in Silverlights use of Dependancy Properties</p>\n\n<p>c1.SetValue(Canvas.LeftProperty, value);</p>\n"
},
{
"answer_id": 257749,
"author": "Bill Reiss",
"author_id": 18967,
"author_profile": "https://Stackoverflow.com/users/18967",
"pm_score": 0,
"selected": false,
"text": "<p>something like this...</p>\n\n<pre><code>double left=50;\nc1.SetValue(Canvas.LeftProperty, left);\n</code></pre>\n"
},
{
"answer_id": 258323,
"author": "Tanmoy",
"author_id": 1312208,
"author_profile": "https://Stackoverflow.com/users/1312208",
"pm_score": 0,
"selected": false,
"text": "<p>Another way\nCanvas.SetLeft(c1,value)</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257740",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172/"
] |
Basically I'm trying to change the `Canvas.Left` property of an Ellipse Silverlight control in C#. Here is how I'm accessing the control:
```
Ellipse c1 = this.FindName("Circle1") as Ellipse;
```
How would I then set the `Canvas.Left` property?
Thanks,
Jeff
|
The answer lies in Silverlights use of Dependancy Properties
c1.SetValue(Canvas.LeftProperty, value);
|
257,767 |
<p>I have a largish Mercurial repository that I've decided would be better as several smaller repositories. Is there a way that I can split the repository and have each piece retain its revision history?</p>
|
[
{
"answer_id": 257788,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Just clone it and delete the unwanted stuff out of each copy.</p>\n"
},
{
"answer_id": 257927,
"author": "Ry4an Brase",
"author_id": 8992,
"author_profile": "https://Stackoverflow.com/users/8992",
"pm_score": 7,
"selected": true,
"text": "<p>The best way to do this is using the <a href=\"https://www.mercurial-scm.org/wiki/ConvertExtension\" rel=\"nofollow noreferrer\">'convert' extension</a>. You'll use mercurial and both source and destination type and then use a <code>--filemap</code> with entries like:</p>\n\n<pre><code>exclude path/you/do/not/want\nrename path/you/do/want .\n</code></pre>\n\n<p>The rename is only necessary if you want to take the parts you're keeping and move them \"higher\" in the directory hierarchy.</p>\n"
},
{
"answer_id": 47349707,
"author": "KalenGi",
"author_id": 212076,
"author_profile": "https://Stackoverflow.com/users/212076",
"pm_score": 0,
"selected": false,
"text": "<p>I found a detailed guide <a href=\"http://510x.se/notes/posts/Splitting_a_Mercurial_repository_while_keeping_relevant_history/\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<p>Create a file map <code>new-repo.filemap</code> such as</p>\n\n<pre><code>include vendor/FooBackend\nrename vendor/FooBackend .\n</code></pre>\n\n<p>Create another file map <code>rewrite-old-repo.filemap</code>:</p>\n\n<pre><code>exclude vendor/FooBackend\n</code></pre>\n\n<p>Create the new repository:</p>\n\n<pre><code>hg convert /path/to/current/repo /path/to/new/repo --filemap new-repo.filemap\n</code></pre>\n\n<p>The new repository is now finished. The directory is empty, but a <code>hg update</code> will bring its contents up to speed.</p>\n\n<p>Create the modified repository:</p>\n\n<pre><code>hg convert /path/to/current/repo /path/to/rewritten/repo --filemap rewrite-old-repo.filemap\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207/"
] |
I have a largish Mercurial repository that I've decided would be better as several smaller repositories. Is there a way that I can split the repository and have each piece retain its revision history?
|
The best way to do this is using the ['convert' extension](https://www.mercurial-scm.org/wiki/ConvertExtension). You'll use mercurial and both source and destination type and then use a `--filemap` with entries like:
```
exclude path/you/do/not/want
rename path/you/do/want .
```
The rename is only necessary if you want to take the parts you're keeping and move them "higher" in the directory hierarchy.
|
257,772 |
<p>I am using Structure map like the MVC storefront by Rob Conery does and I have an AdminController and so to get to it I just type:</p>
<pre><code>website/Admin/action
</code></pre>
<p>however if I miss spell the controller name I get the error below:</p>
<p>Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: key</p>
<p>There error occurs on this line:</p>
<pre><code>Controller controller = ObjectFactory.GetInstance(controllerType) as Controller;
</code></pre>
<p>Does anyone have any ideas on how I can handle this error or not allow it to happen at all and maybe just goto a 404 page??</p>
<p>Cheers in advance</p>
|
[
{
"answer_id": 257846,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 1,
"selected": false,
"text": "<p>You have a couple different options (or if you want, two things you can combine for a solution). To remove some of the potential problems between the chair and address bar you can <a href=\"http://en.wikipedia.org/wiki/Soundex\" rel=\"nofollow noreferrer\">implement a SoundEx solution</a> <a href=\"http://www.csharphelp.com/archives2/archive394.html\" rel=\"nofollow noreferrer\">in C#</a> using the new routing framework to potentially capture some misspellings and re-route them to the expected URL (and/or add routes for what you believe common misspellings or requests will be). This, however, isn't a solution that will fully solve the problem so you'll need to <a href=\"http://aspnetresources.com/articles/CustomErrorPages.aspx\" rel=\"nofollow noreferrer\">look in to implementing custom error pages</a> for your application.</p>\n"
},
{
"answer_id": 258051,
"author": "Andrew Stanton-Nurse",
"author_id": 29813,
"author_profile": "https://Stackoverflow.com/users/29813",
"pm_score": 4,
"selected": true,
"text": "<p>The problem is that if there is no controller with the expected type name (i.e. if the user types \"<strong>Amdin</strong>\" the ControllerFactory base class will look for \"<strong>Amdin</strong>Controller\" and won't find it, but will still call your overriden method). In that case, the controllerType variable will be null. So you can just check it for null before the line you quoted and then (if it is null) either: </p>\n\n<p>A) Implement a spelling correction such as the one cfeduke suggests</p>\n\n<p>or B) simply throw an HttpException with the status code 404 (that <em>should</em> cause the 404 error you are looking for). </p>\n\n<p>NOTE: If you do a spelling correction, you should probably do a Response.Redirect to the new URL, rather than just silently loading the right controller, that way the address bar changes to reflect the spelling correction</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29376/"
] |
I am using Structure map like the MVC storefront by Rob Conery does and I have an AdminController and so to get to it I just type:
```
website/Admin/action
```
however if I miss spell the controller name I get the error below:
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: key
There error occurs on this line:
```
Controller controller = ObjectFactory.GetInstance(controllerType) as Controller;
```
Does anyone have any ideas on how I can handle this error or not allow it to happen at all and maybe just goto a 404 page??
Cheers in advance
|
The problem is that if there is no controller with the expected type name (i.e. if the user types "**Amdin**" the ControllerFactory base class will look for "**Amdin**Controller" and won't find it, but will still call your overriden method). In that case, the controllerType variable will be null. So you can just check it for null before the line you quoted and then (if it is null) either:
A) Implement a spelling correction such as the one cfeduke suggests
or B) simply throw an HttpException with the status code 404 (that *should* cause the 404 error you are looking for).
NOTE: If you do a spelling correction, you should probably do a Response.Redirect to the new URL, rather than just silently loading the right controller, that way the address bar changes to reflect the spelling correction
|
257,793 |
<p>I recently switched my hosting provider and due to the time zone that the server is now in, my code has stopped working. </p>
<p>The hosting server reports in Pacific time, However, my code needs to work with GMT as my site is for the UK market. So, all my displays and searches need to be in the format dd/MM/yyyy</p>
<p>How can I account for the difference? </p>
<p>For instance, when I do a DateTime.Parse("03/11/2008") it fail as I assume the 'Parse' is against the servers settings. I also get "String was not recognized as a valid DateTime." throughout my code. </p>
|
[
{
"answer_id": 257807,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 2,
"selected": false,
"text": "<p>Try </p>\n\n<pre><code>DateTime.Parse(\"28/11/2008\", new CultureInfo(\"en-GB\"))\n</code></pre>\n\n<p>Have a look at <a href=\"http://msdn.microsoft.com/en-us/library/kc8s65zs.aspx\" rel=\"nofollow noreferrer\">the overload for DateTime.Parse on MSDN</a>. </p>\n\n<p>Also, be careful not to confuse time zones (pacific, GMT) with cultures.\nCultures are your actual problem here.</p>\n"
},
{
"answer_id": 257825,
"author": "Pavel Chuchuva",
"author_id": 14131,
"author_profile": "https://Stackoverflow.com/users/14131",
"pm_score": 4,
"selected": true,
"text": "<p>In your web.config file add <code><globalization></code> element under <code><system.web></code> node:</p>\n\n<pre><code><system.web>\n <globalization culture=\"en-gb\"/>\n <!-- ... -->\n</system.web>\n</code></pre>\n"
},
{
"answer_id": 333278,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 1,
"selected": false,
"text": "<p>In order to avoid dealing with these very boring issues, I advise you to allways parse your data following the standard and unique SQL/ISO date format which is YYYY-MM-DD. Your queries will then work internationally, whatever are the date parameters on your main server or on the querying clients (where local date settings might be different than main server settings)!</p>\n"
},
{
"answer_id": 32817459,
"author": "Mukklan",
"author_id": 4316363,
"author_profile": "https://Stackoverflow.com/users/4316363",
"pm_score": 0,
"selected": false,
"text": "<p>I had this problem which the above answers didn't solve. So maybe this can help someone not to tear all their hair off..</p>\n\n<p>I got NaN-NaN-Nan on the new server in my date-textbox. Found out that the new server had the internet explorer option \"Display intranet sites in Compability Mode\". \nWorkaround here was to put </p>\n\n<pre><code><meta http-equiv=\"X-UA-Compatible\" content=\"IE=9; IE=8; IE=7; IE=EDGE\" / >\n</code></pre>\n\n<p>in the head of the aspx to force off compability mode.</p>\n\n<p>This solved a lot of weird stuff that was going on.\nHope this helps someone! </p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26300/"
] |
I recently switched my hosting provider and due to the time zone that the server is now in, my code has stopped working.
The hosting server reports in Pacific time, However, my code needs to work with GMT as my site is for the UK market. So, all my displays and searches need to be in the format dd/MM/yyyy
How can I account for the difference?
For instance, when I do a DateTime.Parse("03/11/2008") it fail as I assume the 'Parse' is against the servers settings. I also get "String was not recognized as a valid DateTime." throughout my code.
|
In your web.config file add `<globalization>` element under `<system.web>` node:
```
<system.web>
<globalization culture="en-gb"/>
<!-- ... -->
</system.web>
```
|
257,795 |
<p>I'm trying to add an header file to dev-C++ but when I compile it it doesn't work.
Here are my exact steps (for my example, I'm trying to get mysql.h to work):</p>
<ol>
<li>copy "mysql.h" into c:\dev-c++\includes</li>
<li>check that in dev-C++ tools > compiler options > directories > c includes and c++ includes have the path to "c:\dev-c++\includes"</li>
<li>include #include at the top of my file</li>
<li>compiled</li>
</ol>
<p>This is what the dev-C++ compiler told me:</p>
<pre><code>13 C:\Documents and Settings\Steve\Desktop\server code\setup1\main.c `mysql' undeclared (first use in this function)
</code></pre>
<p>As well as other errors due to not locating the header file</p>
<p>Are the steps I've outlined correct? Or is there something else I need to do to get the header files to compile.</p>
<p>P.S. I tried doing the same with VS2008 (put mysql.h in the vs2008 include folder, etc)
but still have the same error. I would like to stick with Dev-c++ if possible.</p>
|
[
{
"answer_id": 257800,
"author": "jpoh",
"author_id": 4368,
"author_profile": "https://Stackoverflow.com/users/4368",
"pm_score": 2,
"selected": false,
"text": "<p>You didn't say how you included it at the top of your file. This should work if you did</p>\n\n<pre><code>#include \"mysql.h\"\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>#include <mysql>\n</code></pre>\n\n<p>which is a mistake that people sometimes make.</p>\n\n<p>EDIT: Perhaps try using relative paths rather than an absolute path (as you seem to be doing) when specifying additional include directories? I don't know if that would make a difference (and I don't have the time to check) but I've always used relative paths and it's always worked for me (it's also good practice anyway). So, instead of</p>\n\n<p>C:\\Projects\\ProjectName\\Include</p>\n\n<p>something like</p>\n\n<p>\\Include or ..\\Include depending on your project file structure.</p>\n"
},
{
"answer_id": 257822,
"author": "Seiti",
"author_id": 27959,
"author_profile": "https://Stackoverflow.com/users/27959",
"pm_score": 3,
"selected": true,
"text": "<p>Dev-C++ is a port of GCC, so try this page: <a href=\"http://gcc.gnu.org/onlinedocs/cpp/Search-Path.html#Search-Path\" rel=\"nofollow noreferrer\">http://gcc.gnu.org/onlinedocs/cpp/Search-Path.html</a>. </p>\n\n<p>Note that you probably have to tinkle with the Makefile.</p>\n"
},
{
"answer_id": 4318829,
"author": "Jose Luis Manrique",
"author_id": 525751,
"author_profile": "https://Stackoverflow.com/users/525751",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem.... </p>\n\n<p>You need to put the #include after \"using namespace std;\", in order to use your header file in the standard namespace.</p>\n\n<p>For me it is working.</p>\n\n<p>Best wishes.</p>\n"
},
{
"answer_id": 4714364,
"author": "makman99",
"author_id": 578644,
"author_profile": "https://Stackoverflow.com/users/578644",
"pm_score": 0,
"selected": false,
"text": "<p>On the left side, right click the Project and choose \"Add to Project\", and then select the header file.</p>\n"
},
{
"answer_id": 45390104,
"author": "Ritesh Aggarwal",
"author_id": 8240164,
"author_profile": "https://Stackoverflow.com/users/8240164",
"pm_score": 0,
"selected": false,
"text": "<p>Its very simple ...</p>\n\n<p>Just make Your header file and save it as .h extension.</p>\n\n<p>Then use #include <strong>\"file_name.h\"</strong> instead of using <strong>include</strong></p>\n\n<p><strong><em>Example- \nThis is my header file.</em></strong></p>\n\n<pre><code>#include<iostream>\n using namespace std;\n\n namespace Ritesh\n {\n int a;\n int b;\n void sum();\n }\n void Ritesh::sum()\n {\n cout<<a+b;\n }\n</code></pre>\n\n<p><strong>Then use of it-</strong></p>\n\n<pre><code>#include<iostream>\n#include \"Ritesh.h\"\n using namespace std;\n using namespace Ritesh;\n int main()\n {\n a=4;b=6;\n sum();\n }\n</code></pre>\n\n<p>Output-\n<a href=\"https://i.stack.imgur.com/Rwr8X.jpg\" rel=\"nofollow noreferrer\">Output of program</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
I'm trying to add an header file to dev-C++ but when I compile it it doesn't work.
Here are my exact steps (for my example, I'm trying to get mysql.h to work):
1. copy "mysql.h" into c:\dev-c++\includes
2. check that in dev-C++ tools > compiler options > directories > c includes and c++ includes have the path to "c:\dev-c++\includes"
3. include #include at the top of my file
4. compiled
This is what the dev-C++ compiler told me:
```
13 C:\Documents and Settings\Steve\Desktop\server code\setup1\main.c `mysql' undeclared (first use in this function)
```
As well as other errors due to not locating the header file
Are the steps I've outlined correct? Or is there something else I need to do to get the header files to compile.
P.S. I tried doing the same with VS2008 (put mysql.h in the vs2008 include folder, etc)
but still have the same error. I would like to stick with Dev-c++ if possible.
|
Dev-C++ is a port of GCC, so try this page: [http://gcc.gnu.org/onlinedocs/cpp/Search-Path.html](http://gcc.gnu.org/onlinedocs/cpp/Search-Path.html#Search-Path).
Note that you probably have to tinkle with the Makefile.
|
257,797 |
<p>I wrote a C++ project in VS2005, and used lots of STL container with its plus-in STL. However, I found STL in VS2005 does not have a hash_map in it, I want to use SGI hash_map. How can I change my project to use SGI STL?</p>
<p>Thanks for Brian's method, it works! And it's simple.</p>
|
[
{
"answer_id": 257799,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 3,
"selected": true,
"text": "<p>VS2005 does have a hash_map:</p>\n\n<pre><code>#include <hash_map>\nstdext::hash_map\n</code></pre>\n\n<p>If you still want to though you can <a href=\"http://www.sgi.com/tech/stl/download.html\" rel=\"nofollow noreferrer\">download the sgi stl here</a>. You should be able to just set the include directory to the sgi location. It will take precedence over the VC++ global include directories.</p>\n"
},
{
"answer_id": 258225,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 0,
"selected": false,
"text": "<p>I do not know if VS2005 has TR1, but if it has (or if you later decide to use another compiler which has it), you can use <code>unordered_map</code>:</p>\n\n<pre><code>#include <tr1/unordered_map>\nstd::tr1::unordered_map mymap;\n</code></pre>\n\n<p>Also, for completeness, GCC (which used to have <code><hash_map></code>) has <code>hash_map</code> on <code><ext/hash_map></code> (on a different namespace). On recent GCC releases, you can also use <code><tr1/unordered_map></code>.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
I wrote a C++ project in VS2005, and used lots of STL container with its plus-in STL. However, I found STL in VS2005 does not have a hash\_map in it, I want to use SGI hash\_map. How can I change my project to use SGI STL?
Thanks for Brian's method, it works! And it's simple.
|
VS2005 does have a hash\_map:
```
#include <hash_map>
stdext::hash_map
```
If you still want to though you can [download the sgi stl here](http://www.sgi.com/tech/stl/download.html). You should be able to just set the include directory to the sgi location. It will take precedence over the VC++ global include directories.
|
257,801 |
<p>Here's the scenario:</p>
<p>I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.</p>
<p>Here is the code so far:</p>
<pre><code><input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
</code></pre>
<p>Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set.</p>
|
[
{
"answer_id": 257852,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 0,
"selected": false,
"text": "<p>Here is an idea. I don't think it is very pretty but should work:</p>\n\n<pre><code>$('input#tb').blur(function(){ \n var url = $('input.thickbox').attr('alt');\n var tbVal = $(this).val();\n\n // add the textbox value into the query string here\n // url = ..\n\n $('input.thickbox').attr('alt', url);\n\n});\n</code></pre>\n\n<p>Basically, you update the button alt tag every time the textbox loses focus. Instead, you could also listen to key strokes and update after every one. </p>\n\n<p>As far as updateing the query string, I'll let you figure out the best way. I can see putting a placeholder in there like: &TB=TB_PLACEHOLDER. Then you can just do a string replace.</p>\n"
},
{
"answer_id": 257957,
"author": "Scott Evernden",
"author_id": 11397,
"author_profile": "https://Stackoverflow.com/users/11397",
"pm_score": 4,
"selected": true,
"text": "<p>Just handle the onclick of your button to run a function that calls <code>tb_show()</code>, passing the value of the text box. Something like</p>\n\n<pre><code>... onclick = \"doSearch()\" ...\n\nfunction doSearch()\n{\n tb_show(caption, 'Search.aspx?KeepThis=true&q=\\\"' +\n $('input#tb').val() +\n '\\\"&TB_iframe=true&height=500&width=700');\n}\n</code></pre>\n"
},
{
"answer_id": 681151,
"author": "TheAlbear",
"author_id": 27922,
"author_profile": "https://Stackoverflow.com/users/27922",
"pm_score": 0,
"selected": false,
"text": "<p>In the <a href=\"http://en.wiktionary.org/wiki/code-behind\" rel=\"nofollow noreferrer\">code-behind</a> you could also just add the alt tag progammatically,</p>\n\n<pre><code>button1.Attributes.Add(\"alt\", \"Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700\");\n</code></pre>\n"
},
{
"answer_id": 1034674,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you read the manual, under the iframe content section, it tells you that your parameters need to go before the TB_iframe parameter. Everything after this gets stripped off.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1574/"
] |
Here's the scenario:
I have a textbox and a button on a web page. When the button is clicked, I want a popup window to open (using Thickbox) that will show all items that match the value entered in the textbox. I am currently using the IFrame implementation of Thickbox. The problem is that the URL to show is hardcoded into the "alt' attribute of the button. What I really need is for the "alt" attribute to pass along the value in the textbox to the popup.
Here is the code so far:
```
<input type="textbox" id="tb" />
<input alt="Search.aspx?KeepThis=true&TB_iframe=true&height=500&width=700" class="thickbox" title="Search" type="button" value="Search" />
```
Ideally, I would like to put the textbox value into the Search.aspx url but I can't seem to figure out how to do that. My current alternative is to use jQuery to set the click function of the Search button to call a web service that will set some values in the ASP.NET session. The Search.aspx page will then use the session variables to do the search. However, this is a bit flaky since it seems like there will always be the possibility that the search executes before the session variables are set.
|
Just handle the onclick of your button to run a function that calls `tb_show()`, passing the value of the text box. Something like
```
... onclick = "doSearch()" ...
function doSearch()
{
tb_show(caption, 'Search.aspx?KeepThis=true&q=\"' +
$('input#tb').val() +
'\"&TB_iframe=true&height=500&width=700');
}
```
|
257,805 |
<p>I'm having a hard time understanding some git/DCVS concepts. Here's what happened:</p>
<ol>
<li>I created a git project, and imported it from an SVN repo</li>
<li>I made some commits</li>
<li>I wanted to experiment something, so I created a branch called <strong>constants-update</strong></li>
<li>I switched to <strong>constants-update</strong>branch, moved some files, deleted others and added many more</li>
<li>I committed to this branch</li>
<li>Now I'm trying to switch to my master branch using <code>git checkout master</code></li>
<li>I got this error: <strong>error: You have local changes to 'src/groovy/Constants.groovy'; cannot switch branches.</strong></li>
</ol>
<p>My understanding of DCVS is that I can switch branches at will, even if some branch has more or less files than the others, as long as I commit my files. I've tried committing with <code>git commit -a</code> and switching to master branch, but I have the same error. </p>
<p>As a side note, when I commit git warns me that LF will be replaced by CRLF and warns me about some trailing whitespaces also; after I commit I do a <code>git status</code> and a bunch of files always appear as <code>#modified ...</code>.</p>
<p>Is this related to git/<strong>windows</strong>, or I do not understand correctly what it is supposed to happen? I just want to switch to my master branch <strong>without losing my changes</strong> in the other branch.</p>
|
[
{
"answer_id": 257829,
"author": "Grant Limberg",
"author_id": 27314,
"author_profile": "https://Stackoverflow.com/users/27314",
"pm_score": 2,
"selected": false,
"text": "<p>Lookup git-stash for changing branches while there are unsaved changes in the current branch.</p>\n"
},
{
"answer_id": 257830,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You are correct in your thinking about how this should work.</p>\n\n<p>However, it sounds like git is having issues with the line endings, and it thinks all your files are modified even when they aren't. I don't use git on Windows, but I was going to suggest the \"core.autocrlf\" option to make the crlf handling work. However, the following blog entry indicates that this might not be a good idea: <a href=\"http://weierophinney.net/matthew/archives/191-git-svn-Tip-dont-use-core.autocrlf.html\" rel=\"nofollow noreferrer\">http://weierophinney.net/matthew/archives/191-git-svn-Tip-dont-use-core.autocrlf.html</a></p>\n"
},
{
"answer_id": 258295,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 3,
"selected": true,
"text": "<p>I solved the problem <a href=\"http://www.dont-panic.cc/capi/2007/07/13/git-on-windows-you-have-some-suspicious-patch-lines/\" rel=\"nofollow noreferrer\">hacking my pre-commit hook</a> (commenting these lines in <code>.git/hooks/pre-commit</code> with a <code>#</code>):</p>\n\n<pre><code># if (/\\s$/) {\n# bad_line(\"trailing whitespace\", $_);\n# }\n</code></pre>\n"
},
{
"answer_id": 490571,
"author": "Autodidact",
"author_id": 60072,
"author_profile": "https://Stackoverflow.com/users/60072",
"pm_score": 2,
"selected": false,
"text": "<p>Just use the following option in .gitconfig file which resides in your users directory.</p>\n\n<p>[core]\nautocrlf = true</p>\n\n<p>And it will solve the issue.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22992/"
] |
I'm having a hard time understanding some git/DCVS concepts. Here's what happened:
1. I created a git project, and imported it from an SVN repo
2. I made some commits
3. I wanted to experiment something, so I created a branch called **constants-update**
4. I switched to **constants-update**branch, moved some files, deleted others and added many more
5. I committed to this branch
6. Now I'm trying to switch to my master branch using `git checkout master`
7. I got this error: **error: You have local changes to 'src/groovy/Constants.groovy'; cannot switch branches.**
My understanding of DCVS is that I can switch branches at will, even if some branch has more or less files than the others, as long as I commit my files. I've tried committing with `git commit -a` and switching to master branch, but I have the same error.
As a side note, when I commit git warns me that LF will be replaced by CRLF and warns me about some trailing whitespaces also; after I commit I do a `git status` and a bunch of files always appear as `#modified ...`.
Is this related to git/**windows**, or I do not understand correctly what it is supposed to happen? I just want to switch to my master branch **without losing my changes** in the other branch.
|
I solved the problem [hacking my pre-commit hook](http://www.dont-panic.cc/capi/2007/07/13/git-on-windows-you-have-some-suspicious-patch-lines/) (commenting these lines in `.git/hooks/pre-commit` with a `#`):
```
# if (/\s$/) {
# bad_line("trailing whitespace", $_);
# }
```
|
257,809 |
<p>I want to search a table to find all rows where one particular field is one of two values. I know exactly what the values would be, but I'm wondering which is the most efficient way to search for them:</p>
<p>for the sake of example, the two values are "xpoints" and "ypoints". I know for certain that there will be no other values in that field which has "points" at the end, so the two queries I'm considering are:</p>
<pre><code>WHERE `myField` IN ('xpoints', 'ypoints')
--- or...
WHERE `myField` LIKE '_points'
</code></pre>
<p>which would give the best results in this case?</p>
|
[
{
"answer_id": 257813,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 5,
"selected": true,
"text": "<p>As always with SQL queries, run it through the profiler to find out. However, my gut instinct would have to say that the IN search would be quicker. Espcially in the example you gave, if the field was indexed, it would only have to do 2 lookups. If you did a like search, it may have to do a scan, because you are looking for records that end with a certain value. It would also be more accurate as LIKE '_points' could also return 'gpoints', or any other similar string.</p>\n"
},
{
"answer_id": 257836,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>Unless all of the data items in the column in question start with 'x' or 'y', I believe IN will always give you a better query. If it is indexed, as @Kibbee points out, you will only have to perform 2 lookups to get both. Alternatively, if it is not indexed, a table scan using IN will only have to check the first letter most of the time whereas with LIKE it will have to check two characters every time (assuming all items are at least 2 characters) -- since the first character is allowed to be anything.</p>\n"
},
{
"answer_id": 258022,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 0,
"selected": false,
"text": "<p>Try it and see. Create a large amount of test data, Also, try it with and without an index on myfield. While you are at it, see if there's a noticeable difference between\nLIKE '<em>points' and LIKE 'xpoint</em>'.</p>\n\n<p>It depends on what the optimizer does with each query. </p>\n\n<p>For small amounts of data, the difference will be negligible. Do whichever one makes more sense. For large amounts of data the amount of disk I/O matters much more than the amount of CPU time. </p>\n\n<p>I'm betting that IN will get you better results than LIKE, if there is an index on myfield. I'm also betting that 'xpoint_' runs faster than '_points'. But there's nothing like trying it yourself. </p>\n"
},
{
"answer_id": 261715,
"author": "Ciaran McNulty",
"author_id": 34024,
"author_profile": "https://Stackoverflow.com/users/34024",
"pm_score": 0,
"selected": false,
"text": "<p>MySQL can't use an index when using string comparisons such as LIKE '%foo' or '_foo', but can use an index for comparisons like 'foo%' and 'foo_'.</p>\n\n<p>So in your case, IN will be much faster assuming that the field is indexed.</p>\n\n<p>If you're working with a limited set of possible values, it's worth specifying the field as an ENUM - MySQL will then store it internally as an integer and make this sort of lookup much faster, and save disk space.</p>\n"
},
{
"answer_id": 263089,
"author": "Eric Caron",
"author_id": 34340,
"author_profile": "https://Stackoverflow.com/users/34340",
"pm_score": 0,
"selected": false,
"text": "<p>It will be faster to do the IN-version than the LIKE-version. Especially when your wildcard isn't at the end of the comparison, but even under ideal conditions IN would still be ideal up until your query nears the size of your max-query insert.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257809",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
I want to search a table to find all rows where one particular field is one of two values. I know exactly what the values would be, but I'm wondering which is the most efficient way to search for them:
for the sake of example, the two values are "xpoints" and "ypoints". I know for certain that there will be no other values in that field which has "points" at the end, so the two queries I'm considering are:
```
WHERE `myField` IN ('xpoints', 'ypoints')
--- or...
WHERE `myField` LIKE '_points'
```
which would give the best results in this case?
|
As always with SQL queries, run it through the profiler to find out. However, my gut instinct would have to say that the IN search would be quicker. Espcially in the example you gave, if the field was indexed, it would only have to do 2 lookups. If you did a like search, it may have to do a scan, because you are looking for records that end with a certain value. It would also be more accurate as LIKE '\_points' could also return 'gpoints', or any other similar string.
|
257,844 |
<p>How can I <strong>quickly</strong> create a large file on a Linux (<a href="http://en.wikipedia.org/wiki/Red_Hat_Linux" rel="noreferrer">Red Hat Linux</a>) system?</p>
<p><a href="http://en.wikipedia.org/wiki/Dd_%28Unix%29" rel="noreferrer">dd</a> will do the job, but reading from <code>/dev/zero</code> and writing to the drive can take a long time when you need a file several hundreds of GBs in size for testing... If you need to do that repeatedly, the time really adds up.</p>
<p>I don't care about the contents of the file, I just want it to be created quickly. How can this be done?</p>
<p>Using a sparse file won't work for this. I need the file to be allocated disk space.</p>
|
[
{
"answer_id": 257849,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": false,
"text": "<h1>Linux & all filesystems</h1>\n\n<p><code>xfs_mkfile 10240m 10Gigfile</code></p>\n\n<h1>Linux & and some filesystems (ext4, xfs, btrfs and ocfs2)</h1>\n\n<p><code>fallocate -l 10G 10Gigfile</code></p>\n\n<h1>OS X, Solaris, SunOS and probably other UNIXes</h1>\n\n<p><code>mkfile 10240m 10Gigfile</code></p>\n\n<h1>HP-UX</h1>\n\n<p><code>prealloc 10Gigfile 10737418240</code></p>\n\n<h1>Explanation</h1>\n\n<p>Try <code>mkfile <size></code> myfile as an alternative of <code>dd</code>. With the <code>-n</code> option the size is noted, but disk blocks aren't allocated until data is written to them. Without the <code>-n</code> option, the space is zero-filled, which means writing to the disk, which means taking time. </p>\n\n<p><a href=\"http://www.manpagez.com/man/8/mkfile/\" rel=\"noreferrer\">mkfile</a> is derived from SunOS and is not available everywhere. Most Linux systems have <a href=\"http://linux.die.net/man/8/xfs_mkfile\" rel=\"noreferrer\"><code>xfs_mkfile</code></a> which works exactly the same way, and not just on XFS file systems despite the name. It's included in <em>xfsprogs</em> (for Debian/Ubuntu) or similar named packages.</p>\n\n<p>Most Linux systems also have <a href=\"http://linux.die.net/man/1/fallocate\" rel=\"noreferrer\"><code>fallocate</code></a>, which only works on certain file systems (such as btrfs, ext4, ocfs2, and xfs), but is the fastest, as it allocates all the file space (creates non-holey files) but does not initialize any of it.</p>\n"
},
{
"answer_id": 257865,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.</p>\n\n<p>For example, have a pool of files called:</p>\n\n<ul>\n<li>/home/bigfiles/512M-A</li>\n<li>/home/bigfiles/512M-B</li>\n<li>/home/bigfiles/1024M-A</li>\n<li>/home/bigfiles/1024M-B</li>\n</ul>\n\n<p>Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a \"<code>ln /home/bigfiles/1024M-A /home/oracle/logfile</code>\".</p>\n\n<p>If it's on a separate filesystem, you will have to use a symbolic link.</p>\n\n<p>The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.</p>\n\n<p>The link operation is about as fast as you can get.</p>\n"
},
{
"answer_id": 257929,
"author": "Barry Brown",
"author_id": 17312,
"author_profile": "https://Stackoverflow.com/users/17312",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think you're going to get much faster than dd. The bottleneck is the disk; writing hundreds of GB of data to it is going to take a long time no matter how you do it.</p>\n\n<p>But here's a possibility that might work for your application. If you don't care about the contents of the file, how about creating a \"virtual\" file whose contents are the dynamic output of a program? Instead of open()ing the file, use popen() to open a pipe to an external program. The external program generates data whenever it's needed. Once the pipe is open, it acts just like a regular file in that the program that opened the pipe can fseek(), rewind(), etc. You'll need to use pclose() instead of close() when you're done with the pipe.</p>\n\n<p>If your application needs the file to be a certain size, it will be up to the external program to keep track of where in the \"file\" it is and send an eof when the \"end\" has been reached.</p>\n"
},
{
"answer_id": 257975,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 6,
"selected": false,
"text": "<p>Where seek is the size of the file you want in bytes - 1.</p>\n\n<pre><code>dd if=/dev/zero of=filename bs=1 count=1 seek=1048575\n</code></pre>\n"
},
{
"answer_id": 3530654,
"author": "kiv",
"author_id": 426314,
"author_profile": "https://Stackoverflow.com/users/426314",
"pm_score": 7,
"selected": false,
"text": "<pre><code>truncate -s 10M output.file\n</code></pre>\n<p>will create a 10 M file instantaneously (M stands for 1024<em>1024 bytes, MB stands for 1000</em>1000 - same with K, KB, G, GB...)</p>\n<p><strong>EDIT:</strong> as many have pointed out, this will not physically allocate the file on your device. With this you could actually create an arbitrary large file, regardless of the available space on the device, as it creates a "sparse" file.</p>\n<p>For e.g. notice no HDD space is consumed with this command:</p>\n<pre><code>### BEFORE\n$ df -h | grep lvm\n/dev/mapper/lvm--raid0-lvm0\n 7.2T 6.6T 232G 97% /export/lvm-raid0\n\n$ truncate -s 500M 500MB.file\n\n### AFTER\n$ df -h | grep lvm\n/dev/mapper/lvm--raid0-lvm0\n 7.2T 6.6T 232G 97% /export/lvm-raid0\n</code></pre>\n<p>So, when doing this, you will be deferring physical allocation until the file is accessed. If you're mapping this file to memory, you may not have the expected performance.</p>\n<p>But this is still a useful command to know. For e.g. when benchmarking transfers using files, the specified size of the file will still get moved.</p>\n<pre><code>$ rsync -aHAxvP --numeric-ids --delete --info=progress2 \\\n [email protected]:/export/lvm-raid0/500MB.file \\\n /export/raid1/\nreceiving incremental file list\n500MB.file\n 524,288,000 100% 41.40MB/s 0:00:12 (xfr#1, to-chk=0/1)\n\nsent 30 bytes received 524,352,082 bytes 38,840,897.19 bytes/sec\ntotal size is 524,288,000 speedup is 1.00\n</code></pre>\n"
},
{
"answer_id": 5688625,
"author": "Franta",
"author_id": 2512257,
"author_profile": "https://Stackoverflow.com/users/2512257",
"pm_score": 9,
"selected": false,
"text": "<p><code>dd</code> from the other answers is a good solution, but it is slow for this purpose. In Linux (and other POSIX systems), we have <code>fallocate</code>, which uses the desired space without having to actually writing to it, works with most modern disk based file systems, very fast:</p>\n\n<p>For example:</p>\n\n<pre><code>fallocate -l 10G gentoo_root.img\n</code></pre>\n"
},
{
"answer_id": 6839128,
"author": "Alex Dupuy",
"author_id": 18829,
"author_profile": "https://Stackoverflow.com/users/18829",
"pm_score": 2,
"selected": false,
"text": "<p>The GPL mkfile is just a (ba)sh script wrapper around dd; BSD's mkfile just memsets a buffer with non-zero and writes it repeatedly. I would not expect the former to out-perform dd. The latter might edge out dd if=/dev/zero slightly since it omits the reads, but anything that does significantly better is probably just creating a sparse file.</p>\n\n<p>Absent a system call that actually allocates space for a file without writing data (and Linux and BSD lack this, probably Solaris as well) you might get a small improvement in performance by using ftrunc(2)/truncate(1) to extend the file to the desired size, mmap the file into memory, then write non-zero data to the first bytes of every disk block (use fgetconf to find the disk block size).</p>\n"
},
{
"answer_id": 9393456,
"author": "Sepero",
"author_id": 1225603,
"author_profile": "https://Stackoverflow.com/users/1225603",
"pm_score": 5,
"selected": false,
"text": "<p>Examples where seek is the size of the file you want in bytes</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#kilobytes\ndd if=/dev/zero of=filename bs=1 count=0 seek=200K\n\n#megabytes\ndd if=/dev/zero of=filename bs=1 count=0 seek=200M\n\n#gigabytes\ndd if=/dev/zero of=filename bs=1 count=0 seek=200G\n\n#terabytes\ndd if=/dev/zero of=filename bs=1 count=0 seek=200T\n</code></pre>\n\n<p><br/></p>\n\n<p>From the dd manpage:</p>\n\n<blockquote>\n <p>BLOCKS and BYTES may be followed by the following multiplicative suffixes: c=1, w=2, b=512, kB=1000, K=1024, MB=1000*1000, M=1024*1024, GB =1000*1000*1000, G=1024*1024*1024, and so on for T, P, E, Z, Y.</p>\n</blockquote>\n"
},
{
"answer_id": 10317205,
"author": "Humungous Hippo",
"author_id": 1356398,
"author_profile": "https://Stackoverflow.com/users/1356398",
"pm_score": 4,
"selected": false,
"text": "<p>I don't know a whole lot about Linux, but here's the C Code I wrote to fake huge files on DC Share many years ago.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include < stdio.h >\n#include < stdlib.h >\n\nint main() {\n int i;\n FILE *fp;\n\n fp=fopen(\"bigfakefile.txt\",\"w\");\n\n for(i=0;i<(1024*1024);i++) {\n fseek(fp,(1024*1024),SEEK_CUR);\n fprintf(fp,\"C\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 11779492,
"author": "Dan McAllister",
"author_id": 1571677,
"author_profile": "https://Stackoverflow.com/users/1571677",
"pm_score": 8,
"selected": false,
"text": "<p>This is a common question -- especially in today's environment of virtual environments. Unfortunately, the answer is not as straight-forward as one might assume.</p>\n\n<p>dd is the obvious first choice, but dd is essentially a copy and that forces you to write every block of data (thus, initializing the file contents)... And that initialization is what takes up so much I/O time. (Want to make it take even longer? Use <a href=\"http://en.wikipedia.org/wiki//dev/random\" rel=\"noreferrer\">/dev/random</a> instead of <a href=\"http://en.wikipedia.org/wiki//dev/zero\" rel=\"noreferrer\">/dev/zero</a>! Then you'll use CPU as well as I/O time!) In the end though, dd is a poor choice (though essentially the default used by the VM \"create\" GUIs). E.g:</p>\n\n<pre><code>dd if=/dev/zero of=./gentoo_root.img bs=4k iflag=fullblock,count_bytes count=10G\n</code></pre>\n\n<p><a href=\"http://linux.die.net/man/1/truncate\" rel=\"noreferrer\">truncate</a> is another choice -- and is likely the fastest... But that is because it creates a \"sparse file\". Essentially, a sparse file is a section of disk that has a lot of the same data, and the underlying filesystem \"cheats\" by not really storing all of the data, but just \"pretending\" that it's all there. Thus, when you use truncate to create a 20 GB drive for your VM, the filesystem doesn't actually allocate 20 GB, but it cheats and says that there are 20 GB of zeros there, even though as little as one track on the disk may actually (really) be in use. E.g.:</p>\n\n<pre><code> truncate -s 10G gentoo_root.img\n</code></pre>\n\n<p><strong>fallocate is the</strong> final -- and <strong>best</strong> -- <strong>choice</strong> for use with VM disk allocation, because it essentially \"reserves\" (or \"allocates\" all of the space you're seeking, but it doesn't bother to write anything. So, when you use fallocate to create a 20 GB virtual drive space, you really do get a 20 GB file (not a \"sparse file\", and you won't have bothered to write anything to it -- which means virtually anything could be in there -- kind of like a brand new disk!) E.g.:</p>\n\n<pre><code>fallocate -l 10G gentoo_root.img\n</code></pre>\n"
},
{
"answer_id": 20541029,
"author": "Yogesh",
"author_id": 1514461,
"author_profile": "https://Stackoverflow.com/users/1514461",
"pm_score": 3,
"selected": false,
"text": "<p>You can use \"yes\" command also. The syntax is fairly simple:</p>\n\n<pre><code>#yes >> myfile\n</code></pre>\n\n<p>Press \"Ctrl + C\" to stop this, else it will eat up all your space available.</p>\n\n<p>To clean this file run:</p>\n\n<pre><code>#>myfile\n</code></pre>\n\n<p>will clean this file.</p>\n"
},
{
"answer_id": 27714438,
"author": "user79878",
"author_id": 79878,
"author_profile": "https://Stackoverflow.com/users/79878",
"pm_score": 2,
"selected": false,
"text": "<p>This is the fastest I could do (which is <strong>not</strong> fast) with the following constraints:</p>\n\n<ul>\n<li>The goal of the large file is to fill a disk, so can't be compressible.</li>\n<li>Using ext3 filesystem. (<code>fallocate</code> not available)</li>\n</ul>\n\n<p>This is the gist of it...</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>// include stdlib.h, stdio.h, and stdint.h\nint32_t buf[256]; // Block size.\nfor (int i = 0; i < 256; ++i)\n{\n buf[i] = rand(); // random to be non-compressible.\n}\nFILE* file = fopen(\"/file/on/your/system\", \"wb\");\nint blocksToWrite = 1024 * 1024; // 1 GB\nfor (int i = 0; i < blocksToWrite; ++i)\n{\n fwrite(buf, sizeof(int32_t), 256, file);\n}\n</code></pre>\n\n<p>In our case this is for an embedded linux system and this works well enough, but would prefer something faster.</p>\n\n<p>FYI the command <code>dd if=/dev/urandom of=outputfile bs=1024 count = XX</code> was so slow as to be unusable.</p>\n"
},
{
"answer_id": 32803609,
"author": "max",
"author_id": 1896222,
"author_profile": "https://Stackoverflow.com/users/1896222",
"pm_score": 5,
"selected": false,
"text": "<p>To make a 1 GB file:</p>\n\n<pre><code>dd if=/dev/zero of=filename bs=1G count=1\n</code></pre>\n"
},
{
"answer_id": 48526912,
"author": "stefan",
"author_id": 4378583,
"author_profile": "https://Stackoverflow.com/users/4378583",
"pm_score": 2,
"selected": false,
"text": "<p>Shameless plug: OTFFS provides a file system providing arbitrarily large (well, almost. Exabytes is the current limit) files of generated content. It is Linux-only, plain C, and in early alpha.</p>\n\n<p>See <a href=\"https://github.com/s5k6/otffs\" rel=\"nofollow noreferrer\">https://github.com/s5k6/otffs</a>.</p>\n"
},
{
"answer_id": 65733550,
"author": "TarithJ",
"author_id": 14412197,
"author_profile": "https://Stackoverflow.com/users/14412197",
"pm_score": -1,
"selected": false,
"text": "<p>You could use <a href=\"https://github.com/flew-software/trash-dump\" rel=\"nofollow noreferrer\">https://github.com/flew-software/trash-dump</a>\nyou can create file that is any size and with random data</p>\n<p>heres a command you can run after installing trash-dump (creates a 1GB file)</p>\n<pre><code>$ trash-dump --filename="huge" --seed=1232 --noBytes=1000000000\n</code></pre>\n<p>BTW I created it</p>\n"
},
{
"answer_id": 71944464,
"author": "Mike S",
"author_id": 3768749,
"author_profile": "https://Stackoverflow.com/users/3768749",
"pm_score": 0,
"selected": false,
"text": "<p>So I wanted to create a large file with repeated ascii strings. "Why?" you may ask. Because I need to use it for some NFS troubleshooting I'm doing. I need the file to be compressible because I'm sharing a tcpdump of a file copy with the vendor of our NAS. I had originally created a 1g file filled with random data from /dev/urandom, but of course since it's random, it means it won't compress at all and I need to send the full 1g of data to the vendor, which is difficult.</p>\n<p>So I created a file with all the printable ascii characters, repeated over and over, to a limit of 1g in size. I was worried it would take a long time. It actually went amazingly quickly, IMHO:</p>\n<pre><code>cd /dev/shm\ndate\ntime yes $(for ((i=32;i<127;i++)) do printf "\\\\$(printf %03o "$i")"; done) | head -c 1073741824 > ascii1g_file.txt\ndate\n\nWed Apr 20 12:30:13 CDT 2022\n\nreal 0m0.773s\nuser 0m0.060s\nsys 0m1.195s\nWed Apr 20 12:30:14 CDT 2022\n</code></pre>\n<p>Copying it from an nfs partition to /dev/shm took just as long as with the random file (which one would expect, I know, but I wanted to be sure):</p>\n<pre><code>cp ascii1gfile.txt /home/greygnome/\nuptime; free -m; sync; echo 1 > /proc/sys/vm/drop_caches; free -m; date; dd if=/home/greygnome/ascii1gfile.txt of=/dev/shm/outfile bs=16384 2>&1; date; rm -f /dev/shm/outfile \n</code></pre>\n<p>But while doing that I ran a simultaneous tcpdump:</p>\n<pre><code>tcpdump -i em1 -w /dev/shm/dump.pcap\n</code></pre>\n<p>I was able to compress the pcap file down to 12M in size! Awesomesauce!</p>\n<p>Edit: Before you ding me because the OP said, "I don't care about the contents," know that I posted this answer because it's one of the first replies to "how to create a large file linux" in a Google search. And sometimes, disregarding the contents of a file can have unforeseen side effects.\nEdit 2: And <code>fallocate</code> seems to be unavailable on a number of filesystems, and creating a 1GB compressible file in 1.2s seems pretty decent to me (aka, "quickly").</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17007/"
] |
How can I **quickly** create a large file on a Linux ([Red Hat Linux](http://en.wikipedia.org/wiki/Red_Hat_Linux)) system?
[dd](http://en.wikipedia.org/wiki/Dd_%28Unix%29) will do the job, but reading from `/dev/zero` and writing to the drive can take a long time when you need a file several hundreds of GBs in size for testing... If you need to do that repeatedly, the time really adds up.
I don't care about the contents of the file, I just want it to be created quickly. How can this be done?
Using a sparse file won't work for this. I need the file to be allocated disk space.
|
`dd` from the other answers is a good solution, but it is slow for this purpose. In Linux (and other POSIX systems), we have `fallocate`, which uses the desired space without having to actually writing to it, works with most modern disk based file systems, very fast:
For example:
```
fallocate -l 10G gentoo_root.img
```
|
257,855 |
<p>In my fieldset I have labels next (side) to my textboxes, but for some reason, they are towards the top and not middle. Here is my CSS for the fieldset:</p>
<pre><code>fieldset {
clear: both;
font-size: 100%;
border-color: #000000;
border-width: 1px 0 0 0;
border-style: solid none none none;
padding: 10px;
margin: 0 0 0 0;
}
label
{
font: bold 12px Verdana, Arial, Helvetica, sans-serif, MS UI Gothic;
float: left;
width: 12em;
text-align:right;
vertical-align:text-bottom;
}
</code></pre>
<p>What am I missing?</p>
|
[
{
"answer_id": 257860,
"author": "Zack The Human",
"author_id": 18265,
"author_profile": "https://Stackoverflow.com/users/18265",
"pm_score": 3,
"selected": true,
"text": "<p>Try adjusting the <strong>line-height</strong> property for the label element. You may need to increase or decrease it.</p>\n"
},
{
"answer_id": 257910,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": -1,
"selected": false,
"text": "<p>To me this is the most frustrating thing about css... \nZack is right it will probably take some tweaking with the line-height, sometimes <b>lots</b> of tweaking (like 20px). i think that floating the element causes line height to be difficult?? \nif you want it in the middle of the line you should set vertical-align:middle; too. </p>\n\n<p>hope this helps...</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257855",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
In my fieldset I have labels next (side) to my textboxes, but for some reason, they are towards the top and not middle. Here is my CSS for the fieldset:
```
fieldset {
clear: both;
font-size: 100%;
border-color: #000000;
border-width: 1px 0 0 0;
border-style: solid none none none;
padding: 10px;
margin: 0 0 0 0;
}
label
{
font: bold 12px Verdana, Arial, Helvetica, sans-serif, MS UI Gothic;
float: left;
width: 12em;
text-align:right;
vertical-align:text-bottom;
}
```
What am I missing?
|
Try adjusting the **line-height** property for the label element. You may need to increase or decrease it.
|
257,872 |
<p>I want to force Apache to use HTTPS for a particular URL in the following form:</p>
<pre><code>https://www.example.com/signup/*
</code></pre>
<p>so</p>
<p>if someone goes to any of the following example URLs directly, Apache will forward the URL over to the HTTPS equivalent site.</p>
<p>e.g.</p>
<pre><code>http://www.example.com/signup --> https://www.example.com/signup
http://www.example.com/signup/basic+plan --> https://www.example.com/signup/basic+plan
http://www.example.com/signup/premium --> https://www.example.com/signup/premium
</code></pre>
<p>Anyone know how?</p>
<p>Thanks in advance</p>
|
[
{
"answer_id": 257875,
"author": "hayalci",
"author_id": 16084,
"author_profile": "https://Stackoverflow.com/users/16084",
"pm_score": 1,
"selected": false,
"text": "<p>You should take a look at <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html\" rel=\"nofollow noreferrer\">mod_rewrite</a> documentation</p>\n"
},
{
"answer_id": 257878,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the <a href=\"http://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirect\" rel=\"nofollow noreferrer\">Redirect</a> directive:</p>\n\n<pre><code>Redirect 301 /signup https://www.example.com/signup\n</code></pre>\n\n<p>This will automatically preserve anything following /signup in the URL. Be sure to configure this directive only on your non-SSL site, or it might get into a recursive loop!</p>\n"
},
{
"answer_id": 257898,
"author": "Bill B",
"author_id": 27088,
"author_profile": "https://Stackoverflow.com/users/27088",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this with mod_rewrite -</p>\n\n<p>RewriteCond %{SERVER_PORT} !^443$</p>\n\n<p>RewriteRule ^/signup <a href=\"https://example.com/signup\" rel=\"nofollow noreferrer\">https://example.com/signup</a></p>\n\n<p>RewriteRule ^/signup/(.*)$ <a href=\"https://example.com/signup/\" rel=\"nofollow noreferrer\">https://example.com/signup/</a>$1</p>\n\n<p>Should work, though I haven't tested it.</p>\n\n<p>-- edit --</p>\n\n<p>Correction, I just tried this on one of my servers, and it works fine for me. You may want to doublecheck your mod_rewrite configuration. Also, if you're using .htaccess, you'll want to make sure overrides are allowed for that directory.</p>\n\n<p>As a side note, this assumes your SSL traffic is coming over port 443. If it isn't, you'll need to adjust the rewrite condition accordingly.</p>\n"
},
{
"answer_id": 257932,
"author": "Murat Ayfer",
"author_id": 25910,
"author_profile": "https://Stackoverflow.com/users/25910",
"pm_score": 2,
"selected": false,
"text": "<p>I think this was what i used:</p>\n\n<pre><code>RewriteEngine On \nRewriteCond %{SERVER_PORT} 80 \nRewriteCond %{REQUEST_URI} ^/somefolder/?\nRewriteRule ^(.*)$ https://www.domain.com/somefolder/$1 [R,L]\n</code></pre>\n\n<p>(from <a href=\"http://www.besthostratings.com/articles/force-ssl-htaccess.html\" rel=\"nofollow noreferrer\">here</a>)</p>\n"
},
{
"answer_id": 258923,
"author": "Timmy_",
"author_id": 33554,
"author_profile": "https://Stackoverflow.com/users/33554",
"pm_score": 3,
"selected": false,
"text": "<p>Thank Murat,</p>\n\n<p>Yours almost worked but figured out how to get it to exactly work.</p>\n\n<p>The following is what works:</p>\n\n<pre><code>RewriteCond %{SERVER_PORT} 80 \nRewriteCond %{REQUEST_URI} ^/somefolder/?\nRewriteRule ^(.*)$ https://www.domain.com/$1 [R,L]\n</code></pre>\n\n<p>Notice that I didn't include somefolder in the www.domain.com rewriterule</p>\n"
},
{
"answer_id": 693182,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I used the following to require the checkout section of a website to require SSL:</p>\n\n<pre><code><Directory \"/var/www/html\">\n RewriteEngine on\n Options +FollowSymLinks\n Order allow,deny\n Allow from all\n RewriteCond %{SERVER_PORT} !^443$\n RewriteRule \\.(gif|jpg|jpeg|jpe|png|css|js)$ - [S=1]\n RewriteRule ^checkout(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n</Directory>\n</code></pre>\n\n<p>So for example, hitting <a href=\"http://www.example.com/checkout\" rel=\"nofollow noreferrer\">http://www.example.com/checkout</a> redirects to <a href=\"https://www.example.com/checkout\" rel=\"nofollow noreferrer\">https://www.example.com/checkout</a></p>\n\n<p>The rule will skip file extensions that are typically included within a page so that you don't get mixed content warnings. You should add to this list as necessary.</p>\n\n<p>If you want multiple pages change the RewriteRule to something like:</p>\n\n<pre><code>RewriteRule ^(checkout|login)(.*)$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n</code></pre>\n\n<p>Of course, the directory should match the actual path on your server. This page may also help with some more information for your specific needs: <a href=\"http://www.whoopis.com/howtos/apache-rewrite.html\" rel=\"nofollow noreferrer\">http://www.whoopis.com/howtos/apache-rewrite.html</a></p>\n\n<p>I'm using this on a website that runs Plesk 8.6 but that shouldn't matter. This is in my vhost.conf file which is like putting it in your httpd.conf file. I'm not sure if you'd need to adjust anything to use it in a .htaccess file but I doubt it. If adding to a conf file don't forget to restart apache to reload the configuration.</p>\n\n<p>If you are like me and want to use SSL only on particular pages then you also want a rewrite rule that sends you back to regular http for the rest. You can use the following for the reverse effect:</p>\n\n<pre><code>RewriteCond %{SERVER_PORT} ^443$\nRewriteRule \\.(gif|jpg|jpeg|jpe|png|css|js)$ - [S=1]\nRewriteRule !^(checkout|login)(.*)$ http://%{SERVER_NAME}%{REQUEST_URI} [L,R]\n</code></pre>\n\n<p>If you are using Plesk like I am keep in mind that all non-SSL traffic uses the vhost.conf file but all SSL traffic uses the vhost_ssl.conf file. That means your first rewrite rule to require SSL would go in the vhost.conf file but the second rule to force back to non-SSL will have to go in the vhost_ssl file. If you are using httpd.conf or .htaccess I think you can put them both in the same place.</p>\n\n<p>I've also posted this tutorial on my blog: <a href=\"http://www.jonathandean.com/2009/03/apache-rewrite-rules-to-force-securenon-secure-pages/\" rel=\"nofollow noreferrer\">Apache rewrite rules to force secure/non-secure pages</a>.</p>\n"
},
{
"answer_id": 51480769,
"author": "RobbySherwood",
"author_id": 3320453,
"author_profile": "https://Stackoverflow.com/users/3320453",
"pm_score": 0,
"selected": false,
"text": "<p>.htaccess files are normally placed in a scope with Options -FollowSymLinks, which blocks Rewrite rules. This is often a security rule.</p>\n\n<p>So a more trivial thing is often needed like this one:</p>\n\n<pre><code><If \"%{HTTPS} != 'on'\">\n Redirect 301 /your/path https://www.example.com/your/path\n</If>\n</code></pre>\n\n<p>This is a small enhancement to the answer of Greg Hewgill.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33554/"
] |
I want to force Apache to use HTTPS for a particular URL in the following form:
```
https://www.example.com/signup/*
```
so
if someone goes to any of the following example URLs directly, Apache will forward the URL over to the HTTPS equivalent site.
e.g.
```
http://www.example.com/signup --> https://www.example.com/signup
http://www.example.com/signup/basic+plan --> https://www.example.com/signup/basic+plan
http://www.example.com/signup/premium --> https://www.example.com/signup/premium
```
Anyone know how?
Thanks in advance
|
Thank Murat,
Yours almost worked but figured out how to get it to exactly work.
The following is what works:
```
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/somefolder/?
RewriteRule ^(.*)$ https://www.domain.com/$1 [R,L]
```
Notice that I didn't include somefolder in the www.domain.com rewriterule
|
257,877 |
<p>I want to trim trailing whitespace at the end of all XHTML paragraphs. I am using Ruby with the REXML library.</p>
<p>Say I have the following in a valid XHTML file:</p>
<pre><code><p>hello <span>world</span> a </p>
<p>Hi there </p>
<p>The End </p>
</code></pre>
<p>I want to end up with this:</p>
<pre><code><p>hello <span>world</span> a</p>
<p>Hi there</p>
<p>The End</p>
</code></pre>
<p>So I was thinking I could use XPath to get just the text nodes that I want, then trim the text, which would allow me to end up with what I want (previous).</p>
<p>I started with the following XPath:</p>
<pre><code>//root/p/child::text()
</code></pre>
<p>Of course, the problem here is that it returns all text nodes that are children of all p-tags. Which is this:</p>
<pre><code>'hello '
' a '
'Hi there '
'The End '
</code></pre>
<p>Trying the following XPath gives me the last text node of the last paragraph, not the last text node of each paragraph that is a child of the root node.</p>
<pre><code>//root/p/child::text()[last()]
</code></pre>
<p>This only returns: <code>'The End '</code></p>
<p>What I would like to get from the XPath is therefore:</p>
<pre><code>' a '
'Hi there '
'The End '
</code></pre>
<p>Can I do this with XPath? Or should I maybe be looking at using regular expressions (That's probably more of a headache than XPath)?</p>
|
[
{
"answer_id": 257917,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": true,
"text": "<p>Your example worked for me</p>\n\n<pre>//p/child::text()[last()]</pre>\n"
},
{
"answer_id": 258030,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 1,
"selected": false,
"text": "<p>Just in case you didn't know, XSL has a <code>normalize-space()</code> function which will get rid of leading and trailing spaces.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5758/"
] |
I want to trim trailing whitespace at the end of all XHTML paragraphs. I am using Ruby with the REXML library.
Say I have the following in a valid XHTML file:
```
<p>hello <span>world</span> a </p>
<p>Hi there </p>
<p>The End </p>
```
I want to end up with this:
```
<p>hello <span>world</span> a</p>
<p>Hi there</p>
<p>The End</p>
```
So I was thinking I could use XPath to get just the text nodes that I want, then trim the text, which would allow me to end up with what I want (previous).
I started with the following XPath:
```
//root/p/child::text()
```
Of course, the problem here is that it returns all text nodes that are children of all p-tags. Which is this:
```
'hello '
' a '
'Hi there '
'The End '
```
Trying the following XPath gives me the last text node of the last paragraph, not the last text node of each paragraph that is a child of the root node.
```
//root/p/child::text()[last()]
```
This only returns: `'The End '`
What I would like to get from the XPath is therefore:
```
' a '
'Hi there '
'The End '
```
Can I do this with XPath? Or should I maybe be looking at using regular expressions (That's probably more of a headache than XPath)?
|
Your example worked for me
```
//p/child::text()[last()]
```
|
257,901 |
<p>I'm using this script to display all the images in a folder, but I can't figure out how to get each image's file name to display underneath it. Any suggestions?</p>
<pre><code><?php
$dirname = "images";
$images = scandir($dirname);
$ignore = Array(".", "..", "otherfiletoignore");
foreach($images as $curimg){
if (!in_array($curimg, $ignore)) {
echo "<img src='images/$curimg' /><br />\n";
}
}
?>
</code></pre>
|
[
{
"answer_id": 257904,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": true,
"text": "<pre><code>echo \"<img src='images/$curimg' /><br />$curimg<br />\\n\";\n</code></pre>\n"
},
{
"answer_id": 257912,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I think nickf's suggestion is the simplest thing you can do achieve what you want without any css or complex structure..</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32972/"
] |
I'm using this script to display all the images in a folder, but I can't figure out how to get each image's file name to display underneath it. Any suggestions?
```
<?php
$dirname = "images";
$images = scandir($dirname);
$ignore = Array(".", "..", "otherfiletoignore");
foreach($images as $curimg){
if (!in_array($curimg, $ignore)) {
echo "<img src='images/$curimg' /><br />\n";
}
}
?>
```
|
```
echo "<img src='images/$curimg' /><br />$curimg<br />\n";
```
|
257,902 |
<p>I have seen lots of chat examples in Erlang but what about lists, like a work queue? If I want to build a work queue system, like a project management system, is it possible to re-order messages in a process mailbox or do I have to use message priorities? Are there examples of workflow systems built in Erlang?</p>
|
[
{
"answer_id": 258348,
"author": "Adam Lindberg",
"author_id": 2457,
"author_profile": "https://Stackoverflow.com/users/2457",
"pm_score": 4,
"selected": true,
"text": "<p>You cannot reorder messages in process message queues in Erlang.</p>\n\n<p>You can, however do selective receives in which you can receive the message you deem most important first. It's not entirely the same but works for most purposes.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>receive\n {important, Msg} ->\n handle(Msg)\nafter 0 ->\n ok\nend,\nreceive\n OtherMsg ->\n handle(Msg)\nend\n</code></pre>\n\n<p>It differs from:</p>\n\n<pre><code>receive\n {important, Msg} ->\n handle(Msg);\n OtherMsg ->\n handle(Msg)\nend\n</code></pre>\n\n<p>In that it will always scan the whole message queue for <code>{important, Msg}</code> before continuing handling the rest of the messages. It means that those kinds of messages will always be handled before any others, if they exist. This of course comes at some performance cost (it takes more time scanning the whole queue twice).</p>\n"
},
{
"answer_id": 286057,
"author": "Justin Sheehy",
"author_id": 11944,
"author_profile": "https://Stackoverflow.com/users/11944",
"pm_score": 2,
"selected": false,
"text": "<p>Process mailboxes work quite well as-is for job queues.</p>\n\n<p>Just have your messages include sufficient information so that selective receive patterns are easy to write, and you won't feel the need to re-order mailbox contents.</p>\n"
},
{
"answer_id": 286102,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 2,
"selected": false,
"text": "<p>If you do need to reorder messages, you can follow the gatekeeper pattern: reify the mailbox as a separate process. When your original process is ready for another message, the gatekeeper can compute which message to forward, by any rule you choose.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32829/"
] |
I have seen lots of chat examples in Erlang but what about lists, like a work queue? If I want to build a work queue system, like a project management system, is it possible to re-order messages in a process mailbox or do I have to use message priorities? Are there examples of workflow systems built in Erlang?
|
You cannot reorder messages in process message queues in Erlang.
You can, however do selective receives in which you can receive the message you deem most important first. It's not entirely the same but works for most purposes.
Here's an example:
```
receive
{important, Msg} ->
handle(Msg)
after 0 ->
ok
end,
receive
OtherMsg ->
handle(Msg)
end
```
It differs from:
```
receive
{important, Msg} ->
handle(Msg);
OtherMsg ->
handle(Msg)
end
```
In that it will always scan the whole message queue for `{important, Msg}` before continuing handling the rest of the messages. It means that those kinds of messages will always be handled before any others, if they exist. This of course comes at some performance cost (it takes more time scanning the whole queue twice).
|
257,906 |
<p>The activity monitor in sql2k8 allows us to see the most expensive queries. Ok, that's cool, but is there a way I can log this info or get this info via query analyser? I don't really want to have the Sql Management console open and me looking at the activity monitor dashboard.</p>
<p>I want to figure out which queries are poorly written/schema is poorly designed, etc.</p>
<p>Thanks heaps for any help!</p>
|
[
{
"answer_id": 257924,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "<p>Would the SQL Server Profiler do what you need? I haven't used 2008 yet so I don't know if the tool is still in there but if it is I believe you can set up a trace to log queries that meet specific criteria (such as those that execute and drive CPU up above a certain threshold).</p>\n\n<p>We've used this on our project and it did a pretty good job of helping us troubleshoot poorly executing queries (though don't leave it on full time, rely on the general Windows Performance Counters for performance health tracking).</p>\n"
},
{
"answer_id": 257944,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 7,
"selected": true,
"text": "<ol>\n<li><p>Use SQL Server Profiler (on the tools menu in SSMS) to create a trace that logs these events:</p>\n\n<pre><code> RPC:Completed\n SP:Completed\n SP:StmtCompleted\n SQL:BatchCompleted\n SQL:StmtCompleted\n</code></pre></li>\n<li><p>You can start with the standard trace template and prune it. You didn't specify whether this was for a specific database or the whole server, if it is for specific Db's, include the DatabaseID column and set a filter to your DB (<code>SELECT DB_ID('dbname')</code>). Make sure the logical Reads data column is included for each event. Set the trace to log to a file. If you are leaving this trace to run unattended in the background, it is a good idea to set a maximum trace file size say 500MB or 1GB if you have plenty of room (it all depends on how much activity there is on the server, so you will have to suck it and see).</p></li>\n<li><p>Briefly start the trace and then pause it. Goto File->Export->Script Trace Definition and pick your DB version, and save to a file. You now have a sql script that creates a trace that has much less overhead than running through the profiler GUI. When you run this script it will output the Trace ID (usually <code>@ID=2</code>); note this down.</p></li>\n<li><p>Once you have a trace file (.trc) (either the trace completed due to reaching the max file size or you stopped the running trace using</p>\n\n<p>EXEC sp_trace_setstatus @ID, 0<br>\n EXEC sp_trace_setstatus @ID, 2</p></li>\n</ol>\n\n<p>You can load the trace into profiler, or use <a href=\"http://www.cleardata.biz/cleartrace/\" rel=\"noreferrer\">ClearTrace</a> (very handy) or load it into a table like so:</p>\n\n<pre><code>SELECT * INTO TraceTable\nFROM ::fn_trace_gettable('C:\\location of your trace output.trc', default)\n</code></pre>\n\n<p>Then you can run a query to aggregate the data such as this one:</p>\n\n<pre><code>SELECT COUNT(*) AS TotalExecutions, \n EventClass, CAST(TextData as nvarchar(2000))\n ,SUM(Duration) AS DurationTotal\n ,SUM(CPU) AS CPUTotal\n ,SUM(Reads) AS ReadsTotal\n ,SUM(Writes) AS WritesTotal\nFROM TraceTable\nGROUP BY EventClass, CAST(TextData as nvarchar(2000))\nORDER BY ReadsTotal DESC\n</code></pre>\n\n<p>Once you have identified the costly queries, you can generate and examine the actual execution plans.</p>\n"
},
{
"answer_id": 1892024,
"author": "Tom Lianza",
"author_id": 26624,
"author_profile": "https://Stackoverflow.com/users/26624",
"pm_score": 2,
"selected": false,
"text": "<p>I had never heard of this tool before, but Microsoft provides a set of reports that do a fantastic job of giving you exactly this - including slowest queries. Check out their <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=1d3a4a0d-7e0c-4730-8204-e419218c1efc&displaylang=en\" rel=\"nofollow noreferrer\">Performance Dashboard Reports</a>.</p>\n\n<p>Not sure if they're SQL 2008-compatible, but worth checking out.</p>\n"
},
{
"answer_id": 5729147,
"author": "jaraics",
"author_id": 113108,
"author_profile": "https://Stackoverflow.com/users/113108",
"pm_score": 2,
"selected": false,
"text": "<p>There's a new tool, <a href=\"http://blogs.technet.com/b/rob/archive/2008/06/20/sql-server-2008-performance-studio.aspx\" rel=\"nofollow\">Performance Studio</a> in SQL Server 2008 which builds on top of Dynamic Management Views maintained automatically by the server, that gives an overview of the server performance. It worth checking out.</p>\n"
},
{
"answer_id": 8285345,
"author": "gngolakia",
"author_id": 1050111,
"author_profile": "https://Stackoverflow.com/users/1050111",
"pm_score": 5,
"selected": false,
"text": "<p>The Following script gives you the result.</p>\n\n<pre><code>SELECT TOP 10 \nSUBSTRING(qt.TEXT, (qs.statement_start_offset/2)+1,\n((CASE qs.statement_end_offset\nWHEN -1 THEN DATALENGTH(qt.TEXT)\nELSE qs.statement_end_offset\nEND - qs.statement_start_offset)/2)+1),\nqs.execution_count,\nqs.total_logical_reads, \nqs.last_logical_reads,\nqs.total_logical_writes, qs.last_logical_writes,\nqs.total_worker_time,\nqs.last_worker_time,\nqs.total_elapsed_time/1000000 total_elapsed_time_in_S,\nqs.last_elapsed_time/1000000 last_elapsed_time_in_S,\nqs.last_execution_time,qp.query_plan\nFROM sys.dm_exec_query_stats qs\nCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) qt\nCROSS APPLY sys.dm_exec_query_plan(qs.plan_handle) qp\nORDER BY qs.total_logical_reads DESC \n</code></pre>\n"
},
{
"answer_id": 17104492,
"author": "user2485339",
"author_id": 2485339,
"author_profile": "https://Stackoverflow.com/users/2485339",
"pm_score": 0,
"selected": false,
"text": "<p>(DELL)Quest SQL Optimizer for SQL Server 9.0 introduces Find SQL module which allow users to locate the most resource-intensive SQL in your SQL Server.\n<a href=\"https://support.quest.com/softwaredownloads.aspx?pr=268445262\" rel=\"nofollow\">https://support.quest.com/softwaredownloads.aspx?pr=268445262</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
The activity monitor in sql2k8 allows us to see the most expensive queries. Ok, that's cool, but is there a way I can log this info or get this info via query analyser? I don't really want to have the Sql Management console open and me looking at the activity monitor dashboard.
I want to figure out which queries are poorly written/schema is poorly designed, etc.
Thanks heaps for any help!
|
1. Use SQL Server Profiler (on the tools menu in SSMS) to create a trace that logs these events:
```
RPC:Completed
SP:Completed
SP:StmtCompleted
SQL:BatchCompleted
SQL:StmtCompleted
```
2. You can start with the standard trace template and prune it. You didn't specify whether this was for a specific database or the whole server, if it is for specific Db's, include the DatabaseID column and set a filter to your DB (`SELECT DB_ID('dbname')`). Make sure the logical Reads data column is included for each event. Set the trace to log to a file. If you are leaving this trace to run unattended in the background, it is a good idea to set a maximum trace file size say 500MB or 1GB if you have plenty of room (it all depends on how much activity there is on the server, so you will have to suck it and see).
3. Briefly start the trace and then pause it. Goto File->Export->Script Trace Definition and pick your DB version, and save to a file. You now have a sql script that creates a trace that has much less overhead than running through the profiler GUI. When you run this script it will output the Trace ID (usually `@ID=2`); note this down.
4. Once you have a trace file (.trc) (either the trace completed due to reaching the max file size or you stopped the running trace using
EXEC sp\_trace\_setstatus @ID, 0
EXEC sp\_trace\_setstatus @ID, 2
You can load the trace into profiler, or use [ClearTrace](http://www.cleardata.biz/cleartrace/) (very handy) or load it into a table like so:
```
SELECT * INTO TraceTable
FROM ::fn_trace_gettable('C:\location of your trace output.trc', default)
```
Then you can run a query to aggregate the data such as this one:
```
SELECT COUNT(*) AS TotalExecutions,
EventClass, CAST(TextData as nvarchar(2000))
,SUM(Duration) AS DurationTotal
,SUM(CPU) AS CPUTotal
,SUM(Reads) AS ReadsTotal
,SUM(Writes) AS WritesTotal
FROM TraceTable
GROUP BY EventClass, CAST(TextData as nvarchar(2000))
ORDER BY ReadsTotal DESC
```
Once you have identified the costly queries, you can generate and examine the actual execution plans.
|
257,993 |
<p>I am a trying to learn C# .Net.</p>
<p>I had written small (hobby) Analog Clock application in VB sometime ago(edit: VB6, to be precise), and I thought I will rewrite in C#.NET, as part of my <em>learning</em> process.</p>
<p>In the VB application, I drew the hands of the clock in XOR Drawmode, so that I have to <em>move</em> the second hand, I just had to redraw it in the previous position and then draw the current position - I need not refresh the whole Form. All I did was </p>
<pre><code>Me.DrawMode = vbNotXorPen
</code></pre>
<p>and then</p>
<pre><code>Me.Line...
</code></pre>
<p>on a VB Form</p>
<p>In C# I don't find an equivalent Xor Pen Draw mode.</p>
<p>I found</p>
<pre><code>ControlPaint.DrawReversibleLine
</code></pre>
<p>somewhere on the net, but I am not sure whether <code>ControlPaint</code> is meant for such purposes (and I don't understand based on what co-ordinate system <code>ControlPaint</code> is drawing)</p>
<p>Is there an equivalent to XOR drawing in C#.NET?
Or is there a better way to do what I am doing (with the best performance)</p>
<p>(Both VB and C# are my hobbies. So feel free to correct me wherever I am wrong)</p>
|
[
{
"answer_id": 258010,
"author": "nullDev",
"author_id": 6621,
"author_profile": "https://Stackoverflow.com/users/6621",
"pm_score": 3,
"selected": true,
"text": "<p>IMHO, until and unless you are targeting some really slow computers, you don't need to optimize performance by using XOR technique.</p>\n\n<p>Since you'd be drawing the second hand only once in a second, a complete redraw of the clock would be much better. Also, the second hand will \"look\" good if drawn directly, and use smoothing mode set to Anti alias for a more cleaner look.</p>\n\n<p>To optimize performance, you can create a bmp for clock every one minute and then draw the second hand upon it.</p>\n"
},
{
"answer_id": 258025,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 2,
"selected": false,
"text": "<p>.NET/GDI+ does not support XOR drawing. You'll have to workaround it by using p/invoke calls of several native functions.</p>\n\n<p>See the link below for more information</p>\n\n<p><a href=\"http://www.vbaccelerator.com/home/net/code/libraries/Graphics/ZoomIn/article.asp\" rel=\"nofollow noreferrer\">http://www.vbaccelerator.com/home/net/code/libraries/Graphics/ZoomIn/article.asp</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/257993",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25949/"
] |
I am a trying to learn C# .Net.
I had written small (hobby) Analog Clock application in VB sometime ago(edit: VB6, to be precise), and I thought I will rewrite in C#.NET, as part of my *learning* process.
In the VB application, I drew the hands of the clock in XOR Drawmode, so that I have to *move* the second hand, I just had to redraw it in the previous position and then draw the current position - I need not refresh the whole Form. All I did was
```
Me.DrawMode = vbNotXorPen
```
and then
```
Me.Line...
```
on a VB Form
In C# I don't find an equivalent Xor Pen Draw mode.
I found
```
ControlPaint.DrawReversibleLine
```
somewhere on the net, but I am not sure whether `ControlPaint` is meant for such purposes (and I don't understand based on what co-ordinate system `ControlPaint` is drawing)
Is there an equivalent to XOR drawing in C#.NET?
Or is there a better way to do what I am doing (with the best performance)
(Both VB and C# are my hobbies. So feel free to correct me wherever I am wrong)
|
IMHO, until and unless you are targeting some really slow computers, you don't need to optimize performance by using XOR technique.
Since you'd be drawing the second hand only once in a second, a complete redraw of the clock would be much better. Also, the second hand will "look" good if drawn directly, and use smoothing mode set to Anti alias for a more cleaner look.
To optimize performance, you can create a bmp for clock every one minute and then draw the second hand upon it.
|
258,006 |
<p>I'm trying to play a sound file from an iPhone program.</p>
<p>Here's the code:</p>
<pre><code>NSString *path = [[NSBundle mainBundle] pathForResource:@"play" ofType:@"caf"];
NSFileHandle *bodyf = [NSFileHandle fileHandleForReadingAtPath:path];
NSData *body = [bodyf availableData];
NSLog( @"length of play.caf %d",[body length] );
NSURL *url = [NSURL fileURLWithPath:path isDirectory:NO];
NSLog( [url description] );
NSLog( @"%d", AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID) );
</code></pre>
<p>The first NSLog is to check that I have access to the file (I did), the second NSLog is to show the file URL, and the third NSLog returns -1500 "An unspecified error has occurred."</p>
<p>For the second NSLog, I get the following output:</p>
<p>file://localhost/Users/alan/Library/Application 敲慬楴敶瑓楲杮upport/iPhone蒠ꁻތĀ⾅獕牥⽳污湡䰯扩慲祲䄯灰楬慣楴湯匠灵潰瑲椯桐湯楓畭慬潴⽲獕牥䄯灰楬慣楴湯⽳䙂㕅㡂㤱䌭䐳ⴸ䐴䙃㠭㍃ⴷ䍁㈶㠵䙁㤴㈰䰯捯瑡䵥灡⽰汰祡挮晡imulator/User/Applications/BFE5B819-C3D8-4DCF-8C37-AC6258AF4902/LocateMe.app/play.caf</p>
<p>This is either due to my misunderstanding of the "description" method, or this contributes to the problem.</p>
<p>Any idea what is going wrong?</p>
|
[
{
"answer_id": 258046,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 0,
"selected": false,
"text": "<p>I tried the same with my application that plays sounds just fine. The sounds don’t play in the Simulator and when I try to <code>NSLog</code> the URL, I get the same garbage as You and <code>EXC_BAD_ACCESS</code> on the top of it. When I log the URL on the device, the URL is fine, but I get <code>EXC_BAD_ACCESS</code> nevertheless. When I drop the logging, sounds play and everything works. If somebody could explain this behaviour I’d be grateful. As for Your problem, I’d drop the logging and try the code on the device.</p>\n"
},
{
"answer_id": 259630,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 2,
"selected": false,
"text": "<p>The first parameter to NSLog is a format string; you're passing <code>[URL description]</code> as the format string to the second use of NSLog. That's bad, because if the description of the URL contains any <code>%</code> characters then it will wind up printing random stuff from the stack.</p>\n\n<p>Instead, write</p>\n\n<pre><code>NSLog(@\"%@\", URL);\n</code></pre>\n\n<p>You don't need to even use <code>-description</code> here; NSLog will invoke it for you automatically because <code>%@</code> means \"an object,\" not \"an NSString,\" and it's smart enough to do the right thing for you.</p>\n"
},
{
"answer_id": 463849,
"author": "Alan",
"author_id": 19391,
"author_profile": "https://Stackoverflow.com/users/19391",
"pm_score": 2,
"selected": true,
"text": "<p>An update on this.</p>\n\n<p>I got my keys to allow me to run my app on the device.</p>\n\n<p>I found that my .caf file successfully played when the app ran on the device.</p>\n\n<p>I then tried various alternatives.</p>\n\n<p>A .wav file that is 60 seconds long failed to work on the simulator and the device.</p>\n\n<p>A .wav file that is 5 seconds long would work on the simulator, but not on the device.</p>\n\n<p>A .aiff file that is 5 seconds long works on the simulator and the device.</p>\n\n<p>It would be good to know definitively what the simulator and the device are checking about the file when it is passed to AudioServicesCreateSystemSoundID</p>\n"
},
{
"answer_id": 809670,
"author": "Kevin Bomberry",
"author_id": 98842,
"author_profile": "https://Stackoverflow.com/users/98842",
"pm_score": 2,
"selected": false,
"text": "<p>In addition, it seems that the iPhone simulator does not like to play (systemSound) sounds over 5 seconds in length. I had the same issue as out apps almost always play a start up systemSound.</p>\n\n<p>One of the apps I was working on the simulator would not play the sound but the device would. Later I found that there is some strange limitation on the simulator and the way it handles sounds. I've filed a bug with Apple. Hopefully this will be address with the release of the iPhone SDK 3.0.</p>\n"
},
{
"answer_id": 1648133,
"author": "Biranchi",
"author_id": 97651,
"author_profile": "https://Stackoverflow.com/users/97651",
"pm_score": 0,
"selected": false,
"text": "<p>Use \"AVAudioPlayer\" class for playing .caf files</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19391/"
] |
I'm trying to play a sound file from an iPhone program.
Here's the code:
```
NSString *path = [[NSBundle mainBundle] pathForResource:@"play" ofType:@"caf"];
NSFileHandle *bodyf = [NSFileHandle fileHandleForReadingAtPath:path];
NSData *body = [bodyf availableData];
NSLog( @"length of play.caf %d",[body length] );
NSURL *url = [NSURL fileURLWithPath:path isDirectory:NO];
NSLog( [url description] );
NSLog( @"%d", AudioServicesCreateSystemSoundID((CFURLRef)url, &soundID) );
```
The first NSLog is to check that I have access to the file (I did), the second NSLog is to show the file URL, and the third NSLog returns -1500 "An unspecified error has occurred."
For the second NSLog, I get the following output:
file://localhost/Users/alan/Library/Application 敲慬楴敶瑓楲杮upport/iPhone蒠ꁻތĀ⾅獕牥⽳污湡䰯扩慲祲䄯灰楬慣楴湯匠灵潰瑲椯桐湯楓畭慬潴⽲獕牥䄯灰楬慣楴湯⽳䙂㕅㡂㤱䌭䐳ⴸ䐴䙃㠭㍃ⴷ䍁㈶㠵䙁㤴㈰䰯捯瑡䵥灡⽰汰祡挮晡imulator/User/Applications/BFE5B819-C3D8-4DCF-8C37-AC6258AF4902/LocateMe.app/play.caf
This is either due to my misunderstanding of the "description" method, or this contributes to the problem.
Any idea what is going wrong?
|
An update on this.
I got my keys to allow me to run my app on the device.
I found that my .caf file successfully played when the app ran on the device.
I then tried various alternatives.
A .wav file that is 60 seconds long failed to work on the simulator and the device.
A .wav file that is 5 seconds long would work on the simulator, but not on the device.
A .aiff file that is 5 seconds long works on the simulator and the device.
It would be good to know definitively what the simulator and the device are checking about the file when it is passed to AudioServicesCreateSystemSoundID
|
258,007 |
<p>How can I make the command button in my VC++ 6.0 dialog visible or invisible on load?</p>
|
[
{
"answer_id": 258031,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 1,
"selected": false,
"text": "<p>What do you mean by 'commnad button' exactly ? </p>\n\n<p>Anyway, you need to obtain the handle of the button then call ShowWindow function:</p>\n\n<pre><code>BOOL prevState = ShowWindow( itemHandle, SW_HIDE );\n</code></pre>\n"
},
{
"answer_id": 258209,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 2,
"selected": false,
"text": "<p>From the resource editor once you select the button, you can see its properties in the properties window. Here you can set the visible property to true / false. (assuming this functionality is present in 6.0 - i use 2003 now and cannot remember if this used to be present in 6.0)</p>\n\n<p><strong>Add CButton variable</strong> </p>\n\n<p>If you want to dynamically change the buttons visibility during load, add a variable for your button using the MFC class wizard. (you are lucky to have this - this wizard seems to have been removed from Visual Studio .NET)</p>\n\n<p><strong>Override CDialog InitDialog</strong></p>\n\n<p>Next override the initdialog function of your dialog box and then once the base InitDialog function has been successfully called, set the buttons showwindow property to SW_HIDE / before showing the dialog box. </p>\n\n<p><strong>Code</strong></p>\n\n<pre><code>BOOL CMyDialog::OnInitDialog() \n {\n CDialog::OnInitDialog();\n\n if (ConditionShow)\n m_MyButton.ShowWindow(SW_SHOW);\n else\n m_MyButton.ShowWindow(SW_HIDE);\n\n return TRUE;\n }\n</code></pre>\n"
},
{
"answer_id": 258899,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 2,
"selected": false,
"text": "<p>You can also do it without adding a CButton variable - just call</p>\n\n<p>In the OnInitDialog method of the window containing the button/control, put in code:</p>\n\n<p>CWnd *wnd = GetDlgItem (YOUR_RESOURCE_NAME_OF_THE_BUTTON)\nwnd->ShowWindow(SW_SHOW) or SW_HIDE</p>\n"
},
{
"answer_id": 44361551,
"author": "Mahbub Alam",
"author_id": 6659365,
"author_profile": "https://Stackoverflow.com/users/6659365",
"pm_score": 1,
"selected": false,
"text": "<p>Only use</p>\n\n<pre><code>ShowDlgItem(Your_DLG_ITEM_ID,1); // visible = true \nShowDlgItem(Your_DLG_ITEM_ID,0); // visible = false\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I make the command button in my VC++ 6.0 dialog visible or invisible on load?
|
From the resource editor once you select the button, you can see its properties in the properties window. Here you can set the visible property to true / false. (assuming this functionality is present in 6.0 - i use 2003 now and cannot remember if this used to be present in 6.0)
**Add CButton variable**
If you want to dynamically change the buttons visibility during load, add a variable for your button using the MFC class wizard. (you are lucky to have this - this wizard seems to have been removed from Visual Studio .NET)
**Override CDialog InitDialog**
Next override the initdialog function of your dialog box and then once the base InitDialog function has been successfully called, set the buttons showwindow property to SW\_HIDE / before showing the dialog box.
**Code**
```
BOOL CMyDialog::OnInitDialog()
{
CDialog::OnInitDialog();
if (ConditionShow)
m_MyButton.ShowWindow(SW_SHOW);
else
m_MyButton.ShowWindow(SW_HIDE);
return TRUE;
}
```
|
258,011 |
<p>I am using windsor DI framework in one of my MVC project. The project works fine when I tried to run from Visual Studio 2008.</p>
<p>But when i tried to run the project creating an application in IIS7 then I recieved the following error message:</p>
<blockquote>
<p>Looks like you forgot to register the http module
Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule Add '<add
name="PerRequestLifestyle"
type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
Castle.MicroKernel" />' to the section on your
web.config</p>
</blockquote>
<p>But this module already exists in the httpmodule section of web.config file.</p>
<p>Does anyone know what I have to do to eliminate this problem.</p>
|
[
{
"answer_id": 258063,
"author": "yfeldblum",
"author_id": 12349,
"author_profile": "https://Stackoverflow.com/users/12349",
"pm_score": 6,
"selected": true,
"text": "<p>Try adding it to the <code>system.webServer</code> section as well?</p>\n\n<pre><code><configuration>\n <system.web>\n <httpModules>\n <add name=\"PerRequestLifestyle\" type=\"...\" />\n </httpModules>\n </system.web>\n <system.webServer>\n <modules>\n <add name=\"PerRequestLifestyle\" type=\"...\" />\n </modules>\n </system.webServer>\n</configuration>\n</code></pre>\n"
},
{
"answer_id": 4179657,
"author": "Korwin",
"author_id": 507602,
"author_profile": "https://Stackoverflow.com/users/507602",
"pm_score": 2,
"selected": false,
"text": "<p>It helped me:</p>\n\n<pre><code><system.web>\n <httpModules>\n <add name=\"PerRequestLifestyle\" type=\"Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor\" />\n </httpModules>\n</system.web>\n</code></pre>\n"
},
{
"answer_id": 4968333,
"author": "David Levin",
"author_id": 571203,
"author_profile": "https://Stackoverflow.com/users/571203",
"pm_score": 6,
"selected": false,
"text": "<p>I had the same error, but it caused by another reason: </p>\n\n<p>I tried to resolve <code>IService</code> at <code>Application_Start</code> for custom route class processing, but type for <code>IService</code> was registered with <code>PerWebRequestLifestyle</code>. Routing subsystem stays at higher level that web request, and objects not exist at route processing time.</p>\n"
},
{
"answer_id": 7666018,
"author": "Maciorus",
"author_id": 878801,
"author_profile": "https://Stackoverflow.com/users/878801",
"pm_score": 2,
"selected": false,
"text": "<p>I've come across this issue in my dev enviroment. What's worth noting is this tag: </p>\n\n<pre><code> <validation validateIntegratedModeConfiguration=\"false\"/>\n</code></pre>\n\n<p>While it obviously does what it says on the tin, it can stop those pesky errors showing up. Assuming the rest of your configuration is working Ok.</p>\n\n<p>What has worked for me:</p>\n\n<pre><code><system.webServer>\n <validation validateIntegratedModeConfiguration=\"false\"/>\n <modules runAllManagedModulesForAllRequests=\"true\">\n <remove name=\"PerRequestLifestyle\"/>\n <add name=\"PerRequestLifestyle\" type=\"Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule, Castle.Windsor\"/>\n </modules>\n</system.webServer>\n</code></pre>\n"
},
{
"answer_id": 37425848,
"author": "Marvin Glenn Lacuna",
"author_id": 2705829,
"author_profile": "https://Stackoverflow.com/users/2705829",
"pm_score": -1,
"selected": false,
"text": "<p>I wrote a blog post that explains the issue in a code-level by decompiling the Castle.Windsor.dll. </p>\n\n<p><a href=\"https://sitecorelogy.com/2016/05/25/fixed-sitecore-forgot-to-register-the-http-module-castle-microkernel-lifestyle-perwebrequestlifestylemodule/\" rel=\"nofollow\">Fixed and Explained: Forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am using windsor DI framework in one of my MVC project. The project works fine when I tried to run from Visual Studio 2008.
But when i tried to run the project creating an application in IIS7 then I recieved the following error message:
>
> Looks like you forgot to register the http module
> Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule Add '<add
> name="PerRequestLifestyle"
> type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
> Castle.MicroKernel" />' to the section on your
> web.config
>
>
>
But this module already exists in the httpmodule section of web.config file.
Does anyone know what I have to do to eliminate this problem.
|
Try adding it to the `system.webServer` section as well?
```
<configuration>
<system.web>
<httpModules>
<add name="PerRequestLifestyle" type="..." />
</httpModules>
</system.web>
<system.webServer>
<modules>
<add name="PerRequestLifestyle" type="..." />
</modules>
</system.webServer>
</configuration>
```
|
258,023 |
<p>I need to create a panel which should be invisible but the components inside it (for example, JTextArea, JButton, etc.) should be visible. When I click on the invisible panel, it should become visible.</p>
<p>I can only use JRE 1.4 and nothing more than that. :(</p>
<p>Any idea how to create such a transparent panel???</p>
|
[
{
"answer_id": 258040,
"author": "gizmo",
"author_id": 9396,
"author_profile": "https://Stackoverflow.com/users/9396",
"pm_score": 3,
"selected": false,
"text": "<p><code>JComponent.setOpaque(false)</code> is the way to go.</p>\n"
},
{
"answer_id": 258041,
"author": "Peter",
"author_id": 26483,
"author_profile": "https://Stackoverflow.com/users/26483",
"pm_score": 4,
"selected": true,
"text": "<p>Transparancy is controlled with</p>\n\n<pre><code>setOpaque(false)\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22550/"
] |
I need to create a panel which should be invisible but the components inside it (for example, JTextArea, JButton, etc.) should be visible. When I click on the invisible panel, it should become visible.
I can only use JRE 1.4 and nothing more than that. :(
Any idea how to create such a transparent panel???
|
Transparancy is controlled with
```
setOpaque(false)
```
|
258,050 |
<p><code>CString</code> is quite handy, while <code>std::string</code> is more compatible with STL container. I am using <code>hash_map</code>. However, <code>hash_map</code> does not support <code>CString</code>s as keys, so I want to convert the <code>CString</code> into a <code>std::string</code>.</p>
<p>Writing a <code>CString</code> hash function seems to take a lot of time.</p>
<pre><code>CString -----> std::string
</code></pre>
<p>How can I do this?</p>
<pre><code>std::string -----> CString:
inline CString toCString(std::string const& str)
{
return CString(str.c_str());
}
</code></pre>
<p>Am I right?</p>
<hr />
<p><strong>EDIT:</strong></p>
<p>Here are more questions:</p>
<p>How can I convert from <code>wstring</code> to <code>CString</code> and vice versa?</p>
<pre><code>// wstring -> CString
std::wstring src;
CString result(src.c_str());
// CString -> wstring
CString src;
std::wstring des(src.GetString());
</code></pre>
<p>Is there any problem with this?</p>
<p>Additionally, how can I convert from <code>std::wstring</code> to <code>std::string</code> and vice versa?</p>
|
[
{
"answer_id": 258052,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": true,
"text": "<p>According to <a href=\"http://www.codeguru.com/forum/archive/index.php/t-231155.html\" rel=\"noreferrer\">CodeGuru</a>:</p>\n\n<p><code>CString</code> to <code>std::string</code>:</p>\n\n<pre><code>CString cs(\"Hello\");\nstd::string s((LPCTSTR)cs);\n</code></pre>\n\n<p><strong>BUT:</strong> <code>std::string</code> cannot always construct from a <code>LPCTSTR</code>. i.e. the code will fail for UNICODE builds.</p>\n\n<p>As <code>std::string</code> can construct only from <code>LPSTR</code> / <code>LPCSTR</code>, a programmer who uses VC++ 7.x or better can utilize conversion classes such as <code>CT2CA</code> as an intermediary.</p>\n\n<pre><code>CString cs (\"Hello\");\n// Convert a TCHAR string to a LPCSTR\nCT2CA pszConvertedAnsiString (cs);\n// construct a std::string using the LPCSTR input\nstd::string strStd (pszConvertedAnsiString);\n</code></pre>\n\n<p><a href=\"http://cstrings.blogspot.com/2006/08/how-to-convert-from-stdstring-to.html\" rel=\"noreferrer\"><code>std::string</code> to <code>CString</code></a>: (From <a href=\"http://cstrings.blogspot.com/2006/08/how-to-convert-from-stdstring-to.html\" rel=\"noreferrer\">Visual Studio's CString FAQs...</a>)</p>\n\n<pre><code>std::string s(\"Hello\");\nCString cs(s.c_str());\n</code></pre>\n\n<p><code>CStringT</code> can construct from both character or wide-character strings. i.e. It can convert from <code>char*</code> (i.e. <code>LPSTR</code>) or from <code>wchar_t*</code> (<code>LPWSTR</code>).</p>\n\n<p>In other words, char-specialization (of <code>CStringT</code>) i.e. <code>CStringA</code>, <code>wchar_t</code>-specilization <code>CStringW</code>, and <code>TCHAR</code>-specialization <code>CString</code> can be constructed from either <code>char</code> or wide-character, <del>null terminated (null-termination is very important here)</del> string sources.<br>\nAlthoug <a href=\"https://stackoverflow.com/users/1889329/iinspectable\">IInspectable</a> amends the \"null-termination\" part <a href=\"https://stackoverflow.com/questions/258050/how-to-convert-cstring-and-stdstring-stdwstring-to-each-other/258052?noredirect=1#comment29168168_258052\">in the comments</a>:</p>\n\n<blockquote>\n <p><strong>NUL-termination is not required</strong>.<br>\n <code>CStringT</code> has conversion constructors that take an explicit length argument. This also means that you can construct <code>CStringT</code> objects from <code>std::string</code> objects with embedded <code>NUL</code> characters.</p>\n</blockquote>\n"
},
{
"answer_id": 258217,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 5,
"selected": false,
"text": "<p>Solve that by using <code>std::basic_string<TCHAR></code> instead of <code>std::string</code> and it should work fine regardless of your character setting.</p>\n"
},
{
"answer_id": 568867,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": -1,
"selected": false,
"text": "<p>If you're looking to convert easily between other strings types, perhaps the <a href=\"http://msdn.microsoft.com/en-us/library/zthfhkd6(VS.71).aspx\" rel=\"nofollow noreferrer\"><code>_bstr_t</code></a> class would be more appropriate? It supports converstion between <code>char</code>, <code>wchar_t</code> and <code>BSTR</code>.</p>\n"
},
{
"answer_id": 1116184,
"author": "thehouse",
"author_id": 67013,
"author_profile": "https://Stackoverflow.com/users/67013",
"pm_score": 3,
"selected": false,
"text": "<p>If you want something more C++-like, this is what I use. Although it depends on Boost, that's just for exceptions. You can easily remove those leaving it to depend only on the STL and the <code>WideCharToMultiByte()</code> Win32 API call.</p>\n\n<pre><code>#include <string>\n#include <vector>\n#include <cassert>\n#include <exception>\n\n#include <boost/system/system_error.hpp>\n#include <boost/integer_traits.hpp>\n\n/**\n * Convert a Windows wide string to a UTF-8 (multi-byte) string.\n */\nstd::string WideStringToUtf8String(const std::wstring& wide)\n{\n if (wide.size() > boost::integer_traits<int>::const_max)\n throw std::length_error(\n \"Wide string cannot be more than INT_MAX characters long.\");\n if (wide.size() == 0)\n return \"\";\n\n // Calculate necessary buffer size\n int len = ::WideCharToMultiByte(\n CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()), \n NULL, 0, NULL, NULL);\n\n // Perform actual conversion\n if (len > 0)\n {\n std::vector<char> buffer(len);\n len = ::WideCharToMultiByte(\n CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()),\n &buffer[0], static_cast<int>(buffer.size()), NULL, NULL);\n if (len > 0)\n {\n assert(len == static_cast<int>(buffer.size()));\n return std::string(&buffer[0], buffer.size());\n }\n }\n\n throw boost::system::system_error(\n ::GetLastError(), boost::system::system_category);\n}\n</code></pre>\n"
},
{
"answer_id": 6227932,
"author": "Salman Marvasti",
"author_id": 782787,
"author_profile": "https://Stackoverflow.com/users/782787",
"pm_score": 3,
"selected": false,
"text": "<p>It is more efficient to convert <code>CString</code> to <code>std::string</code> using the conversion where the length is specified.</p>\n<pre><code>CString someStr("Hello how are you");\nstd::string std(someStr, someStr.GetLength());\n</code></pre>\n<p>In a tight loop, this makes a significant performance improvement.</p>\n"
},
{
"answer_id": 33627524,
"author": "user5546107",
"author_id": 5546107,
"author_profile": "https://Stackoverflow.com/users/5546107",
"pm_score": -1,
"selected": false,
"text": "<p>Works for me:</p>\n\n<pre><code>std::wstring CStringToWString(const CString& s)\n{\n std::string s2;\n s2 = std::string((LPCTSTR)s);\n return std::wstring(s2.begin(),s2.end());\n}\n\nCString WStringToCString(std::wstring s)\n{\n std::string s2;\n s2 = std::string(s.begin(),s.end());\n return s2.c_str();\n}\n</code></pre>\n"
},
{
"answer_id": 35925070,
"author": "Neil",
"author_id": 620612,
"author_profile": "https://Stackoverflow.com/users/620612",
"pm_score": 1,
"selected": false,
"text": "<p>This is a follow up to Sal's answer, where he/she provided the solution:</p>\n\n<pre><code>CString someStr(\"Hello how are you\");\nstd::string std(somStr, someStr.GetLength());\n</code></pre>\n\n<p>This is useful also when converting a non-typical C-String to a std::string</p>\n\n<p>A use case for me was having a pre-allocated char array (like C-String), but it's not NUL terminated. (i.e. SHA digest).\nThe above syntax allows me to specify the length of the SHA digest of the char array so that std::string doesn't have to look for the terminating NUL char, which may or may not be there.</p>\n\n<p>Such as:</p>\n\n<pre><code>unsigned char hashResult[SHA_DIGEST_LENGTH]; \nauto value = std::string(reinterpret_cast<char*>hashResult, SHA_DIGEST_LENGTH);\n</code></pre>\n"
},
{
"answer_id": 41785583,
"author": "freeze",
"author_id": 7159803,
"author_profile": "https://Stackoverflow.com/users/7159803",
"pm_score": 2,
"selected": false,
"text": "<p>This works fine:</p>\n\n<pre><code>//Convert CString to std::string\ninline std::string to_string(const CString& cst)\n{\n return CT2A(cst.GetString());\n}\n</code></pre>\n"
},
{
"answer_id": 44835115,
"author": "zar",
"author_id": 841330,
"author_profile": "https://Stackoverflow.com/users/841330",
"pm_score": 0,
"selected": false,
"text": "<p>All other answers didn't quite address what I was looking for which was to convert <code>CString</code> on the fly as opposed to store the result in a variable. </p>\n\n<p>The solution is similar to above but we need one more step to instantiate a nameless object. I am illustrating with an example. Here is my function which needs <code>std::string</code> but I have <code>CString</code>.</p>\n\n<pre><code>void CStringsPlayDlg::writeLog(const std::string &text)\n{\n std::string filename = \"c:\\\\test\\\\test.txt\";\n\n std::ofstream log_file(filename.c_str(), std::ios_base::out | std::ios_base::app);\n\n log_file << text << std::endl;\n}\n</code></pre>\n\n<p>How to call it when you have a <code>CString</code>?</p>\n\n<pre><code>std::string firstName = \"First\";\nCString lastName = _T(\"Last\");\n\nwriteLog( firstName + \", \" + std::string( CT2A( lastName ) ) ); \n</code></pre>\n\n<p>Note that the last line is not a direct typecast but we are creating a nameless <code>std::string</code> object and supply the <code>CString</code> via its constructor.</p>\n"
},
{
"answer_id": 46798233,
"author": "u8it",
"author_id": 3546415,
"author_profile": "https://Stackoverflow.com/users/3546415",
"pm_score": 0,
"selected": false,
"text": "<p>One interesting approach is to cast <code>CString</code> to <code>CStringA</code> inside a <code>string</code> constructor. Unlike <code>std::string s((LPCTSTR)cs);</code> this will work even if <code>_UNICODE</code> is defined. However, if that is the case, this will perform conversion from Unicode to ANSI, so it is unsafe for higher Unicode values beyond the ASCII character set. Such conversion is subject to the <code>_CSTRING_DISABLE_NARROW_WIDE_CONVERSION</code> preprocessor definition. <a href=\"https://msdn.microsoft.com/en-us/library/5bzxfsea.aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/5bzxfsea.aspx</a></p>\n\n<pre><code> CString s1(\"SomeString\");\n string s2((CStringA)s1);\n</code></pre>\n"
},
{
"answer_id": 51945055,
"author": "Pat. ANDRIA",
"author_id": 7561697,
"author_profile": "https://Stackoverflow.com/users/7561697",
"pm_score": 2,
"selected": false,
"text": "<p>From this post (Thank you <a href=\"https://stackoverflow.com/users/5987/mark-ransom\">Mark Ransom</a> )</p>\n<p><a href=\"https://stackoverflow.com/questions/2954399/convert-cstring-to-string-vc6\">Convert CString to string (VC6)</a></p>\n<p>I have tested this and it works fine.</p>\n<pre><code>std::string Utils::CString2String(const CString& cString) \n{\n std::string strStd;\n\n for (int i = 0; i < cString.GetLength(); ++i)\n {\n if (cString[i] <= 0x7f)\n strStd.append(1, static_cast<char>(cString[i]));\n else\n strStd.append(1, '?');\n }\n\n return strStd;\n}\n</code></pre>\n"
},
{
"answer_id": 51945363,
"author": "Amit G.",
"author_id": 706055,
"author_profile": "https://Stackoverflow.com/users/706055",
"pm_score": 2,
"selected": false,
"text": "<p>(Since VS2012 ...and at least until VS2017 v15.8.1)</p>\n\n<p>Since it's a MFC project & CString is a MFC class, MS provides a Technical Note <a href=\"https://msdn.microsoft.com/en-us/library/805c56f8.aspx\" rel=\"nofollow noreferrer\">TN059: Using MFC MBCS/Unicode Conversion Macros</a> and Generic Conversion Macros:</p>\n\n<pre><code>A2CW (LPCSTR) -> (LPCWSTR) \nA2W (LPCSTR) -> (LPWSTR) \nW2CA (LPCWSTR) -> (LPCSTR) \nW2A (LPCWSTR) -> (LPSTR) \n</code></pre>\n\n<p>Use:</p>\n\n<pre><code>void Example() // ** UNICODE case **\n{\n USES_CONVERSION; // (1)\n\n // CString to std::string / std::wstring\n CString strMfc{ \"Test\" }; // strMfc = L\"Test\"\n std::string strStd = W2A(strMfc); // ** Conversion Macro: strStd = \"Test\" **\n std::wstring wstrStd = strMfc.GetString(); // wsrStd = L\"Test\"\n\n // std::string to CString / std::wstring\n strStd = \"Test 2\";\n strMfc = strStd.c_str(); // strMfc = L\"Test 2\"\n wstrStd = A2W(strStd.c_str()); // ** Conversion Macro: wstrStd = L\"Test 2\" **\n\n // std::wstring to CString / std::string \n wstrStd = L\"Test 3\";\n strMfc = wstrStd.c_str(); // strMfc = L\"Test 3\"\n strStd = W2A(wstrStd.c_str()); // ** Conversion Macro: strStd = \"Test 3\" **\n}\n</code></pre>\n\n<p>--</p>\n\n<p>Footnotes:</p>\n\n<p>(1) In order to for the conversion-macros to have space to store the temporary length, it is necessary to declare a local variable called <code>_convert</code> that does this in each function that uses the conversion macros. This is done by invoking the <code>USES_CONVERSION</code> macro. In VS2017 MFC code (atlconv.h) it looks like this:</p>\n\n<pre><code>#ifndef _DEBUG\n #define USES_CONVERSION int _convert; (_convert); UINT _acp = ATL::_AtlGetConversionACP() /*CP_THREAD_ACP*/; (_acp); LPCWSTR _lpw; (_lpw); LPCSTR _lpa; (_lpa)\n#else\n #define USES_CONVERSION int _convert = 0; (_convert); UINT _acp = ATL::_AtlGetConversionACP() /*CP_THREAD_ACP*/; (_acp); LPCWSTR _lpw = NULL; (_lpw); LPCSTR _lpa = NULL; (_lpa)\n#endif\n</code></pre>\n"
},
{
"answer_id": 52201660,
"author": "IInspectable",
"author_id": 1889329,
"author_profile": "https://Stackoverflow.com/users/1889329",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Is there <strong>any</strong> problem?</p>\n</blockquote>\n\n<p>There are several issues:</p>\n\n<ul>\n<li><code>CString</code> is a template specialization of <a href=\"https://learn.microsoft.com/en-us/cpp/atl-mfc-shared/reference/cstringt-class\" rel=\"nofollow noreferrer\">CStringT</a>. Depending on the <em>BaseType</em> describing the character type, there are two concrete specializations: <code>CStringA</code> (using <code>char</code>) and <code>CStringW</code> (using <code>wchar_t</code>).</li>\n<li>While <code>wchar_t</code> on Windows is ubiquitously used to store UTF-16 encoded code units, using <code>char</code> is ambiguous. The latter commonly stores ANSI encoded characters, but can also store ASCII, UTF-8, or even binary data.</li>\n<li>We don't know the character encoding (or even character type) of <code>CString</code> (which is controlled through the <code>_UNICODE</code> preprocessor symbol), making the question ambiguous. We also don't know the desired character encoding of <code>std::string</code>.</li>\n<li>Converting between Unicode and ANSI is inherently lossy: ANSI encoding can only represent a subset of the Unicode character set.</li>\n</ul>\n\n<p>To address these issues, I'm going to assume that <code>wchar_t</code> will store UTF-16 encoded code units, and <code>char</code> will hold UTF-8 octet sequences. That's the only reasonable choice you can make to ensure that source and destination strings retain the same information, without limiting the solution to a subset of the source or destination domains.</p>\n\n<p>The following implementations convert between <code>CStringA</code>/<code>CStringW</code> and <code>std::wstring</code>/<code>std::string</code> mapping from UTF-8 to UTF-16 and vice versa:</p>\n\n<pre><code>#include <string>\n#include <atlconv.h>\n\nstd::string to_utf8(CStringW const& src_utf16)\n{\n return { CW2A(src_utf16.GetString(), CP_UTF8).m_psz };\n}\n\nstd::wstring to_utf16(CStringA const& src_utf8)\n{\n return { CA2W(src_utf8.GetString(), CP_UTF8).m_psz };\n}\n</code></pre>\n\n<p>The remaining two functions construct C++ string objects from MFC strings, leaving the encoding unchanged. Note that while the previous functions cannot cope with embedded NUL characters, these functions are immune to that.</p>\n\n<pre><code>#include <string>\n#include <atlconv.h>\n\nstd::string to_std_string(CStringA const& src)\n{\n return { src.GetString(), src.GetString() + src.GetLength() };\n}\n\nstd::wstring to_std_wstring(CStringW const& src)\n{\n return { src.GetString(), src.GetString() + src.GetLength() };\n}\n</code></pre>\n"
},
{
"answer_id": 55765583,
"author": "shawon",
"author_id": 3859220,
"author_profile": "https://Stackoverflow.com/users/3859220",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <strong>CT2CA</strong> </p>\n\n<pre><code>CString datasetPath;\nCT2CA st(datasetPath);\nstring dataset(st);\n</code></pre>\n"
},
{
"answer_id": 58534341,
"author": "JL Mutzz Mutz",
"author_id": 12266718,
"author_profile": "https://Stackoverflow.com/users/12266718",
"pm_score": 2,
"selected": false,
"text": "<p>to convert <code>CString to std::string</code>. You can use this format.</p>\n\n<pre><code>std::string sText(CW2A(CSText.GetString(), CP_UTF8 ));\n</code></pre>\n"
},
{
"answer_id": 69285124,
"author": "GiaMat45",
"author_id": 14877217,
"author_profile": "https://Stackoverflow.com/users/14877217",
"pm_score": 2,
"selected": false,
"text": "<p><code>CString</code> has method, <code>GetString()</code>, that returns an <code>LPCWSTR</code> type if you are using Unicode, or <code>LPCSTR</code> otherwise.</p>\n<p>In the Unicode case, you must pass it through a <code>wstring</code>:</p>\n<pre><code>CString cs("Hello");\nwstring ws = wstring(cs.GetString());\nstring s = string(ws.begin(), ws.end());\n</code></pre>\n<p>Else you can simply convert the string directly:</p>\n<pre><code>CString cs("Hello");\nstring s = string(cs.GetString());\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258050",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
`CString` is quite handy, while `std::string` is more compatible with STL container. I am using `hash_map`. However, `hash_map` does not support `CString`s as keys, so I want to convert the `CString` into a `std::string`.
Writing a `CString` hash function seems to take a lot of time.
```
CString -----> std::string
```
How can I do this?
```
std::string -----> CString:
inline CString toCString(std::string const& str)
{
return CString(str.c_str());
}
```
Am I right?
---
**EDIT:**
Here are more questions:
How can I convert from `wstring` to `CString` and vice versa?
```
// wstring -> CString
std::wstring src;
CString result(src.c_str());
// CString -> wstring
CString src;
std::wstring des(src.GetString());
```
Is there any problem with this?
Additionally, how can I convert from `std::wstring` to `std::string` and vice versa?
|
According to [CodeGuru](http://www.codeguru.com/forum/archive/index.php/t-231155.html):
`CString` to `std::string`:
```
CString cs("Hello");
std::string s((LPCTSTR)cs);
```
**BUT:** `std::string` cannot always construct from a `LPCTSTR`. i.e. the code will fail for UNICODE builds.
As `std::string` can construct only from `LPSTR` / `LPCSTR`, a programmer who uses VC++ 7.x or better can utilize conversion classes such as `CT2CA` as an intermediary.
```
CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
```
[`std::string` to `CString`](http://cstrings.blogspot.com/2006/08/how-to-convert-from-stdstring-to.html): (From [Visual Studio's CString FAQs...](http://cstrings.blogspot.com/2006/08/how-to-convert-from-stdstring-to.html))
```
std::string s("Hello");
CString cs(s.c_str());
```
`CStringT` can construct from both character or wide-character strings. i.e. It can convert from `char*` (i.e. `LPSTR`) or from `wchar_t*` (`LPWSTR`).
In other words, char-specialization (of `CStringT`) i.e. `CStringA`, `wchar_t`-specilization `CStringW`, and `TCHAR`-specialization `CString` can be constructed from either `char` or wide-character, ~~null terminated (null-termination is very important here)~~ string sources.
Althoug [IInspectable](https://stackoverflow.com/users/1889329/iinspectable) amends the "null-termination" part [in the comments](https://stackoverflow.com/questions/258050/how-to-convert-cstring-and-stdstring-stdwstring-to-each-other/258052?noredirect=1#comment29168168_258052):
>
> **NUL-termination is not required**.
>
> `CStringT` has conversion constructors that take an explicit length argument. This also means that you can construct `CStringT` objects from `std::string` objects with embedded `NUL` characters.
>
>
>
|
258,053 |
<p>In excel 2007, I have a formula in a cell like the following:</p>
<pre><code>=COUNTIFS('2008-10-31'!$C:$C;">="&'$A7)
</code></pre>
<p>Now I want to make the name of the sheet ('2008-10-31') be dependent on the value of some cell (say A1). Something like: </p>
<pre><code>=COUNTIFS(A1!$C:$C;">="&'$A7) // error
</code></pre>
<p>Is there is way to do this? Or do I have to write a VBA-Macro for it?</p>
|
[
{
"answer_id": 258090,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>You are looking for the INDIRECT worksheet function:</p>\n\n<pre><code>=INDIRECT(\"SHEET2!A1\")\n=COUNTIFS(INDIRECT(A1 & \"!$C:$C\"); \">=\" & $A7)\n</code></pre>\n\n<p>The function turns a string into a real cell reference.</p>\n"
},
{
"answer_id": 258161,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 5,
"selected": true,
"text": "<p>INDIRECT does what you want. Note that if the sheet name has any spaces, you need to put single quotes round it, ie </p>\n\n<pre><code>=COUNTIFS(INDIRECT(\"'\" & A1 & \"'!$C:$C\"); \">=\" & $A7)\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258053",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26070/"
] |
In excel 2007, I have a formula in a cell like the following:
```
=COUNTIFS('2008-10-31'!$C:$C;">="&'$A7)
```
Now I want to make the name of the sheet ('2008-10-31') be dependent on the value of some cell (say A1). Something like:
```
=COUNTIFS(A1!$C:$C;">="&'$A7) // error
```
Is there is way to do this? Or do I have to write a VBA-Macro for it?
|
INDIRECT does what you want. Note that if the sheet name has any spaces, you need to put single quotes round it, ie
```
=COUNTIFS(INDIRECT("'" & A1 & "'!$C:$C"); ">=" & $A7)
```
|
258,056 |
<p>I need to get the data of an particular <code><td></code>, but I don't have any <code>id</code> or <code>name</code> for that particular <code><td></code>. How do you get the contents of that <code><td></code>?</p>
<p>For example:</p>
<pre><code><table>
<tr><td>name</td><td>praveen</td></tr>
<tr><td>designation</td><td>software engineer</td></tr>
</table>
</code></pre>
<p>Is it possible to get the value "designation" from this table.. I need to extract the word "software engineer" using javascript.</p>
|
[
{
"answer_id": 258067,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>Something along the line of:<br>\n(not tested, just quick code to give an idea)</p>\n\n<pre><code>var tables = document.getElementById('TABLE'); // instead of document.all.tag\nvar rows;\nvar cells;\nvar maxCells = 1;\nvar designation;\nif (tables) {\n for (var t=0; t<tables.length; t++) {\n rows = tables[t].all.tags('TR');\n if (tables[t].all.tags('TABLE').length == 0) {\n for (var r=0; r<rows.length; r++) {\n if (rows[r].innerText != '') {\n cells = rows[r].all.tags('TD');\n for (var c=0; c<cells.length; c++) {\n if (cells[c].innerText == 'designation' && c<(cells.length-1)) {\n designation = cells[c+1].innerText;\n }\n }\n }\n }\n }\n }\n}\n</code></pre>\n\n<p>Since document.all is IE specific, you should rather user getElementById, with the following to <a href=\"http://www.sixteensmallstones.org/ie-javascript-bugs-overriding-internet-explorers-documentgetelementbyid-to-be-w3c-compliant-exposes-an-additional-bug-in-getattributes\" rel=\"nofollow noreferrer\">redefine that function for IE</a>:</p>\n\n<pre><code>if (/msie/i.test (navigator.userAgent)) //only override IE\n{\n document.nativeGetElementById = document.getElementById;\n document.getElementById = function(id)\n {\n var elem = document.nativeGetElementById(id);\n if(elem)\n {\n //make sure that it is a valid match on id\n if(elem.attributes['id'].value == id)\n {\n return elem;\n }\n else\n {\n //otherwise find the correct element\n for(var i=1;i<document.all[id].length;i++)\n {\n if(document.all[id][i].attributes['id'].value == id)\n {\n return document.all[id][i];\n }\n }\n }\n }\n return null;\n };\n}\n</code></pre>\n"
},
{
"answer_id": 258109,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>A quick solution:</p>\n\n<pre><code>function GetTdContent(label)\n{\n var TDs = document.getElementsByTagName(\"TD\");\n var foundFlag = false;\n\n for (i = 0; i < TDs.length; i++)\n {\n if (foundFlag) return TDs[i].innerHTML;\n foundFlag = TDs[i].innerHTML.toLower() == label.toLower(); \n }\n}\n</code></pre>\n\n<p>elsewhere call:</p>\n\n<pre><code>var value = GetTdContent(\"designation\");\n</code></pre>\n\n<p>Explanation:</p>\n\n<p>The function iterates all TDs in the document. If it finds one with the given label, say \"designation\", it loops one more time and returns the next TD content.</p>\n\n<p>This makes a few assumptions about your source HTML. If you know your data though, it can be enough.</p>\n"
},
{
"answer_id": 258111,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 0,
"selected": false,
"text": "<p>Use XPath (tutorial here, including instructions for IE and other browsers: <a href=\"http://www.w3schools.com/XPath/xpath_examples.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/XPath/xpath_examples.asp</a>)</p>\n\n<p>The xpath for your example is</p>\n\n<p>//table/tr/td[text()=\"designation\"]/following::td</p>\n\n<p>(\"the td that follows the td with text \"designation\" that's in a tr that's in a table somewhere in the document\")</p>\n\n<p>Simpler Xpaths are possible - if it's the only table cell that could contain 'designation' you could use</p>\n\n<p>//td[text()=\"designation\"]/following::td</p>\n\n<p>One issue with writing code to do the particular search is that it needs changing, possibly significantly, if the structure of your page changes. The Xpath may not need to change at all, and if it does, it's only one line.</p>\n"
},
{
"answer_id": 258130,
"author": "Jeff Schumacher",
"author_id": 27498,
"author_profile": "https://Stackoverflow.com/users/27498",
"pm_score": 2,
"selected": false,
"text": "<p>I prefer to use jQuery to do all the heavy lifting for this sort of task.</p>\n\n<p>For example, the following function will return the text of the next element of the same type that you're searching for:<br /></p>\n\n<pre><code>function GetNextChildText(tagToFind, valueToFind) {\n var nextText = \"\";\n $(tagToFind).each(function(i) {\n if ($(this).text() == valueToFind) {\n if ($(this).next() != null && $(this).next() != undefined) {\n nextText = $(this).next().text();\n }\n }\n });\n return (nextText);\n}\n</code></pre>\n\n<p>So, for your example table, your call to return the designation could be:<br /></p>\n\n<pre><code>var designationText = GetNextChildText('td', 'designation');\n</code></pre>\n\n<p>And the result is that the variable designationText would contain the value 'software engineer'.</p>\n"
},
{
"answer_id": 258918,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<p>Tomalak's a little quicker:</p>\n\n<pre><code><script type=\"text/javascript\">\nfunction getText(tText){\n var tds = document.getElementsByTagName(\"td\");\n for(var i=0, im=tds.length; im>i; i++){\n if(tds[i].firstChild.nodeValue == tText)\n return tds[i].nextSibling.firstChild.nodeValue;\n }\n}\n</script>\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to get the data of an particular `<td>`, but I don't have any `id` or `name` for that particular `<td>`. How do you get the contents of that `<td>`?
For example:
```
<table>
<tr><td>name</td><td>praveen</td></tr>
<tr><td>designation</td><td>software engineer</td></tr>
</table>
```
Is it possible to get the value "designation" from this table.. I need to extract the word "software engineer" using javascript.
|
A quick solution:
```
function GetTdContent(label)
{
var TDs = document.getElementsByTagName("TD");
var foundFlag = false;
for (i = 0; i < TDs.length; i++)
{
if (foundFlag) return TDs[i].innerHTML;
foundFlag = TDs[i].innerHTML.toLower() == label.toLower();
}
}
```
elsewhere call:
```
var value = GetTdContent("designation");
```
Explanation:
The function iterates all TDs in the document. If it finds one with the given label, say "designation", it loops one more time and returns the next TD content.
This makes a few assumptions about your source HTML. If you know your data though, it can be enough.
|
258,062 |
<p><em>This is javascript, but a virtually identical regex is failing in PHP too, so I don't think it's language specific</em></p>
<pre><code>var r = new RegExp(
"^(:19|20)?[0-9][0-9]" // optional 19/20 start followed by 2 numbers
+ "-" // a hyphen
+ "(:0?[1-9]|1[0-2])" // optional 0 followed by 1-9, or 10, 11, 12
+ "-" // a hyphen
+ "(:3[01]|[12][0-9]|0?[1-9])$" // you get the idea.
);
r.test("2008-07-01"); // == false
</code></pre>
<p>What on earth am I missing?</p>
|
[
{
"answer_id": 258066,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 5,
"selected": true,
"text": "<p>I think your non-capturing blocks should be e.g. <code>(?:19|20)</code> rather than <code>(:19|20)</code></p>\n"
},
{
"answer_id": 258118,
"author": "Fusion",
"author_id": 6253,
"author_profile": "https://Stackoverflow.com/users/6253",
"pm_score": 2,
"selected": false,
"text": "<p>Correct; your regular expression would actually work with <code>?:</code></p>\n\n<p><code>?</code> when used a prefix indicates that you're going to do something about capturing. Either not capture the block <code>(:)</code>, capture ahead <code>(=)</code>, behind <code>(<=)</code>, etc.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
*This is javascript, but a virtually identical regex is failing in PHP too, so I don't think it's language specific*
```
var r = new RegExp(
"^(:19|20)?[0-9][0-9]" // optional 19/20 start followed by 2 numbers
+ "-" // a hyphen
+ "(:0?[1-9]|1[0-2])" // optional 0 followed by 1-9, or 10, 11, 12
+ "-" // a hyphen
+ "(:3[01]|[12][0-9]|0?[1-9])$" // you get the idea.
);
r.test("2008-07-01"); // == false
```
What on earth am I missing?
|
I think your non-capturing blocks should be e.g. `(?:19|20)` rather than `(:19|20)`
|
258,119 |
<p>I am instantiating a class A (which I am importing from somebody
else, so I can't modify it) into my class X.</p>
<p>Is there a way I can intercept or wrap calls to methods in A?
I.e., in the code below can I call</p>
<pre><code>x.a.p1()
</code></pre>
<p>and get the output</p>
<pre><code>X.pre
A.p1
X.post
</code></pre>
<p>Many TIA!</p>
<pre><code>class A:
# in my real application, this is an imported class
# that I cannot modify
def p1(self): print 'A.p1'
class X:
def __init__(self):
self.a=A()
def pre(self): print 'X.pre'
def post(self): print 'X.post'
x=X()
x.a.p1()
</code></pre>
|
[
{
"answer_id": 258125,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>The no-whistles-or-bells solution would be to write a wrapper class for class A that does just that.</p>\n"
},
{
"answer_id": 258179,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 1,
"selected": false,
"text": "<p>You could just modify the A instance and replace the p1 function with a wrapper function:</p>\n\n<pre><code>def wrapped(pre, post, f):\n def wrapper(*args, **kwargs):\n pre()\n retval = f(*args, **kwargs)\n post()\n return retval\n return wrapper\n\nclass Y:\n def __init__(self):\n self.a=A()\n self.a.p1 = wrapped(self.pre, self.post, self.a.p1)\n\n def pre(self): print 'X.pre'\n def post(self): print 'X.post'\n</code></pre>\n"
},
{
"answer_id": 258253,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I've just recently read about decorators in python, I'm not understanding them yet but it seems to me that they can be a solution to your problem. see Bruce Eckel intro to decorators at:\n<a href=\"http://www.artima.com/weblogs/viewpost.jsp?thread=240808\" rel=\"nofollow noreferrer\">http://www.artima.com/weblogs/viewpost.jsp?thread=240808</a></p>\n\n<p>He has a few more posts on that topic there.</p>\n\n<p>Edit: Three days later I stumble upon this article, which shows how to do a similar task without decorators, what's the problems with it and then introduces decorators and develop a quite full solution:\n<a href=\"http://wordaligned.org/articles/echo\" rel=\"nofollow noreferrer\">http://wordaligned.org/articles/echo</a></p>\n"
},
{
"answer_id": 258259,
"author": "Mark Harrison",
"author_id": 116,
"author_profile": "https://Stackoverflow.com/users/116",
"pm_score": 0,
"selected": false,
"text": "<p>Here's what I've received from Steven D'Aprano on comp.lang.python.</p>\n\n<pre><code># Define two decorator factories.\ndef precall(pre):\n def decorator(f):\n def newf(*args, **kwargs):\n pre()\n return f(*args, **kwargs)\n return newf\n return decorator\n\ndef postcall(post):\n def decorator(f):\n def newf(*args, **kwargs):\n x = f(*args, **kwargs)\n post()\n return x\n return newf\n return decorator\n</code></pre>\n\n<p>Now you can monkey patch class A if you want. It's probably not a great\nidea to do this in production code, as it will effect class A everywhere.\n[this is ok for my application, as it is basically a protocol converter and there's exactly one instance of each class being processed.]</p>\n\n<pre><code>class A:\n # in my real application, this is an imported class\n # that I cannot modify\n def p1(self): print 'A.p1'\n\nclass X:\n def __init__(self):\n self.a=A()\n A.p1 = precall(self.pre)(postcall(self.post)(A.p1))\n def pre(self): print 'X.pre'\n def post(self): print 'X.post'\n\n\nx=X()\nx.a.p1()\n</code></pre>\n\n<p>Gives the desired result.</p>\n\n<pre><code>X.pre\nA.p1\nX.post\n</code></pre>\n"
},
{
"answer_id": 258274,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 4,
"selected": true,
"text": "<p>Here is the solution I and my colleagues came up with:</p>\n\n<pre><code>from types import MethodType\n\nclass PrePostCaller:\n def __init__(self, other):\n self.other = other\n\n def pre(self): print 'pre'\n def post(self): print 'post'\n\n def __getattr__(self, name):\n if hasattr(self.other, name):\n func = getattr(self.other, name)\n return lambda *args, **kwargs: self._wrap(func, args, kwargs)\n raise AttributeError(name)\n\n def _wrap(self, func, args, kwargs):\n self.pre()\n if type(func) == MethodType:\n result = func( *args, **kwargs)\n else:\n result = func(self.other, *args, **kwargs)\n self.post()\n return result\n\n#Examples of use\nclass Foo:\n def stuff(self):\n print 'stuff'\n\na = PrePostCaller(Foo())\na.stuff()\n\na = PrePostCaller([1,2,3])\nprint a.count()\n</code></pre>\n\n<p>Gives:</p>\n\n<pre><code>pre\nstuff\npost\npre\npost\n0\n</code></pre>\n\n<p>So when creating an instance of your object, wrap it with the PrePostCaller object. After that you continue using the object as if it was an instance of the wrapped object. With this solution you can do the wrapping on a per instance basis.</p>\n"
},
{
"answer_id": 258283,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 1,
"selected": false,
"text": "<p>As others have mentioned, the wrapper/decorator solution is probably be the easiest one. I don't recommend modifyng the wrapped class itself, for the same reasons that you point out.</p>\n\n<p>If you have many external classes you can write a code generator to generate the wrapper classes for you. Since you are doing this in Python you can probably even implement the generator as a part of the program, generating the wrappers at startup, or something.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
I am instantiating a class A (which I am importing from somebody
else, so I can't modify it) into my class X.
Is there a way I can intercept or wrap calls to methods in A?
I.e., in the code below can I call
```
x.a.p1()
```
and get the output
```
X.pre
A.p1
X.post
```
Many TIA!
```
class A:
# in my real application, this is an imported class
# that I cannot modify
def p1(self): print 'A.p1'
class X:
def __init__(self):
self.a=A()
def pre(self): print 'X.pre'
def post(self): print 'X.post'
x=X()
x.a.p1()
```
|
Here is the solution I and my colleagues came up with:
```
from types import MethodType
class PrePostCaller:
def __init__(self, other):
self.other = other
def pre(self): print 'pre'
def post(self): print 'post'
def __getattr__(self, name):
if hasattr(self.other, name):
func = getattr(self.other, name)
return lambda *args, **kwargs: self._wrap(func, args, kwargs)
raise AttributeError(name)
def _wrap(self, func, args, kwargs):
self.pre()
if type(func) == MethodType:
result = func( *args, **kwargs)
else:
result = func(self.other, *args, **kwargs)
self.post()
return result
#Examples of use
class Foo:
def stuff(self):
print 'stuff'
a = PrePostCaller(Foo())
a.stuff()
a = PrePostCaller([1,2,3])
print a.count()
```
Gives:
```
pre
stuff
post
pre
post
0
```
So when creating an instance of your object, wrap it with the PrePostCaller object. After that you continue using the object as if it was an instance of the wrapped object. With this solution you can do the wrapping on a per instance basis.
|
258,120 |
<p>Is the memory space consumed by one object with 100 attributes the same as that of 100 objects, with one attribute each?</p>
<p>How much memory is allocated for an object?<br>
How much additional space is used when adding an attribute?</p>
|
[
{
"answer_id": 258124,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 3,
"selected": false,
"text": "<p>No, registering an object takes a bit of memory too. 100 objects with 1 attribute will take up more memory.</p>\n"
},
{
"answer_id": 258127,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 1,
"selected": false,
"text": "<p>no, 100 small objects needs more information (memory) than one big.</p>\n"
},
{
"answer_id": 258143,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": false,
"text": "<p>Each object has a certain overhead for its associated monitor and type information, as well as the fields themselves. Beyond that, fields can be laid out pretty much however the JVM sees fit (I believe) - but as <a href=\"https://stackoverflow.com/questions/229886/size-of-a-byte-in-memory-java#230063\">shown in another answer</a>, at least <em>some</em> JVMs will pack fairly tightly. Consider a class like this:</p>\n\n<pre><code>public class SingleByte\n{\n private byte b;\n}\n</code></pre>\n\n<p>vs</p>\n\n<pre><code>public class OneHundredBytes\n{\n private byte b00, b01, ..., b99;\n}\n</code></pre>\n\n<p>On a 32-bit JVM, I'd expect 100 instances of <code>SingleByte</code> to take 1200 bytes (8 bytes of overhead + 4 bytes for the field due to padding/alignment). I'd expect one instance of <code>OneHundredBytes</code> to take 108 bytes - the overhead, and then 100 bytes, packed. It can certainly vary by JVM though - one implementation may decide not to pack the fields in <code>OneHundredBytes</code>, leading to it taking 408 bytes (= 8 bytes overhead + 4 * 100 aligned/padded bytes). On a 64 bit JVM the overhead may well be bigger too (not sure).</p>\n\n<p>EDIT: See the comment below; apparently HotSpot pads to 8 byte boundaries instead of 32, so each instance of <code>SingleByte</code> would take 16 bytes.</p>\n\n<p>Either way, the \"single large object\" will be at least as efficient as multiple small objects - for simple cases like this.</p>\n"
},
{
"answer_id": 258150,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"http://mindprod.com/jgloss/sizeof.html\" rel=\"noreferrer\">Mindprod</a> points out that this is not a straightforward question to answer:</p>\n\n<blockquote>\n <p>A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.<br>\n For example, the JVM or native compiler might decide to store a <code>boolean[]</code> in 64-bit long chunks like a <code>BitSet</code>. It does not have to tell you, so long as the program gives the same answers.</p>\n \n <ul>\n <li>It might allocate some temporary Objects on the stack. </li>\n <li>It may optimize some variables or method calls totally out of existence replacing them with constants. </li>\n <li>It might version methods or loops, i.e. compile two versions of a method, each optimized for a certain situation, then decide up front which one to call. </li>\n </ul>\n \n <p>Then of course the hardware and OS have multilayer caches, on chip-cache, SRAM cache, DRAM cache, ordinary RAM working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption. </p>\n</blockquote>\n\n<h2>Measurement methods</h2>\n\n<p>You can use <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize-java.lang.Object-\" rel=\"noreferrer\"><code>Instrumentation.getObjectSize()</code></a> to obtain an estimate of the storage consumed by an object.</p>\n\n<p>To visualize the <em>actual</em> object layout, footprint, and references, you can use the <a href=\"http://openjdk.java.net/projects/code-tools/jol/\" rel=\"noreferrer\">JOL (Java Object Layout) tool</a>.</p>\n\n<h2>Object headers and Object references</h2>\n\n<p>In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. <em>(From <a href=\"https://stackoverflow.com/a/32224498/6309\">Dmitry Spikhalskiy's answer</a>, <a href=\"https://stackoverflow.com/a/35407947/6309\">Jayen's answer</a>, and <a href=\"http://www.javaworld.com/javaworld/javatips/jw-javatip130.html\" rel=\"noreferrer\">JavaWorld</a>.)</em></p>\n\n<p>Typically, references are 4 bytes on 32bit platforms or on 64bit platforms up to <code>-Xmx32G</code>; and 8 bytes above 32Gb (<code>-Xmx32G</code>). <em>(See <a href=\"http://www.lowtek.ca/roo/2008/java-performance-in-64bit-land/\" rel=\"noreferrer\">compressed object references</a>.)</em></p>\n\n<p>As a result, a 64-bit JVM would typically require 30-50% more heap space. <em>(<a href=\"http://www.javacodegeeks.com/2012/12/should-i-use-a-32-or-a-64-bit-jvm.html\" rel=\"noreferrer\">Should I use a 32- or a 64-bit JVM?</a>, 2012, JDK 1.7)</em></p>\n\n<h2>Boxed types, arrays, and strings</h2>\n\n<p>Boxed wrappers have overhead compared to primitive types (from <a href=\"http://www.javaworld.com/javaworld/javatips/jw-javatip130.html\" rel=\"noreferrer\">JavaWorld</a>):</p>\n\n<blockquote>\n <ul>\n <li><p><strong><code>Integer</code></strong>: The 16-byte result is a little worse than I expected because an <code>int</code> value can fit into just 4 extra bytes. Using an <code>Integer</code> costs me a 300 percent memory overhead compared to when I can store the value as a primitive type</p></li>\n <li><p><strong><code>Long</code></strong>: 16 bytes also: Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like a <code>Long</code> is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast, <code>Integer</code> had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary. </p></li>\n </ul>\n</blockquote>\n\n<p>Other containers are costly too:</p>\n\n<blockquote>\n <ul>\n <li><p><strong>Multidimensional arrays</strong>: it offers another surprise.<br>\n Developers commonly employ constructs like <code>int[dim1][dim2]</code> in numerical and scientific computing.</p>\n \n <p>In an <code>int[dim1][dim2]</code> array instance, every nested <code>int[dim2]</code> array is an <code>Object</code> in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ.</p>\n \n <p>For example, a <code>int[128][2]</code> instance takes 3,600 bytes. Compared to the 1,040 bytes an <code>int[256]</code> instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case of <code>byte[256][1]</code>, the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead. </p></li>\n <li><p><strong><code>String</code></strong>: a <code>String</code>'s memory growth tracks its internal char array's growth. However, the <code>String</code> class adds another 24 bytes of overhead.</p>\n \n <p>For a nonempty <code>String</code> of size 10 characters or less, the added overhead cost relative to useful payload (2 bytes for each char plus 4 bytes for the length), ranges from 100 to 400 percent. </p></li>\n </ul>\n</blockquote>\n\n<h2>Alignment</h2>\n\n<p>Consider this <a href=\"https://plumbr.eu/blog/memory-leaks/how-much-memory-do-i-need-part-2-what-is-shallow-heap\" rel=\"noreferrer\">example object</a>:</p>\n\n<pre><code>class X { // 8 bytes for reference to the class definition\n int a; // 4 bytes\n byte b; // 1 byte\n Integer c = new Integer(); // 4 bytes for a reference\n}\n</code></pre>\n\n<p>A naïve sum would suggest that an instance of <code>X</code> would use 17 bytes. However, due to alignment (also called padding), the JVM allocates the memory in multiples of 8 bytes, so instead of 17 bytes it would allocate 24 bytes.</p>\n"
},
{
"answer_id": 260545,
"author": "Matt Passell",
"author_id": 33836,
"author_profile": "https://Stackoverflow.com/users/33836",
"pm_score": 2,
"selected": false,
"text": "<p>I've gotten very good results from the <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/instrument/Instrumentation.html\" rel=\"nofollow noreferrer\">java.lang.instrument.Instrumentation</a> approach mentioned in another answer. For good examples of its use, see the entry, <em><a href=\"http://www.javaspecialists.eu/archive/Issue142.html\" rel=\"nofollow noreferrer\">Instrumentation Memory Counter</a></em> from the JavaSpecialists' Newsletter and the <a href=\"https://sourceforge.net/projects/sizeof/\" rel=\"nofollow noreferrer\">java.sizeOf</a> library on SourceForge.</p>\n"
},
{
"answer_id": 286504,
"author": "kohlerm",
"author_id": 26056,
"author_profile": "https://Stackoverflow.com/users/26056",
"pm_score": 0,
"selected": false,
"text": "<p>The rules about how much memory is consumed depend on the JVM implementation and the CPU architecture (32 bit versus 64 bit for example). </p>\n\n<p>For the detailed rules for the SUN JVM check <a href=\"http://www.sdn.sap.com/irj/scn/weblogs?blog=/pub/wlg/5163\" rel=\"nofollow noreferrer\">my old blog</a></p>\n\n<p>Regards,\n<a href=\"http://kohlerm.blogspot.com/\" rel=\"nofollow noreferrer\">Markus</a></p>\n"
},
{
"answer_id": 726709,
"author": "Neil Coffey",
"author_id": 48933,
"author_profile": "https://Stackoverflow.com/users/48933",
"pm_score": 2,
"selected": false,
"text": "<p>In case it's useful to anyone, you can download from my web site a small <a href=\"http://www.javamex.com/classmexer/\" rel=\"nofollow noreferrer\">Java agent for querying the memory usage of an object</a>. It'll let you query \"deep\" memory usage as well.</p>\n"
},
{
"answer_id": 14501891,
"author": "catch23",
"author_id": 1498427,
"author_profile": "https://Stackoverflow.com/users/1498427",
"pm_score": 3,
"selected": false,
"text": "<p>The total used / free memory of a program can be obtained in the program via</p>\n<pre><code>java.lang.Runtime.getRuntime();\n</code></pre>\n<p>The runtime has several methods which relate to the memory. The following coding example demonstrates its usage.</p>\n<pre><code> public class PerformanceTest {\n private static final long MEGABYTE = 1024L * 1024L;\n\n public static long bytesToMegabytes(long bytes) {\n return bytes / MEGABYTE;\n }\n\n public static void main(String[] args) {\n // I assume you will know how to create an object Person yourself...\n List <Person> list = new ArrayList <Person> ();\n for (int i = 0; i <= 100_000; i++) {\n list.add(new Person("Jim", "Knopf"));\n }\n\n // Get the Java runtime\n Runtime runtime = Runtime.getRuntime();\n\n // Run the garbage collector\n runtime.gc();\n\n // Calculate the used memory\n long memory = runtime.totalMemory() - runtime.freeMemory();\n System.out.println("Used memory is bytes: " + memory);\n System.out.println("Used memory is megabytes: " + bytesToMegabytes(memory));\n }\n }\n</code></pre>\n"
},
{
"answer_id": 16625324,
"author": "Nikhil Agrawal",
"author_id": 2218452,
"author_profile": "https://Stackoverflow.com/users/2218452",
"pm_score": 3,
"selected": false,
"text": "<p>The question will be a very broad one.</p>\n\n<p>It depends on the class variable or you may call as states memory usage in java.</p>\n\n<p>It also has some additional memory requirement for headers and referencing.</p>\n\n<p><strong>The heap memory used by a Java object includes</strong></p>\n\n<ul>\n<li><p>memory for primitive fields, according to their size (see below for Sizes of primitive types); </p></li>\n<li><p>memory for reference fields (4 bytes each); </p></li>\n<li><p>an object header, consisting of a few bytes of \"housekeeping\" information; </p></li>\n</ul>\n\n<p>Objects in java also requires some \"housekeeping\" information, such as recording an object's class, ID and status flags such as whether the object is currently reachable, currently synchronization-locked etc. </p>\n\n<p>Java object header size varies on 32 and 64 bit jvm.</p>\n\n<p>Although these are the main memory consumers jvm also requires additional fields sometimes like for alignment of the code e.t.c.</p>\n\n<p><strong>Sizes of primitive types</strong></p>\n\n<p><strong>boolean & byte</strong> -- 1</p>\n\n<p><strong>char & short</strong> -- 2</p>\n\n<p><strong>int & float</strong> -- 4</p>\n\n<p><strong>long & double</strong> -- 8 </p>\n"
},
{
"answer_id": 30063849,
"author": "Arun",
"author_id": 278326,
"author_profile": "https://Stackoverflow.com/users/278326",
"pm_score": 3,
"selected": false,
"text": "<p>It appears that every object has an overhead of 16 bytes on 32-bit systems (and 24-byte on 64-bit systems).</p>\n\n<p><a href=\"http://algs4.cs.princeton.edu/14analysis/\" rel=\"noreferrer\">http://algs4.cs.princeton.edu/14analysis/</a> is a good source of information. One example among many good ones is the following.</p>\n\n<p><img src=\"https://i.stack.imgur.com/d5jNj.png\" alt=\"enter image description here\"></p>\n\n<p><a href=\"http://www.cs.virginia.edu/kim/publicity/pldi09tutorials/memory-efficient-java-tutorial.pdf\" rel=\"noreferrer\">http://www.cs.virginia.edu/kim/publicity/pldi09tutorials/memory-efficient-java-tutorial.pdf</a> is also very informative, for example:</p>\n\n<p><img src=\"https://i.stack.imgur.com/E8l6J.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 32224498,
"author": "Dmitry Spikhalskiy",
"author_id": 525203,
"author_profile": "https://Stackoverflow.com/users/525203",
"pm_score": 5,
"selected": false,
"text": "<p>It depends on architecture/jdk. For a modern JDK and 64bit architecture, an object has 12-bytes header and padding by 8 bytes - so minimum object size is 16 bytes. You can use a tool called <a href=\"http://openjdk.java.net/projects/code-tools/jol/\" rel=\"noreferrer\">Java Object Layout</a> to determine a size and get details about object layout and internal structure of any entity or guess this information by class reference. Example of an output for Integer on my environment:</p>\n\n<pre><code>Running 64-bit HotSpot VM.\nUsing compressed oop with 3-bit shift.\nUsing compressed klass with 3-bit shift.\nObjects are 8 bytes aligned.\nField sizes by type: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\nArray element sizes: 4, 1, 1, 2, 2, 4, 4, 8, 8 [bytes]\n\njava.lang.Integer object internals:\n OFFSET SIZE TYPE DESCRIPTION VALUE\n 0 12 (object header) N/A\n 12 4 int Integer.value N/A\nInstance size: 16 bytes (estimated, the sample instance is not available)\nSpace losses: 0 bytes internal + 0 bytes external = 0 bytes total\n</code></pre>\n\n<p>So, for Integer, instance size is 16 bytes, because 4-bytes int compacted in place right after header and before padding boundary.</p>\n\n<p>Code sample:</p>\n\n<pre><code>import org.openjdk.jol.info.ClassLayout;\nimport org.openjdk.jol.util.VMSupport;\n\npublic static void main(String[] args) {\n System.out.println(VMSupport.vmDetails());\n System.out.println(ClassLayout.parseClass(Integer.class).toPrintable());\n}\n</code></pre>\n\n<p>If you use maven, to get JOL:</p>\n\n<pre><code><dependency>\n <groupId>org.openjdk.jol</groupId>\n <artifactId>jol-core</artifactId>\n <version>0.3.2</version>\n</dependency>\n</code></pre>\n"
},
{
"answer_id": 35407947,
"author": "Jayen",
"author_id": 192798,
"author_profile": "https://Stackoverflow.com/users/192798",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Is the memory space consumed by one object with 100 attributes the same as that of 100 objects, with one attribute each?</p>\n</blockquote>\n\n<p>No.</p>\n\n<blockquote>\n <p>How much memory is allocated for an object?</p>\n</blockquote>\n\n<ul>\n<li>The overhead is 8 bytes on 32-bit, 12 bytes on 64-bit; and then rounded up to a multiple of 4 bytes (32-bit) or 8 bytes (64-bit).</li>\n</ul>\n\n<blockquote>\n <p>How much additional space is used when adding an attribute?</p>\n</blockquote>\n\n<ul>\n<li>Attributes range from 1 byte (byte) to 8 bytes (long/double), but references are either 4 bytes or 8 bytes depending <em>not</em> on whether it's 32bit or 64bit, but rather whether -Xmx is < 32Gb or >= 32Gb: typical 64-bit JVM's have an optimisation called \"-UseCompressedOops\" which compress references to 4 bytes if the heap is below 32Gb.</li>\n</ul>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is the memory space consumed by one object with 100 attributes the same as that of 100 objects, with one attribute each?
How much memory is allocated for an object?
How much additional space is used when adding an attribute?
|
[Mindprod](http://mindprod.com/jgloss/sizeof.html) points out that this is not a straightforward question to answer:
>
> A JVM is free to store data any way it pleases internally, big or little endian, with any amount of padding or overhead, though primitives must behave as if they had the official sizes.
>
> For example, the JVM or native compiler might decide to store a `boolean[]` in 64-bit long chunks like a `BitSet`. It does not have to tell you, so long as the program gives the same answers.
>
>
> * It might allocate some temporary Objects on the stack.
> * It may optimize some variables or method calls totally out of existence replacing them with constants.
> * It might version methods or loops, i.e. compile two versions of a method, each optimized for a certain situation, then decide up front which one to call.
>
>
> Then of course the hardware and OS have multilayer caches, on chip-cache, SRAM cache, DRAM cache, ordinary RAM working set and backing store on disk. Your data may be duplicated at every cache level. All this complexity means you can only very roughly predict RAM consumption.
>
>
>
Measurement methods
-------------------
You can use [`Instrumentation.getObjectSize()`](https://docs.oracle.com/javase/8/docs/api/java/lang/instrument/Instrumentation.html#getObjectSize-java.lang.Object-) to obtain an estimate of the storage consumed by an object.
To visualize the *actual* object layout, footprint, and references, you can use the [JOL (Java Object Layout) tool](http://openjdk.java.net/projects/code-tools/jol/).
Object headers and Object references
------------------------------------
In a modern 64-bit JDK, an object has a 12-byte header, padded to a multiple of 8 bytes, so the minimum object size is 16 bytes. For 32-bit JVMs, the overhead is 8 bytes, padded to a multiple of 4 bytes. *(From [Dmitry Spikhalskiy's answer](https://stackoverflow.com/a/32224498/6309), [Jayen's answer](https://stackoverflow.com/a/35407947/6309), and [JavaWorld](http://www.javaworld.com/javaworld/javatips/jw-javatip130.html).)*
Typically, references are 4 bytes on 32bit platforms or on 64bit platforms up to `-Xmx32G`; and 8 bytes above 32Gb (`-Xmx32G`). *(See [compressed object references](http://www.lowtek.ca/roo/2008/java-performance-in-64bit-land/).)*
As a result, a 64-bit JVM would typically require 30-50% more heap space. *([Should I use a 32- or a 64-bit JVM?](http://www.javacodegeeks.com/2012/12/should-i-use-a-32-or-a-64-bit-jvm.html), 2012, JDK 1.7)*
Boxed types, arrays, and strings
--------------------------------
Boxed wrappers have overhead compared to primitive types (from [JavaWorld](http://www.javaworld.com/javaworld/javatips/jw-javatip130.html)):
>
> * **`Integer`**: The 16-byte result is a little worse than I expected because an `int` value can fit into just 4 extra bytes. Using an `Integer` costs me a 300 percent memory overhead compared to when I can store the value as a primitive type
> * **`Long`**: 16 bytes also: Clearly, actual object size on the heap is subject to low-level memory alignment done by a particular JVM implementation for a particular CPU type. It looks like a `Long` is 8 bytes of Object overhead, plus 8 bytes more for the actual long value. In contrast, `Integer` had an unused 4-byte hole, most likely because the JVM I use forces object alignment on an 8-byte word boundary.
>
>
>
Other containers are costly too:
>
> * **Multidimensional arrays**: it offers another surprise.
>
> Developers commonly employ constructs like `int[dim1][dim2]` in numerical and scientific computing.
>
>
> In an `int[dim1][dim2]` array instance, every nested `int[dim2]` array is an `Object` in its own right. Each adds the usual 16-byte array overhead. When I don't need a triangular or ragged array, that represents pure overhead. The impact grows when array dimensions greatly differ.
>
>
> For example, a `int[128][2]` instance takes 3,600 bytes. Compared to the 1,040 bytes an `int[256]` instance uses (which has the same capacity), 3,600 bytes represent a 246 percent overhead. In the extreme case of `byte[256][1]`, the overhead factor is almost 19! Compare that to the C/C++ situation in which the same syntax does not add any storage overhead.
> * **`String`**: a `String`'s memory growth tracks its internal char array's growth. However, the `String` class adds another 24 bytes of overhead.
>
>
> For a nonempty `String` of size 10 characters or less, the added overhead cost relative to useful payload (2 bytes for each char plus 4 bytes for the length), ranges from 100 to 400 percent.
>
>
>
Alignment
---------
Consider this [example object](https://plumbr.eu/blog/memory-leaks/how-much-memory-do-i-need-part-2-what-is-shallow-heap):
```
class X { // 8 bytes for reference to the class definition
int a; // 4 bytes
byte b; // 1 byte
Integer c = new Integer(); // 4 bytes for a reference
}
```
A naïve sum would suggest that an instance of `X` would use 17 bytes. However, due to alignment (also called padding), the JVM allocates the memory in multiples of 8 bytes, so instead of 17 bytes it would allocate 24 bytes.
|
258,134 |
<p>I'm doing some FK analysis of our tables by making a directed
graph representing FK dependencies and then traversing the
graph. In my code, I name everything using directed graph
terminology, but I'd like to have something a bit more
"user friendly" in the report.</p>
<p>In this scenario:</p>
<pre><code>create table t1(a varchar2(20));
alter table t1 add constraint t1_fk foreign key(a) references t2(b);
</code></pre>
<p>t1.a must exist in t2.b. So, what words should I use in the blanks?</p>
<pre><code>t1 is the _______ of t2.
t2 is the _______ of t1.
</code></pre>
<p>Many TIA!</p>
|
[
{
"answer_id": 258152,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>I'd say (things between brackets are optional, but I'd use them)</p>\n\n<pre>\n[Column a of] table t1 references [column b of] table t2\n</pre>\n\n<p>and</p>\n\n<pre>\n[Column b of] table t2 is referenced by [column a of] table t1\n</pre>\n\n<p>?</p>\n\n<p>I'd also specify the action that happens on delete/update if any.</p>\n\n<pre>\nColumn b of table t2 is referenced by column a of table t1. \nDeleting a record in table t2 will delete matching records on table t1\n</pre>\n"
},
{
"answer_id": 258248,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>I'd say something along the lines of</p>\n\n<pre>\nt1 is the master of t2. An ID must be in t1, before it can be mentioned in t2.\nt2 is the slave of t1. It cannot refer to an ID that does not exist in t1.\n</pre>\n\n<p>Most non-technical people will grasp the master/slave terminology very intuitively.</p>\n"
},
{
"answer_id": 258269,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 1,
"selected": false,
"text": "<p>You could adopt the following sentence form:</p>\n\n<ul>\n<li>Each t1 row must be linked to exactly one t2 row</li>\n<li>Each t2 row may be linked with any number of t1 rows, or none</li>\n</ul>\n"
},
{
"answer_id": 258354,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 2,
"selected": false,
"text": "<pre><code>t1 is the parent of t2.\nt2 is the child of t1.\n</code></pre>\n\n<p>What is the audience for this? If it's people that understand a relational schema, then that will probably do. If it is non-technical people, then generally I have documented in my modelling tool (ERWin) the meaning of the relationships specifically.</p>\n\n<pre><code>InvoiceLineItem is a part of Invoice.\nInvoice has one or more InvoiceLineItems.\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>User must belong to a Business.\nBusiness has zero or more Users.\n</code></pre>\n"
},
{
"answer_id": 42073637,
"author": "jakodev",
"author_id": 5736075,
"author_profile": "https://Stackoverflow.com/users/5736075",
"pm_score": 0,
"selected": false,
"text": "<p>In the explained scenario I think that the correct naming should be (technically speaking):<br>\n<code>t2</code>is the parent of <code>t1</code><br>\n<code>t1</code> is the child of <code>t2</code></p>\n\n<p>The table of the constrained column is called <strong>child</strong>, while the table of the referenced column is called <strong>parent</strong>.</p>\n\n<p>Personally I dislike this naming, in SQL SERVER when you are querying for the <code>sys.foreign_keys</code> view the child table is called <code>parent_object_id</code>, while the referenced table is called <code>referenced_object_id</code>.. from the point of view of the constraint itself, could be right.. but at the end this is very confusing.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258134",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
I'm doing some FK analysis of our tables by making a directed
graph representing FK dependencies and then traversing the
graph. In my code, I name everything using directed graph
terminology, but I'd like to have something a bit more
"user friendly" in the report.
In this scenario:
```
create table t1(a varchar2(20));
alter table t1 add constraint t1_fk foreign key(a) references t2(b);
```
t1.a must exist in t2.b. So, what words should I use in the blanks?
```
t1 is the _______ of t2.
t2 is the _______ of t1.
```
Many TIA!
|
I'd say (things between brackets are optional, but I'd use them)
```
[Column a of] table t1 references [column b of] table t2
```
and
```
[Column b of] table t2 is referenced by [column a of] table t1
```
?
I'd also specify the action that happens on delete/update if any.
```
Column b of table t2 is referenced by column a of table t1.
Deleting a record in table t2 will delete matching records on table t1
```
|
258,136 |
<p>I am investigating a production system where there are several Windows services communicating with each other through TCP/IP sockets. I'm trying to figure out which executable is listening to which IP address and which port on a given machine.</p>
<p>Other than rummaging through each windows service's obscure configuration files, is there a system tool that can more easily give me the details I want?</p>
|
[
{
"answer_id": 258139,
"author": "begray",
"author_id": 12123,
"author_profile": "https://Stackoverflow.com/users/12123",
"pm_score": 0,
"selected": false,
"text": "<p>Command line netstat tool might help you. To learn available parameters run it with /?: netstat /?</p>\n\n<p>Or there is a better GUI alternative: SysInternals TcpView (freely downloadable from ms site)</p>\n"
},
{
"answer_id": 258140,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 2,
"selected": false,
"text": "<p>Give this a whirl.</p>\n\n<pre><code>netstat -abn\n</code></pre>\n"
},
{
"answer_id": 258147,
"author": "Gordon Thompson",
"author_id": 21299,
"author_profile": "https://Stackoverflow.com/users/21299",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx</a></p>\n\n<p>SysInternals TCPView is great</p>\n"
},
{
"answer_id": 258153,
"author": "mkoeller",
"author_id": 33433,
"author_profile": "https://Stackoverflow.com/users/33433",
"pm_score": 6,
"selected": true,
"text": "<p>As already mentioned <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx\" rel=\"noreferrer\">TCPView</a> by SysInternals (i.e. Microsoft) is a great tool.\nBut on production systems you may not be allowed to install additional software, so I think you may want to try out netstat.exe, which is typically located at C:\\WINNT\\system32\\netstat.exe .</p>\n\n<p>A help page is available with </p>\n\n<pre><code>netstat -?\n</code></pre>\n\n<p>Examples are:</p>\n\n<pre><code>netstat -a\n</code></pre>\n\n<p>Lists all local TCP connections and listening ports together with remote TCP endpoint.</p>\n\n<pre><code>netstat -o\n</code></pre>\n\n<p>Adds the process ID to the output.</p>\n\n<pre><code>netstat -b \n</code></pre>\n\n<p>Gives you the name of the executable wich was involved in establishing this connection/port.</p>\n"
},
{
"answer_id": 14195750,
"author": "urig",
"author_id": 33404,
"author_profile": "https://Stackoverflow.com/users/33404",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks everyone. Very helpful indeed. A friend also introduced me to a freeware utility called \"Active Ports\" from DeviceLock: <a href=\"http://www.devicelock.com/freeware.html/\" rel=\"nofollow\">http://www.devicelock.com/freeware.html/</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33404/"
] |
I am investigating a production system where there are several Windows services communicating with each other through TCP/IP sockets. I'm trying to figure out which executable is listening to which IP address and which port on a given machine.
Other than rummaging through each windows service's obscure configuration files, is there a system tool that can more easily give me the details I want?
|
As already mentioned [TCPView](http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx) by SysInternals (i.e. Microsoft) is a great tool.
But on production systems you may not be allowed to install additional software, so I think you may want to try out netstat.exe, which is typically located at C:\WINNT\system32\netstat.exe .
A help page is available with
```
netstat -?
```
Examples are:
```
netstat -a
```
Lists all local TCP connections and listening ports together with remote TCP endpoint.
```
netstat -o
```
Adds the process ID to the output.
```
netstat -b
```
Gives you the name of the executable wich was involved in establishing this connection/port.
|
258,172 |
<p>I'm operating a neighbourhood <a href="http://maps.google.de/maps/ms?ie=UTF8&hl=de&msa=0&msid=101021148567197540440.00043fcffa4cdf06fb4bc&ll=51.791948,8.173571&spn=0.033976,0.058365&t=h&z=14" rel="nofollow noreferrer">WIFI network in a rural environment</a>.</p>
<p>Now I'm looking fo a monitoring tool to run on a server (Windows or Linux) which would track bandwidth, uptime (clients as well as internet connection), etc...
Most of this information is exposed via SNMP by my routers and access points, so SNMP support is required.</p>
<p>Additional features should be: </p>
<ul>
<li>Graphical data representation</li>
<li>free license</li>
</ul>
<p>So what's the best choice for me?</p>
<p><em>Edit</em> These are the tools mentioned so far:</p>
<ul>
<li><a href="http://oss.oetiker.ch/mrtg/" rel="nofollow noreferrer">MRTG</a></li>
<li><a href="http://munin.projects.linpro.no/" rel="nofollow noreferrer">Munin</a></li>
<li><a href="http://www.nagios.org/" rel="nofollow noreferrer">Nagios</a></li>
<li><a href="http://www.zenoss.com/product/core" rel="nofollow noreferrer">Zenoss Core</a></li>
<li><a href="http://www.ntop.org/" rel="nofollow noreferrer">ntop</a></li>
<li><a href="http://cacti.net/features.php" rel="nofollow noreferrer">cacti</a></li>
<li><a href="http://www.zabbix.com/" rel="nofollow noreferrer">ZABBIX</a></li>
</ul>
|
[
{
"answer_id": 258200,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this fits your usage but a lot of web hosting provider uses <a href=\"http://www.nagios.org/\" rel=\"nofollow noreferrer\"> Nagios</a> for network monitoring</p>\n"
},
{
"answer_id": 258216,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://oss.oetiker.ch/mrtg/\" rel=\"nofollow noreferrer\">MRTG</a> is probably the easiest to setup. If your router has SNMP (as you mention), to setup it's a single command:</p>\n\n<pre><code>cfgmaker --output=mrtg_myrouter.cfg [email protected]\n</code></pre>\n\n<p>MRTG is good for high-bandwidth routers and the likes. It's not great for other data (it can be coerced into graphing most things, but it's a little unintuitive to setup)</p>\n\n<p>For monitoring other stuff I like <a href=\"http://munin.projects.linpro.no/\" rel=\"nofollow noreferrer\">Munin</a>. I would describe it again, but I posted an answer a while ago <a href=\"https://stackoverflow.com/questions/40737/generate-disk-usage-graphscharts-with-cli-only-tools-in-linux#43733\">here</a> (about graphing disc-usage).</p>\n\n<p>Munin can of course graph network usage, and easily pull data via SNMP (in fact it's the recommended setup for grabbing data from Windows-based servers - run a SNMP daemon on the Windows machine, and have Munin connect to this). The graphs are also prettier than MRG, I would say (clearly the most important factor..)</p>\n\n<p>There's an example installation of <a href=\"http://www.switch.ch/network/operation/statistics/geant2.html\" rel=\"nofollow noreferrer\">MRTG here</a>, and <a href=\"http://munin.ping.uio.no/\" rel=\"nofollow noreferrer\">Munin here</a></p>\n"
},
{
"answer_id": 258302,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.zenoss.com/product/core\" rel=\"nofollow noreferrer\">Zenoss Core</a> is free and open source. It keeps RRD graphs (like other monitoring tools mentioned here). To monitor parameters other than basic network bandwidth (and up state), the switch or router SNMP definitions and MIBs should be available as a <a href=\"http://www.zenoss.com/community/projects/zenpacks/\" rel=\"nofollow noreferrer\">ZenPack</a>. Runs on a Linux (virtual?) server. Uses Google Maps to display link status.</p>\n"
},
{
"answer_id": 258681,
"author": "Harald Scheirich",
"author_id": 22080,
"author_profile": "https://Stackoverflow.com/users/22080",
"pm_score": 1,
"selected": false,
"text": "<p>I have been using <a href=\"http://www.ntop.org/\" rel=\"nofollow noreferrer\">ntop</a> it is free on linux and for purchase if you want a windows binary and worked pretty well for us</p>\n"
},
{
"answer_id": 606633,
"author": "Kazimieras Aliulis",
"author_id": 53319,
"author_profile": "https://Stackoverflow.com/users/53319",
"pm_score": 2,
"selected": false,
"text": "<p>IMHO, <a href=\"http://cacti.net/\" rel=\"nofollow noreferrer\">Cacti</a> is easiest to install and use.</p>\n\n<p><a href=\"http://www.zabbix.com/\" rel=\"nofollow noreferrer\">Zabbix</a> is interesting, but harder to use.</p>\n\n<p>And <a href=\"http://www.slac.stanford.edu/xorg/nmtf/nmtf-tools.html\" rel=\"nofollow noreferrer\">here</a> is a very comprehensive list of all network monitoring tools.</p>\n"
},
{
"answer_id": 704989,
"author": "Martijn Heemels",
"author_id": 35434,
"author_profile": "https://Stackoverflow.com/users/35434",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same question last week and tried several options.</p>\n\n<p>For basic snmp graphing needs, <strong>cacti</strong> is great, but graphing apache, mysql, etc. is a bit too hard I think.</p>\n\n<p><strong>ntop</strong> is also a nice tool, but has a different usecase than the other ones in your list.</p>\n\n<p>You should look at <strong>Zenoss</strong>. The Core version is FOSS, userfriendly, and very powerful. I had no need for the Enterprise version, but your needs may differ.\nIt does graphing, monitoring and alerting of all the basic stats, but download some ZenPacks and you can easily add Apache, MySQL or many other stats. All configuration can be done via the GUI. The interface is clear and responsive and allows for easy management of very large networks.</p>\n\n<p>In short, I'm glad I never spent much time on <strong>Nagios</strong>, because I believe Zenoss is the best option available.</p>\n"
},
{
"answer_id": 23626845,
"author": "M. Adel",
"author_id": 3584922,
"author_profile": "https://Stackoverflow.com/users/3584922",
"pm_score": 0,
"selected": false,
"text": "<p>Also consider <a href=\"http://cactiez.cactiusers.org/\" rel=\"nofollow\">CactiEZ</a> on a VM or small server, it is a baremetal CentOS 6 based system.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33433/"
] |
I'm operating a neighbourhood [WIFI network in a rural environment](http://maps.google.de/maps/ms?ie=UTF8&hl=de&msa=0&msid=101021148567197540440.00043fcffa4cdf06fb4bc&ll=51.791948,8.173571&spn=0.033976,0.058365&t=h&z=14).
Now I'm looking fo a monitoring tool to run on a server (Windows or Linux) which would track bandwidth, uptime (clients as well as internet connection), etc...
Most of this information is exposed via SNMP by my routers and access points, so SNMP support is required.
Additional features should be:
* Graphical data representation
* free license
So what's the best choice for me?
*Edit* These are the tools mentioned so far:
* [MRTG](http://oss.oetiker.ch/mrtg/)
* [Munin](http://munin.projects.linpro.no/)
* [Nagios](http://www.nagios.org/)
* [Zenoss Core](http://www.zenoss.com/product/core)
* [ntop](http://www.ntop.org/)
* [cacti](http://cacti.net/features.php)
* [ZABBIX](http://www.zabbix.com/)
|
[MRTG](http://oss.oetiker.ch/mrtg/) is probably the easiest to setup. If your router has SNMP (as you mention), to setup it's a single command:
```
cfgmaker --output=mrtg_myrouter.cfg [email protected]
```
MRTG is good for high-bandwidth routers and the likes. It's not great for other data (it can be coerced into graphing most things, but it's a little unintuitive to setup)
For monitoring other stuff I like [Munin](http://munin.projects.linpro.no/). I would describe it again, but I posted an answer a while ago [here](https://stackoverflow.com/questions/40737/generate-disk-usage-graphscharts-with-cli-only-tools-in-linux#43733) (about graphing disc-usage).
Munin can of course graph network usage, and easily pull data via SNMP (in fact it's the recommended setup for grabbing data from Windows-based servers - run a SNMP daemon on the Windows machine, and have Munin connect to this). The graphs are also prettier than MRG, I would say (clearly the most important factor..)
There's an example installation of [MRTG here](http://www.switch.ch/network/operation/statistics/geant2.html), and [Munin here](http://munin.ping.uio.no/)
|
258,173 |
<p>I'm doing .NET 3.5 programming in VB for a class. I have a .mdb database with 3 related tables, and a table adapter with some queries on it that look like this:</p>
<pre><code>SELECT PropertyID, Street, Unit, City, Zip, Type, Bedrooms, Bathrooms, Area, MonthlyRent
FROM tblProperties
</code></pre>
<p>Then in a form i have a DataGridView. What i want to do is take the data that is returned from the query and display it in the DGV. However, when i do this, it displays all 35 columns in the database, not the 10 i selected (The ten are the only ones that have data in them however... so it's basically a table with a bunch of blank columns).</p>
<p>My current, inelegant solution is to return the query to a DataTable, then iterate through the table's columns, deleting the one's i dont want. This is not robust, efficient, and does not like me delete the primary key column.</p>
<p>My TA suggested trying to use an untyped databinding... he said this should display only the data I pull, but neither of us has been able to figure this out yet.</p>
<p>Thank You!</p>
<p>UPDATE</p>
<p>I'm not sure what you mean by the .aspx/.aspx.vb pages, but this is the query code i have from the table adapter</p>
<pre><code>SELECT tblRent.PaymentID, tblTenant.TenantName, tblProperties.Street, tblProperties.Unit, tblProperties.City, tblRent.AmountPaid, tblRent.PaymentDate,
tblTenant.Telephone
FROM ((tblProperties INNER JOIN
tblRent ON tblProperties.PropertyID = tblRent.PropertyID) INNER JOIN
tblTenant ON tblProperties.PropertyID = tblTenant.PropertyID)
</code></pre>
<p>and here is where i use it in code:</p>
<pre><code>Public Sub getRent()
propView.DataSource = TblPropertiesTableAdapter.GetAllRentReceipts()
propView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
propView.ReadOnly = True
End Sub
</code></pre>
<p>propView is a DataGridView that does not have a DataSource selected at load</p>
|
[
{
"answer_id": 258200,
"author": "paan",
"author_id": 2976,
"author_profile": "https://Stackoverflow.com/users/2976",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if this fits your usage but a lot of web hosting provider uses <a href=\"http://www.nagios.org/\" rel=\"nofollow noreferrer\"> Nagios</a> for network monitoring</p>\n"
},
{
"answer_id": 258216,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://oss.oetiker.ch/mrtg/\" rel=\"nofollow noreferrer\">MRTG</a> is probably the easiest to setup. If your router has SNMP (as you mention), to setup it's a single command:</p>\n\n<pre><code>cfgmaker --output=mrtg_myrouter.cfg [email protected]\n</code></pre>\n\n<p>MRTG is good for high-bandwidth routers and the likes. It's not great for other data (it can be coerced into graphing most things, but it's a little unintuitive to setup)</p>\n\n<p>For monitoring other stuff I like <a href=\"http://munin.projects.linpro.no/\" rel=\"nofollow noreferrer\">Munin</a>. I would describe it again, but I posted an answer a while ago <a href=\"https://stackoverflow.com/questions/40737/generate-disk-usage-graphscharts-with-cli-only-tools-in-linux#43733\">here</a> (about graphing disc-usage).</p>\n\n<p>Munin can of course graph network usage, and easily pull data via SNMP (in fact it's the recommended setup for grabbing data from Windows-based servers - run a SNMP daemon on the Windows machine, and have Munin connect to this). The graphs are also prettier than MRG, I would say (clearly the most important factor..)</p>\n\n<p>There's an example installation of <a href=\"http://www.switch.ch/network/operation/statistics/geant2.html\" rel=\"nofollow noreferrer\">MRTG here</a>, and <a href=\"http://munin.ping.uio.no/\" rel=\"nofollow noreferrer\">Munin here</a></p>\n"
},
{
"answer_id": 258302,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.zenoss.com/product/core\" rel=\"nofollow noreferrer\">Zenoss Core</a> is free and open source. It keeps RRD graphs (like other monitoring tools mentioned here). To monitor parameters other than basic network bandwidth (and up state), the switch or router SNMP definitions and MIBs should be available as a <a href=\"http://www.zenoss.com/community/projects/zenpacks/\" rel=\"nofollow noreferrer\">ZenPack</a>. Runs on a Linux (virtual?) server. Uses Google Maps to display link status.</p>\n"
},
{
"answer_id": 258681,
"author": "Harald Scheirich",
"author_id": 22080,
"author_profile": "https://Stackoverflow.com/users/22080",
"pm_score": 1,
"selected": false,
"text": "<p>I have been using <a href=\"http://www.ntop.org/\" rel=\"nofollow noreferrer\">ntop</a> it is free on linux and for purchase if you want a windows binary and worked pretty well for us</p>\n"
},
{
"answer_id": 606633,
"author": "Kazimieras Aliulis",
"author_id": 53319,
"author_profile": "https://Stackoverflow.com/users/53319",
"pm_score": 2,
"selected": false,
"text": "<p>IMHO, <a href=\"http://cacti.net/\" rel=\"nofollow noreferrer\">Cacti</a> is easiest to install and use.</p>\n\n<p><a href=\"http://www.zabbix.com/\" rel=\"nofollow noreferrer\">Zabbix</a> is interesting, but harder to use.</p>\n\n<p>And <a href=\"http://www.slac.stanford.edu/xorg/nmtf/nmtf-tools.html\" rel=\"nofollow noreferrer\">here</a> is a very comprehensive list of all network monitoring tools.</p>\n"
},
{
"answer_id": 704989,
"author": "Martijn Heemels",
"author_id": 35434,
"author_profile": "https://Stackoverflow.com/users/35434",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same question last week and tried several options.</p>\n\n<p>For basic snmp graphing needs, <strong>cacti</strong> is great, but graphing apache, mysql, etc. is a bit too hard I think.</p>\n\n<p><strong>ntop</strong> is also a nice tool, but has a different usecase than the other ones in your list.</p>\n\n<p>You should look at <strong>Zenoss</strong>. The Core version is FOSS, userfriendly, and very powerful. I had no need for the Enterprise version, but your needs may differ.\nIt does graphing, monitoring and alerting of all the basic stats, but download some ZenPacks and you can easily add Apache, MySQL or many other stats. All configuration can be done via the GUI. The interface is clear and responsive and allows for easy management of very large networks.</p>\n\n<p>In short, I'm glad I never spent much time on <strong>Nagios</strong>, because I believe Zenoss is the best option available.</p>\n"
},
{
"answer_id": 23626845,
"author": "M. Adel",
"author_id": 3584922,
"author_profile": "https://Stackoverflow.com/users/3584922",
"pm_score": 0,
"selected": false,
"text": "<p>Also consider <a href=\"http://cactiez.cactiusers.org/\" rel=\"nofollow\">CactiEZ</a> on a VM or small server, it is a baremetal CentOS 6 based system.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33583/"
] |
I'm doing .NET 3.5 programming in VB for a class. I have a .mdb database with 3 related tables, and a table adapter with some queries on it that look like this:
```
SELECT PropertyID, Street, Unit, City, Zip, Type, Bedrooms, Bathrooms, Area, MonthlyRent
FROM tblProperties
```
Then in a form i have a DataGridView. What i want to do is take the data that is returned from the query and display it in the DGV. However, when i do this, it displays all 35 columns in the database, not the 10 i selected (The ten are the only ones that have data in them however... so it's basically a table with a bunch of blank columns).
My current, inelegant solution is to return the query to a DataTable, then iterate through the table's columns, deleting the one's i dont want. This is not robust, efficient, and does not like me delete the primary key column.
My TA suggested trying to use an untyped databinding... he said this should display only the data I pull, but neither of us has been able to figure this out yet.
Thank You!
UPDATE
I'm not sure what you mean by the .aspx/.aspx.vb pages, but this is the query code i have from the table adapter
```
SELECT tblRent.PaymentID, tblTenant.TenantName, tblProperties.Street, tblProperties.Unit, tblProperties.City, tblRent.AmountPaid, tblRent.PaymentDate,
tblTenant.Telephone
FROM ((tblProperties INNER JOIN
tblRent ON tblProperties.PropertyID = tblRent.PropertyID) INNER JOIN
tblTenant ON tblProperties.PropertyID = tblTenant.PropertyID)
```
and here is where i use it in code:
```
Public Sub getRent()
propView.DataSource = TblPropertiesTableAdapter.GetAllRentReceipts()
propView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)
propView.ReadOnly = True
End Sub
```
propView is a DataGridView that does not have a DataSource selected at load
|
[MRTG](http://oss.oetiker.ch/mrtg/) is probably the easiest to setup. If your router has SNMP (as you mention), to setup it's a single command:
```
cfgmaker --output=mrtg_myrouter.cfg [email protected]
```
MRTG is good for high-bandwidth routers and the likes. It's not great for other data (it can be coerced into graphing most things, but it's a little unintuitive to setup)
For monitoring other stuff I like [Munin](http://munin.projects.linpro.no/). I would describe it again, but I posted an answer a while ago [here](https://stackoverflow.com/questions/40737/generate-disk-usage-graphscharts-with-cli-only-tools-in-linux#43733) (about graphing disc-usage).
Munin can of course graph network usage, and easily pull data via SNMP (in fact it's the recommended setup for grabbing data from Windows-based servers - run a SNMP daemon on the Windows machine, and have Munin connect to this). The graphs are also prettier than MRG, I would say (clearly the most important factor..)
There's an example installation of [MRTG here](http://www.switch.ch/network/operation/statistics/geant2.html), and [Munin here](http://munin.ping.uio.no/)
|
258,198 |
<p>inside my C# app I runs a 7z process to extract an archive into it's directory</p>
<p>the archive is located in a random-named directory on the %TEMP% directory for example</p>
<blockquote>
<p>C:\Documents and Settings\User\Local
Settings\Temp\vtugoyrc.fd2</p>
</blockquote>
<p>(fullPathFilename = "C:\Documents and Settings\User\Local Settings\Temp\vtugoyrc.fd2\xxx.7z")</p>
<p>my code is:</p>
<pre><code>sevenZipProcessInfo.FileName = SEVEN_ZIP_EXECUTABLE_PATH;
sevenZipProcessInfo.Arguments = "x " + fullPathFilename;
sevenZipProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
sevenZipProcessInfo.UseShellExecute = true;
sevenZipProcessInfo.WorkingDirectory = Path.GetDirectoryName(fullPathFilename);
Process sevenZipProcess = Process.Start(sevenZipProcessInfo);
if (sevenZipProcess != null)
{
sevenZipProcess.WaitForExit();
if (sevenZipProcess.ExitCode != 0)
...exit code is 2 (fatal error by the 7z help)
</code></pre>
<p>Where can I find more elaborate documentation ?</p>
|
[
{
"answer_id": 258206,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 3,
"selected": false,
"text": "<p>You're using 7 Zip as an external process here. Its the equivalent of calling the commands directly from the command line.</p>\n\n<p>Have you considered using an actual Library for zipping/unzipping your files. Something you can reference in your C# project.</p>\n\n<p><a href=\"http://www.icsharpcode.net/OpenSource/SharpZipLib/\" rel=\"nofollow noreferrer\">Sharp Zip Lib</a> is fairly well reknowned but heres a specific <a href=\"http://innerlimit.googlepages.com/sevenzipinterface\" rel=\"nofollow noreferrer\">wrapper library</a> for using the 7zip archive</p>\n"
},
{
"answer_id": 258338,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming that the process writes errors to stderr/stdout, you could set UseShellExecute to false, and redirect stdout/stderr; there is an example on MSDN <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandarderror.aspx\" rel=\"nofollow noreferrer\">here</a> (stderr) and <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.redirectstandardoutput.aspx\" rel=\"nofollow noreferrer\">here</a> (stdout).</p>\n\n<p>If you need to read from both stderr <strong>and</strong> stdout, <strong>and</strong> use <code>WaitForExit()</code>, then things get more interesting - usually involving either a few threads, or async methods.</p>\n\n<p>One other final option is to use pipe redirection in the command - i.e. <code>1>out.txt 2>&1</code> - this pipes stdout into out.txt, and pipes stderr into stdout, so this <em>also</em> goes into out.txt. Then read from <code>out.txt</code>.</p>\n"
},
{
"answer_id": 258670,
"author": "Hanan",
"author_id": 30324,
"author_profile": "https://Stackoverflow.com/users/30324",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for all help.</p>\n\n<p>Anyhow the problem was the use of 'long-path-name' -> command-line process can't find C:\\Documents and Settings\\ (because of the spaces in the name). Solutions to this can be found \nhere <a href=\"https://stackoverflow.com/questions/258367/standard-way-to-convert-to-long-path-in-net\">standard way to convert to short path in .net</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30324/"
] |
inside my C# app I runs a 7z process to extract an archive into it's directory
the archive is located in a random-named directory on the %TEMP% directory for example
>
> C:\Documents and Settings\User\Local
> Settings\Temp\vtugoyrc.fd2
>
>
>
(fullPathFilename = "C:\Documents and Settings\User\Local Settings\Temp\vtugoyrc.fd2\xxx.7z")
my code is:
```
sevenZipProcessInfo.FileName = SEVEN_ZIP_EXECUTABLE_PATH;
sevenZipProcessInfo.Arguments = "x " + fullPathFilename;
sevenZipProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
sevenZipProcessInfo.UseShellExecute = true;
sevenZipProcessInfo.WorkingDirectory = Path.GetDirectoryName(fullPathFilename);
Process sevenZipProcess = Process.Start(sevenZipProcessInfo);
if (sevenZipProcess != null)
{
sevenZipProcess.WaitForExit();
if (sevenZipProcess.ExitCode != 0)
...exit code is 2 (fatal error by the 7z help)
```
Where can I find more elaborate documentation ?
|
You're using 7 Zip as an external process here. Its the equivalent of calling the commands directly from the command line.
Have you considered using an actual Library for zipping/unzipping your files. Something you can reference in your C# project.
[Sharp Zip Lib](http://www.icsharpcode.net/OpenSource/SharpZipLib/) is fairly well reknowned but heres a specific [wrapper library](http://innerlimit.googlepages.com/sevenzipinterface) for using the 7zip archive
|
258,211 |
<pre><code>#!/bin/bash
hello()
{
SRC=$1
DEST=$2
for IP in `cat /opt/ankit/configs/machine.configs` ; do
echo $SRC | grep '*' > /dev/null
if test `echo $?` -eq 0 ; then
for STAR in $SRC ; do
echo -en "$IP"
echo -en "\n\t ARG1=$STAR ARG2=$2\n\n"
done
else
echo -en "$IP"
echo -en "\n\t ARG1=$SRC ARG2=$DEST\n\n"
fi
done
}
hello $1 $2
</code></pre>
<p>The above is the shell script which I provide source (SRC) & desitnation (DEST) path. It worked fine when I did not put in a SRC path with wild card '<em>'. When I run this shell script and give '</em>'.pdf or '*'as follows:</p>
<pre><code>root@ankit1:~/as_prac# ./test.sh /home/dev/Examples/*.pdf /ankit_test/as
</code></pre>
<p>I get the following output:</p>
<pre><code>192.168.1.6
ARG1=/home/dev/Examples/case_Contact.pdf ARG2=/home/dev/Examples/case_howard_county_library.pdf
</code></pre>
<p>The DEST is /ankit_test/as but DEST also get manupulated due to '*'. The expected answer is </p>
<pre><code>ARG1=/home/dev/Examples/case_Contact.pdf ARG2=/ankit_test/as
</code></pre>
<p>So, if you understand what I am trying to do, please help me out to solve this BUG.
I'll be grateful to you.</p>
<p>Thanks in advance!!!</p>
<p>I need to know exactly how I use '*.pdf' in my program one by one without disturbing DEST.</p>
|
[
{
"answer_id": 258232,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 2,
"selected": false,
"text": "<p>The shell will expand wildcards unless you escape them, so for example if you have </p>\n\n<pre><code>$ ls\none.pdf two.pdf three.pdf\n</code></pre>\n\n<p>and run your script as</p>\n\n<pre><code>./test.sh *.pdf /ankit__test/as\n</code></pre>\n\n<p>it will be the same as </p>\n\n<pre><code>./test.sh one.pdf two.pdf three.pdf /ankit__test/as\n</code></pre>\n\n<p>which is not what you expect. Doing</p>\n\n<pre><code>./test.sh \\*.pdf /ankit__test/as\n</code></pre>\n\n<p>should work.</p>\n"
},
{
"answer_id": 258245,
"author": "dogbane",
"author_id": 7412,
"author_profile": "https://Stackoverflow.com/users/7412",
"pm_score": 1,
"selected": false,
"text": "<p>You are also missing a final \"done\" to close your outer for loop.</p>\n"
},
{
"answer_id": 258252,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 0,
"selected": false,
"text": "<p>There's no need to spawn a shell to look at the <code>$?</code> variable, you can evaluate it directly.</p>\n\n<p>It should just be:</p>\n\n<pre><code>if [ $? -eq 0 ]; then\n</code></pre>\n"
},
{
"answer_id": 258298,
"author": "dogbane",
"author_id": 7412,
"author_profile": "https://Stackoverflow.com/users/7412",
"pm_score": 2,
"selected": false,
"text": "<p>Your script needs more work. \nEven after escaping the wildcard, you won't get your expected answer. You will get:</p>\n\n<pre><code>ARG1=/home/dev/Examples/*.pdf ARG2=/ankit__test/as\n</code></pre>\n\n<p>Try the following instead:</p>\n\n<pre><code>for IP in `cat /opt/ankit/configs/machine.configs`\ndo\n for i in $SRC\n do\n echo -en \"$IP\"\n echo -en \"\\n\\t ARG1=$i ARG2=$DEST\\n\\n\"\n done\ndone\n</code></pre>\n\n<p>Run it like this:</p>\n\n<pre><code>root@ankit1:~/as_prac# ./test.sh \"/home/dev/Examples/*.pdf\" /ankit__test/as\n</code></pre>\n"
},
{
"answer_id": 258309,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 1,
"selected": false,
"text": "<p>OK, this appears to do what you want:</p>\n\n<pre><code>#!/bin/bash\n\nhello() {\n\n SRC=$1\n DEST=$2\n\n while read IP ; do\n for FILE in $SRC; do\n echo -e \"$IP\"\n echo -e \"\\tARG1=$FILE ARG2=$DEST\\n\"\n done\n done < /tmp/machine.configs\n }\n\n hello \"$1\" $2\n</code></pre>\n\n<ol>\n<li>You still need to escape any wildcard characters when you invoke the script</li>\n<li>The double quotes are necessary when you invoke the <code>hello</code> function, otherwise the mere fact of evaluating <code>$1</code> causes the wildcard to be expanded, but we don't want that to happen until <code>$SRC</code> is assigned in the function</li>\n</ol>\n"
},
{
"answer_id": 258330,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 2,
"selected": false,
"text": "<p>If you can, change the order of the parameters passed to your shell script as follows:</p>\n\n<pre><code>./test.sh /ankit_test/as /home/dev/Examples/*.pdf\n</code></pre>\n\n<p>That would make your life a lot easier since the variable part moves to the end of the line. Then, the following script will do what you want:</p>\n\n<pre><code>#!/bin/bash\nhello()\n{\n SRC=$1\n DEST=$2\n\n for IP in `cat /opt/ankit/configs/machine.configs` ; do\n echo -en \"$IP\"\n echo -en \"\\n\\t ARG1=$SRC ARG2=$DEST\\n\\n\"\n done\n}\n\narg2=$1\nshift\nwhile [[ \"$1\" != \"\" ]] ; do\n hello $1 $arg2\n shift\ndone\n</code></pre>\n"
},
{
"answer_id": 266187,
"author": "godbyk",
"author_id": 4214,
"author_profile": "https://Stackoverflow.com/users/4214",
"pm_score": 1,
"selected": false,
"text": "<p>Here's what I came up with:</p>\n\n<pre><code>#!/bin/bash\n\nhello()\n{\n # DEST will contain the last argument\n eval DEST=\\$$#\n\n while [ $1 != $DEST ]; do\n SRC=$1\n\n for IP in `cat /opt/ankit/configs/machine.configs`; do\n echo -en \"$IP\"\n echo -en \"\\n\\t ARG1=$SRC ARG2=$DEST\\n\\n\"\n done\n\n shift || break\n done\n}\n\nhello $*\n</code></pre>\n\n<p>Instead of passing only two parameters to the hello() function, we'll pass in all the arguments that the script got. </p>\n\n<p>Inside the hello() function, we first assign the final argument to the DEST var. Then we loop through all of the arguments, assigning each one to SRC, and run whatever commands we want using the SRC and DEST arguments. Note that you may want to put quotation marks around $SRC and $DEST in case they contain spaces. We stop looping when SRC is the same as DEST because that means we've hit the final argument (the destination).</p>\n"
},
{
"answer_id": 10163215,
"author": "dannysauer",
"author_id": 65589,
"author_profile": "https://Stackoverflow.com/users/65589",
"pm_score": 0,
"selected": false,
"text": "<p>You're running</p>\n\n<pre><code>./test.sh /home/dev/Examples/*.pdf /ankit_test/as \n</code></pre>\n\n<p>and your interactive shell is expanding the wildcard before the script gets it. You just need to quote the first argument when you launch it, as in</p>\n\n<pre><code>./test.sh \"/home/dev/Examples/*.pdf\" /ankit_test/as\n</code></pre>\n\n<p>and then, in your script, quote \"$SRC\" anywhere where you literally want the things with wildcards (ie, when you do <code>echo $SRC</code>, instead use <code>echo \"$SRC\"</code>) and leave it unquoted when you want the wildcards expanded. Basically, always put quotes around things which might contain shell metacharacters unless you want the metacharacters interpreted. :)</p>\n"
},
{
"answer_id": 11780892,
"author": "Mike L",
"author_id": 1239140,
"author_profile": "https://Stackoverflow.com/users/1239140",
"pm_score": 1,
"selected": false,
"text": "<p>For multiple input files using a wildcard such as *.txt, I found this to work perfectly, no escaping required. It should work just like a native bash app like \"ls\" or \"rm.\" This was not documented just about anywhere so since I spent a better part of 3 days trying to figure it out I decided I should post it for future readers.</p>\n\n<p>Directory contains the following files (output of ls)</p>\n\n<pre><code>file1.txt file2.txt file3.txt\n</code></pre>\n\n<p>Run script like</p>\n\n<pre><code>$ ./script.sh *.txt\n</code></pre>\n\n<p>Or even like</p>\n\n<pre><code>$ ./script.sh file{1..3}.txt\n</code></pre>\n\n<p>The script</p>\n\n<pre><code>#!/bin/bash\n\n# store default IFS, we need to temporarily change this\nsfi=$IFS\n\n#set IFS to $'\\n\\' - new line\nIFS=$'\\n'\n\nif [[ -z $@ ]]\n then\n echo \"Error: Missing required argument\"\n echo\n exit 1\nfi\n\n# Put the file glob into an array\nfile=(\"$@\")\n\n# Now loop through them\nfor (( i=0 ; i < ${#file[*]} ; i++ ));\ndo\n\n if [ -w ${file[$i]} ]; then\n echo ${file[$i]} \" writable\" \n else\n echo ${file[$i]} \" NOT writable\"\n fi\ndone\n\n# Reset IFS to its default value\nIFS=$sfi\n</code></pre>\n\n<p>The output</p>\n\n<pre><code>file1.txt writable\nfile2.txt writable\nfile3.txt writable\n</code></pre>\n\n<p>The key was switching the IFS (Internal Field Separator) temporarily. You have to be sure to store this before switching and then switch it back when you are done with it as demonstrated above.</p>\n\n<p>Now you have a list of expanded files (<strong>with spaces escaped</strong>) in the file[] array which you can then loop through. I like this solution the best, easiest to program for and easiest for the users.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258211",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24813/"
] |
```
#!/bin/bash
hello()
{
SRC=$1
DEST=$2
for IP in `cat /opt/ankit/configs/machine.configs` ; do
echo $SRC | grep '*' > /dev/null
if test `echo $?` -eq 0 ; then
for STAR in $SRC ; do
echo -en "$IP"
echo -en "\n\t ARG1=$STAR ARG2=$2\n\n"
done
else
echo -en "$IP"
echo -en "\n\t ARG1=$SRC ARG2=$DEST\n\n"
fi
done
}
hello $1 $2
```
The above is the shell script which I provide source (SRC) & desitnation (DEST) path. It worked fine when I did not put in a SRC path with wild card '*'. When I run this shell script and give '*'.pdf or '\*'as follows:
```
root@ankit1:~/as_prac# ./test.sh /home/dev/Examples/*.pdf /ankit_test/as
```
I get the following output:
```
192.168.1.6
ARG1=/home/dev/Examples/case_Contact.pdf ARG2=/home/dev/Examples/case_howard_county_library.pdf
```
The DEST is /ankit\_test/as but DEST also get manupulated due to '\*'. The expected answer is
```
ARG1=/home/dev/Examples/case_Contact.pdf ARG2=/ankit_test/as
```
So, if you understand what I am trying to do, please help me out to solve this BUG.
I'll be grateful to you.
Thanks in advance!!!
I need to know exactly how I use '\*.pdf' in my program one by one without disturbing DEST.
|
The shell will expand wildcards unless you escape them, so for example if you have
```
$ ls
one.pdf two.pdf three.pdf
```
and run your script as
```
./test.sh *.pdf /ankit__test/as
```
it will be the same as
```
./test.sh one.pdf two.pdf three.pdf /ankit__test/as
```
which is not what you expect. Doing
```
./test.sh \*.pdf /ankit__test/as
```
should work.
|
258,212 |
<p>I have a web server which saves cache files and keeps them for 7 days. The file names are md5 hashes, i.e. exactly 32 hex characters long, and are being kept in a tree structure that looks like this:</p>
<pre><code>00/
00/
00000ae9355e59a3d8a314a5470753d8
.
.
00/
01/
</code></pre>
<p>You get the idea.</p>
<p>My problem is that deleting old files is taking a really long time. I have a daily cron job that runs </p>
<pre><code>find cache/ -mtime +7 -type f -delete
</code></pre>
<p>which takes more than half a day to complete. I worry about scalability and the effect this has on the performance of the server. Additionally, the cache directory is now a black hole in my system, trapping the occasional innocent <code>du</code> or <code>find</code>.</p>
<p>The standard solution to LRU cache is some sort of a heap. Is there a way to scale this to the filesystem level?
Is there some other way to implement this in a way which makes it easier to manage?</p>
<p>Here are ideas I considered:</p>
<ol>
<li>Create 7 top directories, one for each week day, and empty one directory every day. This increases the seek time for a cache file 7-fold, makes it really complicated when a file is overwritten, and I'm not sure what it will do to the deletion time.</li>
<li>Save the files as blobs in a MySQL table with indexes on name and date. This seemed promising, but in practice it's always been much slower than FS. Maybe I'm not doing it right.</li>
</ol>
<p>Any ideas?</p>
|
[
{
"answer_id": 258215,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 0,
"selected": false,
"text": "<p>How about having a table in your database that uses the hash as the key. The other field would then be the name of the file. That way the file can be stored in a date-related fashion for fast deletion, and the database can be used for finding that file's location based on the hash in a fast fashion.</p>\n"
},
{
"answer_id": 258224,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/ReiserFS\" rel=\"nofollow noreferrer\">Reiserfs</a> is relatively efficient at handling small files. Did you try different Linux <a href=\"http://en.wikipedia.org/wiki/Comparison_of_file_systems\" rel=\"nofollow noreferrer\">file systems</a>? I'm not sure about delete performance - you can consider formatting (mkfs) as a substitute for individual file deletion. For example, you can create a different file system (cache1, cache2, ...) for each weekday.</p>\n"
},
{
"answer_id": 258227,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<p>When you store a file, make a symbolic link to a second directory structure that is organized by date, not by name. </p>\n\n<p>Retrieve your files using the \"name\" structure, delete them using the \"date\" structure.</p>\n"
},
{
"answer_id": 258233,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 1,
"selected": false,
"text": "<p>How about this:</p>\n\n<ul>\n<li>Have another folder called, say, \"ToDelete\"</li>\n<li>When you add a new item, get today's date and look for a subfolder in \"ToDelete\" that has a name indicative of the current date</li>\n<li>If it's not there, create it</li>\n<li>Add a symbolic link to the item you've created in today's folder</li>\n<li>Create a cron job that goes to the folder in \"ToDelete\" which is of the correct date and delete all the folders that are linked.</li>\n<li>Delete the folder which contained all the links.</li>\n</ul>\n"
},
{
"answer_id": 258266,
"author": "Anya Shenanigans",
"author_id": 17833,
"author_profile": "https://Stackoverflow.com/users/17833",
"pm_score": 2,
"selected": false,
"text": "<p>Assuming this is ext2/3 have you tried adding in the indexed directories? When you have a large number of files in any particular directory the lookup will be painfully slow to delete something.<br>\nuse tune2fs -o dir_index to enable the dir_index option.<br>\nWhen mounting a file system, make sure to use noatime option, which stops the OS from updating access time information for the directories (still needs to modify them).<br>\nLooking at the original post it seems as though you only have 2 levels of indirection to the files, which means that you can have a huge number of files in the leaf directories. When there are more than a million entries in these you will find that searches and changes are terribly slow. An alternative is to use a deeper hierarchy of directories, reducing the number of items in any particular directory, therefore reducing the cost of search and updates to the particular individual directory.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258212",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581/"
] |
I have a web server which saves cache files and keeps them for 7 days. The file names are md5 hashes, i.e. exactly 32 hex characters long, and are being kept in a tree structure that looks like this:
```
00/
00/
00000ae9355e59a3d8a314a5470753d8
.
.
00/
01/
```
You get the idea.
My problem is that deleting old files is taking a really long time. I have a daily cron job that runs
```
find cache/ -mtime +7 -type f -delete
```
which takes more than half a day to complete. I worry about scalability and the effect this has on the performance of the server. Additionally, the cache directory is now a black hole in my system, trapping the occasional innocent `du` or `find`.
The standard solution to LRU cache is some sort of a heap. Is there a way to scale this to the filesystem level?
Is there some other way to implement this in a way which makes it easier to manage?
Here are ideas I considered:
1. Create 7 top directories, one for each week day, and empty one directory every day. This increases the seek time for a cache file 7-fold, makes it really complicated when a file is overwritten, and I'm not sure what it will do to the deletion time.
2. Save the files as blobs in a MySQL table with indexes on name and date. This seemed promising, but in practice it's always been much slower than FS. Maybe I'm not doing it right.
Any ideas?
|
When you store a file, make a symbolic link to a second directory structure that is organized by date, not by name.
Retrieve your files using the "name" structure, delete them using the "date" structure.
|
258,218 |
<p>In MSBuild, I would like to call a task that extracts all the files in all the project in a specific solution and hold these files in a property that can be passed around to other tasks (for processing etc.)</p>
<p>I was thinking something along the lines of:</p>
<pre><code><ParseSolutionFile SolutionFile="$(TheSolutionFile)">
<Output TaskParameter="FilesFound" ItemName="AllFilesInSolution"/>
</ParseSolutionFile>
<Message Text="Found $(AllFilesInSolution)" />
</code></pre>
<p>which would output the list of all files in the projects in the solution and I could use the AllFilesInSolution property as input to other analysis tasks. Is this an already existing task or do I need to build it myself? If I need to build it myself, should the task output an array of strings or of ITaskItems or something else?</p>
|
[
{
"answer_id": 261037,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know about tasks, but there are already properties that hold all items. Just look in your typical project file and you'll see which collection they're being added to.</p>\n\n<p>Note the properties <strong>Content</strong>, <strong>Compile</strong>, <strong>Folder</strong>... any time you add a file to a project, it gets put in one of the main collections like this:</p>\n\n<pre><code><ItemGroup>\n <Content Include=\"Default.aspx\" />\n <Content Include=\"Web.config\" />\n</ItemGroup>\n<ItemGroup>\n <Compile Include=\"Default.aspx.cs\">\n <SubType>ASPXCodeBehind</SubType>\n <DependentUpon>Default.aspx</DependentUpon>\n </Compile>\n <Compile Include=\"Default.aspx.designer.cs\">\n <DependentUpon>Default.aspx</DependentUpon>\n </Compile>\n</ItemGroup>\n<ItemGroup>\n <Folder Include=\"App_Data\\\" />\n</ItemGroup>\n</code></pre>\n\n<p>Then you can do stuff like this to put the values from existing properties into your properties (the Condition attribute acts as a filter):</p>\n\n<pre><code><CreateItem Include=\"@(Content)\" Condition=\"'%(Extension)' == '.aspx'\">\n <Output TaskParameter=\"Include\" ItemName=\"ViewsContent\" />\n</CreateItem>\n</code></pre>\n\n<p>Or you can do it manually (the Include attribute uses the existing property OutputPath, but it indicates a path that inclues all files):</p>\n\n<pre><code><CreateItem Include=\"$(OutputPath)\\**\\*\">\n <Output TaskParameter=\"Include\" ItemName=\"OutputFiles\" />\n</CreateItem>\n</code></pre>\n\n<p>There are more details in the MSDN MSBuild documentation that I read when I was mucking with custom build tasks and stuff that was very helpful. Go read up on the CreateItem task and you'll be able to make more sense out of what I posted here. It's really easy to pick up on.</p>\n"
},
{
"answer_id": 22701810,
"author": "BozoJoe",
"author_id": 38461,
"author_profile": "https://Stackoverflow.com/users/38461",
"pm_score": 0,
"selected": false,
"text": "<p>I use the following for solutions with SSRS projects (which dont build under TFS w/o vs installed on the build box). Basically we require that the RDLs be bundled into a build output so we can mark a build for release.</p>\n\n<pre><code><Target Name=\"CopyArtifactstoDropLocation\">\n <CreateItem Include=\"$(SolutionRoot)\\**\\*.*\">\n <Output TaskParameter=\"Include\" ItemName=\"YourFilesToCopy\" />\n </CreateItem>\n\n <Copy\n SourceFiles=\"@(YourFilesToCopy)\"\n DestinationFiles=\"@(YourFilesToCopy->'$(DropLocation)\\$(BuildNumber)\\Release\\%(RecursiveDir)%(Filename)%(Extension)')\" />\n</Target>\n</code></pre>\n\n<p>Just replace the usage of the Copy Task with whatever you need to do with your bundle. Granted this is going to get everything in your solution root, but if your using TFS then you should only have buildable artifacts.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9222/"
] |
In MSBuild, I would like to call a task that extracts all the files in all the project in a specific solution and hold these files in a property that can be passed around to other tasks (for processing etc.)
I was thinking something along the lines of:
```
<ParseSolutionFile SolutionFile="$(TheSolutionFile)">
<Output TaskParameter="FilesFound" ItemName="AllFilesInSolution"/>
</ParseSolutionFile>
<Message Text="Found $(AllFilesInSolution)" />
```
which would output the list of all files in the projects in the solution and I could use the AllFilesInSolution property as input to other analysis tasks. Is this an already existing task or do I need to build it myself? If I need to build it myself, should the task output an array of strings or of ITaskItems or something else?
|
I don't know about tasks, but there are already properties that hold all items. Just look in your typical project file and you'll see which collection they're being added to.
Note the properties **Content**, **Compile**, **Folder**... any time you add a file to a project, it gets put in one of the main collections like this:
```
<ItemGroup>
<Content Include="Default.aspx" />
<Content Include="Web.config" />
</ItemGroup>
<ItemGroup>
<Compile Include="Default.aspx.cs">
<SubType>ASPXCodeBehind</SubType>
<DependentUpon>Default.aspx</DependentUpon>
</Compile>
<Compile Include="Default.aspx.designer.cs">
<DependentUpon>Default.aspx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<Folder Include="App_Data\" />
</ItemGroup>
```
Then you can do stuff like this to put the values from existing properties into your properties (the Condition attribute acts as a filter):
```
<CreateItem Include="@(Content)" Condition="'%(Extension)' == '.aspx'">
<Output TaskParameter="Include" ItemName="ViewsContent" />
</CreateItem>
```
Or you can do it manually (the Include attribute uses the existing property OutputPath, but it indicates a path that inclues all files):
```
<CreateItem Include="$(OutputPath)\**\*">
<Output TaskParameter="Include" ItemName="OutputFiles" />
</CreateItem>
```
There are more details in the MSDN MSBuild documentation that I read when I was mucking with custom build tasks and stuff that was very helpful. Go read up on the CreateItem task and you'll be able to make more sense out of what I posted here. It's really easy to pick up on.
|
258,228 |
<p>I have been bitten by something unexpected recently. I wanted to make something like that:</p>
<pre><code>try :
thing.merge(iterable) # this is an iterable so I add it to the list
except TypeError :
thing.append(iterable) # this is not iterable, so I add it
</code></pre>
<p>Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added.</p>
<p>Unfortunetly, an Exception is iterable. The following code does not raise any <code>TypeError</code>:</p>
<pre><code>for x in Exception() :
print 1
</code></pre>
<p>Does anybody know why?</p>
|
[
{
"answer_id": 258234,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "<p>NOT VALID. Check Brian anwser.</p>\n\n<p>Ok, I just got it :</p>\n\n<pre><code>for x in Exception(\"test\") :\n print x\n ....: \n ....: \ntest\n</code></pre>\n\n<p>Don't bother ;-)</p>\n\n<p>Anyway, it's good to know.</p>\n\n<p>EDIT : looking to the comments, I feel like adding some explanations.</p>\n\n<p>An exception contains a message you passed to during instantiation :</p>\n\n<pre><code>raise Exception(\"test\") \n\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nException: test\n</code></pre>\n\n<p>It's fair to say that the message is what defines the Exception the best, so str() returns it :</p>\n\n<pre><code>print Exception(\"test\") \ntest\n</code></pre>\n\n<p>Now, it happens that Exceptions are implicitly converted to string when used in something else than an Exception context.</p>\n\n<p>So when I do :</p>\n\n<pre><code>for x in Exception(\"test\") :\n print x\n</code></pre>\n\n<p>I am iterating over the string \"test\".</p>\n\n<p>And when I do : </p>\n\n<pre><code>for x in Exception() :\n print x\n</code></pre>\n\n<p>I do iterate over an empty string. Tricky. Because when it comes to my issue :</p>\n\n<pre><code>try :\n thing.merge(ExceptionLikeObject)\nexcept TypeError :\n ...\n</code></pre>\n\n<p>This won't raise anything since ExceptionLikeObject is considered as a string.</p>\n\n<p>Well now, we know the HOW, but I still not the WHY. Maybe the built-in Exception inherit from the built-in String ? Because as far as I know :</p>\n\n<ul>\n<li>adding <strong>str</strong> does not make any object iterable.</li>\n<li>I bypassed the problem by overloding <strong>iter</strong>, making it raising TypeError !</li>\n</ul>\n\n<p>Not a problem anymore, but still a mystery.</p>\n"
},
{
"answer_id": 258930,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 5,
"selected": true,
"text": "<p>Note that what is happening is not related to any kind of implicit string conversion etc, but because the <code>Exception</code> class implements <code>___getitem__</code> to return the values from the args tuple (<code>ex.args</code>). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string.</p>\n<p>This surprised me too, but thinking about it, I'm guessing it is for backwards compatibility reasons. Python used to (<a href=\"http://www.python.org/doc/essays/stdexceptions.html\" rel=\"nofollow noreferrer\">pre-1.5</a>) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block, i.e:</p>\n<pre><code>try:\n raise "something failed", (42, "some other details")\nexcept "something failed", args:\n errCode, msg = args\n print "something failed. error code %d: %s" % (errCode, msg)\n</code></pre>\n<p>It looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with <code>IOError</code> in the Fatal Breakage section of the above <a href=\"http://www.python.org/doc/essays/stdexceptions.html\" rel=\"nofollow noreferrer\">link</a></p>\n<p>String exceptions have been deprecated for a while, and are gone in Python 3. Exception objects are no longer iterable in Python 3:</p>\n<pre><code>>>> list(Exception("test"))\nTraceback (most recent call last):\n File "<stdin>", line 1, in <module>\nTypeError: 'Exception' object is not iterable\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9951/"
] |
I have been bitten by something unexpected recently. I wanted to make something like that:
```
try :
thing.merge(iterable) # this is an iterable so I add it to the list
except TypeError :
thing.append(iterable) # this is not iterable, so I add it
```
Well, It was working fine until I passed an object inheriting from Exception which was supposed to be added.
Unfortunetly, an Exception is iterable. The following code does not raise any `TypeError`:
```
for x in Exception() :
print 1
```
Does anybody know why?
|
Note that what is happening is not related to any kind of implicit string conversion etc, but because the `Exception` class implements `___getitem__` to return the values from the args tuple (`ex.args`). You can see this by the fact that you get the whole string as your first and only item in the iteration, rather than the character-by-character result you'd get if you iterate over the string.
This surprised me too, but thinking about it, I'm guessing it is for backwards compatibility reasons. Python used to ([pre-1.5](http://www.python.org/doc/essays/stdexceptions.html)) lack the current class hierarchy of exceptions. Instead, strings were thrown, with (usually) a tuple argument for any details that should be passed to the handling block, i.e:
```
try:
raise "something failed", (42, "some other details")
except "something failed", args:
errCode, msg = args
print "something failed. error code %d: %s" % (errCode, msg)
```
It looks like this behavior was put in to avoid breaking pre-1.5 code expecting a tuple of arguments, rather than a non-iterable exception object. There are a couple of examples of this with `IOError` in the Fatal Breakage section of the above [link](http://www.python.org/doc/essays/stdexceptions.html)
String exceptions have been deprecated for a while, and are gone in Python 3. Exception objects are no longer iterable in Python 3:
```
>>> list(Exception("test"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Exception' object is not iterable
```
|
258,231 |
<p>I have a Table called <em>Product</em> and I have the Table <em>StorageHistory</em>.</p>
<p>Now, Product contains a reference to StorageHistory in it's mappings</p>
<pre><code><set name="StorageHistories" lazy="false">
<key column="ProductId" />
<one-to-many class="StorageHistory" />
</set>
</code></pre>
<p>And it works, when I retrieve an object from the ORM I get an empty ISet.</p>
<p>What gives me a headache is how to construct the object in the first place.
When I do the following:</p>
<pre><code>var product = new Product();
session.Save(product);
</code></pre>
<p>the product.StorageHistories property is NULL and I get a NullReferenceException.
So, how do I add items to that collection, or should I go the way to add the StorageHistory items themselves to the DB?</p>
|
[
{
"answer_id": 258255,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 4,
"selected": true,
"text": "<p>I always do the following in the ctor of the parent object:</p>\n\n<p>histories = new HashedSet();</p>\n\n<p>This covers the Save() use case. The Load()/Get() etc usecase is covered by NHibernate as you stated.</p>\n"
},
{
"answer_id": 269847,
"author": "Min",
"author_id": 14461,
"author_profile": "https://Stackoverflow.com/users/14461",
"pm_score": 0,
"selected": false,
"text": "<p>Why not?</p>\n\n<pre><code>private ISet _StorageHistories;\npublic virtual ISet StorageHistories {\n protected set { _StorageHistories = value;}\n get { if (_StorageHistories == null) _StorageHistories = new HashSet();\n return _StorageHistories;\n }\n}\n</code></pre>\n\n<p>Of course if you go through the trouble of having a private anyway you might as well put it in the constructor.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21699/"
] |
I have a Table called *Product* and I have the Table *StorageHistory*.
Now, Product contains a reference to StorageHistory in it's mappings
```
<set name="StorageHistories" lazy="false">
<key column="ProductId" />
<one-to-many class="StorageHistory" />
</set>
```
And it works, when I retrieve an object from the ORM I get an empty ISet.
What gives me a headache is how to construct the object in the first place.
When I do the following:
```
var product = new Product();
session.Save(product);
```
the product.StorageHistories property is NULL and I get a NullReferenceException.
So, how do I add items to that collection, or should I go the way to add the StorageHistory items themselves to the DB?
|
I always do the following in the ctor of the parent object:
histories = new HashedSet();
This covers the Save() use case. The Load()/Get() etc usecase is covered by NHibernate as you stated.
|
258,251 |
<p>How do I apply 'use base' in Perl to inherit subs from some base module?</p>
<p>I'm used to C++ inheritance mechanics, and all the sites I googled for this caused more confusion then help. I want to do something like the following:</p>
<pre><code>#! /usr/bin/perl
#The base class to inherit from
use strict;
use warnings;
package 'TestBase';
#-------------------------------
sub tbSub
{
my ($self, $parm) = @_;
print "\nTestBase: $parm\n";
}
1;
</code></pre>
<p>.</p>
<pre><code>#! /usr/bin/perl
#The descendent class
use strict;
use warnings;
use base qw(TestBase);
sub main;
sub mySub;
#-------------------------------
#Entry point...
main();
#---code------------------------
sub main
{
mySub(1);
tbSub(2);
mySub(3);
}
#-------------------------------
sub mySub
{
my $parm = shift;
print "\nTester: $parm\n";
}
</code></pre>
<p>Perl complains/cannot find tbSub. </p>
|
[
{
"answer_id": 258308,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 2,
"selected": false,
"text": "<p>Perl's inheritance inherits <em>methods</em>, not functions. That means you will have to call </p>\n\n<pre><code>main->tbSub(2);\n</code></pre>\n\n<p>However, what you really want is to inherit the method into a proper class:</p>\n\n<pre><code>package Derived;\nuse base \"TestBase\";\n\npackage main;\nDerived->somemethod(\"foo\");\n</code></pre>\n\n<p>Calling methods in the current package as functions won't pass in the $self or \"this\" object nor the class name magically. Internally,</p>\n\n<pre><code>Class->somemethod(\"foo\")\n</code></pre>\n\n<p>essentially ends up being called as</p>\n\n<pre><code>Class::somemethod(\"Class\", \"foo\")\n</code></pre>\n\n<p>internally. Of course, this assumes Class has a subroutine/method named \"somemethod\". If not, the superclasses of Class will be checked and if those don't have a method \"somemethod\" either, you'll get a fatal error. (Same logic applies for $obj->method(\"foo\").)</p>\n"
},
{
"answer_id": 258315,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 6,
"selected": true,
"text": "<p>The C++ mechnics aren't much different than the Perl mechanics: To use inheritance, you need two classes: the base class and the inheriting class. But you don't have any descendent class. </p>\n\n<p>You are also lacking a constructor. Unlike C++, Perl will not provide a default constructor for you.</p>\n\n<p>Your base class contains a bad syntax error, so I guess you didn't try the code before posting. </p>\n\n<p>Finally, as tsee already observed, you will have to let Perl know whether you want a function call or a method call. </p>\n\n<p>What you really want would look something like this:</p>\n\n<pre><code>my $foo = TestDescendent->new();\n$foo->main();\n\n\npackage TestBase;\n\nsub new {\n my $class = shift;\n return bless {}, $class;\n}\n\nsub tbSub\n{\n my ($self, $parm) = @_;\n print \"\\nTestBase: $parm\\n\";\n}\n\npackage TestDescendent;\nuse base 'TestBase';\n\nsub main {\n my $self = shift;\n $self->mySub( 1 );\n $self->tbSub( 2 );\n $self->mySub( 3 );\n}\n\nsub mySub\n{\n my $self = shift;\n my $parm = shift;\n print \"\\nTester: $parm\\n\";\n}\n\n1;\n</code></pre>\n"
},
{
"answer_id": 258320,
"author": "lexu",
"author_id": 31472,
"author_profile": "https://Stackoverflow.com/users/31472",
"pm_score": 3,
"selected": false,
"text": "<p>It seems to me, you are mixing up two things here: Object-Oriented and Procedural Perl. Perl OO is kind of \"different\" (as in not mainstream but workable).</p>\n\n<p>Your TestBase.pm module seems to expect to be run as a Perl object (Perl oo-style), but your Perl script wants to access it as \"normal\" module. Perl doesn't work the way C++ does (as you realised) so you would have to construct your code differently. See Damian Conway's books for explanations (and smarter code than mine below).</p>\n\n<hr>\n\n<p><strong>Procedural:</strong></p>\n\n<pre><code>#! /usr/bin/perl\n#The module to inherit from\n\npackage TestBase;\n use strict;\n use warnings;\n\n use Exporter ();\n our @ISA = qw (Exporter);\n our @EXPORT = qw (tbSub);\n\n#-------------------------------\nsub tbSub\n{\n my ($parm) = @_;\n print \"\\nTestBase: $parm\\n\";\n}\n\n1;\n</code></pre>\n\n<p>.</p>\n\n<pre><code>#! /usr/bin/perl\n#The descendent class\nuse strict;\nuse warnings;\n\nuse TestBase; \nsub main;\nsub mySub;\n\n#-------------------------------\n#Entry point...\nmain();\n\n#---code------------------------\nsub main\n{\n\n mySub(1);\n tbSub(2);\n mySub(3);\n}\n\n#-------------------------------\nsub mySub\n{\n my $parm = shift;\n print \"\\nTester: $parm\\n\";\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Perl OO</strong></p>\n\n<pre><code>#! /usr/bin/perl\n#The base class to inherit from\n\npackage TestBase;\n use strict;\n use warnings;\n\n#-------------------------------\nsub new { my $s={ };\n return bless $s;\n}\nsub tbSub\n{\n my ($self,$parm) = @_;\n print \"\\nTestBase: $parm\\n\";\n}\n\n1;\n</code></pre>\n\n<p>.</p>\n\n<pre><code>#! /usr/bin/perl\n#The descendent class\nuse strict;\nuse warnings;\n\nuse TestBase; \nsub main;\nsub mySub;\n\n#-------------------------------\n#Entry point...\nmain();\n\n#---code------------------------\nsub main\n{\n my $tb = TestBase->new();\n mySub(1);\n $tb->tbSub(2);\n mySub(3);\n}\n\n#-------------------------------\nsub mySub\n{\n my $parm = shift;\n print \"\\nTester: $parm\\n\";\n}\n</code></pre>\n"
},
{
"answer_id": 258439,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 3,
"selected": false,
"text": "<p>As a sidenote, there is little good reason to <code>use base</code> rather than the newer <code>use <a href=\"http://p3rl.org/parent\" rel=\"noreferrer\">parent</a></code>.</p>\n"
},
{
"answer_id": 259325,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 3,
"selected": false,
"text": "<p>You should have a look at using <a href=\"http://search.cpan.org/dist/Moose/lib/Moose.pm\" rel=\"nofollow noreferrer\">Moose</a> which is a postmodern object system for Perl5. You will probably find it a lot easier to grasp than using standard Perl OO semantics... especially when coming from another OO language.</p>\n\n<p>Here's a <a href=\"http://moose.perl.org\" rel=\"nofollow noreferrer\">Moose</a> version of your question....</p>\n\n<pre><code>package TestBase;\nuse Moose;\n\nsub tbSub {\n my ($self, $parm) = @_;\n print \"\\nTestBase: $parm\\n\";\n}\n\n\npackage TestDescendent;\nuse Moose;\nextends 'TestBase';\n\nsub main {\n my $self = shift;\n $self->mySub( 1 );\n $self->tbSub( 2 );\n $self->mySub( 3 );\n}\n\nsub mySub {\n my ($self, $parm) = @_;\n print \"\\nTester: $parm\\n\";\n}\n\n\npackage main;\nmy $foo = TestDescendent->new();\n$foo->main\n</code></pre>\n\n<p>The differences are.... </p>\n\n<ul>\n<li>Constructor automatically created for you & </li>\n<li>Inheritance defined by \"extends\" command instead of \"use base\". </li>\n</ul>\n\n<p>So this example only covers the tip of the Moose iceberg ;-)</p>\n"
},
{
"answer_id": 259993,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 1,
"selected": false,
"text": "<p>OO syntax uses the <code>-></code> operator to separate the message and arguments from the receiver of the message. A short illustration below. </p>\n\n<pre><code>You->do_something( @params );\n\nOR \n\n$you->do_something( @params );\n\npackage A;\n\nsub do_neat_thing { \n my ( $class_or_instance, @args ) = @_;\n my $class = ref( $class_or_instance );\n if ( $class ) {\n say \"Instance of '$class' does a neat thing.\";\n }\n else { \n say \"$class_or_instance does a neat thing.\";\n }\n}\n\n...\npackage main;\nA->do_neat_thing(); # A does a neat thing.\nmy $a_obj = A->new();\n$a_obj->do_neat_thing(); # Instance of 'A' does a neat thing.\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15161/"
] |
How do I apply 'use base' in Perl to inherit subs from some base module?
I'm used to C++ inheritance mechanics, and all the sites I googled for this caused more confusion then help. I want to do something like the following:
```
#! /usr/bin/perl
#The base class to inherit from
use strict;
use warnings;
package 'TestBase';
#-------------------------------
sub tbSub
{
my ($self, $parm) = @_;
print "\nTestBase: $parm\n";
}
1;
```
.
```
#! /usr/bin/perl
#The descendent class
use strict;
use warnings;
use base qw(TestBase);
sub main;
sub mySub;
#-------------------------------
#Entry point...
main();
#---code------------------------
sub main
{
mySub(1);
tbSub(2);
mySub(3);
}
#-------------------------------
sub mySub
{
my $parm = shift;
print "\nTester: $parm\n";
}
```
Perl complains/cannot find tbSub.
|
The C++ mechnics aren't much different than the Perl mechanics: To use inheritance, you need two classes: the base class and the inheriting class. But you don't have any descendent class.
You are also lacking a constructor. Unlike C++, Perl will not provide a default constructor for you.
Your base class contains a bad syntax error, so I guess you didn't try the code before posting.
Finally, as tsee already observed, you will have to let Perl know whether you want a function call or a method call.
What you really want would look something like this:
```
my $foo = TestDescendent->new();
$foo->main();
package TestBase;
sub new {
my $class = shift;
return bless {}, $class;
}
sub tbSub
{
my ($self, $parm) = @_;
print "\nTestBase: $parm\n";
}
package TestDescendent;
use base 'TestBase';
sub main {
my $self = shift;
$self->mySub( 1 );
$self->tbSub( 2 );
$self->mySub( 3 );
}
sub mySub
{
my $self = shift;
my $parm = shift;
print "\nTester: $parm\n";
}
1;
```
|
258,264 |
<p>Is there any way of using Memcached for fragment caching in Rails?</p>
|
[
{
"answer_id": 259239,
"author": "TonyLa",
"author_id": 1295,
"author_profile": "https://Stackoverflow.com/users/1295",
"pm_score": 3,
"selected": true,
"text": "<p>You can set the fragment_cache_store in your environment.rb</p>\n\n<pre><code> ActionController::Base.cache_store = ActiveSupport::Cache::MemCacheStore.new()\n</code></pre>\n\n<p><a href=\"http://api.rubyonrails.org/classes/ActionController/Caching.html#M000628\" rel=\"nofollow noreferrer\">http://api.rubyonrails.org/classes/ActionController/Caching.html#M000628</a></p>\n"
},
{
"answer_id": 1034898,
"author": "Brian Armstrong",
"author_id": 76486,
"author_profile": "https://Stackoverflow.com/users/76486",
"pm_score": 3,
"selected": false,
"text": "<p>you can add this to your development.rb and it should do fragment caching as well as the others</p>\n\n<pre><code>config.action_controller.perform_caching = true\nconfig.cache_classes = true\nconfig.cache_store = :mem_cache_store\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12037/"
] |
Is there any way of using Memcached for fragment caching in Rails?
|
You can set the fragment\_cache\_store in your environment.rb
```
ActionController::Base.cache_store = ActiveSupport::Cache::MemCacheStore.new()
```
<http://api.rubyonrails.org/classes/ActionController/Caching.html#M000628>
|
258,273 |
<p>Heres the link:</p>
<p><a href="http://tinyurl.com/596xva" rel="nofollow noreferrer">DAMNIE6TOHELL</a></p>
<p>As you can see if viewed in glorious 'IE6-o-color', the footer is shifting 1px over to the left.
I'm struggling to find a fix for this, I've whittled it down to a bare minimum of HTML.</p>
<p>Is it something to do with haslayout perhaps? Any help much appreciated.</p>
|
[
{
"answer_id": 258293,
"author": "yoavf",
"author_id": 1011,
"author_profile": "https://Stackoverflow.com/users/1011",
"pm_score": 2,
"selected": true,
"text": "<p>Add </p>\n\n<pre><code>background-position: 50% top;\n</code></pre>\n\n<p>to the css of container_bottom. </p>\n\n<p>It works for me with IE Developer toolbar, but it's on a IE6 Virtual machine, so I'm not sure about real world results</p>\n"
},
{
"answer_id": 258300,
"author": "philnash",
"author_id": 28376,
"author_profile": "https://Stackoverflow.com/users/28376",
"pm_score": 2,
"selected": false,
"text": "<p>This looks like it's a case of the <a href=\"http://www.pmob.co.uk/temp/onepxjog.htm\" rel=\"nofollow noreferrer\">IE6 1px jog</a> which can be solved by a few different fixes.</p>\n\n<p>You will only want to apply these fixes to IE6, using your favourite method (conditional comments, star html hack, whatever). You could</p>\n\n<ul>\n<li><p>apply background position to #container_bottom</p>\n\n<p>container_bottom { background-position:1px 0; }</p></li>\n<li><p>apply a left margin or padding to #container_bottom</p>\n\n<p>container_bottom { margin-left:1px; }</p></li>\n<li><p>or float #container_bottom to the left and give it a width</p>\n\n<p>container_bottom { float:left; width:800px; }</p></li>\n</ul>\n\n<p>Any of those seemed to work for me.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
Heres the link:
[DAMNIE6TOHELL](http://tinyurl.com/596xva)
As you can see if viewed in glorious 'IE6-o-color', the footer is shifting 1px over to the left.
I'm struggling to find a fix for this, I've whittled it down to a bare minimum of HTML.
Is it something to do with haslayout perhaps? Any help much appreciated.
|
Add
```
background-position: 50% top;
```
to the css of container\_bottom.
It works for me with IE Developer toolbar, but it's on a IE6 Virtual machine, so I'm not sure about real world results
|
258,275 |
<p>I'm trying to run a command-line process (which is extraction of a .7z archive) on a file that lies in a temporary folder on the windows user temp directory
(C:\Documents and Settings\User\Local Settings\Temp), using Process in my c# app.</p>
<p>I think the process return error that happens because of "access denied" because I can see a win32Exception with error code 5 when I dig in the prcoess object of .NET.</p>
<p>doing the same on some other location worked fine before, so I guess maybe it's something I'm not supposed to do ? (running a process to use a file on the the %TEMP%)
perhaps I need to pass security somehow?</p>
|
[
{
"answer_id": 258276,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>Assuming that you are using regular .NET (not CF/Silverlight, etc) Accessing files in the user's temp area is entirely expected. I wonder if the problem isn't more that you've accidentally left the file open after creating it, perhaps by not using a \"using\" or similar?</p>\n\n<p>I probably wouldn't suggest using environment variables (%TEMP% etc) when shelling out to a separate process; ideally you'd pass the full path to the file (less things to get wrong...), making sure to <em>quote</em> any path arguments (in case of space) - i.e. so your args are @\"... \"\"c:\\some path\\whatever\\tmp\"\"...\" (if you see what I mean).</p>\n\n<p>Finally, if you are extracting files, you need to think about the existing contents. <code>Path.GetTempFileName()</code> is fine for creating a single file place-holder, but for extracting an archive you probably want to create a directory - guids are handy for this purpoes (while avioding conflicts, and remember to remove it afterwards):</p>\n\n<pre><code>string dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());\n</code></pre>\n"
},
{
"answer_id": 258703,
"author": "Hanan",
"author_id": 30324,
"author_profile": "https://Stackoverflow.com/users/30324",
"pm_score": 0,
"selected": false,
"text": "<p>running the same process using command-line (cmd) helped to figure out my problem was that I specified path arguments to the process using long-path-name.</p>\n\n<p>Solution to this can be found here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/258367/standard-way-to-convert-to-long-path-in-net\">standard way to convert to short path in .net</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30324/"
] |
I'm trying to run a command-line process (which is extraction of a .7z archive) on a file that lies in a temporary folder on the windows user temp directory
(C:\Documents and Settings\User\Local Settings\Temp), using Process in my c# app.
I think the process return error that happens because of "access denied" because I can see a win32Exception with error code 5 when I dig in the prcoess object of .NET.
doing the same on some other location worked fine before, so I guess maybe it's something I'm not supposed to do ? (running a process to use a file on the the %TEMP%)
perhaps I need to pass security somehow?
|
Assuming that you are using regular .NET (not CF/Silverlight, etc) Accessing files in the user's temp area is entirely expected. I wonder if the problem isn't more that you've accidentally left the file open after creating it, perhaps by not using a "using" or similar?
I probably wouldn't suggest using environment variables (%TEMP% etc) when shelling out to a separate process; ideally you'd pass the full path to the file (less things to get wrong...), making sure to *quote* any path arguments (in case of space) - i.e. so your args are @"... ""c:\some path\whatever\tmp""..." (if you see what I mean).
Finally, if you are extracting files, you need to think about the existing contents. `Path.GetTempFileName()` is fine for creating a single file place-holder, but for extracting an archive you probably want to create a directory - guids are handy for this purpoes (while avioding conflicts, and remember to remove it afterwards):
```
string dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
```
|
258,280 |
<p>I created an html helper </p>
<pre><code>Html.BreadCrumb(IDictionary<string, string> crumbs)
</code></pre>
<p>Where the first string is the label and the second string is the URL.
The helper creates the html required (an unordered list, some classes for first element, current element, last element, dead element and separators etc)
All working nice, but I do this by creating a stringbuilder, pumping all the html in it and returning the stringbuilder's content as a string.</p>
<p>I figure in this example it doesn't matter all that much, but what if an Html helper is churning out a big load of html? Isn't there a way to push it to Response.Write instead of a stringbuilder?</p>
<p>Or any other issues/improvements you have?</p>
|
[
{
"answer_id": 258343,
"author": "Rene Saarsoo",
"author_id": 15982,
"author_profile": "https://Stackoverflow.com/users/15982",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think you will have any performance problems as long as the size of the HTML pages you produce is reasonable. And when you really start to create pages of megabytes in size, then you should ask yourself, why are you creating such huge HTML files?</p>\n"
},
{
"answer_id": 258773,
"author": "Craig Stuntz",
"author_id": 7714,
"author_profile": "https://Stackoverflow.com/users/7714",
"pm_score": 2,
"selected": true,
"text": "<p>It certainly is possible to use Response.Write instead of returning a string; see the source for System.Web.Mvc.Ajax.Form (in AjaxExtensions.cs) in the MVC source for an example.</p>\n\n<p>You then call the helper with <% instead of <%=.</p>\n\n<p>Will it be any faster? I doubt it, but it's easy to test.</p>\n"
},
{
"answer_id": 263422,
"author": "Eilon",
"author_id": 31668,
"author_profile": "https://Stackoverflow.com/users/31668",
"pm_score": 3,
"selected": false,
"text": "<p>BTW we have a naming pattern in ASP.NET MVC for the various rendering techniques.</p>\n\n<p>Helpers that return a string of what they are should be named what they are. For example, Url.Action() and Html.TextBox() return those exact items. Thus, these helpers should be used with the <%= %> syntax.</p>\n\n<p>Helpers that render directly to the output stream should start with Render. For example, Html.RenderPartial(). These are used with the <% %> syntax.</p>\n\n<p>Helpers that use the IDisposable pattern should be named with Begin/End. For example, Html.BeginForm() and Html.EndForm(). These should also be used with the <% %> syntax.</p>\n\n<p>Thanks,\nEilon</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
I created an html helper
```
Html.BreadCrumb(IDictionary<string, string> crumbs)
```
Where the first string is the label and the second string is the URL.
The helper creates the html required (an unordered list, some classes for first element, current element, last element, dead element and separators etc)
All working nice, but I do this by creating a stringbuilder, pumping all the html in it and returning the stringbuilder's content as a string.
I figure in this example it doesn't matter all that much, but what if an Html helper is churning out a big load of html? Isn't there a way to push it to Response.Write instead of a stringbuilder?
Or any other issues/improvements you have?
|
It certainly is possible to use Response.Write instead of returning a string; see the source for System.Web.Mvc.Ajax.Form (in AjaxExtensions.cs) in the MVC source for an example.
You then call the helper with <% instead of <%=.
Will it be any faster? I doubt it, but it's easy to test.
|
258,284 |
<p>In either a Windows or Mac OS X terminal if you type...</p>
<pre><code>nslookup -type=SRV _xmpp-server._tcp.gmail.com
</code></pre>
<p>... (for example) you will receive a bunch of SRV records relating to different google chat servers..</p>
<p>Does anyone have any experience in this area and possibly know how to service this information (hostname, port, weight, priority) using the iPhone SDK? I have experimented with the Bonjour classes, but as yet have had no luck..</p>
<p>Thanks!</p>
|
[
{
"answer_id": 258413,
"author": "Alex Reynolds",
"author_id": 19410,
"author_profile": "https://Stackoverflow.com/users/19410",
"pm_score": 0,
"selected": false,
"text": "<p>Hmm, looks like I can't run <code>system()</code> on the Simulator or the device. I can run <code>NSTask</code> on the Simulator, but not the iPhone, and <code>NSTask</code> is not part of the <code>Foundation</code> framework.</p>\n\n<p>The <a href=\"http://www.isc.org/index.pl?/sw/bind/index.php\" rel=\"nofollow noreferrer\">ISC BIND</a> package has a BSD license. If feasible, perhaps relevant parts of the <code>dig</code> code could be wrapped into the project directly.</p>\n"
},
{
"answer_id": 258433,
"author": "Marius",
"author_id": 4712,
"author_profile": "https://Stackoverflow.com/users/4712",
"pm_score": 1,
"selected": false,
"text": "<p>I think your best bet is to implement a DNS query tool using CFNetwork. </p>\n\n<p>Try to read more about this here: <a href=\"http://developer.apple.com/documentation/Networking/Conceptual/CFNetwork/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP30001132-CH1-DontLinkElementID_24\" rel=\"nofollow noreferrer\">http://developer.apple.com/documentation/Networking/Conceptual/CFNetwork/Introduction/chapter_1_section_1.html#//apple_ref/doc/uid/TP30001132-CH1-DontLinkElementID_24</a></p>\n"
},
{
"answer_id": 258799,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": true,
"text": "<p>I believe you need to use the DNSServiceDiscovery framework. I don't have the iPhone SDK, but a Google search suggests that it is available on the iPhone.</p>\n\n<p>See the Apple Developer Site for <a href=\"https://developer.apple.com/library/mac/documentation/networking/conceptual/dns_discovery_api/Introduction.html\" rel=\"nofollow noreferrer\">full API details</a>.</p>\n\n<p>I've included some (incomplete) sample code too:</p>\n\n<pre><code>#include <dns_sd.h>\n\nint main(int argc, char *argv[])\n{\n DNSServiceRef sdRef;\n DNSServiceErrorType res;\n\n DNSServiceQueryRecord(\n &sdRef, 0, 0,\n \"_xmpp-server._tcp.gmail.com\",\n kDNSServiceType_SRV,\n kDNSServiceClass_IN,\n callback,\n NULL\n );\n\n DNSServiceProcessResult(sdRef);\n DNSServiceRefDeallocate(sdRef);\n}\n</code></pre>\n\n<p>You'll need to provide your own callback function, and note that the <code>rdata</code> field sent to the callback is in wire-format, so you'll have to decode the raw data from the SRV record fields yourself.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33604/"
] |
In either a Windows or Mac OS X terminal if you type...
```
nslookup -type=SRV _xmpp-server._tcp.gmail.com
```
... (for example) you will receive a bunch of SRV records relating to different google chat servers..
Does anyone have any experience in this area and possibly know how to service this information (hostname, port, weight, priority) using the iPhone SDK? I have experimented with the Bonjour classes, but as yet have had no luck..
Thanks!
|
I believe you need to use the DNSServiceDiscovery framework. I don't have the iPhone SDK, but a Google search suggests that it is available on the iPhone.
See the Apple Developer Site for [full API details](https://developer.apple.com/library/mac/documentation/networking/conceptual/dns_discovery_api/Introduction.html).
I've included some (incomplete) sample code too:
```
#include <dns_sd.h>
int main(int argc, char *argv[])
{
DNSServiceRef sdRef;
DNSServiceErrorType res;
DNSServiceQueryRecord(
&sdRef, 0, 0,
"_xmpp-server._tcp.gmail.com",
kDNSServiceType_SRV,
kDNSServiceClass_IN,
callback,
NULL
);
DNSServiceProcessResult(sdRef);
DNSServiceRefDeallocate(sdRef);
}
```
You'll need to provide your own callback function, and note that the `rdata` field sent to the callback is in wire-format, so you'll have to decode the raw data from the SRV record fields yourself.
|
258,291 |
<p>In a visual studio project I have three layers, Data Layer, Business Layer and Presentation Layer. </p>
<p>In the Data Layer I have a few XSLT's that transform some objects into an email, all works fine but I have discovered that the XSLTs do not get built/copied when building. </p>
<p>I have currently, created a folder in the deploy location and placed the XSLT's there but I am concerned about relying on a manual process to update these. </p>
<p>Has anyone encountered a similar issue and if so how did they get around it. </p>
<p>It smacks of changing the MSBuild script to copy the build artifacts to the required location, does anyone have examples of this?</p>
<p>Thaks </p>
|
[
{
"answer_id": 258406,
"author": "Kev",
"author_id": 419,
"author_profile": "https://Stackoverflow.com/users/419",
"pm_score": 0,
"selected": false,
"text": "<p>Obvious question maybe, but still has to be asked, did you include the folder containing the XSLT's in the project itself? Is this a web or forms app?</p>\n"
},
{
"answer_id": 258449,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "<p>In VS, it is easy to set the properties of the XSLT files in the project to copy on build, by default they do not.</p>\n"
},
{
"answer_id": 258711,
"author": "Dean",
"author_id": 11802,
"author_profile": "https://Stackoverflow.com/users/11802",
"pm_score": 0,
"selected": false,
"text": "<p>I may have explained myself poorly.</p>\n\n<p>THe Data layer is a class library that a the presentation layer references. </p>\n\n<p>On building the DataLayer I can get the XSLTs to output to the Bin directory of the DataLayer. However when I build and publish the presentation layer, it correctly grabs the DLL but not the XSLTs</p>\n"
},
{
"answer_id": 258854,
"author": "jon without an h",
"author_id": 27578,
"author_profile": "https://Stackoverflow.com/users/27578",
"pm_score": 3,
"selected": true,
"text": "<p>If you are using Visual Studio 2005/2008, the easiest way to do this is by including your XSLT files as project resources.</p>\n\n<ol>\n<li>Open the Properties for your project.</li>\n<li>Select the Resources tab. You will probably see a link that says \"This project does not contain a default resources file. Click here to create one.\" Go ahead and click on that.</li>\n<li>Click the Add Resource drop-down near the top and select Add Existing File.</li>\n<li>Browse to your XSLT files and select them.</li>\n</ol>\n\n<p>After you have done this, you can easily access the resources in the following manner:</p>\n\n<pre><code>// To get the contents of the resource as a string:\nstring xslt = global::MyNamespace.Properties.Resources.MyXsltFile;\n// To get a Stream containing the resource:\nStream xsltStream = global::MyNamespace.Properties.Resources.ResourceManager.GetStream(\"MyXsltFile\");\n</code></pre>\n\n<p><br>\nIf you are using Visual Studio 2003, your best bet is to include those XSLT files as embedded resources for the DLL. In Visual Studio, select the file(s) in Solution Explorer, open the Properties pane, and change the Build Type to \"Embedded Resource\". You can then use the <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx\" rel=\"nofollow noreferrer\">GetManifestResourceStream method</a> to get a Stream containing the XSLT(s). The name to pass will be based on the default namespace of your assembly, the folder containing the file, and the name of the file.</p>\n\n<p>For example, say your data layer assembly has a default namespace of My.DataLayer. Within your data layer project you have a folder named Templates which contains a file called Transform.xslt. The code to get your XSLT would look like this:</p>\n\n<pre><code>// There are numerous ways to get a reference to the Assembly ... this way works\n// when called from a class that is in your data layer. Have a look also at the\n// static methods available on the Assembly class.\nSystem.Reflection.Assembly assembly = (GetType()).Assembly;\nSystem.IO.Stream xsltStream = assembly.GetManifestResourceStream(\"My.DataLayer.Templates.Transform.xslt\");\n</code></pre>\n\n<p>For more information check out <a href=\"http://www.codeproject.com/KB/dotnet/embeddedresources.aspx\" rel=\"nofollow noreferrer\">this article on CodeProject</a>.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11802/"
] |
In a visual studio project I have three layers, Data Layer, Business Layer and Presentation Layer.
In the Data Layer I have a few XSLT's that transform some objects into an email, all works fine but I have discovered that the XSLTs do not get built/copied when building.
I have currently, created a folder in the deploy location and placed the XSLT's there but I am concerned about relying on a manual process to update these.
Has anyone encountered a similar issue and if so how did they get around it.
It smacks of changing the MSBuild script to copy the build artifacts to the required location, does anyone have examples of this?
Thaks
|
If you are using Visual Studio 2005/2008, the easiest way to do this is by including your XSLT files as project resources.
1. Open the Properties for your project.
2. Select the Resources tab. You will probably see a link that says "This project does not contain a default resources file. Click here to create one." Go ahead and click on that.
3. Click the Add Resource drop-down near the top and select Add Existing File.
4. Browse to your XSLT files and select them.
After you have done this, you can easily access the resources in the following manner:
```
// To get the contents of the resource as a string:
string xslt = global::MyNamespace.Properties.Resources.MyXsltFile;
// To get a Stream containing the resource:
Stream xsltStream = global::MyNamespace.Properties.Resources.ResourceManager.GetStream("MyXsltFile");
```
If you are using Visual Studio 2003, your best bet is to include those XSLT files as embedded resources for the DLL. In Visual Studio, select the file(s) in Solution Explorer, open the Properties pane, and change the Build Type to "Embedded Resource". You can then use the [GetManifestResourceStream method](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx) to get a Stream containing the XSLT(s). The name to pass will be based on the default namespace of your assembly, the folder containing the file, and the name of the file.
For example, say your data layer assembly has a default namespace of My.DataLayer. Within your data layer project you have a folder named Templates which contains a file called Transform.xslt. The code to get your XSLT would look like this:
```
// There are numerous ways to get a reference to the Assembly ... this way works
// when called from a class that is in your data layer. Have a look also at the
// static methods available on the Assembly class.
System.Reflection.Assembly assembly = (GetType()).Assembly;
System.IO.Stream xsltStream = assembly.GetManifestResourceStream("My.DataLayer.Templates.Transform.xslt");
```
For more information check out [this article on CodeProject](http://www.codeproject.com/KB/dotnet/embeddedresources.aspx).
|
258,296 |
<p>I have a models <code>A</code> and <code>B</code>, that are like this:</p>
<pre><code>class A(models.Model):
title = models.CharField(max_length=20)
(...)
class B(models.Model):
date = models.DateTimeField(auto_now_add=True)
(...)
a = models.ForeignKey(A)
</code></pre>
<p>Now I have some <code>A</code> and <code>B</code> objects, and I'd like to get a query that selects all <code>A</code> objects that have less then 2 <code>B</code> pointing at them.</p>
<p>A is something like a pool thing, and users (the B) join pool. if there's only 1 or 0 joined, the pool shouldn't be displayed at all.</p>
<p>Is it possible with such model design? Or should I modify that a bit?</p>
|
[
{
"answer_id": 258310,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": true,
"text": "<p>Sounds like a job for <a href=\"http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none\" rel=\"noreferrer\"><code>extra</code></a>.</p>\n\n<pre><code>A.objects.extra(\n select={\n 'b_count': 'SELECT COUNT(*) FROM yourapp_b WHERE yourapp_b.a_id = yourapp_a.id',\n },\n where=['b_count < 2']\n)\n</code></pre>\n\n<p>If the B count is something you often need as a filtering or ordering criterion, or needs to be displayed on list views, you could consider denormalisation by adding a b_count field to your A model and using signals to update it when a B is added or deleted:</p>\n\n<pre><code>from django.db import connection, transaction\nfrom django.db.models.signals import post_delete, post_save\n\ndef update_b_count(instance, **kwargs):\n \"\"\"\n Updates the B count for the A related to the given B.\n \"\"\"\n if not kwargs.get('created', True) or kwargs.get('raw', False):\n return\n cursor = connection.cursor()\n cursor.execute(\n 'UPDATE yourapp_a SET b_count = ('\n 'SELECT COUNT(*) FROM yourapp_b '\n 'WHERE yourapp_b.a_id = yourapp_a.id'\n ') '\n 'WHERE id = %s', [instance.a_id])\n transaction.commit_unless_managed()\n\npost_save.connect(update_b_count, sender=B)\npost_delete.connect(update_b_count, sender=B)\n</code></pre>\n\n<p>Another solution would be to manage a status flag on the A object when you're adding or removing a related B.</p>\n\n<pre><code>B.objects.create(a=some_a)\nif some_a.hidden and some_a.b_set.count() > 1:\n A.objects.filter(id=some_a.id).update(hidden=False)\n\n...\n\nsome_a = b.a\nsome_b.delete()\nif not some_a.hidden and some_a.b_set.count() < 2:\n A.objects.filter(id=some_a.id).update(hidden=True)\n</code></pre>\n"
},
{
"answer_id": 258329,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "<p>I'd recommend modifying your design to include some status field on A.</p>\n\n<p>The issue is one of \"why?\" Why does A have < 2 B's and why does A have >= 2 B's. Is it because user's didn't enter something? Or is because they tried and their input had errors. Or is it because the < 2 rule doesn't apply in this case.</p>\n\n<p>Using presence or absence of a Foreign Key limits the meaning to -- well -- present or absent. You don't have any way to represent \"why?\"</p>\n\n<p>Also, you have the following option</p>\n\n<pre><code>[ a for a in A.objects.all() if a.b_set.count() < 2 ]\n</code></pre>\n\n<p>This can be pricey because it does fetch all the A's rather than force the database to do the work.</p>\n\n<hr>\n\n<p>Edit: From the comment \"would require me to watch for user join / user leaving the pool events\".</p>\n\n<p>You don't \"watch\" anything -- you provide an API which does what you need. That's the central benefit of the Django model. Here's one way, with explict methods in the <code>A</code> class.</p>\n\n<pre><code>class A( models.Model ):\n ....\n def addB( self, b ):\n self.b_set.add( b )\n self.changeFlags()\n def removeB( self, b ):\n self.b_set.remove( b )\n self.changeFlags()\n def changeFlags( self ):\n if self.b_set.count() < 2: self.show= NotYet\n else: self.show= ShowNow\n</code></pre>\n\n<p>You can also define a special <code>Manager</code> for this, and replace the default <code>b_set</code> Manager with your manager that counts references and updates <code>A</code>.</p>\n"
},
{
"answer_id": 845814,
"author": "un33k",
"author_id": 103734,
"author_profile": "https://Stackoverflow.com/users/103734",
"pm_score": 1,
"selected": false,
"text": "<p>I assume that joining or leaving the pool may not happen as often as listing (showing) the pools. I also believe that it would be more efficient for the users join/leave actions to update the pool display status. This way, listing & showing the pools would require less time as you would just run a single query for SHOW_STATUS of the pool objects.</p>\n"
},
{
"answer_id": 6205303,
"author": "gravitron",
"author_id": 456506,
"author_profile": "https://Stackoverflow.com/users/456506",
"pm_score": 7,
"selected": false,
"text": "<p>The question and selected answer are from 2008 and since then this functionality has been integrated into the django framework. Since this is a top google hit for \"django filter foreign key count\" I'd like to add an easier solution with a recent django version using <a href=\"https://docs.djangoproject.com/en/dev/topics/db/aggregation/\" rel=\"noreferrer\" title=\"Aggregation\">Aggregation</a>.</p>\n\n<pre><code>from django.db.models import Count\ncats = A.objects.annotate(num_b=Count('b')).filter(num_b__lt=2)\n</code></pre>\n\n<p>In my case I had to take this concept a step further. My \"B\" object had a boolean field called is_available, and I only wanted to return A objects who had more than 0 B objects with is_available set to True.</p>\n\n<pre><code>A.objects.filter(B__is_available=True).annotate(num_b=Count('b')).filter(num_b__gt=0).order_by('-num_items')\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258296",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
I have a models `A` and `B`, that are like this:
```
class A(models.Model):
title = models.CharField(max_length=20)
(...)
class B(models.Model):
date = models.DateTimeField(auto_now_add=True)
(...)
a = models.ForeignKey(A)
```
Now I have some `A` and `B` objects, and I'd like to get a query that selects all `A` objects that have less then 2 `B` pointing at them.
A is something like a pool thing, and users (the B) join pool. if there's only 1 or 0 joined, the pool shouldn't be displayed at all.
Is it possible with such model design? Or should I modify that a bit?
|
Sounds like a job for [`extra`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#extra-select-none-where-none-params-none-tables-none-order-by-none-select-params-none).
```
A.objects.extra(
select={
'b_count': 'SELECT COUNT(*) FROM yourapp_b WHERE yourapp_b.a_id = yourapp_a.id',
},
where=['b_count < 2']
)
```
If the B count is something you often need as a filtering or ordering criterion, or needs to be displayed on list views, you could consider denormalisation by adding a b\_count field to your A model and using signals to update it when a B is added or deleted:
```
from django.db import connection, transaction
from django.db.models.signals import post_delete, post_save
def update_b_count(instance, **kwargs):
"""
Updates the B count for the A related to the given B.
"""
if not kwargs.get('created', True) or kwargs.get('raw', False):
return
cursor = connection.cursor()
cursor.execute(
'UPDATE yourapp_a SET b_count = ('
'SELECT COUNT(*) FROM yourapp_b '
'WHERE yourapp_b.a_id = yourapp_a.id'
') '
'WHERE id = %s', [instance.a_id])
transaction.commit_unless_managed()
post_save.connect(update_b_count, sender=B)
post_delete.connect(update_b_count, sender=B)
```
Another solution would be to manage a status flag on the A object when you're adding or removing a related B.
```
B.objects.create(a=some_a)
if some_a.hidden and some_a.b_set.count() > 1:
A.objects.filter(id=some_a.id).update(hidden=False)
...
some_a = b.a
some_b.delete()
if not some_a.hidden and some_a.b_set.count() < 2:
A.objects.filter(id=some_a.id).update(hidden=True)
```
|
258,317 |
<p>I have the following snippet in one of my html pages :</p>
<pre><code><div class="inputboximage">
<div class="value2">
<input name='address1' value='Somewhere' type="text" size="26" maxlength="40" />
<br />
</div>
</div>
</code></pre>
<p>My problem is that I need the <code>inputboximage background</code> to change when I click in the <code>address1</code> text field and to revert to the original when it loses focus.</p>
<p>I have used the following :</p>
<pre><code> <script>
$(document).ready(function(){
$("input").focus(function () {
$(this.parentNode).css('background-image', 'url(images/curvedinputblue.gif)');
});
$("input").blur(function () {
$(this.parentNode).css('background-image', 'url(images/curvedinput.gif)');
});
});
</script>
</code></pre>
<p>but instead of replacing the image, it seems to be adding a background image to the value2 div as you would expect. I can use <code>parentNode.parentNode</code> in this case, but there is also a chance that the <code>inputboxImage</code> node could be further up or down the parent tree.</p>
<p>Is there a way I can change this code so that it will navigate down the parent tree until it finds a div called <code>inputboximage</code> and replace the image there?</p>
<p>Also, if I have two different div classes, <code>inputboximage</code> and <code>inputboximageLarge</code>, is there a way to modify this function so that it will work with both, replacing the background image with a different image for each one?</p>
|
[
{
"answer_id": 258319,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>I think using</p>\n\n<pre><code>$(this).parents('div.inputBoxImage').css(...)\n</code></pre>\n\n<p>instead of <code>$(this.parentNode)</code> should work.</p>\n\n<p>See the jQuery <a href=\"http://docs.jquery.com/Traversing/parents#expr\" rel=\"noreferrer\">traversing documentation</a></p>\n\n<p>Edit: updated following Prody's answer (changed parent to parents)</p>\n"
},
{
"answer_id": 258341,
"author": "Prody",
"author_id": 21240,
"author_profile": "https://Stackoverflow.com/users/21240",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not 100% sure but I think what you need is what Phill Sacre's answer suggests except using <code>parents</code> (notice the last s)</p>\n\n<p>From jQuery API:</p>\n\n<p>parent( String expr ) returns jQuery\nGet a set of elements containing the unique parents of the matched set of elements.</p>\n\n<p>parents( String expr ) returns jQuery\nGet a set of elements containing the unique ancestors of the matched set of elements (except for the root element).</p>\n"
},
{
"answer_id": 258358,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 0,
"selected": false,
"text": "<p>Now since in HTML only IDs are unique, you can reference the div directly without doing any traversal:</p>\n\n<pre><code><div class=\"inputboximage\" id=\"inputboximage\">\n <div class=\"value2\">\n <input name='address1' value='5 The Laurels' type=\"text\" size=\"26\" maxlength=\"40\" />\n <br />\n\n </div>\n</div>\n\n<script>\n $(document).ready(function(){\n\n $(\"input\").focus(function () {\n $('#inputboximage').css('background-image', 'url(images/curvedinputblue.gif)');\n });\n\n\n });\n</script>\n</code></pre>\n\n<p>Note that while it is possible to filter the parent elements for CSS classing, using style classes dor behaviour is a Bad Idea TM and you should avoid doing that. But if you are really desperate, you can give it a try:</p>\n\n<pre><code>$(\"input\").focus(function () {\n $(this).parents('div.inputboximage').css('background-image', 'url(images/curvedinputblue.gif)');\n });\n</code></pre>\n"
},
{
"answer_id": 455511,
"author": "adardesign",
"author_id": 56449,
"author_profile": "https://Stackoverflow.com/users/56449",
"pm_score": 0,
"selected": false,
"text": "<p>.parent().css(changes here)</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258317",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24079/"
] |
I have the following snippet in one of my html pages :
```
<div class="inputboximage">
<div class="value2">
<input name='address1' value='Somewhere' type="text" size="26" maxlength="40" />
<br />
</div>
</div>
```
My problem is that I need the `inputboximage background` to change when I click in the `address1` text field and to revert to the original when it loses focus.
I have used the following :
```
<script>
$(document).ready(function(){
$("input").focus(function () {
$(this.parentNode).css('background-image', 'url(images/curvedinputblue.gif)');
});
$("input").blur(function () {
$(this.parentNode).css('background-image', 'url(images/curvedinput.gif)');
});
});
</script>
```
but instead of replacing the image, it seems to be adding a background image to the value2 div as you would expect. I can use `parentNode.parentNode` in this case, but there is also a chance that the `inputboxImage` node could be further up or down the parent tree.
Is there a way I can change this code so that it will navigate down the parent tree until it finds a div called `inputboximage` and replace the image there?
Also, if I have two different div classes, `inputboximage` and `inputboximageLarge`, is there a way to modify this function so that it will work with both, replacing the background image with a different image for each one?
|
I think using
```
$(this).parents('div.inputBoxImage').css(...)
```
instead of `$(this.parentNode)` should work.
See the jQuery [traversing documentation](http://docs.jquery.com/Traversing/parents#expr)
Edit: updated following Prody's answer (changed parent to parents)
|
258,339 |
<p>I have a GUI application that executes (in a new process) "console" applications and parse the output. To redirect the Output i set the pConsole.StartInfo.RedirectStandardOutput to true. I also subscribes to the event pConsole.Exited.</p>
<p>The problem I see is that I have to use Thread.Sleep() in the Exited event handler to get the last data.</p>
<p>My Exited event handler looks like this:</p>
<pre><code>Thread.Sleep(100); // Wait for additional data (if any).
pConsole.OutputDataReceived -= new System.Diagnostics.DataReceivedEventHandler(this.localTerminal_DataAvailableEvent);
int exit = pConsole.ExitCode;
pConsole.Dispose();
pConsole = null;
</code></pre>
<p>It seems that the Exited event executes before my last pConsole_DataAvailableEvent. Anyone knows how/why this is happening?</p>
<p>I also use a mutex/lock to make sure my Exited event is finished before I start execute my next console application.</p>
|
[
{
"answer_id": 258349,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>I strongly suspect that it's just the operating system flushing any output buffers. It looks like your workaround is okay-ish, although obviously it's ugly (not your fault) and the length of sleep could be wastefully long in some cases and not long enough in some pathological other cases.</p>\n"
},
{
"answer_id": 258387,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know if it is any better, but I've just been looking at something similar using threads to read both stderr/stdout, like below. It involves a few extra threads (to avoid deadlocks / complex async code), but seems to work pretty robustly.</p>\n\n<p>The key here is that I <code>Join()</code> on the two threads handling IO, so I only move on once both output streams have been fully consumed.</p>\n\n<pre><code> using (Process proc = Process.Start(psi))\n {\n Thread stdErr = new Thread(DumpStream(proc.StandardError, Console.Error));\n Thread stdOut = new Thread(DumpStream(proc.StandardOutput, Console.Out));\n stdErr.Name = \"stderr reader\";\n stdOut.Name = \"stdout reader\";\n stdErr.Start();\n stdOut.Start();\n proc.WaitForExit();\n stdOut.Join();\n stdErr.Join();\n if (proc.ExitCode != 0) {...} // etc\n }\n\n static ThreadStart DumpStream(TextReader reader, TextWriter writer)\n {\n return (ThreadStart) delegate\n {\n string line;\n while ((line = reader.ReadLine()) != null) writer.WriteLine(line);\n };\n }\n</code></pre>\n"
},
{
"answer_id": 259449,
"author": "JSBձոգչ",
"author_id": 8078,
"author_profile": "https://Stackoverflow.com/users/8078",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is almost certainly output buffering: the process exits, triggering your Exited event, but some output data is still in the buffer. Your hack will probably work in some cases, but other approaches may be more robust. Consider:</p>\n\n<p>1) Eliminating the Exited event handler, and instead check Process.HasExited in the OutputDataReceived handler.</p>\n\n<p>2) Don't use the OutputDataReceived handler, but simply have a call Read() on the Process.StandardOutput stream. Do the post-process cleanup once the stream is closed.</p>\n"
},
{
"answer_id": 4592125,
"author": "Bamboo",
"author_id": 324472,
"author_profile": "https://Stackoverflow.com/users/324472",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to Marc Gravell's answer</p>\n\n<p>proc.StandardError, proc.StandardOutput both has a EndOfStream method.\nThis will be useful to determine the case where the output does not yield a newline before user inputs/prompts</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a GUI application that executes (in a new process) "console" applications and parse the output. To redirect the Output i set the pConsole.StartInfo.RedirectStandardOutput to true. I also subscribes to the event pConsole.Exited.
The problem I see is that I have to use Thread.Sleep() in the Exited event handler to get the last data.
My Exited event handler looks like this:
```
Thread.Sleep(100); // Wait for additional data (if any).
pConsole.OutputDataReceived -= new System.Diagnostics.DataReceivedEventHandler(this.localTerminal_DataAvailableEvent);
int exit = pConsole.ExitCode;
pConsole.Dispose();
pConsole = null;
```
It seems that the Exited event executes before my last pConsole\_DataAvailableEvent. Anyone knows how/why this is happening?
I also use a mutex/lock to make sure my Exited event is finished before I start execute my next console application.
|
I don't know if it is any better, but I've just been looking at something similar using threads to read both stderr/stdout, like below. It involves a few extra threads (to avoid deadlocks / complex async code), but seems to work pretty robustly.
The key here is that I `Join()` on the two threads handling IO, so I only move on once both output streams have been fully consumed.
```
using (Process proc = Process.Start(psi))
{
Thread stdErr = new Thread(DumpStream(proc.StandardError, Console.Error));
Thread stdOut = new Thread(DumpStream(proc.StandardOutput, Console.Out));
stdErr.Name = "stderr reader";
stdOut.Name = "stdout reader";
stdErr.Start();
stdOut.Start();
proc.WaitForExit();
stdOut.Join();
stdErr.Join();
if (proc.ExitCode != 0) {...} // etc
}
static ThreadStart DumpStream(TextReader reader, TextWriter writer)
{
return (ThreadStart) delegate
{
string line;
while ((line = reader.ReadLine()) != null) writer.WriteLine(line);
};
}
```
|
258,344 |
<p>Is it possible to define a spring-managed EJB3 hibernate listener?</p>
<p>I have this definition in my <strong>persistence.xml</strong>:</p>
<pre><code><properties>
<property name="hibernate.ejb.interceptor"
value="my.class.HibernateAuditInterceptor" />
<property name="hibernate.ejb.event.post-update"
value="my.class.HibernateAuditTrailEventListener" />
</properties>
</code></pre>
<p>But I would like to manage <code>HibernateAuditInterceptor</code> and <code>HibernateAuditTrailEventListener</code> with spring, so I can do some bean injection (ex: session-scoped bean) within these classes. Is this possible?</p>
|
[
{
"answer_id": 262992,
"author": "Chochos",
"author_id": 10165,
"author_profile": "https://Stackoverflow.com/users/10165",
"pm_score": 1,
"selected": true,
"text": "<p>The problem is that those properties are just strings. Even if you define your SessionFactory as a Spring bean, any properties you pass to it through the hibernateProperties setter are just strings:</p>\n\n<pre><code><bean id=\"mySessionFactory\" class=\"org.springframework.orm.hibernate3.LocalSessionFactoryBean\">\n <property name=\"dataSource\"ref=\"myDataSource\"/>\n <property name=\"mappingResources\">\n <list>\n <value>whatever.hbm.xml</value>\n </list>\n </property>\n <property name=\"hibernateProperties\">\n <value>\n hibernate.ejb.interceptor= my.class.HibernateAuditInterceptor\n </value>\n <value>\n hibernate.ejb.event.post-update=my.class.HibernateAuditTrailEventListener\n </value>\n </property>\n</bean>\n</code></pre>\n\n<p>So I don't think you can do that.</p>\n"
},
{
"answer_id": 3063721,
"author": "Jack Slacker",
"author_id": 369570,
"author_profile": "https://Stackoverflow.com/users/369570",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/\" rel=\"nofollow noreferrer\">http://blog.krecan.net/2009/01/24/spring-managed-hibernate-interceptor-in-jpa/</a></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258344",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22992/"
] |
Is it possible to define a spring-managed EJB3 hibernate listener?
I have this definition in my **persistence.xml**:
```
<properties>
<property name="hibernate.ejb.interceptor"
value="my.class.HibernateAuditInterceptor" />
<property name="hibernate.ejb.event.post-update"
value="my.class.HibernateAuditTrailEventListener" />
</properties>
```
But I would like to manage `HibernateAuditInterceptor` and `HibernateAuditTrailEventListener` with spring, so I can do some bean injection (ex: session-scoped bean) within these classes. Is this possible?
|
The problem is that those properties are just strings. Even if you define your SessionFactory as a Spring bean, any properties you pass to it through the hibernateProperties setter are just strings:
```
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource"ref="myDataSource"/>
<property name="mappingResources">
<list>
<value>whatever.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.ejb.interceptor= my.class.HibernateAuditInterceptor
</value>
<value>
hibernate.ejb.event.post-update=my.class.HibernateAuditTrailEventListener
</value>
</property>
</bean>
```
So I don't think you can do that.
|
258,355 |
<p>I'm trying to find a way to automate some exception logging code to add to the stack information already available.</p>
<p>Is there any way to use reflection to retrieve the values of all variables on the stack (locals and parameters) - I sincerely doubt the names of the variables are available, but in many cases it would be useful to see the values.</p>
|
[
{
"answer_id": 258373,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "<p>Not really. For this level of digging you'd probably need something like WinDbg.</p>\n\n<p>If a <em>specific</em> variable is of interest, you can add it to the exception yourself (although even this introduces issues with duplicate keys, re-entrancy, etc):</p>\n\n<pre><code> string dir = ...todo...\n try\n {\n // some code\n }\n catch (Exception ex)\n {\n ex.Data.Add(\"dir\", dir);\n throw;\n }\n</code></pre>\n"
},
{
"answer_id": 1340636,
"author": "Jason Haley",
"author_id": 202991,
"author_profile": "https://Stackoverflow.com/users/202991",
"pm_score": 0,
"selected": false,
"text": "<p>You might check out John Robbins' SUPERASSERT (<a href=\"http://msdn.microsoft.com/en-us/magazine/cc188701.aspx\" rel=\"nofollow noreferrer\">SUPERASSERT Goes .Net</a>), his book gives a great walkthrough of one way to do what you are after (plus a WHOLE lot more).</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5777/"
] |
I'm trying to find a way to automate some exception logging code to add to the stack information already available.
Is there any way to use reflection to retrieve the values of all variables on the stack (locals and parameters) - I sincerely doubt the names of the variables are available, but in many cases it would be useful to see the values.
|
Not really. For this level of digging you'd probably need something like WinDbg.
If a *specific* variable is of interest, you can add it to the exception yourself (although even this introduces issues with duplicate keys, re-entrancy, etc):
```
string dir = ...todo...
try
{
// some code
}
catch (Exception ex)
{
ex.Data.Add("dir", dir);
throw;
}
```
|
258,365 |
<p>Here is the directory structure</p>
<pre><code>/domain.com
/public_html
/functions
/image
/mobile
/www
</code></pre>
<p>the /domain.com/public_html/www folder has a file index.php
the default web directory is /user/public_html/www
in the index file is an include that includes the functions with
include"../functions/function.inc"
this works without problem
when I want to link to a picture in the image folder I don't get any results
for example </p>
<pre><code><img src="../image/graphic/logo.gif" alt="alt text"/>
</code></pre>
<p>Does anybody has any idea why the link to the image does not work and how to link correctly to the image file ?</p>
<p>I tried <code><img src="<?php echo $_SERVER['PHP_SELF']; ?>../image/graphic/logo.gif" alt="alt text"/></code></p>
<p>but that gives me the same result
when I build a link around the image to get to the properties I get this as path
<a href="http://domain.com/image/pc/tattoo_small/small_2008_10_22_001.JPG" rel="noreferrer">http://domain.com/image/pc/tattoo_small/small_2008_10_22_001.JPG</a>
the path should be
<a href="http://domain.com/public_html/image/pc/tattoo_small/small_2008_10_22_001.JPG" rel="noreferrer">http://domain.com/public_html/image/pc/tattoo_small/small_2008_10_22_001.JPG</a>
when I try to browse directly to this url
<a href="http://domain.com/public_html/image/pc/tattoo_small/small_2008_10_22_001.JPG" rel="noreferrer">http://domain.com/public_html/image/pc/tattoo_small/small_2008_10_22_001.JPG</a>
I get an 404 file not found error
because the default web directory is
/domain.com/public_html/www
I tried
<a href="http://domain.com/../image/pc/tattoo_small/small_2008_10_22_001.JPG" rel="noreferrer">http://domain.com/../image/pc/tattoo_small/small_2008_10_22_001.JPG</a>
to get to the image folder but that does not help neither.</p>
<p>Anybody any ideas or is it impossible to html link to graphical files outside the default web directory ?</p>
<p>thanks for reading this far</p>
<p>Thanks for the answers so far.
I will try to solve my problem with one of the recommended solutions and report my working solution back here.
I wanted to have the image folder at the same level as the www and mobile folder because some of the images used for the pc (www) version and the mobile version are the same.
Of course it is easier to just get an image folder in the www and in the mobile folder and I think that is what I am going to do.</p>
<p>thank you everybody for the advice. The main reason why I am not going to work with a script is that a script will be a difficult solution to an easy problem and also because I don't really see how you can wrap your image in a css class and how to provide alt text for an image.</p>
|
[
{
"answer_id": 258370,
"author": "JamShady",
"author_id": 11905,
"author_profile": "https://Stackoverflow.com/users/11905",
"pm_score": 3,
"selected": false,
"text": "<p>You can't serve a page that's outside of the web directory because the path doesn't work, i.e. <a href=\"http://mydomain.com/../page.html\" rel=\"noreferrer\">http://mydomain.com/../page.html</a> simply refers to an inaccessible location.</p>\n\n<p>If you really want to serve (static) files that are outside the webroot, you could write a small PHP script to read them and output them. Thus you would redirect requests to the PHP script, and the PHP would read the appropriate file from disk and return it back.</p>\n"
},
{
"answer_id": 258371,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 1,
"selected": false,
"text": "<p>It's impossible to link directly to a file outside of the web-accessible area of the web server.</p>\n\n<p>However, you can write a PHP script that will proxy images for you</p>\n\n<pre><code><img src=\"my_php_proxy.php\">\n</code></pre>\n\n<p>because PHP can send image data as well as HTML. This PHP \"image\" isn't restricted to the same folder as the web accessible stuff, it can access any readable file on the server. See <a href=\"http://www.electrictoolbox.com/image-headers-php/\" rel=\"nofollow noreferrer\">http://www.electrictoolbox.com/image-headers-php/</a> for more info</p>\n"
},
{
"answer_id": 258380,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 5,
"selected": false,
"text": "<p>It is not possible to directly access files outside of the webroot; this is a builtin security restriction that is there for good reason.</p>\n\n<p>It is however possible to use a PHP-script to serve these images for you. This way you can call an image like:</p>\n\n<pre><code>/image.php?file=myfile.jpg\n</code></pre>\n\n<p>and use <a href=\"http://php.net/manual/en/function.file-get-contents.php\" rel=\"noreferrer\">file_get_contents()</a> to get the file contents and print them to your browser. You should also send the headers to the client, in this case using PHP's <a href=\"http://php.net/header\" rel=\"noreferrer\">header()</a> function. A short example:</p>\n\n<pre><code><?php\n\n $file = basename(urldecode($_GET['file']));\n $fileDir = '/path/to/files/';\n\n if (file_exists($fileDir . $file))\n {\n // Note: You should probably do some more checks \n // on the filetype, size, etc.\n $contents = file_get_contents($fileDir . $file);\n\n // Note: You should probably implement some kind \n // of check on filetype\n header('Content-type: image/jpeg');\n\n echo $contents;\n }\n\n?>\n</code></pre>\n\n<p>Using a script to this has some more advantages:</p>\n\n<ul>\n<li>You can track your downloads and implement a counter, for example</li>\n<li>You can restrict files to authenticated users</li>\n<li>... etc</li>\n</ul>\n"
},
{
"answer_id": 258381,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 0,
"selected": false,
"text": "<p>You can either make a link to the image directory inside the public___html, move the image directory to public_html or, if you have a particular liking towards convoluted solutions, you can write a script that reads the image file and outputs it to the user (Of course, unless you make a whitelist of all the images, you might have a potential security problem in your hands).</p>\n"
},
{
"answer_id": 258460,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 4,
"selected": false,
"text": "<p>If you are using Apache as the server, you can set it to alias a directory in httpd.conf...</p>\n\n<pre><code><IfModule mod_alias.c>\n\n Alias /images/ \"/User/Public_html/Image/\"\n\n <Directory \"/User/Public_html/Image\">\n Options Indexes MultiViews\n AllowOverride None\n Order allow,deny\n Allow from all\n </Directory>\n\n</IfModule>\n</code></pre>\n\n<p>IIRC, the aliased folder does not need to be within the webroot.</p>\n"
},
{
"answer_id": 292773,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 3,
"selected": false,
"text": "<p>Create symlink inside web root that points to directory you want. </p>\n\n<pre><code>cd public_html\nln -s ../images\n</code></pre>\n\n<p>Apache needs <code>Options +FollowSymlinks</code> configuration directive for this to work (you may place it in <code>.htaccess</code> in your web root).</p>\n\n<p>Writing PHP script that serves files from outside web root defeats the purpose of web root. You'd have to verify paths very carefully to avoid exposing entire disk to the web.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18383/"
] |
Here is the directory structure
```
/domain.com
/public_html
/functions
/image
/mobile
/www
```
the /domain.com/public\_html/www folder has a file index.php
the default web directory is /user/public\_html/www
in the index file is an include that includes the functions with
include"../functions/function.inc"
this works without problem
when I want to link to a picture in the image folder I don't get any results
for example
```
<img src="../image/graphic/logo.gif" alt="alt text"/>
```
Does anybody has any idea why the link to the image does not work and how to link correctly to the image file ?
I tried `<img src="<?php echo $_SERVER['PHP_SELF']; ?>../image/graphic/logo.gif" alt="alt text"/>`
but that gives me the same result
when I build a link around the image to get to the properties I get this as path
<http://domain.com/image/pc/tattoo_small/small_2008_10_22_001.JPG>
the path should be
<http://domain.com/public_html/image/pc/tattoo_small/small_2008_10_22_001.JPG>
when I try to browse directly to this url
<http://domain.com/public_html/image/pc/tattoo_small/small_2008_10_22_001.JPG>
I get an 404 file not found error
because the default web directory is
/domain.com/public\_html/www
I tried
<http://domain.com/../image/pc/tattoo_small/small_2008_10_22_001.JPG>
to get to the image folder but that does not help neither.
Anybody any ideas or is it impossible to html link to graphical files outside the default web directory ?
thanks for reading this far
Thanks for the answers so far.
I will try to solve my problem with one of the recommended solutions and report my working solution back here.
I wanted to have the image folder at the same level as the www and mobile folder because some of the images used for the pc (www) version and the mobile version are the same.
Of course it is easier to just get an image folder in the www and in the mobile folder and I think that is what I am going to do.
thank you everybody for the advice. The main reason why I am not going to work with a script is that a script will be a difficult solution to an easy problem and also because I don't really see how you can wrap your image in a css class and how to provide alt text for an image.
|
It is not possible to directly access files outside of the webroot; this is a builtin security restriction that is there for good reason.
It is however possible to use a PHP-script to serve these images for you. This way you can call an image like:
```
/image.php?file=myfile.jpg
```
and use [file\_get\_contents()](http://php.net/manual/en/function.file-get-contents.php) to get the file contents and print them to your browser. You should also send the headers to the client, in this case using PHP's [header()](http://php.net/header) function. A short example:
```
<?php
$file = basename(urldecode($_GET['file']));
$fileDir = '/path/to/files/';
if (file_exists($fileDir . $file))
{
// Note: You should probably do some more checks
// on the filetype, size, etc.
$contents = file_get_contents($fileDir . $file);
// Note: You should probably implement some kind
// of check on filetype
header('Content-type: image/jpeg');
echo $contents;
}
?>
```
Using a script to this has some more advantages:
* You can track your downloads and implement a counter, for example
* You can restrict files to authenticated users
* ... etc
|
258,367 |
<p>looking for the standard bug-proofed way to convert "long names" such as "C:\Documents and settings" to their equivalent "short names" "C:\DOCUME~1"</p>
<p>I need this to run an external process from withing my C# app. It fails if I feed it with paths in the "long name".</p>
|
[
{
"answer_id": 258382,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 5,
"selected": false,
"text": "<p>If you are prepared to start calling out to Windows API functions, then GetShortPathName() and GetLongPathName() provide this functionality.</p>\n\n<p>See <a href=\"http://csharparticles.blogspot.com/2005/07/long-and-short-file-name-conversion-in.html\" rel=\"noreferrer\">http://csharparticles.blogspot.com/2005/07/long-and-short-file-name-conversion-in.html</a></p>\n\n<pre><code> const int MAX_PATH = 255;\n\n [DllImport(\"kernel32.dll\", CharSet = CharSet.Auto)]\n public static extern int GetShortPathName(\n [MarshalAs(UnmanagedType.LPTStr)]\n string path,\n [MarshalAs(UnmanagedType.LPTStr)]\n StringBuilder shortPath,\n int shortPathLength\n );\n\n private static string GetShortPath(string path) {\n var shortPath = new StringBuilder(MAX_PATH);\n GetShortPathName(path, shortPath, MAX_PATH);\n return shortPath.ToString();\n }\n</code></pre>\n"
},
{
"answer_id": 258441,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 3,
"selected": true,
"text": "<p>Does the external process fail even if you enclose the long file paths in quotes? That may be a simpler method, if the external app supports it.</p>\n\n<p>e.g.</p>\n\n<pre><code>myExternalApp \"C:\\Documents And Settings\\myUser\\SomeData.file\"\n</code></pre>\n"
},
{
"answer_id": 19029416,
"author": "FiDO",
"author_id": 2640031,
"author_profile": "https://Stackoverflow.com/users/2640031",
"pm_score": 2,
"selected": false,
"text": "<p>The trick with GetShortPathName from WinAPI works fine, but be careful when using very long paths there. </p>\n\n<p>We just had an issue when calling 7zip with paths longer than MAX_PATH. GetShortPathName wasn't working if the path was too long. Just prefix it with \"\\?\\\" and then it will do the job and return correctly shortened path.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30324/"
] |
looking for the standard bug-proofed way to convert "long names" such as "C:\Documents and settings" to their equivalent "short names" "C:\DOCUME~1"
I need this to run an external process from withing my C# app. It fails if I feed it with paths in the "long name".
|
Does the external process fail even if you enclose the long file paths in quotes? That may be a simpler method, if the external app supports it.
e.g.
```
myExternalApp "C:\Documents And Settings\myUser\SomeData.file"
```
|
258,372 |
<p>I have a div container and have defined its style as follows:</p>
<pre><code>div#tbl-container
{
width: 600px;
overflow: auto;
scrollbar-base-color:#ffeaff
}
</code></pre>
<p>This gives me both horizontal and vertical scroll bars automatically once I populate my table which is contained by this div.
I just want only horizontal scroll bars to appear automatically. I will modify the height of the table programmatically.</p>
<p>How do I do this?</p>
|
[
{
"answer_id": 258379,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 1,
"selected": false,
"text": "<p><strong>CSS3</strong> has the <code>overflow-x</code> property, but I wouldn't expect great support for that. In <strong>CSS2</strong> all you can do is set a general <code>scroll</code> policy and work your <code>widths</code> and <code>heights</code> not to mess them up.</p>\n"
},
{
"answer_id": 258393,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 9,
"selected": true,
"text": "<p>You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.</p>\n\n<p>However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.</p>\n\n<p>IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:</p>\n\n<pre><code>overflow: auto;\noverflow-y: hidden;\n</code></pre>\n\n<p>You may also need to add for IE8:</p>\n\n<pre><code>-ms-overflow-y: hidden;\n</code></pre>\n\n<p>as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)</p>\n\n<p>On the other hand it's entirely possible IE8 will have fixed the bug anyway.</p>\n"
},
{
"answer_id": 258400,
"author": "Tsundoku",
"author_id": 28586,
"author_profile": "https://Stackoverflow.com/users/28586",
"pm_score": 4,
"selected": false,
"text": "<p>you can also make it <code>overflow: auto</code> and give a maximum fixed height and width that way, when the text or whatever is in there, overflows it'll show only the required scrollbar</p>\n"
},
{
"answer_id": 1820365,
"author": "Dinesh Appuhamy",
"author_id": 221401,
"author_profile": "https://Stackoverflow.com/users/221401",
"pm_score": 5,
"selected": false,
"text": "<p>To show both:</p>\n\n<pre><code><div style=\"height:250px; width:550px; overflow-x:scroll ; overflow-y: scroll; padding-bottom:10px;\"> </div>\n</code></pre>\n\n<p>Hide X Axis: </p>\n\n<pre><code><div style=\"height:250px; width:550px; overflow-x:hidden; overflow-y: scroll; padding-bottom:10px;\"> </div>\n</code></pre>\n\n<p>Hide Y Axis:</p>\n\n<pre><code><div style=\"height:250px; width:550px; overflow-x:scroll ; overflow-y: hidden; padding-bottom:10px;\"> </div>\n</code></pre>\n"
},
{
"answer_id": 8319119,
"author": "Hoby",
"author_id": 1072366,
"author_profile": "https://Stackoverflow.com/users/1072366",
"pm_score": 6,
"selected": false,
"text": "<p>I also had to add <code>white-space: nowrap;</code> to the style, otherwise elements would wrap down into the area that we're removing the ability to scroll to.</p>\n"
},
{
"answer_id": 11534137,
"author": "Guest",
"author_id": 1533565,
"author_profile": "https://Stackoverflow.com/users/1533565",
"pm_score": 0,
"selected": false,
"text": "<p>We should set to <code>overflow: auto</code> and hide a scrollbar which we don't use for working on unsupporting CSS3 browser.\nLook at this <a href=\"http://xme.im/css-overflow-strict-how-to-display-horizontal-or-verticle-only\" rel=\"nofollow\">CSS Overflow; XME.im</a></p>\n"
},
{
"answer_id": 13814545,
"author": "joginder",
"author_id": 1893737,
"author_profile": "https://Stackoverflow.com/users/1893737",
"pm_score": 1,
"selected": false,
"text": "<pre><code>.box-author-txt {width:596px; float:left; padding:5px 0px 10px 10px; border:1px #dddddd solid; -moz-border-radius: 0 0 5px 5px; -webkit-border-radius: 0 0 5px 5px; -o-border-radius: 0 0 5px 5px; border-radius: 0 0 5px 5px; overflow-x: scroll; white-space: nowrap; overflow-y: hidden;}\n\n\n.box-author-txt ul{ vertical-align:top; height:auto; display: inline-block; white-space: nowrap; margin:0 9px 0 0; padding:0px;}\n.box-author-txt ul li{ list-style-type:none; width:140px; }\n</code></pre>\n"
},
{
"answer_id": 17201632,
"author": "Anudeep Sharma",
"author_id": 1069208,
"author_profile": "https://Stackoverflow.com/users/1069208",
"pm_score": 2,
"selected": false,
"text": "<p>Use the following </p>\n\n<pre><code><div style=\"max-width:980px; overflow-x: scroll; white-space: nowrap;\">\n<table border=\"1\" style=\"cellpadding:0; cellspacing:0; border:0; width=:100%;\" >\n</code></pre>\n"
},
{
"answer_id": 25688137,
"author": "Marco Allori",
"author_id": 1059966,
"author_profile": "https://Stackoverflow.com/users/1059966",
"pm_score": 5,
"selected": false,
"text": "<p>This solution is <strong>without height/width specification for the father div</strong> so it will be <strong>responsive</strong> to window resizing and most useful cause horizontal scrollbars appears just if needed.</p>\n\n<pre><code>.container{\n padding:20px;\n border:dotted 1px;\n white-space:nowrap;\n overflow-x:auto;\n}\n\n.box{\n width:100px;\n height:180px;\n background-color: red;\n margin:10px;\n display:inline-block\n}\n</code></pre>\n\n<p>Take a look at <a href=\"http://jsfiddle.net/evqt871L/\">DEMO</a></p>\n"
},
{
"answer_id": 32911333,
"author": "Amélie Medem",
"author_id": 3924974,
"author_profile": "https://Stackoverflow.com/users/3924974",
"pm_score": 3,
"selected": false,
"text": "<p>I use the CSS properties :\n1) \"<code>overflow-x: auto</code>\";\n2) \"<code>overflow-y: hidden</code>\";\n3) \"<code>white-space: nowrap</code>\";</p>\n\n<p>Don't forget to set a Width, both for the container and inner DIVS components. <strong>The property \"white-space : nowrap\"</strong> allows the inner DIVS not to drop on a different line.</p>\n\n<p>Considering the following HTML:</p>\n\n<pre><code><div class=\"container\"> \n <div class=\"inner-1\"></div>\n <div class=\"inner-2\"></div>\n <div class=\"inner-3\"></div>\n</div>\n</code></pre>\n\n<p>I use the following CSS to have an horizontal scroll only:</p>\n\n<pre><code>.container {\n height: 80px;\n width: 600px;\n overflow-x: auto;\n overflow-y: hidden; \n white-space: nowrap;\n}\n.inner-1,.inner-2,.inner-3 {\n height: 60px;\n max-width: 250px;\n display: inline-block; /* this should fix it */\n}\n</code></pre>\n\n<p>Fiddle: <a href=\"https://jsfiddle.net/qrjh93x8/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/qrjh93x8/</a> (not working with the above code)</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13370/"
] |
I have a div container and have defined its style as follows:
```
div#tbl-container
{
width: 600px;
overflow: auto;
scrollbar-base-color:#ffeaff
}
```
This gives me both horizontal and vertical scroll bars automatically once I populate my table which is contained by this div.
I just want only horizontal scroll bars to appear automatically. I will modify the height of the table programmatically.
How do I do this?
|
You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.
However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.
IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:
```
overflow: auto;
overflow-y: hidden;
```
You may also need to add for IE8:
```
-ms-overflow-y: hidden;
```
as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)
On the other hand it's entirely possible IE8 will have fixed the bug anyway.
|
258,375 |
<p>A lot of iPhone apps use a blue badge to indicate the number of items in the subviews, such as the Mail client:</p>
<p><a href="http://skitch.com/leonho/4xeu/iphoto" rel="noreferrer">iPhoto http://img.skitch.com/20081103-tjr9yupbhgr3sqfh7u56if4rsn.preview.jpg</a></p>
<p>Are there any standards way (or even an API) do this?</p>
<p>UPDATE: I have created a class called BlueBadge to do this. It is available at <a href="http://github.com/leonho/iphone-libs/tree/master" rel="noreferrer">http://github.com/leonho/iphone-libs/tree/master</a></p>
|
[
{
"answer_id": 258485,
"author": "Kristian",
"author_id": 23246,
"author_profile": "https://Stackoverflow.com/users/23246",
"pm_score": 0,
"selected": false,
"text": "<p>There are a few methods in the NSBezierPath class called \"appendBezierPathWithRoundedRect....\".</p>\n\n<p>I havent tried them out myself, but they might work. It's worth a try.</p>\n"
},
{
"answer_id": 258510,
"author": "Kristian",
"author_id": 23246,
"author_profile": "https://Stackoverflow.com/users/23246",
"pm_score": -1,
"selected": false,
"text": "<p>There is also another type of badge that you might already know, it's the \"red\" one that is on the application icon. They are created by doing something like:</p>\n\n<pre><code>NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];\nNSString *caldate = [[now \n dateWithCalendarFormat:@\"%b\" \n timeZone:nil] description];\n[self setApplicationBadge:caldate];\"\n</code></pre>\n\n<p>this will set the badge with a 3 letter abbreviation for the current month.</p>\n"
},
{
"answer_id": 258591,
"author": "Ben Gottlieb",
"author_id": 6694,
"author_profile": "https://Stackoverflow.com/users/6694",
"pm_score": 6,
"selected": true,
"text": "<p>To my knowledge there's no API for this. However, using CoreGraphics (NSBezierPath is not available on iPhone), you can do it pretty easily. It's just two arcs in a CGPath and some text:</p>\n\n<pre><code>CGContextRef context = UIGraphicsGetCurrentContext();\nfloat radius = bounds.size.height / 2.0;\nNSString *countString = [NSString stringWithFormat: @\"%d\", count];\n\nCGContextClearRect(context, bounds);\n\nCGContextSetFillColorWithColor(context, ovalColor);\nCGContextBeginPath(context);\nCGContextAddArc(context, radius, radius, radius, M_PI / 2 , 3 * M_PI / 2, NO);\nCGContextAddArc(context, bounds.size.width - radius, radius, radius, 3 * M_PI / 2, M_PI / 2, NO);\nCGContextClosePath(context);\nCGContextFillPath(context);\n\n[[UIColor whiteColor] set];\n\nUIFont *font = [UIFont boldSystemFontOfSize: 14];\nCGSize numberSize = [countString sizeWithFont: font];\n\nbounds.origin.x = (bounds.size.width - numberSize.width) / 2;\n\n[countString drawInRect: bounds withFont: font];\n</code></pre>\n"
},
{
"answer_id": 342702,
"author": "kleinman",
"author_id": 43451,
"author_profile": "https://Stackoverflow.com/users/43451",
"pm_score": 2,
"selected": false,
"text": "<p>I think a better way to implement something very close to the <code>UITabBarItem</code> badge is to use the <code>UIImage stretchableImageWithLeftCapWidth:topCapHeight:</code> method where both end caps could be a fancier image and the middle will be strech automatically (using the 1px wide image) to fit the <code>NSString</code> size that would be overlaid on top.</p>\n\n<p>Still need to get the proper images but that could be easily pulled from a screenshot or constructed from PS.</p>\n"
},
{
"answer_id": 9339418,
"author": "Yonat",
"author_id": 1176162,
"author_profile": "https://Stackoverflow.com/users/1176162",
"pm_score": 1,
"selected": false,
"text": "<p>You can do it easily and flexibly by using a simple UILabel and changing the cornerRadius of its underlaying layer:</p>\n\n<pre><code>#import <QuartzCore/QuartzCore.h> // don't forget!\n// ...\nUILabel *badge = [[UILabel alloc] init];\nbadge.layer.backgroundColor = [UIColor blueColor].CGColor;\nbadge.layer.cornerRadius = badge.bounds.size.height / 2;\n</code></pre>\n\n<p>You can use my (small and simple) <a href=\"http://ootips.org/yonat/badge-label/\" rel=\"nofollow\">code for a BadgeLabel class and a matching BadgeTableViewCell class</a>.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258375",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30883/"
] |
A lot of iPhone apps use a blue badge to indicate the number of items in the subviews, such as the Mail client:
[iPhoto http://img.skitch.com/20081103-tjr9yupbhgr3sqfh7u56if4rsn.preview.jpg](http://skitch.com/leonho/4xeu/iphoto)
Are there any standards way (or even an API) do this?
UPDATE: I have created a class called BlueBadge to do this. It is available at <http://github.com/leonho/iphone-libs/tree/master>
|
To my knowledge there's no API for this. However, using CoreGraphics (NSBezierPath is not available on iPhone), you can do it pretty easily. It's just two arcs in a CGPath and some text:
```
CGContextRef context = UIGraphicsGetCurrentContext();
float radius = bounds.size.height / 2.0;
NSString *countString = [NSString stringWithFormat: @"%d", count];
CGContextClearRect(context, bounds);
CGContextSetFillColorWithColor(context, ovalColor);
CGContextBeginPath(context);
CGContextAddArc(context, radius, radius, radius, M_PI / 2 , 3 * M_PI / 2, NO);
CGContextAddArc(context, bounds.size.width - radius, radius, radius, 3 * M_PI / 2, M_PI / 2, NO);
CGContextClosePath(context);
CGContextFillPath(context);
[[UIColor whiteColor] set];
UIFont *font = [UIFont boldSystemFontOfSize: 14];
CGSize numberSize = [countString sizeWithFont: font];
bounds.origin.x = (bounds.size.width - numberSize.width) / 2;
[countString drawInRect: bounds withFont: font];
```
|
258,390 |
<p>I have a text file of URLs, about 14000. Below is a couple of examples:</p>
<p><a href="http://www.domainname.com/pagename?CONTENT_ITEM_ID=100&param2=123" rel="nofollow noreferrer">http://www.domainname.com/pagename?CONTENT_ITEM_ID=100&param2=123</a><br />
<a href="http://www.domainname.com/images?IMAGE_ID=10" rel="nofollow noreferrer">http://www.domainname.com/images?IMAGE_ID=10</a><br />
<a href="http://www.domainname.com/pagename?CONTENT_ITEM_ID=101&param2=123" rel="nofollow noreferrer">http://www.domainname.com/pagename?CONTENT_ITEM_ID=101&param2=123</a><br />
<a href="http://www.domainname.com/images?IMAGE_ID=11" rel="nofollow noreferrer">http://www.domainname.com/images?IMAGE_ID=11</a><br />
<a href="http://www.domainname.com/pagename?CONTENT_ITEM_ID=102&param2=123" rel="nofollow noreferrer">http://www.domainname.com/pagename?CONTENT_ITEM_ID=102&param2=123</a><br /></p>
<p>I have loaded the text file into a Python list and I am trying to get all the URLs with CONTENT_ITEM_ID separated off into a list of their own. What would be the best way to do this in Python?</p>
<p>Cheers</p>
|
[
{
"answer_id": 258396,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 3,
"selected": false,
"text": "<pre><code>list2 = filter( lambda x: x.find( 'CONTENT_ITEM_ID ') != -1, list1 )\n</code></pre>\n\n<p>The filter calls the function (first parameter) on each element of list1 (second parameter). If the function returns true (non-zero), the element is copied to the output list.</p>\n\n<p>The lambda basically creates a temporary unnamed function. This is just to avoid having to create a function and then pass it, like this:</p>\n\n<pre><code>function look_for_content_item_id( elem ):\n if elem.find( 'CONTENT_ITEM_ID') == -1:\n return 0\n return 1\nlist2 = filter( look_for_content_item_id, list1 )\n</code></pre>\n"
},
{
"answer_id": 258415,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 5,
"selected": true,
"text": "<p>Here's another alternative to Graeme's, using the newer list comprehension syntax:</p>\n\n<pre><code>list2= [line for line in file if 'CONTENT_ITEM_ID' in line]\n</code></pre>\n\n<p>Which you prefer is a matter of taste!</p>\n"
},
{
"answer_id": 258491,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": false,
"text": "<p>I liked @bobince's answer (+1), but will up the ante.</p>\n\n<p>Since you have a rather large starting set, you may wish to avoid loading the entire list into memory. Unless you need the whole list for something else, you could use a <a href=\"http://www.python.org/doc/2.5.2/ref/genexpr.html\" rel=\"noreferrer\">Python generator expression</a> to perform the same task by building up the filtered list item by item as they're requested:</p>\n\n<pre><code>for filtered_url in (line for line in file if 'CONTENT_ITEM_ID' in line):\n do_something_with_filtered_url(filtered_url)\n</code></pre>\n"
},
{
"answer_id": 258512,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": false,
"text": "<p>For completeness; You can also use <code>ifilter</code>. It is like filter, but doesn't build up a list.</p>\n\n<pre><code>from itertools import ifilter\n\nfor line in ifilter(lambda line: 'CONTENT_ITEM_ID' in line, urls):\n do_something(line)\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
I have a text file of URLs, about 14000. Below is a couple of examples:
<http://www.domainname.com/pagename?CONTENT_ITEM_ID=100¶m2=123>
<http://www.domainname.com/images?IMAGE_ID=10>
<http://www.domainname.com/pagename?CONTENT_ITEM_ID=101¶m2=123>
<http://www.domainname.com/images?IMAGE_ID=11>
<http://www.domainname.com/pagename?CONTENT_ITEM_ID=102¶m2=123>
I have loaded the text file into a Python list and I am trying to get all the URLs with CONTENT\_ITEM\_ID separated off into a list of their own. What would be the best way to do this in Python?
Cheers
|
Here's another alternative to Graeme's, using the newer list comprehension syntax:
```
list2= [line for line in file if 'CONTENT_ITEM_ID' in line]
```
Which you prefer is a matter of taste!
|
258,397 |
<p>I am desiging a new website for my company and I am trying to implement switch navigation which is what I have used on all my sites in the past.</p>
<pre><code><?php
switch($x) {
default:
include("inc/main.php");
break;
case "products":
include("inc/products.php");
break;
}
?>
</code></pre>
<p>For some reason when I go to index.php?x=products nothing happens, it still displays inc/main.php, in other words it hasn't detected the X variable from the URL. Is this something to do with global variables?</p>
|
[
{
"answer_id": 258405,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": true,
"text": "<p>Yes, your PHP configuration has <strong>correctly</strong> got <code>register_globals</code> turned off, because that's incredibly insecure.</p>\n\n<p>Just put:</p>\n\n<pre><code>$x = $_REQUEST['x']\n</code></pre>\n\n<p>at the top of your script.</p>\n\n<p>You can also use <code>$_GET</code> if you specifically only want this to work for the <code>GET</code> HTTP method. I've seen some people claim that <code>$_REQUEST</code> is somehow insecure, but no evidence to back that up.</p>\n"
},
{
"answer_id": 258408,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 1,
"selected": false,
"text": "<p>You should use $_GET to read out these variables. There is a deprecated function called <a href=\"http://nl.php.net/register_globals\" rel=\"nofollow noreferrer\">register_globals</a>, but I would definately not advise to use this, as it is a potential security risk.</p>\n"
},
{
"answer_id": 258410,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 3,
"selected": false,
"text": "<p>It seems like your previous webhosts all used <a href=\"http://php.net/register_globals\" rel=\"noreferrer\">register_globals</a> and your code relies on that. This is a <strong>dangerous</strong> setting and was rightfully removed in PHP 6.0! Use <code>switch($_GET['x']) {</code> instead.</p>\n"
},
{
"answer_id": 7157716,
"author": "rafa",
"author_id": 889482,
"author_profile": "https://Stackoverflow.com/users/889482",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"http://php.net/manual/es/function.extract.php\" rel=\"nofollow\">http://php.net/manual/es/function.extract.php</a> to extract the variables if you want to do it, but keep in mind this lets any user set variables with the content they want in your script, which makes it as insecure as using register_globals</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
I am desiging a new website for my company and I am trying to implement switch navigation which is what I have used on all my sites in the past.
```
<?php
switch($x) {
default:
include("inc/main.php");
break;
case "products":
include("inc/products.php");
break;
}
?>
```
For some reason when I go to index.php?x=products nothing happens, it still displays inc/main.php, in other words it hasn't detected the X variable from the URL. Is this something to do with global variables?
|
Yes, your PHP configuration has **correctly** got `register_globals` turned off, because that's incredibly insecure.
Just put:
```
$x = $_REQUEST['x']
```
at the top of your script.
You can also use `$_GET` if you specifically only want this to work for the `GET` HTTP method. I've seen some people claim that `$_REQUEST` is somehow insecure, but no evidence to back that up.
|
258,407 |
<p>I need to convert a UNICODE_STRING structure to a simple NULL TERMINATED STRING.</p>
<pre><code>typedef
struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
}
UNICODE_STRING, *PUNICODE_STRING;
</code></pre>
<p>I can't find a clean sollution on MSDN about it.
Anyone been there?
I am not using .net so I need a native API sollution.</p>
<p>Thanks a lot!</p>
|
[
{
"answer_id": 258693,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "<p>You should use WideCharToMultiByte. As an estimate for the output buffer size, you can use the Length field - but do consider the case of true multi-byte strings, in which case it will fail with ERROR_INSUFFICIENT_BUFFER, and you need to start over with a larger buffer. Or, you call it with an output buffer size of 0 first always, so it tells you the necessary size of the buffer.</p>\n"
},
{
"answer_id": 9657638,
"author": "SecurityMatt",
"author_id": 1250976,
"author_profile": "https://Stackoverflow.com/users/1250976",
"pm_score": 0,
"selected": false,
"text": "<pre><code>WCHAR* UnicodeStringToNulTerminated(UNICODE_STRING* str)\n{\n WCHAR* result;\n if(str == NULL)\n return NULL;\n result = (WCHAR*)malloc(str->Length + 2);\n if(result == NULL)\n // raise?\n return NULL;\n memcpy(result, str->Buffer, str->Length);\n result[str->Length] = L'\\0';\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 11320148,
"author": "RectangleEquals",
"author_id": 1500110,
"author_profile": "https://Stackoverflow.com/users/1500110",
"pm_score": 2,
"selected": false,
"text": "<p>When compiling for unicode and converting to ansi, this appears to work for me<br>\n(Modified from <a href=\"http://support.microsoft.com/kb/138813\" rel=\"nofollow\">http://support.microsoft.com/kb/138813</a>):<br><br></p>\n\n<pre><code>HRESULT UnicodeToAnsi(LPCOLESTR pszW, LPSTR* ppszA){\n ULONG cbAnsi, cCharacters;\n DWORD dwError;\n // If input is null then just return the same. \n if (pszW == NULL) \n {\n *ppszA = NULL;\n return NOERROR;\n }\n cCharacters = wcslen(pszW)+1;\n cbAnsi = cCharacters*2;\n\n *ppszA = (LPSTR) CoTaskMemAlloc(cbAnsi);\n if (NULL == *ppszA)\n return E_OUTOFMEMORY;\n\n if (0 == WideCharToMultiByte(CP_ACP, 0, pszW, cCharacters, *ppszA, cbAnsi, NULL, NULL)) \n {\n dwError = GetLastError();\n CoTaskMemFree(*ppszA);\n *ppszA = NULL;\n return HRESULT_FROM_WIN32(dwError);\n }\n return NOERROR;\n}\n</code></pre>\n\n<p><br>\nUsage:</p>\n\n<pre><code>LPSTR pszstrA;\nUnicodeToAnsi(my_unicode_string.Buffer, &pszstrA);\ncout << \"My ansi string: (\" << pszstrA << \")\\r\\n\";\n</code></pre>\n"
},
{
"answer_id": 11321143,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 0,
"selected": false,
"text": "<p>Since you did not say whether you need an ANSI or UNICODE null-terminated string, I'm going to assume UNICODE:</p>\n\n<pre><code>#include <string>\n\nUNICODE_STRING us;\n// fill us as needed...\n\nstd::wstring ws(us.Buffer, us.Length);\n// use ws.c_str() where needed...\n</code></pre>\n"
},
{
"answer_id": 13409339,
"author": "glagolig",
"author_id": 1236546,
"author_profile": "https://Stackoverflow.com/users/1236546",
"pm_score": 1,
"selected": false,
"text": "<p>Alternative code that converts to ANSI and does not require number of unicode characters in UNICODE_STRING that has to be passed as a parameter to WideCharToMultiByte. (Note that UNICODE_STRING.Length is a number of bytes, not unicode characters, and wcslen does not work if buffer is not zero-terminated).</p>\n\n<pre><code>UNICODE_STRING tmp;\n// ...\nSTRING dest; // or ANSI_STRING in kernel mode\n\nLONG (WINAPI *RtlUnicodeStringToAnsiString)(PVOID, PVOID, BOOL);\n*(FARPROC *)&RtlUnicodeStringToAnsiString = \n GetProcAddress(LoadLibraryA(\"NTDLL.DLL\"), \"RtlUnicodeStringToAnsiString\");\nif(!RtlUnicodeStringToAnsiString)\n{\n return;\n}\n\nULONG unicodeBufferSize = tmp.Length;\ndest.Buffer = (PCHAR)malloc(unicodeBufferSize+1); // that must be enough...\ndest.Length = 0;\ndest.MaximumLength = unicodeBufferSize+1;\n\nRtlUnicodeStringToAnsiString(&dest, &tmp, FALSE);\ndest.Buffer[dest.Length] = 0; // now we get it in dest.Buffer\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to convert a UNICODE\_STRING structure to a simple NULL TERMINATED STRING.
```
typedef
struct _UNICODE_STRING
{
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
}
UNICODE_STRING, *PUNICODE_STRING;
```
I can't find a clean sollution on MSDN about it.
Anyone been there?
I am not using .net so I need a native API sollution.
Thanks a lot!
|
You should use WideCharToMultiByte. As an estimate for the output buffer size, you can use the Length field - but do consider the case of true multi-byte strings, in which case it will fail with ERROR\_INSUFFICIENT\_BUFFER, and you need to start over with a larger buffer. Or, you call it with an output buffer size of 0 first always, so it tells you the necessary size of the buffer.
|
258,409 |
<p>I have a 'generic' boiler plate static method for checking for InvokeRequired and invoking an associated action accordingly.</p>
<p>If an unhandled exception is raised by the action, the stack trace isn't much help because it starts from here. I can get information about the control, but that isn't always much help. I was wondering if it is possible to get 'something' useful out of the Action - other that 'Target'. (Note that the Action is often a lambda or anonymous delegate...)</p>
<pre><code> public static void Invoke(Control ctrl, Action action)
{
if (ctrl == null)
throw new ArgumentNullException("ctrl");
if (action == null)
return;
var invokeRequired = ctrl.InvokeRequired;
try
{
if (ctrl.InvokeRequired)
ctrl.Invoke(action);
else
action();
}
catch (Exception ex)
{
throw new Exception(String.Format("Invoke error, ctrl={0}, action Target={1}", ctrl.Name, action.Target), ex);
}
}
</code></pre>
<p>EDIT: In line with this answer, here is the new overload (also slightly improved)</p>
<pre><code>public static void Invoke(Control ctrl, Action action, string context)
{
if (ctrl == null)
throw new ArgumentNullException("ctrl");
if (action == null)
return; //not sure it's worththrowing an exception here...
var invokeRequired = ctrl.InvokeRequired;
try
{
if (invokeRequired)
ctrl.Invoke(action);
else
action();
}
catch (Exception ex)
{
var ps = invokeRequired ? "" : " - has the target control been initialised?";
var errmsg = String.Format("Invoke error, ctrl={0}, action Target={1}, context={2}{3}", ctrl.Name, action.Target, context, ps);
throw new Exception(errmsg, ex);
}
}
</code></pre>
|
[
{
"answer_id": 258693,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 2,
"selected": false,
"text": "<p>You should use WideCharToMultiByte. As an estimate for the output buffer size, you can use the Length field - but do consider the case of true multi-byte strings, in which case it will fail with ERROR_INSUFFICIENT_BUFFER, and you need to start over with a larger buffer. Or, you call it with an output buffer size of 0 first always, so it tells you the necessary size of the buffer.</p>\n"
},
{
"answer_id": 9657638,
"author": "SecurityMatt",
"author_id": 1250976,
"author_profile": "https://Stackoverflow.com/users/1250976",
"pm_score": 0,
"selected": false,
"text": "<pre><code>WCHAR* UnicodeStringToNulTerminated(UNICODE_STRING* str)\n{\n WCHAR* result;\n if(str == NULL)\n return NULL;\n result = (WCHAR*)malloc(str->Length + 2);\n if(result == NULL)\n // raise?\n return NULL;\n memcpy(result, str->Buffer, str->Length);\n result[str->Length] = L'\\0';\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 11320148,
"author": "RectangleEquals",
"author_id": 1500110,
"author_profile": "https://Stackoverflow.com/users/1500110",
"pm_score": 2,
"selected": false,
"text": "<p>When compiling for unicode and converting to ansi, this appears to work for me<br>\n(Modified from <a href=\"http://support.microsoft.com/kb/138813\" rel=\"nofollow\">http://support.microsoft.com/kb/138813</a>):<br><br></p>\n\n<pre><code>HRESULT UnicodeToAnsi(LPCOLESTR pszW, LPSTR* ppszA){\n ULONG cbAnsi, cCharacters;\n DWORD dwError;\n // If input is null then just return the same. \n if (pszW == NULL) \n {\n *ppszA = NULL;\n return NOERROR;\n }\n cCharacters = wcslen(pszW)+1;\n cbAnsi = cCharacters*2;\n\n *ppszA = (LPSTR) CoTaskMemAlloc(cbAnsi);\n if (NULL == *ppszA)\n return E_OUTOFMEMORY;\n\n if (0 == WideCharToMultiByte(CP_ACP, 0, pszW, cCharacters, *ppszA, cbAnsi, NULL, NULL)) \n {\n dwError = GetLastError();\n CoTaskMemFree(*ppszA);\n *ppszA = NULL;\n return HRESULT_FROM_WIN32(dwError);\n }\n return NOERROR;\n}\n</code></pre>\n\n<p><br>\nUsage:</p>\n\n<pre><code>LPSTR pszstrA;\nUnicodeToAnsi(my_unicode_string.Buffer, &pszstrA);\ncout << \"My ansi string: (\" << pszstrA << \")\\r\\n\";\n</code></pre>\n"
},
{
"answer_id": 11321143,
"author": "Remy Lebeau",
"author_id": 65863,
"author_profile": "https://Stackoverflow.com/users/65863",
"pm_score": 0,
"selected": false,
"text": "<p>Since you did not say whether you need an ANSI or UNICODE null-terminated string, I'm going to assume UNICODE:</p>\n\n<pre><code>#include <string>\n\nUNICODE_STRING us;\n// fill us as needed...\n\nstd::wstring ws(us.Buffer, us.Length);\n// use ws.c_str() where needed...\n</code></pre>\n"
},
{
"answer_id": 13409339,
"author": "glagolig",
"author_id": 1236546,
"author_profile": "https://Stackoverflow.com/users/1236546",
"pm_score": 1,
"selected": false,
"text": "<p>Alternative code that converts to ANSI and does not require number of unicode characters in UNICODE_STRING that has to be passed as a parameter to WideCharToMultiByte. (Note that UNICODE_STRING.Length is a number of bytes, not unicode characters, and wcslen does not work if buffer is not zero-terminated).</p>\n\n<pre><code>UNICODE_STRING tmp;\n// ...\nSTRING dest; // or ANSI_STRING in kernel mode\n\nLONG (WINAPI *RtlUnicodeStringToAnsiString)(PVOID, PVOID, BOOL);\n*(FARPROC *)&RtlUnicodeStringToAnsiString = \n GetProcAddress(LoadLibraryA(\"NTDLL.DLL\"), \"RtlUnicodeStringToAnsiString\");\nif(!RtlUnicodeStringToAnsiString)\n{\n return;\n}\n\nULONG unicodeBufferSize = tmp.Length;\ndest.Buffer = (PCHAR)malloc(unicodeBufferSize+1); // that must be enough...\ndest.Length = 0;\ndest.MaximumLength = unicodeBufferSize+1;\n\nRtlUnicodeStringToAnsiString(&dest, &tmp, FALSE);\ndest.Buffer[dest.Length] = 0; // now we get it in dest.Buffer\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258409",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11410/"
] |
I have a 'generic' boiler plate static method for checking for InvokeRequired and invoking an associated action accordingly.
If an unhandled exception is raised by the action, the stack trace isn't much help because it starts from here. I can get information about the control, but that isn't always much help. I was wondering if it is possible to get 'something' useful out of the Action - other that 'Target'. (Note that the Action is often a lambda or anonymous delegate...)
```
public static void Invoke(Control ctrl, Action action)
{
if (ctrl == null)
throw new ArgumentNullException("ctrl");
if (action == null)
return;
var invokeRequired = ctrl.InvokeRequired;
try
{
if (ctrl.InvokeRequired)
ctrl.Invoke(action);
else
action();
}
catch (Exception ex)
{
throw new Exception(String.Format("Invoke error, ctrl={0}, action Target={1}", ctrl.Name, action.Target), ex);
}
}
```
EDIT: In line with this answer, here is the new overload (also slightly improved)
```
public static void Invoke(Control ctrl, Action action, string context)
{
if (ctrl == null)
throw new ArgumentNullException("ctrl");
if (action == null)
return; //not sure it's worththrowing an exception here...
var invokeRequired = ctrl.InvokeRequired;
try
{
if (invokeRequired)
ctrl.Invoke(action);
else
action();
}
catch (Exception ex)
{
var ps = invokeRequired ? "" : " - has the target control been initialised?";
var errmsg = String.Format("Invoke error, ctrl={0}, action Target={1}, context={2}{3}", ctrl.Name, action.Target, context, ps);
throw new Exception(errmsg, ex);
}
}
```
|
You should use WideCharToMultiByte. As an estimate for the output buffer size, you can use the Length field - but do consider the case of true multi-byte strings, in which case it will fail with ERROR\_INSUFFICIENT\_BUFFER, and you need to start over with a larger buffer. Or, you call it with an output buffer size of 0 first always, so it tells you the necessary size of the buffer.
|
258,422 |
<p>Using qsort in C we pass in a comparison function e.g.</p>
<pre><code>int cmp(const void*, const void*);
</code></pre>
<p>the protoype of qsort expects a <code>int (* )(const void* , const void*)</code> so we call:</p>
<pre><code>qsort(..., cmp);
</code></pre>
<p>but it is equally valid to call:</p>
<pre><code>qsort(..., &cmp);
</code></pre>
<p>and this is what we would have to do if we passed in a static member-function in C++. Kernighan & Ritchie (2nd Edition, 5.11 "Pointers To Functions" p119) states that "since [cmp] is known to be a function, the & operator is not necessary, in the same way that it is not needed before an array name."</p>
<p>Does anyone else feel slightly uncomfortable with this (esp. regarding type-safety)?</p>
|
[
{
"answer_id": 258435,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 3,
"selected": false,
"text": "<p>Whether you feel uncomfortable or not doesn't change the fact that C is not considered a type-safe language. Case in point:</p>\n\n<pre><code>int main()\n{\n int integer = 0xFFFFFF; \n void (*functionPointer)() = (void(*)())integer; \n\n functionPointer(); \n\n return 0; \n}\n</code></pre>\n\n<p>This is completely valid at compile time, but it is obviously not safe.</p>\n"
},
{
"answer_id": 258458,
"author": "workmad3",
"author_id": 16035,
"author_profile": "https://Stackoverflow.com/users/16035",
"pm_score": 2,
"selected": false,
"text": "<p>It's a syntax detail. If you don't like not using the & to indicate a function pointer then always use it. If you like saving the extra keypresses and not being as explicit in your coding then take advantage of it.</p>\n\n<p>As regards type safety, I don't see how it makes any difference. The compiler is given a function as an argument and it can work out what the function signature is entirely from the name. The fact that you aren't calling it (with the () syntax) gives all the indication the compiler needs that you want a function pointer in this location. The & is just a syntactic nicety to indicate to humans that they are looking at a pointer of some description.</p>\n\n<p>If you are using C++, then I'd suggest looking at boost functors as a nicer method of passing around functions anyway. These lovely entities allow a unified and fairly clear syntax for all functions in C++ :)</p>\n"
},
{
"answer_id": 258459,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "<p>It's not so much a sense of discomfort as a distaste for valid-yet-conflicting syntax options. Either <code>cmp</code> is pointer, and should be treated consistently as such, or it's some other type--which, IMHO is syntactically misleading.</p>\n\n<p>Going a bit further, I'd also require a call either to dereference the pointer (to highlight the fact that it's a pointer) or not (because a function name <em>is</em> a pointer) ... but not allow both. </p>\n\n<p>Function pointers can be extremely powerful, yet they seem to be a source of confusion to both new and experienced programmers alike. Part of the difficulty could be alleviated by requiring a single, meaningful syntax that <em>clarifies</em> their use, rather than <em>obscuring</em> it.</p>\n"
},
{
"answer_id": 258461,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "<p>I suspect you only feel uncomfortable because you're not used to coding as 'close to the metal' as C allows. The reason why C doesn't require the address-of operator on functions is that there's nothing you can really do with functions other than call them or pass them.</p>\n\n<p>In other words, there's no sensible definition for manipulating the 'value' of a function.</p>\n\n<p>Whereas with ints, you can add to or subtract from the value, this makes no sense for functions.</p>\n\n<p>In any case, C predates both C++ and its own standardization - the original K&R C didn't even have prototypes and ANSI had to make sure that their standardization didn't break existing code as much as possible.</p>\n"
},
{
"answer_id": 260202,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 1,
"selected": false,
"text": "<p>Note that the same goes for 'dereferencing' (i.e. calling) function pointers; you don't have to</p>\n\n<pre><code>(*funcptr)(arg1, arg2);\n</code></pre>\n\n<p>as</p>\n\n<pre><code>funcptr(arg1, arg2);\n</code></pre>\n\n<p>will suffice.</p>\n"
},
{
"answer_id": 264142,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "<p>Well, the answer is that passing a function by value yields a function pointer, the same way as passing an array by value yields a pointer to its first element. one says that the array and the function \"decay\". there are only a few occasions where that decay doesn't happen. \nfor example sizeof(array) yields the sizeof the array, not the one of its first element pointer. sizeof(function) is invalid (functions are no objects), you have to do sizeof(&function). Other occasions are binding to references: </p>\n\n<pre><code>void baz();\n\nvoid foo(void (&bar)()) {\n bar();\n}\n\n// doesnt work, since a reference to a function is requested. \n// you have to pass 'bar' itself, without taking its address \n// explicitely.\nfoo(&baz); \n</code></pre>\n\n<p>This, btw all is the reason you can do</p>\n\n<pre><code>template<typename T, int N>\nvoid ByRef(T (&foo)[N]) { \n ...\n}\n</code></pre>\n\n<p>since the array does not decay yet when considering reference parameters. </p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26665/"
] |
Using qsort in C we pass in a comparison function e.g.
```
int cmp(const void*, const void*);
```
the protoype of qsort expects a `int (* )(const void* , const void*)` so we call:
```
qsort(..., cmp);
```
but it is equally valid to call:
```
qsort(..., &cmp);
```
and this is what we would have to do if we passed in a static member-function in C++. Kernighan & Ritchie (2nd Edition, 5.11 "Pointers To Functions" p119) states that "since [cmp] is known to be a function, the & operator is not necessary, in the same way that it is not needed before an array name."
Does anyone else feel slightly uncomfortable with this (esp. regarding type-safety)?
|
Whether you feel uncomfortable or not doesn't change the fact that C is not considered a type-safe language. Case in point:
```
int main()
{
int integer = 0xFFFFFF;
void (*functionPointer)() = (void(*)())integer;
functionPointer();
return 0;
}
```
This is completely valid at compile time, but it is obviously not safe.
|
258,425 |
<p>I have a large project for which I am attempting to use TDD.
I am using <a href="http://tut-framework.sourceforge.net/" rel="nofollow noreferrer">Tut</a> as my test framework, which has its flaws but is sufficient for what I need. </p>
<p>I need to exploit link time test seams, <strong>each test must be in its own executable</strong>. The project for this executable then launches itself as a post build step.</p>
<p>Unfortunately, this means that my Visual Studio Sln is filling up with tests, which is not scalable and also hides the actual important projects.</p>
<p>Does anyone know of a better way of running these tests?
Is it possible to hide projects from a build and yet still have them build? </p>
|
[
{
"answer_id": 258453,
"author": "sergtk",
"author_id": 13441,
"author_profile": "https://Stackoverflow.com/users/13441",
"pm_score": 3,
"selected": true,
"text": "<p>\"Is it possible to hide projects from a build and yet still have them build?\"</p>\n\n<p>You can make separate solution for test cases.\nThen you can set up post build step of your main projects. This post-build should build tests-projects via separate solution and run them. Building test-projects should be done via command line (see e.g. <a href=\"http://www-unix.mcs.anl.gov/mpi/mpich1/docs/mpichntman/node10.htm\" rel=\"nofollow noreferrer\">here</a> for details).</p>\n\n<p>If you need to link your unit tests with some lib-s from main projects, you can use </p>\n\n<pre><code>#pragma comment(lib, \"libname\")\n</code></pre>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx\" rel=\"nofollow noreferrer\">this MSDN page</a> for details.</p>\n"
},
{
"answer_id": 271739,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 0,
"selected": false,
"text": "<p>You could try to group your tests into folders (are they called filters?) within your solution in Solution Explorer. This would separate tests from your other projects.</p>\n\n<p>But, otherwise, could you avoid using link time test seams (Yes, I know, its probably too late to suggest this) and use polymorphism to provide your run-time variation and have less test projects?</p>\n"
},
{
"answer_id": 579631,
"author": "Dushara",
"author_id": 54018,
"author_profile": "https://Stackoverflow.com/users/54018",
"pm_score": 0,
"selected": false,
"text": "<p>Don't know if you're still looking for a solution. But here's an idea:</p>\n\n<p>You can keep all your tests in one library and write an application that spawns itself and executes each test. This way you end up with one executable (and hence one project) for a suite and each test will be like a separate executable.</p>\n\n<p>This is in-fact the mechanism used in <a href=\"http://code.google.com/p/cunitwin32/\" rel=\"nofollow noreferrer\">CUnitWin32</a>. You might even be able to wrap your tests in that framework.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1575281/"
] |
I have a large project for which I am attempting to use TDD.
I am using [Tut](http://tut-framework.sourceforge.net/) as my test framework, which has its flaws but is sufficient for what I need.
I need to exploit link time test seams, **each test must be in its own executable**. The project for this executable then launches itself as a post build step.
Unfortunately, this means that my Visual Studio Sln is filling up with tests, which is not scalable and also hides the actual important projects.
Does anyone know of a better way of running these tests?
Is it possible to hide projects from a build and yet still have them build?
|
"Is it possible to hide projects from a build and yet still have them build?"
You can make separate solution for test cases.
Then you can set up post build step of your main projects. This post-build should build tests-projects via separate solution and run them. Building test-projects should be done via command line (see e.g. [here](http://www-unix.mcs.anl.gov/mpi/mpich1/docs/mpichntman/node10.htm) for details).
If you need to link your unit tests with some lib-s from main projects, you can use
```
#pragma comment(lib, "libname")
```
See [this MSDN page](http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx) for details.
|
258,481 |
<p>In any (non-web) .net project, the compiler automatically declares the DEBUG and TRACE constants, so I can use conditional compiling to, for example, handle exceptions differently in debug vs release mode.</p>
<p>For example:</p>
<pre><code>#if DEBUG
/* re-throw the exception... */
#else
/* write something in the event log... */
#endif
</code></pre>
<p>How do I obtain the same behavior in an ASP.net project?
It looks like the system.web/compilation section in the web.config could be what I need, but how do I check it programmatically?
Or am I better off declaring a DEBUG constant myself and comment it out in release builds?</p>
<p>EDIT: I'm on VS 2008</p>
|
[
{
"answer_id": 258495,
"author": "Andrew Theken",
"author_id": 32238,
"author_profile": "https://Stackoverflow.com/users/32238",
"pm_score": 4,
"selected": true,
"text": "<p>Look at <a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx\" rel=\"noreferrer\">ConfigurationManager.GetSection()</a> - this should get you most of the way there.. however, I think you're better off just changing between debug and release modes and letting the compiler determine to execute the \"#if DEBUG\" enclosed statements.</p>\n\n<pre><code>#if DEBUG\n/* re-throw the exception... */\n#else\n/* write something in the event log... */\n#endif\n</code></pre>\n\n<p>the above will work just fine, just make sure you have at least two build configurations (right-click the project you're working on and go to \"Properties\" there's a section in there on Builds) - make sure that one of those builds has the \"define DEBUG\" checked and the other does not.</p>\n"
},
{
"answer_id": 258515,
"author": "TheCodeJunkie",
"author_id": 25319,
"author_profile": "https://Stackoverflow.com/users/25319",
"pm_score": 3,
"selected": false,
"text": "<p>To add ontop of Andrews answer, you could wrap it in a method as well</p>\n\n<pre><code>public bool IsDebugMode\n{\n get\n {\n#if DEBUG \n return true;\n#else\n return false;\n#endif\n }\n}\n</code></pre>\n"
},
{
"answer_id": 259271,
"author": "Loris",
"author_id": 23824,
"author_profile": "https://Stackoverflow.com/users/23824",
"pm_score": 3,
"selected": false,
"text": "<p>This is what I ended up doing:</p>\n\n<pre><code>protected bool IsDebugMode\n{\n get\n {\n System.Web.Configuration.CompilationSection tSection;\n tSection = ConfigurationManager.GetSection(\"system.web/compilation\") as System.Web.Configuration.CompilationSection;\n if (null != tSection)\n {\n return tSection.Debug;\n }\n /* Default to release behavior */\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 60073084,
"author": "ShrapNull",
"author_id": 1652234,
"author_profile": "https://Stackoverflow.com/users/1652234",
"pm_score": 1,
"selected": false,
"text": "<p>Personally I don't like the way \"#if debug\" changes the layout. I do it by creating a conditional method that is only called when in debug mode and pass a boolean by reference.</p>\n\n<pre><code>[Conditional(\"DEBUG\")]\nprivate void IsDebugCheck(ref bool isDebug)\n{\n isDebug = true;\n}\n\npublic void SomeCallingMethod()\n{ \n bool isDebug = false;\n IsDebugCheck(ref isDebug);\n}\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23824/"
] |
In any (non-web) .net project, the compiler automatically declares the DEBUG and TRACE constants, so I can use conditional compiling to, for example, handle exceptions differently in debug vs release mode.
For example:
```
#if DEBUG
/* re-throw the exception... */
#else
/* write something in the event log... */
#endif
```
How do I obtain the same behavior in an ASP.net project?
It looks like the system.web/compilation section in the web.config could be what I need, but how do I check it programmatically?
Or am I better off declaring a DEBUG constant myself and comment it out in release builds?
EDIT: I'm on VS 2008
|
Look at [ConfigurationManager.GetSection()](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.getsection.aspx) - this should get you most of the way there.. however, I think you're better off just changing between debug and release modes and letting the compiler determine to execute the "#if DEBUG" enclosed statements.
```
#if DEBUG
/* re-throw the exception... */
#else
/* write something in the event log... */
#endif
```
the above will work just fine, just make sure you have at least two build configurations (right-click the project you're working on and go to "Properties" there's a section in there on Builds) - make sure that one of those builds has the "define DEBUG" checked and the other does not.
|
258,483 |
<h2>Question</h2>
<p>I'm sure many of you have been faced by the challenge of localizing a database backend to an application. If you've not then I'd be pretty confident in saying that the odds of you having to do so in the future is quite large. I'm talking anout storing multiple translations of texts (and the same can be said for currency etc.) for your database entities.</p>
<p>For example the classic "Category" table might have a Name and a Description column which should be globalized. One way would be to do have a "Text" table for each of your entities and then do a join to retreive the values based on the provided language.</p>
<p>This leaves you with a lot of "Text" tables, one for each entity which you want to localize, with the addition of a TextType to distinguish between the various texts that it may store.</p>
<p>I'm curious if there are any, documented, best-practises / design patterns on implementing this kind of support into a SQL Server 2005/2008 datebase (I'm being specific about the RDBMS since it might contain supported keywords and such which helps with the implementation)?</p>
<h2>Thoughts on XML approach</h2>
<p>One idea I have been toying with (albeit only in my head so far) was to leverage the XML datatype introduced in SQL Server 2005. The idea was to make columns which should support localization, of the XML datatype (and bind a schema to it). The XML would contain the localized strings along with the language code / culture it was tied to.</p>
<p>Something along the lines of</p>
<pre><code>Product
ID (int, identity)
Name (XML ...)
Description (XML ...)
</code></pre>
<p>Then you would have something like this as the XML</p>
<pre><code><localization>
<text culture="sv-SE">Detta är ett namn</text>
<text culture="en-EN">This is a name</text>
</localization>
</code></pre>
<p>You could then do (This isn't production code so I'll use the *)</p>
<pre><code>SELECT *
From Product
Where Product.ID = 10
</code></pre>
<p>And you would get back the product with all localized texts which would mean you would have to do the extraction on the client-side. The biggest problem here is obviously the amount of extra data that you would have to return on each query, The benefits would be a cleaner design with no look-up tables, joins and so on. </p>
<p>Btw, what ever method I do end up using in my design I will still be using Linq To SQL (.NET Platform) to query the database (the XML approach should be a problem since it would return an XElement which could be interpreted client-side)</p>
<p>So suggestion on database localization design patterns, and possibly comments on the XML thought, would be very apprechiated.</p>
|
[
{
"answer_id": 258678,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 1,
"selected": false,
"text": "<p>I can't see why you need multiple text tables. A single text table, with a \"globally\" unique text ID, should be sufficient. The table would have ID, language, text columns, and you would only ever get the text in the language that you need to present (or perhaps not retrieve the text at all). The join should be fairly efficient, since the combination of (ID, language) is the primary key.</p>\n"
},
{
"answer_id": 258713,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 1,
"selected": false,
"text": "<p>That's one of the questions that are difficult to answer because there are so many \"it depends\" in the answer :-)</p>\n\n<p>The answer depends on the amount of localized items in the database, on deployment scenarios, caching issues, access patterns and so on. If you can give us some data on how big the application is, how many concurrent users it will have and how it will be deployed, that would be very helpful.</p>\n\n<p>In general terms I usually use one of two approaches: </p>\n\n<ol>\n<li>Store the localized items near the executable (localized ressource dlls)</li>\n<li>Store localized items in the DB and introduce a localeID column in tables that contain the localized items.</li>\n</ol>\n\n<p>The advantage of the first method is the good VisualStudio support. The advantage of the second is the centralized deployment.</p>\n"
},
{
"answer_id": 261900,
"author": "TToni",
"author_id": 20703,
"author_profile": "https://Stackoverflow.com/users/20703",
"pm_score": 1,
"selected": false,
"text": "<p>I see no advantage in using the XML-columns to store the localized values. Except maybe that you have all localized versions of one item \"in one place\" if that's worth something to you.</p>\n\n<p>I would propose to use a cultureID-column in each table that has localizable items. That way you don't need any XML-handling at all. You already have your data in a relational schema so why introduce another layer of complexity when the relational schema is perfectly capable of handling the problem?</p>\n\n<p>Let's say \"sv-SE\" has cultureID = 1 and \"en-EN\" has 2.</p>\n\n<p>Then your query would be modified as</p>\n\n<pre><code>SELECT *\nFrom Product\nWhere Product.ID = 10 AND Product.cultureID = 1\n</code></pre>\n\n<p>for a swedish client.</p>\n\n<p>This solution I have seen frequently in localized databases. It scales well with both number of cultures and number of datarecords. It avoids XML-parsing and processing and is easy to implement.</p>\n\n<p>And another point: The XML-solution gives you a flexibility you don't need: You could for example take the \"sv-SE\"-value from the \"Name\"-column and the \"en-EN\"-value from the \"Description\"-column. However, you don't need this since your client will request only one culture at a time. Flexibility usually has a cost. In this case it is that you need to parse all columns individually while with the cultureID solution you get the whole record with all the values right for the requested culture.</p>\n"
},
{
"answer_id": 261979,
"author": "Mac",
"author_id": 8696,
"author_profile": "https://Stackoverflow.com/users/8696",
"pm_score": 2,
"selected": false,
"text": "<p>I think you can stick with XML which allows for a cleaner design. I would go further and take advantage of the <code>xml:lang</code> attribute which <a href=\"http://www.opentag.com/xfaq_lang.htm\" rel=\"nofollow noreferrer\">is designed for this usage</a> :</p>\n\n<pre><code><l10n>\n <text xml:lang=\"sv-SE\">Detta är ett namn</text>\n <text xml:lang=\"en-EN\">This is a name</text>\n</l10n>\n</code></pre>\n\n<p>One step further, you could select the localized resource in your query via <a href=\"http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx\" rel=\"nofollow noreferrer\">a XPath query</a> (as suggested in the comments) to avoid any client side treatment. This would give something like this (untested) :</p>\n\n<pre><code>SELECT Name.value('(l10n/text[lang()=\"en\"])[1]', 'NVARCHAR(MAX)')\n FROM Product\n WHERE Product.ID=10;\n</code></pre>\n\n<p>Note that this solution would be an elegant but less efficient solution than the separate table one. Which may be OK for some application.</p>\n"
},
{
"answer_id": 375326,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I like the XML approach, because the separate-table-solution would NOT return a result if e.g. there is no swedish translation (cultureID = 1) unless you do an outer join. But nevertheless you can NOT fall back to English. With the XML approach you simply can fall back to English.\nAny news on the XML approach in a producitve environment?</p>\n"
},
{
"answer_id": 865133,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 0,
"selected": false,
"text": "<p>Here some thoghts on the Rick Strahl's blog: </p>\n\n<p><a href=\"http://www.west-wind.com/weblog/posts/695968.aspx\" rel=\"nofollow noreferrer\">Localization of database</a>\n<a href=\"http://www.west-wind.com/Weblog/posts/698097.aspx\" rel=\"nofollow noreferrer\">Localization of JavaScript</a> </p>\n\n<p>I do prefer to use a single switch in a UserSetting table , which is used by calling stored procedure ... here some of the code </p>\n\n<pre><code>CREATE TABLE [dbo].[Lang_en_US_Msg](\n [MsgId] [int] IDENTITY(1,1) NOT NULL,\n [MsgKey] [varchar](200) NOT NULL,\n [MsgTxt] [varchar](2000) NOT NULL,\n [MsgDescription] [varchar](2000) NOT NULL,\n CONSTRAINT [PK_Lang_US-us__Msg] PRIMARY KEY CLUSTERED \n(\n [MsgId] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nGO\n\nCREATE TABLE [dbo].[User](\n [UserId] [int] IDENTITY(1,1) NOT NULL,\n [FirstName] [varchar](50) NOT NULL,\n [MiddleName] [varchar](50) NULL,\n [LastName] [varchar](50) NULL,\n [DomainName] [varchar](50) NULL,\n CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED \n(\n [UserId] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nCREATE TABLE [dbo].[UserSetting](\n [UserSettingId] [int] IDENTITY(1,1) NOT NULL,\n [UserId] [int] NOT NULL,\n [CultureInfo] [varchar](50) NOT NULL,\n [GuiLanguage] [varchar](10) NOT NULL,\n CONSTRAINT [PK_UserSetting] PRIMARY KEY CLUSTERED \n(\n [UserSettingId] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n</code></pre>\n\n<p>GO</p>\n\n<pre><code> ALTER TABLE [dbo].[UserSetting] ADD CONSTRAINT [DF_UserSetting_CultureInfo] DEFAULT ('fi-FI') FOR [CultureInfo]\n GO\n\n CREATE TABLE [dbo].[Lang_fi_FI_Msg](\n [MsgId] [int] IDENTITY(1,1) NOT NULL,\n [MsgKey] [varchar](200) NOT NULL,\n [MsgTxt] [varchar](2000) NOT NULL,\n [MsgDescription] [varchar](2000) NOT NULL,\n [DbSysNameForExpansion] [varchar](50) NULL,\n CONSTRAINT [PK_Lang_Fi-fi__Msg] PRIMARY KEY CLUSTERED \n(\n [MsgId] ASC\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n) ON [PRIMARY]\n\nCREATE PROCEDURE [dbo].[procGui_GetPageMsgs]\n@domainUser varchar(50) , -- the domain_user performing the action \n@msgOut varchar(4000) OUT, -- the (error) msg to be shown to the user \n@debugMsgOut varchar(4000) OUT , -- this variable holds the debug msg to be shown if debug level is enabled \n@ret int OUT -- the variable indicating success or failure \n\nAS \nBEGIN -- proc start \n SET NOCOUNT ON; \n\ndeclare @procedureName varchar(200) \ndeclare @procStep varchar(4000) \n\n\nset @procedureName = ( SELECT OBJECT_NAME(@@PROCID)) \nset @msgOut = ' ' \nset @debugMsgOut = ' ' \nset @procStep = ' ' \n\n\nBEGIN TRY --begin try \nset @ret = 1 --assume false from the beginning \n\n--===============================================================\n --debug set @procStep=@procStep + 'GETTING THE GUI LANGUAGE FOR THIS USER '\n--===============================================================\n\ndeclare @guiLanguage nvarchar(10)\n\n\n\n\nif ( @domainUser is null)\n set @guiLanguage = (select Val from AppSetting where Name='guiLanguage')\nelse \n set @guiLanguage = (select GuiLanguage from UserSetting us join [User] u on u.UserId = us.UserId where u.DomainName=@domainUser)\n\nset @guiLanguage = REPLACE ( @guiLanguage , '-' , '_' ) ;\n\n\n--===============================================================\nset @procStep=@procStep + ' BUILDING THE SQL QUERY '\n--===============================================================\n\nDECLARE @sqlQuery AS nvarchar(2000)\nSET @sqlQuery = 'SELECT MsgKey , MsgTxt FROM dbo.lang_' + @guiLanguage + '_Msg'\n\n\n--===============================================================\nset @procStep=@procStep + 'EXECUTING THE SQL QUERY'\n--===============================================================\nprint @sqlQuery\n\n exec sp_executesql @sqlQuery\n\n set @debugMsgOut = @procStep\n set @ret = @@ERROR \n\n\nEND TRY --end try \n\nBEGIN CATCH \n PRINT 'In CATCH block. \n Error number: ' + CAST(ERROR_NUMBER() AS varchar(10)) + ' \n Error message: ' + ERROR_MESSAGE() + ' \n Error severity: ' + CAST(ERROR_SEVERITY() AS varchar(10)) + ' \n Error state: ' + CAST(ERROR_STATE() AS varchar(10)) + ' \n XACT_STATE: ' + CAST(XACT_STATE() AS varchar(10)); \n\nset @msgOut = 'Failed to execute ' + @sqlQuery \nset @debugMsgOut = ' Error number: ' + CAST(ERROR_NUMBER() AS varchar(10)) + \n 'Error message: ' + ERROR_MESSAGE() + 'Error severity: ' + CAST(ERROR_SEVERITY() AS varchar(10)) + \n 'Error state: ' + CAST(ERROR_STATE() AS varchar(10)) + 'XACT_STATE: ' + CAST(XACT_STATE() AS varchar(10)) \n\n--record the error in the database \n--debug \n --EXEC [dbo].[procUtils_DebugDb]\n -- @DomainUser = @domainUser,\n -- @debugmsg = @debugMsgOut,\n -- @ret = 1,\n -- @procedureName = @procedureName ,\n -- @procedureStep = @procStep\n\n -- set @ret = 1 \n\nEND CATCH \n\n\nreturn @ret \nEND --procedure end \n</code></pre>\n"
},
{
"answer_id": 1416897,
"author": "eduncan911",
"author_id": 56693,
"author_profile": "https://Stackoverflow.com/users/56693",
"pm_score": 0,
"selected": false,
"text": "<p>I see the delima overall - you have a single entity you must represent as a single instance (one ProductID of \"10\" for example), but have multiple localized text of different columns/properties. That is a tough one, and I do see the need for POS systems, that you only want to track that one ProductID = 10, not multiple products that have different ProductIDs, but are the same thing with just different text.</p>\n\n<p>I would lean towards the XML column solution you and others have outlined here already. Yes, it's more data transfering over the wire - but, it keeps things simple and can be filtered with XElement if packet site becomes an issue.</p>\n\n<p>The main drawback being the amount of data transfered over the wire from the DB to the service layer/UI/App. I would try to do some transformation on the SQL end before returning the result, to only return the one culture UI. You could always just SELECT the currect culsture via xml in an sproc, and return it as normal text as well.</p>\n\n<p>Overall, this is different then, say, a Blog Post or CMS need for localization - which I've done a few of.</p>\n\n<p>My approach to the Post scenerio would be similar to TToni's, with the exception of modelling the data from a the Domain's perspective (and a touch of BDD). With that said, focus on what you want to achieve:</p>\n\n<pre><code>Given a users culture is \"sv-se\"\nWhen the user views a post list\nIt should list posts only in \"sv-se\" culture\n</code></pre>\n\n<p>This means that the user should see a list of posts only for their culture. The way we implemented this before was to pass in a set of cultures to query for based on what the user could see. If the user has 'sv-se' set as their primary, but also has selected they speak US English (en-us), then the query would be:</p>\n\n<pre><code>SELECT * FROM Post WHERE CultureUI IN ('sv-se', 'en-us')\n</code></pre>\n\n<p>Notice how this gives you all posts and their different PostID, unique to that language. The PostID isn't as important here on blogs because each post is bound to a different language. If there are copies being transcribed, that works fine here too as each post is unique to that culture, and therefore gets a unique set of comments and such.</p>\n\n<p>But to go back to the 1st part of my answer, your need stems from the requirement of needing a single instance with multiple texts. An Xml column fits that fine.</p>\n"
},
{
"answer_id": 1492063,
"author": "NightOwl888",
"author_id": 181087,
"author_profile": "https://Stackoverflow.com/users/181087",
"pm_score": 0,
"selected": false,
"text": "<p>Another approach to consider: don't store content in the database, but keep \"application\" supporting database records and \"content\" as separate entities.</p>\n\n<p>I used an approach similar to this when creating multiple themes for my ecommerce website. Several of the products have a manufacturer logo which also must match the website theme. Since there is no real database support for themes, I had a problem. The solution I came up with was to use a token in the database to identify the ClientID of the image, rather than storing the URL of the image (which would vary based on theme).</p>\n\n<p>Following the same approach, you could change your database from storing the name and description of the product into storing a name token and a description token that would identify the resource (in an resx file or in the database using Rick Strahl's approach) that contains the content. The built-in functionality of .NET would then handle the switching of language rather than attempting to do it in the database (it is rarely a good idea to put business logic in the database). You could then use the token on the client to look up the correct resource.</p>\n\n<pre><code>Label1.Text = GetLocalResourceObject(\"TokenStoredInDatabase\").ToString()\n</code></pre>\n\n<p>The disadvantage to this approach is obviously keeping the database tokens and the resource tokens in sync (because products could be added without any descriptions), but could potentially be done easier using a resourceprovider such as the one Rick Strahl created. This approach may not work if you have products that change frequently, but for some people it might.</p>\n\n<p>The advantage is that you have a small amount of data to transfer to the client from the database, your content is cleanly separated from your database, and your database won't need to be more complex than it is now.</p>\n\n<p>On a side note, if you are running an e-Commerce store and actually want to get your localized pages indexed, you have to deviate a little from the seemingly natural way that Microsoft created. There is clearly disagreement between a practical and logical design flow and what <a href=\"http://googlewebmastercentral.blogspot.com/2008/08/how-to-start-multilingual-site.html\" rel=\"nofollow noreferrer\">Google recommends</a> for SEO. Indeed, some webmasters have complained that their pages weren't indexed by the search engines for anything but the \"default\" culture because the search engines only will index a single URL once even if it changes depending on the culture of the browser.</p>\n\n<p>Fortunately, there is a simple approach to get around this: put links on the page to translate it into the other languages based on a querystring parameter. An example of this can be found (oops, they won't let me post another link!!) and if you check, each culture of the page has been indexed by both Google and Yahoo (although not by Bing). A more advanced approach may use URL rewriting in combination with some fancy regular expressions to make your single localized page look like it has multiple directories, but actually pass a querystring parameter to the page instead.</p>\n"
},
{
"answer_id": 3418944,
"author": "Rei Miyasaka",
"author_id": 388626,
"author_profile": "https://Stackoverflow.com/users/388626",
"pm_score": 0,
"selected": false,
"text": "<p>Indexing becomes an issue. I don't think you can index xml, and of course, you can't index it if you store it as a string because every string will start with <code><localization> <text culture=\"...\"></code>.</p>\n"
},
{
"answer_id": 4130084,
"author": "Richard Bladh",
"author_id": 501401,
"author_profile": "https://Stackoverflow.com/users/501401",
"pm_score": 2,
"selected": false,
"text": "<p>Here is how I've done it.\nI don't use LINQ or SP for this one, because the query is too complex and is dynamically built and this is just a excerpt of the query.</p>\n\n<p>I have a products table:</p>\n\n<pre><code>* id\n* price\n* stocklevel\n* active\n* name\n* shortdescription\n* longdescription\n</code></pre>\n\n<p>and a products_globalization table:</p>\n\n<pre><code>* id\n* products_id\n* name\n* shortdescription\n* longdescription\n</code></pre>\n\n<p>As you can see the products-table contains all the globalization-columns aswell. These columns contains the default-language (thus, being able to skip doing a join when requesting the default culture - BUT I'm not sure if this is worth the trouble, I mean the join between the two tables are index-based so... - give me some feedback on this one).</p>\n\n<p>I prefer having a side-by-side table over a global-resourcetable because in certain situations you might need to do i.e. a database (MySQL) MATCH on a couple of columns, such as MATCH(name, shortdescription, longdescription) AGAINST ('Something here').</p>\n\n<p>In a normal scenario some of the product translations might be missing but I still want to show all products (not just the ones who are translated). So it's not enough to do to a join, we actually need to do a left join based on the products-table.</p>\n\n<p>Pseudo:</p>\n\n<pre><code>string query = \"\";\nif(string.IsNullOrEmpty(culture)) {\n // No culture specified, no join needed.\n query = \"SELECT p.price, p.name, p.shortdescription FROM products p WHERE p.price > ?Price\";\n} else {\n query = \"SELECT p.price, case when pg.name is null then p.name else pg.name end as 'name', case when pg.shortdescription is null then p.shortdescription else pg.shortdescription end as 'shortdescription' FROM products p\"\n + \" LEFT JOIN products_globalization pg ON pg.products_id = p.id AND pg.culture = ?Culture\"\n + \" WHERE p.price > ?Price\";\n}\n</code></pre>\n\n<p>I would go with COALESCE instead of CASE ELSE but thats besides the point.</p>\n\n<p>Well, thats my take on it. Feel free to critize my suggestion...</p>\n\n<p>Kind regards,\nRichard</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25319/"
] |
Question
--------
I'm sure many of you have been faced by the challenge of localizing a database backend to an application. If you've not then I'd be pretty confident in saying that the odds of you having to do so in the future is quite large. I'm talking anout storing multiple translations of texts (and the same can be said for currency etc.) for your database entities.
For example the classic "Category" table might have a Name and a Description column which should be globalized. One way would be to do have a "Text" table for each of your entities and then do a join to retreive the values based on the provided language.
This leaves you with a lot of "Text" tables, one for each entity which you want to localize, with the addition of a TextType to distinguish between the various texts that it may store.
I'm curious if there are any, documented, best-practises / design patterns on implementing this kind of support into a SQL Server 2005/2008 datebase (I'm being specific about the RDBMS since it might contain supported keywords and such which helps with the implementation)?
Thoughts on XML approach
------------------------
One idea I have been toying with (albeit only in my head so far) was to leverage the XML datatype introduced in SQL Server 2005. The idea was to make columns which should support localization, of the XML datatype (and bind a schema to it). The XML would contain the localized strings along with the language code / culture it was tied to.
Something along the lines of
```
Product
ID (int, identity)
Name (XML ...)
Description (XML ...)
```
Then you would have something like this as the XML
```
<localization>
<text culture="sv-SE">Detta är ett namn</text>
<text culture="en-EN">This is a name</text>
</localization>
```
You could then do (This isn't production code so I'll use the \*)
```
SELECT *
From Product
Where Product.ID = 10
```
And you would get back the product with all localized texts which would mean you would have to do the extraction on the client-side. The biggest problem here is obviously the amount of extra data that you would have to return on each query, The benefits would be a cleaner design with no look-up tables, joins and so on.
Btw, what ever method I do end up using in my design I will still be using Linq To SQL (.NET Platform) to query the database (the XML approach should be a problem since it would return an XElement which could be interpreted client-side)
So suggestion on database localization design patterns, and possibly comments on the XML thought, would be very apprechiated.
|
I think you can stick with XML which allows for a cleaner design. I would go further and take advantage of the `xml:lang` attribute which [is designed for this usage](http://www.opentag.com/xfaq_lang.htm) :
```
<l10n>
<text xml:lang="sv-SE">Detta är ett namn</text>
<text xml:lang="en-EN">This is a name</text>
</l10n>
```
One step further, you could select the localized resource in your query via [a XPath query](http://msdn.microsoft.com/en-us/library/ms345117(SQL.90).aspx) (as suggested in the comments) to avoid any client side treatment. This would give something like this (untested) :
```
SELECT Name.value('(l10n/text[lang()="en"])[1]', 'NVARCHAR(MAX)')
FROM Product
WHERE Product.ID=10;
```
Note that this solution would be an elegant but less efficient solution than the separate table one. Which may be OK for some application.
|
258,486 |
<p>How to calculate the length (in pixels) of a string in Java?</p>
<p>Preferable without using Swing.</p>
<p>EDIT:
I would like to draw the string using the drawString() in Java2D
and use the length for word wrapping.</p>
|
[
{
"answer_id": 258499,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": true,
"text": "<p>If you just want to use AWT, then use <a href=\"http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics.html#getFontMetrics()\" rel=\"noreferrer\"><code>Graphics.getFontMetrics</code></a> (optionally specifying the font, for a non-default one) to get a <code>FontMetrics</code> and then <a href=\"http://docs.oracle.com/javase/6/docs/api/java/awt/FontMetrics.html#stringWidth(java.lang.String)\" rel=\"noreferrer\"><code>FontMetrics.stringWidth</code></a> to find the width for the specified string.</p>\n\n<p>For example, if you have a <code>Graphics</code> variable called <code>g</code>, you'd use:</p>\n\n<pre><code>int width = g.getFontMetrics().stringWidth(text);\n</code></pre>\n\n<p>For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.</p>\n"
},
{
"answer_id": 14832962,
"author": "Olofu Mark",
"author_id": 2055028,
"author_profile": "https://Stackoverflow.com/users/2055028",
"pm_score": 6,
"selected": false,
"text": "<p>It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.</p>\n\n<p>I have tested this in a web servlet and it does calculate the text width.</p>\n\n<pre><code>import java.awt.Font;\nimport java.awt.font.FontRenderContext;\nimport java.awt.geom.AffineTransform;\n\n...\n\nString text = \"Hello World\";\nAffineTransform affinetransform = new AffineTransform(); \nFontRenderContext frc = new FontRenderContext(affinetransform,true,true); \nFont font = new Font(\"Tahoma\", Font.PLAIN, 12);\nint textwidth = (int)(font.getStringBounds(text, frc).getWidth());\nint textheight = (int)(font.getStringBounds(text, frc).getHeight());\n</code></pre>\n\n<hr>\n\n<p>Add the necessary values to these dimensions to create any required margin.</p>\n"
},
{
"answer_id": 18450804,
"author": "Ed Poor",
"author_id": 487839,
"author_profile": "https://Stackoverflow.com/users/487839",
"pm_score": 3,
"selected": false,
"text": "<p>Use the getWidth method in the following class:</p>\n\n<pre><code>import java.awt.*;\nimport java.awt.geom.*;\nimport java.awt.font.*;\n\nclass StringMetrics {\n\n Font font;\n FontRenderContext context;\n\n public StringMetrics(Graphics2D g2) {\n\n font = g2.getFont();\n context = g2.getFontRenderContext();\n }\n\n Rectangle2D getBounds(String message) {\n\n return font.getStringBounds(message, context);\n }\n\n double getWidth(String message) {\n\n Rectangle2D bounds = getBounds(message);\n return bounds.getWidth();\n }\n\n double getHeight(String message) {\n\n Rectangle2D bounds = getBounds(message);\n return bounds.getHeight();\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 44180263,
"author": "wmioduszewski",
"author_id": 2395747,
"author_profile": "https://Stackoverflow.com/users/2395747",
"pm_score": 1,
"selected": false,
"text": "<p>I personally was searching for something to let me compute the multiline string area, so I could determine if given area is big enough to print the string - with preserving specific font.</p>\n<pre><code>private static Hashtable hash = new Hashtable();\nprivate Font font;\nprivate LineBreakMeasurer lineBreakMeasurer;\nprivate int start, end;\n\npublic PixelLengthCheck(Font font) {\n this.font = font;\n}\n\npublic boolean tryIfStringFits(String textToMeasure, Dimension areaToFit) {\n AttributedString attributedString = new AttributedString(textToMeasure, hash);\n attributedString.addAttribute(TextAttribute.FONT, font);\n AttributedCharacterIterator attributedCharacterIterator =\n attributedString.getIterator();\n start = attributedCharacterIterator.getBeginIndex();\n end = attributedCharacterIterator.getEndIndex();\n\n lineBreakMeasurer = new LineBreakMeasurer(attributedCharacterIterator,\n new FontRenderContext(null, false, false));\n\n float width = (float) areaToFit.width;\n float height = 0;\n lineBreakMeasurer.setPosition(start);\n\n while (lineBreakMeasurer.getPosition() < end) {\n TextLayout textLayout = lineBreakMeasurer.nextLayout(width);\n height += textLayout.getAscent();\n height += textLayout.getDescent() + textLayout.getLeading();\n }\n\n boolean res = height <= areaToFit.getHeight();\n\n return res;\n}\n</code></pre>\n"
},
{
"answer_id": 60643245,
"author": "John Henckel",
"author_id": 1812732,
"author_profile": "https://Stackoverflow.com/users/1812732",
"pm_score": 2,
"selected": false,
"text": "<p>And now for something <em>completely</em> different. The following assumes arial font, and makes a wild guess based on a linear interpolation of character vs width.</p>\n\n<pre><code>// Returns the size in PICA of the string, given space is 200 and 'W' is 1000.\n// see https://p2p.wrox.com/access/32197-calculate-character-widths.html\n\nstatic int picaSize(String s)\n{\n // the following characters are sorted by width in Arial font\n String lookup = \" .:,;'^`!|jl/\\\\i-()JfIt[]?{}sr*a\\\"ce_gFzLxkP+0123456789<=>~qvy$SbduEphonTBCXY#VRKZN%GUAHD@OQ&wmMW\";\n int result = 0;\n for (int i = 0; i < s.length(); ++i)\n {\n int c = lookup.indexOf(s.charAt(i));\n result += (c < 0 ? 60 : c) * 7 + 200;\n }\n return result;\n}\n</code></pre>\n\n<p>Interesting, but perhaps not very practical.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26567/"
] |
How to calculate the length (in pixels) of a string in Java?
Preferable without using Swing.
EDIT:
I would like to draw the string using the drawString() in Java2D
and use the length for word wrapping.
|
If you just want to use AWT, then use [`Graphics.getFontMetrics`](http://docs.oracle.com/javase/6/docs/api/java/awt/Graphics.html#getFontMetrics()) (optionally specifying the font, for a non-default one) to get a `FontMetrics` and then [`FontMetrics.stringWidth`](http://docs.oracle.com/javase/6/docs/api/java/awt/FontMetrics.html#stringWidth(java.lang.String)) to find the width for the specified string.
For example, if you have a `Graphics` variable called `g`, you'd use:
```
int width = g.getFontMetrics().stringWidth(text);
```
For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.
|
258,529 |
<p>Here's an interface:</p>
<pre><code>public interface Foo<T> extends Comparable<Foo<T>> {
...
}
</code></pre>
<p>And there are some classes implementing this interface:</p>
<pre><code>public class Bar extends Something implements Foo<Something> {
public Vector<Foo<Bar>> giveBar() {
...
}
}
public class Boo extends SomethingElse implements Foo<SomethingElse> {
public Vector<Foo<Boo>> giveBoo() {
...
}
}
</code></pre>
<p>Now I want to keep a bunch of Foos (that may really be Foos or Boos) inside a vector. </p>
<pre><code>Bar bar = new Bar();
Boo boo = new Boo();
Vector<Foo<?>> vector;
if (...)
vector = bar.giveBar();
else
vector = boo.giveBoo();
</code></pre>
<p>I get:</p>
<pre><code>Type mismatch: cannot convert from Vector<Foo<SomethingElse>> to Vector<Foo<?>>
</code></pre>
<p>The same goes for:</p>
<pre><code>Vector<Foo> vector;
if (...)
vector = giveBar();
else
vector = giveBoo();
</code></pre>
<p>Is a superclass that both Bar and Boo extend the only solution to this problem?</p>
|
[
{
"answer_id": 258623,
"author": "Marcus Downing",
"author_id": 1000,
"author_profile": "https://Stackoverflow.com/users/1000",
"pm_score": 4,
"selected": true,
"text": "<p>What all that code boils down to is:</p>\n\n<pre><code>Vector<A> vector = new Vector<B>();\n</code></pre>\n\n<p>In this case B extends A, but that's not allowed because the types don't match. To make clear why this doesn't work, imagine the following code:</p>\n\n<pre><code>Vector<Vector<?>> vector = new Vector<Vector<String>>();\nvector.add(new Vector<Integer>());\n</code></pre>\n\n<p>The variable's type is of a <em>vector of vectors of unknown type</em>; and what's being assigned to it is a <em>vector of vectors of strings</em>. The second line adds a <em>vector of integers</em> to that. The component type of the variable <code>Vector<?></code>, which accepts <code>Vector<Integer></code>; but the actual vector's component type is <code>Vector<String></code>, which doesn't. If the compiler didn't object to the assignment on the first line, it would allow you to write the incorrect second line without being spotted.</p>\n\n<p>C#'s generics have a similar restriction, but the difference is that a generic class in C# stores it component type, while Java forgets component types when the code is compiled.</p>\n\n<p>ps - Why on earth are you using <code>Vector</code> rather than <code>LinkedList</code> or <code>ArrayList</code>? Is it because there are threading issues involved?</p>\n"
},
{
"answer_id": 258633,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 2,
"selected": false,
"text": "<p>You can use</p>\n\n<pre><code>Vector<? extends Foo<?>> vector;\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258529",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Here's an interface:
```
public interface Foo<T> extends Comparable<Foo<T>> {
...
}
```
And there are some classes implementing this interface:
```
public class Bar extends Something implements Foo<Something> {
public Vector<Foo<Bar>> giveBar() {
...
}
}
public class Boo extends SomethingElse implements Foo<SomethingElse> {
public Vector<Foo<Boo>> giveBoo() {
...
}
}
```
Now I want to keep a bunch of Foos (that may really be Foos or Boos) inside a vector.
```
Bar bar = new Bar();
Boo boo = new Boo();
Vector<Foo<?>> vector;
if (...)
vector = bar.giveBar();
else
vector = boo.giveBoo();
```
I get:
```
Type mismatch: cannot convert from Vector<Foo<SomethingElse>> to Vector<Foo<?>>
```
The same goes for:
```
Vector<Foo> vector;
if (...)
vector = giveBar();
else
vector = giveBoo();
```
Is a superclass that both Bar and Boo extend the only solution to this problem?
|
What all that code boils down to is:
```
Vector<A> vector = new Vector<B>();
```
In this case B extends A, but that's not allowed because the types don't match. To make clear why this doesn't work, imagine the following code:
```
Vector<Vector<?>> vector = new Vector<Vector<String>>();
vector.add(new Vector<Integer>());
```
The variable's type is of a *vector of vectors of unknown type*; and what's being assigned to it is a *vector of vectors of strings*. The second line adds a *vector of integers* to that. The component type of the variable `Vector<?>`, which accepts `Vector<Integer>`; but the actual vector's component type is `Vector<String>`, which doesn't. If the compiler didn't object to the assignment on the first line, it would allow you to write the incorrect second line without being spotted.
C#'s generics have a similar restriction, but the difference is that a generic class in C# stores it component type, while Java forgets component types when the code is compiled.
ps - Why on earth are you using `Vector` rather than `LinkedList` or `ArrayList`? Is it because there are threading issues involved?
|
258,556 |
<p>I am using the <code>OpenArgs</code> parameter to send a value when using <code>DoCmd.OpenForm</code>:</p>
<pre><code>DoCmd.OpenForm "frmSetOther", acNormal, , , acFormAdd, acDialog, "value"
</code></pre>
<p>I then use <code>Me.OpenArgs</code> inside the opened form to grab the <strong><em>value</em></strong>. It sometimes sends a <strong>Null</strong> value instead of the original string. What is wrong?</p>
|
[
{
"answer_id": 258570,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<p>Is the value taken from a user completed control? Do you ensure that the focus is moved from the control before you run the openform line? </p>\n\n<p>EDIT: The value property of the control will be equal to the previous value, which may be null, unless you do this.</p>\n"
},
{
"answer_id": 258582,
"author": "lamcro",
"author_id": 15884,
"author_profile": "https://Stackoverflow.com/users/15884",
"pm_score": 0,
"selected": false,
"text": "<p>I think I found the answer to my problem:</p>\n\n<blockquote>\n <p>In my experience, OpenArgs has to be handled immediately upon opening of the form. <a href=\"http://www.dbforums.com/archive/index.php/t-1620380.html\" rel=\"nofollow noreferrer\">(link)</a></p>\n</blockquote>\n\n<p>I checked this by putting a break before attempting to use the OpenArgs value, and it was null. But when I remove the break, the program shows no error. This must only happen while developing.</p>\n"
},
{
"answer_id": 258779,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 3,
"selected": true,
"text": "<p>A very interesting alternative to this \"openArgs\" argument is to use the .properties collection of the currentProject.allforms(\"myFormName\") object. When you need to pass a value to a form (such as a filter inherited from another control or another form, for example), just add the corresponding property for your form, and add your value to this property. </p>\n\n<p>Example:</p>\n\n<pre><code>addPropertyToForm \"formFilter\",\"Tbl_myTable.myField LIKE 'A*'\",myFormName\n</code></pre>\n\n<p>The called function will try to update the value of the \"formFilter\" property of the object. If the property does not exist (err 2455 is raised), it will be added as a new property in the error management code.</p>\n\n<pre><code>Function addPropertyToForm(_ \n x_propertyName as string, _\n x_value As Variant, _\n x_formName As String) \nAs Boolean\n\nOn Error GoTo errManager\nCurrentProject.AllForms(x_formName).Properties(x_propertyName).Value = x_value\naddPropertyToForm = True\nOn Error GoTo 0\n\nExit Function\n\nerrManager:\nIf Err.Number = 2455 Then\n CurrentProject.AllForms(x_formName).Properties.Add x_propertyName, Nz(x_value)\n Resume Next\nElse\n msgbox err.number & \". The property \" & x_propertyName & \"was not created\"\nEnd If\n\nEnd Function \n</code></pre>\n"
},
{
"answer_id": 258986,
"author": "Mathieu Pagé",
"author_id": 5861,
"author_profile": "https://Stackoverflow.com/users/5861",
"pm_score": 5,
"selected": false,
"text": "<p>This often happens during developpment whem the form is already oppened (in edit mode for example) and you invoke the docmd.OpenForm function. In this case, the form is placed in normal (view) mode and the OnOpen and OnLoad events are raised, but the OpenArgs property is set to null no mater what you passed to docmd.OpenForm.</p>\n\n<p>The solution is obviously to close the form before you invoke it with docmd.OpenForm. However there is a workaround I like to use. In the OnOpen event I check if me.OpenArgs is null and if it is I replace it with some debug values.</p>\n\n<pre><code>if not isnull(me.OpenArgs) then\n myvalue = me.OpenArgs\nelse\n msgbox \"Debug mode\"\n myValue = \"foo\"\nendif\n</code></pre>\n"
},
{
"answer_id": 814293,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Answer here. your form may be already open, even in Design mode:\n<a href=\"http://www.tech-archive.net/Archive/Access/microsoft.public.access.formscoding/2007-02/msg00928.html\" rel=\"nofollow noreferrer\">http://www.tech-archive.net/Archive/Access/microsoft.public.access.formscoding/2007-02/msg00928.html</a></p>\n"
},
{
"answer_id": 12879186,
"author": "George Elam",
"author_id": 1744325,
"author_profile": "https://Stackoverflow.com/users/1744325",
"pm_score": 3,
"selected": false,
"text": "<p>I just had this problem. The <code>Arg</code> string did not get passed, because the report was already open, but not visible. It had been left open when the code crashed with the <code>Null string error</code>.</p>\n\n<p>The solution was to close the report in the immediate window, with </p>\n\n<pre><code>Docmd.Close acReport, \"myReport\"\n</code></pre>\n\n<p>It fixed my bug and the args were passed properly.</p>\n"
},
{
"answer_id": 46089882,
"author": "Henrik Erlandsson",
"author_id": 343825,
"author_profile": "https://Stackoverflow.com/users/343825",
"pm_score": 1,
"selected": false,
"text": "<p>It could be that you had your form open already (as suggested), but just check for null and the form will handle opening with missing arguments as well.</p>\n\n<p>This will allow opening the form for a quick peek (by you or the users) if the arguments aren't vital.</p>\n\n<pre><code>Private Sub Form_Open(Cancel As Integer)\n If Not IsNull(Me.OpenArgs) Then\n Me.lblHeading.Caption = Me.OpenArgs\n End If\nEnd Sub\n</code></pre>\n\n<p>A null value can be passed to OpenArgs by omitting the value in the OpenForm call, or by double-clicking the form in the Access Objects sidebar.</p>\n\n<hr>\n\n<p>If it's a <a href=\"https://msdn.microsoft.com/en-us/vba/access-vba/articles/form-modal-property-access\" rel=\"nofollow noreferrer\">modal</a> form, you should explicitly check if it's open and close it before opening it if so. This is a common gotcha. </p>\n\n<p>The same could of course be done for all forms, not just modal ones, and then you wouldn't need the null check (provided you never pass null to it). But often there are a lot of forms in a project, and even more OpenForm calls than forms...</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15884/"
] |
I am using the `OpenArgs` parameter to send a value when using `DoCmd.OpenForm`:
```
DoCmd.OpenForm "frmSetOther", acNormal, , , acFormAdd, acDialog, "value"
```
I then use `Me.OpenArgs` inside the opened form to grab the ***value***. It sometimes sends a **Null** value instead of the original string. What is wrong?
|
A very interesting alternative to this "openArgs" argument is to use the .properties collection of the currentProject.allforms("myFormName") object. When you need to pass a value to a form (such as a filter inherited from another control or another form, for example), just add the corresponding property for your form, and add your value to this property.
Example:
```
addPropertyToForm "formFilter","Tbl_myTable.myField LIKE 'A*'",myFormName
```
The called function will try to update the value of the "formFilter" property of the object. If the property does not exist (err 2455 is raised), it will be added as a new property in the error management code.
```
Function addPropertyToForm(_
x_propertyName as string, _
x_value As Variant, _
x_formName As String)
As Boolean
On Error GoTo errManager
CurrentProject.AllForms(x_formName).Properties(x_propertyName).Value = x_value
addPropertyToForm = True
On Error GoTo 0
Exit Function
errManager:
If Err.Number = 2455 Then
CurrentProject.AllForms(x_formName).Properties.Add x_propertyName, Nz(x_value)
Resume Next
Else
msgbox err.number & ". The property " & x_propertyName & "was not created"
End If
End Function
```
|
258,590 |
<p>I have an SVN repository structure like below. We are using multiple levels under branches for various release maintenance branches, plus a directory for feature branches.</p>
<p>git-svn init seems to work with a single --branches argument, i.e. it seems to expect all of the branches to be in a single location.</p>
<pre><code>trunk
branches
1.1
1.2.1
1.2.2
1.2
1.2.1
1.2.2
1.2.3
features
feature1
feature2
</code></pre>
<p>Any ideas on how to handle this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 258604,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<p>Would it be feasible to create a <code>git</code> repo for each of the branch subdirectories?</p>\n"
},
{
"answer_id": 258659,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 1,
"selected": false,
"text": "<p>By convention, Subversion branches all live in a single 'branches' path in the Subversion repository, so I'm not surprised that <code>git-svn</code> makes this assumption.</p>\n\n<p>I'd suggest the following (note, you may lose some history in this operation):</p>\n\n<ol>\n<li>Flatten the Subversion <code>branches</code> paths, using a naming convention to keep unique identities and the idea of the current structure.</li>\n<li>Perform <code>git-svn</code></li>\n<li>Move things around in the <code>git</code> repository to conform with your practices.</li>\n</ol>\n\n<p>The danger of <code>losing history</code> depends on how well <code>git-svn</code> follows copy operations from dissimilar paths. I've run into this problem migrating subversion repositories (1.4-ish) recently.</p>\n"
},
{
"answer_id": 267217,
"author": "Peter Burns",
"author_id": 101,
"author_profile": "https://Stackoverflow.com/users/101",
"pm_score": 0,
"selected": false,
"text": "<p>You could add multiple <code>git svn</code> remotes for each of the branches, or possibly each of the directories of branches. The initial <code>git svn fetch</code> would take forever, but from what I understand it should work.</p>\n"
},
{
"answer_id": 630684,
"author": "Greg",
"author_id": 42882,
"author_profile": "https://Stackoverflow.com/users/42882",
"pm_score": 5,
"selected": true,
"text": "<p>In your config file, set the svn-remotes section to something like:</p>\n\n<pre><code>[svn-remote \"svn\"]\n url = svn://svnserver/repo\n fetch = trunk:refs/remotes/trunk\n branches = branches/*/*:refs/remotes/*\n tags = tags/*:refs/remotes/tags/*\n</code></pre>\n\n<p>This should let you grab the nested branches.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15203/"
] |
I have an SVN repository structure like below. We are using multiple levels under branches for various release maintenance branches, plus a directory for feature branches.
git-svn init seems to work with a single --branches argument, i.e. it seems to expect all of the branches to be in a single location.
```
trunk
branches
1.1
1.2.1
1.2.2
1.2
1.2.1
1.2.2
1.2.3
features
feature1
feature2
```
Any ideas on how to handle this?
Thanks
|
In your config file, set the svn-remotes section to something like:
```
[svn-remote "svn"]
url = svn://svnserver/repo
fetch = trunk:refs/remotes/trunk
branches = branches/*/*:refs/remotes/*
tags = tags/*:refs/remotes/tags/*
```
This should let you grab the nested branches.
|
258,655 |
<p>Anyone know how to detect if a television is currently connected to a PC in c#?</p>
<p>Cheers</p>
|
[
{
"answer_id": 258697,
"author": "Kristian",
"author_id": 23246,
"author_profile": "https://Stackoverflow.com/users/23246",
"pm_score": 3,
"selected": false,
"text": "<p>How is the device attached?</p>\n\n<p>Whenever a device arrival/removal happens, Windows sends a message called WM_DEVICECHANGE to all the applications running currently in the system. But to receive this message our application should handle the \"Windows Process function\". C# applications will not have default support for this function, but it's possible to add it. You could extend the form class.</p>\n\n<p>The code to do this for a usb mass storage device would be something like:</p>\n\n<pre><code>using System;\nusing System.Drawing;\nusing System.Collections;\nusing System.ComponentModel;\nusing System.Windows.Forms;\nusing System.Data;\nusing System.Runtime.InteropServices;\nnamespace WindowsApplication\n{\n /// <summary>\n /// Summary description for Form1.\n /// </summary>\n public class Form1 : System.Windows.Forms.Form\n {\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.Container components = null;\n\n public Form1()\n {\n //\n // Required for Windows Form Designer support\n //\n InitializeComponent();\n\n //\n // TODO: Add any constructor code after InitializeComponent call\n //\n }\n\n [StructLayout(LayoutKind.Sequential)] \n public struct DEV_BROADCAST_VOLUME \n { \n public int dbcv_size; \n public int dbcv_devicetype; \n public int dbcv_reserved; \n public int dbcv_unitmask; \n } \n\n protected override void WndProc(ref Message m) \n { \n //you may find these definitions in dbt.h and winuser.h \n const int WM_DEVICECHANGE = 0x0219; \n const int DBT_DEVICEARRIVAL = 0x8000; // system detected a new device \n const int DBT_DEVICEREMOVECOMPLETE = 0x8001; // system detected a new device \n const int DBT_DEVTYP_VOLUME = 0x00000002; // logical volume \n switch(m.Msg)\n {\n case WM_DEVICECHANGE:\n switch(m.WParam.ToInt32())\n {\n case DBT_DEVICEARRIVAL:\n { \n int devType = Marshal.ReadInt32(m.LParam,4); \n if(devType == DBT_DEVTYP_VOLUME) \n { \n DEV_BROADCAST_VOLUME vol; \n vol = (DEV_BROADCAST_VOLUME) \n Marshal.PtrToStructure(m.LParam,typeof(DEV_BROADCAST_VOLUME)); \n MessageBox.Show(vol.dbcv_unitmask.ToString(\"x\")); \n } \n } \n break;\n case DBT_DEVICEREMOVECOMPLETE:\n MessageBox.Show(\"Removal\");\n break;\n }\n\n break;\n }\n //we detect the media arrival event \n base.WndProc (ref m); \n\n\n } \n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n protected override void Dispose( bool disposing )\n {\n if( disposing )\n {\n if (components != null) \n {\n components.Dispose();\n }\n }\n base.Dispose( disposing );\n }\n\n\n #region Windows Form Designer generated code\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n // \n // Form1\n // \n this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);\n this.ClientSize = new System.Drawing.Size(292, 273);\n this.Name = \"Form1\";\n this.Text = \"Form1\";\n this.Load += new System.EventHandler(this.Form1_Load);\n\n }\n #endregion\n\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main() \n {\n Application.Run(new Form1());\n }\n\n private void Form1_Load(object sender, System.EventArgs e)\n {\n\n }\n }\n}\n</code></pre>\n\n<p>It might give you an idea how to implement it.</p>\n"
},
{
"answer_id": 258699,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>I suppose you are talking about monitors/TV's ?</p>\n\n<p>You can make a winform application with a big button saying 'TV CONNECTED' when the user switches to the TV :-)</p>\n\n<p>If the only connection to the PC is just the VGA connector, you are out of luck. You could always implement an infrared sensor connected to a serial port to read infrared signals from the remote control (whenever the user clicks it).</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33647/"
] |
Anyone know how to detect if a television is currently connected to a PC in c#?
Cheers
|
How is the device attached?
Whenever a device arrival/removal happens, Windows sends a message called WM\_DEVICECHANGE to all the applications running currently in the system. But to receive this message our application should handle the "Windows Process function". C# applications will not have default support for this function, but it's possible to add it. You could extend the form class.
The code to do this for a usb mass storage device would be something like:
```
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;
namespace WindowsApplication
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
[StructLayout(LayoutKind.Sequential)]
public struct DEV_BROADCAST_VOLUME
{
public int dbcv_size;
public int dbcv_devicetype;
public int dbcv_reserved;
public int dbcv_unitmask;
}
protected override void WndProc(ref Message m)
{
//you may find these definitions in dbt.h and winuser.h
const int WM_DEVICECHANGE = 0x0219;
const int DBT_DEVICEARRIVAL = 0x8000; // system detected a new device
const int DBT_DEVICEREMOVECOMPLETE = 0x8001; // system detected a new device
const int DBT_DEVTYP_VOLUME = 0x00000002; // logical volume
switch(m.Msg)
{
case WM_DEVICECHANGE:
switch(m.WParam.ToInt32())
{
case DBT_DEVICEARRIVAL:
{
int devType = Marshal.ReadInt32(m.LParam,4);
if(devType == DBT_DEVTYP_VOLUME)
{
DEV_BROADCAST_VOLUME vol;
vol = (DEV_BROADCAST_VOLUME)
Marshal.PtrToStructure(m.LParam,typeof(DEV_BROADCAST_VOLUME));
MessageBox.Show(vol.dbcv_unitmask.ToString("x"));
}
}
break;
case DBT_DEVICEREMOVECOMPLETE:
MessageBox.Show("Removal");
break;
}
break;
}
//we detect the media arrival event
base.WndProc (ref m);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
}
}
}
```
It might give you an idea how to implement it.
|
258,661 |
<p>I have a GridView defined like this:</p>
<pre><code><asp:GridView ID="myGridView" ruant="server">
<asp:BoundField DataField="myField" />
<asp:CommandField ShowDeleteButton="true" ShowEditButton="true" />
</asp:GridView>
</code></pre>
<p>After I put a row into edit mode with the Edit button, how do I capture the Enter key and trigger the resulting Update on the row? Right now if I hit enter, the page reloads, what was entered into the TextBox is lost, and the row stays in edit mode. I know how to <a href="https://stackoverflow.com/questions/152099/i-want-to-prevent-aspnet-gridview-from-reacting-to-the-enter-button">disable the enter key entirely</a> on the form (the current workaround), but I'd like to have it fire the Update command.</p>
|
[
{
"answer_id": 258669,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "<p>Well, using the knowledge from the question you linked, it's simple:</p>\n\n<pre><code>string js = \"if (event.keyCode == 13) this.form.submit();\"\nmyGridView.Attributes.Add(\"onkeydown\", js);\n</code></pre>\n\n<p>As we found out in the comments, this introduces a small problem. The <code>GridView_RowUpdating</code> server event does not fire anymore, but the question author relies on it.</p>\n\n<p>In short - the server event model relies on the form field <code>__EVENTTARGET</code> to be set. This form field is not sent when just calling the <code>form.submit()</code>. A solution would be to \"click\" the relevant button with JavaScript.</p>\n\n<pre><code>string js = \"if ((event.which && event.which == 13) || \" \n + \"(event.keyCode && event.keyCode == 13)) \"\n + \"{document.myForm.Update.click();return false;} \"\n + \"else return true;\";\nmyGridView.Attributes.Add(\"onkeydown\", js);\n</code></pre>\n\n<p>See <a href=\"http://www.allasp.net/enterkey.aspx\" rel=\"nofollow noreferrer\">\"Using the enter key to submit a form\"</a> on AllAsp.net, which covers the issue in more detail.</p>\n"
},
{
"answer_id": 906430,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Set \"UseSubmitBehavior\" property of buttons on the page to \"False\" (default is True)\nsolves the submit issue in several comments.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258661",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
I have a GridView defined like this:
```
<asp:GridView ID="myGridView" ruant="server">
<asp:BoundField DataField="myField" />
<asp:CommandField ShowDeleteButton="true" ShowEditButton="true" />
</asp:GridView>
```
After I put a row into edit mode with the Edit button, how do I capture the Enter key and trigger the resulting Update on the row? Right now if I hit enter, the page reloads, what was entered into the TextBox is lost, and the row stays in edit mode. I know how to [disable the enter key entirely](https://stackoverflow.com/questions/152099/i-want-to-prevent-aspnet-gridview-from-reacting-to-the-enter-button) on the form (the current workaround), but I'd like to have it fire the Update command.
|
Well, using the knowledge from the question you linked, it's simple:
```
string js = "if (event.keyCode == 13) this.form.submit();"
myGridView.Attributes.Add("onkeydown", js);
```
As we found out in the comments, this introduces a small problem. The `GridView_RowUpdating` server event does not fire anymore, but the question author relies on it.
In short - the server event model relies on the form field `__EVENTTARGET` to be set. This form field is not sent when just calling the `form.submit()`. A solution would be to "click" the relevant button with JavaScript.
```
string js = "if ((event.which && event.which == 13) || "
+ "(event.keyCode && event.keyCode == 13)) "
+ "{document.myForm.Update.click();return false;} "
+ "else return true;";
myGridView.Attributes.Add("onkeydown", js);
```
See ["Using the enter key to submit a form"](http://www.allasp.net/enterkey.aspx) on AllAsp.net, which covers the issue in more detail.
|
258,668 |
<p>In GWT, what is the best way to convert a JavaScriptObject overlay type into a JSON string?</p>
<p>I currently have</p>
<pre><code>public final String toJSON() {
return new JSONObject(this).toString();
}
</code></pre>
<p>Which seems to work fine. I would like to know if there are any better approaches.</p>
|
[
{
"answer_id": 332195,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 3,
"selected": true,
"text": "<p>I've never actually tried that (only consumed JSON so far, never needed to produce it). This seems to be native browser/javascript functionality.</p>\n\n<p>You <em>could</em> write it as:</p>\n\n<pre><code>public native String toJSON() /*-{\n return this.toString();\n}-*/;\n</code></pre>\n\n<p>They essentially just do the exact same thing and likely result in identical JavaScript output. The optimizing compiler is really amazing.</p>\n"
},
{
"answer_id": 7109319,
"author": "Nick Franceschina",
"author_id": 130221,
"author_profile": "https://Stackoverflow.com/users/130221",
"pm_score": 2,
"selected": false,
"text": "<p>we have a JSNI method like that, but use douglas crockfords JSON library (in case the browser doesn't supply one natively):</p>\n\n<p><a href=\"https://github.com/douglascrockford/JSON-js\" rel=\"nofollow\">https://github.com/douglascrockford/JSON-js</a></p>\n\n<pre><code>public native String stringify() /*-{\n return JSON.stringify();\n}-*/;\n</code></pre>\n\n<p>whats nice is that stringify can take parameters to pretty-print the output with a specified indentation... among other things</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32320/"
] |
In GWT, what is the best way to convert a JavaScriptObject overlay type into a JSON string?
I currently have
```
public final String toJSON() {
return new JSONObject(this).toString();
}
```
Which seems to work fine. I would like to know if there are any better approaches.
|
I've never actually tried that (only consumed JSON so far, never needed to produce it). This seems to be native browser/javascript functionality.
You *could* write it as:
```
public native String toJSON() /*-{
return this.toString();
}-*/;
```
They essentially just do the exact same thing and likely result in identical JavaScript output. The optimizing compiler is really amazing.
|
258,680 |
<p>Is there a possible htaccess directive that can transparently forward request from index.php to index_internal.php if the request is coming from an internal ip range?</p>
|
[
{
"answer_id": 258704,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 1,
"selected": false,
"text": "<p>Something like this should do it (obviously change the IP address to match your network):</p>\n\n<pre><code>RewriteCond %{REMOTE_ADDR} ^192\\.168\\.\nRewriteRule index.php index_internal.php\n</code></pre>\n\n<p>If you want an actual header then make it <code>RewriteRule index.php index_internal.php [L,R,QSA]</code></p>\n"
},
{
"answer_id": 258717,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 3,
"selected": true,
"text": "<pre><code>RewriteEngine on\n\nRewriteCond %{REMOTE_ADDR} ^192\\.168\\.1\\. [OR]\nRewriteCond %{REMOTE_ADDR} ^10\\.15\\.\nRewriteRule ^index\\.php$ index_internal.php [R,NC,QSA,L]\n</code></pre>\n\n<p>What this does: </p>\n\n<p>start mod_rewrite engine (you may have that already)</p>\n\n<p>if (client IP address starts with \"192.168.1.\" [or]</p>\n\n<p>client IP address starts with \"10.15.\") </p>\n\n<p>and page name is index.php ([n]ot [c]ase sensitive), [r]edirect to index_internal.php, [q]uery [s]tring [a]ppend (i.e. <code>index.php?foo=bar</code> becomes <code>index_internal.php?foo=bar</code>), [l]eave processing.</p>\n\n<p>Modify as needed for IP address blocks.</p>\n"
},
{
"answer_id": 258741,
"author": "ken",
"author_id": 20300,
"author_profile": "https://Stackoverflow.com/users/20300",
"pm_score": 1,
"selected": false,
"text": "<p>ok here's my code (no redirect) based on <a href=\"http://en.wikipedia.org/wiki/Private_network\" rel=\"nofollow noreferrer\">wikipedia's private network list</a></p>\n\n<pre><code>RewriteEngine on\nRewriteCond %{REMOTE_ADDR} ^10\\. [OR]\nRewriteCond %{REMOTE_ADDR} ^172\\.[1-3]{1}\\d{1}\\. [OR]\nRewriteCond %{REMOTE_ADDR} ^192\\.168\\.\nRewriteRule ^index\\.php index_internal.php [NC,QSA,L]\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20300/"
] |
Is there a possible htaccess directive that can transparently forward request from index.php to index\_internal.php if the request is coming from an internal ip range?
|
```
RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^192\.168\.1\. [OR]
RewriteCond %{REMOTE_ADDR} ^10\.15\.
RewriteRule ^index\.php$ index_internal.php [R,NC,QSA,L]
```
What this does:
start mod\_rewrite engine (you may have that already)
if (client IP address starts with "192.168.1." [or]
client IP address starts with "10.15.")
and page name is index.php ([n]ot [c]ase sensitive), [r]edirect to index\_internal.php, [q]uery [s]tring [a]ppend (i.e. `index.php?foo=bar` becomes `index_internal.php?foo=bar`), [l]eave processing.
Modify as needed for IP address blocks.
|
258,691 |
<p>I am using an XmlDocument to parse and manipulate an XHTML string, converting some nodes to non-HTML nodes.</p>
<p>What is the best way to get a list of all nodes with a given class name? Can it be done with XPath?</p>
|
[
{
"answer_id": 258698,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 3,
"selected": true,
"text": "<p>With a given class? If it is just the one class, then you should be able to do something like .SelectNodes(\"//*[@class='foo']\"). If it isn't xhtml, then the <a href=\"http://www.codeplex.com/htmlagilitypack\" rel=\"nofollow noreferrer\">HTML Agility Pack</a> is worth looking at.</p>\n\n<p>At the client, jQuery would be a good option - and supports composite class names.</p>\n\n<p>If you have multiple class names on individual elements, and need to handle it at the server, I expect you might need to find the candidate classes first (\"//*[@class!='']), and then loop over them doing a <code>Split()</code> and checking for the class-name in the results; i.e. pull it apart manually.</p>\n\n<p>In LINQ terms, something like:</p>\n\n<pre><code> var qry = from XmlElement el in d.SelectNodes(\"//*[@class!='']\")\n let classes = el.GetAttribute(\"class\").Split(new[] {' '},\n StringSplitOptions.RemoveEmptyEntries)\n where classes.Contains(\"foo\")\n select el;\n</code></pre>\n"
},
{
"answer_id": 258700,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>Yes, it's easy with XPath:</p>\n\n<pre><code>//*[@class='foo']\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18107/"
] |
I am using an XmlDocument to parse and manipulate an XHTML string, converting some nodes to non-HTML nodes.
What is the best way to get a list of all nodes with a given class name? Can it be done with XPath?
|
With a given class? If it is just the one class, then you should be able to do something like .SelectNodes("//\*[@class='foo']"). If it isn't xhtml, then the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) is worth looking at.
At the client, jQuery would be a good option - and supports composite class names.
If you have multiple class names on individual elements, and need to handle it at the server, I expect you might need to find the candidate classes first ("//\*[@class!='']), and then loop over them doing a `Split()` and checking for the class-name in the results; i.e. pull it apart manually.
In LINQ terms, something like:
```
var qry = from XmlElement el in d.SelectNodes("//*[@class!='']")
let classes = el.GetAttribute("class").Split(new[] {' '},
StringSplitOptions.RemoveEmptyEntries)
where classes.Contains("foo")
select el;
```
|
258,694 |
<p>For a one-shot operation, i need to parse the contents of an XML string and change the numbers of the "ID" field. However, i can not risk changing anything else of the string, eg. whitespace, line feeds, etc. MUST remain as they are! </p>
<p>Since i have made the experience that XmlReader tends to mess whitespace up and may even reformat your XML i don't want to use it (but feel free to convince me otherwise). This also screams for RegEx but ... i'm not good at RegEx, particularly not with the .NET implementation.</p>
<p>Here's a short part of the string, the number of the ID field needs to be updated in some cases. There can be many such VAR entries in the string. So i need to convert each ID to Int32, compare & modify it, then put it back into the string.</p>
<pre><code><VAR NAME="sf_name" ID="1001210">
</code></pre>
<p>I am looking for the simplest (in terms of coding time) and safest way to do this.</p>
|
[
{
"answer_id": 258723,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": true,
"text": "<p>The regex pattern you are looking for is:</p>\n\n<pre><code>ID=\"(\\d+)\"\n</code></pre>\n\n<p>Match group 1 would contain the number. Use a <a href=\"http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx\" rel=\"nofollow noreferrer\">MatchEvaluator Delegate</a> to replace matches with dynamically calculated replacements.</p>\n\n<pre><code>Regex r = new Regex(\"ID=\\\"(\\\\d+)\\\"\");\nstring outputXml = r.Replace(inputXml, new MatchEvaluator(ReplaceFunction));\n</code></pre>\n\n<p>where <code>ReplaceFunction</code> is something like this:</p>\n\n<pre><code>public string ReplaceFunction(Match m)\n{\n // do stuff with m.Groups(1);\n return result.ToString();\n}\n</code></pre>\n\n<p>If you need I can expand the Regex to match more specifically. Currently <em>all</em> ID values (that contain numbers only) are replaced. You can also build that bit of \"extra intelligence\" into the match evaluator function and make it return the match unchanged if you don't want to change it.</p>\n"
},
{
"answer_id": 258730,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at this property <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.preservewhitespace.aspx\" rel=\"nofollow noreferrer\">PreserveWhitespace</a> in <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx\" rel=\"nofollow noreferrer\">XmlDocument</a> class</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15328/"
] |
For a one-shot operation, i need to parse the contents of an XML string and change the numbers of the "ID" field. However, i can not risk changing anything else of the string, eg. whitespace, line feeds, etc. MUST remain as they are!
Since i have made the experience that XmlReader tends to mess whitespace up and may even reformat your XML i don't want to use it (but feel free to convince me otherwise). This also screams for RegEx but ... i'm not good at RegEx, particularly not with the .NET implementation.
Here's a short part of the string, the number of the ID field needs to be updated in some cases. There can be many such VAR entries in the string. So i need to convert each ID to Int32, compare & modify it, then put it back into the string.
```
<VAR NAME="sf_name" ID="1001210">
```
I am looking for the simplest (in terms of coding time) and safest way to do this.
|
The regex pattern you are looking for is:
```
ID="(\d+)"
```
Match group 1 would contain the number. Use a [MatchEvaluator Delegate](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.matchevaluator.aspx) to replace matches with dynamically calculated replacements.
```
Regex r = new Regex("ID=\"(\\d+)\"");
string outputXml = r.Replace(inputXml, new MatchEvaluator(ReplaceFunction));
```
where `ReplaceFunction` is something like this:
```
public string ReplaceFunction(Match m)
{
// do stuff with m.Groups(1);
return result.ToString();
}
```
If you need I can expand the Regex to match more specifically. Currently *all* ID values (that contain numbers only) are replaced. You can also build that bit of "extra intelligence" into the match evaluator function and make it return the match unchanged if you don't want to change it.
|
258,725 |
<p>When working with my .Net 2.0 code base ReSharper continually recommends applying the latest c# 3.0 language features, most notably; convert simple properties into auto-implement properties or declaring local variables as var. Amongst others.</p>
<p>When a new language feature arrives do you go back and religiously apply it across your existing code base or do you leave the code as originally written accepting that if new code is written using new language features there will be inconsistencies across your code?</p>
|
[
{
"answer_id": 258739,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>If it ain't broke, don't fix it. Of course, if you have confidence in your unit tests, you can give it a whirl, but you shouldn't really go randomly changing code \"just because\".</p>\n\n<p>Of course - in some cases, simplifying code is a valid reason to make a change - but even something as innocent as switching to an auto-implemented property could break code that makes assumptions and uses reflection to update the fields directly. Or it could break serialization.</p>\n\n<p>Changing to \"var\" can actually give you a different (more specific) type, which might cause a different method overload to get selected, etc.</p>\n\n<p>So again; it comes down to your confidence in the unit tests.</p>\n\n<p>Other considerations:</p>\n\n<ul>\n<li>does the rest of the team understand the new syntax yet?</li>\n<li>does your project need to support C# 2.0 (for example, some open source projects might want to retain compatibility with C# 2.0).</li>\n</ul>\n\n<p>If neither of these are an issue, you should be OK to use the new features in new code... just be a <em>little</em> cautious before hitting \"update all\" on old code...</p>\n\n<p>Here's a trivial example of \"var\" as a breaking change:</p>\n\n<pre><code> static void Main() {\n using (TextReader reader = File.OpenText(\"foo.bar\")) { // [HERE]\n Write(reader);\n }\n }\n static void Write(TextReader reader) {\n Console.Write(reader.ReadToEnd());\n }\n static void Write(StreamReader reader) {\n throw new NotImplementedException();\n }\n</code></pre>\n\n<p>Now switch to <code>var reader</code> on the line marked <code>[HERE]</code>...</p>\n"
},
{
"answer_id": 258744,
"author": "Alexandre Brisebois",
"author_id": 18619,
"author_profile": "https://Stackoverflow.com/users/18619",
"pm_score": 2,
"selected": false,
"text": "<p>I would simply maintain the code as I go. Eventually a large portion of the app will have been cleaned or tuned to the new features and improvements. Don't change something for the sake of changing it. If you don't get any performance or stability improvements there is no need to waste time updating code. </p>\n\n<p>C# 3 building on C# 2 and both are quite compatible. Hence each update should be reflected upon.</p>\n"
},
{
"answer_id": 258747,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 1,
"selected": false,
"text": "<p>I leave it until I'm changing that line (or often just lines near it). Then I upgrade. (Sometimes I'll update the whole class or file, once I change one of them)</p>\n"
},
{
"answer_id": 258754,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 0,
"selected": false,
"text": "<p>I leave it be. Besides the fact that it would be alot of work, there's also the issue of is the code really the same or are there side effects of the new feature.</p>\n\n<p>In the specific case of var, the compiler puts the correct type in at compile time anyway, so there's really no benefit.</p>\n\n<p>EDIT: Actually I'm wrong about var not breaking things, so yeah, my original advice stands. If it ain't broke...</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26409/"
] |
When working with my .Net 2.0 code base ReSharper continually recommends applying the latest c# 3.0 language features, most notably; convert simple properties into auto-implement properties or declaring local variables as var. Amongst others.
When a new language feature arrives do you go back and religiously apply it across your existing code base or do you leave the code as originally written accepting that if new code is written using new language features there will be inconsistencies across your code?
|
If it ain't broke, don't fix it. Of course, if you have confidence in your unit tests, you can give it a whirl, but you shouldn't really go randomly changing code "just because".
Of course - in some cases, simplifying code is a valid reason to make a change - but even something as innocent as switching to an auto-implemented property could break code that makes assumptions and uses reflection to update the fields directly. Or it could break serialization.
Changing to "var" can actually give you a different (more specific) type, which might cause a different method overload to get selected, etc.
So again; it comes down to your confidence in the unit tests.
Other considerations:
* does the rest of the team understand the new syntax yet?
* does your project need to support C# 2.0 (for example, some open source projects might want to retain compatibility with C# 2.0).
If neither of these are an issue, you should be OK to use the new features in new code... just be a *little* cautious before hitting "update all" on old code...
Here's a trivial example of "var" as a breaking change:
```
static void Main() {
using (TextReader reader = File.OpenText("foo.bar")) { // [HERE]
Write(reader);
}
}
static void Write(TextReader reader) {
Console.Write(reader.ReadToEnd());
}
static void Write(StreamReader reader) {
throw new NotImplementedException();
}
```
Now switch to `var reader` on the line marked `[HERE]`...
|
258,726 |
<p>I am using a bat file on a Windows 2000 SP4 server to copy database files while the database is shut down. Once the bat file hits the xcopy command, it does the copy, but never returns to the bat file to continue with the other commands (start up the database, etc). I should mention that the xcopy takes several hours. Is there some sort of time out or time max with bat files? Is this normal? If so, is there any way around this?</p>
|
[
{
"answer_id": 258758,
"author": "Brian Knoblauch",
"author_id": 15689,
"author_profile": "https://Stackoverflow.com/users/15689",
"pm_score": 0,
"selected": false,
"text": "<p>There's no timeout that I'm aware of on .bat or .cmd files. However, there may be on the process that's launching it? How are you launching it?</p>\n"
},
{
"answer_id": 258761,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "<p>Batch files don't timeout. It sounds like you might be running into a prompt from XCOPY, like an \"Are you sure\" prompt.</p>\n\n<p>Make sure you've added the necessary command-line switches to XCOPY to make it silent.</p>\n\n<p>The ones I'm aware of are:</p>\n\n<pre><code>-Y to suppress prompts about overwriting files\n\n-C continue even if errors occur\n</code></pre>\n"
},
{
"answer_id": 258776,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Also, make sure that you are running the XCOPY.EXE app, and not finding an XCOPY.BAT file somewhere on your path. (calling a batch file from a batch file prevent returning, unless you use the CALL command)</p>\n\n<p>And, be sure you are not overwriting the batch file itself during the XCOPY. </p>\n"
},
{
"answer_id": 259688,
"author": "Dave Cluderay",
"author_id": 30933,
"author_profile": "https://Stackoverflow.com/users/30933",
"pm_score": 1,
"selected": false,
"text": "<p>Presumably everything looks OK in your backup.log file?\nIt looks like you are redirecting STDOUT to your log file, but not STDERR - would suggest adding 2>&1 to the end of the command line to ensure you're not missing any error information from the log.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am using a bat file on a Windows 2000 SP4 server to copy database files while the database is shut down. Once the bat file hits the xcopy command, it does the copy, but never returns to the bat file to continue with the other commands (start up the database, etc). I should mention that the xcopy takes several hours. Is there some sort of time out or time max with bat files? Is this normal? If so, is there any way around this?
|
Batch files don't timeout. It sounds like you might be running into a prompt from XCOPY, like an "Are you sure" prompt.
Make sure you've added the necessary command-line switches to XCOPY to make it silent.
The ones I'm aware of are:
```
-Y to suppress prompts about overwriting files
-C continue even if errors occur
```
|
258,727 |
<p>I'd like to display a stack trace in an error dialog in Delphi 2007 (Win32).</p>
<p>Ideally, I'd like something like this:</p>
<pre><code>try
//do something
except on e : exception do
begin
//rollback a transaction or whatever i need to do here
MessageDlg('An error has occurred!' + #13#10 +
e.Message + #13#10 +
'Here is the stack trace:' + #13#10 +
e.StackTrace,mtError,[mbOK],0);
end; //except
end; /try-except
</code></pre>
<p>And for the output to be like the Call Stack in the IDE:</p>
<pre><code>MYPROGRAM.SomeFunction
MYPROGRAM.SomeProcedure
MYPROGRAM.MYPROGRAM
:7c817067 kernel32.RegisterWaitForInputIdle + 0x49
</code></pre>
|
[
{
"answer_id": 258759,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 6,
"selected": true,
"text": "<p><a href=\"http://www.madshi.net/madExceptDescription.htm\" rel=\"noreferrer\">madExcept</a> has a method StackTrace (in unit madStackTrace) that does that.</p>\n\n<p><a href=\"http://sourceforge.net/projects/jcl/\" rel=\"noreferrer\">JEDI Code Library</a> offers similar functionality in unit JclDebug.</p>\n"
},
{
"answer_id": 2288441,
"author": "Martin Binder",
"author_id": 125092,
"author_profile": "https://Stackoverflow.com/users/125092",
"pm_score": 3,
"selected": false,
"text": "<p>We use <a href=\"http://www.dimusware.com/products/excmagic/index.html\" rel=\"noreferrer\">Exceptional Magic</a> and it works really well for us. With it you can do something like this:</p>\n\n<pre><code>try\n raise Exception.Create('Something bad happened...');\nexcept\n on e: Exception do begin\n CallStack := TStringList.Create;\n try\n ExceptionHook.LogException; // Logs call stack\n ExceptionHook.CallStack.Dump(CallStack);\n ShowMessage(CallStack.Text);\n finally\n CallStack.Free;\n end;\n end;\n end;\n</code></pre>\n\n<p>This yields a pretty detailed call stack:</p>\n\n<pre><code>Exception 'Exception' in module BOAppTemplate.exe at 003F3C36\nSomething bad happened...\n\nModule: BOAppUnit, Source: BOAppUnit.pas, Line 66\nProcedure: MyProcedure\n\nCall stack:\n:007F4C36 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 66)\n:7C812AFB [kernel32.dll]\n:007F4C36 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 66)\n:00404DF4 [BOAppTemplate.exe] System::__linkproc__ AfterConstruction\nRecursive call (2 times):\n:007F4C36 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 66)\n:007F4CE6 [BOAppTemplate.exe] MyProcedure (BOAppUnit.pas, line 79)\n:007F4D22 [BOAppTemplate.exe] Boappunit::TBOAppForm::Button1Click (BOAppUnit.pas, line 82)\n:004604C2 [BOAppTemplate.exe] Controls::TControl::Click\n:004487FB [BOAppTemplate.exe] Stdctrls::TButton::Click\n:004488F9 [BOAppTemplate.exe] Stdctrls::TButton::CNCommand\n:0045FFBA [BOAppTemplate.exe] Controls::TControl::WndProc\n</code></pre>\n\n<p>Exceptional Magic is only $25 without the source, so it's relatively cheap. Hope that helps!</p>\n"
},
{
"answer_id": 2773216,
"author": "Alex",
"author_id": 92713,
"author_profile": "https://Stackoverflow.com/users/92713",
"pm_score": 3,
"selected": false,
"text": "<p>You may be interested in this article: \"<a href=\"http://eurekalog.blogspot.com/2010/05/new-exception-class-in-delphi-2009-and_05.html\" rel=\"nofollow noreferrer\">New Exception class in Delphi 2009 and above</a>\".</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
I'd like to display a stack trace in an error dialog in Delphi 2007 (Win32).
Ideally, I'd like something like this:
```
try
//do something
except on e : exception do
begin
//rollback a transaction or whatever i need to do here
MessageDlg('An error has occurred!' + #13#10 +
e.Message + #13#10 +
'Here is the stack trace:' + #13#10 +
e.StackTrace,mtError,[mbOK],0);
end; //except
end; /try-except
```
And for the output to be like the Call Stack in the IDE:
```
MYPROGRAM.SomeFunction
MYPROGRAM.SomeProcedure
MYPROGRAM.MYPROGRAM
:7c817067 kernel32.RegisterWaitForInputIdle + 0x49
```
|
[madExcept](http://www.madshi.net/madExceptDescription.htm) has a method StackTrace (in unit madStackTrace) that does that.
[JEDI Code Library](http://sourceforge.net/projects/jcl/) offers similar functionality in unit JclDebug.
|
258,729 |
<p>I have a simple linux script:</p>
<pre><code>#!/bin/sh
for i in `ls $1`
do
echo $i
done
</code></pre>
<p>In my temp folder are 4 file: a.a, a.aa, a.ab and a.ac</p>
<p>When i call ./script temp/*.?? i get:</p>
<pre><code>temp/a.aa
</code></pre>
<p>When i call ./script "temp/*.??" i get:</p>
<pre><code>temp/a.aa
temp/a.ab
temp/a.ac
</code></pre>
<p>Why do the double quote change the result?</p>
|
[
{
"answer_id": 258778,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "<p>Because without the quotes the shell is expanding your call to:</p>\n\n<pre><code>./script temp/a.aa temp/a.ab temp/a.ac\n</code></pre>\n\n<p>So <code>$1</code> is <code>temp/a.aa</code> instead of <code>temp/*.??</code>.</p>\n"
},
{
"answer_id": 258783,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "<p>In the first case the shell expands <code>temp/*.??</code> to:</p>\n\n<pre><code>temp/a.aa temp/a.ab temp/a.ac\n</code></pre>\n\n<p>Since you are only looking at the first parameter in your script only <code>temp/a.aa</code> is passed to ls.</p>\n\n<p>In the second case, the shell does not perform any expansion because of the quotes and the script receives the single argument <code>temp/*.??</code> which is expanded in the call to <code>ls</code>.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258729",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12860/"
] |
I have a simple linux script:
```
#!/bin/sh
for i in `ls $1`
do
echo $i
done
```
In my temp folder are 4 file: a.a, a.aa, a.ab and a.ac
When i call ./script temp/\*.?? i get:
```
temp/a.aa
```
When i call ./script "temp/\*.??" i get:
```
temp/a.aa
temp/a.ab
temp/a.ac
```
Why do the double quote change the result?
|
In the first case the shell expands `temp/*.??` to:
```
temp/a.aa temp/a.ab temp/a.ac
```
Since you are only looking at the first parameter in your script only `temp/a.aa` is passed to ls.
In the second case, the shell does not perform any expansion because of the quotes and the script receives the single argument `temp/*.??` which is expanded in the call to `ls`.
|
258,738 |
<p>I have a Java maven project which includes XSLT transformations. I load the stylesheet as follows:</p>
<pre><code>TransformerFactory tFactory = TransformerFactory.newInstance();
DocumentBuilderFactory dFactory = DocumentBuilderFactory
.newInstance();
dFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("xsl/stylesheet.xsl");
InputSource xslInputSource = new InputSource(in);
Document xslDoc = dBuilder.parse(xslInputSource);
DOMSource xslDomSource = new DOMSource(xslDoc);
Transformer transformer = tFactory.newTransformer(xslDomSource);
</code></pre>
<p>The stylesheet.xsl has a number of statements. These appear to be causing problems, when I try to run my unit tests I get the following errors:</p>
<pre><code>C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: footer.xsl
C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: topbar.xsl
</code></pre>
<p>The include statements in the XSLT are relative links</p>
<pre><code>xsl:include href="footer.xsl"
xsl:include href="topbar.xsl"
</code></pre>
<p>I have tried experimenting and changing these to the following - but I still get the error.</p>
<pre><code>xsl:include href="xsl/footer.xsl"
xsl:include href="xsl/topbar.xsl"
</code></pre>
<p>Any ideas? Any help much appreciated.</p>
|
[
{
"answer_id": 258753,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 0,
"selected": false,
"text": "<p>I had a problem similar to this once with relative paths in the XSLT. </p>\n\n<p>If you can, try to put absolute paths in the XSLT - that should resolve the error.</p>\n\n<p>An absolute path probably isn't preferable for the final version of the XSLT, but it should get you past the maven problem. Perhaps you can have two versions of the XSLT, one with absolute paths for maven and one with relative paths for whatever other tool it's being used with.</p>\n"
},
{
"answer_id": 258821,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 1,
"selected": false,
"text": "<p>Set your DocumentBuilder object with an <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/org/xml/sax/EntityResolver.html\" rel=\"nofollow noreferrer\">EntityResolver</a>.</p>\n\n<p>You'll have to extend EntityResolver class to resolve your external entities (footer.xsl and topbar.xsl). </p>\n"
},
{
"answer_id": 258951,
"author": "will",
"author_id": 8633,
"author_profile": "https://Stackoverflow.com/users/8633",
"pm_score": 5,
"selected": true,
"text": "<p>Solved my problem using a URIResolver.</p>\n\n<pre><code>class MyURIResolver implements URIResolver {\n@Override\npublic Source resolve(String href, String base) throws TransformerException {\n try {\n ClassLoader cl = this.getClass().getClassLoader();\n java.io.InputStream in = cl.getResourceAsStream(\"xsl/\" + href);\n InputSource xslInputSource = new InputSource(in);\n Document xslDoc = dBuilder.parse(xslInputSource);\n DOMSource xslDomSource = new DOMSource(xslDoc);\n xslDomSource.setSystemId(\"xsl/\" + href);\n return xslDomSource;\n } catch (...\n</code></pre>\n\n<p>And assigning this with the TransformerFactory</p>\n\n<pre><code>tFactory.setURIResolver(new MyURIResolver());\n</code></pre>\n"
},
{
"answer_id": 11138263,
"author": "Rajdeep Kwatra",
"author_id": 1472087,
"author_profile": "https://Stackoverflow.com/users/1472087",
"pm_score": 3,
"selected": false,
"text": "<p>URIResolver can also be used in a more straightforward way as below:</p>\n\n<pre><code>class XsltURIResolver implements URIResolver {\n\n @Override\n public Source resolve(String href, String base) throws TransformerException {\n try{\n InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(\"xslts/\" + href);\n return new StreamSource(inputStream);\n }\n catch(Exception ex){\n ex.printStackTrace();\n return null;\n }\n }\n}\n</code></pre>\n\n<p>Use the URIResolver with TransformerFactory as shown below:</p>\n\n<pre><code>TransformerFactory transFact = TransformerFactory.newInstance();\ntransFact.setURIResolver(new XsltURIResolver());\n</code></pre>\n\n<p>Or with a lambda expression:</p>\n\n<pre><code>transFact.setURIResolver((href, base) -> {\n final InputStream s = this.getClass().getClassLoader().getResourceAsStream(\"xslts/\" + href);\n return new StreamSource(s);\n});\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8633/"
] |
I have a Java maven project which includes XSLT transformations. I load the stylesheet as follows:
```
TransformerFactory tFactory = TransformerFactory.newInstance();
DocumentBuilderFactory dFactory = DocumentBuilderFactory
.newInstance();
dFactory.setNamespaceAware(true);
DocumentBuilder dBuilder = dFactory.newDocumentBuilder();
ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("xsl/stylesheet.xsl");
InputSource xslInputSource = new InputSource(in);
Document xslDoc = dBuilder.parse(xslInputSource);
DOMSource xslDomSource = new DOMSource(xslDoc);
Transformer transformer = tFactory.newTransformer(xslDomSource);
```
The stylesheet.xsl has a number of statements. These appear to be causing problems, when I try to run my unit tests I get the following errors:
```
C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: footer.xsl
C:\Code\workspace\app\dummy.xsl; Line #0; Column #0; Had IO Exception with stylesheet file: topbar.xsl
```
The include statements in the XSLT are relative links
```
xsl:include href="footer.xsl"
xsl:include href="topbar.xsl"
```
I have tried experimenting and changing these to the following - but I still get the error.
```
xsl:include href="xsl/footer.xsl"
xsl:include href="xsl/topbar.xsl"
```
Any ideas? Any help much appreciated.
|
Solved my problem using a URIResolver.
```
class MyURIResolver implements URIResolver {
@Override
public Source resolve(String href, String base) throws TransformerException {
try {
ClassLoader cl = this.getClass().getClassLoader();
java.io.InputStream in = cl.getResourceAsStream("xsl/" + href);
InputSource xslInputSource = new InputSource(in);
Document xslDoc = dBuilder.parse(xslInputSource);
DOMSource xslDomSource = new DOMSource(xslDoc);
xslDomSource.setSystemId("xsl/" + href);
return xslDomSource;
} catch (...
```
And assigning this with the TransformerFactory
```
tFactory.setURIResolver(new MyURIResolver());
```
|
258,746 |
<p>I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:</p>
<pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3
</code></pre>
<p>How could I slice out:</p>
<pre><code>http://www.domainname.com/page?CONTENT_ITEM_ID=1234
</code></pre>
<p>Sometimes there is more than two parameters after the CONTENT_ITEM_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho.</p>
<p>Cheers</p>
|
[
{
"answer_id": 258797,
"author": "RailsSon",
"author_id": 30786,
"author_profile": "https://Stackoverflow.com/users/30786",
"pm_score": 1,
"selected": false,
"text": "<p>I figured it out below is what I needed to do:</p>\n\n<pre><code>url = \"http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3\"\nurl = url[: url.find(\"&\")]\nprint url\n'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'\n</code></pre>\n"
},
{
"answer_id": 258798,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import re\nurl = 'http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3'\nm = re.search('(.*?)&', url)\nprint m.group(1)\n</code></pre>\n"
},
{
"answer_id": 258800,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 2,
"selected": false,
"text": "<p>The quick and dirty solution is this:</p>\n\n<pre><code>>>> \"http://something.com/page?CONTENT_ITEM_ID=1234&param3\".split(\"&\")[0]\n'http://something.com/page?CONTENT_ITEM_ID=1234'\n</code></pre>\n"
},
{
"answer_id": 258810,
"author": "Kena",
"author_id": 8027,
"author_profile": "https://Stackoverflow.com/users/8027",
"pm_score": 2,
"selected": false,
"text": "<p>Another option would be to use the split function, with & as a parameter. That way, you'd extract both the base url and both parameters.</p>\n\n<pre><code> url.split(\"&\") \n</code></pre>\n\n<p>returns a list with</p>\n\n<pre><code> ['http://www.domainname.com/page?CONTENT_ITEM_ID=1234', 'param2', 'param3']\n</code></pre>\n"
},
{
"answer_id": 258832,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>Look at the <a href=\"https://stackoverflow.com/questions/163009/urllib2-file-name\">urllib2 file name</a> question for some discussion of this topic.</p>\n\n<p>Also see the \"<a href=\"https://stackoverflow.com/questions/229352/python-find-question\">Python Find Question</a>\" question.</p>\n"
},
{
"answer_id": 258993,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 0,
"selected": false,
"text": "<p>This method isn't dependent on the position of the parameter within the url string. This could be refined, I'm sure, but it gets the point across.</p>\n\n<pre><code>url = 'http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3'\nparts = url.split('?')\nid = dict(i.split('=') for i in parts[1].split('&'))['CONTENT_ITEM_ID']\nnew_url = parts[0] + '?CONTENT_ITEM_ID=' + id\n</code></pre>\n"
},
{
"answer_id": 259054,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": "<p>Parsin URL is never as simple I it seems to be, that's why there are the urlparse and urllib modules.</p>\n\n<p>E.G :</p>\n\n<pre><code>import urllib\nurl =\"http://www.domainname.com/page?CONTENT_ITEM_ID=1234&param2&param3\"\nquery = urllib.splitquery(url)\nresult = \"?\".join((query[0], query[1].split(\"&\")[0]))\nprint result\n'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'\n</code></pre>\n\n<p>This is still not 100 % reliable, but much more than splitting it yourself because there are a lot of valid url format that you and me don't know and discover one day in error logs.</p>\n"
},
{
"answer_id": 259159,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": true,
"text": "<p>Use the <a href=\"http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit\" rel=\"nofollow noreferrer\">urlparse</a> module. Check this function:</p>\n\n<pre><code>import urlparse\n\ndef process_url(url, keep_params=('CONTENT_ITEM_ID=',)):\n parsed= urlparse.urlsplit(url)\n filtered_query= '&'.join(\n qry_item\n for qry_item in parsed.query.split('&')\n if qry_item.startswith(keep_params))\n return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:])\n</code></pre>\n\n<p>In your example:</p>\n\n<pre><code>>>> process_url(a)\n'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'\n</code></pre>\n\n<p>This function has the added bonus that it's easier to use if you decide that you also want some more query parameters, or if the order of the parameters is not fixed, as in:</p>\n\n<pre><code>>>> url='http://www.domainname.com/page?other_value=xx&param3&CONTENT_ITEM_ID=1234&param1'\n>>> process_url(url, ('CONTENT_ITEM_ID', 'other_value'))\n'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234'\n</code></pre>\n"
},
{
"answer_id": 2326780,
"author": "Alien Life Form",
"author_id": 279600,
"author_profile": "https://Stackoverflow.com/users/279600",
"pm_score": 0,
"selected": false,
"text": "<p>An ancient question, but still, I'd like to remark that query string paramenters can also be separated by ';' not only '&'.</p>\n"
},
{
"answer_id": 11576768,
"author": "neutrinus",
"author_id": 1216074,
"author_profile": "https://Stackoverflow.com/users/1216074",
"pm_score": 0,
"selected": false,
"text": "<p>beside <em>urlparse</em> there is also <a href=\"https://github.com/gruns/furl/\" rel=\"nofollow\">furl</a>, which has IMHO better API.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30786/"
] |
I am working with a huge list of URL's. Just a quick question I have trying to slice a part of the URL out, see below:
```
http://www.domainname.com/page?CONTENT_ITEM_ID=1234¶m2¶m3
```
How could I slice out:
```
http://www.domainname.com/page?CONTENT_ITEM_ID=1234
```
Sometimes there is more than two parameters after the CONTENT\_ITEM\_ID and the ID is different each time, I am thinking it can be done by finding the first & and then slicing off the chars before that &, not quite sure how to do this tho.
Cheers
|
Use the [urlparse](http://docs.python.org/2/library/urlparse.html#urlparse.urlsplit) module. Check this function:
```
import urlparse
def process_url(url, keep_params=('CONTENT_ITEM_ID=',)):
parsed= urlparse.urlsplit(url)
filtered_query= '&'.join(
qry_item
for qry_item in parsed.query.split('&')
if qry_item.startswith(keep_params))
return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:])
```
In your example:
```
>>> process_url(a)
'http://www.domainname.com/page?CONTENT_ITEM_ID=1234'
```
This function has the added bonus that it's easier to use if you decide that you also want some more query parameters, or if the order of the parameters is not fixed, as in:
```
>>> url='http://www.domainname.com/page?other_value=xx¶m3&CONTENT_ITEM_ID=1234¶m1'
>>> process_url(url, ('CONTENT_ITEM_ID', 'other_value'))
'http://www.domainname.com/page?other_value=xx&CONTENT_ITEM_ID=1234'
```
|
258,757 |
<p>How do I escape a string in SQL Server's stored procedure so that it is safe to use in <code>LIKE</code> expression.</p>
<p>Suppose I have an <code>NVARCHAR</code> variable like so:</p>
<pre><code>declare @myString NVARCHAR(100);
</code></pre>
<p>And I want to use it in a <code>LIKE</code> expression:</p>
<pre><code>... WHERE ... LIKE '%' + @myString + '%';
</code></pre>
<p>How do I escape the string (more specifically, characters that are meaningful to <code>LIKE</code> pattern matching, e.g. <code>%</code> or <code>?</code>) in T-SQL, so that it is safe to use in this manner?</p>
<p>For example, given:</p>
<pre><code>@myString = 'aa%bb'
</code></pre>
<p>I want:</p>
<pre><code>WHERE ... LIKE '%' + @somehowEscapedMyString + '%'
</code></pre>
<p>to match <code>'aa%bb'</code>, <code>'caa%bbc'</code> but not <code>'aaxbb'</code> or <code>'caaxbb'</code>.</p>
|
[
{
"answer_id": 258766,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 2,
"selected": false,
"text": "<p>You specify the escape character. Documentation here:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/ms179859.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms179859.aspx</a></p>\n"
},
{
"answer_id": 258808,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<p>Do you want to look for strings that include an escape character? For instance you want this:</p>\n\n<pre><code>select * from table where myfield like '%10%%'.\n</code></pre>\n\n<p>Where you want to search for all fields with 10%? If that is the case then you may use the ESCAPE clause to specify an escape character and escape the wildcard character.</p>\n\n<pre><code>select * from table where myfield like '%10!%%' ESCAPE '!'\n</code></pre>\n"
},
{
"answer_id": 258947,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 8,
"selected": true,
"text": "<p>To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (<a href=\"http://msdn.microsoft.com/en-us/library/ms179859.aspx\" rel=\"noreferrer\">MSDN Ref</a>)</p>\n\n<p>For example this escapes the % symbol, using \\ as the escape char:</p>\n\n<pre><code>select * from table where myfield like '%15\\% off%' ESCAPE '\\'\n</code></pre>\n\n<p>If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg: </p>\n\n<pre><code>set @myString = replace( \n replace( \n replace( \n replace( @myString\n , '\\', '\\\\' )\n , '%', '\\%' )\n , '_', '\\_' )\n , '[', '\\[' )\n</code></pre>\n\n<p>(Note that you have to escape your escape char too, and make sure that's the inner <code>replace</code> so you don't escape the ones added from the other <code>replace</code> statements). Then you can use something like this: </p>\n\n<pre><code>select * from table where myfield like '%' + @myString + '%' ESCAPE '\\'\n</code></pre>\n\n<p>Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.</p>\n"
},
{
"answer_id": 1178393,
"author": "Dries Van Hansewijck",
"author_id": 95981,
"author_profile": "https://Stackoverflow.com/users/95981",
"pm_score": 4,
"selected": false,
"text": "<p>Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become</p>\n\n<pre><code>WHERE ... LIKE '%aa[%]bb%'\n</code></pre>\n\n<p>If you need proof:</p>\n\n<pre><code>create table test (field nvarchar(100))\ngo\ninsert test values ('abcdef%hijklm')\ninsert test values ('abcdefghijklm')\ngo\nselect * from test where field like 'abcdef[%]hijklm'\ngo\n</code></pre>\n"
},
{
"answer_id": 9242060,
"author": "Martin Smith",
"author_id": 73226,
"author_profile": "https://Stackoverflow.com/users/73226",
"pm_score": 4,
"selected": false,
"text": "<p>Rather than escaping <strong>all</strong> characters in a string that have particular significance in the pattern syntax given that you are using a leading wildcard in the pattern it is quicker and easier just to do.</p>\n\n<pre><code>SELECT * \nFROM YourTable\nWHERE CHARINDEX(@myString , YourColumn) > 0\n</code></pre>\n\n<p>In cases where you are not using a leading wildcard the approach above should be avoided however as it cannot use an index on <code>YourColumn</code>.</p>\n\n<p>Additionally in cases where the optimum execution plan will vary according to the number of matching rows the estimates may be better when using <code>LIKE</code> with the square bracket escaping syntax when compared to <a href=\"https://dba.stackexchange.com/q/46917/3690\">both <code>CHARINDEX</code></a> and <a href=\"https://dba.stackexchange.com/a/47206/3690\">the <code>ESCAPE</code> keyword</a>.</p>\n"
},
{
"answer_id": 56923634,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 0,
"selected": false,
"text": "<p>Alternative escaping syntax:</p>\n\n<blockquote>\n <p><a href=\"https://learn.microsoft.com/en-us/sql/connect/jdbc/using-sql-escape-sequences?view=sql-server-2017\" rel=\"nofollow noreferrer\">LIKE Wildcard Literals</a></p>\n \n <p>The JDBC driver supports the <strong>{escape 'escape character'}</strong> syntax for using LIKE clause wildcards as literals.</p>\n</blockquote>\n\n<pre><code>SELECT *\nFROM tab\nWHERE col LIKE 'a\\_c' {escape '\\'};\n</code></pre>\n\n<p><strong><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=e4080bf5917b482e809013444f1fc40b\" rel=\"nofollow noreferrer\">db<>fiddle demo</a></strong></p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I escape a string in SQL Server's stored procedure so that it is safe to use in `LIKE` expression.
Suppose I have an `NVARCHAR` variable like so:
```
declare @myString NVARCHAR(100);
```
And I want to use it in a `LIKE` expression:
```
... WHERE ... LIKE '%' + @myString + '%';
```
How do I escape the string (more specifically, characters that are meaningful to `LIKE` pattern matching, e.g. `%` or `?`) in T-SQL, so that it is safe to use in this manner?
For example, given:
```
@myString = 'aa%bb'
```
I want:
```
WHERE ... LIKE '%' + @somehowEscapedMyString + '%'
```
to match `'aa%bb'`, `'caa%bbc'` but not `'aaxbb'` or `'caaxbb'`.
|
To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. ([MSDN Ref](http://msdn.microsoft.com/en-us/library/ms179859.aspx))
For example this escapes the % symbol, using \ as the escape char:
```
select * from table where myfield like '%15\% off%' ESCAPE '\'
```
If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:
```
set @myString = replace(
replace(
replace(
replace( @myString
, '\', '\\' )
, '%', '\%' )
, '_', '\_' )
, '[', '\[' )
```
(Note that you have to escape your escape char too, and make sure that's the inner `replace` so you don't escape the ones added from the other `replace` statements). Then you can use something like this:
```
select * from table where myfield like '%' + @myString + '%' ESCAPE '\'
```
Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.
|
258,762 |
<p>Is there a way in .NET 2.0 (C#) to serialize object like you do using XmlSerializer in a simple / customizable human readable format thats for instance looks like <a href="http://community.moertel.com/pxsl/" rel="noreferrer">PXLS</a> or JSON?
Also I know that XML is human readable, I'm looking for something with less annoying redundancy, something that you can output to the console as a result for the user.</p>
|
[
{
"answer_id": 258813,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>The built-in serialization options for .Net are Xml, Xml-Soap, and binary. Since you've ruled out xml and binary is definitely not human readable, you'll have to roll your own.</p>\n\n<p>When rolling your own, you have a few options:</p>\n\n<ul>\n<li>Add Utility or Extention methods to the class, like AviewAnew suggested</li>\n<li>Extend System.Runtime.Serialization.Formatter / Implement System.Runtime.Serialization.IFormatter</li>\n<li>Find a generic component online via google that will do what you want.</li>\n</ul>\n\n<p>Note that the 2nd item can be specialized for your specific class (it doesn't have to be able to handle any class, if you don't want it to) and the latter two items are not mutually exclusive. </p>\n\n<p>I have searched for a .Net JSON formatter in the past, and there are definitely multiple options out there. However, I ended up going a different direction that time. I just didn't feel very confident in any of them. Maybe someone else can provide a more specific recommendation. JSON is becoming big enough that hopefully Microsoft will include \"native\" support for it in the framework soon. </p>\n"
},
{
"answer_id": 258876,
"author": "ullmark",
"author_id": 23044,
"author_profile": "https://Stackoverflow.com/users/23044",
"pm_score": 4,
"selected": true,
"text": "<p>To Serialize into JSON in .NET you do as follows:</p>\n\n<pre><code>public static string ToJson(IEnumerable collection)\n {\n DataContractJsonSerializer ser = new DataContractJsonSerializer(collection.GetType());\n string json;\n using (MemoryStream m = new MemoryStream())\n {\n XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(m);\n ser.WriteObject(m, collection);\n writer.Flush();\n\n json = Encoding.Default.GetString(m.ToArray());\n }\n return json;\n }\n</code></pre>\n\n<p>The collections item need to have the \"DataContract\" attribute, and each member you wish to be serialized into the JSON must have the \"DataMember\" attibute.</p>\n\n<p>It's possible that this only works for .NET 3.5. But there is an equally simple version for 2.0 aswell...</p>\n"
},
{
"answer_id": 2554460,
"author": "Zax",
"author_id": 306087,
"author_profile": "https://Stackoverflow.com/users/306087",
"pm_score": 2,
"selected": false,
"text": "<p>I found a exaustive documentation here:</p>\n\n<p><a href=\"http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx\" rel=\"nofollow noreferrer\">http://pietschsoft.com/post/2008/02/NET-35-JSON-Serialization-using-the-DataContractJsonSerializer.aspx</a></p>\n\n<p>with this usefull class (support generics)</p>\n\n<pre><code>using System.Runtime.Serialization;\nusing System.Runtime.Serialization.Json;\n\npublic class JSONHelper\n{\n public static string Serialize<T>(T obj)\n {\n DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());\n MemoryStream ms = new MemoryStream();\n serializer.WriteObject(ms, obj);\n string retVal = Encoding.Default.GetString(ms.ToArray());\n ms.Dispose();\n return retVal;\n }\n\n public static T Deserialize<T>(string json)\n {\n T obj = Activator.CreateInstance<T>();\n MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));\n DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());\n obj = (T)serializer.ReadObject(ms);\n ms.Close();\n ms.Dispose();\n return obj;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 38538472,
"author": "Makeman",
"author_id": 6627992,
"author_profile": "https://Stackoverflow.com/users/6627992",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/a/38538454/6627992\">https://stackoverflow.com/a/38538454/6627992</a></p>\n\n<p>You may use following standard method for getting formatted Json</p>\n\n<p><em>JsonReaderWriterFactory.CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars)</em></p>\n\n<p>Only set <em>\"indent==true\"</em></p>\n\n<p>Try something like this</p>\n\n<pre><code> public readonly DataContractJsonSerializerSettings Settings = \n new DataContractJsonSerializerSettings\n { UseSimpleDictionaryFormat = true };\n\n public void Keep<TValue>(TValue item, string path)\n {\n try\n {\n using (var stream = File.Open(path, FileMode.Create))\n {\n var currentCulture = Thread.CurrentThread.CurrentCulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n\n try\n {\n using (var writer = JsonReaderWriterFactory.CreateJsonWriter(\n stream, Encoding.UTF8, true, true, \" \"))\n {\n var serializer = new DataContractJsonSerializer(type, Settings);\n serializer.WriteObject(writer, item);\n writer.Flush();\n }\n }\n catch (Exception exception)\n {\n Debug.WriteLine(exception.ToString());\n }\n finally\n {\n Thread.CurrentThread.CurrentCulture = currentCulture;\n }\n }\n }\n catch (Exception exception)\n {\n Debug.WriteLine(exception.ToString());\n }\n }\n</code></pre>\n\n<p>Pay your attention to lines</p>\n\n<pre><code> var currentCulture = Thread.CurrentThread.CurrentCulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n ....\n Thread.CurrentThread.CurrentCulture = currentCulture;\n</code></pre>\n\n<p>You should use <em>InvariantCulture</em> to avoid exception during deserialization on the computers with different Regional settings. For example, invalid format of <em>double</em> or <em>DateTime</em> sometimes cause them.</p>\n\n<p>For deserializing</p>\n\n<pre><code> public TValue Revive<TValue>(string path, params object[] constructorArgs)\n {\n try\n {\n using (var stream = File.OpenRead(path))\n {\n var currentCulture = Thread.CurrentThread.CurrentCulture;\n Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;\n\n try\n {\n var serializer = new DataContractJsonSerializer(type, Settings);\n var item = (TValue) serializer.ReadObject(stream);\n if (Equals(item, null)) throw new Exception();\n return item;\n }\n catch (Exception exception)\n {\n Debug.WriteLine(exception.ToString());\n return (TValue) Activator.CreateInstance(type, constructorArgs);\n }\n finally\n {\n Thread.CurrentThread.CurrentCulture = currentCulture;\n }\n }\n }\n catch\n {\n return (TValue) Activator.CreateInstance(typeof (TValue), constructorArgs);\n }\n }\n</code></pre>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 42370310,
"author": "frenchone",
"author_id": 461581,
"author_profile": "https://Stackoverflow.com/users/461581",
"pm_score": 0,
"selected": false,
"text": "<p>Apply a xsl to your xml to strip out what you don't want to see ?</p>\n\n<p>something like</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n<xsl:output method=\"text\" indent=\"yes\"/>\n <xsl:template match=\"*\">\n <xsl:value-of select=\"name()\" /><xsl:text>\n</xsl:text>\n <xsl:apply-templates select=\"@*\"/>\n<xsl:apply-templates select=\"*\"/>\n </xsl:template>\n <xsl:template match=\"@*|text()|comment()|processing-instruction\">\n <xsl:value-of select=\"name()\" />:<xsl:value-of select=\".\" /><xsl:text>\n</xsl:text>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25782/"
] |
Is there a way in .NET 2.0 (C#) to serialize object like you do using XmlSerializer in a simple / customizable human readable format thats for instance looks like [PXLS](http://community.moertel.com/pxsl/) or JSON?
Also I know that XML is human readable, I'm looking for something with less annoying redundancy, something that you can output to the console as a result for the user.
|
To Serialize into JSON in .NET you do as follows:
```
public static string ToJson(IEnumerable collection)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(collection.GetType());
string json;
using (MemoryStream m = new MemoryStream())
{
XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(m);
ser.WriteObject(m, collection);
writer.Flush();
json = Encoding.Default.GetString(m.ToArray());
}
return json;
}
```
The collections item need to have the "DataContract" attribute, and each member you wish to be serialized into the JSON must have the "DataMember" attibute.
It's possible that this only works for .NET 3.5. But there is an equally simple version for 2.0 aswell...
|
258,767 |
<p>I am using <strong>0.97-pre-SVN-unknown</strong> release of Django.</p>
<p>I have a model for which I have not given any primary_key. Django, consequently, automatically provides an AutoField that is called "id". Everything's fine with that. But now, I have to change the "verbose_name" of that AutoField to something other than "id". I cannot override the "id" field the usual way, because that would require dropping/resetting the entire model and its data (which is strictly not an option). I cannot find another way around it. Does what I want even possible to achieve? If you may suggest any alternatives that would get me away with what I want without having to drop the model/table, I'd be happy.</p>
|
[
{
"answer_id": 259027,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 2,
"selected": false,
"text": "<p>Look into the command-line options for <code>manage.py</code>; there's a command to dump all of the model data to JSON, and another command to load it back in from JSON. You can export all of your model data, add your new field to the model, then import your data back in. Just make sure that you set the <code>db_column</code> option to <code>'id'</code> so you don't break your existing data.</p>\n\n<p><strong>Edit</strong>: Specifically, you want the commands <a href=\"http://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata\" rel=\"nofollow noreferrer\"><code>dumpdata</code></a> and <a href=\"http://docs.djangoproject.com/en/dev/ref/django-admin/#loaddata-fixture-fixture\" rel=\"nofollow noreferrer\"><code>loaddata</code></a>.</p>\n"
},
{
"answer_id": 259077,
"author": "Alex Koshelev",
"author_id": 19772,
"author_profile": "https://Stackoverflow.com/users/19772",
"pm_score": 3,
"selected": true,
"text": "<p>Hmm... and what about explicitly write <em>id</em> field in the model definition? Like this for example:</p>\n\n<pre><code>class Entry(models.Model):\n id = models.AutoField(verbose_name=\"custom name\")\n # and other fields...\n</code></pre>\n\n<p>It doesn't require any underlying database changes.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258767",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23191/"
] |
I am using **0.97-pre-SVN-unknown** release of Django.
I have a model for which I have not given any primary\_key. Django, consequently, automatically provides an AutoField that is called "id". Everything's fine with that. But now, I have to change the "verbose\_name" of that AutoField to something other than "id". I cannot override the "id" field the usual way, because that would require dropping/resetting the entire model and its data (which is strictly not an option). I cannot find another way around it. Does what I want even possible to achieve? If you may suggest any alternatives that would get me away with what I want without having to drop the model/table, I'd be happy.
|
Hmm... and what about explicitly write *id* field in the model definition? Like this for example:
```
class Entry(models.Model):
id = models.AutoField(verbose_name="custom name")
# and other fields...
```
It doesn't require any underlying database changes.
|
258,769 |
<p>My link is here:</p>
<p><a href="http://tinyurl.com/5kr4ra" rel="nofollow noreferrer">Example Page</a></p>
<p>I'm using list-style-image: to give my horizontal lists ( very top and bottom ) seperators. I have a class of .first to remove the image from the first li in each list.</p>
<p>Lo and behold in IE6, it doesn't work. What happens is that the bullet images are not being displayed, and also the bottom few pixels of the text appears to be cropped.</p>
<p><a href="http://tinyurl.com/66hcso" rel="nofollow noreferrer">Screenshot</a></p>
<p>I've fixed a few 'haslayout' bugs with this page, but I have a feeling its something to do with my rule hierarchy, although no amount of hacking about seems to work for me.</p>
<p>Can someone shed some light on this perhaps? Thanks.</p>
<p>Also, my colour change works on hover, but not the underline, in the same selector?</p>
<p><strong>EDIT</strong> OK, I have used the background image technique that yoavf suggests, which seems to do the trick, but the cropping issue still remains. Looks like a separate issue then...</p>
<p>heres my revised CSS</p>
<pre><code>#site-navigation li {
background-image:url(../img/site-nav-seperator.gif);
background-position:0 4px;
background-repeat:no-repeat;
float:left;
padding-left:15px;
}
#site-navigation li.first {
background-image:none;
}
</code></pre>
<p><strong>further edit:</strong></p>
<p>Managed to fix the cropping too, by giving the a tag some line-height.</p>
<pre><code>#site-navigation a {
color:#666666;
display: block;
text-decoration:none;
margin-right: 1em;
line-height: 1.1em;
}
</code></pre>
<p>this bit feels like a bodge though :)</p>
|
[
{
"answer_id": 258844,
"author": "yoavf",
"author_id": 1011,
"author_profile": "https://Stackoverflow.com/users/1011",
"pm_score": 3,
"selected": true,
"text": "<p>I know this isn't really a solution, but I would recommend using <strong>background-image</strong> instead of <strong>list-style image</strong>.\nYou'll achive the same effect, and it will work in all browsers.</p>\n"
},
{
"answer_id": 258860,
"author": "Filini",
"author_id": 21162,
"author_profile": "https://Stackoverflow.com/users/21162",
"pm_score": 1,
"selected": false,
"text": "<p>Looks like a problem with margins and paddings of your objects inside site-navigation.</p>\n\n<p>If you showed your CSS for those elements, we could check it faster :)</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258769",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
My link is here:
[Example Page](http://tinyurl.com/5kr4ra)
I'm using list-style-image: to give my horizontal lists ( very top and bottom ) seperators. I have a class of .first to remove the image from the first li in each list.
Lo and behold in IE6, it doesn't work. What happens is that the bullet images are not being displayed, and also the bottom few pixels of the text appears to be cropped.
[Screenshot](http://tinyurl.com/66hcso)
I've fixed a few 'haslayout' bugs with this page, but I have a feeling its something to do with my rule hierarchy, although no amount of hacking about seems to work for me.
Can someone shed some light on this perhaps? Thanks.
Also, my colour change works on hover, but not the underline, in the same selector?
**EDIT** OK, I have used the background image technique that yoavf suggests, which seems to do the trick, but the cropping issue still remains. Looks like a separate issue then...
heres my revised CSS
```
#site-navigation li {
background-image:url(../img/site-nav-seperator.gif);
background-position:0 4px;
background-repeat:no-repeat;
float:left;
padding-left:15px;
}
#site-navigation li.first {
background-image:none;
}
```
**further edit:**
Managed to fix the cropping too, by giving the a tag some line-height.
```
#site-navigation a {
color:#666666;
display: block;
text-decoration:none;
margin-right: 1em;
line-height: 1.1em;
}
```
this bit feels like a bodge though :)
|
I know this isn't really a solution, but I would recommend using **background-image** instead of **list-style image**.
You'll achive the same effect, and it will work in all browsers.
|
258,793 |
<p>I need to be able to compare some month names I have in an array.</p>
<p>It would be nice if there were some direct way like:</p>
<pre><code>Month.toInt("January") > Month.toInt("May")
</code></pre>
<p>My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it would have been already implemented in .Net, anyone done this before?</p>
|
[
{
"answer_id": 258814,
"author": "Adam Naylor",
"author_id": 17540,
"author_profile": "https://Stackoverflow.com/users/17540",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using c# 3.0 (or above) you can use extenders<br/><br/></p>\n"
},
{
"answer_id": 258828,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 9,
"selected": true,
"text": "<p><code>DateTime.ParseExact(monthName, \"MMMM\", CultureInfo.CurrentCulture ).Month</code></p>\n\n<p>Although, for your purposes, you'll probably be better off just creating a <code>Dictionary<string, int></code> mapping the month's name to its value.</p>\n"
},
{
"answer_id": 258833,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 5,
"selected": false,
"text": "<p>You could do something like this:</p>\n\n<pre><code>Convert.ToDate(month + \" 01, 1900\").Month\n</code></pre>\n"
},
{
"answer_id": 258836,
"author": "Rune Grimstad",
"author_id": 30366,
"author_profile": "https://Stackoverflow.com/users/30366",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the DateTime.Parse method to get a DateTime object and then check its Month property. Do something like this:</p>\n\n<pre><code>int month = DateTime.Parse(\"1.\" + monthName + \" 2008\").Month;\n</code></pre>\n\n<p>The trick is to build a valid date to create a DateTime object.</p>\n"
},
{
"answer_id": 258851,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 3,
"selected": false,
"text": "<p>You can use an enum of months:</p>\n\n<pre><code>public enum Month\n{\n January,\n February,\n // (...)\n December,\n} \n\npublic Month ToInt(Month Input)\n{\n return (int)Enum.Parse(typeof(Month), Input, true));\n}\n</code></pre>\n\n<p>I am not 100% certain on the syntax for enum.Parse(), though. </p>\n"
},
{
"answer_id": 258895,
"author": "Rasmus Faber",
"author_id": 5542,
"author_profile": "https://Stackoverflow.com/users/5542",
"pm_score": 4,
"selected": false,
"text": "<p>If you use the <code>DateTime.ParseExact()</code>-method that several people have suggested, you should carefully consider what you want to happen when the application runs in a non-English environment! </p>\n\n<p>In Denmark, which of <code>ParseExact(\"Januar\", ...)</code> and <code>ParseExact(\"January\", ...)</code> should work and which should fail? </p>\n\n<p>That will be the difference between <code>CultureInfo.CurrentCulture</code> and <code>CultureInfo.InvariantCulture</code>.</p>\n"
},
{
"answer_id": 4132642,
"author": "Thabiso",
"author_id": 501747,
"author_profile": "https://Stackoverflow.com/users/501747",
"pm_score": 2,
"selected": false,
"text": "<pre><code>Public Function returnMonthNumber(ByVal monthName As String) As Integer\n Select Case monthName.ToLower\n Case Is = \"january\"\n Return 1\n Case Is = \"february\"\n Return 2\n Case Is = \"march\"\n Return 3\n Case Is = \"april\"\n Return 4\n Case Is = \"may\"\n Return 5\n Case Is = \"june\"\n Return 6\n Case Is = \"july\"\n Return 7\n Case Is = \"august\"\n Return 8\n Case Is = \"september\"\n Return 9\n Case Is = \"october\"\n Return 10\n Case Is = \"november\"\n Return 11\n Case Is = \"december\"\n Return 12\n Case Else\n Return 0\n End Select\nEnd Function\n</code></pre>\n\n<p>caution code is in Beta version.</p>\n"
},
{
"answer_id": 12312505,
"author": "Ebenezer Ampiah",
"author_id": 1653844,
"author_profile": "https://Stackoverflow.com/users/1653844",
"pm_score": 0,
"selected": false,
"text": "<p>What I did was to use SimpleDateFormat to create a format string, and parse the text to a date, and then retrieve the month from that. The code is below:</p>\n\n<pre><code>int year = 2012 \\\\or any other year\nString monthName = \"January\" \\\\or any other month\nSimpleDateFormat format = new SimpleDateFormat(\"dd-MMM-yyyy\");\nint monthNumber = format.parse(\"01-\" + monthName + \"-\" + year).getMonth();\n</code></pre>\n"
},
{
"answer_id": 12547484,
"author": "Mark Seemann",
"author_id": 126014,
"author_profile": "https://Stackoverflow.com/users/126014",
"pm_score": 3,
"selected": false,
"text": "<p>You don't have to create a DateTime instance to do this. It's as simple as this:</p>\n\n<pre><code>public static class Month\n{\n public static int ToInt(this string month)\n {\n return Array.IndexOf(\n CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n month.ToLower(CultureInfo.CurrentCulture))\n + 1;\n }\n}\n</code></pre>\n\n<p>I'm running on the <code>da-DK</code> culture, so this unit test passes:</p>\n\n<pre><code>[Theory]\n[InlineData(\"Januar\", 1)]\n[InlineData(\"Februar\", 2)]\n[InlineData(\"Marts\", 3)]\n[InlineData(\"April\", 4)]\n[InlineData(\"Maj\", 5)]\n[InlineData(\"Juni\", 6)]\n[InlineData(\"Juli\", 7)]\n[InlineData(\"August\", 8)]\n[InlineData(\"September\", 9)]\n[InlineData(\"Oktober\", 10)]\n[InlineData(\"November\", 11)]\n[InlineData(\"December\", 12)]\npublic void Test(string monthName, int expected)\n{\n var actual = monthName.ToInt();\n Assert.Equal(expected, actual);\n}\n</code></pre>\n\n<p>I'll leave it as an exercise to the reader to create an overload where you can pass in an explicit CultureInfo.</p>\n"
},
{
"answer_id": 16174698,
"author": "Maria Carolina Araujo",
"author_id": 2312262,
"author_profile": "https://Stackoverflow.com/users/2312262",
"pm_score": 1,
"selected": false,
"text": "<p>I translate it into C# code in Spanish version, regards:</p>\n\n<pre><code>public string ObtenerNumeroMes(string NombreMes){\n\n string NumeroMes; \n\n switch(NombreMes) {\n\n case (\"ENERO\") :\n NumeroMes = \"01\";\n return NumeroMes;\n\n case (\"FEBRERO\") :\n NumeroMes = \"02\";\n return NumeroMes;\n\n case (\"MARZO\") :\n NumeroMes = \"03\";\n return NumeroMes;\n\n case (\"ABRIL\") :\n NumeroMes = \"04\";\n return NumeroMes;\n\n case (\"MAYO\") :\n NumeroMes = \"05\";\n return NumeroMes;\n\n case (\"JUNIO\") :\n NumeroMes = \"06\";\n return NumeroMes;\n\n case (\"JULIO\") :\n NumeroMes = \"07\";\n return NumeroMes;\n\n case (\"AGOSTO\") :\n NumeroMes = \"08\";\n return NumeroMes;\n\n case (\"SEPTIEMBRE\") :\n NumeroMes = \"09\";\n return NumeroMes;\n\n case (\"OCTUBRE\") :\n NumeroMes = \"10\";\n return NumeroMes;\n\n case (\"NOVIEMBRE\") :\n NumeroMes = \"11\";\n return NumeroMes;\n\n case (\"DICIEMBRE\") :\n NumeroMes = \"12\";\n return NumeroMes;\n\n default:\n Console.WriteLine(\"Error\");\n return \"ERROR\";\n\n }\n\n }\n</code></pre>\n"
},
{
"answer_id": 30089582,
"author": "Carlos A. Ortiz",
"author_id": 4872590,
"author_profile": "https://Stackoverflow.com/users/4872590",
"pm_score": 3,
"selected": false,
"text": "<p>One simply solution would be create a Dictionary with names and values. Then using Contains() you can find the right value.</p>\n\n<pre><code>Dictionary<string, string> months = new Dictionary<string, string>()\n{\n { \"january\", \"01\"},\n { \"february\", \"02\"},\n { \"march\", \"03\"},\n { \"april\", \"04\"},\n { \"may\", \"05\"},\n { \"june\", \"06\"},\n { \"july\", \"07\"},\n { \"august\", \"08\"},\n { \"september\", \"09\"},\n { \"october\", \"10\"},\n { \"november\", \"11\"},\n { \"december\", \"12\"},\n};\nforeach (var month in months)\n{\n if (StringThatContainsMonth.ToLower().Contains(month.Key))\n {\n string thisMonth = month.Value;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 30770498,
"author": "David Clarke",
"author_id": 132599,
"author_profile": "https://Stackoverflow.com/users/132599",
"pm_score": 2,
"selected": false,
"text": "<p>And answering this seven years after the question was asked, it is possible to do this comparison using built-in methods:</p>\n\n<pre><code>Month.toInt(\"January\") > Month.toInt(\"May\")\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n t => t.Equals(\"January\", StringComparison.CurrentCultureIgnoreCase)) >\nArray.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n t => t.Equals(\"May\", StringComparison.CurrentCultureIgnoreCase))\n</code></pre>\n\n<p>Which can be refactored into an extension method for simplicity. The following is a LINQPad example (hence the <code>Dump()</code> method calls):</p>\n\n<pre><code>void Main()\n{\n (\"January\".GetMonthIndex() > \"May\".GetMonthIndex()).Dump();\n (\"January\".GetMonthIndex() == \"january\".GetMonthIndex()).Dump();\n (\"January\".GetMonthIndex() < \"May\".GetMonthIndex()).Dump();\n}\n\npublic static class Extension {\n public static int GetMonthIndex(this string month) {\n return Array.FindIndex( CultureInfo.CurrentCulture.DateTimeFormat.MonthNames,\n t => t.Equals(month, StringComparison.CurrentCultureIgnoreCase));\n }\n}\n</code></pre>\n\n<p>With output:</p>\n\n<pre><code>False\nTrue\nTrue\n</code></pre>\n"
},
{
"answer_id": 58725406,
"author": "Nitika Chopra",
"author_id": 7534013,
"author_profile": "https://Stackoverflow.com/users/7534013",
"pm_score": 0,
"selected": false,
"text": "<p>This code helps you...</p>\n\n<pre><code>using System.Globalization;\n\n....\n\nstring FullMonthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(DateTime.UtcNow.Month);\n</code></pre>\n\n<p>GetMonthName Method - it returns string...</p>\n\n<p>If you want to get a month as an integer, then simply use - </p>\n\n<pre><code>DateTime dt= DateTime.UtcNow;\nint month= dt.Month;\n</code></pre>\n\n<p>I hope, it helps you!!!</p>\n\n<p>Thanks!!!</p>\n"
},
{
"answer_id": 67821590,
"author": "user15276771",
"author_id": 15276771,
"author_profile": "https://Stackoverflow.com/users/15276771",
"pm_score": 0,
"selected": false,
"text": "<pre><code>int selectedValue = 0;\n switch (curentMonth)\n {\n case "January":\n selectedValue = 1;\n break;\n case "February":\n selectedValue = 2;\n break;\n }\n if (selectedValue != 0)\n {\n /* var list= db.model_name.Where(x => x.column== selectedValue);\n return list; */\n }\n return Ok(selectedValue);\n</code></pre>\n"
},
{
"answer_id": 74273272,
"author": "RARE Kpop Manifesto",
"author_id": 14672114,
"author_profile": "https://Stackoverflow.com/users/14672114",
"pm_score": 0,
"selected": false,
"text": "<p>This code is for <code>awk</code>, but easily adaptable to <code>C/C++/C#</code></p>\n<p>— <em>in <code>awk</code>, all indices are <code>"1-based"</code> instead of <code>"0-based"</code> - the leading edge <code>"="</code> of the reference string is simply pre-shifting the positions. remove that <code>"="</code> for any 0-based languages`</em></p>\n<pre><code>function __(_) { # input - Eng. month names, any casing, min. 3 letters\n # output - MM : [01-12], zero-padded\n return \\\n ((_=toupper(_)) ~ "^[OND]" ? "" : _<_) \\\n (index("=ANEBARPRAYUNULUGEPCTOVEC", substr(_ "",_+=_^=_<_,_))/_)\n}\n</code></pre>\n<p>The reference string might look odd at first -</p>\n<blockquote>\n<p><code>the 2nd + 3rd letters of month names constitute a unique set</code></p>\n</blockquote>\n<p>So OP can input the english name of the months, full or abbreviated, and it'll return a zero-padded 2-digit month number. If you need it to be in integer form, then just scrub out the middle line that performs the padding.</p>\n<p>You'll notice only 1 input variable declared and no other temp variables whatsoever - one of <code>awk</code>'s major strengths is its <em><strong>extreme</strong></em> agility when it comes to dynamic typing of variables,\neven for truly illogical operations like taking the <code>"0th-power"</code> of a <code>string</code> variable like</p>\n<blockquote>\n<pre><code>"Boston" ^ 0 \n</code></pre>\n</blockquote>\n<p>This would seamlessly coerce that variable to a <code>numeric</code> data type, with a new value of <code>1</code>.</p>\n<p>This flexibility enables the recycling and re-using of the input temp variable(s) for <em><strong>any</strong></em> other purpose the moment the original input value(s) is/are no longer needed.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21367/"
] |
I need to be able to compare some month names I have in an array.
It would be nice if there were some direct way like:
```
Month.toInt("January") > Month.toInt("May")
```
My Google searching seems to suggest the only way is to write your own method, but this seems like a common enough problem that I would think it would have been already implemented in .Net, anyone done this before?
|
`DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month`
Although, for your purposes, you'll probably be better off just creating a `Dictionary<string, int>` mapping the month's name to its value.
|
258,807 |
<p>I've got 2 remote databases as part of a query </p>
<pre><code>select p.ID,p.ProjectCode_VC,p.Name_VC,v.*
FROM [serverB].Projects.dbo.Projects_T p
LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on
p.ProjectCode_VC = v.PROJ_CODE
</code></pre>
<p>The problem is that serverA uses collation <code>Latin1_General_BIN</code> and serverB uses <code>Latin1_General_CP1_CP_AS</code> and the query refuses to run. </p>
<p>Both servers are SQL 2000 servers. Both databases are set in stone so I cannot change their collations, unfortunately. </p>
<p>Is there anyway you guys know how to get this to work?</p>
<p><strong>Update:</strong> I found an alternative solution. In the Linked Server Properties, you can specify the linked server's collation there.</p>
|
[
{
"answer_id": 258855,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 4,
"selected": true,
"text": "<p>Just add the collation to your select, like:</p>\n\n<pre><code>select \n p.ID,\n p.ProjectCode_VC,\n p.Name_VC,\n v.* \nFROM\n [serverB].Projects.dbo.Projects_T p \n LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on p.ProjectCode_VC \n collate Latin1_General_Bin = v.PROJ_CODE\n</code></pre>\n\n<p>or the other way around. So \"convert\" one of the collations to the other.</p>\n"
},
{
"answer_id": 8045282,
"author": "djoko soewarno",
"author_id": 1034834,
"author_profile": "https://Stackoverflow.com/users/1034834",
"pm_score": 2,
"selected": false,
"text": "<p>Or you can use a more generic query like this:</p>\n\n<pre><code>select * from profile, userinfo\nwhere profile.custid collate database_default = userinfo.custid collate database_default\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2995/"
] |
I've got 2 remote databases as part of a query
```
select p.ID,p.ProjectCode_VC,p.Name_VC,v.*
FROM [serverB].Projects.dbo.Projects_T p
LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on
p.ProjectCode_VC = v.PROJ_CODE
```
The problem is that serverA uses collation `Latin1_General_BIN` and serverB uses `Latin1_General_CP1_CP_AS` and the query refuses to run.
Both servers are SQL 2000 servers. Both databases are set in stone so I cannot change their collations, unfortunately.
Is there anyway you guys know how to get this to work?
**Update:** I found an alternative solution. In the Linked Server Properties, you can specify the linked server's collation there.
|
Just add the collation to your select, like:
```
select
p.ID,
p.ProjectCode_VC,
p.Name_VC,
v.*
FROM
[serverB].Projects.dbo.Projects_T p
LEFT JOIN [serverA].SOCON.dbo.vw_PROJECT v on p.ProjectCode_VC
collate Latin1_General_Bin = v.PROJ_CODE
```
or the other way around. So "convert" one of the collations to the other.
|
258,812 |
<p>I've created a Silverlight project that produces [something].xap file to package a few silverlight UserControls. I would like to manipulate that .xap file through the use of javascript in the browser to show and hide user controls based upon java script events.</p>
<p>Is it possible to do this?</p>
<p>If so any sample could or links to documentation would be appreciated.</p>
<p>Thanks in advance</p>
<p>Kevin</p>
|
[
{
"answer_id": 258940,
"author": "Aaron Fischer",
"author_id": 5618,
"author_profile": "https://Stackoverflow.com/users/5618",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a my collections of my links for this subject.</p>\n\n<ul>\n<li><a href=\"http://weblogs.asp.net/albertpascual/archive/2008/08/13/javascript-communication-to-silverlight-2-0.aspx\" rel=\"nofollow noreferrer\">Javascript communication to\nSilverlight 2.0</a></li>\n<li><a href=\"http://www.wilcob.com/Wilco/Articles/silverlight-interoperability.aspx\" rel=\"nofollow noreferrer\">Silverlight\ninteroperability</a></li>\n<li><a href=\"http://pietschsoft.com/post/2008/06/Silverlight-and-JavaScript-Interop-Basics.aspx\" rel=\"nofollow noreferrer\">Silverlight\nand JavaScript Interop Basics</a></li>\n</ul>\n"
},
{
"answer_id": 259144,
"author": "Kevin",
"author_id": 2723,
"author_profile": "https://Stackoverflow.com/users/2723",
"pm_score": 1,
"selected": false,
"text": "<p>Here's my solution...not sure if it's the \"best-practices\" way...comments????</p>\n\n<p>In the App class within my Silverlight application I have the following code:</p>\n\n<pre><code> private Page _page = null;\n private void Application_Startup(object sender, StartupEventArgs e)\n {\n _page = new Page();\n this.RootVisual = _page;\n\n HtmlPage.RegisterScriptableObject(\"App\", this);\n }\n</code></pre>\n\n<p>Also to the App class I add a [ScriptableMember] to be called from JavaScript</p>\n\n<pre><code> [ScriptableMember]\n public void ShowTeamSearch(Guid ctxId, Guid teamId)\n {\n _page.ShowTeamSearcher(ctxId, teamId);\n }\n</code></pre>\n\n<p>The Page class is the default one that get's created within the Silverlight Control project, it really doesn't have any UI or logic, it's just used to swap in/out the views.</p>\n\n<pre><code> Login oLogin;\n TeamSearcher oSearcher;\n\n public Page()\n {\n InitializeComponent();\n oLogin = new Login();\n oSearcher = new TeamSearcher();\n\n oLogin.Visibility = Visibility;\n this.LayoutRoot.Children.Add(oLogin);\n }\n</code></pre>\n\n<p>Also a method is added to show/hide the views...this could/will probably get more advanced/robust with animations etc...but this shows the basic idea:</p>\n\n<pre><code> public void ShowTeamSearcher(Guid ctxId, Guid teamId)\n {\n oSearcher.UserTeamId = teamId;\n oSearcher.UserContextId = ctxId;\n\n LayoutRoot.Children.Remove(oLogin);\n LayoutRoot.Children.Add(oSearcher);\n }\n</code></pre>\n\n<p>Then to invoke this in the JavaScript after assigning the id of oXaml to the instance of the silverlight host.</p>\n\n<pre><code> var slControl = document.getElementById('oXaml');\n slControl.Content.App.ShowTeamSearch(sessionId, teamId); \n</code></pre>\n\n<p>This seems to work and isn't all that bad of a solution, but there might be something better...thoughts?</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
] |
I've created a Silverlight project that produces [something].xap file to package a few silverlight UserControls. I would like to manipulate that .xap file through the use of javascript in the browser to show and hide user controls based upon java script events.
Is it possible to do this?
If so any sample could or links to documentation would be appreciated.
Thanks in advance
Kevin
|
Here's my solution...not sure if it's the "best-practices" way...comments????
In the App class within my Silverlight application I have the following code:
```
private Page _page = null;
private void Application_Startup(object sender, StartupEventArgs e)
{
_page = new Page();
this.RootVisual = _page;
HtmlPage.RegisterScriptableObject("App", this);
}
```
Also to the App class I add a [ScriptableMember] to be called from JavaScript
```
[ScriptableMember]
public void ShowTeamSearch(Guid ctxId, Guid teamId)
{
_page.ShowTeamSearcher(ctxId, teamId);
}
```
The Page class is the default one that get's created within the Silverlight Control project, it really doesn't have any UI or logic, it's just used to swap in/out the views.
```
Login oLogin;
TeamSearcher oSearcher;
public Page()
{
InitializeComponent();
oLogin = new Login();
oSearcher = new TeamSearcher();
oLogin.Visibility = Visibility;
this.LayoutRoot.Children.Add(oLogin);
}
```
Also a method is added to show/hide the views...this could/will probably get more advanced/robust with animations etc...but this shows the basic idea:
```
public void ShowTeamSearcher(Guid ctxId, Guid teamId)
{
oSearcher.UserTeamId = teamId;
oSearcher.UserContextId = ctxId;
LayoutRoot.Children.Remove(oLogin);
LayoutRoot.Children.Add(oSearcher);
}
```
Then to invoke this in the JavaScript after assigning the id of oXaml to the instance of the silverlight host.
```
var slControl = document.getElementById('oXaml');
slControl.Content.App.ShowTeamSearch(sessionId, teamId);
```
This seems to work and isn't all that bad of a solution, but there might be something better...thoughts?
|
258,824 |
<p>I have a window which overrides a <code>RadioButton</code>'s <code>ControlTemplate</code> to show a custom control inside of it. Inside the custom control, I have a button's visibility tied to <code>IsMouseOver</code>, which works correctly in showing the button only when the mouse is hovering over the control. However, when I click on the <code>RadioButton</code>, the <code>Button</code> disappears. After some debugging and reading, it seems that the <code>RadioButton</code> is capturing the mouse on click, and this makes <code>IsMouseOver</code> for the <code>UserControl</code> false.</p>
<p>I tried binding the <code>Button</code>'s visibility to <code>FindAncestor {x:Type RadioButton}</code> and it works, but it seems a bit fragile to me to have the <code>UserControl</code> depend on who is containing it. The code for the window and the user control is below. Any suggestions?</p>
<pre><code><Window x:Name="window" x:Class="WPFTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPFTest="clr-namespace:WPFTest"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style TargetType="{x:Type RadioButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<WPFTest:TestUC />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Border BorderBrush="Black" BorderThickness="2">
<StackPanel>
<RadioButton x:Name="OptionButton" Height="100" />
<TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}" />
</StackPanel>
</Border>
</Window>
<UserControl x:Name="_this" x:Class="WPFTest.TestUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</UserControl.Resources>
<StackPanel>
<TextBlock Text="SomeText" />
<TextBlock Text="{Binding ElementName=_this, Path=IsMouseOver}" />
<Button x:Name="_cancelTextBlock" Content="Cancel" Visibility="{Binding ElementName=_this, Path=IsMouseOver, Converter={StaticResource BooleanToVisibilityConverter}}" />
</StackPanel>
</UserControl>
</code></pre>
|
[
{
"answer_id": 258935,
"author": "DavidN",
"author_id": 33662,
"author_profile": "https://Stackoverflow.com/users/33662",
"pm_score": 2,
"selected": true,
"text": "<p>I seemed to have fixed the problem by setting a trigger in the control template, which binds to the RadioButton's IsMouseOver, and sets a custom DependencyProperty on the UserControl. </p>\n\n<p>Something like: </p>\n\n<pre><code><ControlTemplate TargetType=\"{x:Type RadioButton}\">\n <WPFTest:TestUC x:Name=\"UC\" />\n <ControlTemplate.Triggers>\n <Trigger Property=\"IsMouseOver\" Value=\"True\">\n <Setter Property=\"ShowCancel\" Value=\"True\" TargetName=\"UC\"/>\n </Trigger>\n </ControlTemplate.Triggers>\n</ControlTemplate>\n</code></pre>\n\n<p>I'm still confused as to why the Mouse Capture falsifies IsMouseOver on the UserControl child of the RadioButton however. Can anyone shed some light on this? </p>\n"
},
{
"answer_id": 259178,
"author": "cplotts",
"author_id": 22294,
"author_profile": "https://Stackoverflow.com/users/22294",
"pm_score": 0,
"selected": false,
"text": "<p>Very interesting problem. I myself would like to know more of why the UserControl IsMouseOver changes to false when the TextBlock(s) in its visuals are mouse downed upon.</p>\n\n<p>However, here is another way to solve it ... maybe you will like this approach better.</p>\n\n<p><strong>Instead of using RadioButton (since you are retemplating it) why don't you just use Control?</strong> (I think IsMouseOver is getting changed to false due to the fact that it is a Button derived control.)</p>\n\n<p>Following is the xaml for the Window ...</p>\n\n<pre><code><Window\n x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\"\n Width=\"300\"\n Height=\"300\"\n>\n <Window.Resources>\n <Style TargetType=\"{x:Type Control}\">\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"{x:Type Control}\">\n <local:UserControl1/>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n </Window.Resources>\n\n <Border BorderBrush=\"Black\" BorderThickness=\"2\">\n <StackPanel>\n <Control x:Name=\"OptionButton\" Height=\"100\"/>\n <TextBlock Text=\"{Binding ElementName=OptionButton, Path=IsMouseOver}\"/>\n </StackPanel>\n </Border>\n</Window>\n</code></pre>\n\n<h3>EDIT:</h3>\n\n<p>I just wanted to add ... that if you're okay with the above approach ... then, the right thing to do is probably to just use the UserControl in the Window's visual tree versus retemplating a Control. So ... like this:</p>\n\n<pre><code><Window\n x:Class=\"WpfApplication1.Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:WpfApplication1\"\n Title=\"Window1\"\n Width=\"300\"\n Height=\"300\"\n>\n <Border BorderBrush=\"Black\" BorderThickness=\"2\">\n <StackPanel>\n <local:UserControl1 x:Name=\"OptionButton\" Height=\"100\"/>\n <TextBlock Text=\"{Binding ElementName=OptionButton, Path=IsMouseOver}\"/>\n </StackPanel>\n </Border>\n</Window>\n</code></pre>\n"
},
{
"answer_id": 376999,
"author": "sirrocco",
"author_id": 5246,
"author_profile": "https://Stackoverflow.com/users/5246",
"pm_score": 1,
"selected": false,
"text": "<p>After the event is handled by the RadioButton , it is only <em>set</em> as handled but in reality it still bubbles up. So you just need to specify that you want to handle handled events too.</p>\n\n<p>For that you need to look at <a href=\"http://www.google.ro/search?hl=ro&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=xUW&q=handledEventsToo&btnG=C%C4%83utare&meta=\" rel=\"nofollow noreferrer\">handledEventsToo</a>.</p>\n\n<p>Unfortunately I don't think it can be set in xaml. only code.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33662/"
] |
I have a window which overrides a `RadioButton`'s `ControlTemplate` to show a custom control inside of it. Inside the custom control, I have a button's visibility tied to `IsMouseOver`, which works correctly in showing the button only when the mouse is hovering over the control. However, when I click on the `RadioButton`, the `Button` disappears. After some debugging and reading, it seems that the `RadioButton` is capturing the mouse on click, and this makes `IsMouseOver` for the `UserControl` false.
I tried binding the `Button`'s visibility to `FindAncestor {x:Type RadioButton}` and it works, but it seems a bit fragile to me to have the `UserControl` depend on who is containing it. The code for the window and the user control is below. Any suggestions?
```
<Window x:Name="window" x:Class="WPFTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WPFTest="clr-namespace:WPFTest"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<Style TargetType="{x:Type RadioButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type RadioButton}">
<WPFTest:TestUC />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Border BorderBrush="Black" BorderThickness="2">
<StackPanel>
<RadioButton x:Name="OptionButton" Height="100" />
<TextBlock Text="{Binding ElementName=OptionButton, Path=IsMouseOver}" />
</StackPanel>
</Border>
</Window>
<UserControl x:Name="_this" x:Class="WPFTest.TestUC"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</UserControl.Resources>
<StackPanel>
<TextBlock Text="SomeText" />
<TextBlock Text="{Binding ElementName=_this, Path=IsMouseOver}" />
<Button x:Name="_cancelTextBlock" Content="Cancel" Visibility="{Binding ElementName=_this, Path=IsMouseOver, Converter={StaticResource BooleanToVisibilityConverter}}" />
</StackPanel>
</UserControl>
```
|
I seemed to have fixed the problem by setting a trigger in the control template, which binds to the RadioButton's IsMouseOver, and sets a custom DependencyProperty on the UserControl.
Something like:
```
<ControlTemplate TargetType="{x:Type RadioButton}">
<WPFTest:TestUC x:Name="UC" />
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="ShowCancel" Value="True" TargetName="UC"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
```
I'm still confused as to why the Mouse Capture falsifies IsMouseOver on the UserControl child of the RadioButton however. Can anyone shed some light on this?
|
258,857 |
<p>In C#, how do I set the Identity of a Thread?</p>
<p>For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?</p>
<p>Or is this not possible?</p>
|
[
{
"answer_id": 258884,
"author": "dove",
"author_id": 30913,
"author_profile": "https://Stackoverflow.com/users/30913",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, using <a href=\"http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx\" rel=\"nofollow noreferrer\">impersonation</a> literally</p>\n\n<pre><code>using (new Impersonation())\n{\n // your elevated code\n}\n</code></pre>\n\n<p>and the class is as follows, for settings I use castle dictionary adaptor if it looks strange.</p>\n\n<pre><code>[PermissionSet(SecurityAction.Demand, Name = \"FullTrust\")]\npublic class Impersonation : IDisposable\n{\n private readonly SafeTokenHandle _handle;\n private readonly WindowsImpersonationContext _context;\n\n //const int Logon32LogonNewCredentials = 9; \n private const int Logon32LogonInteractive = 2;\n\n public Impersonation()\n {\n var settings = Settings.Instance.Whatever;\n var domain = settings.Domain;\n var username = settings.User;\n var password = settings.Password;\n var ok = LogonUser(username, domain, password, Logon32LogonInteractive, 0, out _handle);\n if (!ok)\n {\n var errorCode = Marshal.GetLastWin32Error();\n throw new ApplicationException(string.Format(\"Could not impersonate the elevated user. LogonUser returned error code {0}.\", errorCode));\n }\n _context = WindowsIdentity.Impersonate(_handle.DangerousGetHandle());\n }\n\n public void Dispose()\n {\n _context.Dispose();\n _handle.Dispose();\n }\n\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\n private static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);\n\n public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n private SafeTokenHandle()\n : base(true)\n { }\n\n [DllImport(\"kernel32.dll\")]\n [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]\n [SuppressUnmanagedCodeSecurity]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool CloseHandle(IntPtr handle);\n\n protected override bool ReleaseHandle()\n {\n return CloseHandle(handle);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 259167,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 6,
"selected": true,
"text": "<p>You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits from <a href=\"https://msdn.microsoft.com/en-us/library/system.security.principal.iidentity(v=vs.110).aspx\" rel=\"noreferrer\">System.Security.Principal.IIdentity</a>, but you need a class that inherits from <a href=\"https://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal(v=vs.110).aspx\" rel=\"noreferrer\">System.Security.Principal.IPrincipal</a> that takes the type of Identity you are using.<br /> For simplicity sake the .Net framework provides <a href=\"https://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal(v=vs.110).aspx\" rel=\"noreferrer\">GenericPrincipal</a> and <a href=\"https://msdn.microsoft.com/en-us/library/system.security.principal.genericidentity(v=vs.110).aspx\" rel=\"noreferrer\">GenericIdentity</a> classes which can be used like this:</p>\n\n<pre><code> using System.Security.Principal;\n\n // ...\n GenericIdentity identity = new GenericIdentity(\"M.Brown\");\n identity.IsAuthenticated = true;\n\n // ...\n System.Threading.Thread.CurrentPrincipal =\n new GenericPrincipal(\n identity,\n new string[] { \"Role1\", \"Role2\" }\n );\n\n //...\n if (!System.Threading.Thread.CurrentPrincipal.IsInRole(\"Role1\"))\n {\n Console.WriteLine(\"Permission denied\");\n return;\n }\n</code></pre>\n\n<p>This won't however give you windows rights to stuff using the new identity. But it can be useful if you are developing a web site and want to create your own user management.</p>\n\n<p>If you want to pretend to be a different Windows user than the account you are currently using then you need to use impersonation. An example of how to do this can be found in the Help for <a href=\"http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx\" rel=\"noreferrer\">System.Security.Principal.WindowsIdentity.Impersonate()</a>. There are limitations about which accounts the account you are running under can impersonate.</p>\n\n<p>In some cases the .Net framework does impersonation for you. One example of where this occurs is if you are developing a ASP.Net web site and you have Integrated Windows Authentication switched on for the virtual directory or site you are running in.</p>\n"
},
{
"answer_id": 32156975,
"author": "Hakan Fıstık",
"author_id": 4390133,
"author_profile": "https://Stackoverflow.com/users/4390133",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Update for the accepted answer [apply ONLY on .NET framework 4.5 and above]</strong><br/>\nIn <code>.NET 4.5</code> the property <code>IsAuthenticated</code> has no set accessor, so you can not set it directly as the accepted answer doing. <br/>You can use the following code for setting that property.</p>\n\n<pre><code>GenericIdentity identity = new GenericIdentity(\"someuser\", \"Forms\");\nThread.CurrentPrincipal = new GenericPrincipal(identity, new string[] { \"somerole\" });\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] |
In C#, how do I set the Identity of a Thread?
For example, if I have Thread MyThread, which is already started, can I change MyThread's Identity?
Or is this not possible?
|
You can set the Identity of a thread by creating a new Principal. You can use any Identity that inherits from [System.Security.Principal.IIdentity](https://msdn.microsoft.com/en-us/library/system.security.principal.iidentity(v=vs.110).aspx), but you need a class that inherits from [System.Security.Principal.IPrincipal](https://msdn.microsoft.com/en-us/library/system.security.principal.iprincipal(v=vs.110).aspx) that takes the type of Identity you are using.
For simplicity sake the .Net framework provides [GenericPrincipal](https://msdn.microsoft.com/en-us/library/system.security.principal.genericprincipal(v=vs.110).aspx) and [GenericIdentity](https://msdn.microsoft.com/en-us/library/system.security.principal.genericidentity(v=vs.110).aspx) classes which can be used like this:
```
using System.Security.Principal;
// ...
GenericIdentity identity = new GenericIdentity("M.Brown");
identity.IsAuthenticated = true;
// ...
System.Threading.Thread.CurrentPrincipal =
new GenericPrincipal(
identity,
new string[] { "Role1", "Role2" }
);
//...
if (!System.Threading.Thread.CurrentPrincipal.IsInRole("Role1"))
{
Console.WriteLine("Permission denied");
return;
}
```
This won't however give you windows rights to stuff using the new identity. But it can be useful if you are developing a web site and want to create your own user management.
If you want to pretend to be a different Windows user than the account you are currently using then you need to use impersonation. An example of how to do this can be found in the Help for [System.Security.Principal.WindowsIdentity.Impersonate()](http://msdn.microsoft.com/en-us/library/chf6fbt4.aspx). There are limitations about which accounts the account you are running under can impersonate.
In some cases the .Net framework does impersonation for you. One example of where this occurs is if you are developing a ASP.Net web site and you have Integrated Windows Authentication switched on for the virtual directory or site you are running in.
|
258,858 |
<p>I'm dynamically generating an asp form, and I would like to add the <strong>label</strong> and <strong>input</strong> elements inside a list.</p>
<p>For example, I would like to end up with something like:</p>
<pre><code><ul>
<li><label for="input"/><input id=input"/></li>
</ul>
</code></pre>
<p>To do this, I create a Label object and a TextBox object, then assign the AssociatedControlId property of the Label to link these. But I cannot add any of these in a ListItem, nor can I add these in the Controls collection of BulletedList...</p>
<p>Any ideas would be greatly apreciated.</p>
|
[
{
"answer_id": 259043,
"author": "Michael DeLorenzo",
"author_id": 1383003,
"author_profile": "https://Stackoverflow.com/users/1383003",
"pm_score": 0,
"selected": false,
"text": "<p>You could probably do something like this using a Repeater. </p>\n\n<pre><code><asp:Repeater ID=\"rpt\" runat=\"server\">\n <HeaderTemplate>\n <ul>\n </HeaderTemplate>\n <ItemTemplate>\n <li>\n <label for='<%# string.Format(\"ctrl-{0}\", Container.ItemIndex) %>'>label for ctrl #<%# Container.ItemIndex %></label>\n <input id='<%# string.Format(\"ctrl-{0}\", Container.ItemIndex) %>' type=\"text\" /> \n </li>\n </ItemTemplate>\n <FooterTemplate>\n </ul>\n </FooterTemplate>\n</asp:Repeater>\n</code></pre>\n\n<p>If you need to add server controls to the list, you'll need to do something with the Repeater's ItemDataBound event.</p>\n"
},
{
"answer_id": 261020,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 3,
"selected": true,
"text": "<p>The System.Web.UI.HtmlControls namespace has some useful controls.</p>\n\n<p>In your aspx:</p>\n\n<pre><code><asp:PlaceHolder ID=\"PlaceHolder1\" runat=\"server\" />\n</code></pre>\n\n<p>In your code behind:</p>\n\n<pre><code>HtmlGenericControl list = new HtmlGenericControl(\"ul\");\nfor (int i = 0; i < 10; i++)\n{\n HtmlGenericControl listItem = new HtmlGenericControl(\"li\");\n Label textLabel = new Label();\n textLabel.Text = String.Format(\"Label {0}\", i);\n listItem.Controls.Add(textLabel);\n // etc...\n list.Controls.Add(listItem);\n}\nPlaceHolder1.Controls.Add(list);\n</code></pre>\n\n<p>Works like a charm.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/920/"
] |
I'm dynamically generating an asp form, and I would like to add the **label** and **input** elements inside a list.
For example, I would like to end up with something like:
```
<ul>
<li><label for="input"/><input id=input"/></li>
</ul>
```
To do this, I create a Label object and a TextBox object, then assign the AssociatedControlId property of the Label to link these. But I cannot add any of these in a ListItem, nor can I add these in the Controls collection of BulletedList...
Any ideas would be greatly apreciated.
|
The System.Web.UI.HtmlControls namespace has some useful controls.
In your aspx:
```
<asp:PlaceHolder ID="PlaceHolder1" runat="server" />
```
In your code behind:
```
HtmlGenericControl list = new HtmlGenericControl("ul");
for (int i = 0; i < 10; i++)
{
HtmlGenericControl listItem = new HtmlGenericControl("li");
Label textLabel = new Label();
textLabel.Text = String.Format("Label {0}", i);
listItem.Controls.Add(textLabel);
// etc...
list.Controls.Add(listItem);
}
PlaceHolder1.Controls.Add(list);
```
Works like a charm.
|
258,864 |
<p>When an <code>Expression<T></code> is compiled, is the resultant code implicitly cached by the framework? I'm thinking along the lines of the static <code>Regex</code> methods where the framework implicitly compiles and caches the last few regexes.</p>
<p>If compiled <code>Expression<T></code> objects are <b>not</b> cached, can you recommend some best practices for keeping the compile-time down or any gotchas that could cause problems if I manually cache an expression?</p>
<pre><code>public MyResultType DoSomething(int arg1, int arg2)
{
var result = invokeHandler(
(IDoSomethingHandler h) => h.DoSomething(arg1, arg2)
);
return result;
}
private TResult invokeHandler<T, TResult>(Expression<Func<T, TResult>> action)
where T : class
{
// Here, I might want to check to see if action is already cached.
var compiledAction = action.Compile();
var methodCallExpr = action as MethodCallExpression;
// Here, I might want to store methodCallExpr in a cache somewhere.
var handler = ServiceLocator.Current.GetInstance<T>();
var result = compiledAction(handler);
return result;
}
</code></pre>
<p>In this example, I'm slightly concerned that if I cache the compiled expression, that it will use the values of <code>arg1</code> and <code>arg2</code> as they were at the time the expression was compiled, rather than retrieving those values from the appropriate place in the stack (i.e. rather than getting the current values).</p>
|
[
{
"answer_id": 258907,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<p>No; I do not believe that it is; if you want it cached, you must hold onto the <code>Delegate</code> reference (typically <code>Func<...></code> or <code>Action<...></code>). Likewise, if you want to get the best performance, you would compile it as a parameterised expression, so you can send in different values when you invoke it.</p>\n\n<p>In this case, re-phrasing would help:</p>\n\n<pre><code>public MyResultType DoSomething(int arg1, int arg2)\n{\n var result = invokeHandler(\n (IDoSomethingHandler h, int a1, int a2) => h.DoSomething(a1, a2),\n arg1, arg2);\n return result;\n}\n\nprivate TResult invokeHandler<T, TResult>(Expression<Func<T,int,int,TResult>> action,\n int arg1, int arg2)\n where T : class\n{\n // Here, I might want to check to see if action is already cached.\n\n var compiledAction = action.Compile();\n var methodCallExpr = action as MethodCallExpression;\n\n // Here, I might want to store methodCallExpr in a cache somewhere.\n\n var handler = ServiceLocator.Current.GetInstance<T>();\n var result = compiledAction(handler, arg1, arg2);\n\n return result;\n}\n</code></pre>\n\n<p>i.e. make the numbers parameters of the expression, and pass the <em>actual</em> ones it at runtime (rather than being constants in the expression).</p>\n"
},
{
"answer_id": 258911,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 2,
"selected": false,
"text": "<p>Lambda experssions are not cached automatically. You will need to implement you own caching/memoization algorithms for that. Check the related Stackoverflow question:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/66382/is-it-possible-to-cache-a-value-evaluated-in-a-lambda-expression-c-linq\">Is it possible to cache a value evaluated in a lambda expression?</a></p>\n\n<p>It is important to note that lambda expressions are lazy evaluated in C#.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30321/"
] |
When an `Expression<T>` is compiled, is the resultant code implicitly cached by the framework? I'm thinking along the lines of the static `Regex` methods where the framework implicitly compiles and caches the last few regexes.
If compiled `Expression<T>` objects are **not** cached, can you recommend some best practices for keeping the compile-time down or any gotchas that could cause problems if I manually cache an expression?
```
public MyResultType DoSomething(int arg1, int arg2)
{
var result = invokeHandler(
(IDoSomethingHandler h) => h.DoSomething(arg1, arg2)
);
return result;
}
private TResult invokeHandler<T, TResult>(Expression<Func<T, TResult>> action)
where T : class
{
// Here, I might want to check to see if action is already cached.
var compiledAction = action.Compile();
var methodCallExpr = action as MethodCallExpression;
// Here, I might want to store methodCallExpr in a cache somewhere.
var handler = ServiceLocator.Current.GetInstance<T>();
var result = compiledAction(handler);
return result;
}
```
In this example, I'm slightly concerned that if I cache the compiled expression, that it will use the values of `arg1` and `arg2` as they were at the time the expression was compiled, rather than retrieving those values from the appropriate place in the stack (i.e. rather than getting the current values).
|
No; I do not believe that it is; if you want it cached, you must hold onto the `Delegate` reference (typically `Func<...>` or `Action<...>`). Likewise, if you want to get the best performance, you would compile it as a parameterised expression, so you can send in different values when you invoke it.
In this case, re-phrasing would help:
```
public MyResultType DoSomething(int arg1, int arg2)
{
var result = invokeHandler(
(IDoSomethingHandler h, int a1, int a2) => h.DoSomething(a1, a2),
arg1, arg2);
return result;
}
private TResult invokeHandler<T, TResult>(Expression<Func<T,int,int,TResult>> action,
int arg1, int arg2)
where T : class
{
// Here, I might want to check to see if action is already cached.
var compiledAction = action.Compile();
var methodCallExpr = action as MethodCallExpression;
// Here, I might want to store methodCallExpr in a cache somewhere.
var handler = ServiceLocator.Current.GetInstance<T>();
var result = compiledAction(handler, arg1, arg2);
return result;
}
```
i.e. make the numbers parameters of the expression, and pass the *actual* ones it at runtime (rather than being constants in the expression).
|
258,871 |
<p>I want to find in a vector of Object pointers for a matching object. Here's a sample code to illustrate my problem:</p>
<pre><code>class A {
public:
A(string a):_a(a) {}
bool operator==(const A& p) {
return p._a == _a;
}
private:
string _a;
};
vector<A*> va;
va.push_back(new A("one"));
va.push_back(new A("two"));
va.push_back(new A("three"));
find(va.begin(), va.end(), new A("two"));
</code></pre>
<p>I want to find the second item pushed into the vector. But since vector is defined as a pointers collection, C++ does not use my overloaded operator, but uses implicit pointer comparison. What is the preferred C++-way of solutiono in this situation?</p>
|
[
{
"answer_id": 258898,
"author": "Laserallan",
"author_id": 11758,
"author_profile": "https://Stackoverflow.com/users/11758",
"pm_score": 1,
"selected": false,
"text": "<p>Try using find_if instead. It has a parameter for a predicate where you can decide exactly how to check wheter you found the right element.</p>\n\n<p><a href=\"http://www.sgi.com/tech/stl/find_if.html\" rel=\"nofollow noreferrer\">http://www.sgi.com/tech/stl/find_if.html</a></p>\n"
},
{
"answer_id": 258913,
"author": "James Hopkin",
"author_id": 11828,
"author_profile": "https://Stackoverflow.com/users/11828",
"pm_score": 5,
"selected": true,
"text": "<p>Use find_if with a functor:</p>\n\n<pre><code>template <typename T>\nstruct pointer_values_equal\n{\n const T* to_find;\n\n bool operator()(const T* other) const\n {\n return *to_find == *other;\n }\n};\n\n\n// usage:\nvoid test(const vector<A*>& va)\n{\n A* to_find = new A(\"two\");\n pointer_values_equal<A> eq = { to_find };\n find_if(va.begin(), va.end(), eq);\n // don't forget to delete A!\n}\n</code></pre>\n\n<p>Note: your operator== for A ought to be const, or, better still, write it as a non-member friend function.</p>\n"
},
{
"answer_id": 258916,
"author": "Pieter",
"author_id": 5822,
"author_profile": "https://Stackoverflow.com/users/5822",
"pm_score": 2,
"selected": false,
"text": "<p>Either use std::find_if and provide a suitable predicate yourself, see other answers for an example of this.</p>\n\n<p>Or as an alternative have a look at <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_container.html\" rel=\"nofollow noreferrer\">boost::ptr_vector</a>, which provides transparent reference access to elements which are really stored as pointers (as an extra bonus, memory management is handled for you as well)</p>\n"
},
{
"answer_id": 261714,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": 1,
"selected": false,
"text": "<p>You could also use Boost::Lambda:</p>\n\n<pre><code>using namespace boost::lambda;\nfind_if(va.begin(), va.end(), *_1 == A(\"two\"));\n</code></pre>\n\n<p>Of course, you should prefer to use shared_ptrs so you don't have to remember to delete!</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258871",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28161/"
] |
I want to find in a vector of Object pointers for a matching object. Here's a sample code to illustrate my problem:
```
class A {
public:
A(string a):_a(a) {}
bool operator==(const A& p) {
return p._a == _a;
}
private:
string _a;
};
vector<A*> va;
va.push_back(new A("one"));
va.push_back(new A("two"));
va.push_back(new A("three"));
find(va.begin(), va.end(), new A("two"));
```
I want to find the second item pushed into the vector. But since vector is defined as a pointers collection, C++ does not use my overloaded operator, but uses implicit pointer comparison. What is the preferred C++-way of solutiono in this situation?
|
Use find\_if with a functor:
```
template <typename T>
struct pointer_values_equal
{
const T* to_find;
bool operator()(const T* other) const
{
return *to_find == *other;
}
};
// usage:
void test(const vector<A*>& va)
{
A* to_find = new A("two");
pointer_values_equal<A> eq = { to_find };
find_if(va.begin(), va.end(), eq);
// don't forget to delete A!
}
```
Note: your operator== for A ought to be const, or, better still, write it as a non-member friend function.
|
258,875 |
<p>I was looking into using some .NET code from within a Delphi program, I will need to make my program extensible using .net assemblies and predefined functions (I already support regular DLLs).</p>
<p>After a lot of searching online, I found <a href="http://www.managed-vcl.com/" rel="noreferrer">Managed-VCL</a>, but I'm not ready to pay $250 for what I need, I also found some newsgroups with code that's incomplete and doesn't work.</p>
<p>I'm using Delphi 2007 for win32. What can I use to dynamically execute a function from an assembly with predefined parameters?</p>
<p>Something like:</p>
<pre><code>procedure ExecAssembly(AssemblyFileName:String; Parameters: Variant);
</code></pre>
<p>I just want to add that I need to be able to load an arbitrary assemblies (maybe all the assemblies in a specific folder), so creating a C# wrapper may not work.</p>
|
[
{
"answer_id": 258904,
"author": "zendar",
"author_id": 25732,
"author_profile": "https://Stackoverflow.com/users/25732",
"pm_score": 2,
"selected": false,
"text": "<p>You can use .Net classes as COM objects in Delphi:</p>\n\n<ul>\n<li>create assembly in C# </li>\n<li>create type library for assembly</li>\n<li>import type library in Delphi</li>\n</ul>\n\n<p>Now you can access classes from .Net assembly that are exported in type library.</p>\n"
},
{
"answer_id": 258906,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": false,
"text": "<p>I can tell you from first hand experience that inter-operating with .Net from Delphi is no picnic. I am a .Net guy, but worked in a .Net and Delphi shop for a while. I managed several projects that were written in .Net (WinForms and WPF) but were called by Delphi. Our Delphi guys had written an interop layer for Delphi to call out to .Net libraries since all of our new products were being written in .Net. It was trouble for us (and these were good Delphi developers). If we could have purchased a <em>good</em> 3rd party library to do the interop for us, it would have been more than worth it. I bet we spent thousands of dollars in man-hours writing and debugging problems with the interop from Delphi to .Net.</p>\n\n<p>I would take that Managed-VLC library for a test drive to see how well it works. If it lives up to its advertising, then it is easily worth the $250. </p>\n"
},
{
"answer_id": 258945,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "<p>Hosting the CLR yourself is not all that difficult (especially if you are just using a single AppDomain). You can use the COM based hosting APIs to start up the runtime, load assemblies, create objects and invoke methods on them. </p>\n\n<p>There is a lot of info online, for example the MSDN documentation on \"<a href=\"http://msdn.microsoft.com/en-us/library/9x0wh2z3(VS.80).aspx\" rel=\"nofollow noreferrer\">Hosting the Common Language Runtime</a>\". <em>(<a href=\"https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-3.0/9x0wh2z3(v=vs.85)\" rel=\"nofollow noreferrer\">new home</a>)</em></p>\n"
},
{
"answer_id": 259419,
"author": "postfuturist",
"author_id": 1892,
"author_profile": "https://Stackoverflow.com/users/1892",
"pm_score": 2,
"selected": false,
"text": "<p>I had this exact same problem. I worked in a Delphi shop and they wanted to start adding functionality to a legacy Delphi app with .NET and C#. I looked at Managed-VLC and I decided to skip it, as I felt it had some serious problems. I found something much simpler here: <a href=\"http://sourceforge.net/projects/delphinet/\" rel=\"nofollow noreferrer\">Delphi.NET</a>. Note: this is <em>not</em> the version of Delphi that runs natively on .NET. This is an open source project to allow legacy Delphi apps to access .NET functionality via COM and reflection. Even though it is old, it works like a charm since it uses COM. I'll verify that it works with .NET 2.0 and 3.5. I got .NET DLL's fully integrated into our legacy Delphi 5 application in days. My boss thought I was a superhero. Good luck!</p>\n"
},
{
"answer_id": 259539,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 2,
"selected": false,
"text": "<p>You could use Delphi for .Net and unmanaged exports, also called reverse P/Invoke.</p>\n\n<p>This essentially lets you create a .Net .dll that has full access to the .Net framework, but can be loaded by any native language, just like you would with any .dll, and without the overhead of com interop.</p>\n\n<p>Here is a simple example:\n<a href=\"http://cc.codegear.com/Item/22688\" rel=\"nofollow noreferrer\">http://cc.codegear.com/Item/22688</a></p>\n"
},
{
"answer_id": 301263,
"author": "Stefan Schultze",
"author_id": 6358,
"author_profile": "https://Stackoverflow.com/users/6358",
"pm_score": 4,
"selected": true,
"text": "<p>In the Jedi Code Library (JCL) - free - there is a JclDotNet.pas, containing a class TJclClrHost, probably doing what you want:</p>\n\n<pre><code> TJclClrHost = class(TJclClrBase, ICorRuntimeHost)\n private\n FDefaultInterface: ICorRuntimeHost;\n FAppDomains: TObjectList;\n procedure EnumAppDomains;\n function GetAppDomain(const Idx: Integer): TJclClrAppDomain;\n function GetAppDomainCount: Integer;\n function GetDefaultAppDomain: IJclClrAppDomain;\n function GetCurrentAppDomain: IJclClrAppDomain;\n protected\n function AddAppDomain(const AppDomain: TJclClrAppDomain): Integer;\n function RemoveAppDomain(const AppDomain: TJclClrAppDomain): Integer; \n public\n constructor Create(const ClrVer: WideString = '';\n const Flavor: TJclClrHostFlavor = hfWorkStation;\n const ConcurrentGC: Boolean = True;\n const LoaderFlags: TJclClrHostLoaderFlags = [hlOptSingleDomain]);\n destructor Destroy; override;\n procedure Start;\n procedure Stop;\n procedure Refresh;\n function CreateDomainSetup: TJclClrAppDomainSetup;\n function CreateAppDomain(const Name: WideString;\n const Setup: TJclClrAppDomainSetup = nil;\n const Evidence: IJclClrEvidence = nil): TJclClrAppDomain;\n function FindAppDomain(const Intf: IJclClrAppDomain; var Ret: TJclClrAppDomain): Boolean; overload;\n function FindAppDomain(const Name: WideString; var Ret: TJclClrAppDomain): Boolean; overload;\n class function CorSystemDirectory: WideString;\n class function CorVersion: WideString;\n class function CorRequiredVersion: WideString;\n class procedure GetClrVersions(VersionNames: TWideStrings); overload;\n class procedure GetClrVersions(VersionNames: TStrings); overload;\n property DefaultInterface: ICorRuntimeHost read FDefaultInterface implements ICorRuntimeHost;\n property AppDomains[const Idx: Integer]: TJclClrAppDomain read GetAppDomain; default;\n property AppDomainCount: Integer read GetAppDomainCount;\n property DefaultAppDomain: IJclClrAppDomain read GetDefaultAppDomain;\n property CurrentAppDomain: IJclClrAppDomain read GetCurrentAppDomain;\n end;\n</code></pre>\n"
},
{
"answer_id": 2052438,
"author": "Lukas Cenovsky",
"author_id": 138803,
"author_profile": "https://Stackoverflow.com/users/138803",
"pm_score": 2,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/2048540/hosting-clr-in-delphi-with-jcl-example\">my question</a> for end to end example of hosting CLR in Delphi with JCL.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258875",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25544/"
] |
I was looking into using some .NET code from within a Delphi program, I will need to make my program extensible using .net assemblies and predefined functions (I already support regular DLLs).
After a lot of searching online, I found [Managed-VCL](http://www.managed-vcl.com/), but I'm not ready to pay $250 for what I need, I also found some newsgroups with code that's incomplete and doesn't work.
I'm using Delphi 2007 for win32. What can I use to dynamically execute a function from an assembly with predefined parameters?
Something like:
```
procedure ExecAssembly(AssemblyFileName:String; Parameters: Variant);
```
I just want to add that I need to be able to load an arbitrary assemblies (maybe all the assemblies in a specific folder), so creating a C# wrapper may not work.
|
In the Jedi Code Library (JCL) - free - there is a JclDotNet.pas, containing a class TJclClrHost, probably doing what you want:
```
TJclClrHost = class(TJclClrBase, ICorRuntimeHost)
private
FDefaultInterface: ICorRuntimeHost;
FAppDomains: TObjectList;
procedure EnumAppDomains;
function GetAppDomain(const Idx: Integer): TJclClrAppDomain;
function GetAppDomainCount: Integer;
function GetDefaultAppDomain: IJclClrAppDomain;
function GetCurrentAppDomain: IJclClrAppDomain;
protected
function AddAppDomain(const AppDomain: TJclClrAppDomain): Integer;
function RemoveAppDomain(const AppDomain: TJclClrAppDomain): Integer;
public
constructor Create(const ClrVer: WideString = '';
const Flavor: TJclClrHostFlavor = hfWorkStation;
const ConcurrentGC: Boolean = True;
const LoaderFlags: TJclClrHostLoaderFlags = [hlOptSingleDomain]);
destructor Destroy; override;
procedure Start;
procedure Stop;
procedure Refresh;
function CreateDomainSetup: TJclClrAppDomainSetup;
function CreateAppDomain(const Name: WideString;
const Setup: TJclClrAppDomainSetup = nil;
const Evidence: IJclClrEvidence = nil): TJclClrAppDomain;
function FindAppDomain(const Intf: IJclClrAppDomain; var Ret: TJclClrAppDomain): Boolean; overload;
function FindAppDomain(const Name: WideString; var Ret: TJclClrAppDomain): Boolean; overload;
class function CorSystemDirectory: WideString;
class function CorVersion: WideString;
class function CorRequiredVersion: WideString;
class procedure GetClrVersions(VersionNames: TWideStrings); overload;
class procedure GetClrVersions(VersionNames: TStrings); overload;
property DefaultInterface: ICorRuntimeHost read FDefaultInterface implements ICorRuntimeHost;
property AppDomains[const Idx: Integer]: TJclClrAppDomain read GetAppDomain; default;
property AppDomainCount: Integer read GetAppDomainCount;
property DefaultAppDomain: IJclClrAppDomain read GetDefaultAppDomain;
property CurrentAppDomain: IJclClrAppDomain read GetCurrentAppDomain;
end;
```
|
258,877 |
<p>I am trying to render a user control into a string. The application is set up to enable user to use tokens and user controls are rendered where the tokens are found.</p>
<pre><code>StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
Control uc = LoadControl("~/includes/HomepageNews.ascx");
uc.RenderControl(writer);
return sb.ToString();
</code></pre>
<p><strong>That code renders the control but none of the events called in the Page_Load of the control are firing. There's a Repeater in the control needs to fire.</strong></p>
|
[
{
"answer_id": 258888,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "<p>You would need to attach the control to a Page by adding it to a Controls collection of the Page or a Control on the page. This won't solve all of your problems unless you do something to explicitly disable rendering during the normal page render event.</p>\n"
},
{
"answer_id": 259791,
"author": "Hauge",
"author_id": 17368,
"author_profile": "https://Stackoverflow.com/users/17368",
"pm_score": 5,
"selected": true,
"text": "<p>I've been using the following code provided by Scott Guthrie in his blog for quite some time:</p>\n\n<pre><code>public class ViewManager\n{\n public static string RenderView(string path, object data)\n {\n Page pageHolder = new Page();\n UserControl viewControl = (UserControl) pageHolder.LoadControl(path);\n\n if (data != null)\n {\n Type viewControlType = viewControl.GetType();\n FieldInfo field = viewControlType.GetField(\"Data\");\n if (field != null)\n {\n field.SetValue(viewControl, data);\n }\n else\n {\n throw new Exception(\"ViewFile: \" + path + \"has no data property\");\n }\n }\n\n pageHolder.Controls.Add(viewControl);\n StringWriter result = new StringWriter();\n HttpContext.Current.Server.Execute(pageHolder, result, false);\n return result.ToString();\n }\n}\n</code></pre>\n\n<p>The <code>object data</code> parameter, enables dynamic loading of data into the user control, and can be used to inject more than one variable into the control via an array or somethin similar.</p>\n\n<p>This code will fire all the normal events in the control.</p>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx\" rel=\"noreferrer\">You can read more about it here</a> </p>\n\n<p>Regards \nJesper Hauge</p>\n"
},
{
"answer_id": 1643619,
"author": "Jon Kragh",
"author_id": 47752,
"author_profile": "https://Stackoverflow.com/users/47752",
"pm_score": 1,
"selected": false,
"text": "<p>I took Hauge's/ Scott Guthrie's method above and tweaked it so that you don't need to use reflection, or modify a UserControl to implement any special interface. The key was I added a strongly typed callback that the RenderView method above calls, instead of doing reflection.</p>\n\n<p>I blogged the helper method and usage <a href=\"http://www.jonkragh.com/index.php/rendering-an-asp-net-usercontrol-to-a-string/\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>HTH,\nJon</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258877",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12252/"
] |
I am trying to render a user control into a string. The application is set up to enable user to use tokens and user controls are rendered where the tokens are found.
```
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter writer = new HtmlTextWriter(sw);
Control uc = LoadControl("~/includes/HomepageNews.ascx");
uc.RenderControl(writer);
return sb.ToString();
```
**That code renders the control but none of the events called in the Page\_Load of the control are firing. There's a Repeater in the control needs to fire.**
|
I've been using the following code provided by Scott Guthrie in his blog for quite some time:
```
public class ViewManager
{
public static string RenderView(string path, object data)
{
Page pageHolder = new Page();
UserControl viewControl = (UserControl) pageHolder.LoadControl(path);
if (data != null)
{
Type viewControlType = viewControl.GetType();
FieldInfo field = viewControlType.GetField("Data");
if (field != null)
{
field.SetValue(viewControl, data);
}
else
{
throw new Exception("ViewFile: " + path + "has no data property");
}
}
pageHolder.Controls.Add(viewControl);
StringWriter result = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, result, false);
return result.ToString();
}
}
```
The `object data` parameter, enables dynamic loading of data into the user control, and can be used to inject more than one variable into the control via an array or somethin similar.
This code will fire all the normal events in the control.
[You can read more about it here](http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx)
Regards
Jesper Hauge
|
258,908 |
<p>I'm trying to find a way to determine how many parameters a constructor has.</p>
<p>Now I've built one constructor with no parameters and 1 constructor with 4 parameters.</p>
<p>Is there, in C#, a way to find out how many parameters a used or given constructor has?</p>
<p>Thing is, I'm using a third constructor to read log files. These logs files are read as string[] elements and there should be just as many as there are arguments. If not, I have a corrupt log file.</p>
<p>But I'm using a lot of subclasses and each constructor has more parameters for their specific log-type.</p>
<p>So I wanted to know: is there a method to check the amount of parameters on a constructor?</p>
<p>And yes, this is a school assignment. I don't know what terms to look for really, so the VS2008 object browser is currently not of much use.</p>
|
[
{
"answer_id": 258915,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "<p>i'm not sure exactly what context you need this information, but if you need it dynamically at run-time try the System.Reflection namespace</p>\n\n<p>otherwise the Intellisense drop-list should show you all the constructors available...</p>\n"
},
{
"answer_id": 258921,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 3,
"selected": true,
"text": "<p>You should look at the System.Reflection Namespace. More specifically, you can get a list of the constructors of a class with:</p>\n\n<pre><code> System.Type.GetType(\"MYClassName\").GetConstructors()\n</code></pre>\n"
},
{
"answer_id": 258942,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds as if you need to re think your code a bit. From your description, having to dynamically determine the number of arguments in a constructor sounds a bit hairy. You might consider a factory design pattern since the type of object created is determined at runtime. If I misunderstand your problem then using reflection as pointed out by other answers will do the trick for you.</p>\n"
},
{
"answer_id": 258983,
"author": "Vordreller",
"author_id": 11795,
"author_profile": "https://Stackoverflow.com/users/11795",
"pm_score": 0,
"selected": false,
"text": "<p>The amount of parameters is constant. I've defined them and they're not changing.</p>\n\n<p>What's happening is I'm simulating a sort of publications tree and I'm making divisions in that(a.k.a. subclasses)</p>\n\n<p>Thusly, all the constructors of my subclasses have the parameters or the classes they inherit from.</p>\n\n<p>Thusly, the length is different for each type of publication.</p>\n\n<p>I have a third constructor, just in case I need to visualise my publication data throuhg reading the log file.</p>\n\n<p>But I have to take into account that the log file might be corrupt. Which includes the possibility that there is no data for all my parameters in the log file.</p>\n\n<p>This is why I have to know how to find the amount of parameters in my constructor: I have to check howmuch data there is in my log compared to the amount of parameters I have.</p>\n"
},
{
"answer_id": 258997,
"author": "Dan Fleet",
"author_id": 7470,
"author_profile": "https://Stackoverflow.com/users/7470",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you make a constructor that takes a reference to the log file (or the current raw logfile entry), reads it, and throw an error if there's any problem? </p>\n\n<p>I'm trying to understand why you'd need to look at the number of elements a constructor has. It seems a weak design from what I've seen so far to trust that the number of elements in the log file happens to identify the type of publication to create.</p>\n\n<p>The short answer to your immediate question is what was stated in an earlier answer: reflect on the constructor for the class you're trying to create, and examine its parameters.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
I'm trying to find a way to determine how many parameters a constructor has.
Now I've built one constructor with no parameters and 1 constructor with 4 parameters.
Is there, in C#, a way to find out how many parameters a used or given constructor has?
Thing is, I'm using a third constructor to read log files. These logs files are read as string[] elements and there should be just as many as there are arguments. If not, I have a corrupt log file.
But I'm using a lot of subclasses and each constructor has more parameters for their specific log-type.
So I wanted to know: is there a method to check the amount of parameters on a constructor?
And yes, this is a school assignment. I don't know what terms to look for really, so the VS2008 object browser is currently not of much use.
|
You should look at the System.Reflection Namespace. More specifically, you can get a list of the constructors of a class with:
```
System.Type.GetType("MYClassName").GetConstructors()
```
|
258,917 |
<p>I have a problem applying the <code>DebuggerDisplay</code> attribute on a generic class:</p>
<pre><code>[DebuggerDisplay("--foo--")]
class Foo
{
}
[DebuggerDisplay("Bar: {t}")]
class Bar<T>
{
public T t;
}
</code></pre>
<p>When inspecting an object of type <code>Bar<Foo></code> I would expect it to show as <code>Bar: --foo--</code>, but I get <code>Bar: {Foo}</code></p>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 258961,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": true,
"text": "<p>The DebuggerDisplay attribute is not recursive. The {} inside the string essentially say evaluate this expression and display the result inline. The string for the inner result is calculated as if there was no DebuggerDisplay attribute in play for type or member. That is why you see {Foo} instead of --foo--. </p>\n\n<p>The reason for this is reliability. It is far too easy to have mutually recursive DebuggerDisplay attribute tags. This would cause a stack overflow or infinite loop to occur when evaluating an inner expression. Not recursively evaluating the DebuggerDisplay attribute prevents this infinite recursion (although it's still quite possible for the user to create it themselves inside a particular expression). </p>\n\n<p>One way you can control the way the inner expression is displayed is by overriding the .ToString() method. This will be evaluated when computing the display string for an inner expression.</p>\n"
},
{
"answer_id": 32602031,
"author": "Ofir",
"author_id": 595859,
"author_profile": "https://Stackoverflow.com/users/595859",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <code>[DebuggerDisplay("Bar<{typeof(T).Name,nq}>")]//nq - no quotes</code>.</p>\n<p>You also can use these practices:\n<a href=\"http://blogs.msdn.com/b/jaredpar/archive/2011/03/18/debuggerdisplay-attribute-best-practices.aspx\" rel=\"nofollow noreferrer\">DebuggerDisplay attribute best practices</a></p>\n"
},
{
"answer_id": 33015200,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 2,
"selected": false,
"text": "<p><em>[Disclaimer: I'm affiliated with OzCode]</em></p>\n\n<p>You can use OzCode's Reveal feature which supports nested/recursive debug information. \n<a href=\"https://i.stack.imgur.com/hWlRv.gif\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/hWlRv.gif\" alt=\"enter image description here\"></a><br>\nOnce you define it for an instance it would be used automatically for all instances of that type.</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31890/"
] |
I have a problem applying the `DebuggerDisplay` attribute on a generic class:
```
[DebuggerDisplay("--foo--")]
class Foo
{
}
[DebuggerDisplay("Bar: {t}")]
class Bar<T>
{
public T t;
}
```
When inspecting an object of type `Bar<Foo>` I would expect it to show as `Bar: --foo--`, but I get `Bar: {Foo}`
What am I doing wrong?
|
The DebuggerDisplay attribute is not recursive. The {} inside the string essentially say evaluate this expression and display the result inline. The string for the inner result is calculated as if there was no DebuggerDisplay attribute in play for type or member. That is why you see {Foo} instead of --foo--.
The reason for this is reliability. It is far too easy to have mutually recursive DebuggerDisplay attribute tags. This would cause a stack overflow or infinite loop to occur when evaluating an inner expression. Not recursively evaluating the DebuggerDisplay attribute prevents this infinite recursion (although it's still quite possible for the user to create it themselves inside a particular expression).
One way you can control the way the inner expression is displayed is by overriding the .ToString() method. This will be evaluated when computing the display string for an inner expression.
|
258,954 |
<p>Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, where the methods taught, would have far better solutions now.</p>
<p>What are some boilerplate code situations, especially ones that you see people implement through force of habit, that you find yourself refactoring to utilize the latest versions of Java?</p>
|
[
{
"answer_id": 258956,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 5,
"selected": false,
"text": "<p>Generics and no longer needing to create an iterator to go through all elements in a collection. The new version is much better, easier to use, and easier to understand.</p>\n\n<p>EDIT:</p>\n\n<p>Before:</p>\n\n<pre><code>List l = someList;\nIterator i = l.getIterator();\nwhile (i.hasNext()) {\n MyObject o = (MyObject)i.next();\n}\n</code></pre>\n\n<p>After</p>\n\n<pre><code>List<MyObject> l = someList;\nfor (MyObject o : l) {\n //do something\n}\n</code></pre>\n"
},
{
"answer_id": 258965,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 4,
"selected": false,
"text": "<p>Q1: Well, the most obvious situations are in the generics / type specific collections. The other one that immediately springs to mind is the improved for loop, which I feel is a lot cleaner looking and easier to understand.</p>\n\n<p>Q2: In general, I have been bundling the JVM along side of my application for customer-facing apps. This allows us to use new language features without having to worry about JVM incompatibility. </p>\n\n<p>If I were not bundling the JRE, I would probably stick to 1.4 for compatibility reasons.</p>\n"
},
{
"answer_id": 258984,
"author": "Kip",
"author_id": 18511,
"author_profile": "https://Stackoverflow.com/users/18511",
"pm_score": 3,
"selected": false,
"text": "<p>Converting a number to a String:</p>\n\n<pre><code>String s = n + \"\";\n</code></pre>\n\n<p>In this case I think there has always been a better way of doing this:</p>\n\n<pre><code>String s = String.valueOf(n);\n</code></pre>\n"
},
{
"answer_id": 259013,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 4,
"selected": false,
"text": "<p>A simple change in since 1.5 but makes a small difference - in the Swing API accessing the contentPane of a JFrame:</p>\n\n<pre><code>myframe.getContentPane().add(mycomponent);\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>myframe.add(mycomponent);\n</code></pre>\n\n<p>And of course the introduction of Enums has changed the way many applications that used constants in the past behave.</p>\n\n<p>String.format() has greatly improved String manipulation and the ternary if statement is quite helpful in making code easier to read.</p>\n"
},
{
"answer_id": 259053,
"author": "Eek",
"author_id": 18752,
"author_profile": "https://Stackoverflow.com/users/18752",
"pm_score": 7,
"selected": true,
"text": "<p>Enums. Replacing </p>\n\n<pre><code>public static final int CLUBS = 0;\npublic static final int DIAMONDS = 1;\npublic static final int HEARTS = 2;\npublic static final int SPADES = 3;\n</code></pre>\n\n<p>with</p>\n\n<pre><code>public enum Suit { \n CLUBS, \n DIAMONDS, \n HEARTS, \n SPADES \n}\n</code></pre>\n"
},
{
"answer_id": 259084,
"author": "Julien Chastang",
"author_id": 32174,
"author_profile": "https://Stackoverflow.com/users/32174",
"pm_score": 5,
"selected": false,
"text": "<p>Here is one that I see:</p>\n\n<p><code>String.split()</code> versus <code>StringTokenizer</code>.</p>\n\n<p><code>StringTokenizer</code> is not recommended for new code, but I still see people use it.</p>\n\n<p>As for compatibility, Sun makes a huge effort to have Java be backwards and forwards compatible. That partially accounts for why generics are so complex. Deprecation is also supposed to help ease transitions from old to new code.</p>\n"
},
{
"answer_id": 259186,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 5,
"selected": false,
"text": "<p>Using local variables of type <code>StringBuffer</code> to perform string concatenation. Unless synchronization is required, it is now recommended to use <code>StringBuilder</code> instead, because this class offers better performance (presumably because it is unsynchronized).</p>\n"
},
{
"answer_id": 259196,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 4,
"selected": false,
"text": "<p>Using local variables of type Vector to hold a list of objects. Unless synchronization is required, it is now recommended to use a List implementation such as ArrayList instead, because this class offers better performance (because it is unsynchronized).</p>\n"
},
{
"answer_id": 259215,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 4,
"selected": false,
"text": "<p>Explicit conversion between primitive and wrapper types (e.g. Integer to int or vice versa) which is taken care of automatically by autoboxing/unboxing since Java 1.5.</p>\n\n<p>An example is</p>\n\n<pre><code>Integer myInteger = 6;\nint myInt = myInteger.intValue();\n</code></pre>\n\n<p>Can simply be written as</p>\n\n<pre><code>Integer myInteger = 6;\nint myInt = myInteger;\n</code></pre>\n\n<p>But watch out for NullPointerExceptions :)</p>\n"
},
{
"answer_id": 259363,
"author": "Pyrolistical",
"author_id": 21838,
"author_profile": "https://Stackoverflow.com/users/21838",
"pm_score": 1,
"selected": false,
"text": "<p>New version of Java rarely break existing code, so just leave old code alone and focus on how the new feature makes your life easier.</p>\n\n<p>If you just leave old code alone, then writing new code using new features isn't as scary.</p>\n"
},
{
"answer_id": 259441,
"author": "Ogre Psalm33",
"author_id": 13140,
"author_profile": "https://Stackoverflow.com/users/13140",
"pm_score": 4,
"selected": false,
"text": "<p>Generic collections make coding much more bug-resistant.\nOLD:</p>\n\n<pre><code>Vector stringVector = new Vector();\nstringVector.add(\"hi\");\nstringVector.add(528); // oops!\nstringVector.add(new Whatzit()); // Oh my, could spell trouble later on!\n</code></pre>\n\n<p>NEW:</p>\n\n<pre><code>ArrayList<String> stringList = new ArrayList<String>();\nstringList.add(\"hello again\");\nstringList.add(new Whatzit()); // Won't compile!\n</code></pre>\n"
},
{
"answer_id": 259665,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 5,
"selected": false,
"text": "<p>Older code using Thread instead of the many other alternatives to Thread... these days, very little of the code I run across still needs to use a raw thread. They would be better served by a level of abstraction, particular <a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html\" rel=\"noreferrer\">Callable</a>/<a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html\" rel=\"noreferrer\">Futures</a>/<a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html\" rel=\"noreferrer\">Executors</a>.</p>\n\n<p>See:</p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/util/Timer.html\" rel=\"noreferrer\">java.util.Timer</a></p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/javax/swing/Timer.html\" rel=\"noreferrer\">javax.swing.Timer</a></p>\n\n<p><a href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-summary.html\" rel=\"noreferrer\">java.util.concurrent.*</a></p>\n"
},
{
"answer_id": 260490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Using Iterator:</p>\n\n<pre><code>List list = getTheList();\nIterator iter = list.iterator()\nwhile (iter.hasNext()) {\n String s = (String) iter.next();\n // .. do something\n}\n</code></pre>\n\n<p>Or an alternate form sometimes seen:</p>\n\n<pre><code>List list = getTheList();\nfor (Iterator iter = list.iterator(); iter.hasNext();) {\n String s = (String) iter.next();\n // .. do something\n}\n</code></pre>\n\n<p>Is now all replaced with:</p>\n\n<pre><code>List<String> list = getTheList();\nfor (String s : list) {\n // .. do something\n}\n</code></pre>\n"
},
{
"answer_id": 260497,
"author": "Jack Leow",
"author_id": 31506,
"author_profile": "https://Stackoverflow.com/users/31506",
"pm_score": 1,
"selected": false,
"text": "<p>String comparisons, really old school Java programmers I've met would do:</p>\n\n<pre><code>String s1 = \"...\", s2 = \"...\";\n\nif (s1.intern() == s2.intern()) {\n ....\n}\n</code></pre>\n\n<p>(Supposedly for performance reasons)</p>\n\n<p>Whereas these days most people just do:</p>\n\n<pre><code>String s1 = \"...\", s2 = \"...\";\n\nif (s1.equals(s2)) {\n ....\n}\n</code></pre>\n"
},
{
"answer_id": 261297,
"author": "dogbane",
"author_id": 7412,
"author_profile": "https://Stackoverflow.com/users/7412",
"pm_score": 4,
"selected": false,
"text": "<p>VARARGS can be useful too.</p>\n\n<p>For example, you can use:</p>\n\n<pre><code>public int add(int... numbers){\n int sum = 0 ;\n for (int i : numbers){\n sum+=i;\n }\n return sum ;\n}\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>public int add(int n1, int n2, int n3, int n4) ;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>public int add(List<Integer> numbers) ;\n</code></pre>\n"
},
{
"answer_id": 617418,
"author": "TofuBeer",
"author_id": 65868,
"author_profile": "https://Stackoverflow.com/users/65868",
"pm_score": 1,
"selected": false,
"text": "<p>Using Vector instead of the new Collections.</p>\n\n<p>Using classes instead of enums</p>\n\n<pre><code> public class Enum\n {\n public static final Enum FOO = new Enum();\n public static final Enum BAR = new Enum();\n }\n</code></pre>\n\n<p>Using Thread instead of the new java.util.concurrency package.</p>\n\n<p><a href=\"http://www.artima.com/weblogs/viewpost.jsp?thread=98061\" rel=\"nofollow noreferrer\">Using marker interfaces instead of annotations</a></p>\n"
},
{
"answer_id": 622385,
"author": "Kjetil Ødegaard",
"author_id": 74185,
"author_profile": "https://Stackoverflow.com/users/74185",
"pm_score": 3,
"selected": false,
"text": "<p>Changing JUnit 3-style tests:</p>\n\n<pre><code>class Test extends TestCase {\n public void testYadaYada() { ... }\n}\n</code></pre>\n\n<p>to JUnit 4-style tests:</p>\n\n<pre><code>class Test {\n @Test public void yadaYada() { ... }\n}\n</code></pre>\n"
},
{
"answer_id": 623007,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 4,
"selected": false,
"text": "<p>Although I admit that static imports can easily be overused, I like to use</p>\n\n<pre><code>import static Math.* ;\n</code></pre>\n\n<p>in classes that use a lot of Math functions. It can really decrease the verbosity of your code. I wouldn't recommend it for lesser-known libraries, though, since that can lead to confusion.</p>\n"
},
{
"answer_id": 623053,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 3,
"selected": false,
"text": "<p>The new <code>for</code>-each construct to iterate over arrays and collection are the biggest for me.</p>\n\n<p>These days, when ever I see the boilerplate <code>for</code> loop to iterate over an array one-by-one using an index variable, it makes me want to scream:</p>\n\n<pre><code>// AGGHHH!!!\nint[] array = new int[] {0, 1, 2, 3, 4};\nfor (int i = 0; i < array.length; i++)\n{\n // Do something...\n}\n</code></pre>\n\n<p>Replacing the above with the <a href=\"http://java.sun.com/j2se/1.5.0/docs/guide/language/foreach.html\" rel=\"nofollow noreferrer\"><code>for</code> construct introduced in Java 5</a>:</p>\n\n<pre><code>// Nice and clean. \nint[] array = new int[] {0, 1, 2, 3, 4};\nfor (int n : array)\n{\n // Do something...\n}\n</code></pre>\n\n<p>Clean, concise, and best of all, it gives <em>meaning</em> to the code rather than showing <em>how</em> to do something. </p>\n\n<p>Clearly, the code has meaning to iterate over the collection, rather than the old <code>for</code> loop saying how to iterate over an array.</p>\n\n<p>Furthermore, as each element is processed independent of other elements, it may allow for future optimizations for parallel processing without having to make changes to the code. (Just speculation, of course.)</p>\n"
},
{
"answer_id": 626185,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 4,
"selected": false,
"text": "<p>Formatted printing was introduced as late as in JDK 1.5. So instead of using:</p>\n\n<pre><code>String str = \"test \" + intValue + \" test \" + doubleValue;\n</code></pre>\n\n<p>or the equivalent using a StringBuilder,</p>\n\n<p>one can use </p>\n\n<pre><code>String str = String.format(\"test %d test %lg\", intValue, doubleValue);\n</code></pre>\n\n<p>The latter is much more readable, both from the string concatenation and the string builder versions. Still I find that people adopt this style very slowly. Log4j framework for example, doesn't use this, although I believe it would be greatly benefited to do so. </p>\n"
},
{
"answer_id": 632128,
"author": "Tony the Pony",
"author_id": 67063,
"author_profile": "https://Stackoverflow.com/users/67063",
"pm_score": 2,
"selected": false,
"text": "<p>Converting classes to use generics, thereby avoiding situations with unnecessary casts.</p>\n"
},
{
"answer_id": 632186,
"author": "user37468",
"author_id": 37468,
"author_profile": "https://Stackoverflow.com/users/37468",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a little wary to refactor along these lines if that is all you are doing to your source tree. The examples so far do not seem like reasons alone to change any working code base, but maybe if you are adding new functionality you should take advantage of all the new stuff. </p>\n\n<p><strong>At the end of the day, these example are not really removing boiler plate code</strong>, they are just using the more manageable constructs of newer JDKs to <strong>make nice looking boiler plate code</strong>.</p>\n\n<p>Most ways to make your code elegant are not in the JDK.</p>\n"
},
{
"answer_id": 632287,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "<p>Okay, now it's my turn to get yelled at.</p>\n\n<p>I don't recommend 90% of these changes.</p>\n\n<p>It's not that it's not a good idea to use them with new code, but breaking into existing code to change a for loop to a for(:) loop is simply a waste of time and a chance to break something. (IIWDFWI) If it works, don't fix it!</p>\n\n<p>If you are at a real development company, that change now becomes something to code-review, test and possibly debug.</p>\n\n<p>If someone doing this kind of a refactor for no reason caused a problem of ANY sort, I'd give them no end of shit.</p>\n\n<p>On the other hand, if you're in the code and changing stuff on that line anyway, feel free to clean it up.</p>\n\n<p>Also, all the suggestions in the name of \"Performance\" really need to learn about the laws of optimization. In two words, Don't! Ever! (Google the \"Rules of optimization if you don't believe me).</p>\n"
},
{
"answer_id": 635078,
"author": "Jonik",
"author_id": 56285,
"author_profile": "https://Stackoverflow.com/users/56285",
"pm_score": 3,
"selected": false,
"text": "<p>Related to <a href=\"https://stackoverflow.com/questions/258954/java-out-with-the-old-in-with-the-new/261297#261297\">varargs</a>; the utility method <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#asList%28T...%29\" rel=\"nofollow noreferrer\">Arrays.asList()</a> which, starting from Java 5, takes varargs parameters is immensely useful.</p>\n\n<p>I often find myself simplifying something like</p>\n\n<pre><code>List<String> items = new ArrayList<String>();\nitems.add(\"one\");\nitems.add(\"two\");\nitems.add(\"three\");\nhandleItems(items);\n</code></pre>\n\n<p>by using</p>\n\n<pre><code>handleItems(Arrays.asList(\"one\", \"two\", \"three\"));\n</code></pre>\n"
},
{
"answer_id": 930073,
"author": "cd1",
"author_id": 38333,
"author_profile": "https://Stackoverflow.com/users/38333",
"pm_score": 5,
"selected": false,
"text": "<p>reading a string from standard input:</p>\n\n<p><strong>Java pre-5</strong>:</p>\n\n<pre><code>try {\n BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));\n String str = reader.readLine();\n reader.close();\n}\ncatch (IOException e) {\n System.err.println(\"error when closing input stream.\");\n}\n</code></pre>\n\n<p><strong>Java 5</strong>:</p>\n\n<pre><code>Scanner reader = new Scanner(System.in);\nString str = reader.nextLine();\nreader.close();\n</code></pre>\n\n<p><strong>Java 6</strong>:</p>\n\n<pre><code>Console reader = System.console();\nString str = reader.readLine();\n</code></pre>\n"
},
{
"answer_id": 930087,
"author": "Nash",
"author_id": 113914,
"author_profile": "https://Stackoverflow.com/users/113914",
"pm_score": 2,
"selected": false,
"text": "<p>Using Swing's new <code>DefaultRowSorter</code> to sort tables versus rolling your own from scratch.</p>\n"
},
{
"answer_id": 930125,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 0,
"selected": false,
"text": "<p>It is worth noting that Java 5.0 has been out for five years now and there have only been minor changes since then. You would have to be working on very old code to be still refactoring it.</p>\n"
},
{
"answer_id": 992375,
"author": "cd1",
"author_id": 38333,
"author_profile": "https://Stackoverflow.com/users/38333",
"pm_score": 3,
"selected": false,
"text": "<p>copying an existing array to a new array:</p>\n\n<p><strong>pre-Java 5</strong>:</p>\n\n<pre><code>int[] src = new int[] {1, 2, 3, 4, 5};\nint[] dest = new int[src.length];\nSystem.arraycopy(src, 0, dest, 0, src.length);\n</code></pre>\n\n<p><strong>Java 6</strong>:</p>\n\n<pre><code>int[] src = new int[] {1, 2, 3, 4, 5};\nint[] dest = Arrays.copyOf(src, src.length);\n</code></pre>\n\n<p>formerly, I had to explicitly create a new array and then copy the source elements to the new array (calling a method with a lot of parameters). now, the syntax is cleaner and the new array is returned from a method, I don't have to create it. by the way, the method <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOf(int[],%20int)\" rel=\"noreferrer\">Arrays.copyOf</a> has a variation called <a href=\"http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#copyOfRange(int[],%20int,%20int)\" rel=\"noreferrer\">Arrays.copyOfRange</a>, which copies a specific region of the source array (pretty much like <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/System.html#arraycopy(java.lang.Object,%20int,%20java.lang.Object,%20int,%20int)\" rel=\"noreferrer\">System.arraycopy</a>).</p>\n"
},
{
"answer_id": 1297057,
"author": "Danijel Arsenovski",
"author_id": 69067,
"author_profile": "https://Stackoverflow.com/users/69067",
"pm_score": 3,
"selected": false,
"text": "<p>Annotations</p>\n\n<p>I wonder no one mentioned it so far, but many frameworks rely on annotations, for example <a href=\"http://www.springsource.org/\" rel=\"noreferrer\">Spring</a> and <a href=\"https://www.hibernate.org/\" rel=\"noreferrer\">Hibernate.</a> It is common today to deprecate xml configuration files are in favor of annotations in code (though this means losing flexibility in moving from configuration to meta-code, but is often the right choice).The best example is EJB 2 (and older) compared to <a href=\"http://www.oracle.com/technology/tech/java/newsletter/articles/simplifying_ejb3.html\" rel=\"noreferrer\">EJB 3.0</a> and how programming EJB has been simplified thanks to annotations. </p>\n\n<p>I find annotations also very useful in combination with some AOP tools like AspectJ or Spring AOP. Such combination can be very powerful. </p>\n"
},
{
"answer_id": 1441504,
"author": "Pops",
"author_id": 122607,
"author_profile": "https://Stackoverflow.com/users/122607",
"pm_score": 2,
"selected": false,
"text": "<p>Improved singleton patterns. Technically these are covered under the popular answer enums, but it's a significant subcategory.</p>\n\n<pre><code>public enum Singleton {\n INSTANCE;\n\n public void someMethod() {\n ...\n }\n}\n</code></pre>\n\n<p>is cleaner and safer than</p>\n\n<pre><code>public class Singleton {\n public static final Singleton INSTANCE = new Singleton();\n\n private Singleton() {\n ...\n }\n\n public void someMethod() {\n ...\n }\n}\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4857/"
] |
Java is nearing version 7. It occurs to me that there must be plenty of textbooks and training manuals kicking around that teach methods based on older versions of Java, where the methods taught, would have far better solutions now.
What are some boilerplate code situations, especially ones that you see people implement through force of habit, that you find yourself refactoring to utilize the latest versions of Java?
|
Enums. Replacing
```
public static final int CLUBS = 0;
public static final int DIAMONDS = 1;
public static final int HEARTS = 2;
public static final int SPADES = 3;
```
with
```
public enum Suit {
CLUBS,
DIAMONDS,
HEARTS,
SPADES
}
```
|
258,960 |
<p>Is there a way for me to serialize an object in .NET without the XML Namespaces automatically serializing also? It seems that by default .NET believes the XSI and XSD namespaces should be included, but I don't want them there.</p>
|
[
{
"answer_id": 258974,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 8,
"selected": true,
"text": "<p>Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is <code>obj</code> and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.</p>\n<p>In VB like this:</p>\n<pre><code>Dim xs As New XmlSerializer(GetType(cEmploymentDetail))\nDim ns As New XmlSerializerNamespaces()\nns.Add("", "")\n\nDim settings As New XmlWriterSettings()\nsettings.OmitXmlDeclaration = True\n\nUsing ms As New MemoryStream(), _\n sw As XmlWriter = XmlWriter.Create(ms, settings), _\n sr As New StreamReader(ms)\n xs.Serialize(sw, obj, ns)\n ms.Position = 0\n Console.WriteLine(sr.ReadToEnd())\nEnd Using\n</code></pre>\n<p>in C# like this:</p>\n<pre><code>//Create our own namespaces for the output\nXmlSerializerNamespaces ns = new XmlSerializerNamespaces();\n\n//Add an empty namespace and empty value\nns.Add("", "");\n\n//Create the serializer\nXmlSerializer slz = new XmlSerializer(someType);\n\n//Serialize the object with our own namespaces (notice the overload)\nslz.Serialize(myXmlTextWriter, someObject, ns);\n</code></pre>\n"
},
{
"answer_id": 2249034,
"author": "Ali B",
"author_id": 271447,
"author_profile": "https://Stackoverflow.com/users/271447",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to get rid of the extra <code>xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"</code> and <code>xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"</code>, but still keep your own namespace <code>xmlns=\"http://schemas.YourCompany.com/YourSchema/\"</code>, you use the same code as above except for this simple change:</p>\n\n<pre><code>// Add lib namespace with empty prefix \nns.Add(\"\", \"http://schemas.YourCompany.com/YourSchema/\"); \n</code></pre>\n"
},
{
"answer_id": 24705961,
"author": "vinjenzo",
"author_id": 735725,
"author_profile": "https://Stackoverflow.com/users/735725",
"pm_score": 3,
"selected": false,
"text": "<p>If you are unable to get rid of extra xmlns attributes for each element, when serializing to xml from generated classes (e.g.: when <strong>xsd.exe</strong> was used), so you have something like:</p>\n\n<pre><code><manyElementWith xmlns=\"urn:names:specification:schema:xsd:one\" />\n</code></pre>\n\n<p>then i would share with you what worked for me (a mix of previous answers and what i found <a href=\"http://blogs.msdn.com/b/dotnetinterop/archive/2006/01/06/prettification-of-xml-serialization-within-web-services.aspx\" rel=\"noreferrer\">here</a>) </p>\n\n<p><em>explicitly set all your different xmlns as follows:</em></p>\n\n<pre><code>Dim xmlns = New XmlSerializerNamespaces()\nxmlns.Add(\"one\", \"urn:names:specification:schema:xsd:one\")\nxmlns.Add(\"two\", \"urn:names:specification:schema:xsd:two\")\nxmlns.Add(\"three\", \"urn:names:specification:schema:xsd:three\")\n</code></pre>\n\n<p><em>then pass it to the serialize</em> </p>\n\n<pre><code>serializer.Serialize(writer, object, xmlns);\n</code></pre>\n\n<p><em>you will have the three namespaces declared in the root element and no more needed to be generated in the other elements which will be prefixed accordingly</em></p>\n\n<pre><code><root xmlns:one=\"urn:names:specification:schema:xsd:one\" ... />\n <one:Element />\n <two:ElementFromAnotherNameSpace /> ...\n</code></pre>\n"
},
{
"answer_id": 28606746,
"author": "Maziar Taheri",
"author_id": 753645,
"author_profile": "https://Stackoverflow.com/users/753645",
"pm_score": 3,
"selected": false,
"text": "<p>I Suggest this helper class:</p>\n\n<pre><code>public static class Xml\n{\n #region Fields\n\n private static readonly XmlWriterSettings WriterSettings = new XmlWriterSettings {OmitXmlDeclaration = true, Indent = true};\n private static readonly XmlSerializerNamespaces Namespaces = new XmlSerializerNamespaces(new[] {new XmlQualifiedName(\"\", \"\")});\n\n #endregion\n\n #region Methods\n\n public static string Serialize(object obj)\n {\n if (obj == null)\n {\n return null;\n }\n\n return DoSerialize(obj);\n }\n\n private static string DoSerialize(object obj)\n {\n using (var ms = new MemoryStream())\n using (var writer = XmlWriter.Create(ms, WriterSettings))\n {\n var serializer = new XmlSerializer(obj.GetType());\n serializer.Serialize(writer, obj, Namespaces);\n return Encoding.UTF8.GetString(ms.ToArray());\n }\n }\n\n public static T Deserialize<T>(string data)\n where T : class\n {\n if (string.IsNullOrEmpty(data))\n {\n return null;\n }\n\n return DoDeserialize<T>(data);\n }\n\n private static T DoDeserialize<T>(string data) where T : class\n {\n using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(data)))\n {\n var serializer = new XmlSerializer(typeof (T));\n return (T) serializer.Deserialize(ms);\n }\n }\n\n #endregion\n}\n</code></pre>\n\n<p>:)</p>\n"
},
{
"answer_id": 39737083,
"author": "D34th",
"author_id": 6398327,
"author_profile": "https://Stackoverflow.com/users/6398327",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to remove the namespace you may also want to remove the version, to save you searching I've added that functionality so the below code will do both.</p>\n\n<p>I've also wrapped it in a generic method as I'm creating very large xml files which are too large to serialize in memory so I've broken my output file down and serialize it in smaller \"chunks\":</p>\n\n<pre><code> public static string XmlSerialize<T>(T entity) where T : class\n {\n // removes version\n XmlWriterSettings settings = new XmlWriterSettings();\n settings.OmitXmlDeclaration = true;\n\n XmlSerializer xsSubmit = new XmlSerializer(typeof(T));\n using (StringWriter sw = new StringWriter())\n using (XmlWriter writer = XmlWriter.Create(sw, settings))\n {\n // removes namespace\n var xmlns = new XmlSerializerNamespaces();\n xmlns.Add(string.Empty, string.Empty);\n\n xsSubmit.Serialize(writer, entity, xmlns);\n return sw.ToString(); // Your XML\n }\n }\n</code></pre>\n"
},
{
"answer_id": 58979104,
"author": "Taurus999able",
"author_id": 11739338,
"author_profile": "https://Stackoverflow.com/users/11739338",
"pm_score": 0,
"selected": false,
"text": "<pre><code> XmlWriterSettings settings = new XmlWriterSettings\n {\n OmitXmlDeclaration = true\n };\n\n XmlSerializerNamespaces ns = new XmlSerializerNamespaces();\n ns.Add(\"\", \"\");\n\n StringBuilder sb = new StringBuilder();\n\n XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));\n\n using (XmlWriter xw = XmlWriter.Create(sb, settings))\n {\n xs.Serialize(xw, model, ns);\n xw.Flush();\n return sb.ToString();\n }\n</code></pre>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13611/"
] |
Is there a way for me to serialize an object in .NET without the XML Namespaces automatically serializing also? It seems that by default .NET believes the XSI and XSD namespaces should be included, but I don't want them there.
|
Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is `obj` and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.
In VB like this:
```
Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")
Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True
Using ms As New MemoryStream(), _
sw As XmlWriter = XmlWriter.Create(ms, settings), _
sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using
```
in C# like this:
```
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);
```
|
258,968 |
<p>Just wondering what the difference between MFC control messages prefixed with the following is:</p>
<pre><code>LVN (e.g. LVN_ITEMCHANGED)
HDN (e.g. HDN_TRACK)
NM (e.g. NM_HOVER)
</code></pre>
<p>Also, I am using a ListControl and trapping when the user clicks on an item using the NM_CLICK message. I also want to trap when a user selects a new item view a key e.g. up/down arrow keys. Can anyone tell me which message I should be trapping for this?</p>
<p>Thanks</p>
|
[
{
"answer_id": 258979,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>LVN = ListView Notification</li>\n<li>HDN = HeaDer control Notification</li>\n<li>NM = er..um.. \"Notification for Mouse\" ?</li>\n</ul>\n"
},
{
"answer_id": 259057,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 3,
"selected": true,
"text": "<p>For change in selection, you need to handle the LVN_ITEMCHANGED notification:</p>\n\n<pre><code>NMLISTVIEW & nm = *(NMLISTVIEW *) pnmh;\nif ( (nm.uNewState ^ nm.uOldState) & LVIS_SELECTED) \n{ \n // nm.iItem was selected or deselected\n if (!m_internalUIChange)\n {\n // see below\n }\n}\n</code></pre>\n\n<p>The first \"if\" checks if the \"selected\" state has changed. Note that, when selecting a different item in the list, this still fires twice: once for the old item to be deselected, and once for the new item to be selected. This is necessary, however, to fetch a \"complete deselect\".</p>\n\n<p>This notification fires very often - even when you modify the control programmatically. If your handler should react only to user events, you will need at least a flag that you set durign these operations (I use a class together with a RAII-Lock for that, so I don't forget to reset it)</p>\n"
}
] |
2008/11/03
|
[
"https://Stackoverflow.com/questions/258968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18664/"
] |
Just wondering what the difference between MFC control messages prefixed with the following is:
```
LVN (e.g. LVN_ITEMCHANGED)
HDN (e.g. HDN_TRACK)
NM (e.g. NM_HOVER)
```
Also, I am using a ListControl and trapping when the user clicks on an item using the NM\_CLICK message. I also want to trap when a user selects a new item view a key e.g. up/down arrow keys. Can anyone tell me which message I should be trapping for this?
Thanks
|
For change in selection, you need to handle the LVN\_ITEMCHANGED notification:
```
NMLISTVIEW & nm = *(NMLISTVIEW *) pnmh;
if ( (nm.uNewState ^ nm.uOldState) & LVIS_SELECTED)
{
// nm.iItem was selected or deselected
if (!m_internalUIChange)
{
// see below
}
}
```
The first "if" checks if the "selected" state has changed. Note that, when selecting a different item in the list, this still fires twice: once for the old item to be deselected, and once for the new item to be selected. This is necessary, however, to fetch a "complete deselect".
This notification fires very often - even when you modify the control programmatically. If your handler should react only to user events, you will need at least a flag that you set durign these operations (I use a class together with a RAII-Lock for that, so I don't forget to reset it)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.