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
87,713
<p>For example, right now I have a roll-my-own solution that uses data files that include blocks like:</p> <pre><code>PlayerCharacter Fighter Hitpoints 25 Strength 10 StartPosition (0, 0, 0) Art Model BigBuffGuy Footprint LargeFootprint end InventoryItem Sword InventoryItem Shield InventoryItem HealthPotion end </code></pre> <ul> <li>human editable (w/ minimal junk characters, ideally)</li> <li>resilient to errors (fewest 'wow i can't parse anything useful anymore' style errors, and thus i've lost all of the data in the rest of the file) - but still able to identify and report them, of course. My example the only complete failure case is missing 'end's.</li> <li>nested structure style data</li> <li>array/list style data</li> <li>customizable foundation types</li> <li>fast</li> </ul> <p>Are there any well known solutions that meet/exceed these requirements?</p>
[ { "answer_id": 87725, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 3, "selected": false, "text": "<p>Yaml is a good solution and very close to what you have. Search for it.</p>\n" }, { "answer_id": 87736, "aut...
2008/09/17
[ "https://Stackoverflow.com/questions/87713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16639/" ]
For example, right now I have a roll-my-own solution that uses data files that include blocks like: ``` PlayerCharacter Fighter Hitpoints 25 Strength 10 StartPosition (0, 0, 0) Art Model BigBuffGuy Footprint LargeFootprint end InventoryItem Sword InventoryItem Shield InventoryItem HealthPotion end ``` * human editable (w/ minimal junk characters, ideally) * resilient to errors (fewest 'wow i can't parse anything useful anymore' style errors, and thus i've lost all of the data in the rest of the file) - but still able to identify and report them, of course. My example the only complete failure case is missing 'end's. * nested structure style data * array/list style data * customizable foundation types * fast Are there any well known solutions that meet/exceed these requirements?
Yaml is a good solution and very close to what you have. Search for it.
87,734
<p>If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated?</p> <p>The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way.</p> <p>If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one.</p> <p><strong>Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.</strong></p>
[ { "answer_id": 87965, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 2, "selected": false, "text": "<p>I think the most useful formula is this one. An ellipsis rotated from an angle phi from the origin has as equation:</p>\...
2008/09/17
[ "https://Stackoverflow.com/questions/87734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2214/" ]
If the major axis of the ellipse is vertical or horizontal, it's easy to calculate the bounding box, but what about when the ellipse is rotated? The only way I can think of so far is to calculate all the points around the perimeter and find the max/min x and y values. It seems like there should be a simpler way. If there's a function (in the mathematical sense) that describes an ellipse at an arbitrary angle, then I could use its derivative to find points where the slope is zero or undefined, but I can't seem to find one. **Edit: to clarify, I need the axis-aligned bounding box, i.e. it should not be rotated with the ellipse, but stay aligned with the x axis so transforming the bounding box won't work.**
You could try using the parametrized equations for an ellipse rotated at an arbitrary angle: ``` x = h + a*cos(t)*cos(phi) - b*sin(t)*sin(phi) [1] y = k + b*sin(t)*cos(phi) + a*cos(t)*sin(phi) [2] ``` ...where ellipse has centre (h,k) semimajor axis a and semiminor axis b, and is rotated through angle phi. You can then differentiate and solve for gradient = 0: ``` 0 = dx/dt = -a*sin(t)*cos(phi) - b*cos(t)*sin(phi) ``` => ``` tan(t) = -b*tan(phi)/a [3] ``` Which should give you many solutions for t (two of which you are interested in), plug that back into [1] to get your max and min x. Repeat for [2]: ``` 0 = dy/dt = b*cos(t)*cos(phi) - a*sin(t)*sin(phi) ``` => ``` tan(t) = b*cot(phi)/a [4] ``` **Lets try an example:** Consider an ellipse at (0,0) with a=2, b=1, rotated by PI/4: [1] => ``` x = 2*cos(t)*cos(PI/4) - sin(t)*sin(PI/4) ``` [3] => ``` tan(t) = -tan(PI/4)/2 = -1/2 ``` => ``` t = -0.4636 + n*PI ``` We are interested in t = -0.4636 and t = -3.6052 So we get: ``` x = 2*cos(-0.4636)*cos(PI/4) - sin(-0.4636)*sin(PI/4) = 1.5811 ``` and ``` x = 2*cos(-3.6052)*cos(PI/4) - sin(-3.6052)*sin(PI/4) = -1.5811 ```
87,747
<p>I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.</p> <p>Results would be something like:</p> <p>TableName, ColumnName</p>
[ { "answer_id": 87773, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 6, "selected": false, "text": "<p>sys.columns.is_identity = 1</p>\n\n<p>e.g.,</p>\n\n<pre><code>select o.name, c.name\nfrom sys.objects o inner join s...
2008/09/17
[ "https://Stackoverflow.com/questions/87747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL. Results would be something like: TableName, ColumnName
Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION\_SCHEMA views: ``` select COLUMN_NAME, TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 order by TABLE_NAME ```
87,753
<p>How can I resize an image, with the image quality unaffected?</p>
[ { "answer_id": 87763, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 5, "selected": false, "text": "<p>Unless you're doing vector graphics, there's no way to resize an image without potentially losing some image quality.</p>\n"...
2008/09/17
[ "https://Stackoverflow.com/questions/87753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
How can I resize an image, with the image quality unaffected?
As [rcar](https://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality#87763) says, you can't without losing some quality, the best you can do in c# is: ``` Bitmap newImage = new Bitmap(newWidth, newHeight); using (Graphics gr = Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight)); } ```
87,758
<p>I have several old 3.5in floppy disks that I would like to backup. My attempts to create an image of the disks have failed. I tried using the UNIX utility dd_rescue, but when the kernel tries to open (<code>/dev/fd0</code>) I get a kernel error,</p> <pre><code>floppy0: probe failed... </code></pre> <p>I would like an image because some of the floppies are using the LIF file system format. Does anyone have any ideas as to what I should do?</p> <p>HP now Agilent made some tools that could read and write to files on LIF formatted disk. I could use these tools to copy and convert the files to the local disk but not without possibly losing some data in the process. In other words, converting from LIF to some other format back to LIF will lose some information.</p> <p>I just want to backup the raw bytes on the disk and not be concerned with the type of file system.</p>
[ { "answer_id": 88447, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 3, "selected": true, "text": "<p>I think you'll find the best resource <a href=\"http://www.hpcc.org/datafile/hpil/lif_utils.html\" rel=\"nofollow noref...
2008/09/17
[ "https://Stackoverflow.com/questions/87758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4778/" ]
I have several old 3.5in floppy disks that I would like to backup. My attempts to create an image of the disks have failed. I tried using the UNIX utility dd\_rescue, but when the kernel tries to open (`/dev/fd0`) I get a kernel error, ``` floppy0: probe failed... ``` I would like an image because some of the floppies are using the LIF file system format. Does anyone have any ideas as to what I should do? HP now Agilent made some tools that could read and write to files on LIF formatted disk. I could use these tools to copy and convert the files to the local disk but not without possibly losing some data in the process. In other words, converting from LIF to some other format back to LIF will lose some information. I just want to backup the raw bytes on the disk and not be concerned with the type of file system.
I think you'll find the best resource [here](http://www.hpcc.org/datafile/hpil/lif_utils.html). Also, if you're going to use raw dd, LIF format has 77 cylinders vs 80 for a normal floppy.
87,760
<p>Ive been smashing my head with this for a while. I have 2 completely identical .wmv files encoded with wmv3 codec. I put them both through ffmpeg with the following command:</p> <pre><code>/usr/bin/ffmpeg -i file.wmv -ar 44100 -ab 64k -qscale 9 -s 512x384 -f flv file.flv </code></pre> <p>One file converts just fine, and gives me the following output:</p> <pre><code> FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -&gt; 29.97 (30000/1001) Input #0, asf, from 'ok.wmv': Duration: 00:14:22.3, start: 3.000000, bitrate: 467 kb/s Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s Stream #0.1: Video: wmv3, yuv420p, 320x240 [PAR 0:1 DAR 0:1], 400 kb/s, 29.97 tb(r) Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 29.97 tb(c) Stream #0.1: Audio: libmp3lame, 44100 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -&gt; #0.0 Stream #0.0 -&gt; #0.1 Press [q] to stop encoding frame=25846 fps=132 q=9.0 Lsize= 88486kB time=862.4 bitrate= 840.5kbits/s video:80827kB audio:6738kB global headers:0kB muxing overhead 1.050642% </code></pre> <p>While another file, fails:</p> <pre><code>FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) [wmv3 @ 0x3700940d20]Extra data: 8 bits left, value: 0 Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -&gt; 25.00 (25/1) Input #0, asf, from 'bad3.wmv': Duration: 00:06:34.9, start: 4.000000, bitrate: 1666 kb/s Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 256 kb/s Stream #0.1: Video: wmv3, yuv420p, 512x384 [PAR 0:1 DAR 0:1], 1395 kb/s, 25.00 tb(r) File 'ok.flv' already exists. Overwrite ? [y/N] y Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 25.00 tb(c) Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -&gt; #0.0 Stream #0.0 -&gt; #0.1 Unsupported codec (id=0) for input stream #0.0 </code></pre> <p>The only difference I see is with the Input audio codec</p> <p>Working:</p> <pre><code>Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s </code></pre> <p>Not working:</p> <pre><code> Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 64 kb/s </code></pre> <p>Any ideas?</p>
[ { "answer_id": 87837, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "<p>Well the obvious answer is that the audio is encoded differently in the second wmv file, so they are not completely identic...
2008/09/17
[ "https://Stackoverflow.com/questions/87760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ive been smashing my head with this for a while. I have 2 completely identical .wmv files encoded with wmv3 codec. I put them both through ffmpeg with the following command: ``` /usr/bin/ffmpeg -i file.wmv -ar 44100 -ab 64k -qscale 9 -s 512x384 -f flv file.flv ``` One file converts just fine, and gives me the following output: ``` FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 29.97 (30000/1001) Input #0, asf, from 'ok.wmv': Duration: 00:14:22.3, start: 3.000000, bitrate: 467 kb/s Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s Stream #0.1: Video: wmv3, yuv420p, 320x240 [PAR 0:1 DAR 0:1], 400 kb/s, 29.97 tb(r) Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 29.97 tb(c) Stream #0.1: Audio: libmp3lame, 44100 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -> #0.0 Stream #0.0 -> #0.1 Press [q] to stop encoding frame=25846 fps=132 q=9.0 Lsize= 88486kB time=862.4 bitrate= 840.5kbits/s video:80827kB audio:6738kB global headers:0kB muxing overhead 1.050642% ``` While another file, fails: ``` FFmpeg version SVN-r11070, Copyright (c) 2000-2007 Fabrice Bellard, et al. configuration: --prefix=/usr --incdir=/usr/include/ffmpeg --libdir=/usr/lib64 --shlibdir=/usr/lib64 --mandir=/usr/share/man --arch=x86_64 --extra-cflags=-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic --enable-liba52 --enable-libfaac --enable-libfaad --enable-libgsm --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-libxvid --enable-libx264 --enable-pp --enable-pthreads --disable-static --enable-shared --enable-gpl --disable-debug --disable-optimizations --disable-strip libavutil version: 49.5.0 libavcodec version: 51.48.0 libavformat version: 51.19.0 built on Jun 25 2008 09:17:38, gcc: 4.1.2 20070925 (Red Hat 4.1.2-33) [wmv3 @ 0x3700940d20]Extra data: 8 bits left, value: 0 Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000/1) -> 25.00 (25/1) Input #0, asf, from 'bad3.wmv': Duration: 00:06:34.9, start: 4.000000, bitrate: 1666 kb/s Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 256 kb/s Stream #0.1: Video: wmv3, yuv420p, 512x384 [PAR 0:1 DAR 0:1], 1395 kb/s, 25.00 tb(r) File 'ok.flv' already exists. Overwrite ? [y/N] y Output #0, flv, to 'ok.flv': Stream #0.0: Video: flv, yuv420p, 512x384 [PAR 0:1 DAR 0:1], q=2-31, 200 kb/s, 25.00 tb(c) Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, 64 kb/s Stream mapping: Stream #0.1 -> #0.0 Stream #0.0 -> #0.1 Unsupported codec (id=0) for input stream #0.0 ``` The only difference I see is with the Input audio codec Working: ``` Stream #0.0: Audio: wmav2, 44100 Hz, stereo, 64 kb/s ``` Not working: ``` Stream #0.0: Audio: 0x0162, 48000 Hz, stereo, 64 kb/s ``` Any ideas?
It is in fact the audio format, which causes trouble. Audio formats are identified by its TwoCC (0x0162 here). You can look up the different TwoCCs here: <http://wiki.multimedia.cx/index.php?title=TwoCC> and you'll find: 0x0162 Windows Media Audio Professional V9 This codec isn't supported yet by ffmpeg and mencoder as far as I know. You can search at google for "`ffmpeg audio 0x0162`" and check for yourself.
87,795
<p>All I want is to update an ListViewItem's text whithout seeing any flickering.</p> <p>This is my code for updating (called several times):</p> <pre><code>listView.BeginUpdate(); listViewItem.SubItems[0].Text = state.ToString(); // update the state listViewItem.SubItems[1].Text = progress.ToString(); // update the progress listView.EndUpdate(); </code></pre> <p>I've seen some solutions that involve overriding the component's <code>WndProc():</code></p> <pre><code>protected override void WndProc(ref Message m) { if (m.Msg == (int)WM.WM_ERASEBKGND) { m.Msg = (int)IntPtr.Zero; } base.WndProc(ref m); } </code></pre> <p><strong>They say it solves the problem, but in my case It didn't</strong>. I believe this is because I'm using icons on every item.</p>
[ { "answer_id": 87840, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 0, "selected": false, "text": "<p>If you only want to update the text, simply set the changed SubItem's text directly rather than updating the entire ListV...
2008/09/17
[ "https://Stackoverflow.com/questions/87795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ]
All I want is to update an ListViewItem's text whithout seeing any flickering. This is my code for updating (called several times): ``` listView.BeginUpdate(); listViewItem.SubItems[0].Text = state.ToString(); // update the state listViewItem.SubItems[1].Text = progress.ToString(); // update the progress listView.EndUpdate(); ``` I've seen some solutions that involve overriding the component's `WndProc():` ``` protected override void WndProc(ref Message m) { if (m.Msg == (int)WM.WM_ERASEBKGND) { m.Msg = (int)IntPtr.Zero; } base.WndProc(ref m); } ``` **They say it solves the problem, but in my case It didn't**. I believe this is because I'm using icons on every item.
To end this question, here is a helper class that should be called when the form is loading for each ListView or any other ListView's derived control in your form. Thanks to "Brian Gillespie" for giving the solution. ``` public enum ListViewExtendedStyles { /// <summary> /// LVS_EX_GRIDLINES /// </summary> GridLines = 0x00000001, /// <summary> /// LVS_EX_SUBITEMIMAGES /// </summary> SubItemImages = 0x00000002, /// <summary> /// LVS_EX_CHECKBOXES /// </summary> CheckBoxes = 0x00000004, /// <summary> /// LVS_EX_TRACKSELECT /// </summary> TrackSelect = 0x00000008, /// <summary> /// LVS_EX_HEADERDRAGDROP /// </summary> HeaderDragDrop = 0x00000010, /// <summary> /// LVS_EX_FULLROWSELECT /// </summary> FullRowSelect = 0x00000020, /// <summary> /// LVS_EX_ONECLICKACTIVATE /// </summary> OneClickActivate = 0x00000040, /// <summary> /// LVS_EX_TWOCLICKACTIVATE /// </summary> TwoClickActivate = 0x00000080, /// <summary> /// LVS_EX_FLATSB /// </summary> FlatsB = 0x00000100, /// <summary> /// LVS_EX_REGIONAL /// </summary> Regional = 0x00000200, /// <summary> /// LVS_EX_INFOTIP /// </summary> InfoTip = 0x00000400, /// <summary> /// LVS_EX_UNDERLINEHOT /// </summary> UnderlineHot = 0x00000800, /// <summary> /// LVS_EX_UNDERLINECOLD /// </summary> UnderlineCold = 0x00001000, /// <summary> /// LVS_EX_MULTIWORKAREAS /// </summary> MultilWorkAreas = 0x00002000, /// <summary> /// LVS_EX_LABELTIP /// </summary> LabelTip = 0x00004000, /// <summary> /// LVS_EX_BORDERSELECT /// </summary> BorderSelect = 0x00008000, /// <summary> /// LVS_EX_DOUBLEBUFFER /// </summary> DoubleBuffer = 0x00010000, /// <summary> /// LVS_EX_HIDELABELS /// </summary> HideLabels = 0x00020000, /// <summary> /// LVS_EX_SINGLEROW /// </summary> SingleRow = 0x00040000, /// <summary> /// LVS_EX_SNAPTOGRID /// </summary> SnapToGrid = 0x00080000, /// <summary> /// LVS_EX_SIMPLESELECT /// </summary> SimpleSelect = 0x00100000 } public enum ListViewMessages { First = 0x1000, SetExtendedStyle = (First + 54), GetExtendedStyle = (First + 55), } /// <summary> /// Contains helper methods to change extended styles on ListView, including enabling double buffering. /// Based on Giovanni Montrone's article on <see cref="http://www.codeproject.com/KB/list/listviewxp.aspx"/> /// </summary> public class ListViewHelper { private ListViewHelper() { } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SendMessage(IntPtr handle, int messg, int wparam, int lparam); public static void SetExtendedStyle(Control control, ListViewExtendedStyles exStyle) { ListViewExtendedStyles styles; styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); styles |= exStyle; SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } public static void EnableDoubleBuffer(Control control) { ListViewExtendedStyles styles; // read current style styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); // enable double buffer and border select styles |= ListViewExtendedStyles.DoubleBuffer | ListViewExtendedStyles.BorderSelect; // write new style SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } public static void DisableDoubleBuffer(Control control) { ListViewExtendedStyles styles; // read current style styles = (ListViewExtendedStyles)SendMessage(control.Handle, (int)ListViewMessages.GetExtendedStyle, 0, 0); // disable double buffer and border select styles -= styles & ListViewExtendedStyles.DoubleBuffer; styles -= styles & ListViewExtendedStyles.BorderSelect; // write new style SendMessage(control.Handle, (int)ListViewMessages.SetExtendedStyle, 0, (int)styles); } } ```
87,812
<p>Say I have the following class</p> <pre><code>MyComponent : IMyComponent { public MyComponent(int start_at) {...} } </code></pre> <p>I can register an instance of it with castle windsor via xml as follows</p> <pre><code>&lt;component id="sample" service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample"&gt; &lt;parameters&gt; &lt;start_at&gt;1&lt;/start_at &gt; &lt;/parameters&gt; &lt;/component&gt; </code></pre> <p>How would I go about doing the exact same thing but in code? (Notice, the constructor parameter)</p>
[ { "answer_id": 87893, "author": "Gareth", "author_id": 1313, "author_profile": "https://Stackoverflow.com/users/1313", "pm_score": 0, "selected": false, "text": "<p>You need to pass in an IDictionary when you ask the container for the instance.</p>\n\n<p>You'd use this Resolve overload o...
2008/09/17
[ "https://Stackoverflow.com/questions/87812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
Say I have the following class ``` MyComponent : IMyComponent { public MyComponent(int start_at) {...} } ``` I can register an instance of it with castle windsor via xml as follows ``` <component id="sample" service="NS.IMyComponent, WindsorSample" type="NS.MyComponent, WindsorSample"> <parameters> <start_at>1</start_at > </parameters> </component> ``` How would I go about doing the exact same thing but in code? (Notice, the constructor parameter)
Edit: Used the answers below code with the Fluent Interface :) ``` namespace WindsorSample { using Castle.MicroKernel.Registration; using Castle.Windsor; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; public class MyComponent : IMyComponent { public MyComponent(int start_at) { this.Value = start_at; } public int Value { get; private set; } } public interface IMyComponent { int Value { get; } } [TestFixture] public class ConcreteImplFixture { [Test] void ResolvingConcreteImplShouldInitialiseValue() { IWindsorContainer container = new WindsorContainer(); container.Register( Component.For<IMyComponent>() .ImplementedBy<MyComponent>() .Parameters(Parameter.ForKey("start_at").Eq("1"))); Assert.That(container.Resolve<IMyComponent>().Value, Is.EqualTo(1)); } } } ```
87,818
<p>Hi I am trying to find a way to read the cookie that i generated in .net web application to read that on the php page because i want the users to login once but they should be able to view .net and php pages ,until the cookie expires user should not need to login in again , but both .net and php web applications are on different servers , help me with this issue please , thanks</p>
[ { "answer_id": 87834, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>any cookie given to a browser will be readable by server processing the request --- they're language agnostic.</p>\n\n<p>try...
2008/09/17
[ "https://Stackoverflow.com/questions/87818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Hi I am trying to find a way to read the cookie that i generated in .net web application to read that on the php page because i want the users to login once but they should be able to view .net and php pages ,until the cookie expires user should not need to login in again , but both .net and php web applications are on different servers , help me with this issue please , thanks
You mention that : > > but both .net and php web applications are on different servers > > > Are both applications running under the same domain name? (ie: www.mydomain.com) or are they on different domains? If they're on the same domain, then you can do what you're trying to do in PHP by using the $\_COOKIE variable. Just get the cookie's value by ``` $myCookie = $_COOKIE["cookie_name"]; ``` Then you can do whatever you want with the value of $myCookie. But if they're on different domains (ie: foo.mydomain.com and bar.mydomain.com), you cannot access the cookie from both sites. The web browser will only send a cookie to pages on the domain that set the cookie. However, if you originally set the cookie with only the top-level domain (mydomain.com), then sub-domains (anything.mydomain.com) should be able to read the cookie.
87,821
<p>Is it possible to use an <strong>IF</strong> clause within a <strong>WHERE</strong> clause in MS SQL?</p> <p>Example:</p> <pre><code>WHERE IF IsNumeric(@OrderNumber) = 1 OrderNumber = @OrderNumber ELSE OrderNumber LIKE '%' + @OrderNumber + '%' </code></pre>
[ { "answer_id": 87833, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>Use a <a href=\"http://msdn.microsoft.com/en-us/library/ms181765.aspx\" rel=\"noreferrer\">CASE</a> statement instea...
2008/09/17
[ "https://Stackoverflow.com/questions/87821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/299/" ]
Is it possible to use an **IF** clause within a **WHERE** clause in MS SQL? Example: ``` WHERE IF IsNumeric(@OrderNumber) = 1 OrderNumber = @OrderNumber ELSE OrderNumber LIKE '%' + @OrderNumber + '%' ```
Use a [CASE](http://msdn.microsoft.com/en-us/library/ms181765.aspx) statement **UPDATE:** The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows: ``` WHERE OrderNumber LIKE CASE WHEN IsNumeric(@OrderNumber) = 1 THEN @OrderNumber ELSE '%' + @OrderNumber END ``` Or you can use an IF statement like @[N. J. Reed](https://stackoverflow.com/questions/87821/sql-if-clause-within-where-clause#87992) points out.
87,831
<p>Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own compiler. Can anyone point me at a way to do that or at least how to set up a target of my own that will use our target platform's compiler?</p>
[ { "answer_id": 87844, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 2, "selected": false, "text": "<p>You need to write your own task. <a href=\"http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/07/writing-cu...
2008/09/17
[ "https://Stackoverflow.com/questions/87831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424554/" ]
Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own compiler. Can anyone point me at a way to do that or at least how to set up a target of my own that will use our target platform's compiler?
Here is one I did for Delphi. Each 'arg' is a separate param with a value defined elsewhere. The target is called with the params set up before calling it. ``` <target name="build.application"> <exec program="dcc32" basedir="${Delphi.Bin}" workingdir="${Application.Folder}" verbose="true"> <arg value="${Application.Compiler.Directive}" /> <arg value="-Q" /> <arg value="/B" /> <arg value="/E${Application.Output.Folder}" /> <arg value="/U${Application.Lib.Folder};${Application.Search.Folder}" /> <arg value="${Application.Folder}\${Delphi.Project}" /> </exec> </target> ```
87,877
<p>I am trying to build a dependency graph of tables based on the foreign keys between them. This graph needs to start with an arbitrary table name as its root. I could, given a table name look up the tables that reference it using the all_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient. I wrote a recursive query that does this for all tables, but when I add:</p> <pre><code>START WITH Table_Name=:tablename </code></pre> <p>It doesn't return the entire tree.</p>
[ { "answer_id": 88217, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 2, "selected": false, "text": "<p>Simplest way to do this is to copy all the FK info into a simple, 2-column (parent,child) table, and then use the...
2008/09/17
[ "https://Stackoverflow.com/questions/87877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
I am trying to build a dependency graph of tables based on the foreign keys between them. This graph needs to start with an arbitrary table name as its root. I could, given a table name look up the tables that reference it using the all\_constraints view, then look up the tables that reference them, and so on, but this would be horrible inefficient. I wrote a recursive query that does this for all tables, but when I add: ``` START WITH Table_Name=:tablename ``` It doesn't return the entire tree.
``` select parent, child, level from ( select parent_table.table_name parent, child_table.table_name child from user_tables parent_table, user_constraints parent_constraint, user_constraints child_constraint, user_tables child_table where parent_table.table_name = parent_constraint.table_name and parent_constraint.constraint_type IN( 'P', 'U' ) and child_constraint.r_constraint_name = parent_constraint.constraint_name and child_constraint.constraint_type = 'R' and child_table.table_name = child_constraint.table_name and child_table.table_name != parent_table.table_name ) start with parent = 'DEPT' connect by prior child = parent ``` should work (replace the table name, of course) assuming that everything is in the same schema. Use the DBA\_ versions of the data dictionary tables and conditions for the OWNER and R\_OWNER columns if you need to handle cross-schema dependencies. On further reflection, this does not account for self-referential constraints (i.e. a constraint on the EMP table that the MGR column references the EMPNO column) either, so you'd have to modify the code to handle that case if you need to deal with self-referential constraints. For testing purposes, I added a few new tables to the SCOTT schema that also reference the DEPT table (including a grandchild dependency) ``` SQL> create table dept_child2 ( 2 deptno number references dept( deptno ) 3 ); Table created. SQL> create table dept_child3 ( 2 dept_child3_no number primary key, 3 deptno number references dept( deptno ) 4 ); Table created. SQL> create table dept_grandchild ( 2 dept_child3_no number references dept_child3( dept_child3_no ) 3 ); Table created. ``` and verified that the query returned the expected output ``` SQL> ed Wrote file afiedt.buf 1 select parent, child, level from ( 2 select parent_table.table_name parent, child_table.table_name child 3 from user_tables parent_table, 4 user_constraints parent_constraint, 5 user_constraints child_constraint, 6 user_tables child_table 7 where parent_table.table_name = parent_constraint.table_name 8 and parent_constraint.constraint_type IN( 'P', 'U' ) 9 and child_constraint.r_constraint_name = parent_constraint.constraint_name 10 and child_constraint.constraint_type = 'R' 11 and child_table.table_name = child_constraint.table_name 12 and child_table.table_name != parent_table.table_name 13 ) 14 start with parent = 'DEPT' 15* connect by prior child = parent SQL> / PARENT CHILD LEVEL ------------------------------ ------------------------------ ---------- DEPT DEPT_CHILD3 1 DEPT_CHILD3 DEPT_GRANDCHILD 2 DEPT DEPT_CHILD2 1 DEPT EMP 1 ```
87,902
<p>I am trying to validate user id's matching the example:</p> <pre><code>smith.jack or smith.jack.s </code></pre> <p>In other words, any number of non-whitespace characters (except dot), followed by exactly one dot, followed by any number of non-whitespace characters (except dot), optionally followed by exactly one dot followed by any number of non-whitespace characters (except dot). I have come up with several variations that work fine except for allowing consecutive dots! For example, the following Regex</p> <pre><code>^([\S][^.]*[.]{1}[\S][^.]*|[\S][^.]*[.]{1}[\S][^.]*[.]{1}[\S][^.]*)$ </code></pre> <p>matches "smith.jack" and "smith.jack.s" but also matches "smith..jack" "smith..jack.s" ! My gosh, it even likes a dot as a first character. It seems like it would be so simple to code, but it isn't. I am using .NET, btw.</p> <p>Frustrating.</p>
[ { "answer_id": 87919, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 1, "selected": false, "text": "<pre><code>[^\\s.]+\\.[^\\s.]+(\\.[^\\s.]+)?\n</code></pre>\n\n<p>BTW what you asked for allows \".\" and \"..\"</p>\n" }, { ...
2008/09/17
[ "https://Stackoverflow.com/questions/87902", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to validate user id's matching the example: ``` smith.jack or smith.jack.s ``` In other words, any number of non-whitespace characters (except dot), followed by exactly one dot, followed by any number of non-whitespace characters (except dot), optionally followed by exactly one dot followed by any number of non-whitespace characters (except dot). I have come up with several variations that work fine except for allowing consecutive dots! For example, the following Regex ``` ^([\S][^.]*[.]{1}[\S][^.]*|[\S][^.]*[.]{1}[\S][^.]*[.]{1}[\S][^.]*)$ ``` matches "smith.jack" and "smith.jack.s" but also matches "smith..jack" "smith..jack.s" ! My gosh, it even likes a dot as a first character. It seems like it would be so simple to code, but it isn't. I am using .NET, btw. Frustrating.
^([^.\s]+)\.([^.\s]+)(?:\.([^.\s]+))?$
87,909
<p>Is it possible to set the title of a page when it's simply a loaded SWF?</p>
[ { "answer_id": 87984, "author": "madcolor", "author_id": 13954, "author_profile": "https://Stackoverflow.com/users/13954", "pm_score": 0, "selected": false, "text": "<p>I would think you would be able to do it. You would have to access the javascript DOM. </p>\n\n<p>A couple links that ...
2008/09/17
[ "https://Stackoverflow.com/questions/87909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/69665/" ]
Is it possible to set the title of a page when it's simply a loaded SWF?
This is how I would do it: ``` ExternalInterface.call("document.title = 'Hello World'"); ``` Or more generalized: ``` function setPageTitle( newTitle : String ) : void { var jsCode : String = "function( title ) { document.title = title; }"; ExternalInterface.call(jsCode, newTitle); } ```
87,934
<p>In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working.</p> <p>I has used the auto-complete plugin provided with Notepad++, which presented me with <code>onClick</code>.</p> <p>When I changed the capital <code>C</code> to a small <code>c</code>, it did work.</p> <p>So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals.</p> <p>But when you change <code>getElementById</code> to <code>getelementbyid</code>, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters.</p> <p>So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?</p>
[ { "answer_id": 87958, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 6, "selected": true, "text": "<p>Javascript is <strong>ALWAYS</strong> case-sensitive, html is not.</p>\n\n<p>It sounds as thought you are talking about wh...
2008/09/17
[ "https://Stackoverflow.com/questions/87934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11795/" ]
In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working. I has used the auto-complete plugin provided with Notepad++, which presented me with `onClick`. When I changed the capital `C` to a small `c`, it did work. So first of all, when looking at the functions in the auto-completion, I noticed a lot of functions using capitals. But when you change `getElementById` to `getelementbyid`, you also get an error, and to make matters worse, my handbook from school writes all the stuff with capital letters but the solutions are all done in small letters. So what is it with JavaScript and its selective nature towards which functions can have capital letters in them and which can't?
Javascript is **ALWAYS** case-sensitive, html is not. It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is. So, you can do this: ``` <div id='divYo' onClick="alert('yo!');">Say Yo</div> // Upper-case 'C' ``` or: ``` <div id='divYo' onclick="alert('yo!');">Say Yo</div> // Lower-case 'C' ``` but through the DOM you must use the correct case. So this works: ``` getElementById('divYo').onclick = function() { alert('yo!'); }; // Lower-case 'C' ``` but you cannot do this: ``` getElementById('divYo').onClick = function() { alert('yo!'); }; // Upper-case 'C' ``` EDIT: CMS makes a great point that most DOM methods and properties are in [camelCase](http://www.perlmonks.org/?node_id=45213). The one exception that comes to mind are event handler properties and these are generally accepted to be [the wrong way to attach to events](http://javascript.about.com/library/blonclick.htm) anyway. Prefer using [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) as in: ``` document.getElementById('divYo').addEventListener('click', modifyText, false); ```
87,970
<p>I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.</p> <p>For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:</p> <pre><code>int[] IntArray = {1,2,3}; </code></pre> <p>Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.</p>
[ { "answer_id": 88017, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 4, "selected": true, "text": "<p>Array list has ctor which accepts ICollection, which is implemented by the Array class.</p>\n\n<pre><code>object[] my...
2008/09/17
[ "https://Stackoverflow.com/questions/87970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16866/" ]
I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method. For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like: ``` int[] IntArray = {1,2,3}; ``` Is there a similar way to do this for an arraylist? I tried the addrange method but the curly brace method doesn't implement the ICollection interface.
Array list has ctor which accepts ICollection, which is implemented by the Array class. ``` object[] myArray = new object[] {1,2,3,"string1","string2"}; ArrayList myArrayList = new ArrayList(myArray); ```
87,986
<p>In C# you can get the original error and trace the execution path (stack trace) using the inner exception that is passed up. I would like to know how this can be achieved using the error handling try/catch in sql server 2005 when an error occurs in a stored procedure nested 2 or 3 levels deep. </p> <p>I am hoping that functions like ERROR_MESSAGE(), ERROR_LINE(), ERROR_PROCEDURE(), ERROR_SEVERITY() can be easily passed up the line so that the top level stored proc can access them.</p>
[ { "answer_id": 88941, "author": "Daniel", "author_id": 6852, "author_profile": "https://Stackoverflow.com/users/6852", "pm_score": 0, "selected": false, "text": "<p>One way you could do this would be to create an in memory table and insert rows into it when you catch an exception. You w...
2008/09/17
[ "https://Stackoverflow.com/questions/87986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11989/" ]
In C# you can get the original error and trace the execution path (stack trace) using the inner exception that is passed up. I would like to know how this can be achieved using the error handling try/catch in sql server 2005 when an error occurs in a stored procedure nested 2 or 3 levels deep. I am hoping that functions like ERROR\_MESSAGE(), ERROR\_LINE(), ERROR\_PROCEDURE(), ERROR\_SEVERITY() can be easily passed up the line so that the top level stored proc can access them.
The best way to handle this is using OUTPUT parameters and XML. The sample code below will demonstrate how and you can modify what you do with the XML in the TopProcedure to better handle your response to the error. ``` USE tempdb go CREATE PROCEDURE SubProcedure @RandomNumber int, @XMLErrors XML OUTPUT AS BEGIN BEGIN TRY IF @RandomNumber > 50 RaisError('Bad number set!',16,1) else select @RandomNumber END TRY BEGIN CATCH SET @XMLErrors = (SELECT * FROM (SELECT ERROR_MESSAGE() ErrorMessage, ERROR_LINE() ErrorLine, ERROR_PROCEDURE() ErrorProcedure, ERROR_SEVERITY() ErrorSeverity) a FOR XML AUTO, ELEMENTS, ROOT('root')) END CATCH END go CREATE PROCEDURE TopProcedure @RandomNumber int AS BEGIN declare @XMLErrors XML exec SubProcedure @RandomNumber, @XMLErrors OUTPUT IF @XMLErrors IS NOT NULL select @XMLErrors END go exec TopProcedure 25 go exec TopProcedure 55 go DROP PROCEDURE TopProcedure GO DROP PROCEDURE SubProcedure GO ``` The initial call to TopProcedure will return 25. The second will return an XML block that looks like this: ``` <root> <a> <ErrorMessage>Bad number set!</ErrorMessage> <ErrorLine>6</ErrorLine> <ErrorProcedure>SubProcedure</ErrorProcedure> <ErrorSeverity>16</ErrorSeverity> </a> </root> ``` Enjoy
87,999
<p>Well the docs finally said it, I need to take it easy on my wrist for a few months. Being that I'm a .NET Developer this could end my livelihood for a little while, something I'm not anxious to do. That said, are there any good handsfree options for developers? Anyone had success using any of the speech recognition software out there?</p> <p>POSTSCRIPT: I've recovered my arm again to the point where two-handed programming isn't a problem. Dragon Naturally speaking worked well enough, but was slower, not like the keyboard where I was programming faster than I thought.</p>
[ { "answer_id": 88070, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.hanselman.com/blog/SpeechRecognitionInWindowsVistaImListening.aspx\" rel=\"nofollow noreferrer\">S...
2008/09/17
[ "https://Stackoverflow.com/questions/87999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16868/" ]
Well the docs finally said it, I need to take it easy on my wrist for a few months. Being that I'm a .NET Developer this could end my livelihood for a little while, something I'm not anxious to do. That said, are there any good handsfree options for developers? Anyone had success using any of the speech recognition software out there? POSTSCRIPT: I've recovered my arm again to the point where two-handed programming isn't a problem. Dragon Naturally speaking worked well enough, but was slower, not like the keyboard where I was programming faster than I thought.
### It's out there, and it works... There are quite a few speech recognition programs out there, of which [Dragon NaturallySpeaking](http://www.nuance.com/naturallyspeaking/) is, I think, one of the most widely used ones. I've used it myself, and have been impressed with its quality. That being a couple of years ago, I guess things have improved even further by now. ### ...but it ain't easy... Even though it works amazingly well, I won't say it's an easy solution. It takes time to train the program, and even then, it'll make mistakes. It's painstakingly slow compared to typing, so I had to keep saying to myself "Don't grab the keyboard, don't grab the keyboard, ..." (after which I'd grab the keyboard anyway). I myself tend to mumble a bit, which didn't make things much better, either ;-). Especially the first weeks can be frustrating. You can even get [voice-related problems](http://www.ataword.com/voice.html) if you [strain your voice too much](http://archives.cnn.com/2000/TECH/computing/05/23/voice.saving.tips.idg/). ### ...especially for programmers! All in all, it's certainly a workable solution **for people writing normal text/prose**. As a programmer, you're in a completely different realm, for which there are no real solutions. Things might have changed by now, but I'd be surprised if they have. What's the problem? Most SR software is built to recognize normal language. Programmers write very cryptic stuff, and it's hard, if not impossible, to find software that does the conversion between normal language and code. For example, how would you dictate: ``` if (somevar == 'a') { print('You pressed a!'); } ``` Using the commands in your average SR program, this is a huge pain: "if space left bracket equal sign equal sign apostrophe spell a apostrophe ...". And I'm not even talking about *navigating* your code. Ever noticed how much you're using the keyboard while programming, and how different that usage is from how a 'normal' user uses the keyboard? ### How to make the best of it Thus far, I've only worked with Dragon NaturallySpeaking (DNS), so I can only speak for that product. There are some interesting add-ons and websites targeted for people like programmers: * [Vocola](http://www.vocola.net) is an unofficial plugin that allows you to easily add your own commands to DNS. I found it essential, basically. You'll also be able to find command sets written by other programmers, for e.g. navigating code. It's based on a software package written in Python, so there are also some more advanced and fancy packages around. Also check out Vocola's [Resources page](http://vocola.net/VoiceResources.html). (Warning: when I used it, there were some problems with installing Vocola; check out the newsgroup below for info!) * [SpeechComputing.com](http://speechcomputing.com/) is a forum/newsgroup with lots of interesting discussions. A good place to start. ### Closing remarks It seems that the best solution to this problem is, really: * Find ways around actual coding. * Try to recover. I'm somewhat reluctant to recommend this book, but it seems to work amazingly well for people with RSI/carpal tunnel and other chronic pain issues: [J.E. Sarno, Mindbody prescription](https://rads.stackoverflow.com/amzn/click/com/0446675156). I'm working with it right now, and I think it's definitely worth reading.
88,011
<p>For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for <a href="http://www.foobar.com/anything" rel="nofollow noreferrer">http://www.foobar.com/anything</a> to <a href="http://foobar.com/anything" rel="nofollow noreferrer">http://foobar.com/anything</a>. The best I could come up with is a mod_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"? </p> <p>PS: I found <a href="https://stackoverflow.com/questions/50931/redirecting-non-www-url-to-www">this somewhat related question</a>, but it's for IIS and does the opposite of what I want. Also it's still complex.</p>
[ { "answer_id": 88034, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<pre><code>RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www.domain.com$ [NC]\nRewriteRule ^(.*)$ http://domain.com/$1 [R=301,...
2008/09/17
[ "https://Stackoverflow.com/questions/88011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
For various reasons, such as cookies, SEO, and to keep things simple, I would like to make apache automatically redirect any requests for <http://www.foobar.com/anything> to <http://foobar.com/anything>. The best I could come up with is a mod\_rewrite-based monstrosity, is there some easy simple way to tell it "Redirect all requests for domain ABC to XYZ"? PS: I found [this somewhat related question](https://stackoverflow.com/questions/50931/redirecting-non-www-url-to-www), but it's for IIS and does the opposite of what I want. Also it's still complex.
It's as easy as: ``` <VirtualHost 10.0.0.1:80> ServerName www.example.com Redirect permanent / http://example.com/ </VirtualHost> ``` Adapt host names and IPs as needed :)
88,078
<p>I wand to construct an MSI which, in its installation process, will deploy itself along with its contained Files/Components, to the TargetDir.</p> <p>So MyApp.msi contains MyApp.exe and MyAppBootstrapperEmpty.exe (with no resources) in its File Table.</p> <p>The user launches a MyAppBootstrapperPackaged.exe (containing MyApp.msi as a resource, obtained from the internet somewhere, or email or otherwise). MyAppBootStrapperPackaged.exe extracts MyApp.msi to a temp folder and executes it via msiexec.exe.</p> <p>After the msiexec.exe process completes, I want MyApp.msi, MyBootstrapperEmpty.exe (AND MyApp.exe in %ProgramFiles%\MyApp folder so MyApp.exe can be assured access to MyApp.msi when it runs (for creating the below-mentioned packaged content).</p> <p>MyAppBootstrapper*.exe could try and copy MyApp.msi to %ProgramFiles%\MyApp folder, but would need elevation to do so, and would not allow for its removal via Windows Installer uninstall process (from Add/Remove Programs or otherwise), which should be preserved.</p> <p>Obviously (I think it's obvious - am I wrong?) I can't include the MSI as a file in my Media/CAB (chicken and egg scenario), so I believe it would have to be done via a Custom Action before the install process, adding the original MSI to the MSI DB's Media/CAB and the appropriate entry in the File table on the fly. Can this be done and if so how?</p> <p>Think of a content distribution model where content files are only ever to be distributed together with the App. Content is produced by the end user via the App at run time, and packaged into a distributable EXE which includes both the App and the content.</p> <p>MyApp's installer must remain an MSI, but may be executed by a Bootstrapper EXE. The installed MyApp.exe must have access to both MyApp.msi and EXE is to be "assembled" at runtime by the App from a base (empty) MyAppBootstrapper.exe, which is also installed by the MSI, and the content created by the end-user. The EXE's resource MSI must be the same as that used to install the App which is doing the runtime packaging.</p> <p>WIX is not to be installed with MyApp.</p> <p>There can be no network dependencies at run-/packaging- time (i.e. can't do the packaging via a Webservice - must be done locally).</p> <p>I am familiar with (and using) Custom Actions (managed and unmanaged, via DTF and otherwise).</p>
[ { "answer_id": 88366, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>So if I understand, then I think I would have the app create a transform (MST) that has the content files and apply that t...
2008/09/17
[ "https://Stackoverflow.com/questions/88078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8787/" ]
I wand to construct an MSI which, in its installation process, will deploy itself along with its contained Files/Components, to the TargetDir. So MyApp.msi contains MyApp.exe and MyAppBootstrapperEmpty.exe (with no resources) in its File Table. The user launches a MyAppBootstrapperPackaged.exe (containing MyApp.msi as a resource, obtained from the internet somewhere, or email or otherwise). MyAppBootStrapperPackaged.exe extracts MyApp.msi to a temp folder and executes it via msiexec.exe. After the msiexec.exe process completes, I want MyApp.msi, MyBootstrapperEmpty.exe (AND MyApp.exe in %ProgramFiles%\MyApp folder so MyApp.exe can be assured access to MyApp.msi when it runs (for creating the below-mentioned packaged content). MyAppBootstrapper\*.exe could try and copy MyApp.msi to %ProgramFiles%\MyApp folder, but would need elevation to do so, and would not allow for its removal via Windows Installer uninstall process (from Add/Remove Programs or otherwise), which should be preserved. Obviously (I think it's obvious - am I wrong?) I can't include the MSI as a file in my Media/CAB (chicken and egg scenario), so I believe it would have to be done via a Custom Action before the install process, adding the original MSI to the MSI DB's Media/CAB and the appropriate entry in the File table on the fly. Can this be done and if so how? Think of a content distribution model where content files are only ever to be distributed together with the App. Content is produced by the end user via the App at run time, and packaged into a distributable EXE which includes both the App and the content. MyApp's installer must remain an MSI, but may be executed by a Bootstrapper EXE. The installed MyApp.exe must have access to both MyApp.msi and EXE is to be "assembled" at runtime by the App from a base (empty) MyAppBootstrapper.exe, which is also installed by the MSI, and the content created by the end-user. The EXE's resource MSI must be the same as that used to install the App which is doing the runtime packaging. WIX is not to be installed with MyApp. There can be no network dependencies at run-/packaging- time (i.e. can't do the packaging via a Webservice - must be done locally). I am familiar with (and using) Custom Actions (managed and unmanaged, via DTF and otherwise).
Add an uncompressed medium to your wxs like this: ``` <Media Id='2'/> ``` And then create a component with a File element like this: ``` <File Source='/path/to/myinstaller.msi' Compressed='no' DiskId='2' /> ``` This will make the installer look for a file called "myinstaller.msi" on the installation medium, in the same folder as the msi that is being installed. The source path above should point to a dummy file, it is only there to appease wix. **Edit**: The following sample test.wxs demonstrates that it works. It produces a test.msi file which installs itself to c:\program files\test. Note that you need to put a dummy test.msi file in the same folder as text.wxs to appease wix. ``` <?xml version='1.0' encoding='utf-8'?> <Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'> <Product Name='ProductName' Id='*' Language='1033' Version='0.0.1' Manufacturer='ManufacturerName' > <Package Keywords='Installer' Description='Installer which installs itself' Manufacturer='ManufactererName' InstallerVersion='100' Languages='1033' Compressed='yes' SummaryCodepage='1252'/> <Media Id='1' Cabinet='test.cab' EmbedCab='yes'/> <Media Id='2' /> <Directory Id='TARGETDIR' Name="SourceDir"> <Directory Id='ProgramFilesFolder'> <Directory Id='TestFolder' Name='Test' > <Component Id="InstallMyself"> <File Source="./test.msi" Compressed="no" DiskId="2" /> </Component> </Directory> </Directory> </Directory> <Feature Id='Complete' Display='expand' Level='1' Title='Copy msi file to program files folder' Description='Test'> <ComponentRef Id="InstallMyself" /> </Feature> </Product> </Wix> ```
88,094
<p>I seem to make this mistake every time I set up a new development box. Is there a way to make sure you don't have to manually assign rights for the ASPNET user? I usually install .Net then IIS, then Visual Studio but it seems I still have to manually assign rights to the ASPNET user to get everything running correctly. Is my install order wrong?</p>
[ { "answer_id": 88124, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 3, "selected": true, "text": "<p>Install IIS, then .NET. The .NET installation will automatically register the needed things with IIS.</p>\n\n<p>If...
2008/09/17
[ "https://Stackoverflow.com/questions/88094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16636/" ]
I seem to make this mistake every time I set up a new development box. Is there a way to make sure you don't have to manually assign rights for the ASPNET user? I usually install .Net then IIS, then Visual Studio but it seems I still have to manually assign rights to the ASPNET user to get everything running correctly. Is my install order wrong?
Install IIS, then .NET. The .NET installation will automatically register the needed things with IIS. If you install .NET first, run this: ``` %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -i ``` to run the registration parts, and ``` %windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ga userA ``` to set up the security rights for userA
88,096
<p>I am working on a project with peek performance requirements, so we need to bulk (batch?) several operations (for example persisting the data to a database) for efficiency.</p> <p>However, I want our code to maintain an easy to understand flow, like:</p> <pre><code>input = Read(); parsed = Parse(input); if (parsed.Count &gt; 10) { status = Persist(parsed); ReportSuccess(status); return; } ReportFailure(); </code></pre> <p>The feature I'm looking for here is automatically have Persist() happen in bulks (and ergo asynchronously), but behave to its user as if it's synchronous (user should block until the bulk action completes). I want the implementor to be able to implement Persist(ICollection).</p> <p>I looked into flow-based programming, with which I am not highly familiar. I saw one library for fbp in C# <a href="http://www.jpaulmorrison.com/fbp/" rel="nofollow noreferrer">here</a>, and played a bit with Microsoft's Workflow Foundation, but my impression is that both are overkill for what I need. What would you use to implement a bulked flow behavior?</p> <p>Note that I would like to get code that is exactly like what I wrote (simple to understand &amp; debug), so solutions that involve yield or configuration in order to connect flows to one another are inadequate for my purpose. Also, <a href="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern" rel="nofollow noreferrer">chaining</a> is not what I'm looking for - I don't want to first build a chain and then run it, I want code that looks as if it is a simple flow ("Do A, Do B, if C then do D").</p>
[ { "answer_id": 88169, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 0, "selected": false, "text": "<p>I don't know if this is what you need, because it's sqlserver based, but have you tried taking a look to <a href=\"http://...
2008/09/17
[ "https://Stackoverflow.com/questions/88096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I am working on a project with peek performance requirements, so we need to bulk (batch?) several operations (for example persisting the data to a database) for efficiency. However, I want our code to maintain an easy to understand flow, like: ``` input = Read(); parsed = Parse(input); if (parsed.Count > 10) { status = Persist(parsed); ReportSuccess(status); return; } ReportFailure(); ``` The feature I'm looking for here is automatically have Persist() happen in bulks (and ergo asynchronously), but behave to its user as if it's synchronous (user should block until the bulk action completes). I want the implementor to be able to implement Persist(ICollection). I looked into flow-based programming, with which I am not highly familiar. I saw one library for fbp in C# [here](http://www.jpaulmorrison.com/fbp/), and played a bit with Microsoft's Workflow Foundation, but my impression is that both are overkill for what I need. What would you use to implement a bulked flow behavior? Note that I would like to get code that is exactly like what I wrote (simple to understand & debug), so solutions that involve yield or configuration in order to connect flows to one another are inadequate for my purpose. Also, [chaining](http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern) is not what I'm looking for - I don't want to first build a chain and then run it, I want code that looks as if it is a simple flow ("Do A, Do B, if C then do D").
Common problem - instead of calling Persist I usually load up commands (or smt along those lines) into a Persistor class then after the loop is finished I call Persistor.Persist to persist the batch. Just a few pointers - If you're generating sql the commands you add to the persistor can represent your queries somehow (with built-in objects, custom objects or just query strings). If you're calling stored procedures you can use the commands to append stuff to a piece of xml tha will be passed down to the SP when you call the persist method. hope it helps - Pretty sure there's a pattern for this but dunno the name :)
88,235
<p>Recently I ran into this error in my web application:</p> <blockquote> <p>java.lang.OutOfMemoryError: PermGen space</p> </blockquote> <p>It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparently this can occur after redeploying an application a few times.</p> <p>What causes it and what can be done to avoid it? How do I fix the problem?</p>
[ { "answer_id": 88262, "author": "Chris", "author_id": 16907, "author_profile": "https://Stackoverflow.com/users/16907", "pm_score": 10, "selected": true, "text": "<p>The solution was to add these flags to JVM command line when Tomcat is started:</p>\n<pre><code>-XX:+CMSClassUnloadingEnab...
2008/09/17
[ "https://Stackoverflow.com/questions/88235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16907/" ]
Recently I ran into this error in my web application: > > java.lang.OutOfMemoryError: PermGen space > > > It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparently this can occur after redeploying an application a few times. What causes it and what can be done to avoid it? How do I fix the problem?
The solution was to add these flags to JVM command line when Tomcat is started: ``` -XX:+CMSClassUnloadingEnabled -XX:+CMSPermGenSweepingEnabled ``` You can do that by shutting down the tomcat service, then going into the Tomcat/bin directory and running tomcat6w.exe. Under the "Java" tab, add the arguments to the "Java Options" box. Click "OK" and then restart the service. If you get an error *the specified service does not exist as an installed service* you should run: ``` tomcat6w //ES//servicename ``` where ***servicename*** is the name of the server as viewed in services.msc Source: orx's comment on [Eric's Agile Answers](https://web.archive.org/web/20160124133922/http://www.jroller.com/agileanswers/entry/preventing_java_s_java_lang).
88,269
<p>In certain unknown situations selenium does not detect that a page has loaded when using the open method. I am using the Java API. For example (This code will not produce this error. I don't know of an externally visible page that will.):</p> <pre><code>Selenium browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com"); browser.start(); browser.open("http://www.google.com/webhp?hl=en"); browser.type("q", "hello world"); </code></pre> <p>When the error occurs, the call to 'open' times out, even though you can clearly see that the page has loaded successfully before the timeout occurs. Increasing the timeout does not help. The call to 'type' never occurs, no progress is made.</p> <p>How do you get selenium to recognize that the page has loaded when this error occurs?</p>
[ { "answer_id": 88315, "author": "Jim Deville", "author_id": 1591, "author_profile": "https://Stackoverflow.com/users/1591", "pm_score": 1, "selected": false, "text": "<p>When I do Selenium testing, I wait to see if a certain element is visible (waitForVisible), then I do my action. I usu...
2008/09/17
[ "https://Stackoverflow.com/questions/88269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4356/" ]
In certain unknown situations selenium does not detect that a page has loaded when using the open method. I am using the Java API. For example (This code will not produce this error. I don't know of an externally visible page that will.): ``` Selenium browser = new DefaultSelenium("localhost", 4444, "*firefox", "http://www.google.com"); browser.start(); browser.open("http://www.google.com/webhp?hl=en"); browser.type("q", "hello world"); ``` When the error occurs, the call to 'open' times out, even though you can clearly see that the page has loaded successfully before the timeout occurs. Increasing the timeout does not help. The call to 'type' never occurs, no progress is made. How do you get selenium to recognize that the page has loaded when this error occurs?
I faced this problem quite recently. All JS-based solutions didn't quite fit ICEFaces 2.x + Selenium 2.x/Webdriver combination I have. What I did and what worked for me is the following: In the corner of the screen, there's connection activity indicator. ``` <ice:outputConnectionStatus id="connectStat" showPopupOnDisconnect="true"/> ``` In my Java unit test, I wait until its 'idle' image comes back again: ``` private void waitForAjax() throws InterruptedException { for (int second = 0;; second++) { if (second >= 60) fail("timeout"); try { if ("visibility: visible;".equals( selenium.getAttribute("top_right_form:connectStat:connection-idle@style"))) { break; } } catch (Exception e) { } Thread.sleep(1000); } } ``` You can disable rendering of this indicator in production build, if showing it at the page is unnecessary, or use empty 1x1 gifs as its images. Works 100% (with popups, pushed messages etc.) and relieves you from the hell of specifying waitForElement(...) for each element separately. Hope this helps someone.
88,276
<p>I've been trying to figure this out for about two weeks. I'm able to create email items in people's folders, read the folders, all that stuff but for the life of me I can not get anything to work with the calendars.</p> <p>I can provide examples of the XML I'm sending to WebDav but hoping someone out there has done this and has an example?</p>
[ { "answer_id": 92523, "author": "Robert Sanders", "author_id": 16952, "author_profile": "https://Stackoverflow.com/users/16952", "pm_score": 2, "selected": false, "text": "<p>I did this in a Java program a few years back, and the way I did it was to PUT a VCALENDAR document into the fold...
2008/09/17
[ "https://Stackoverflow.com/questions/88276", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've been trying to figure this out for about two weeks. I'm able to create email items in people's folders, read the folders, all that stuff but for the life of me I can not get anything to work with the calendars. I can provide examples of the XML I'm sending to WebDav but hoping someone out there has done this and has an example?
I did this in a Java program a few years back, and the way I did it was to PUT a VCALENDAR document into the folder. One quirk is that the VCALENDAR had to be enclosed within an RFC822 message. It's a bizarre combination of WebDAV, email, and iCAL/VCAL, but it worked at the time on Exchange 2003 hosted at Link2Exchange. I'm sure there is an easier way, but this is what worked for me. Below I show a tcpdump packet trace of what happened. You should probably use ngrep/tcpdump on your own Outlook/Entourage client to see what it does. Note that "Cal2" is the name of my test calendar folder. You'd use "Calendar" for the main calendar folder. ``` T 10.0.1.95:59741 -> 66.211.136.9:80 [AP] PUT /exchange/yourname.domainname.com/Cal2/CC1.1163646061548.0.eml HTTP/1.1. translate: f. Content-Type: message/rfc822. Pragma: no-cache. Accept: */*. Cache-Control: no-cache. Authorization: Basic NOYOUCANTSEEMYPASSWORDYOUBASTARDS. User-Agent: Jakarta Commons-HttpClient/2.0final. Host: e1.exmx.net. Cookie: sessionid=29486b50-d398-4f76-9604-8421950c7dcd:0x0. Content-Length: 478. Expect: 100-continue. . T 66.211.136.9:80 -> 10.0.1.95:59741 [AP] HTTP/1.1 100 Continue. . T 10.0.1.95:59741 -> 66.211.136.9:80 [AP] content-class: urn:content-classes:appointment. Content-Type: text/calendar;. .method=REQUEST;. .charset="utf-8". Content-Transfer-Encoding: 8bit. . BEGIN:VCALENDAR. BEGIN:VEVENT. UID:E1+1382+1014+495066799@I1+1382+1014+6+495066799. SUMMARY:Voice Architecture Leads Meeting. PRIORITY:5. LOCATION:x44444 pc:6879. DTSTART:20061122T193000Z. DTEND:20061122T203000Z. DTSTAMP:20061110T074856Z. DESCRIPTION:this is a description. SUMMARY:this is a summary. END:VEVENT. END:VCALENDAR. T 66.211.136.9:80 -> 10.0.1.95:59741 [AP] HTTP/1.1 201 Created. Date: Thu, 16 Nov 2006 03:00:16 GMT. Server: Microsoft-IIS/6.0. X-Powered-By: ASP.NET. MS-Exchange-Permanent-URL: http://e1.exmx.net/exchange/yourname.yourdomain.com/-FlatUrlSpace-/122cda661de1da48936f9 44bda4dde6e-3af8a8/122cda661de1da48936f944bda4dde6e-3f3383. Location: http://e1.exmx.net/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml. Repl-UID: <rid:122cda661de1da48936f944bda4dde6e0000003f3383>. Content-Type: text/html. Content-Length: 110. Allow: OPTIONS, TRACE, GET, HEAD, DELETE, PUT, COPY, MOVE, PROPFIND, PROPPATCH, SEARCH, SUBSCRIBE, UNSUBSCRIBE, PO LL, BDELETE, BCOPY, BMOVE, BPROPPATCH, BPROPFIND, LOCK, UNLOCK. ResourceTag: <rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671>. GetETag: "122cda661de1da48936f944bda4dde6e0000003f4671". MS-WebStorage: 6.5.7638. Cache-Control: no-cache. ``` . ``` T 66.211.136.9:80 -> 10.0.1.95:59741 [AP] <body><h1>/exchange/yourname.yourdomain.com/Cal2/CC1.1163646061548.0.eml was created successfully</h1></body>. ``` You can verify that it worked using something like Cadaver to query the object's properties via WebDAV like so: ``` dav:/exchange/yourname@yourdomain.com/Cal2/> propget CC1.1163646061548.0.eml Fetching properties for `CC1.1163646061548.0.eml': textdescription = this is a description contentclass = urn:content-classes:appointment supportedlock = <lockentry><locktype><transaction><groupoperation></groupoperation></transaction></locktype><locks cope><local></local></lockscope></lockentry> permanenturl = http://e1.exmx.net/exchange/yourname@yourdomain.com/-FlatUrlSpace-/122cda661de1da48936f944bda4dde6e- 3af8a8/122cda661de1da48936f944bda4dde6e-3f3383 getcontenttype = message/rfc822 id = AQEAAAAAOvioAQAAAAA/M4MAAAAA mid = -8992774761696198655 uid = E1+1382+1014+495066799@I1+1382+1014+6+495066799 isfolder = 0 resourcetype = method = PUBLISH getetag = "122cda661de1da48936f944bda4dde6e0000003f4671" lockdiscovery = outlookmessageclass = IPM.Appointment creationdate = 2006-11-16T03:00:16.549Z outlookmessageclass = IPM.Appointment creationdate = 2006-11-16T03:00:16.549Z ntsecuritydescriptor = CAAEAAAAAAABAC+MMAAAAEwAAAAAAAAAFAAAAAIAHAABAAAAARAUAL8PHwABAQAAAAAABQcAAAABBQAAAAAABRUAAAC nkePD6LEa8iIT/+gqDAAAAQUAAAAAAAUVAAAAp5Hjw+ixGvIiE//oAQIAAA== dtstamp = 2006-11-10T07:48:56.000Z lastmodified = 2006-11-16T03:00:16.565Z dtstart = 2006-11-22T19:30:00.000Z location = x44444 pc:6879 duration = 3600 htmldescription = <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <HTML> <HEAD> <META NAME="Generator" CONTENT="MS Exchange Server version 6.5.7638.1"> <TITLE>this is a summary</TITLE> </HEAD> <BODY> <!-- Converted from text/plain format --> <P><FONT SIZE=2>this is a description</FONT> </P> </BODY> </HTML> ishidden = 0 parentname = http://e1.exmx.net/exchange/yourname@yourdomain.com/Cal2/ meetingstatus = TENTATIVE subject = this is a summary getcontentlength = 631 normalizedsubject = this is a summary isstructureddocument = 0 repl-uid = rid:122cda661de1da48936f944bda4dde6e0000003f3383 timezoneid = 0 displayname = CC1.1163646061548.0.eml href = http://e1.exmx.net/exchange/yourname@yourdomain.com/Cal2/CC1.1163646061548.0.eml nomodifyexceptions = 1 patternend = 2006-11-22T20:30:00.000Z isreadonly = 0 instancetype = 0 uid = AQEAAAAAPzODAAAAAAAAAAAAAAAA getlastmodified = 2006-11-16T03:00:16.565Z created = 2006-11-16T03:00:16.549Z sensitivity = 0 dtend = 2006-11-22T20:30:00.000Z hasattachment = 0 iscollection = 0 read = 1 resourcetag = rt:122cda661de1da48936f944bda4dde6e0000003f3383122cda661de1da48936f944bda4dde6e0000003f4671 patternstart = 2006-11-22T19:30:00.000Z priority = 0 sequence = 0 ```
88,306
<p>I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output?</p> <p>I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie.</p> <p>Is there another way that already exist to add a cookie that will go out on the next response?</p>
[ { "answer_id": 90665, "author": "Avi", "author_id": 9983, "author_profile": "https://Stackoverflow.com/users/9983", "pm_score": 2, "selected": false, "text": "<p>I've just looked into this in depth, and the answer seems to be no. Specifically, there's no way to get at the response from ...
2008/09/17
[ "https://Stackoverflow.com/questions/88306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2766176/" ]
I'm making a small web application in Seaside. I have a login component, and after the user logs in I want to send along a cookie when the next component renders itself. Is there a way to get at the object handling the response so I can add something to the headers it will output? I'm trying to avoid using WASession>>redirectWithCookies since it seems pretty kludgey to redirect only because I want to set a cookie. Is there another way that already exist to add a cookie that will go out on the next response?
There is currently no built-in way to add cookies during the action/callback phase of request processing. This is most likely a defect and is noted in this issue: <http://code.google.com/p/seaside/issues/detail?id=48> This is currently slated to be fixed for Seaside 2.9 but I don't know if it will even be backported to 2.8 or not. Keep in mind that there is already (by default) a redirection between the action and rendering phases to prevent a Refresh from re-triggering the callbacks, so in the grand scheme of things, one more redirect in this case isn't *so* bad. If you still want to dig further, have a look at WARenderContinuation>>handleRequest:. That's where callback processing is triggered and the redirect or rendering phase begun. **Edited to add:** The issue has now been fixed and (in the latest development code) you can now properly add cookies to the current response at any time. Simply access the response object in the current request context and add the cookie. For example, you might do something like: ``` self requestContext response addCookie: aCookie ``` This is unlikely to be backported to Seaside 2.8 as it required a fairly major shift in the way responses are handled.
88,311
<p>I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z":</p> <pre><code>value = ""; 8.times{value &lt;&lt; (65 + rand(25)).chr} </code></pre> <p>but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to:</p> <pre><code>value = ""; 8.times{value &lt;&lt; ((rand(2)==1?65:97) + rand(25)).chr} </code></pre> <p>but it looks like trash.</p> <p>Does anyone have a better method?</p>
[ { "answer_id": 88338, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 0, "selected": false, "text": "<p>To make your first into one statement:</p>\n\n<pre><code>(0...8).collect { |n| value &lt;&lt; (65 + rand(25)).chr }.joi...
2008/09/17
[ "https://Stackoverflow.com/questions/88311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10157/" ]
I'm currently generating an 8-character pseudo-random uppercase string for "A" .. "Z": ``` value = ""; 8.times{value << (65 + rand(25)).chr} ``` but it doesn't look clean, and it can't be passed as an argument since it isn't a single statement. To get a mixed-case string "a" .. "z" plus "A" .. "Z", I changed it to: ``` value = ""; 8.times{value << ((rand(2)==1?65:97) + rand(25)).chr} ``` but it looks like trash. Does anyone have a better method?
``` (0...8).map { (65 + rand(26)).chr }.join ``` I spend too much time golfing. ``` (0...50).map { ('a'..'z').to_a[rand(26)] }.join ``` And a last one that's even more confusing, but more flexible and wastes fewer cycles: ``` o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten string = (0...50).map { o[rand(o.length)] }.join ``` If you want to generate some random text then use the following: ``` 50.times.map { (0...(rand(10))).map { ('a'..'z').to_a[rand(26)] }.join }.join(" ") ``` this code generates 50 random word string with words length less than 10 characters and then join with space
88,325
<p>I have a class:</p> <pre><code>class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") </code></pre> <p>and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error:</p> <pre><code>def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass = MyClass(Error, foo)) </code></pre> <p>But I get...</p> <pre><code>NameError: global name 'Error' is not defined </code></pre> <p>Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?</p>
[ { "answer_id": 88346, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 6, "selected": true, "text": "<p>'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metas...
2008/09/17
[ "https://Stackoverflow.com/questions/88325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
I have a class: ``` class MyClass: def __init__(self, foo): if foo != 1: raise Error("foo is not equal to 1!") ``` and a unit test that is supposed to make sure the incorrect arg passed to the constructor properly raises an error: ``` def testInsufficientArgs(self): foo = 0 self.assertRaises((Error), myClass = MyClass(Error, foo)) ``` But I get... ``` NameError: global name 'Error' is not defined ``` Why? Where should I be defining this Error object? I thought it was built-in as a default exception type, no?
'Error' in this example could be any exception object. I think perhaps you have read a code example that used it as a metasyntatic placeholder to mean, "The Appropriate Exception Class". The baseclass of all exceptions is called 'Exception', and most of its subclasses are descriptive names of the type of error involved, such as 'OSError', 'ValueError', 'NameError', 'TypeError'. In this case, the appropriate error is 'ValueError' (the value of foo was wrong, therefore a ValueError). I would recommend replacing 'Error' with 'ValueError' in your script. Here is a complete version of the code you are trying to write, I'm duplicating everything because you have a weird keyword argument in your original example that you seem to be conflating with an assignment, and I'm using the 'failUnless' function name because that's the non-aliased name of the function: ``` class MyClass: def __init__(self, foo): if foo != 1: raise ValueError("foo is not equal to 1!") import unittest class TestFoo(unittest.TestCase): def testInsufficientArgs(self): foo = 0 self.failUnlessRaises(ValueError, MyClass, foo) if __name__ == '__main__': unittest.main() ``` The output is: ``` . ---------------------------------------------------------------------- Ran 1 test in 0.007s OK ``` There is a flaw in the unit testing library 'unittest' that other unit testing frameworks fix. You'll note that it is impossible to gain access to the exception object from the calling context. If you want to fix this, you'll have to redefine that method in a subclass of UnitTest: This is an example of it in use: ``` class TestFoo(unittest.TestCase): def failUnlessRaises(self, excClass, callableObj, *args, **kwargs): try: callableObj(*args, **kwargs) except excClass, excObj: return excObj # Actually return the exception object else: if hasattr(excClass,'__name__'): excName = excClass.__name__ else: excName = str(excClass) raise self.failureException, "%s not raised" % excName def testInsufficientArgs(self): foo = 0 excObj = self.failUnlessRaises(ValueError, MyClass, foo) self.failUnlessEqual(excObj[0], 'foo is not equal to 1!') ``` I have copied the failUnlessRaises function from unittest.py from python2.5 and modified it slightly.
88,326
<p>Does <a href="http://elmah.github.io/" rel="nofollow noreferrer">ELMAH</a> logged exceptions even when they do not bubble up to the application? I'd like to pop up a message when an exception occurs and still log the exception. Currently I've been putting everything in try catch blocks and spitting out messages, but this gets tedious.</p>
[ { "answer_id": 841426, "author": "Michael La Voie", "author_id": 65843, "author_profile": "https://Stackoverflow.com/users/65843", "pm_score": 7, "selected": false, "text": "<p>ELMAH has been updated to support a new feature called <a href=\"https://code.google.com/p/elmah/wiki/DotNetSla...
2008/09/17
[ "https://Stackoverflow.com/questions/88326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16891/" ]
Does [ELMAH](http://elmah.github.io/) logged exceptions even when they do not bubble up to the application? I'd like to pop up a message when an exception occurs and still log the exception. Currently I've been putting everything in try catch blocks and spitting out messages, but this gets tedious.
ELMAH has been updated to support a new feature called [Signaling](https://code.google.com/p/elmah/wiki/DotNetSlackersArticle#Error_Signaling). This allows you to handle exceptions how you want, while still logging them to ELMAH. ``` try { int i = 5; int j = 0; i = i / j; //Throws exception } catch (Exception ex) { MyPersonalHandlingCode(ex); ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling } ``` Re-throwing exceptions can be a bad practice as it makes it difficult to trace the flow of an application. Using Signaling is a much better approach if you intended to handle the error in some fashion and simply want to document it. Please check out this excellent guide by [DotNetSlackers on ELMAH](http://dotnetslackers.com/articles/aspnet/ErrorLoggingModulesAndHandlers.aspx)
88,399
<p>I saw <a href="https://stackoverflow.com/questions/73319/duplicate-a-whole-line-in-vim#73357">this same question for VIM</a> and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?</p>
[ { "answer_id": 88408, "author": "Arthur Thomas", "author_id": 14009, "author_profile": "https://Stackoverflow.com/users/14009", "pm_score": -1, "selected": false, "text": "<p>well ive usually used:</p>\n\n<pre>Ctl-Space (set the mark)\nmove to end of line\nCtl-K kill line\nCtl-Y * 2 (yan...
2008/09/17
[ "https://Stackoverflow.com/questions/88399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I saw [this same question for VIM](https://stackoverflow.com/questions/73319/duplicate-a-whole-line-in-vim#73357) and it has been something that I myself wanted to know how to do for Emacs. In ReSharper I use CTRL-D for this action. What is the least number of commands to perform this in Emacs?
I use ``` C-a C-SPACE C-n M-w C-y ``` which breaks down to * `C-a`: move cursor to start of line * `C-SPACE`: begin a selection ("set mark") * `C-n`: move cursor to next line * `M-w`: copy region * `C-y`: paste ("yank") The aforementioned ``` C-a C-k C-k C-y C-y ``` amounts to the same thing (TMTOWTDI) * `C-a`: move cursor to start of line * `C-k`: cut ("kill") the line * `C-k`: cut the newline * `C-y`: paste ("yank") (we're back at square one) * `C-y`: paste again (now we've got two copies of the line) These are both embarrassingly verbose compared to `C-d` in your editor, but in Emacs there's always a customization. `C-d` is bound to `delete-char` by default, so how about `C-c C-d`? Just add the following to your `.emacs`: ``` (global-set-key "\C-c\C-d" "\C-a\C- \C-n\M-w\C-y") ``` (@Nathan's elisp version is probably preferable, because it won't break if any of the key bindings are changed.) Beware: some Emacs modes may reclaim `C-c C-d` to do something else.
88,434
<p>I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on.</p> <p>Is this possible? And if so I'd like to have it detected before the client types their first letter.</p> <p>Is there a non-platform specific way to do this?</p>
[ { "answer_id": 88456, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 6, "selected": true, "text": "<p>Try this, from java.awt.Toolkit, returns a boolean:</p>\n\n<pre><code>Toolkit.getDefaultToolkit().getLockingKeyState(...
2008/09/17
[ "https://Stackoverflow.com/questions/88434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
I'm trying to build a better username/password field for my workplace and would like to be able to complain when they have their caps lock on. Is this possible? And if so I'd like to have it detected before the client types their first letter. Is there a non-platform specific way to do this?
Try this, from java.awt.Toolkit, returns a boolean: ``` Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK) ```
88,454
<p>Most of the MVC samples I have seen pass an instance of the view to the controller like this</p> <pre><code>public class View { Controller controller = new Controller(this); } </code></pre> <p>Is there any advantage to passing a class which provides access to just the the properties and events the controller is interested in, like this:</p> <pre><code>public class UIWrapper { private TextBox textBox; public TextBox TextBox { get {return textBox;} } public UIWrapper(ref TextBox textBox) { this.textBox = textBox; } public class View { UIWrapper wrapper = new UIWrapper(this); Controller controller = new Controller(wrapper) } </code></pre>
[ { "answer_id": 90767, "author": "Seldaek", "author_id": 6512, "author_profile": "https://Stackoverflow.com/users/6512", "pm_score": 0, "selected": false, "text": "<p>This is probably not the solution you want, but just to help you with the log parsing, you can use this to get counts for ...
2008/09/17
[ "https://Stackoverflow.com/questions/88454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35031/" ]
Most of the MVC samples I have seen pass an instance of the view to the controller like this ``` public class View { Controller controller = new Controller(this); } ``` Is there any advantage to passing a class which provides access to just the the properties and events the controller is interested in, like this: ``` public class UIWrapper { private TextBox textBox; public TextBox TextBox { get {return textBox;} } public UIWrapper(ref TextBox textBox) { this.textBox = textBox; } public class View { UIWrapper wrapper = new UIWrapper(this); Controller controller = new Controller(wrapper) } ```
My advice is to use the cached framework regardless of your user-base. The fact is, you won't be alone in doing so and it will only be a matter of time before it pays off (even if it is on return visits).
88,460
<p>I'm trying to use libvirt with virsh to manage my kvm/qemu vms. The problem I have is with getting it to work with public IPs. The server is running ubuntu 8.04.</p> <p>libvirt keeps trying to run it as:</p> <pre><code>/usr/bin/kvm -M pc -m 256 -smp 3 -monitor pty -no-acpi \ -drive file=/opt/virtual-machines/calculon/root.qcow2,if=ide,boot=on \ -net nic,vlan=0,model=virtio -net tap,fd=10,vlan=0 -usb -vnc 127.0.0.1:0 </code></pre> <p>Which boots, but does not have any network access (pings go nowhere). Running it without fd=10 makes it work right, with kvm creating the necessary TAP device for me and networking functioning inside the host. All the setup guides I've seen focus on setting up masquerading, while I just want a simple bridge and unfiltered access to the net (both the guests and host must use public IPs). </p> <p>Running ifconfig on the host gives this, the bridge is manually setup in my /etc/network/interfaces file. :</p> <pre><code>br0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet addr:12.34.56.78 Bcast:12.34.56.79 Mask:255.255.255.240 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3359 errors:0 dropped:0 overruns:0 frame:0 TX packets:3025 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:180646 (176.4 KB) TX bytes:230908 (225.4 KB) eth0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:6088386 errors:0 dropped:0 overruns:0 frame:0 TX packets:3058 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:680236624 (648.7 MB) TX bytes:261696 (255.5 KB) Interrupt:33 </code></pre> <p>Any help would be greatly appreciated.</p>
[ { "answer_id": 90689, "author": "AgentK", "author_id": 14868, "author_profile": "https://Stackoverflow.com/users/14868", "pm_score": 4, "selected": true, "text": "<p>I followed the bridged networking guide at <a href=\"https://help.ubuntu.com/community/KVM\" rel=\"noreferrer\">https://he...
2008/09/17
[ "https://Stackoverflow.com/questions/88460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11105/" ]
I'm trying to use libvirt with virsh to manage my kvm/qemu vms. The problem I have is with getting it to work with public IPs. The server is running ubuntu 8.04. libvirt keeps trying to run it as: ``` /usr/bin/kvm -M pc -m 256 -smp 3 -monitor pty -no-acpi \ -drive file=/opt/virtual-machines/calculon/root.qcow2,if=ide,boot=on \ -net nic,vlan=0,model=virtio -net tap,fd=10,vlan=0 -usb -vnc 127.0.0.1:0 ``` Which boots, but does not have any network access (pings go nowhere). Running it without fd=10 makes it work right, with kvm creating the necessary TAP device for me and networking functioning inside the host. All the setup guides I've seen focus on setting up masquerading, while I just want a simple bridge and unfiltered access to the net (both the guests and host must use public IPs). Running ifconfig on the host gives this, the bridge is manually setup in my /etc/network/interfaces file. : ``` br0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet addr:12.34.56.78 Bcast:12.34.56.79 Mask:255.255.255.240 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:3359 errors:0 dropped:0 overruns:0 frame:0 TX packets:3025 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0 RX bytes:180646 (176.4 KB) TX bytes:230908 (225.4 KB) eth0 Link encap:Ethernet HWaddr 00:1e:c9:3c:59:b8 inet6 addr: fe80::21e:c9ff:fe3c:59b8/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:6088386 errors:0 dropped:0 overruns:0 frame:0 TX packets:3058 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:680236624 (648.7 MB) TX bytes:261696 (255.5 KB) Interrupt:33 ``` Any help would be greatly appreciated.
I followed the bridged networking guide at <https://help.ubuntu.com/community/KVM> and have the following in /etc/network/interfaces: ``` auto eth0 iface eth0 inet manual auto br0 iface br0 inet static address 192.168.0.10 network 192.168.0.0 netmask 255.255.255.0 broadcast 192.168.0.255 gateway 192.168.0.1 bridge_ports eth0 bridge_fd 9 bridge_hello 2 bridge_maxage 12 bridge_stp off ``` I have not changed any libvirt network settings and my kvm images are booted like: ``` /usr/bin/kvm -M pc -no-kqemu -m 256 -smp 1 -monitor pty -boot c -hda \ /libvirt/apt.img -net nic,macaddr=00:16:3e:77:32:1d,vlan=0 -net \ tap,fd=11,script=,vlan=0 -usb -vnc 127.0.0.1:0 ``` I then specify the static network settings in the kvm image as normal. Has all worked ok since I followed the guide. I do have the following settings in my xml files in /etc/libvirt/qemu/ though under devices: ``` <interface type='bridge'> <mac address='00:16:3e:77:32:1d'/> <source bridge='br0'/> </interface> ```
88,473
<p>Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities? I've tried the following but it doesn't work:</p> <pre><code>var values = new[] { "String1", "String2" }; // some string values var foo = model.entitySet.Where(e =&gt; values.Contains(e.Name)); </code></pre> <p>I believe this works in LINQ-to-SQL though? Any thoughts?</p>
[ { "answer_id": 88486, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "<p>Yes it does translate to SQL, it generates a standard IN statement like this:</p>\n\n<pre><code>SELECT [t0].[col1]\...
2008/09/17
[ "https://Stackoverflow.com/questions/88473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16948/" ]
Does anybody know how to apply a "where in values" type condition using LINQ-to-Entities? I've tried the following but it doesn't work: ``` var values = new[] { "String1", "String2" }; // some string values var foo = model.entitySet.Where(e => values.Contains(e.Name)); ``` I believe this works in LINQ-to-SQL though? Any thoughts?
It is somewhat of a shame that [Contains is not supported in Linq to Entities](http://msdn.microsoft.com/en-us/library/bb738638.aspx). IN and JOIN are not the same operator (Filtering by IN never changes the cardinality of the query).
88,481
<p>I see that Adobe AIR uses WebKit as its render and I see that WebKit (at least the most current build) has some SVG support. Does this mean (and has anyone specifically tried) that an Adobe AIR application could render SVG on an HTML page?</p>
[ { "answer_id": 88513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Adobe AIR can only support SVG once Adobe updates their version of WebKit (AIR's HTML rendering engine) and enables the SVG ...
2008/09/17
[ "https://Stackoverflow.com/questions/88481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8256/" ]
I see that Adobe AIR uses WebKit as its render and I see that WebKit (at least the most current build) has some SVG support. Does this mean (and has anyone specifically tried) that an Adobe AIR application could render SVG on an HTML page?
On the offchance that it's helpful (and that you don't already know), Flex can embed SVG at ~~runtime~~ compile time, which effectively converts it to SWF format and embeds it as a resource. ``` [Embed(source="assets/frog.svg")] [Bindable] public var SvgAsset:Class; ``` More info at Adobe's [embedding assets article](http://www.adobe.com/devnet/flex/quickstart/embedding_assets/#EmbeddingSvgFiles).
88,485
<p>This is a follow up question to <a href="https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined">This Question</a>. </p> <p>I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used:</p> <pre><code>function exist(sFN) { if(self[sFN]) return true; return false; } </code></pre> <p>It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?</p>
[ { "answer_id": 88498, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 2, "selected": false, "text": "<p>just use <code>typeof</code>.</p>\n\n<pre><code>typeof(foobar) // -&gt; undefined\ntypeof(alert) // -&gt; function\n</cod...
2008/09/17
[ "https://Stackoverflow.com/questions/88485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2515/" ]
This is a follow up question to [This Question](https://stackoverflow.com/questions/85815/how-to-tell-if-a-javascript-function-is-defined). I like (and understand) the solution there. However, in the code I am working in, another way to solve the same problem is used: ``` function exist(sFN) { if(self[sFN]) return true; return false; } ``` It seems to work fine, although I don't understand how. Does it work? How? What are minuses of this approach? Should I switch to solution from the other question?
Your condition is checking the existence of the "sFN" property in the "self" object. Anything that isn't null, undefined, 0, and "" will evaluate to true. As others have said, you can use typeof, or instanceof to see if it's actually a function. Looking at your linked example, you should read up on the difference between ==/!= and ===/!== in javascript. Short answer: ("" == null) is true, ("" === null) is false.
88,518
<p>I'm a complete perl novice, am running a perl script using perl 5.10 and getting this warning: </p> <pre><code>$* is no longer supported at migrate.pl line 380. </code></pre> <p>Can anyone describe what $* did and what the recommended replacement of it is now? Alternatively if you could point me to documentation that describes this that would be great.</p> <p>The script I'm running is to migrate a source code database from vss to svn and can be found here: <a href="http://www.x2systems.com/files/migrate.pl.txt" rel="noreferrer">http://www.x2systems.com/files/migrate.pl.txt</a></p> <p>The two snippets of code that use it are: </p> <pre><code> $* = 1; $/ = ':'; $cmd = $SSCMD . " Dir -I- \"$proj\""; $_ = `$cmd`; # what this next expression does is to merge wrapped lines like: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/excep # tion: # into: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/exception: s/\n((\w*\-*\.*\w*\/*)+\:)/$1/g; $* = 0; </code></pre> <p>and then some ways later on: </p> <pre><code> $cmd = $SSCMD . " get -GTM -W -I-Y -GL\"$localdir\" -V$version \"$file\" 2&gt;&amp;1"; $out = `$cmd`; # get rid of stupid VSS warning messages $* = 1; $out =~ s/\n?Project.*rebuilt\.//g; $out =~ s/\n?File.*rebuilt\.//g; $out =~ s/\n.*was moved out of this project.*rebuilt\.//g; $out =~ s/\nContinue anyway.*Y//g; $* = 0; </code></pre> <p>many thanks, </p> <ul> <li>Rory</li> </ul>
[ { "answer_id": 88528, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 1, "selected": false, "text": "<p>It turns on multi-line mode. Since perl 5.0 (from 1994), the correct way to do that is adding a <em><code>m</code>...
2008/09/17
[ "https://Stackoverflow.com/questions/88518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8479/" ]
I'm a complete perl novice, am running a perl script using perl 5.10 and getting this warning: ``` $* is no longer supported at migrate.pl line 380. ``` Can anyone describe what $\* did and what the recommended replacement of it is now? Alternatively if you could point me to documentation that describes this that would be great. The script I'm running is to migrate a source code database from vss to svn and can be found here: <http://www.x2systems.com/files/migrate.pl.txt> The two snippets of code that use it are: ``` $* = 1; $/ = ':'; $cmd = $SSCMD . " Dir -I- \"$proj\""; $_ = `$cmd`; # what this next expression does is to merge wrapped lines like: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/excep # tion: # into: # $/DeviceAuthority/src/com/eclyptic/networkdevicedomain/deviceinterrogator/exception: s/\n((\w*\-*\.*\w*\/*)+\:)/$1/g; $* = 0; ``` and then some ways later on: ``` $cmd = $SSCMD . " get -GTM -W -I-Y -GL\"$localdir\" -V$version \"$file\" 2>&1"; $out = `$cmd`; # get rid of stupid VSS warning messages $* = 1; $out =~ s/\n?Project.*rebuilt\.//g; $out =~ s/\n?File.*rebuilt\.//g; $out =~ s/\n.*was moved out of this project.*rebuilt\.//g; $out =~ s/\nContinue anyway.*Y//g; $* = 0; ``` many thanks, * Rory
From [perlvar](http://perldoc.perl.org/perlvar.html#%24*): > > Use of $\* is deprecated in modern Perl, supplanted by the /s and /m modifiers on pattern matching. > > > If you have access to the place where it's being matched just add it to the end: ``` $haystack =~ m/.../sm; ``` If you only have access to the string, you can surround the expression with ``` qr/(?ms-ix:$expr)/; ``` Or in your case: ``` s/\n((\w*\-*\.*\w*\/*)+\:)/$1/gsm; ```
88,522
<p>I wanting to show prices for my products in my online store. I'm currently doing:</p> <pre><code>&lt;span class="ourprice"&gt; &lt;%=GetPrice().ToString("C")%&gt; &lt;/span&gt; </code></pre> <p>Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00"</p> <p>I think the correct HTML for an output of "£12.00" is "<code>&amp;pound;12.00</code>", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00. </p> <p>(The server is in the UK, with localisation is set appropriately in web.config).</p> <p>Is the below an improvement, or is there a better way?</p> <pre><code>&lt;span class="ourprice"&gt; &lt;%=GetPrice().ToString("C").Replace("£","&amp;pound;")%&gt; &lt;/span&gt; </code></pre>
[ { "answer_id": 88535, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 2, "selected": false, "text": "<p>Try this, it'll use your locale set for the application:</p>\n\n<pre><code>&lt;%=String.Format(\"{0:C}\",GetPrice())...
2008/09/17
[ "https://Stackoverflow.com/questions/88522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11538/" ]
I wanting to show prices for my products in my online store. I'm currently doing: ``` <span class="ourprice"> <%=GetPrice().ToString("C")%> </span> ``` Where GetPrice() returns a decimal. So this currently returns a value e.g. "£12.00" I think the correct HTML for an output of "£12.00" is "`&pound;12.00`", so although this is rendering fine in most browsers, some browsers (Mozilla) show this as $12.00. (The server is in the UK, with localisation is set appropriately in web.config). Is the below an improvement, or is there a better way? ``` <span class="ourprice"> <%=GetPrice().ToString("C").Replace("£","&pound;")%> </span> ```
The £ symbol (U+00A3), and the html entities & #163; and & pound; should all render the same in a browser. If the browser doesn't recognise £, it probably won't recognise the entity versions. It's in ISO 8859-1 (Latin-1), so I'd be surprised if a Mozilla browser can't render it (my FF certainly can). If you see a $ sign, it's likely you have two things: 1. The browser default language is en-us 2. Asp.net is doing automatic locale switching. The default web.config setting is something like ``` <globalization culture="auto:en-us" uiCulture="auto:en-US" /> ``` As you (almost certainly) want UK-only prices, simply specify the locale in web.config: ``` <globalization culture="us" uiCulture="en-gb" /> ``` (or on page level:) ``` <%@Page Culture="en-gb" UICulture="en-gb" ..etc... %> ``` Thereafter the string formats such as String.Format("{0:C}",GetPrice()) and GetPrice().ToString("C") will use the en-GB locale as asp.net will have set the currentCulture for you (although you can specify the en-gb culture in the overloads if you're paranoid).
88,546
<p>In Perl, a conditional can be expressed either as</p> <pre><code>if (condition) { do something } </code></pre> <p>or as</p> <pre><code>(condition) and do { do something } </code></pre> <p>Interestingly, the second way seems to be about 10% faster. Does anyone know why?</p>
[ { "answer_id": 88611, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 4, "selected": false, "text": "<p>I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is</p>\n\n<pre><code>LISTOP (0x...
2008/09/17
[ "https://Stackoverflow.com/questions/88546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In Perl, a conditional can be expressed either as ``` if (condition) { do something } ``` or as ``` (condition) and do { do something } ``` Interestingly, the second way seems to be about 10% faster. Does anyone know why?
I've deparsed it, and it really shouldn't be faster. The opcode tree for the first is ``` LISTOP (0x8177a18) leave [1] OP (0x8176590) enter COP (0x8177a40) nextstate LISTOP (0x8177b20) scope OP (0x81779b8) null [174] UNOP (0x8177c40) dofile SVOP (0x8177b58) const [1] PV (0x81546e4) "something" ``` The opcode tree for the second is ``` LISTOP (0x8177b28) leave [1] OP (0x8176598) enter COP (0x8177a48) nextstate UNOP (0x8177980) null LISTOP (0x8177ca0) scope OP (0x81779c0) null [174] UNOP (0x8177c48) dofile SVOP (0x8177b60) const [1] PV (0x81546e4) "something" ``` I really don't see how the latter could be faster. It does an opcode more!
88,554
<p>In <em>C++</em>, I can have take input like this: </p> <pre><code>cin &gt;&gt; a &gt;&gt; b &gt;&gt; c; </code></pre> <p>And <code>a</code> can be <code>int</code>, <code>b</code> can be <code>float</code>, and <code>c</code> can be whatever... How do I do the same in <em>python</em>?</p> <p><code>input()</code> and <code>raw_input()</code>, the way I'm using them, don't seem to be giving me the desired results.</p>
[ { "answer_id": 88587, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>You generally shouldn't use <code>input()</code> in production code. If you want an <code>int</code> and then a <code>float<...
2008/09/17
[ "https://Stackoverflow.com/questions/88554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10096/" ]
In *C++*, I can have take input like this: ``` cin >> a >> b >> c; ``` And `a` can be `int`, `b` can be `float`, and `c` can be whatever... How do I do the same in *python*? `input()` and `raw_input()`, the way I'm using them, don't seem to be giving me the desired results.
You generally shouldn't use `input()` in production code. If you want an `int` and then a `float`, try this: ``` >>> line = raw_input().split() >>> a = int(line[0]) >>> b = float(line[1]) >>> c = " ".join(line[2:]) ``` It all depends on what exactly you're trying to accomplish, but remember that readability counts. Obscure one-liners may seem cool but in the face of maintainability, try to choose something sensible :) (P.S.: Don't forget to check for errors with `try: ... except (ValueError, IndexError):`)
88,558
<p>I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function.</p> <p>The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen.</p> <p>Here is the function:</p> <pre><code>// Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement-&gt;ssState == Hidden) continue;*/ gsElement-&gt;Draw(); } } </code></pre> <p>Here are a copy of my classes:</p> <pre><code>class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this-&gt;strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus &amp;&amp; (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this-&gt;bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector &lt;BUTTON&gt; vbtnMenuEntries; MenuScreen(string strName):GameScreen(strName){ } virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); for(unsigned int i = 0; i &lt; vbtnMenuEntries.size(); i++){ vbtnMenuEntries[i].IsPressed(); } } virtual void Draw(){ GameScreen::Draw(); for(unsigned int i = 0; i &lt; vbtnMenuEntries.size(); i++) vbtnMenuEntries[i].Draw(); } }; class testMenu : public MenuScreen{ public: vector&lt;OBJECT&gt; test; //OBJECT background3(); // OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40); // BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test()); bool draw; testMenu():MenuScreen("testMenu"){ OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768); OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40); test.push_back(background3); test.push_back(testPic); //background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height) //test.push_back(background3); // vbtnMenuEntries.push_back(x); draw = false; } void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); //cout &lt;&lt; "X" &lt;&lt; endl; /*if(MouseLButton == true){ testMenu2 t; smManager.AddScreen(t); }*/ } void Draw(){ //background3.Draw(); test[0].Draw(); test[1].Draw(); MenuScreen::Draw(); ///*if(draw){*/ // testPic.Draw(); //} } /*void test(){ draw = true; }*/ }; </code></pre>
[ { "answer_id": 88620, "author": "Curt Hagenlocher", "author_id": 533, "author_profile": "https://Stackoverflow.com/users/533", "pm_score": 3, "selected": false, "text": "<p>If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing wh...
2008/09/17
[ "https://Stackoverflow.com/questions/88558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am making a game in C++ and am having problems with my derived class. I have a base class called GameScreen which has a vitrual void draw() function with no statements. I also have a derived class called MenuScreen which also has a virtual void draw() function and a derived class from MenuScreen called TestMenu which also has a void draw() function. In my program I have a list of GameScreens that I have a GameScreen iterator pass through calling each GameScreens draw() function. The issue is that I have placed a TestMenu object on the GameScreen list. Instead of the iterator calling the draw() function of TestMenu it is calling the draw() function of the GameScreen class. Does anyone know how I could call the draw() function of TestMenu instead of the one in GameScreen. Here is the function: ``` // Tell each screen to draw itself. //gsElement is a GameScreen iterator //gsScreens is a list of type GameScreen void Draw() { for (gsElement = gsScreens.begin(); gsElement != gsScreens.end(); gsElement++) { /*if (gsElement->ssState == Hidden) continue;*/ gsElement->Draw(); } } ``` Here are a copy of my classes: ``` class GameScreen { public: string strName; bool bIsPopup; bool bOtherScreenHasFocus; ScreenState ssState; //ScreenManager smScreenManager; GameScreen(string strName){ this->strName = strName; } //Determine if the screen should be drawn or not bool IsActive(){ return !bOtherScreenHasFocus && (ssState == Active); } //------------------------------------ //Load graphics content for the screen //------------------------------------ virtual void LoadContent(){ } //------------------------------------ //Unload content for the screen //------------------------------------ virtual void UnloadContent(){ } //------------------------------------------------------------------------- //Update changes whether the screen should be updated or not and sets //whether the screen should be drawn or not. // //Input: // bOtherScreenHasFocus - is used set whether the screen should update // bCoveredByOtherScreen - is used to set whether the screen is drawn or not //------------------------------------------------------------------------- virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ this->bOtherScreenHasFocus = bOtherScreenHasFocus; //if the screen is covered by another than change the screen state to hidden //else set the screen state to active if(bCoveredByOtherScreen){ ssState = Hidden; } else{ ssState = Active; } } //----------------------------------------------------------- //Takes input from the mouse and calls appropriate actions //----------------------------------------------------------- virtual void HandleInput(){ } //---------------------- //Draw content on screen //---------------------- virtual void Draw(){ } //-------------------------------------- //Deletes screen from the screen manager //-------------------------------------- void ExitScreen(){ //smScreenManager.RemoveScreen(*this); } }; class MenuScreen: public GameScreen{ public: vector <BUTTON> vbtnMenuEntries; MenuScreen(string strName):GameScreen(strName){ } virtual void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ GameScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++){ vbtnMenuEntries[i].IsPressed(); } } virtual void Draw(){ GameScreen::Draw(); for(unsigned int i = 0; i < vbtnMenuEntries.size(); i++) vbtnMenuEntries[i].Draw(); } }; class testMenu : public MenuScreen{ public: vector<OBJECT> test; //OBJECT background3(); // OBJECT testPic(512, 384, buttonHover.png, 100, 40, 100, 40); // BUTTON x(256, 384, buttonNormal.png, buttonHover.png, buttonPressed.png, 100, 40, test()); bool draw; testMenu():MenuScreen("testMenu"){ OBJECT background3(1, 1, 0, TEXT("background.png"), 1, 1, 1024, 768); OBJECT testPic(512, 384,0, TEXT("buttonHover.png"), 1, 1, 100, 40); test.push_back(background3); test.push_back(testPic); //background3.Init(int xLoc, int yLoc, int zLoc, LPCTSTR filePath, int Rows, int Cols, int Width, int Height) //test.push_back(background3); // vbtnMenuEntries.push_back(x); draw = false; } void Update(bool bOtherScreenHasFocus, bool bCoveredByOtherScreen){ MenuScreen::Update(bOtherScreenHasFocus, bCoveredByOtherScreen); //cout << "X" << endl; /*if(MouseLButton == true){ testMenu2 t; smManager.AddScreen(t); }*/ } void Draw(){ //background3.Draw(); test[0].Draw(); test[1].Draw(); MenuScreen::Draw(); ///*if(draw){*/ // testPic.Draw(); //} } /*void test(){ draw = true; }*/ }; ```
If gsScreens is a list of objects instead of a list of pointers (as your code suggests), then you're not storing what you think you're storing in it. What's happening is that -- instead of putting a TestMenu into the list, you're actually constructing a new MenuScreen using the compiler-generated copy constructor and putting this MenuScreen into the list. C++ is polymorphic through pointers, so if you don't have a pointer you won't get polymorphic behavior.
88,570
<p>Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following:</p> <pre><code>&lt;DirectoryMatch ^/home/www/(.*)&gt; AuthType Basic AuthName $1 AuthUserFile /etc/apache2/svn.passwd Require group $1 admin &lt;/DirectoryMatch&gt; </code></pre> <p>but so far I've had no success.</p> <p>Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0. </p> <p>For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.</p>
[ { "answer_id": 88704, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>What you are trying to do looks very similar to <a href=\"http://httpd.apache.org/docs/2.0/howto/public_html.html\" rel=\"no...
2008/09/17
[ "https://Stackoverflow.com/questions/88570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16960/" ]
Does anyone know if it's possible to use regex capture within Apache's DirectoryMatch directive? I'd like to do something like the following: ``` <DirectoryMatch ^/home/www/(.*)> AuthType Basic AuthName $1 AuthUserFile /etc/apache2/svn.passwd Require group $1 admin </DirectoryMatch> ``` but so far I've had no success. Specifically, I'm trying to create a group-based HTTP Auth for individual directories/vhosts on a server in Apache 2.0. For example, Site A, pointing to /home/www/a will be available to all users in group admin and group a, site b at /home/www/b will be available to all users in group admin and group b, etc. I'd like to keep everything based on the directory name so I can easily script adding htpasswd users to the correct groups and automate this as much as possible, but other suggestions for solving the problem are certainly welcome.
You could tackle the problem from a completely different angle: enable the perl module and you can include a little perl script in your httpd.conf. You could then do something like this: ``` <Perl> my @groups = qw/ foo bar baz /; foreach ( @groups ) { push @PerlConfig, qq| <Directory /home/www/$_> blah </Directory> |; } </Perl> ``` That way, you could even read your groups and other information from a database or by simply globbing /home/www or whatever else tickles your fancy.
88,573
<p>In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example:</p> <pre><code>void foo() throw(); // guaranteed not to throw an exception void bar() throw(int); // may throw an exception of type int void baz() throw(...); // may throw an exception of some unspecified type </code></pre> <p>I'm doubtful about actually using them because of the following:</p> <ol> <li>The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error.</li> <li>If a function violates an exception specifier, I think the standard behaviour is to terminate the program.</li> <li>In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong.</li> </ol> <p>Do you think exception specifiers should be used?<br> Please answer with "yes" or "no" and provide some reasons to justify your answer.</p>
[ { "answer_id": 88591, "author": "Kris Kumler", "author_id": 4281, "author_profile": "https://Stackoverflow.com/users/4281", "pm_score": 2, "selected": false, "text": "<p>Generally I would not use exception specifiers. However, in cases where if any other exception were to come from the ...
2008/09/17
[ "https://Stackoverflow.com/questions/88573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
In C++, you can specify that a function may or may not throw an exception by using an exception specifier. For example: ``` void foo() throw(); // guaranteed not to throw an exception void bar() throw(int); // may throw an exception of type int void baz() throw(...); // may throw an exception of some unspecified type ``` I'm doubtful about actually using them because of the following: 1. The compiler doesn't really enforce exception specifiers in any rigorous way, so the benefits are not great. Ideally, you would like to get a compile error. 2. If a function violates an exception specifier, I think the standard behaviour is to terminate the program. 3. In VS.Net, it treats throw(X) as throw(...), so adherence to the standard is not strong. Do you think exception specifiers should be used? Please answer with "yes" or "no" and provide some reasons to justify your answer.
No. Here are several examples why: 1. Template code is impossible to write with exception specifications, ``` template<class T> void f( T k ) { T x( k ); x.x(); } ``` The copies might throw, the parameter passing might throw, and `x()` might throw some unknown exception. 2. Exception-specifications tend to prohibit extensibility. ``` virtual void open() throw( FileNotFound ); ``` might evolve into ``` virtual void open() throw( FileNotFound, SocketNotReady, InterprocessObjectNotImplemented, HardwareUnresponsive ); ``` You could really write that as ``` throw( ... ) ``` The first is not extensible, the second is overambitious and the third is really what you mean, when you write virtual functions. 3. Legacy code When you write code which relies on another library, you don't really know what it might do when something goes horribly wrong. ``` int lib_f(); void g() throw( k_too_small_exception ) { int k = lib_f(); if( k < 0 ) throw k_too_small_exception(); } ``` `g` will terminate, when `lib_f()` throws. This is (in most cases) not what you really want. `std::terminate()` should never be called. It is always better to let the application crash with an unhandled exception, from which you can retrieve a stack-trace, than to silently/violently die. 4. Write code that returns common errors and throws on exceptional occasions. ``` Error e = open( "bla.txt" ); if( e == FileNotFound ) MessageUser( "File bla.txt not found" ); if( e == AccessDenied ) MessageUser( "Failed to open bla.txt, because we don't have read rights ..." ); if( e != Success ) MessageUser( "Failed due to some other error, error code = " + itoa( e ) ); try { std::vector<TObj> k( 1000 ); // ... } catch( const bad_alloc& b ) { MessageUser( "out of memory, exiting process" ); throw; } ``` Nevertheless, when your library just throws your own exceptions, you can use exception specifications to state your intent.
88,613
<p>How do I tokenize the string:</p> <pre><code>&quot;2+24*48/32&quot; </code></pre> <p>Into a list:</p> <pre><code>['2', '+', '24', '*', '48', '/', '32'] </code></pre>
[ { "answer_id": 88639, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 2, "selected": false, "text": "<p>Regular expressions:</p>\n\n<pre><code>&gt;&gt;&gt; import re\n&gt;&gt;&gt; splitter = re.compile(r'([+*/])')\n&gt;&gt;&gt;...
2008/09/17
[ "https://Stackoverflow.com/questions/88613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I tokenize the string: ``` "2+24*48/32" ``` Into a list: ``` ['2', '+', '24', '*', '48', '/', '32'] ```
It just so happens that the tokens you want split are already Python tokens, so you can use the built-in `tokenize` module. It's almost a one-liner; this program: ```py from io import StringIO from tokenize import generate_tokens STRING = 1 print( list( token[STRING] for token in generate_tokens(StringIO("2+24*48/32").readline) if token[STRING] ) ) ``` produces this output: ```py ['2', '+', '24', '*', '48', '/', '32'] ```
88,651
<p>Is it possible to get notifications using <a href="http://www.microsoft.com/sql/technologies/reporting/default.mspx" rel="nofollow noreferrer">SQL Server Reporting Services</a>? Say for example I have a report that I want by mail if has for example suddenly shows more than 10 rows or if a specific value drop below 100 000. Do I need to tie Notification Services into it and how do I do that?</p> <p>Please provide as much technical details as possible as I've never used <a href="http://www.microsoft.com/sql/technologies/notification/default.mspx" rel="nofollow noreferrer">Notification Services</a> before.</p> <p>Someone also told me that Notifications Services is replaced by new functionality in Reporting Services in Sql Server 2008 - is this the case?</p>
[ { "answer_id": 90762, "author": "Simon Munro", "author_id": 3893, "author_profile": "https://Stackoverflow.com/users/3893", "pm_score": 0, "selected": false, "text": "<p>I wouldn't go down the ntofications services route - it is pretty much a deprecated feature of SQL Server and even if ...
2008/09/17
[ "https://Stackoverflow.com/questions/88651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298/" ]
Is it possible to get notifications using [SQL Server Reporting Services](http://www.microsoft.com/sql/technologies/reporting/default.mspx)? Say for example I have a report that I want by mail if has for example suddenly shows more than 10 rows or if a specific value drop below 100 000. Do I need to tie Notification Services into it and how do I do that? Please provide as much technical details as possible as I've never used [Notification Services](http://www.microsoft.com/sql/technologies/notification/default.mspx) before. Someone also told me that Notifications Services is replaced by new functionality in Reporting Services in Sql Server 2008 - is this the case?
I'd agree with Simon re Notification Services Also, data driven SSRS Subscriptions are not available unless you use Enterprise Edition (and isn't available if you use SharePoint Integrated Mode). An alternate way would be to create an Agent job that runs a proc. The proc could check the conditions you require and kick off the subscription if they are met using: ``` exec ReportServer.dbo.AddEvent @EventType='TimedSubscription', @EventData='xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxx' ``` Where the @EventData is the ID of the subscription in dbo.Subscriptions. This will drop a row in [dbo].[Event]. The Service polls this table a few times a minute to kick off subscriptions. Really, this isn't far from what happens when you set up a new Subscription, might even be easier to create a Subscription in the Report Server site, find which agent job was created (the ones with GUID names) and edit the T-SQL. Hope this helps
88,682
<p>What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML?</p> <p>Let's say I have a <code>Foo</code> that has an property <code>Bar[] Bars</code>. A <code>Bar</code> object has a key and a value. By default, this serializes to the following XML:</p> <pre><code>&lt;Foo&gt; &lt;Bars&gt; &lt;Bar key="key0" value="value0"/&gt; ... &lt;/Bars&gt; &lt;/Foo&gt; </code></pre> <p>For JSON, this serializes to:</p> <pre><code>{"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]} </code></pre> <p>What I'd really like to have is this serialize to better reflect the underlying relationship. E.g., </p> <pre><code>&lt;Foo&gt; &lt;Bars&gt; &lt;Key0 value="value0"/&gt; &lt;Key1 value="value1"/&gt; ... &lt;/Bars&gt; &lt;/Foo&gt; </code></pre> <p>I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this? </p> <p>I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g.</p> <pre><code>void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { foreach (Bar bar in Bars){ info.AddValue(bar.Key. bar); } } </code></pre> <p>Any suggestions? What's the best practice here? </p>
[ { "answer_id": 88707, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>ISerializable isn't used for xml serialization; its used for binary serialization. You would be better implementing IXmlSer...
2008/09/17
[ "https://Stackoverflow.com/questions/88682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7242/" ]
What's the best way to serialize a HashTable (or a data best navigated through a string indexer) with SOAP/XML? Let's say I have a `Foo` that has an property `Bar[] Bars`. A `Bar` object has a key and a value. By default, this serializes to the following XML: ``` <Foo> <Bars> <Bar key="key0" value="value0"/> ... </Bars> </Foo> ``` For JSON, this serializes to: ``` {"Foo":["Bars":[{"Key":"key0","Value":"key1} ... ]}]} ``` What I'd really like to have is this serialize to better reflect the underlying relationship. E.g., ``` <Foo> <Bars> <Key0 value="value0"/> <Key1 value="value1"/> ... </Bars> </Foo> ``` I realize there are some challenges with serializing to SOAP in this way, but what's the best approach to providing a schema that better reflects this? I've tried creating a BarsCollection object and defining custom serialization on that, but it doesn't seem to actually invoke the serialization on that object. E.g. ``` void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { foreach (Bar bar in Bars){ info.AddValue(bar.Key. bar); } } ``` Any suggestions? What's the best practice here?
I really don't think that what you want reflects the structure better. To define a schema (think XSD) for this you would have to know all of the potential keys in advance since you indicate that you want each one to be a separate custom type. Conceptually Bars would be an array of objects holding objects of type Key0, Key1, with each of the KeyN class containing a value property. I believe that the first serialization actually is the best reflection of the underlying structure. The reason it "works" more like you want in JSON is that you lose the typing -- everything is just an object. If you don't care about the types why not just use JSON?
88,710
<p>I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.</p>
[ { "answer_id": 88722, "author": "cori", "author_id": 8151, "author_profile": "https://Stackoverflow.com/users/8151", "pm_score": 0, "selected": false, "text": "<p>I know you say that you're not in favor of the Business Development Studio to do this, but I've found the built-in tools to b...
2008/09/17
[ "https://Stackoverflow.com/questions/88710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16980/" ]
I need to create a repeatable process for deploying SQL Server Reporting Services reports. I am not in favor of using Visual Studio and or Business Development Studio to do this. The rs.exe method of scripting deployments also seems rather clunky. Does anyone have a very elegant way that they have been able to deploy reports. The key here is that I want the process to be completely automated.
We use rs.exe, once we developed the script we have not needed to touch it anymore, it just works. Here is the source (I slightly modified it by hand to remove sensitive data without a chance to test it, hope I did not brake anything), it deploys reports and associated images from subdirectories for various languages. Also datasource is created. ``` '===================================================================== ' File: PublishReports.rss ' ' Summary: Script that can be used with RS.exe to ' publish the reports. ' ' Rss file spans from beginnig of this comment to end of module ' (except of "End Module"). '===================================================================== Dim langPaths As String() = {"en", "cs", "pl", "de"} Dim filePath As String = Environment.CurrentDirectory Public Sub Main() rs.Credentials = System.Net.CredentialCache.DefaultCredentials 'Create parent folder Try rs.CreateFolder(parentFolder, "/", Nothing) Console.WriteLine("Parent folder created: {0}", parentFolder) Catch e As Exception Console.WriteLine(e.Message) End Try PublishLanguagesFromFolder(filePath) End Sub Public Sub PublishLanguagesFromFolder(ByVal folder As String) Dim Lang As Integer Dim langPath As String For Lang = langPaths.GetLowerBound(0) To langPaths.GetUpperBound(0) langPath = langPaths(Lang) 'Create the lang folder Try rs.CreateFolder(langPath, "/" + parentFolder, Nothing) Console.WriteLine("Parent lang folder created: {0}", parentFolder + "/" + langPath) Catch e As Exception Console.WriteLine(e.Message) End Try 'Create the shared data source CreateDataSource("/" + parentFolder + "/" + langPath) 'Publish reports and images PublishFolderContents(folder + "\" + langPath, "/" + parentFolder + "/" + langPath) Next 'Lang End Sub Public Sub CreateDataSource(ByVal targetFolder As String) Dim name As String = "data source" 'Data source definition. Dim definition As New DataSourceDefinition definition.CredentialRetrieval = CredentialRetrievalEnum.Store definition.ConnectString = "data source=" + dbServer + ";initial catalog=" + db definition.Enabled = True definition.EnabledSpecified = True definition.Extension = "SQL" definition.ImpersonateUser = False definition.ImpersonateUserSpecified = True 'Use the default prompt string. definition.Prompt = Nothing definition.WindowsCredentials = False 'Login information definition.UserName = "user" definition.Password = "password" Try 'name, folder, overwrite, definition, properties rs.CreateDataSource(name, targetFolder, True, definition, Nothing) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub Public Sub PublishFolderContents(ByVal sourceFolder As String, ByVal targetFolder As String) Dim di As New DirectoryInfo(sourceFolder) Dim fis As FileInfo() = di.GetFiles() Dim fi As FileInfo Dim fileName As String For Each fi In fis fileName = fi.Name Select Case fileName.Substring(fileName.Length - 4).ToUpper Case ".RDL" PublishReport(sourceFolder, fileName, targetFolder) Case ".JPG", ".JPEG" PublishResource(sourceFolder, fileName, "image/jpeg", targetFolder) Case ".GIF", ".PNG", ".BMP" PublishResource(sourceFolder, fileName, "image/" + fileName.Substring(fileName.Length - 3).ToLower, targetFolder) End Select Next fi End Sub Public Sub PublishReport(ByVal sourceFolder As String, ByVal reportName As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + reportName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, properties warnings = rs.CreateReport(reportName.Substring(0, reportName.Length - 4), targetFolder, True, definition, Nothing) If Not (warnings Is Nothing) Then Dim warning As Warning For Each warning In warnings Console.WriteLine(warning.Message) Next warning Else Console.WriteLine("Report: {0} published successfully with no warnings", targetFolder + "/" + reportName) End If Catch e As Exception Console.WriteLine(e.Message) End Try End Sub Public Sub PublishResource(ByVal sourceFolder As String, ByVal resourceName As String, ByVal resourceMIME As String, ByVal targetFolder As String) Dim definition As [Byte]() = Nothing Dim warnings As Warning() = Nothing Try Dim stream As FileStream = File.OpenRead(sourceFolder + "\" + resourceName) definition = New [Byte](stream.Length) {} stream.Read(definition, 0, CInt(stream.Length)) stream.Close() Catch e As IOException Console.WriteLine(e.Message) End Try Try 'name, folder, overwrite, definition, MIME, properties rs.CreateResource(resourceName, targetFolder, True, definition, resourceMIME, Nothing) Console.WriteLine("Resource: {0} with MIME {1} created successfully", targetFolder + "/" + resourceName, resourceMIME) Catch e As Exception Console.WriteLine(e.Message) End Try End Sub ``` Here is the batch to call the rs.exe: ``` SET ReportServer=%1 SET DBServer=%2 SET DBName=%3 SET ReportFolder=%4 rs -i PublishReports.rss -s %ReportServer% -v dbServer="%DBServer%" -v db="%DBName%" -v parentFolder="%ReportFolder%" >PublishReports.log 2>&1 pause ```
88,717
<p>I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them?</p>
[ { "answer_id": 88758, "author": "Andy", "author_id": 3857, "author_profile": "https://Stackoverflow.com/users/3857", "pm_score": 2, "selected": false, "text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/44s54yc4.aspx\" rel=\"nofollow noreferrer\">AppDomain.Creat...
2008/09/17
[ "https://Stackoverflow.com/questions/88717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16979/" ]
I want to load one or more DLLs dynamically so that they run with a different security or basepath than my main application. How do I load these DLLs into a separate AppDomain and instantiate objects from them?
More specifically ``` AppDomain domain = AppDomain.CreateDomain("New domain name"); //Do other things to the domain like set the security policy string pathToDll = @"C:\myDll.dll"; //Full path to dll you want to load Type t = typeof(TypeIWantToLoad); TypeIWantToLoad myObject = (TypeIWantToLoad)domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName); ``` If all that goes properly (no exceptions thrown) you now have an instance of TypeIWantToLoad loaded into your new domain. The instance you have is actually a proxy (since the actual object is in the new domain) but you can use it just like your normal object. Note: As far as I know TypeIWantToLoad has to inherit from MarshalByRefObject.
88,743
<p>I'm using jmockit for unit testing (with TestNG), and I'm having trouble using the Expectations class to mock out a method that takes a primitive type (boolean) as a parameter, using a matcher. Here's some sample code that illustrates the problem.</p> <pre><code>/******************************************************/ import static org.hamcrest.Matchers.is; import mockit.Expectations; import org.testng.annotations.Test; public class PrimitiveMatcherTest { private MyClass obj; @Test public void testPrimitiveMatcher() { new Expectations(true) { MyClass c; { obj = c; invokeReturning(c.getFoo(with(is(false))), "bas"); } }; assert "bas".equals(obj.getFoo(false)); Expectations.assertSatisfied(); } public static class MyClass { public String getFoo(boolean arg) { if (arg) { return "foo"; } else { return "bar"; } } } } /******************************************************/ </code></pre> <p>The line containing the call to invokeReturning(...) throws a NullPointerException.</p> <p>If I change this call to not use a matcher, as in:</p> <pre><code>invokeReturning(c.getFoo(false), "bas"); </code></pre> <p>it works just fine. This is no good for me, because in my real code I'm actually mocking a multi-parameter method and I need to use a matcher on another argument. In this case, the Expectations class requires that <strong>all</strong> arguments use a matcher.</p> <p>I'm pretty sure this is a bug, or perhaps it's not possible to use Matchers with primitive types (that would make me sad). Has anyone encountered this issue, and know how to get around it?</p>
[ { "answer_id": 89215, "author": "DJ.", "author_id": 10638, "author_profile": "https://Stackoverflow.com/users/10638", "pm_score": 1, "selected": false, "text": "<p>the issue is the combination of Expectation usage and that Matchers does not support primitive type.</p>\n\n<p>The Matchers ...
2008/09/17
[ "https://Stackoverflow.com/questions/88743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16977/" ]
I'm using jmockit for unit testing (with TestNG), and I'm having trouble using the Expectations class to mock out a method that takes a primitive type (boolean) as a parameter, using a matcher. Here's some sample code that illustrates the problem. ``` /******************************************************/ import static org.hamcrest.Matchers.is; import mockit.Expectations; import org.testng.annotations.Test; public class PrimitiveMatcherTest { private MyClass obj; @Test public void testPrimitiveMatcher() { new Expectations(true) { MyClass c; { obj = c; invokeReturning(c.getFoo(with(is(false))), "bas"); } }; assert "bas".equals(obj.getFoo(false)); Expectations.assertSatisfied(); } public static class MyClass { public String getFoo(boolean arg) { if (arg) { return "foo"; } else { return "bar"; } } } } /******************************************************/ ``` The line containing the call to invokeReturning(...) throws a NullPointerException. If I change this call to not use a matcher, as in: ``` invokeReturning(c.getFoo(false), "bas"); ``` it works just fine. This is no good for me, because in my real code I'm actually mocking a multi-parameter method and I need to use a matcher on another argument. In this case, the Expectations class requires that **all** arguments use a matcher. I'm pretty sure this is a bug, or perhaps it's not possible to use Matchers with primitive types (that would make me sad). Has anyone encountered this issue, and know how to get around it?
So the problem appears to be in Expectations.with(): ``` protected final <T> T with(Matcher<T> argumentMatcher) { argMatchers.add(argumentMatcher); TypeVariable<?> typeVariable = argumentMatcher.getClass().getTypeParameters()[0]; return (T) Utilities.defaultValueForType(typeVariable.getClass()); } ``` The call to typeVariable.getClass() does not do what the author expects, and the call to Utilities.defaultValueFor type returns null. The de-autoboxing back the the primitive boolean value is where the NPE comes from. I fixed it by changing the invokeReturning(...) call to: ``` invokeReturning(withEqual(false)), "bas"); ``` I'm no longer using a matcher here, but it's good enough for what I need.
88,773
<p>There must be a generic way to transform some hierachical XML such as:</p> <pre><code>&lt;element1 A="AValue" B="BValue"&gt; &lt;element2 C="DValue" D="CValue"&gt; &lt;element3 E="EValue1" F="FValue1"/&gt; &lt;element3 E="EValue2" F="FValue2"/&gt; &lt;/element2&gt; ... &lt;/element1&gt; </code></pre> <p>into the flattened XML (html) picking up selected attributes along the way and providing different labels for the attributes that become column headers.</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;th&gt;A_Label&lt;/th&gt; &lt;th&gt;D_Label&lt;/th&gt; &lt;th&gt;E_Label&lt;/th&gt; &lt;th&gt;F_Label&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;AValue&lt;/td&gt; &lt;td&gt;DValue&lt;/td&gt; &lt;td&gt;EValue1&lt;/td&gt; &lt;td&gt;FValue1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;AValue&lt;/td&gt; &lt;td&gt;DValue&lt;/td&gt; &lt;td&gt;EValue2&lt;/td&gt; &lt;td&gt;FValue2&lt;/td&gt; &lt;/tr&gt; &lt;table&gt; </code></pre> <p>OK, so there's not generic solution due to the attribute re-labelling but you get what I mean hopefully. I've just started on all the XSLT/XPATH stuff so I'll work it out in good time but any clues would be useful.</p>
[ { "answer_id": 88867, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>We already have a Pro*C program reading from an Oracle database, it calls a perl script which in turn executes some Java to ...
2008/09/17
[ "https://Stackoverflow.com/questions/88773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There must be a generic way to transform some hierachical XML such as: ``` <element1 A="AValue" B="BValue"> <element2 C="DValue" D="CValue"> <element3 E="EValue1" F="FValue1"/> <element3 E="EValue2" F="FValue2"/> </element2> ... </element1> ``` into the flattened XML (html) picking up selected attributes along the way and providing different labels for the attributes that become column headers. ``` <table> <tr> <th>A_Label</th> <th>D_Label</th> <th>E_Label</th> <th>F_Label</th> </tr> <tr> <td>AValue</td> <td>DValue</td> <td>EValue1</td> <td>FValue1</td> </tr> <tr> <td>AValue</td> <td>DValue</td> <td>EValue2</td> <td>FValue2</td> </tr> <table> ``` OK, so there's not generic solution due to the attribute re-labelling but you get what I mean hopefully. I've just started on all the XSLT/XPATH stuff so I'll work it out in good time but any clues would be useful.
I'm not 100% sure of what you are trying to do but this solution may work if your element1, element2 and element3 are nested consistently. ``` <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"> <xsl:output method="xml" indent="yes"/> <xsl:template match="/"> <table> <xsl:apply-templates select="//element3"></xsl:apply-templates> </table> </xsl:template> <xsl:template match="element3"> <tr> <td><xsl:value-of select="../../@A"/></td> <td><xsl:value-of select="../../@B"/></td> <td><xsl:value-of select="../@C"/></td> <td><xsl:value-of select="../@D"/></td> <td><xsl:value-of select="@E"/></td> <td><xsl:value-of select="@F"/></td> </tr> <xsl:apply-templates select="*"></xsl:apply-templates> </xsl:template> </xsl:stylesheet> ```
88,775
<p>I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependent on what has to be done). </p> <p>Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down.</p> <p>Hopefully, something can be implemented globally rather than per page.</p>
[ { "answer_id": 88782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Drop an html file called \"app_offline.htm\" into the root of your virtual directory. Simple as that.</p>\n\n<p><a href=\"h...
2008/09/17
[ "https://Stackoverflow.com/questions/88775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16989/" ]
I work at a college and have been developing an ASP.NET site with many, many reports about students, attendance stats... The basis for the data is an MSSQL server DB which is the back end to our student management system. This has a regular maintenance period on Thursday mornings for an unknown length of time (dependent on what has to be done). Most of the staff are aware of this but the less regular users seem to be forever ringing me up. What is the easiest way to disable the site during maintenance obviously I can just try a DB query to test if it is up but am unsure of the best way to for instance redirect all users to a "The website is down for maintenance" message, bearing in mind they could have started a session prior to the website going down. Hopefully, something can be implemented globally rather than per page.
I would suggest doing it in Application\_PreRequestHandlerExecute instead of after an error occurs. Generally, it'd be best not to enter normal processing if you know your database isn't available. I typically use something like below ``` void Application_PreRequestHandlerExecute(Object sender, EventArgs e) { string sPage = Request.ServerVariables["SCRIPT_NAME"]; if (!sPage.EndsWith("Maintenance.aspx", StringComparison.OrdinalIgnoreCase)) { //test the database connection //if it fails then redirect the user to Maintenance.aspx string connStr = ConfigurationManager.ConnectionString["ConnectionString"].ConnectionString; SqlConnection conn = new SqlConnection(connStr); try { conn.Open(); } catch(Exception ex) { Session["DBException"] = ex; Response.Redirect("Maintenance.aspx"); } finally { conn.Close(); } } } ```
88,791
<p>I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for.</p> <p>An example...</p> <pre><code>public class Person { string firstName; string lastName; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName= value; } } } </code></pre> <p>Then doing object intialization with.....</p> <pre><code>Person p = new Person{ FirstName = "Joe", LastName = "Smith" }; Person p = new Person{ FirstName = "Joe" }; </code></pre>
[ { "answer_id": 88802, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>IMHO its sweet. Most objects are newed up with the default constructor, and must have some properties set before they are r...
2008/09/17
[ "https://Stackoverflow.com/questions/88791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342514/" ]
I was wondering what people thought of using properties as object initializers in C#. For some reason it seems to break the fundamentals of what constructors are used for. An example... ``` public class Person { string firstName; string lastName; public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get { return lastName; } set { lastName= value; } } } ``` Then doing object intialization with..... ``` Person p = new Person{ FirstName = "Joe", LastName = "Smith" }; Person p = new Person{ FirstName = "Joe" }; ```
What you see here is some syntatic sugar provided by the compiler. Under the hood what it really does is something like: **Person p = new Person( FirstName = "Joe", LastName = "Smith" );** ``` Person _p$1 = new Person(); _p$1.FirstName = "Joe"; _p$1.LastName = "Smith"; Person p = _p$1; ``` So IMHO you are not really breaking any constructor fundamentals but using a nice language artifact in order to ease readability and maintainability.
88,831
<p>Anyone has ever programmed a PHP (or Perl) function to get the ceiling value Excel style?</p>
[ { "answer_id": 88837, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 2, "selected": false, "text": "<p>Sorry, not quite clear what 'Excel style' is, but PHP has a <a href=\"http://us3.php.net/ceil\" rel=\"nofollow ...
2008/09/18
[ "https://Stackoverflow.com/questions/88831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Anyone has ever programmed a PHP (or Perl) function to get the ceiling value Excel style?
*"Microsoft Excel's ceiling function does not follow the mathematical definition, but rather as with (int) operator in C, it is a mixture of the floor and ceiling function: for x ≥ 0 it returns ceiling(x), and for x < 0 it returns floor(x). This has followed through to the Office Open XML file format. For example, CEILING(-4.5) returns -5. A mathematical ceiling function can be emulated in Excel by using the formula "-INT(-value)" (please note that this is not a general rule, as it depends on Excel's INT function, which behaves differently that most programming languages)."* - from [wikipedia](http://en.wikipedia.org/wiki/Ceiling_function) If php's built in ceil function isn't working right you could make a new function like ``` function excel_ceil($num){ return ($num>0)?ceil($num):floor($num); } ``` Hope that helps
88,838
<p>In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?</p>
[ { "answer_id": 88847, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": "<pre><code>String original = \"hello world\";\nbyte[] utf8Bytes = original.getBytes(\"UTF-8\");\n</code></pre>\n" },...
2008/09/18
[ "https://Stackoverflow.com/questions/88838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14570/" ]
In Java, I have a String and I want to encode it as a byte array (in UTF8, or some other encoding). Alternately, I have a byte array (in some known encoding) and I want to convert it into a Java String. How do I do these conversions?
Convert from `String` to `byte[]`: ``` String s = "some text here"; byte[] b = s.getBytes(StandardCharsets.UTF_8); ``` Convert from `byte[]` to `String`: ``` byte[] b = {(byte) 99, (byte)97, (byte)116}; String s = new String(b, StandardCharsets.US_ASCII); ``` You should, of course, use the correct encoding name. My examples used US-ASCII and UTF-8, two commonly-used encodings.
88,918
<p>This is my first experience using the Zend Framework. I am attempting to follow the <a href="http://framework.zend.com/docs/quickstart/introduction" rel="nofollow noreferrer">Quick Start</a> tutorial. Everything was working as expected until I reached the section on the <a href="http://framework.zend.com/docs/quickstart/create-an-error-controller-and-view" rel="nofollow noreferrer">Error Controller and View</a>. When I navigate to a page that does not exist, instead of receiving the error page I get the Fatal Error screen dump (in all it's glory):</p> <blockquote> <p>Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (error)' in /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php:249 Stack trace: #0 /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Front.php(946): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http)) #1 /home/.fantasia/bcnewman/foo.com/public/index.php(42): Zend_Controller_Front->dispatch() #2 {main} thrown in /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php on line 249</p> </blockquote> <p>I do not believe this is caused by a syntax error on my part (a copied and pasted the example file's content from the tutorial) and I believe I have the application directory structure correct:</p> <pre><code>./application ./application/controllers ./application/controllers/IndexController.php ./application/controllers/ErrorHandler.php ./application/views ./application/views/scripts ./application/views/scripts/index ./application/views/scripts/index/index.phtml ./application/views/scripts/error ./application/views/scripts/error/error.phtml ./application/bootstrap.php ./public ./public/index.php </code></pre> <p>And finally, the <code>IndexController</code> and <code>index.phtml</code> view does work.</p>
[ { "answer_id": 89347, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 2, "selected": false, "text": "<p>Assuming that you have the ErrorController plugin loaded into your front controller, make sure that in your bootstrap ...
2008/09/18
[ "https://Stackoverflow.com/questions/88918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3210/" ]
This is my first experience using the Zend Framework. I am attempting to follow the [Quick Start](http://framework.zend.com/docs/quickstart/introduction) tutorial. Everything was working as expected until I reached the section on the [Error Controller and View](http://framework.zend.com/docs/quickstart/create-an-error-controller-and-view). When I navigate to a page that does not exist, instead of receiving the error page I get the Fatal Error screen dump (in all it's glory): > > Fatal error: Uncaught exception 'Zend\_Controller\_Dispatcher\_Exception' > with message 'Invalid controller specified (error)' in > /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php:249 > Stack trace: #0 > /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Front.php(946): > Zend\_Controller\_Dispatcher\_Standard->dispatch(Object(Zend\_Controller\_Request\_Http), > Object(Zend\_Controller\_Response\_Http)) #1 > /home/.fantasia/bcnewman/foo.com/public/index.php(42): > Zend\_Controller\_Front->dispatch() #2 {main} thrown in > /home/.fantasia/bcnewman/foo.com/library/Zend/Controller/Dispatcher/Standard.php > on line 249 > > > I do not believe this is caused by a syntax error on my part (a copied and pasted the example file's content from the tutorial) and I believe I have the application directory structure correct: ``` ./application ./application/controllers ./application/controllers/IndexController.php ./application/controllers/ErrorHandler.php ./application/views ./application/views/scripts ./application/views/scripts/index ./application/views/scripts/index/index.phtml ./application/views/scripts/error ./application/views/scripts/error/error.phtml ./application/bootstrap.php ./public ./public/index.php ``` And finally, the `IndexController` and `index.phtml` view does work.
You have ErrorHandler.php. It should be ErrorController.php. Controllers all need to be named following the format of NameController.php. Since you don't have it named properly the dispatcher cannot find it.
88,929
<p>Is there a command that would allow me to check if the string <code>"xyz"</code> was ever in file <code>foo.c</code> in the repository and print which revisions they were found in? </p>
[ { "answer_id": 89008, "author": "CaptainPicard", "author_id": 15203, "author_profile": "https://Stackoverflow.com/users/15203", "pm_score": 6, "selected": true, "text": "<p>This will print any commits where the diff contains xyz</p>\n\n<pre><code>git log -Sxyz foo.c\n</code></pre>\n" }...
2008/09/18
[ "https://Stackoverflow.com/questions/88929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
Is there a command that would allow me to check if the string `"xyz"` was ever in file `foo.c` in the repository and print which revisions they were found in?
This will print any commits where the diff contains xyz ``` git log -Sxyz foo.c ```
88,931
<p>When defining or calling functions with enough arguments to span multiple lines, I want vim to line them up. For example,</p> <pre><code>def myfunction(arg1, arg2, arg, ... argsN-1, argN) </code></pre> <p>The idea is for argsN-1 to have its 'a' lined up with args1.</p> <p>Does anyone have a way to have this happen automatically in vim? I've seen the align plugin for lining equal signs (in assignment statements) and such, but I'm not sure if it can be made to solve this problem?</p>
[ { "answer_id": 89119, "author": "solinent", "author_id": 13852, "author_profile": "https://Stackoverflow.com/users/13852", "pm_score": 3, "selected": false, "text": "<p>I believe you have to issue the command:</p>\n\n<pre><code>:set cino=(0\n</code></pre>\n\n<p>This is when using cindent...
2008/09/18
[ "https://Stackoverflow.com/questions/88931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7706/" ]
When defining or calling functions with enough arguments to span multiple lines, I want vim to line them up. For example, ``` def myfunction(arg1, arg2, arg, ... argsN-1, argN) ``` The idea is for argsN-1 to have its 'a' lined up with args1. Does anyone have a way to have this happen automatically in vim? I've seen the align plugin for lining equal signs (in assignment statements) and such, but I'm not sure if it can be made to solve this problem?
The previous poster had it, but forgot the `set` ``` :set cino=(0<Enter> ``` From `:help cinoptions-values` ``` The 'cinoptions' option sets how Vim performs indentation. In the list below, "N" represents a number of your choice (the number can be negative). When there is an 's' after the number, Vim multiplies the number by 'shiftwidth': "1s" is 'shiftwidth', "2s" is two times 'shiftwidth', etc. You can use a decimal point, too: "-0.5s" is minus half a 'shiftwidth'. The examples below assume a 'shiftwidth' of 4. ... (N When in unclosed parentheses, indent N characters from the line with the unclosed parentheses. Add a 'shiftwidth' for every unclosed parentheses. When N is 0 or the unclosed parentheses is the first non-white character in its line, line up with the next non-white character after the unclosed parentheses. (default 'shiftwidth' * 2). cino= cino=(0 > if (c1 && (c2 || if (c1 && (c2 || c3)) c3)) foo; foo; if (c1 && if (c1 && (c2 || c3)) (c2 || c3)) { { ```
88,957
<p>When <code>{0}</code> is used to initialize an object, what does it mean? I can't find any references to <code>{0}</code> anywhere, and because of the curly braces Google searches are not helpful.</p> <p>Example code:</p> <pre><code>SHELLEXECUTEINFO sexi = {0}; // what does this do? sexi.cbSize = sizeof(SHELLEXECUTEINFO); sexi.hwnd = NULL; sexi.fMask = SEE_MASK_NOCLOSEPROCESS; sexi.lpFile = lpFile.c_str(); sexi.lpParameters = args; sexi.nShow = nShow; if(ShellExecuteEx(&amp;sexi)) { DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE); if(wait == WAIT_OBJECT_0) GetExitCodeProcess(sexi.hProcess, &amp;returnCode); } </code></pre> <p>Without it, the above code will crash on runtime.</p>
[ { "answer_id": 88960, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 9, "selected": true, "text": "<p>What's happening here is called <strong>aggregate</strong> initialization. Here is the (abbreviated) definition of a...
2008/09/18
[ "https://Stackoverflow.com/questions/88957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17027/" ]
When `{0}` is used to initialize an object, what does it mean? I can't find any references to `{0}` anywhere, and because of the curly braces Google searches are not helpful. Example code: ``` SHELLEXECUTEINFO sexi = {0}; // what does this do? sexi.cbSize = sizeof(SHELLEXECUTEINFO); sexi.hwnd = NULL; sexi.fMask = SEE_MASK_NOCLOSEPROCESS; sexi.lpFile = lpFile.c_str(); sexi.lpParameters = args; sexi.nShow = nShow; if(ShellExecuteEx(&sexi)) { DWORD wait = WaitForSingleObject(sexi.hProcess, INFINITE); if(wait == WAIT_OBJECT_0) GetExitCodeProcess(sexi.hProcess, &returnCode); } ``` Without it, the above code will crash on runtime.
What's happening here is called **aggregate** initialization. Here is the (abbreviated) definition of an aggregate from section 8.5.1 of the ISO spec: > > An aggregate is an array or a class with no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions. > > > Now, using `{0}` to initialize an aggregate like this is basically a trick to `0` the entire thing. This is because when using aggregate initialization **you don't have to specify all the members** and the spec requires that all unspecified members be default initialized, which means set to `0` for simple types. Here is the relevant quote from the spec: > > If there are fewer initializers in the list than there are members in the > aggregate, then each member not > explicitly initialized shall be > default-initialized. > Example: > > > > ``` > struct S { int a; char* b; int c; }; > S ss = { 1, "asdf" }; > > ``` > > initializes `ss.a` with `1`, `ss.b` with > `"asdf"`, and `ss.c` with the value of an > expression of the form `int()`, that is, > `0`. > > > You can find the complete spec on this topic [here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf#page=207)
88,991
<p>I do not mean the compile errors because I made a syntax mistake or whatever. In C++ we can create compile time errors based on conditions as in the following example:</p> <pre><code>template&lt;int&gt; struct CompileTimeError; template&lt;&gt; struct CompileTimeError&lt;true&gt; {}; #define STATIC_CHECK(expr, msg) { CompileTimeError&lt;((expr) != 0)&gt; ERROR_##msg; (void)ERROR_##msg; } int main(int argc, char* argv[]) { STATIC_CHECK(false, Compile_Time_Failure); return 0; } </code></pre> <p>In VS 2005 this will output:</p> <pre><code>------ Build started: Project: Test, Configuration: Debug Win32 ------ Compiling... Test.cpp f:\temp\test\test\test.cpp(17) : error C2079: 'ERROR_Compile_Time_Failure' uses undefined struct 'CompileTimeError&lt;__formal&gt;' with [ __formal=0 ] Build log was saved at "file://f:\temp\Test\Test\Debug\BuildLog.htm" Test - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== </code></pre> <p>Is there any way to achieve this in Java?</p>
[ { "answer_id": 89017, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>There is no way to produce any actions based on compile-time logic in Java without the use of a separate tool. Tec...
2008/09/18
[ "https://Stackoverflow.com/questions/88991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6508/" ]
I do not mean the compile errors because I made a syntax mistake or whatever. In C++ we can create compile time errors based on conditions as in the following example: ``` template<int> struct CompileTimeError; template<> struct CompileTimeError<true> {}; #define STATIC_CHECK(expr, msg) { CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } int main(int argc, char* argv[]) { STATIC_CHECK(false, Compile_Time_Failure); return 0; } ``` In VS 2005 this will output: ``` ------ Build started: Project: Test, Configuration: Debug Win32 ------ Compiling... Test.cpp f:\temp\test\test\test.cpp(17) : error C2079: 'ERROR_Compile_Time_Failure' uses undefined struct 'CompileTimeError<__formal>' with [ __formal=0 ] Build log was saved at "file://f:\temp\Test\Test\Debug\BuildLog.htm" Test - 1 error(s), 0 warning(s) ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ========== ``` Is there any way to achieve this in Java?
There is no way to do this in Java, not in the same way it works for you in C++. You could perhaps use annotations, and run [apt](http://java.sun.com/j2se/1.5.0/docs/guide/apt/GettingStarted.html) before or after compilation to check your annotations. For example: ``` @MyStaticCheck(false, "Compile Time Error, kind-of") public static void main(String[] args) { return; } ``` And then write your own AnnotationProcessorFactory that looked for @MyStaticCheck annotations, and does something with the arguments. Note: I haven't played too much with apt, but the documentation makes it looks like this is very do-able.
89,051
<p>What I'd like to know is if there is a nice way to queue jQuery functions to execute after a set amount of time. This wouldn't pause the execution of other functions, just the ones following in the chain. Perhaps an example of what I'd envisage it would look like would illustrate:</p> <pre><code>$('#alert') .show() .wait(5000) // &lt;-- this bit .hide() ; </code></pre> <p>I know that it's possible by using timeouts, but it seems like that's a messy way to do it, especially compared to the above example (if it were real).</p> <p>So, is something like this already built-in to jQuery, and if not, what is the best way to emulate it?</p>
[ { "answer_id": 89076, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": true, "text": "<p>You can't do that, and you probably don't want to. While it certainly looks pretty, there is no mechanism in Javascript t...
2008/09/18
[ "https://Stackoverflow.com/questions/89051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
What I'd like to know is if there is a nice way to queue jQuery functions to execute after a set amount of time. This wouldn't pause the execution of other functions, just the ones following in the chain. Perhaps an example of what I'd envisage it would look like would illustrate: ``` $('#alert') .show() .wait(5000) // <-- this bit .hide() ; ``` I know that it's possible by using timeouts, but it seems like that's a messy way to do it, especially compared to the above example (if it were real). So, is something like this already built-in to jQuery, and if not, what is the best way to emulate it?
You can't do that, and you probably don't want to. While it certainly looks pretty, there is no mechanism in Javascript that will allow you do to that without just looping in "wait" until the time has passed. You could certainly do that but you risk seriously degrading the browser performance and if your timeout is longer than a handful of seconds browsers will show a warning to the user that your javascript seems to be stuck. The correct way to do this is with timeouts: ``` var el = $('#alert'); el.show() setTimeout(function() { el.hide() }, 5000); ``` Your other option would be to extend jquery to essentially add an effect for actions you want to delay: ``` jQuery.fn.extend({ delayedHide: function(time) { var self = this; setTimeout(function() { self.hide(); }, time); } }); $('#alert') .show() .delayedHide(5000) ; ``` You could also extend jquery with a method similar to setTimeout: ``` jQuery.fn.extend({ delayThis: function(fn, time, args) { var self = this; setTimeout(function() { jQuery.fn[fn].apply(self, args); }, time); } }); $('#alert') .show() .delayThis('hide', 5000) ; ``` or to call with args pass arguments in an array: ``` $('#alert') .show() .delayThis('css', 5000, [ 'display', 'none' ]) ; ```
89,118
<p>I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file: </p> <p><pre><code> NameVirtualHost 127.0.0.1</p> <p>&lt;VirtualHost 127.0.0.1> ServerName foo.localhost DocumentRoot "C:/xampp/htdocs/foo/public" &lt;/VirtualHost></p> <p>&lt;VirtualHost 127.0.0.1> ServerName bar.localhost DocumentRoot "F:/bar/public" &lt;/VirtualHost> </pre></code></p> <p>When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped.</p> <p>Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.</p>
[ { "answer_id": 91885, "author": "Mark Embling", "author_id": 6844, "author_profile": "https://Stackoverflow.com/users/6844", "pm_score": 6, "selected": false, "text": "<p>Somewhere, you need to tell Apache that people are allowed to see contents of this directory.</p>\n\n<pre><code>&lt;D...
2008/09/18
[ "https://Stackoverflow.com/questions/89118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752/" ]
I am getting an 403 access forbidden when attempting to open a page under a vhost where the document root is sitting on a different drive than where apache is sitting. I installed using the apachefriends release. This is my httpd-vhosts.conf file: ``` NameVirtualHost 127.0.0.1 ``` <VirtualHost 127.0.0.1> ServerName foo.localhost DocumentRoot "C:/xampp/htdocs/foo/public" </VirtualHost> <VirtualHost 127.0.0.1> ServerName bar.localhost DocumentRoot "F:/bar/public" </VirtualHost> When opening bar.localhost in my browser, Apache is giving me 403 Access Forbidden. I tried setting lots of different access rights, even full rights to everyone, but nothing I tried helped. Edit: Thanks! For future reference, add 'Options indexes' within to show directory indexes.
You did not need ``` Options Indexes FollowSymLinks MultiViews Includes ExecCGI AllowOverride All Order Allow,Deny Allow from all Require all granted ``` the only thing what you need is... ``` Require all granted ``` ...inside the directory section. See Apache 2.4 upgrading side: <http://httpd.apache.org/docs/2.4/upgrading.html>
89,154
<pre><code>boolean a = false, b = true; if ( a &amp;&amp; b ) { ... }; </code></pre> <p>In most languages, <code>b</code> will not get evaluated because <code>a</code> is false so <code>a &amp;&amp; b</code> cannot be true. My question is, wouldn't short circuiting be slower in terms of architecture? In a pipeline, do you just stall while waiting to get the result of a to determine if b should be evaluated or not? Would it be better to do nested ifs instead? Does that even help?</p> <p>Also, does anyone know what short-circuit evaluation is typically called? This question arose after I found out that my programming friend had never heard of short-circuit evaluation and stated that it is not common, nor found in many languages, and is inefficient in pipeline. I am not certain about the last one, so asking you folks!</p> <p>Okay, I think a different example to perhaps explain where my friend might be coming from. He believes that since evaluating a statement like the following in parallel:</p> <pre><code>(a) if ( ( a != null ) &amp;&amp; ( a.equals(b) ) ) { ... } </code></pre> <p>will crash the system, an architecture that doesn't have short-circuiting (and thereby not allowing statements like the above) would be faster in processing statements like these:</p> <pre><code>(b) if ( ( a == 4 ) &amp;&amp; ( b == 5 ) ) </code></pre> <p>since if it couldn't do (a) in parallel, it can't do (b) in parallel. In this case, a language that allows short-circuiting is slower than one that does not.</p> <p>I don't know if that's true or not.</p> <p>Thanks</p>
[ { "answer_id": 89170, "author": "user10392", "author_id": 10392, "author_profile": "https://Stackoverflow.com/users/10392", "pm_score": 1, "selected": false, "text": "<p>How can a nested if not stall? Actually if a and b are both variables and not expressions with side effects, they can...
2008/09/18
[ "https://Stackoverflow.com/questions/89154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12682/" ]
``` boolean a = false, b = true; if ( a && b ) { ... }; ``` In most languages, `b` will not get evaluated because `a` is false so `a && b` cannot be true. My question is, wouldn't short circuiting be slower in terms of architecture? In a pipeline, do you just stall while waiting to get the result of a to determine if b should be evaluated or not? Would it be better to do nested ifs instead? Does that even help? Also, does anyone know what short-circuit evaluation is typically called? This question arose after I found out that my programming friend had never heard of short-circuit evaluation and stated that it is not common, nor found in many languages, and is inefficient in pipeline. I am not certain about the last one, so asking you folks! Okay, I think a different example to perhaps explain where my friend might be coming from. He believes that since evaluating a statement like the following in parallel: ``` (a) if ( ( a != null ) && ( a.equals(b) ) ) { ... } ``` will crash the system, an architecture that doesn't have short-circuiting (and thereby not allowing statements like the above) would be faster in processing statements like these: ``` (b) if ( ( a == 4 ) && ( b == 5 ) ) ``` since if it couldn't do (a) in parallel, it can't do (b) in parallel. In this case, a language that allows short-circuiting is slower than one that does not. I don't know if that's true or not. Thanks
Short-circuiting boolean expressions are exactly equivalent to some set of nested ifs, so are as efficient as that would be. If b doesn't have side-effects, it can still be executed in parallel with a (for any value of "in parallel", including pipelining). If b has side effects which the CPU architecture can't cancel when branch prediction fails then yes, this might require delays which wouldn't be there if both sides were always evaluated. So it's something to look at if you do ever find that short-circuiting operators are creating a performance bottleneck in your code, but not worth worrying about otherwise. But short-circuiting is used for control flow as much as to save unnecessary work. It's common among languages I've used, for example the Perl idiom: ``` open($filename) or die("couldn't open file"); ``` the shell idiom: ``` do_something || echo "that failed" ``` or the C/C++/Java/etc idiom: ``` if ((obj != 0) && (obj->ready)) { do_something; } // not -> in Java of course. ``` In all these cases you need short-circuiting, so that the RHS is only evaluated if the LHS dictates that it should be. In such cases there's no point comparing performance with alternative code that's wrong!
89,178
<p>For example:</p> <pre><code>&gt;&gt;&gt; x = [1, 1, 2, 'a', 'a', 3] &gt;&gt;&gt; unique(x) [1, 2, 'a', 3] </code></pre> <p>Assume list elements are hashable.</p> <p><strong>Clarification:</strong> The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].</p>
[ { "answer_id": 89197, "author": "solinent", "author_id": 13852, "author_profile": "https://Stackoverflow.com/users/13852", "pm_score": 0, "selected": false, "text": "<p>I have no experience with python, but an algorithm would be to sort the list, then remove duplicates (by comparing to p...
2008/09/18
[ "https://Stackoverflow.com/questions/89178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16976/" ]
For example: ``` >>> x = [1, 1, 2, 'a', 'a', 3] >>> unique(x) [1, 2, 'a', 3] ``` Assume list elements are hashable. **Clarification:** The result should keep the first duplicate in the list. For example, [1, 2, 3, 2, 3, 1] becomes [1, 2, 3].
``` def unique(items): found = set() keep = [] for item in items: if item not in found: found.add(item) keep.append(item) return keep print unique([1, 1, 2, 'a', 'a', 3]) ```
89,188
<p>Is it possible to get the x,y coordinates of a Flex app within an HTML page? I know you can use ExternalInterface.ObjecID to get the "id attribute of the object tag in Internet Explorer, or the name attribute of the embed tag in Netscape" but I can't seem to get past that step. It seems like it should be possible to get a handle on that embed object. Any suggestions? </p> <p>Thanks.</p>
[ { "answer_id": 89286, "author": "Robert", "author_id": 4959, "author_profile": "https://Stackoverflow.com/users/4959", "pm_score": 0, "selected": false, "text": "<p>If you are trying just to measure where it's at within a page as the external user the only thing that pops into my mind is...
2008/09/18
[ "https://Stackoverflow.com/questions/89188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15899/" ]
Is it possible to get the x,y coordinates of a Flex app within an HTML page? I know you can use ExternalInterface.ObjecID to get the "id attribute of the object tag in Internet Explorer, or the name attribute of the embed tag in Netscape" but I can't seem to get past that step. It seems like it should be possible to get a handle on that embed object. Any suggestions? Thanks.
I think the easiest thing to do is to include some kind of JavaScript library on the HTML page, say jQuery, and use it's functions for determining the position and size of DOM nodes. I would do it more or less like this: ``` var jsCode : String = "function( id ) { return $('#' + id).offset(); }"; var offset : Object = ExternalInterface.call(jsCode, ExternalObject.objectID); trace(offset.left, offset.top); ``` Notice that this is ActionScript code, but it runs JavaScript code through `ExternalInterface`. It uses jQuery and in particular its `offset` method that returns the left and top offset of a DOM node. You could do without jQuery if you looked at how the `offset` method is implemented and included that code in place of the call to jQuery. That way you wouldn't need to load jQuery in the HTML and the Flex app would be self-contained. The reason I suggest to use a library like jQuery is that browsers do these things differently. I'm not sure if calculating offsets is very different from browser to browser, but it doesn't hurt to be insulated from browser differences. The JavaScript in my example is an anonymous function so that the ID of the embed/object tag can be passed in to it as a parameter to `ExternalInterface.call`, but you could just use string concatenation if you want: ``` var jsCode : String = "$('#' +" + ExternalInterface.objectID + ").offset()"; var offset : Object = ExternalInterface.call(jsCode); ``` That would work too, I just think the first version is more elegant.
89,193
<p>Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following:</p> <pre><code>var people = from p in Person where p.age &lt; 18 select p var otherPeople = from p in people where p.firstName equals "Daniel" select p </code></pre> <p>Assuming that <code>Person</code> is an ADO entity which defines the <code>age</code> and <code>firstName</code> fields, what would this do from a database standpoint? Specifically, would the <code>people</code> query be run to produce an in-memory structure, which would then be queried by the <code>otherPeople</code> query? Or would the construction of <code>otherPeople</code> merely pull the data regarding the query from <code>people</code> and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?</p>
[ { "answer_id": 89211, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 1, "selected": false, "text": "<p><code>people</code> and <code>otherPeople</code> contain objects of type <code>IQueryable&lt;Person></code>.</p>\n\...
2008/09/18
[ "https://Stackoverflow.com/questions/89193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815/" ]
Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following: ``` var people = from p in Person where p.age < 18 select p var otherPeople = from p in people where p.firstName equals "Daniel" select p ``` Assuming that `Person` is an ADO entity which defines the `age` and `firstName` fields, what would this do from a database standpoint? Specifically, would the `people` query be run to produce an in-memory structure, which would then be queried by the `otherPeople` query? Or would the construction of `otherPeople` merely pull the data regarding the query from `people` and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?
They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL. Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.
89,228
<p>How do I call an external command within Python as if I'd typed it in a shell or command prompt?</p>
[ { "answer_id": 89237, "author": "nimish", "author_id": 3926, "author_profile": "https://Stackoverflow.com/users/3926", "pm_score": 8, "selected": false, "text": "<pre><code>import os\nos.system(\"your command\")\n</code></pre>\n\n<p>Note that this is dangerous, since the command isn't cl...
2008/09/18
[ "https://Stackoverflow.com/questions/89228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17085/" ]
How do I call an external command within Python as if I'd typed it in a shell or command prompt?
Use the [`subprocess`](https://docs.python.org/library/subprocess.html) module in the standard library: ```py import subprocess subprocess.run(["ls", "-l"]) ``` The advantage of [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run) over [`os.system`](https://docs.python.org/library/os.html#os.system) is that it is more flexible (you can get the [`stdout`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout), [`stderr`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr), the ["real" status code](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode), better [error handling](https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError), etc...). Even [the documentation for `os.system`](https://docs.python.org/library/os.html#os.system) recommends using `subprocess` instead: > > The `subprocess` module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the [Replacing Older Functions with the subprocess Module](https://docs.python.org/library/subprocess.html#subprocess-replacements) section in the [`subprocess`](https://docs.python.org/library/subprocess.html) documentation for some helpful recipes. > > > On Python 3.4 and earlier, use `subprocess.call` instead of `.run`: ```py subprocess.call(["ls", "-l"]) ```
89,245
<p>Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs.</p> <p>BUT....</p> <p>It is very tedious to copy &amp; paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files.</p> <p>Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well.</p> <p>What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers?</p> <p>FOLLOWUP:</p> <p>Will's <a href="https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618">answer</a> was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with <a href="https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618">custom configuration sections</a> ? </p> <p>Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful.</p> <p>Dave </p>
[ { "answer_id": 89261, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>You use one master config file that points to other config files. <a href=\"http://blog.andreloker.de/post/2008/06/Keep-your...
2008/09/18
[ "https://Stackoverflow.com/questions/89245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6996/" ]
Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs. BUT.... It is very tedious to copy & paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files. Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well. What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers? FOLLOWUP: Will's [answer](https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618) was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with [custom configuration sections](https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618) ? Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful. Dave
You use one master config file that points to other config files. [Here's an example of how to do this.](http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx) --- In case the link rots, what you do is specify the [configSource](http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx) for a particular configuration section. This allows you to define that particular section within a separate file. ```xml <pages configSource="pages.config"/> ``` which implies that there is a file called "pages.config" within the same directory that contains the entire `<pages />` node tree.
89,246
<p>I’m trying to run this SQL using get external.</p> <p>It works, but when I try to rename the sub-queries or anything for that matter it remove it.</p> <p>I tried <code>as</code>, <code>as</code> and the name in <code>''</code>, <code>as</code> then the name in <code>""</code>, and the same with space. What is the right way to do that? </p> <p>Relevant SQL:</p> <pre><code>SELECT list_name, app_name, (SELECT fname + ' ' + lname FROM dbo.d_agent_define map WHERE map.agent_id = tac.agent_id) as agent_login, input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) FROM dbo.maps_report_list list JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id) WHERE input = 'SYS_ERR' AND app_name = 'CHARLOTT' AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' AND list_name LIKE 'NRBAD%' ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) </code></pre>
[ { "answer_id": 89314, "author": "jttraino", "author_id": 3203, "author_profile": "https://Stackoverflow.com/users/3203", "pm_score": 1, "selected": false, "text": "<p>You could get rid of your <code>dbo.d_agent_define</code> subquery and just add in a join to the agent define table.</p>\...
2008/09/18
[ "https://Stackoverflow.com/questions/89246", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13122/" ]
I’m trying to run this SQL using get external. It works, but when I try to rename the sub-queries or anything for that matter it remove it. I tried `as`, `as` and the name in `''`, `as` then the name in `""`, and the same with space. What is the right way to do that? Relevant SQL: ``` SELECT list_name, app_name, (SELECT fname + ' ' + lname FROM dbo.d_agent_define map WHERE map.agent_id = tac.agent_id) as agent_login, input, CONVERT(varchar,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) FROM dbo.maps_report_list list JOIN dbo.report_tac_agent tac ON (tac.list_id = list.list_id) WHERE input = 'SYS_ERR' AND app_name = 'CHARLOTT' AND convert(VARCHAR,DATEADD(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' AND list_name LIKE 'NRBAD%' ORDER BY agent_login,CONVERT(VARCHAR,DATEADD(ss,TAC_BEG_tstamp,'01/01/1970')) ```
You could get rid of your `dbo.d_agent_define` subquery and just add in a join to the agent define table. Would this code work? ``` select list_name, app_name, map.fname + ' ' + map.lname as agent_login, input, convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) as tac_seconds from dbo.maps_report_list list join dbo.report_tac_agent tac on (tac.list_id = list.list_id) join dbo.d_agent_define map on (map.agent_id = tac.agent_id) where input = 'SYS_ERR' and app_name = 'CHARLOTT' and convert(varchar,dateadd(ss,day_tstamp,'01/01/1970'),101) = '09/10/2008' and list_name LIKE 'NRBAD%' order by agent_login,convert(varchar,dateadd(ss,TAC_BEG_tstamp,'01/01/1970')) ``` Note that I named your dateadd column because it did not have a name. I also tried to keep your convention of how you do a join. There are a few things that I would do different with this query to make it more readable, but I only focused on getting rid of the subquery problem. I did not do this, but I would recommend that you qualify all of your columns with the table from which you are getting them.
89,257
<p>I've run into what appears to be a variable scope issue I haven't encountered before. I'm using Perl's CGI module and a call to DBI's do() method. Here's the code structure, simplified a bit:</p> <pre><code>use DBI; use CGI qw(:cgi-lib); &amp;ReadParse; my $dbh = DBI-&gt;connect(...............); my $test = $in{test}; $dbh-&gt;do(qq{INSERT INTO events VALUES (?,?,?)},undef,$in{test},"$in{test}",$test); </code></pre> <p>The #1 placeholder variable evaluates as if it is uninitialized. The other two placeholder variables work.</p> <p><strong>The question: Why is the %in hash not available within the context of do(), unless I wrap it in double quotes (#2 placeholder) or reassign the value to a new variable (#3 placeholder)?</strong></p> <p>I think it's something to do with how the CGI module's ReadParse() function assigns scope to the %in hash, but I don't know Perl scoping well enough to understand why %in is available at the top level but not from within my do() statement.</p> <p>If someone does understand the scoping issue, is there a better way to handle it? Wrapping all the %in references in double quotes seems a little messy. Creating new variables for each query parameter isn't realistic.</p> <p>Just to be clear, my question is about the variable scoping issue. I realize that ReadParse() isn't the recommended method to grab query params with CGI.</p> <p>I'm using Perl 5.8.8, CGI 3.20, and DBI 1.52. Thank you in advance to anyone reading this.</p> <p>@Pi &amp; @Bob, thanks for the suggestions. Pre-declaring the scope for %in has no effect (and I always use strict). The result is the same as before: in the db, col1 is null while cols 2 &amp; 3 are set to the expected value.</p> <p>For reference, here's the ReadParse function (see below). It's a standard function that's part of CGI.pm. The way I understand it, I'm not meant to initialize the %in hash (other than satisfying strict) for purposes of setting scope, since the function appears to me to handle that:</p> <pre><code>sub ReadParse { local(*in); if (@_) { *in = $_[0]; } else { my $pkg = caller(); *in=*{"${pkg}::in"}; } tie(%in,CGI); return scalar(keys %in); } </code></pre> <p>I guess my question is what is the best way to get the %in hash within the context of do()? Thanks again! I hope this is the right way to provide additional info to my original question.</p> <p>@Dan: I hear ya regarding the &amp;ReadParse syntax. I'd normally use CGI::ReadParse() but in this case I thought it was best to stick to how <a href="http://search.cpan.org/src/LDS/CGI.pm-3.42/cgi-lib_porting.html" rel="nofollow noreferrer">the CGI.pm documentation has it</a> exactly.</p>
[ { "answer_id": 89282, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 2, "selected": false, "text": "<p><code>use strict;</code>. Always.</p>\n\n<p>Try declaring</p>\n\n<pre><code>our %in;\n</code></pre>\n\n<p>and seeing if tha...
2008/09/18
[ "https://Stackoverflow.com/questions/89257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17092/" ]
I've run into what appears to be a variable scope issue I haven't encountered before. I'm using Perl's CGI module and a call to DBI's do() method. Here's the code structure, simplified a bit: ``` use DBI; use CGI qw(:cgi-lib); &ReadParse; my $dbh = DBI->connect(...............); my $test = $in{test}; $dbh->do(qq{INSERT INTO events VALUES (?,?,?)},undef,$in{test},"$in{test}",$test); ``` The #1 placeholder variable evaluates as if it is uninitialized. The other two placeholder variables work. **The question: Why is the %in hash not available within the context of do(), unless I wrap it in double quotes (#2 placeholder) or reassign the value to a new variable (#3 placeholder)?** I think it's something to do with how the CGI module's ReadParse() function assigns scope to the %in hash, but I don't know Perl scoping well enough to understand why %in is available at the top level but not from within my do() statement. If someone does understand the scoping issue, is there a better way to handle it? Wrapping all the %in references in double quotes seems a little messy. Creating new variables for each query parameter isn't realistic. Just to be clear, my question is about the variable scoping issue. I realize that ReadParse() isn't the recommended method to grab query params with CGI. I'm using Perl 5.8.8, CGI 3.20, and DBI 1.52. Thank you in advance to anyone reading this. @Pi & @Bob, thanks for the suggestions. Pre-declaring the scope for %in has no effect (and I always use strict). The result is the same as before: in the db, col1 is null while cols 2 & 3 are set to the expected value. For reference, here's the ReadParse function (see below). It's a standard function that's part of CGI.pm. The way I understand it, I'm not meant to initialize the %in hash (other than satisfying strict) for purposes of setting scope, since the function appears to me to handle that: ``` sub ReadParse { local(*in); if (@_) { *in = $_[0]; } else { my $pkg = caller(); *in=*{"${pkg}::in"}; } tie(%in,CGI); return scalar(keys %in); } ``` I guess my question is what is the best way to get the %in hash within the context of do()? Thanks again! I hope this is the right way to provide additional info to my original question. @Dan: I hear ya regarding the &ReadParse syntax. I'd normally use CGI::ReadParse() but in this case I thought it was best to stick to how [the CGI.pm documentation has it](http://search.cpan.org/src/LDS/CGI.pm-3.42/cgi-lib_porting.html) exactly.
Per the DBI documentation: Binding a tied variable doesn't work, currently. DBI is pretty complicated under the hood, and unfortunately goes through some gyrations to be efficient that are causing your problem. I agree with everyone else who says to get rid of the ugly old cgi-lib style code. It's unpleasant enough to do CGI without a nice framework (go Catalyst), let alone something that's been obsolete for a decade.
89,285
<p>I've been trimming the UI of our website by doing the following in the onload event of that control:</p> <pre><code>btnDelete.isVisible = user.IsInRole("can delete"); </code></pre> <p>This has become very tedious because there are so many controls to check again and again. As soon as I get it all working, designers request to change the UI and then it starts all over.</p> <p>Any suggestions?</p>
[ { "answer_id": 89295, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 2, "selected": false, "text": "<p>One simple suggestion would be to group controls into panels based on access rights</p>\n" }, { "answer_id...
2008/09/18
[ "https://Stackoverflow.com/questions/89285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14396/" ]
I've been trimming the UI of our website by doing the following in the onload event of that control: ``` btnDelete.isVisible = user.IsInRole("can delete"); ``` This has become very tedious because there are so many controls to check again and again. As soon as I get it all working, designers request to change the UI and then it starts all over. Any suggestions?
One simple suggestion would be to group controls into panels based on access rights
89,332
<p>I frequently use <code>git stash</code> and <code>git stash pop</code> to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but <code>git stash pop</code> appears to remove all references to the associated commit.</p> <p>I know that if I use <code>git stash</code> then <em>.git/refs/stash contains</em> the reference of the commit used to create the stash. And <em>.git/logs/refs/stash contains</em> the whole stash. But those references are gone after <code>git stash pop</code>. I know that the commit is still in my repository somewhere, but I don't know what it was.</p> <p>Is there an easy way to recover yesterday's stash commit reference?</p>
[ { "answer_id": 89388, "author": "Nathan Jones", "author_id": 5848, "author_profile": "https://Stackoverflow.com/users/5848", "pm_score": 6, "selected": false, "text": "<p><code>git fsck --unreachable | grep commit</code> should show the sha1, although the list it returns might be quite l...
2008/09/18
[ "https://Stackoverflow.com/questions/89332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ]
I frequently use `git stash` and `git stash pop` to save and restore changes in my working tree. Yesterday, I had some changes in my working tree that I had stashed and popped, and then I made more changes to my working tree. I'd like to go back and review yesterday's stashed changes, but `git stash pop` appears to remove all references to the associated commit. I know that if I use `git stash` then *.git/refs/stash contains* the reference of the commit used to create the stash. And *.git/logs/refs/stash contains* the whole stash. But those references are gone after `git stash pop`. I know that the commit is still in my repository somewhere, but I don't know what it was. Is there an easy way to recover yesterday's stash commit reference?
Once you know the hash of the stash commit you dropped, you can apply it as a stash: ```bash git stash apply $stash_hash ``` Or, you can create a separate branch for it with ```bash git branch recovered $stash_hash ``` After that, you can do whatever you want with all the normal tools. When you’re done, just blow the branch away. Finding the hash ================ If you have only just popped it and the terminal is still open, you will [still have the hash value printed by `git stash pop` on screen](https://stackoverflow.com/questions/89332/recover-dropped-stash-in-git/7844566#7844566) (thanks, Dolda). Otherwise, you can find it using this for Linux, Unix or Git Bash for Windows: ```bash git fsck --no-reflog | awk '/dangling commit/ {print $3}' ``` ...or using PowerShell for Windows: ``` git fsck --no-reflog | select-string 'dangling commit' | foreach { $_.ToString().Split(" ")[2] } ``` This will show you all the commits at the tips of your commit graph which are no longer referenced from any branch or tag – every lost commit, including every stash commit you’ve ever created, will be somewhere in that graph. The easiest way to find the stash commit you want is probably to pass that list to `gitk`: ```bash gitk --all $( git fsck --no-reflog | awk '/dangling commit/ {print $3}' ) ``` ...or see [the answer from emragins](https://stackoverflow.com/questions/89332#34666995) if using PowerShell for Windows. This will launch a repository browser showing you *every single commit in the repository ever*, regardless of whether it is reachable or not. You can replace `gitk` there with something like `git log --graph --oneline --decorate` if you prefer a nice graph on the console over a separate GUI app. To spot stash commits, look for commit messages of this form:         WIP on *somebranch*: *commithash Some old commit message* *Note*: The commit message will only be in this form (starting with "WIP on") if you did not supply a message when you did `git stash`.
89,418
<p>Assume I have an "images" folder directory under the root of my application. How can I, from within a .css file, reference an image in this directory using an ASP.NET app relative path. </p> <p>Example:</p> <p>When in development, the path of <strong>~/Images/Test.gif</strong> might resolve to <strong>/MyApp/Images/Test.gif</strong> while, in production, it might resolve to <strong>/Images/Test.gif</strong> (depending on the virtual directory for the application). I, obviously, want to avoid having to modify the .css file between environments.</p> <p>I know you can use Page.ResolveClientUrl to inject a url into a control's Style collection dynamically at render time. I would like to avoid doing this.</p>
[ { "answer_id": 89431, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 3, "selected": false, "text": "<p>In case you didn't know you could do this...</p>\n\n<p>If you give a relative path to a resource in a CSS it's rela...
2008/09/18
[ "https://Stackoverflow.com/questions/89418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10834/" ]
Assume I have an "images" folder directory under the root of my application. How can I, from within a .css file, reference an image in this directory using an ASP.NET app relative path. Example: When in development, the path of **~/Images/Test.gif** might resolve to **/MyApp/Images/Test.gif** while, in production, it might resolve to **/Images/Test.gif** (depending on the virtual directory for the application). I, obviously, want to avoid having to modify the .css file between environments. I know you can use Page.ResolveClientUrl to inject a url into a control's Style collection dynamically at render time. I would like to avoid doing this.
Unfortunately Firefox has a stupid bug here... the paths are relative to the path of the page, instead of being relative to the position of the CSS file. Which means if you have pages in different positions in the tree (like having Default.aspx in the root and Information.aspx in the View folder) there's no way to have working relative paths. (IE will correctly solve the paths relative to the location of the CSS file.) The only thing I could find is this comment on <http://www.west-wind.com/weblog/posts/269.aspx> but, to be honest, I haven't managed to make it work yet. If I do I'll edit this comment: > > re: Making sense of ASP.Net Paths by > Russ Brooks February 25, 2006 @ 8:43 > am > > > No one fully answered Brant's question > about the image paths inside the CSS > file itself. I've got the answer. The > question was, "How do we use > application-relative image paths > INSIDE the CSS file?" I have long been > frustrated by this very problem too, > so I just spent the last 3 hours > working out a solution. > > > The solution is to run your CSS files > through the ASPX page handler, then > use a small bit of server-side code in > each of the paths to output the root > application path. Ready? > > > 1. Add to web.config: > > > ``` <compilation debug="true"> <!-- Run CSS files through the ASPX handler so we can write code in them. --> <buildProviders> <add extension=".css" type="System.Web.Compilation.PageBuildProvider" /> </buildProviders> </compilation> <httpHandlers> <add path="*.css" verb="GET" type="System.Web.UI.PageHandlerFactory" validate="true" /> </httpHandlers> ``` > > 2. Inside your CSS, use the Request.ApplicationPath property > wherever a path exists, like this: > > > #content { > background: url(<%= Request.ApplicationPath > %>/images/bg\_content.gif) repeat-y; > } > 3. .NET serves up ASPX pages with a MIME type of "text/html" by default, > consequently, your new server-side CSS > pages are served up with this MIME > type which causes non-IE browsers to > not read the CSS file correctly. We > need to override this to be > "text/css". Simply add this line as > the first line of your CSS file: > > > > ``` > <%@ ContentType="text/css" %> > > ``` > > >
89,441
<p>I have Visual Studio web test attached nicely to a data source, but I need to be able to iterate over each entry in the data source. How should I do this?</p>
[ { "answer_id": 89492, "author": "Ola Karlsson", "author_id": 10696, "author_profile": "https://Stackoverflow.com/users/10696", "pm_score": 2, "selected": true, "text": "<p>This <a href=\"http://www.codeguru.com/csharp/.net/net_general/visualstudionetadd-ins/article.php/c12645__2/\" rel=\...
2008/09/18
[ "https://Stackoverflow.com/questions/89441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13813/" ]
I have Visual Studio web test attached nicely to a data source, but I need to be able to iterate over each entry in the data source. How should I do this?
This [article](http://www.codeguru.com/csharp/.net/net_general/visualstudionetadd-ins/article.php/c12645__2/) seems to Discuss something quite like what you're talking about. Good luck. Ola **EDIT:** From the linked article, your DataSource is exposed to your test via an attribute. ``` [DataSource("System.Data.SqlClient", "Data Source=VSTS;Initial Catalog=ContactManagerWebTest; Integrated Security=True", "ValidContactInfo", DataAccessMethod.Sequential), TestMethod()] ``` There are several other DataSources you can link to, for example CSV, or even Parameters of a Test Case in TFS. Be sure to include the `DataAccessMethod.Sequential`. If there are multiple rows in the table indicated by the `DataSourceAttribute`, then each test run will have `TestContext.DataRow` pointing to the current row/iteration for the test.
89,465
<p>Currently, WScript pops up message box when there is a script error. These scripts are called by other processes, and are ran on a server, so there is nobody to dismiss the error box. </p> <p>What I'd like is for the error message to be dumped to STDOUT, and execution to return the calling process. Popping as a MSGBox just hangs the entire thing.</p> <p>Ideas?</p>
[ { "answer_id": 89511, "author": "X-Cubed", "author_id": 10808, "author_profile": "https://Stackoverflow.com/users/10808", "pm_score": 0, "selected": false, "text": "<p>You haven't stated what language you're using. If you're using VBScript, you can write an error handler using the <a hre...
2008/09/18
[ "https://Stackoverflow.com/questions/89465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
Currently, WScript pops up message box when there is a script error. These scripts are called by other processes, and are ran on a server, so there is nobody to dismiss the error box. What I'd like is for the error message to be dumped to STDOUT, and execution to return the calling process. Popping as a MSGBox just hangs the entire thing. Ideas?
This is how you should be running Script batch jobs: ``` cscript //b scriptname.vbs ```
89,480
<p>For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up?</p> <p>Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?</p>
[ { "answer_id": 89494, "author": "fabiopedrosa", "author_id": 2731698, "author_profile": "https://Stackoverflow.com/users/2731698", "pm_score": 1, "selected": false, "text": "<p>Take a look at .htaccess if you're using apache: <a href=\"http://httpd.apache.org/docs/1.3/howto/htaccess.html...
2008/09/18
[ "https://Stackoverflow.com/questions/89480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15947/" ]
For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up? Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?
How about an .htaccess: ``` Deny from x.x.x.x ``` if you need to deny a range say: 192.168.0.x then you would use ``` Deny from 192.168.0 ``` and the same applies for hostnames: ``` Deny from sub.domain.tld ``` or if you want a PHP solution ``` $ips = array('1.1.1.1', '2.2.2.2', '3.3.3.3'); if(in_array($_SERVER['REMOTE_ADDR'])){die();} ``` For more info on the htaccess method see [this](http://httpd.apache.org/docs/1.3/mod/mod_access.html) page. Now to determine the range is going to be hard, most companies (unless they are big corperate) are going to have a dynamic IP just like you and me. This is a problem I have had to deal with before and the best thing is either to ban the hostname, or the entire range, for example if they are on 192.168.0.123 then ban 192.168.0.123, unfortunatly you are going to get a few innocent people with either method.
89,488
<p>I've been trying to implement a C#-like event system in C++ with the tr1 function templates used to store a function that handles the event. </p> <p>I created a vector so that multiple listeners can be attached to this event, i.e.:</p> <pre><code>vector&lt; function&lt;void (int)&gt; &gt; listenerList; </code></pre> <p>I'd like to be able to remove a handler from the list to stop a listener receiving events.</p> <p>So, how can I find the entry in this list that corresponds to a given listener? Can I test if a 'function' object in the list refers to a particular function?</p> <p>Thanks!</p> <p>EDIT: Having looked into the boost::signal approach, it seems it's probably implemented using a token system as some of you have suggested. <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/signals/tutorial.html" rel="nofollow noreferrer">Here's some info on this</a>. An observer retains a "Connection" object when they attach to an event, and this connection object is used to disconnect if needed. So it looks like whether you use Boost or roll your own with tr1, the basic principle's the same. i.e. it will be a bit clumsy :) </p>
[ { "answer_id": 89542, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/function/faq.html\" rel=\"nofollow noreferrer\">FAQ #1</a>...
2008/09/18
[ "https://Stackoverflow.com/questions/89488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17136/" ]
I've been trying to implement a C#-like event system in C++ with the tr1 function templates used to store a function that handles the event. I created a vector so that multiple listeners can be attached to this event, i.e.: ``` vector< function<void (int)> > listenerList; ``` I'd like to be able to remove a handler from the list to stop a listener receiving events. So, how can I find the entry in this list that corresponds to a given listener? Can I test if a 'function' object in the list refers to a particular function? Thanks! EDIT: Having looked into the boost::signal approach, it seems it's probably implemented using a token system as some of you have suggested. [Here's some info on this](http://www.boost.org/doc/libs/1_36_0/doc/html/signals/tutorial.html). An observer retains a "Connection" object when they attach to an event, and this connection object is used to disconnect if needed. So it looks like whether you use Boost or roll your own with tr1, the basic principle's the same. i.e. it will be a bit clumsy :)
I don't know if you're locked into std C++ and tr1, but if you aren't, it seems like your problem could be completely avoided if you just used something like boost::signal and boost::bind to solve your original problem - creating an event system - instead of trying to roll your own.
89,504
<p>I've got a standard Rails app with Nginx and Mongrel running at <a href="http://mydomain" rel="noreferrer">http://mydomain</a>. I need to run a Wordpress blog at <a href="http://mydomain.com/blog" rel="noreferrer">http://mydomain.com/blog</a>. My preference would be to host the blog in Apache running on either the same server or a separate box but I don't want the user to see a different server in the URL. Is that possible and if not, what would you recommend to accomplish the goal?</p>
[ { "answer_id": 89512, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 0, "selected": false, "text": "<p>Seems to me that something like a rewrite manipulator would do what you want. Sorry I don't have anymore details -- just t...
2008/09/18
[ "https://Stackoverflow.com/questions/89504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14619/" ]
I've got a standard Rails app with Nginx and Mongrel running at <http://mydomain>. I need to run a Wordpress blog at <http://mydomain.com/blog>. My preference would be to host the blog in Apache running on either the same server or a separate box but I don't want the user to see a different server in the URL. Is that possible and if not, what would you recommend to accomplish the goal?
I think joelhardi's solution is superior to the following. However, in my own application, I like to keep the blog on a separate VPS than the Rails site (separation of memory issues). To make the user see the same URL, you use the same proxy trick that you normally use for proxying to a mongrel cluster, except you proxy to port 80 (or whatever) on another box. Easy peasy. To the user it is as transparent as you proxying to mongrel -- they only "see" the NGINX responding on port 80 at your domain. ``` upstream myBlogVPS { server 127.0.0.2:80; #fix me to point to your blog VPS } server { listen 80; #You'll have plenty of things for Rails compatibility here #Make sure you don't accidentally step on this with the Rails config! location /blog { proxy_pass http://myBlogVPS; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } ``` You can use this trick to have Rails play along with ANY server technology you want, incidentally. Proxy directly to the appropriate server/port, and NGINX will hide it from the outside world. Additionally, since the URLs will all refer to the same domain, you can seemlessly integrate a PHP-based blog, Python based tracking system, and Rails app -- as long as you write your URLs correctly.
89,543
<p>I want to set something up so that if an Account within my app is disabled, I want all requests to be redirected to a "disabled" message.</p> <p>I've set this up in my ApplicationController:</p> <pre><code>class ApplicationController &lt; ActionController::Base before_filter :check_account def check_account redirect_to :controller =&gt; "main", :action =&gt; "disabled" and return if !$account.active? end end </code></pre> <p>Of course, this doesn't quite work as it goes into an infinite loop if the Account is not active. I was hoping to use something like:</p> <pre><code>redirect_to :controller =&gt; "main", :action =&gt; "disabled" and return if !$account.active? &amp;&amp; @controller.controller_name != "main" &amp;&amp; @controller.action_name != "disabled" </code></pre> <p>but I noticed that in Rails v2.1 (what I'm using), @controller is now controller and this doesn't seem to work in ApplicationController.</p> <p>What would be the best way to implement something like this?</p>
[ { "answer_id": 89637, "author": "flukus", "author_id": 407256, "author_profile": "https://Stackoverflow.com/users/407256", "pm_score": 0, "selected": false, "text": "<p>If theres not too many overrides then just put the if in the redirect filter</p>\n\n<p>if action != disabled\n redirec...
2008/09/18
[ "https://Stackoverflow.com/questions/89543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14530/" ]
I want to set something up so that if an Account within my app is disabled, I want all requests to be redirected to a "disabled" message. I've set this up in my ApplicationController: ``` class ApplicationController < ActionController::Base before_filter :check_account def check_account redirect_to :controller => "main", :action => "disabled" and return if !$account.active? end end ``` Of course, this doesn't quite work as it goes into an infinite loop if the Account is not active. I was hoping to use something like: ``` redirect_to :controller => "main", :action => "disabled" and return if !$account.active? && @controller.controller_name != "main" && @controller.action_name != "disabled" ``` but I noticed that in Rails v2.1 (what I'm using), @controller is now controller and this doesn't seem to work in ApplicationController. What would be the best way to implement something like this?
You could also use a `skip_before_filter` for the one controller/method you don't want to have the filter apply to.
89,588
<p>You do <code>AssignProcessToJobObject</code> and it fails with "access denied" but only when you are running in the debugger. Why is this?</p>
[ { "answer_id": 89589, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 6, "selected": true, "text": "<p>This one puzzled me for for about 30 minutes.</p>\n\n<p>First off, you probably need a UAC manifest embedded in yo...
2008/09/18
[ "https://Stackoverflow.com/questions/89588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
You do `AssignProcessToJobObject` and it fails with "access denied" but only when you are running in the debugger. Why is this?
This one puzzled me for for about 30 minutes. First off, you probably need a UAC manifest embedded in your app ([as suggested here](https://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows#53214)). Something like this: ``` <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0"> <!-- Identify the application security requirements. --> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"> <security> <requestedPrivileges> <requestedExecutionLevel level="asInvoker" uiAccess="false"/> </requestedPrivileges> </security> </trustInfo> </assembly> ``` Secondly (and this is the bit I got stuck on), when you are running your app under the debugger, it creates your process in a job object. Which your child process needs to be able to breakaway from before you can assign it to your job. So (duh), you need to specify `CREATE_BREAKAWAY_FROM_JOB` in the flags for `CreateProcess`). If you weren't running under the debugger, or your parent process were in the job, this wouldn't have happened.
89,607
<p>I have added some code which compiles cleanly and have just received this Windows error:</p> <pre><code>--------------------------- (MonTel Administrator) 2.12.7: MtAdmin.exe - Application Error --------------------------- The exception Privileged instruction. (0xc0000096) occurred in the application at location 0x00486752. </code></pre> <p>I am about to go on a bug hunt, and I am expecting it to be something silly that I have done which just happens to produce this message. The code compiles cleanly with no errors or warnings. The size of the EXE file has grown to 1,454,132 bytes and includes links to <code>ODCS.lib</code>, but it is otherwise pure C to the Win32 API, with DEBUG on (running on a P4 on Windows&nbsp;2000).</p>
[ { "answer_id": 89643, "author": "Tim Williscroft", "author_id": 2789, "author_profile": "https://Stackoverflow.com/users/2789", "pm_score": 2, "selected": false, "text": "<p>I saw this with Visual c++ 6.0 in the year 2000.</p>\n\n<p>The debug C++ library had calls to physical I/O instruc...
2008/09/18
[ "https://Stackoverflow.com/questions/89607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3137/" ]
I have added some code which compiles cleanly and have just received this Windows error: ``` --------------------------- (MonTel Administrator) 2.12.7: MtAdmin.exe - Application Error --------------------------- The exception Privileged instruction. (0xc0000096) occurred in the application at location 0x00486752. ``` I am about to go on a bug hunt, and I am expecting it to be something silly that I have done which just happens to produce this message. The code compiles cleanly with no errors or warnings. The size of the EXE file has grown to 1,454,132 bytes and includes links to `ODCS.lib`, but it is otherwise pure C to the Win32 API, with DEBUG on (running on a P4 on Windows 2000).
To answer the question, a privileged instruction is a processor op-code (assembler instruction) which can only be executed in "supervisor" (or Ring-0) mode. These types of instructions tend to be used to access I/O devices and protected data structures from the windows kernel. Regular programs execute in "user mode" (Ring-3) which disallows direct access to I/O devices, etc... As others mentioned, the cause is probably a corrupted stack or a messed up function pointer call.
89,609
<p>I'm looking for the best way to take a simple input:</p> <pre><code>echo -n "Enter a string here: " read -e STRING </code></pre> <p>and clean it up by removing non-alphanumeric characters, lower(case), and replacing spaces with underscores.</p> <p>Does order matter? Is <code>tr</code> the best / only way to go about this?</p>
[ { "answer_id": 89642, "author": "Devin Reams", "author_id": 16248, "author_profile": "https://Stackoverflow.com/users/16248", "pm_score": 0, "selected": false, "text": "<p>After a bit of looking around it seems <code>tr</code> is indeed the simplest way:</p>\n\n<pre><code>export CLEANSTR...
2008/09/18
[ "https://Stackoverflow.com/questions/89609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16248/" ]
I'm looking for the best way to take a simple input: ``` echo -n "Enter a string here: " read -e STRING ``` and clean it up by removing non-alphanumeric characters, lower(case), and replacing spaces with underscores. Does order matter? Is `tr` the best / only way to go about this?
As dj\_segfault points out, the shell can do most of this for you. Looks like you'll have to fall back on something external for lower-casing the string, though. For this you have many options, like the perl one-liners above, etc., but I think tr is probably the simplest. ``` # first, strip underscores CLEAN=${STRING//_/} # next, replace spaces with underscores CLEAN=${CLEAN// /_} # now, clean out anything that's not alphanumeric or an underscore CLEAN=${CLEAN//[^a-zA-Z0-9_]/} # finally, lowercase with TR CLEAN=`echo -n $CLEAN | tr A-Z a-z` ``` The order here is somewhat important. We want to get rid of underscores, plus replace spaces with underscores, so we have to be sure to strip underscores first. By waiting to pass things to tr until the end, we know we have only alphanumeric and underscores, and we can be sure we have no spaces, so we don't have to worry about special characters being interpreted by the shell.
89,650
<p>I would like to pass an argument(s) to a method being defined using define_method, how would I do that?</p>
[ { "answer_id": 89661, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 9, "selected": true, "text": "<p>The block that you pass to define_method can include some parameters. That's how your defined method accepts arguments. ...
2008/09/18
[ "https://Stackoverflow.com/questions/89650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1681/" ]
I would like to pass an argument(s) to a method being defined using define\_method, how would I do that?
The block that you pass to define\_method can include some parameters. That's how your defined method accepts arguments. When you define a method you're really just nicknaming the block and keeping a reference to it in the class. The parameters come with the block. So: ``` define_method(:say_hi) { |other| puts "Hi, " + other } ```
89,705
<p>I'm going through the problems on projecteuler.net to learn how to program in Erlang, and I am having the hardest time creating a prime generator that can create all of the primes below 2 million, in less than a minute. Using the sequential style, I have already written three types of generators, including the Sieve of Eratosthenes, and none of them perform well enough.</p> <p>I figured a concurrent Sieve would work great, but I'm getting bad_arity messages, and I'm not sure why. Any suggestions on why I have the problem, or how to code it properly? </p> <p>Here's my code, the commented out sections are where I tried to make things concurrent:</p> <pre> -module(primeserver). -compile(export_all). start() -> register(primes, spawn(fun() -> loop() end)). is_prime(N) -> rpc({is_prime,N}). rpc(Request) -> primes ! {self(), Request}, receive {primes, Response} -> Response end. loop() -> receive {From, {is_prime, N}} -> if N From ! {primes, false}; N =:= 2 -> From ! {primes, true}; N rem 2 =:= 0 -> From ! {primes, false}; true -> Values = is_not_prime(N), Val = not(lists:member(true, Values)), From ! {primes, Val} end, loop() end. for(N,N,_,F) -> [F(N)]; for(I,N,S,F) when I + S [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S =:= N -> [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S > N -> [F(I)]. get_list(I, Limit) -> if I [I*A || A [] end. is_not_prime(N) -> for(3, N, 2, fun(I) -> List = get_list(I,trunc(N/I)), lists:member(N,lists:flatten(List)) end ). %%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end), %%SeedList = [A || A %% lists:foreach(fun(X) -> %% Pid ! {in_list, X} %% end, SeedList) %% end, L). %%wait(I,N) -> %% List = [I*A || A lists:member(X,List) %% end. </pre>
[ { "answer_id": 89726, "author": "theo", "author_id": 7870, "author_profile": "https://Stackoverflow.com/users/7870", "pm_score": -1, "selected": false, "text": "<p>I love Project Euler.</p>\n\n<p>On the subject of prime generators, I am a big fan of the Sieve of Eratosthenes.</p>\n\n<p>F...
2008/09/18
[ "https://Stackoverflow.com/questions/89705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8040/" ]
I'm going through the problems on projecteuler.net to learn how to program in Erlang, and I am having the hardest time creating a prime generator that can create all of the primes below 2 million, in less than a minute. Using the sequential style, I have already written three types of generators, including the Sieve of Eratosthenes, and none of them perform well enough. I figured a concurrent Sieve would work great, but I'm getting bad\_arity messages, and I'm not sure why. Any suggestions on why I have the problem, or how to code it properly? Here's my code, the commented out sections are where I tried to make things concurrent: ``` -module(primeserver). -compile(export_all). start() -> register(primes, spawn(fun() -> loop() end)). is_prime(N) -> rpc({is_prime,N}). rpc(Request) -> primes ! {self(), Request}, receive {primes, Response} -> Response end. loop() -> receive {From, {is_prime, N}} -> if N From ! {primes, false}; N =:= 2 -> From ! {primes, true}; N rem 2 =:= 0 -> From ! {primes, false}; true -> Values = is_not_prime(N), Val = not(lists:member(true, Values)), From ! {primes, Val} end, loop() end. for(N,N,_,F) -> [F(N)]; for(I,N,S,F) when I + S [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S =:= N -> [F(I)|for(I+S, N, S, F)]; for(I,N,S,F) when I + S > N -> [F(I)]. get_list(I, Limit) -> if I [I*A || A [] end. is_not_prime(N) -> for(3, N, 2, fun(I) -> List = get_list(I,trunc(N/I)), lists:member(N,lists:flatten(List)) end ). %%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end), %%SeedList = [A || A %% lists:foreach(fun(X) -> %% Pid ! {in_list, X} %% end, SeedList) %% end, L). %%wait(I,N) -> %% List = [I*A || A lists:member(X,List) %% end. ```
The 'badarity' error means that you're trying to call a 'fun' with the wrong number of arguments. In this case... %%L = for(1,N, fun() -> spawn(fun(I) -> wait(I,N) end) end), The for/3 function expects a fun of arity 1, and the spawn/1 function expects a fun of arity 0. Try this instead: ``` L = for(1, N, fun(I) -> spawn(fun() -> wait(I, N) end) end), ``` The fun passed to spawn inherits needed parts of its environment (namely I), so there's no need to pass it explicitly. While calculating primes is always good fun, please keep in mind that this is not the kind of problem Erlang was designed to solve. Erlang was designed for massive actor-style concurrency. It will most likely perform rather badly on all examples of data-parallel computation. In many cases, [a sequential solution in, say, ML](http://home.mindspring.com/~eric_rollins/erlangAnt.html) will be so fast that any number of cores will not suffice for Erlang to catch up, and e.g. [F# and the .NET Task Parallel Library](http://undirectedgrad.blogspot.com/2007/12/f-and-task-parallel-library.html) would certainly be a much better vehicle for these kinds of operations.
89,708
<p>I am trying to extract a gif image embedded as a resource within my ISAPI dll using WebBroker technology. The resource has been added to the DLL using the following RC code:</p> <pre><code>LOGO_GIF RCDATA logo.gif </code></pre> <p>Using resource explorer I verified it is in the DLL properly.</p> <p>using the following code always throws an exception, "resource not found" (using Delphi 2009)</p> <pre><code>var rc : tResourceStream; begin rc := tResourceStream.Create(hInstance,'LOGO_GIF','RCDATA'); end; </code></pre>
[ { "answer_id": 90236, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 1, "selected": false, "text": "<p>If I remember correctly you are actually dealing with an instance of the web server, not the dll. I don't remember the ...
2008/09/18
[ "https://Stackoverflow.com/questions/89708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9217/" ]
I am trying to extract a gif image embedded as a resource within my ISAPI dll using WebBroker technology. The resource has been added to the DLL using the following RC code: ``` LOGO_GIF RCDATA logo.gif ``` Using resource explorer I verified it is in the DLL properly. using the following code always throws an exception, "resource not found" (using Delphi 2009) ``` var rc : tResourceStream; begin rc := tResourceStream.Create(hInstance,'LOGO_GIF','RCDATA'); end; ```
RCDATA is a [pre-defined](http://msdn.microsoft.com/en-us/library/aa381039(VS.85).aspx) resource type with an integer ID of RT\_RCDATA (declared in Types unit). Try accessing it this way: ``` rc := tResourceStream.Create(hInstance,'LOGO_GIF', MakeIntResource(RT_RCDATA)); ```
89,745
<p>I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file.</p>
[ { "answer_id": 89763, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I'm not sure that can be found in <code>/proc</code>. You could try using the <code>getuid()</code> function or the <c...
2008/09/18
[ "https://Stackoverflow.com/questions/89745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17162/" ]
I am trying to find the virtual file that contains the current users id. I was told that I could find it in the proc directory, but not quite sure which file.
You actually want `/proc/self/status`, which will give you information about the currently executed process. Here is an example: ``` $ cat /proc/self/status Name: cat State: R (running) Tgid: 17618 Pid: 17618 PPid: 3083 TracerPid: 0 Uid: 500 500 500 500 Gid: 500 500 500 500 FDSize: 32 Groups: 10 488 500 VmPeak: 4792 kB VmSize: 4792 kB VmLck: 0 kB VmHWM: 432 kB VmRSS: 432 kB VmData: 156 kB VmStk: 84 kB VmExe: 32 kB VmLib: 1532 kB VmPTE: 24 kB Threads: 1 SigQ: 0/32268 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: 0000000000000000 SigCgt: 0000000000000000 CapInh: 0000000000000000 CapPrm: 0000000000000000 CapEff: 0000000000000000 Cpus_allowed: 00000003 Mems_allowed: 1 voluntary_ctxt_switches: 0 nonvoluntary_ctxt_switches: 3 ``` You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at `/etc/passwd`, or calling the relevant functions for mapping uid to username in whatever language you're using. Ideally, you would just call the system call `getuid()` to look up this information, doing it by looking at `/proc/` is counterproductive.
89,752
<p>How can I get <strong>hierarchy recordset</strong> in ms access through <strong>select</strong> statement?</p>
[ { "answer_id": 89763, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 2, "selected": false, "text": "<p>I'm not sure that can be found in <code>/proc</code>. You could try using the <code>getuid()</code> function or the <c...
2008/09/18
[ "https://Stackoverflow.com/questions/89752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I get **hierarchy recordset** in ms access through **select** statement?
You actually want `/proc/self/status`, which will give you information about the currently executed process. Here is an example: ``` $ cat /proc/self/status Name: cat State: R (running) Tgid: 17618 Pid: 17618 PPid: 3083 TracerPid: 0 Uid: 500 500 500 500 Gid: 500 500 500 500 FDSize: 32 Groups: 10 488 500 VmPeak: 4792 kB VmSize: 4792 kB VmLck: 0 kB VmHWM: 432 kB VmRSS: 432 kB VmData: 156 kB VmStk: 84 kB VmExe: 32 kB VmLib: 1532 kB VmPTE: 24 kB Threads: 1 SigQ: 0/32268 SigPnd: 0000000000000000 ShdPnd: 0000000000000000 SigBlk: 0000000000000000 SigIgn: 0000000000000000 SigCgt: 0000000000000000 CapInh: 0000000000000000 CapPrm: 0000000000000000 CapEff: 0000000000000000 Cpus_allowed: 00000003 Mems_allowed: 1 voluntary_ctxt_switches: 0 nonvoluntary_ctxt_switches: 3 ``` You probably want to look at the first numbers on the Uid and Gid lines. You can look up which uid numbers map to what username by looking at `/etc/passwd`, or calling the relevant functions for mapping uid to username in whatever language you're using. Ideally, you would just call the system call `getuid()` to look up this information, doing it by looking at `/proc/` is counterproductive.
89,791
<p>When I start my process from Visual Studio, it is always created inside a job object. I would like to know how to turn this behaviour off. Any ideas?</p> <p>I expect that it is created in a job object to be debugged. I want to place my program in a different job object.</p> <p>It's not the hosting process. I'm talking about a <a href="http://msdn.microsoft.com/en-us/library/ms684161(VS.85).aspx" rel="noreferrer">Job Object</a>. This is an unmanaged C++ application.</p>
[ { "answer_id": 93065, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "<p>I'm not aware of any ways to control this aspect of processes spawned for debugging by VS.NET. But there's a workaround, which...
2008/09/18
[ "https://Stackoverflow.com/questions/89791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
When I start my process from Visual Studio, it is always created inside a job object. I would like to know how to turn this behaviour off. Any ideas? I expect that it is created in a job object to be debugged. I want to place my program in a different job object. It's not the hosting process. I'm talking about a [Job Object](http://msdn.microsoft.com/en-us/library/ms684161(VS.85).aspx). This is an unmanaged C++ application.
This happens when `devenv.exe` or `VSLauncher.exe` run in compatibility mode. The [Program Compatibility Assistant](http://msdn.microsoft.com/en-us/library/bb756937.aspx) (PCA) attaches a job object to the Visual Studio process, and every child process inherits it. Check if the job name (as reported by Process Explorer) starts with **PCA**. If so, PCA can be disabled as described in the link. You can globally disable PCA using `Run` -> `gpedit.msc` -> `Administrative Templates\Windows Components\Application Compatibility` -> `Turn off Program Compatibility Assistant` -> `Enable`. You can disable PCA for specific executables by adding a registry entry. For Windows 7, the appropriate registry key is `HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Compatibility Assistant`. In regedit, right-click that key, select `New` -> `Multi-String Value`, name it `ExecutablesToExclude`. Set the value to the full path of `denenv.exe` and `VSLauncher.exe`, on separate lines and without quotes. For me, these were: ``` C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe C:\Program Files (x86)\Common Files\microsoft shared\MSEnv\VSLauncher.exe ``` A related issue, on Windows 7, is that executables you build in Visual Studio and run from Explorer (not Visual Studio or the command line) may run in compatibility mode, and again get job objects wrapped around them. To prevent this, your executable needs a manifest that declares compatibility with Windows 7, using the new [Application Manifest Compability section](http://msdn.microsoft.com/en-us/library/dd371711(VS.85).aspx). The link gives an example of a Windows 7 compatible manifest. The default manifest provided by Visual Studio 2010 does not include this Compatibility section.
89,820
<p>I am using mssql and am having trouble using a subquery. The real query is quite complicated, but it has the same structure as this:</p> <pre><code>select customerName, customerId, ( select count(*) from Purchases where Purchases.customerId=customerData.customerId ) as numberTransactions from customerData </code></pre> <p>And what I want to do is order the table by the number of transactions, but when I use</p> <pre><code>order by numberTransactions </code></pre> <p>It tells me there is no such field. Is it possible to do this? Should I be using some sort of special keyword, such as <code>this</code>, or <code>self</code>?</p>
[ { "answer_id": 89831, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 4, "selected": true, "text": "<p>use the field number, in this case:</p>\n\n<pre><code>order by 3\n</code></pre>\n" }, { "answer_id": 89834,...
2008/09/18
[ "https://Stackoverflow.com/questions/89820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6062/" ]
I am using mssql and am having trouble using a subquery. The real query is quite complicated, but it has the same structure as this: ``` select customerName, customerId, ( select count(*) from Purchases where Purchases.customerId=customerData.customerId ) as numberTransactions from customerData ``` And what I want to do is order the table by the number of transactions, but when I use ``` order by numberTransactions ``` It tells me there is no such field. Is it possible to do this? Should I be using some sort of special keyword, such as `this`, or `self`?
use the field number, in this case: ``` order by 3 ```
89,866
<p>We are creating a Real-Time Process in VxWorks 6.x, and we would like to limit the amount of memory which can be allocated to the heap. How do we do this?</p>
[ { "answer_id": 89911, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 3, "selected": true, "text": "<p>When creating a RTP via rtpSpawn(), you can specify an environment variable which controls how the heap behaves.<br>\nTher...
2008/09/18
[ "https://Stackoverflow.com/questions/89866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10703/" ]
We are creating a Real-Time Process in VxWorks 6.x, and we would like to limit the amount of memory which can be allocated to the heap. How do we do this?
When creating a RTP via rtpSpawn(), you can specify an environment variable which controls how the heap behaves. There are 3 environment variables: ``` HEAP_INITIAL_SIZE - How much heap to allocate initially (defaults to 64K) HEAP_MAX_SIZE - Maximum heap to allocate (defaults to no limit) HEAP_INCR_SIZE - memory increment when adding to RTP heap (defaults to 1 virtual page) The following code shows how to use the environment variables: char * envp[] = {"HEAP_INITIAL_SIZE=0x20000", "HEAP_MAX_SIZE=0x100000", NULL); rtpSpawn ("myrtp.vxe", NULL, envp, 100, 0x10000, 0, 0); ```
89,873
<p>Is it possible to manipulate the components, such as <code>year</code>, <code>month</code>, <code>day</code> of a <code>date</code> in VBA? I would like a function that, given a day, a month, and a year, returns the corresponding date.</p>
[ { "answer_id": 89892, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 2, "selected": false, "text": "<p>There are several date functions in VBA - check this <a href=\"http://www.classanytime.com/mis333k/sjdatetime.html\" rel=...
2008/09/18
[ "https://Stackoverflow.com/questions/89873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
Is it possible to manipulate the components, such as `year`, `month`, `day` of a `date` in VBA? I would like a function that, given a day, a month, and a year, returns the corresponding date.
``` DateSerial(YEAR, MONTH, DAY) ``` would be what you are looking for. `DateSerial(2008, 8, 19)` returns `8/19/2008`
89,897
<p>Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the <strong>inverse</strong> of this:</p> <pre><code>foreach(ISomethingable somethingableClass in collectionOfRelatedObjects) { somethingableClass.DoSomething(); } </code></pre> <p>i.e. How to get/iterate through all the objects that <em>don't</em> implement a particular interface?</p> <p>Presumably you'd need to start by upcasting to the highest level:</p> <pre><code>foreach(ParentType parentType in collectionOfRelatedObjects) { // TODO: iterate through everything which *doesn't* implement ISomethingable } </code></pre> <p>Answer by solving the TODO: in the cleanest/simplest and/or most efficient way</p>
[ { "answer_id": 89933, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 3, "selected": false, "text": "<p>Something like this?</p>\n\n<pre><code>foreach (ParentType parentType in collectionOfRelatedObjects) {\n if (!(par...
2008/09/18
[ "https://Stackoverflow.com/questions/89897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12726/" ]
Maybe the need to do this is a 'design smell' but thinking about another question, I was wondering what the cleanest way to implement the **inverse** of this: ``` foreach(ISomethingable somethingableClass in collectionOfRelatedObjects) { somethingableClass.DoSomething(); } ``` i.e. How to get/iterate through all the objects that *don't* implement a particular interface? Presumably you'd need to start by upcasting to the highest level: ``` foreach(ParentType parentType in collectionOfRelatedObjects) { // TODO: iterate through everything which *doesn't* implement ISomethingable } ``` Answer by solving the TODO: in the cleanest/simplest and/or most efficient way
this should do the trick: ``` collectionOfRelatedObjects.Where(o => !(o is ISomethingable)) ```
89,908
<p>I have three models:</p> <pre><code>class ReleaseItem &lt; ActiveRecord::Base has_many :pack_release_items has_one :pack, :through =&gt; :pack_release_items end class Pack &lt; ActiveRecord::Base has_many :pack_release_items has_many :release_items, :through=&gt;:pack_release_items end class PackReleaseItem &lt; ActiveRecord::Base belongs_to :pack belongs_to :release_item end </code></pre> <p>The problem is that, during execution, if I add a pack to a release_item it is not aware that the pack is a pack. For instance:</p> <pre><code>Loading development environment (Rails 2.1.0) &gt;&gt; item = ReleaseItem.new(:filename=&gt;'MAESTRO.TXT') =&gt; #&lt;ReleaseItem id: nil, filename: "MAESTRO.TXT", created_by: nil, title: nil, sauce_author: nil, sauce_group: nil, sauce_comment: nil, filedate: nil, filesize: nil, created_at: nil, updated_at: nil, content: nil&gt; &gt;&gt; pack = Pack.new(:filename=&gt;'legion01.zip', :year=&gt;1998) =&gt; #&lt;Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil&gt; &gt;&gt; item.pack = pack =&gt; #&lt;Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil&gt; &gt;&gt; item.pack.filename NoMethodError: undefined method `filename' for #&lt;Class:0x2196318&gt; from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1667:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1852:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:281:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from (irb):5 &gt;&gt; </code></pre> <p>It seems that I should have access to item.pack, but it is unaware that the pack is a Pack item.</p>
[ { "answer_id": 90003, "author": "Misplaced", "author_id": 13710, "author_profile": "https://Stackoverflow.com/users/13710", "pm_score": 4, "selected": true, "text": "<p>It appears that your usage of has_one :through is correct. The problem you're seeing has to do with saving objects. F...
2008/09/18
[ "https://Stackoverflow.com/questions/89908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13179/" ]
I have three models: ``` class ReleaseItem < ActiveRecord::Base has_many :pack_release_items has_one :pack, :through => :pack_release_items end class Pack < ActiveRecord::Base has_many :pack_release_items has_many :release_items, :through=>:pack_release_items end class PackReleaseItem < ActiveRecord::Base belongs_to :pack belongs_to :release_item end ``` The problem is that, during execution, if I add a pack to a release\_item it is not aware that the pack is a pack. For instance: ``` Loading development environment (Rails 2.1.0) >> item = ReleaseItem.new(:filename=>'MAESTRO.TXT') => #<ReleaseItem id: nil, filename: "MAESTRO.TXT", created_by: nil, title: nil, sauce_author: nil, sauce_group: nil, sauce_comment: nil, filedate: nil, filesize: nil, created_at: nil, updated_at: nil, content: nil> >> pack = Pack.new(:filename=>'legion01.zip', :year=>1998) => #<Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil> >> item.pack = pack => #<Pack id: nil, filename: "legion01.zip", created_by: nil, filesize: nil, items: nil, year: 1998, month: nil, filedate: nil, created_at: nil, updated_at: nil> >> item.pack.filename NoMethodError: undefined method `filename' for #<Class:0x2196318> from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1667:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:285:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1852:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `send' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_proxy.rb:168:in `with_scope' from /usr/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/associations/association_collection.rb:281:in `method_missing_without_paginate' from /usr/local/lib/ruby/gems/1.8/gems/mislav-will_paginate-2.3.3/lib/will_paginate/finder.rb:164:in `method_missing' from (irb):5 >> ``` It seems that I should have access to item.pack, but it is unaware that the pack is a Pack item.
It appears that your usage of has\_one :through is correct. The problem you're seeing has to do with saving objects. For an association to work, the object that is being referenced needs to have an id to populate the `model_id` field for the object. In this case, `PackReleaseItems` have a `pack_id` and a `release_item_id` field that need to be filled for the association to work correctly. Try saving before accessing objects through an association.
89,909
<p>I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.</p>
[ { "answer_id": 89915, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": -1, "selected": false, "text": "<p>use a regex and see if it matches!</p>\n\n<pre><code>([a-z][A-Z][0-9]\\_\\-)*\n</code></pre>\n" }, { "answer_id...
2008/09/18
[ "https://Stackoverflow.com/questions/89909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4527/" ]
I know how to do this if I iterate through all of the characters in the string but I am looking for a more elegant method.
A regular expression will do the trick with very little code: ``` import re ... if re.match("^[A-Za-z0-9_-]*$", my_little_string): # do something here ```
89,987
<p>My DataView is acting funny and it is sorting things alphabetically and I need it to sort things numerically. I have looked all across the web for this one and found many ideas on how to sort it with ICompare, but nothing really solid.</p> <p>So my questions are </p> <ol> <li>How do I implement ICompare on a DataView (Looking for code here).</li> <li>How to correctly decipher from a column full of strings that are actual strings and a column full of numbers(with commas).</li> </ol> <p>I need code to help me out with this one guys. I am more or less lost on the idea of ICompare and how to implement in different scenarios so an over all good explanation would be great.</p> <p>Also, Please don't hand me links. I am looking for solid answers on this one.</p> <p>Some Code that I use.</p> <pre><code> DataView dataView = (DataView)Session["kingdomData"]; dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); gvAllData.DataSource = dataView; gvAllData.DataBind(); private string ConvertSortDirectionToSql(SortDirection sortDirection) { string newSortDirection = String.Empty; if (Session["SortDirection"] == null) { switch (sortDirection) { case SortDirection.Ascending: newSortDirection = "ASC"; break; case SortDirection.Descending: newSortDirection = "DESC"; break; } } else { newSortDirection = Session["SortDirection"].ToString(); switch (newSortDirection) { case "ASC": newSortDirection = "DESC"; break; case "DESC": newSortDirection = "ASC"; break; } } Session["SortDirection"] = newSortDirection; return newSortDirection; } </code></pre> <hr> <p>For the scenario, I build a datatable dynamically and shove it into a dataview where I put the dataview into a gridview while also remembering to put the dataview into a session object for sorting capabilities.</p> <p>When the user calls on the gridview to sort a column, I recall the dataview in the session object and build the dataview sorting expression like this:</p> <pre><code>dataview.sort = e.sortexpression + " " + e.Sortdirection; </code></pre> <p>Or something along those lines. So what ussually comes out is right for all real strings such as </p> <p>Car; Home; scott; zach etc...</p> <p>But when I do the same for number fields WITH comma seperated values it comes out something like</p> <p>900; 800; 700; 600; 200; 120; 1,200; 12,340; 1,000,000;</p> <p>See what I mean? It just sorts the items as an alpha sort instead of a Natural sort. I want to make my Dataview NATURALLY sort the numeric columns correctly like</p> <p>120; 200; 600; 700; 800; 900; 1,200; 12,340; 1,000,000;</p> <p>Let me know what you can do to help me out.<br> P.S. I have looked through countless articles on how to do this and all of them say to shove into a List/Array and do it that way, but is there a much more efficient way?</p>
[ { "answer_id": 90498, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 2, "selected": false, "text": "<p>For the first issue - IIRC you can't sort a DataView with a comparer. If you just need to sort numerically a field you mu...
2008/09/18
[ "https://Stackoverflow.com/questions/89987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7644/" ]
My DataView is acting funny and it is sorting things alphabetically and I need it to sort things numerically. I have looked all across the web for this one and found many ideas on how to sort it with ICompare, but nothing really solid. So my questions are 1. How do I implement ICompare on a DataView (Looking for code here). 2. How to correctly decipher from a column full of strings that are actual strings and a column full of numbers(with commas). I need code to help me out with this one guys. I am more or less lost on the idea of ICompare and how to implement in different scenarios so an over all good explanation would be great. Also, Please don't hand me links. I am looking for solid answers on this one. Some Code that I use. ``` DataView dataView = (DataView)Session["kingdomData"]; dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection); gvAllData.DataSource = dataView; gvAllData.DataBind(); private string ConvertSortDirectionToSql(SortDirection sortDirection) { string newSortDirection = String.Empty; if (Session["SortDirection"] == null) { switch (sortDirection) { case SortDirection.Ascending: newSortDirection = "ASC"; break; case SortDirection.Descending: newSortDirection = "DESC"; break; } } else { newSortDirection = Session["SortDirection"].ToString(); switch (newSortDirection) { case "ASC": newSortDirection = "DESC"; break; case "DESC": newSortDirection = "ASC"; break; } } Session["SortDirection"] = newSortDirection; return newSortDirection; } ``` --- For the scenario, I build a datatable dynamically and shove it into a dataview where I put the dataview into a gridview while also remembering to put the dataview into a session object for sorting capabilities. When the user calls on the gridview to sort a column, I recall the dataview in the session object and build the dataview sorting expression like this: ``` dataview.sort = e.sortexpression + " " + e.Sortdirection; ``` Or something along those lines. So what ussually comes out is right for all real strings such as Car; Home; scott; zach etc... But when I do the same for number fields WITH comma seperated values it comes out something like 900; 800; 700; 600; 200; 120; 1,200; 12,340; 1,000,000; See what I mean? It just sorts the items as an alpha sort instead of a Natural sort. I want to make my Dataview NATURALLY sort the numeric columns correctly like 120; 200; 600; 700; 800; 900; 1,200; 12,340; 1,000,000; Let me know what you can do to help me out. P.S. I have looked through countless articles on how to do this and all of them say to shove into a List/Array and do it that way, but is there a much more efficient way?
For the first issue - IIRC you can't sort a DataView with a comparer. If you just need to sort numerically a field you must be sure that the column type is numeric and not string. Some code would help to elucidate this. For the second issue also you can't do that directly in the DataView. If you really need to sort the records based on some processing of data in a column then I'd copy the data in an array and use an IComparer on the array: ``` DataView dv = new DataView(dt); ArrayList lst = new ArrayList(); lst.AddRange(dv.Table.Rows); lst.Sort(new MyComparer()); foreach (DataRow dr in lst) Debug.WriteLine(dr[0]); ``` The comparer is like this: ``` class MyComparer : IComparer { public int Compare(object x, object y) { DataRow rx = x as DataRow; DataRow ry = y as DataRow; string datax = (string)rx[colName]; string datay = (string)ry[colName]; // Process datax and datay here then compare them (ASC) return datax.CompareTo(datay); } } ``` This will increase the memory consumption, so you need to think if there is maybe a better way to preprocess the data in the table so that you can sort directly the DataView by a column. P.S. colName is the name of the column you're interested to sort by. Replace the comment with actual code to extract the sorting info from the column. You can also use this method to extract sorting info from more columns. Just use something like this: ``` int cmp = colAx.CompareTo(colAy); if (cmp != 0) return cmp; cmp = colBy.CompareTo(colBx); return cmp; ``` This will compare ascending by colA values and then descending by colB values (not that the second compare has *y* first and then *x*) **Edit**: OK, I interpreted wrongly the term comma separated values. From your example I think that you actually meant numbers with thousand separators (1,000,000 = one million). If you store numbers like this in the database then it must be that you're using a text field and that should be the reason your sorting order is alphanumeric. Based on this assumption I would propose to change the type of that column to numeric, keep normal numbers inside and format them (with thousand separators) only when you display them. This way the sort should work directly in the DataView and you don't have to copy the data.
89,989
<p>I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors.</p> <p>As far as I can tell from the man pages, neither <code>curl</code> or <code>wget</code> provide such functionality. Does anyone know about another downloader who does?</p>
[ { "answer_id": 90009, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 5, "selected": false, "text": "<p>I think the <code>-f</code> option to <code>curl</code> does what you want:</p>\n\n<blockquote>\n <p><code>-f</code>, <c...
2008/09/18
[ "https://Stackoverflow.com/questions/89989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65724/" ]
I want to download a lot of urls in a script but I do not want to save the ones that lead to HTTP errors. As far as I can tell from the man pages, neither `curl` or `wget` provide such functionality. Does anyone know about another downloader who does?
One liner I just setup for this very purpose: (works only with a single file, might be useful for others) ``` A=$$; ( wget -q "http://foo.com/pipo.txt" -O $A.d && mv $A.d pipo.txt ) || (rm $A.d; echo "Removing temp file") ``` This will attempt to download the file from the remote Host. If there is an Error, the file is not kept. In all other cases, it's kept and renamed.
90,023
<h2>Update: giving a much more thorough example.</h2> <p>The first two solutions offered were right along the lines of what I was trying to say <em>not</em> to do. I can't know location, it needs to be able to look at the whole document tree. So a solution along these lines, with /Books/ specified as the context will not work:</p> <pre><code>SELECT x.query('.') FROM @xml.nodes('/Books/*[not(@ID) or @ID = 5]') x1(x) </code></pre> <h2>Original question with better example:</h2> <p>Using SQL Server 2005's XQuery implementation I need to select all nodes in an XML document, just once each and keeping their original structure, but only if they are missing a particular attribute, or that attribute has a specific value (passed in by parameter). The query also has to work on the whole XML document (descendant-or-self axis) rather than selecting at a predefined depth.</p> <p>That is to say, each individual node will appear in the resultant document only if it and every one of its ancestors are missing the attribute, or have the attribute with a single specific value.</p> <h2>For example:</h2> <p>If this were the XML:</p> <pre><code> DECLARE @Xml XML SET @Xml = N' &lt;Library&gt; &lt;Novels&gt; &lt;Novel category=&quot;1&quot;&gt;Novel1&lt;/Novel&gt; &lt;Novel category=&quot;2&quot;&gt;Novel2&lt;/Novel&gt; &lt;Novel&gt;Novel3&lt;/Novel&gt; &lt;Novel category=&quot;4&quot;&gt;Novel4&lt;/Novel&gt; &lt;/Novels&gt; &lt;Encyclopedias&gt; &lt;Encyclopedia&gt; &lt;Volume&gt;A-F&lt;/Volume&gt; &lt;Volume category=&quot;2&quot;&gt;G-L&lt;/Volume&gt; &lt;Volume category=&quot;3&quot;&gt;M-S&lt;/Volume&gt; &lt;Volume category=&quot;4&quot;&gt;T-Z&lt;/Volume&gt; &lt;/Encyclopedia&gt; &lt;/Encyclopedias&gt; &lt;Dictionaries category=&quot;1&quot;&gt; &lt;Dictionary&gt;Webster&lt;/Dictionary&gt; &lt;Dictionary&gt;Oxford&lt;/Dictionary&gt; &lt;/Dictionaries&gt; &lt;/Library&gt; ' </code></pre> <p>A parameter of 1 for category would result in this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Library&gt; &lt;Novels&gt; &lt;Novel category=&quot;1&quot;&gt;Novel1&lt;/Novel&gt; &lt;Novel&gt;Novel3&lt;/Novel&gt; &lt;/Novels&gt; &lt;Encyclopedias&gt; &lt;Encyclopedia&gt; &lt;Volume&gt;A-F&lt;/Volume&gt; &lt;/Encyclopedia&gt; &lt;/Encyclopedias&gt; &lt;Dictionaries category=&quot;1&quot;&gt; &lt;Dictionary&gt;Webster&lt;/Dictionary&gt; &lt;Dictionary&gt;Oxford&lt;/Dictionary&gt; &lt;/Dictionaries&gt; &lt;/Library&gt; </code></pre> <p>A parameter of 2 for category would result in this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;Library&gt; &lt;Novels&gt; &lt;Novel category=&quot;2&quot;&gt;Novel2&lt;/Novel&gt; &lt;Novel&gt;Novel3&lt;/Novel&gt; &lt;/Novels&gt; &lt;Encyclopedias&gt; &lt;Encyclopedia&gt; &lt;Volume&gt;A-F&lt;/Volume&gt; &lt;Volume category=&quot;2&quot;&gt;G-L&lt;/Volume&gt; &lt;/Encyclopedia&gt; &lt;/Encyclopedias&gt; &lt;/Library&gt; </code></pre> <p>I know XSLT is perfectly suited for this job, but it's not an option. We have to accomplish this entirely in SQL Server 2005. Any implementations not using XQuery are fine too, as long as it can be done entirely in T-SQL.</p>
[ { "answer_id": 90795, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 3, "selected": true, "text": "<p>It's not clear for me from your example what you're actually trying to achieve. Do you want to return a new XML with all t...
2008/09/18
[ "https://Stackoverflow.com/questions/90023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507/" ]
Update: giving a much more thorough example. -------------------------------------------- The first two solutions offered were right along the lines of what I was trying to say *not* to do. I can't know location, it needs to be able to look at the whole document tree. So a solution along these lines, with /Books/ specified as the context will not work: ``` SELECT x.query('.') FROM @xml.nodes('/Books/*[not(@ID) or @ID = 5]') x1(x) ``` Original question with better example: -------------------------------------- Using SQL Server 2005's XQuery implementation I need to select all nodes in an XML document, just once each and keeping their original structure, but only if they are missing a particular attribute, or that attribute has a specific value (passed in by parameter). The query also has to work on the whole XML document (descendant-or-self axis) rather than selecting at a predefined depth. That is to say, each individual node will appear in the resultant document only if it and every one of its ancestors are missing the attribute, or have the attribute with a single specific value. For example: ------------ If this were the XML: ``` DECLARE @Xml XML SET @Xml = N' <Library> <Novels> <Novel category="1">Novel1</Novel> <Novel category="2">Novel2</Novel> <Novel>Novel3</Novel> <Novel category="4">Novel4</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>A-F</Volume> <Volume category="2">G-L</Volume> <Volume category="3">M-S</Volume> <Volume category="4">T-Z</Volume> </Encyclopedia> </Encyclopedias> <Dictionaries category="1"> <Dictionary>Webster</Dictionary> <Dictionary>Oxford</Dictionary> </Dictionaries> </Library> ' ``` A parameter of 1 for category would result in this: ```xml <Library> <Novels> <Novel category="1">Novel1</Novel> <Novel>Novel3</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>A-F</Volume> </Encyclopedia> </Encyclopedias> <Dictionaries category="1"> <Dictionary>Webster</Dictionary> <Dictionary>Oxford</Dictionary> </Dictionaries> </Library> ``` A parameter of 2 for category would result in this: ```xml <Library> <Novels> <Novel category="2">Novel2</Novel> <Novel>Novel3</Novel> </Novels> <Encyclopedias> <Encyclopedia> <Volume>A-F</Volume> <Volume category="2">G-L</Volume> </Encyclopedia> </Encyclopedias> </Library> ``` I know XSLT is perfectly suited for this job, but it's not an option. We have to accomplish this entirely in SQL Server 2005. Any implementations not using XQuery are fine too, as long as it can be done entirely in T-SQL.
It's not clear for me from your example what you're actually trying to achieve. Do you want to return a new XML with all the nodes stripped out except those that fulfill the condition? If yes, then this looks like the job for an XSLT transform which I don't think it's built-in in MSSQL 2005 (can be added as a UDF: <http://www.topxml.com/rbnews/SQLXML/re-23872_Performing-XSLT-Transforms-on-XML-Data-Stored-in-SQL-Server-2005.aspx>). If you just need to return the list of nodes then you can use this expression: ``` //Book[not(@ID) or @ID = 5] ``` but I get the impression that it's not what you need. It would help if you can provide a clearer example. **Edit**: This example is indeed more clear. The best that I could find is this: ``` SET @Xml.modify('delete(//*[@category!=1])') SELECT @Xml ``` The idea is to delete from the XML all the nodes that you don't need, so you remain with the original structure and the needed nodes. I tested with your two examples and it produced the wanted result. However *modify* has some restrictions - it seems you can't use it in a select statement, it has to modify data in place. If you need to return such data with a select you could use a temporary table in which to copy the original data and then update that table. Something like this: ``` INSERT INTO #temp VALUES(@Xml) UPDATE #temp SET data.modify('delete(//*[@category!=2])') ``` Hope that helps.
90,029
<p>I'm trying to create a deployment tool that will install software based on the hardware found on a system. I'd like the tool to be able to determine if the optical drive is a writer (to determine if burning software sould be installed) or can read DVDs (to determine if a player should be installed). I tried uing the following code </p> <pre><code>strComputer = "." Set objWMIService = GetObject("winmgmts:\\" &amp; strComputer &amp; "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive") For Each objItem in colItems Wscript.Echo "MediaType: " &amp; objItem.MediaType Next </code></pre> <p>but it always respons with CD-ROM</p>
[ { "answer_id": 90072, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 1, "selected": false, "text": "<p>You can use WMI to enumerate what Windows knows about a drive; get the <a href=\"http://msdn.microsoft.com/en-us/library/...
2008/09/18
[ "https://Stackoverflow.com/questions/90029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to create a deployment tool that will install software based on the hardware found on a system. I'd like the tool to be able to determine if the optical drive is a writer (to determine if burning software sould be installed) or can read DVDs (to determine if a player should be installed). I tried uing the following code ``` strComputer = "." Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_CDROMDrive") For Each objItem in colItems Wscript.Echo "MediaType: " & objItem.MediaType Next ``` but it always respons with CD-ROM
You can use WMI to enumerate what Windows knows about a drive; get the [`Win32_DiskDrive`](http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx) instance from which you should be able to grab the the [`Win32_PhysicalMedia`](http://msdn.microsoft.com/en-us/library/aa394346(VS.85).aspx) information for the physical media the drive uses; the [MediaType](http://msdn.microsoft.com/en-us/library/aa394346(VS.85).aspx) property to get what media it uses (CD, CDRW, DVD, DVDRW, etc, etc).
90,049
<p>I'm using a table to design the layout of my web page. I want the table to fill the page even if it doesn't contain much content. Here's the CSS I'm using:</p> <pre class="lang-css prettyprint-override"><code>html, body { height: 100%; margin: 0; padding: 0; } #container { min-height: 100%; width: 100%; } </code></pre> <p>And I place something like this in the page code:</p> <pre><code>&lt;table id="container"&gt; &lt;tr&gt; &lt;td&gt; ... </code></pre> <p>This works for Opera 9, but not for Firefox 2 or Internet Explorer 7. Is there a simple way to make this solution work for all popular browsers?</p> <p>(Adding <code>id="container"</code> to <code>td</code> doesn't help.)</p>
[ { "answer_id": 90109, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 4, "selected": true, "text": "<p>Just use the <code>height</code> property instead of the <code>min-height</code> property when setting <code>#cont...
2008/09/18
[ "https://Stackoverflow.com/questions/90049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17216/" ]
I'm using a table to design the layout of my web page. I want the table to fill the page even if it doesn't contain much content. Here's the CSS I'm using: ```css html, body { height: 100%; margin: 0; padding: 0; } #container { min-height: 100%; width: 100%; } ``` And I place something like this in the page code: ``` <table id="container"> <tr> <td> ... ``` This works for Opera 9, but not for Firefox 2 or Internet Explorer 7. Is there a simple way to make this solution work for all popular browsers? (Adding `id="container"` to `td` doesn't help.)
Just use the `height` property instead of the `min-height` property when setting `#container`. Once the data gets too big, the table will automatically grow.
90,052
<p>Ok, so i'm working on a regular expression to search out all the header information in a site.</p> <p>I've compiled the regular expression:</p> <pre><code>regex = re.compile(r''' &lt;h[0-9]&gt;\s? (&lt;a[ ]href="[A-Za-z0-9.]*"&gt;)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', re.X) </code></pre> <p>When i run this in python reg ex. tester, it works out wonderfully.</p> <p>Sample data:</p> <pre><code>&lt;body&gt; &lt;h1&gt;Dog &lt;/h1&gt; &lt;h2&gt;Cat &lt;/h2&gt; &lt;h3&gt;Fancy &lt;/h3&gt; &lt;h1&gt;Tall cup of lemons&lt;/h1&gt; &lt;h1&gt;&lt;a href="dog.com"&gt;Dog thing&lt;/a&gt;&lt;/h1&gt; &lt;/body&gt; </code></pre> <p>Now, in the REDemo, it works wonderfully.</p> <p>When i put it in my python code, however, it only prints <code>&lt;a href="dog.com"&gt;</code></p> <p>Here's my python code, I'm not sure if i'm doing something wrong or if something is lost in translation. I appreciate your help.</p> <pre><code>stories=[] response = urllib2.urlopen('http://apricotclub.org/duh.html') html = response.read().lower() p = re.compile('&lt;h[0-9]&gt;\\s?(&lt;a href=\"[A-Za-z0-9.]*\"&gt;)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?') stories=re.findall(p, html) for i in stories: if len(i) &gt;= 5: print i </code></pre> <p>I should also note, that when i take out the <code>(&lt;a href=\"[A-Za-z0-9.]*\"&gt;)?</code> from the regular expression it works fine for non-link <code>&lt;hN&gt;</code> lines.</p>
[ { "answer_id": 90095, "author": "habnabit", "author_id": 10999, "author_profile": "https://Stackoverflow.com/users/10999", "pm_score": 2, "selected": false, "text": "<p>Parsing things with regular expressions works for regular languages. HTML is not a regular language, and the stuff you ...
2008/09/18
[ "https://Stackoverflow.com/questions/90052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Ok, so i'm working on a regular expression to search out all the header information in a site. I've compiled the regular expression: ``` regex = re.compile(r''' <h[0-9]>\s? (<a[ ]href="[A-Za-z0-9.]*">)?\s? [A-Za-z0-9.,:'"=/?;\s]*\s? [A-Za-z0-9.,:'"=/?;\s]? ''', re.X) ``` When i run this in python reg ex. tester, it works out wonderfully. Sample data: ``` <body> <h1>Dog </h1> <h2>Cat </h2> <h3>Fancy </h3> <h1>Tall cup of lemons</h1> <h1><a href="dog.com">Dog thing</a></h1> </body> ``` Now, in the REDemo, it works wonderfully. When i put it in my python code, however, it only prints `<a href="dog.com">` Here's my python code, I'm not sure if i'm doing something wrong or if something is lost in translation. I appreciate your help. ``` stories=[] response = urllib2.urlopen('http://apricotclub.org/duh.html') html = response.read().lower() p = re.compile('<h[0-9]>\\s?(<a href=\"[A-Za-z0-9.]*\">)?\\s?[A-Za-z0-9.,:\'\"=/?;\\s]*\\s?[A-Za-z0-9.,:\'\"=/?;\\s]?') stories=re.findall(p, html) for i in stories: if len(i) >= 5: print i ``` I should also note, that when i take out the `(<a href=\"[A-Za-z0-9.]*\">)?` from the regular expression it works fine for non-link `<hN>` lines.
This question has been asked in several forms over the last few days, so I'm going to say this very clearly. Q: How do I parse HTML with Regular Expressions? ================================================ A: Please Don't. ================ Use [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/), [html5lib](http://code.google.com/p/html5lib/) or [lxml.html](http://codespeak.net/lxml/lxmlhtml.html). Please.
90,067
<p>I'm using the following html to load dojo from Google's hosting.</p> <pre><code>&lt;script src="http://www.google.com/jsapi"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt;google.load("dojo", "1.1.1");&lt;/script&gt; &lt;script type="text/javascript"&gt; dojo.require("dojox.gfx"); ... </code></pre> <p>This errors out on the requre line with an error like dojox.gfx is undefined. Is there a way to make this work, or does Google not support the dojox extensions?</p> <p>Alternatively, is there another common host I can use for standard dojo releases?</p>
[ { "answer_id": 90088, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 0, "selected": false, "text": "<p>I believe that google becomes the namespace for your imported libraries. Try: <code>google.dojo.require</code>.</...
2008/09/18
[ "https://Stackoverflow.com/questions/90067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17209/" ]
I'm using the following html to load dojo from Google's hosting. ``` <script src="http://www.google.com/jsapi"></script> <script type="text/javascript">google.load("dojo", "1.1.1");</script> <script type="text/javascript"> dojo.require("dojox.gfx"); ... ``` This errors out on the requre line with an error like dojox.gfx is undefined. Is there a way to make this work, or does Google not support the dojox extensions? Alternatively, is there another common host I can use for standard dojo releases?
Differently from when you reference the .js files directly from the <script> tag (note that google js api also supports this, see [here](http://code.google.com/apis/ajaxlibs/documentation/#dojo)), google.load is not synchronous. This means that when your code reach google.load, it will not wait for dojo to be fully loaded to keep parsing; it will go straight to your dojo.require line, and it will fail there because the **dojo** object will be undefined. The solution (if you don't want to use use the direct <script> tag), is to enclose all your code that references dojo in a **start** function, and set it will as a callback, by doing: ``` google.load("dojo", "1.1.1", {callback: start}); function start() { dojo.require("dojox.gfx"); ... } ``` or ``` google.setOnLoadCallback(start); google.load("dojo", "1.1.1"); function start() { dojo.require("dojox.gfx"); ... } ```