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
135,909
<p>I run into this occasionally and always forget how to do it.</p> <p>One of those things that pop up ever so often.</p> <p>Also, what's the formula to convert angles expressed in radians to degrees and back again?</p>
[ { "answer_id": 135925, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 0, "selected": false, "text": "<p>180 degrees = PI * radians</p>\n" }, { "answer_id": 135927, "author": "thesmallprint", "author_id"...
2008/09/25
[ "https://Stackoverflow.com/questions/135909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
I run into this occasionally and always forget how to do it. One of those things that pop up ever so often. Also, what's the formula to convert angles expressed in radians to degrees and back again?
``` radians = degrees * (pi/180) degrees = radians * (180/pi) ``` As for implementation, the main question is how precise you want to be about the value of pi. There is some related discussion [here](https://stackoverflow.com/questions/19/fastest-way-to-get-value-of-pi)
135,919
<p>I haven't been able to find an adequate answer to what exactly the following error means:</p> <p><code>java.net.SocketException: Software caused connection abort: recv failed</code> </p> <p>Notes:</p> <ul> <li>This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail.</li> <li>The only solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case).</li> <li>The URI is definitely available (as confirmed by asking the browser to do the fetch).</li> </ul> <p>Relevant code:</p> <pre><code>BufferedReader reader; try { URL url = new URL(URI); reader = new BufferedReader(new InputStreamReader(url.openStream()))); } catch( MalformedURLException e ) { throw new IOException("Expecting a well-formed URL: " + e); }//end try: Have a stream String buffer; StringBuilder result = new StringBuilder(); while( null != (buffer = reader.readLine()) ) { result.append(buffer); }//end while: Got the contents. reader.close(); </code></pre>
[ { "answer_id": 135983, "author": "Ken", "author_id": 20621, "author_profile": "https://Stackoverflow.com/users/20621", "pm_score": 2, "selected": false, "text": "<p>Are you accessing http data? Can you use the HttpClient library instead of the standard library? The library has more opt...
2008/09/25
[ "https://Stackoverflow.com/questions/135919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12815/" ]
I haven't been able to find an adequate answer to what exactly the following error means: `java.net.SocketException: Software caused connection abort: recv failed` Notes: * This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail. * The only solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case). * The URI is definitely available (as confirmed by asking the browser to do the fetch). Relevant code: ``` BufferedReader reader; try { URL url = new URL(URI); reader = new BufferedReader(new InputStreamReader(url.openStream()))); } catch( MalformedURLException e ) { throw new IOException("Expecting a well-formed URL: " + e); }//end try: Have a stream String buffer; StringBuilder result = new StringBuilder(); while( null != (buffer = reader.readLine()) ) { result.append(buffer); }//end while: Got the contents. reader.close(); ```
This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.
135,929
<p>I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell.</p> <pre><code>declare @ConstraintName varchar(255) set @ConstraintName = 'PK_Whatever' IF LEFT(@ConstraintName, 2) = 'PK' BEGIN --can't drop primary keys END </code></pre> <p>The error I get is:</p> <pre><code>Incorrect syntax near 'END'. </code></pre> <p>If I add something after the comment, i.e. <code>PRINT @ConstraintName</code>, it works fine.</p>
[ { "answer_id": 135962, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>I can't say for sure in SQL Server, but in Oracle PL/SQL you would put a NULL statement in a block that you want to do...
2008/09/25
[ "https://Stackoverflow.com/questions/135929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73794/" ]
I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell. ``` declare @ConstraintName varchar(255) set @ConstraintName = 'PK_Whatever' IF LEFT(@ConstraintName, 2) = 'PK' BEGIN --can't drop primary keys END ``` The error I get is: ``` Incorrect syntax near 'END'. ``` If I add something after the comment, i.e. `PRINT @ConstraintName`, it works fine.
No, you cannot have an empty if block (or one that contains only comments). You don't say why you would want this. If you are just trying to comment out the contents of the if for debugging, you should comment the entire if.
135,934
<p>I need to show a camera capture dialog in a compact framework 3.7 application by pinvoking SHCameraCapture from the dll Aygshell.dll. I cannont use the managed object CameraCaptureDialog because of limitations with the technology I'm working with. Instead, I need to access it by Pinvoking it.</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/aa454995.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa454995.aspx</a> for documentation on the function. The function takes in a struct that defines the parameters of the dialog. e.g. where to save the file, what resolution to use.</p> <p>I would imaging that I would have to define a copy of the struct in C# and decorate the sturct with the attribute StructLayout. I also imagine that the code would involve [DllImport("aygshell.dll")]. Any sample code of how to call this would be much appreciated.</p>
[ { "answer_id": 138398, "author": "Grokys", "author_id": 6448, "author_profile": "https://Stackoverflow.com/users/6448", "pm_score": 0, "selected": false, "text": "<p>I've not been able to test this, but your struct/function should look something like this:</p>\n\n<pre><code>struct SHCAME...
2008/09/25
[ "https://Stackoverflow.com/questions/135934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12497/" ]
I need to show a camera capture dialog in a compact framework 3.7 application by pinvoking SHCameraCapture from the dll Aygshell.dll. I cannont use the managed object CameraCaptureDialog because of limitations with the technology I'm working with. Instead, I need to access it by Pinvoking it. See <http://msdn.microsoft.com/en-us/library/aa454995.aspx> for documentation on the function. The function takes in a struct that defines the parameters of the dialog. e.g. where to save the file, what resolution to use. I would imaging that I would have to define a copy of the struct in C# and decorate the sturct with the attribute StructLayout. I also imagine that the code would involve [DllImport("aygshell.dll")]. Any sample code of how to call this would be much appreciated.
this code works.... ``` #region Enumerations public enum CAMERACAPTURE_STILLQUALITY { CAMERACAPTURE_STILLQUALITY_DEFAULT = 0, CAMERACAPTURE_STILLQUALITY_LOW = 1, CAMERACAPTURE_STILLQUALITY_NORMAL = 2, CAMERACAPTURE_STILLQUALITY_HIGH = 3 } public enum CAMERACAPTURE_VIDEOTYPES { CAMERACAPTURE_VIDEOTYPE_ALL = 0xFFFF, CAMERACAPTURE_VIDEOTYPE_STANDARD = 1, CAMERACAPTURE_VIDEOTYPE_MESSAGING = 2 } public enum CAMERACAPTURE_MODE { CAMERACAPTURE_MODE_STILL = 0, CAMERACAPTURE_MODE_VIDEOONLY = 1, CAMERACAPTURE_MODE_VIDEOWITHAUDIO = 2 } #endregion //Enumerations #region Structures [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)] public struct struSHCAMERACAPTURE { public uint cbSize; public IntPtr hwndOwner; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public String szFile; [MarshalAs(UnmanagedType.LPTStr)] public String pszInitialDir; //LPCTSTR [MarshalAs(UnmanagedType.LPTStr)] public String pszDefaultFileName; //LPCTSTR [MarshalAs(UnmanagedType.LPTStr)] public String pszTitle; //LPCTSTR public CAMERACAPTURE_STILLQUALITY StillQuality; public CAMERACAPTURE_VIDEOTYPES VideoTypes; public uint nResolutionWidth; public uint nResolutionHeight; public uint nVideoTimeLimit; public CAMERACAPTURE_MODE Mode; } #endregion //Structures #region API [DllImport("Aygshell.dll", SetLastError = true,CharSet=CharSet.Unicode)] public static extern int SHCameraCapture ( ref struSHCAMERACAPTURE pshCamCapture ); private string StartImager(String strImgDir, String strImgFile, uint uintImgHeight, uint uintImgWidth) try { struSHCAMERACAPTURE shCamCapture = new struSHCAMERACAPTURE(); shCamCapture.cbSize = (uint)Marshal.SizeOf(shCamCapture); shCamCapture.hwndOwner = IntPtr.Zero; shCamCapture.szFile = "\\" + strImgFile; //strImgDir + "\\" + strImgFile; shCamCapture.pszInitialDir = "\\"; // strImgDir; shCamCapture.pszDefaultFileName = strImgFile; shCamCapture.pszTitle = "PTT Image Capture"; shCamCapture.StillQuality = 0; // CAMERACAPTURE_STILLQUALITY.CAMERACAPTURE_STILLQUALITY_NORMAL; shCamCapture.VideoTypes = CAMERACAPTURE_VIDEOTYPES.CAMERACAPTURE_VIDEOTYPE_STANDARD; shCamCapture.nResolutionHeight = 0; // uintImgHeight; shCamCapture.nResolutionWidth = 0; // uintImgWidth; shCamCapture.nVideoTimeLimit = 10; shCamCapture.Mode = 0; // CAMERACAPTURE_MODE.CAMERACAPTURE_MODE_STILL; //IntPtr intptrCamCaptr = IntPtr.Zero; //Marshal.StructureToPtr(shCamCapture, intptrCamCaptr, true); int intResult = SHCameraCapture(ref shCamCapture); if (intResult != 0) { Win32Exception Win32 = new Win32Exception(intResult); MessageBox.Show("Error: " + Win32.Message); } return strCaptrErr; } catch (Exception ex) { MessageBox.Show("Error StartImager : " + ex.ToString() + " - " + strCaptrErr , "Nomad Imager Test"); return ""; } ```
135,938
<p>It's not a matter of life or death but I wonder if this could be possible:</p> <p>I got a couple of events from one type of custom event (FormEvent) now I got a FormListener that listens to all those events and handles them according to the event type. Instead of adding one eventListener at the time I wish to add all events at once.</p> <p>so now it looks like this:</p> <pre><code> private function addListeners():void { addEventListener(FormEvent.SHOW_FORM, formListener); addEventListener(FormEvent.SEND_FORM, formListener); addEventListener(FormEvent.CANCEL_FORM, formListener); } private function formListener(event:formEvent):void { switch(event.type){ case "show.form": // handle show form stuff break; case "send.form": // handle send form stuff break; case "cancel.form": // handle cancel form stuff break; } } </code></pre> <p>but instead of adding every event one at the time I would rather be doing something like</p> <pre><code> private function addListeners():void { addEventListener(FormEvent.*, formListener); } </code></pre> <p>I wonder if something like this is possible, i would love it. I work with loads of events :)</p>
[ { "answer_id": 136258, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 0, "selected": false, "text": "<p>I don't know of any routines that let you do that directly, but you could write your own. The syntax here won't be pe...
2008/09/25
[ "https://Stackoverflow.com/questions/135938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18671/" ]
It's not a matter of life or death but I wonder if this could be possible: I got a couple of events from one type of custom event (FormEvent) now I got a FormListener that listens to all those events and handles them according to the event type. Instead of adding one eventListener at the time I wish to add all events at once. so now it looks like this: ``` private function addListeners():void { addEventListener(FormEvent.SHOW_FORM, formListener); addEventListener(FormEvent.SEND_FORM, formListener); addEventListener(FormEvent.CANCEL_FORM, formListener); } private function formListener(event:formEvent):void { switch(event.type){ case "show.form": // handle show form stuff break; case "send.form": // handle send form stuff break; case "cancel.form": // handle cancel form stuff break; } } ``` but instead of adding every event one at the time I would rather be doing something like ``` private function addListeners():void { addEventListener(FormEvent.*, formListener); } ``` I wonder if something like this is possible, i would love it. I work with loads of events :)
You only really need one event listener in this case anyhow. That listener will be listening for any change with the form and a parameter equal to what the change was becomes available to the event listener function. I will show you, but please remember that this is a pseudo situation and normally I wouldn't dispatch an event off of something as simple as a method call because the dispatch is implied so there is no real need to listen for it. First the Custom Event ``` package com.yourDomain.events { import flash.events.Event; public class FormEvent extends Event { //Public Properties public static const CANCEL_FORM:int = "0"; public static const SHOW_FORM:int = "1"; public static const SEND_FORM:int = "2"; public static const STATE_CHANGED:String = "stateChanged"; //Private Properties private var formState:int; public function FormEvent(formState:int):void { super(STATE_CHANGED); formState = formState; } } } ``` So we have just created our custom event class and we have set it up so that we can catch the state through the listener function as I will demonstrate once done with the pseudo form class that will dispatch the for said custom event. Remember that this is all hypothetical as I have no idea what your code looks like or how your implementing things. What is important is to notice that when I dispatch the event I need to send a parameter with it that reflects what the new state is. ``` package com.yourDomain.ui { import flash.events.Event; import flash.events.EventDispatcher; import com.yourDomain.events.FormEvent; public class Form extends EventDispatcher { public function Form():void { //Anything you want form to do upon instantiation goes here. } public function cancelForm():void { dispatchEvent(new Event(FormEvent.CANCEL_FORM); } public function showForm():void { dispatchEvent(new Event(FormEvent.SHOW_FORM); } public function sendForm():void { dispatchEvent(new Event(FormEvent.SEND_FORM); } } } ``` And finally we create the document class that will listen for it. Please know that I realize it isn't logical to create a listener that fires when you call a method of a class because you obviously know you called the method, but for this example it will due. ``` package com.yourDomain.ui { import com.yourDomain.ui.Form; import com.yourDomain.events.FormEvent; //Form is in the same package so we need not import it. public class MainDocumentClass { private var _theForm:Form; public function MainDocumentClass():void { _theForm = new Form(); _theForm.addEventListener(FormEvent.STATE_CHANGED, onFormStateChange, false, 0, true); /* The following three method calls each cause the FormEvent.STATE_CHANGE event to be dispatched. onFormStateChange is notified and checks what the last change actually was. */ _theForm.cancelForm(); _theForm.showForm(); _theForm.sendForm(); } private function onFormStateChange(e:FormEvent):void { switch(e.formState) { case CANCEL_FORM: trace('The form was canceled'); break; case SHOW_FORM: trace('The form was revealed'); break; case SEND_FORM: trace('The form was sent'); break; } } } } ``` I hope that this was helpful, its late and I may have to revise some things later, but this should help get an understanding of how to make your own events and to customize how things work.
135,944
<p>Stored procs in SQL Server sometimes finish with a return code, as opposed to a recordset of data. I've seen ASP code that's able to get this return code, but I can't figure out how to get this code with PHP's mssql driver.</p> <p>mssql_get_last_message() always returns nothing, and I'm thinking it's because it only returns the very last line that came from the server. When we run the proc in another application (outside PHP), there is blank line following the return code.</p> <p>Has anyone figured out how to get return codes from SQL stored procs using PHP's mssql driver?</p>
[ { "answer_id": 135963, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 3, "selected": true, "text": "<p>Are you talking about SQL Server error codes, e.g. RAISERRROR or other failures? If so, last time I checked in PHP you...
2008/09/25
[ "https://Stackoverflow.com/questions/135944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12308/" ]
Stored procs in SQL Server sometimes finish with a return code, as opposed to a recordset of data. I've seen ASP code that's able to get this return code, but I can't figure out how to get this code with PHP's mssql driver. mssql\_get\_last\_message() always returns nothing, and I'm thinking it's because it only returns the very last line that came from the server. When we run the proc in another application (outside PHP), there is blank line following the return code. Has anyone figured out how to get return codes from SQL stored procs using PHP's mssql driver?
Are you talking about SQL Server error codes, e.g. RAISERRROR or other failures? If so, last time I checked in PHP you need to ask for @@ERROR (e.g. select @@error) instead. If it is a return code, you must explicitly catch it, e.g. ``` DECLARE @return_code INT EXEC @return_code = your_stored_procedure 1123 SELECT @return_code ```
135,971
<p>If you have two jars in your classpath that contain different versions of the same class, the classpath order becomes critical.</p> <p>I am looking for a tool that can detect and flag such potential conflicts in a given classpath or set of folders.</p> <p>Certainly a script that starts:</p> <pre><code>classes=`mktemp` for i in `find . -name "*.jar"` do echo "File: $i" &gt; $classes jar tf $i &gt; $classes ... done </code></pre> <p>with some clever sort/uniq/diff/grep/awk later on has potential, but I was wondering if anyone knows of any existing solutions.</p>
[ { "answer_id": 136252, "author": "ferbs", "author_id": 22406, "author_profile": "https://Stackoverflow.com/users/22406", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://classpathhelper.sourceforge.net/\" rel=\"nofollow noreferrer\">Classpath Helper</a> is an Eclipse plug-i...
2008/09/25
[ "https://Stackoverflow.com/questions/135971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
If you have two jars in your classpath that contain different versions of the same class, the classpath order becomes critical. I am looking for a tool that can detect and flag such potential conflicts in a given classpath or set of folders. Certainly a script that starts: ``` classes=`mktemp` for i in `find . -name "*.jar"` do echo "File: $i" > $classes jar tf $i > $classes ... done ``` with some clever sort/uniq/diff/grep/awk later on has potential, but I was wondering if anyone knows of any existing solutions.
The [Tattletale](http://www.jboss.org/tattletale) tool from JBoss is another candidate: "Spot if a class/package is located in multiple JAR files"
135,995
<p>So, I want to define a singleton method for an object, but I want to do it using a closure.</p> <p>For example,</p> <pre><code>def define_say(obj, msg) def obj.say puts msg end end o = Object.new define_say o, "hello world!" o.say </code></pre> <p>This doesn't work because defining a singleton method via "def" is not a closure, so I get an exception that "msg" is an undefined variable or method.</p> <p>What I would like to do is something like using the "define_method" method in the Module class, but as far as I can tell, this can only be used to define a method on a class... but I want a Singleton Method...</p> <p>So, I would love to write it something like this:</p> <pre><code>def define_say(obj, msg) obj.define_singleton_method(:say) { puts msg } end </code></pre> <p>Does anyone know how I can achieve this without having to create a method to store a Proc and then use the Proc within a singleton method? (basically, I want a clean, non-hacky way of doing this)</p>
[ { "answer_id": 136194, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "<p>Here's an answer which does what you're looking for</p>\n\n<pre><code>def define_say(obj, msg)\n # Get a handle to th...
2008/09/25
[ "https://Stackoverflow.com/questions/135995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
So, I want to define a singleton method for an object, but I want to do it using a closure. For example, ``` def define_say(obj, msg) def obj.say puts msg end end o = Object.new define_say o, "hello world!" o.say ``` This doesn't work because defining a singleton method via "def" is not a closure, so I get an exception that "msg" is an undefined variable or method. What I would like to do is something like using the "define\_method" method in the Module class, but as far as I can tell, this can only be used to define a method on a class... but I want a Singleton Method... So, I would love to write it something like this: ``` def define_say(obj, msg) obj.define_singleton_method(:say) { puts msg } end ``` Does anyone know how I can achieve this without having to create a method to store a Proc and then use the Proc within a singleton method? (basically, I want a clean, non-hacky way of doing this)
Here's an answer which does what you're looking for ``` def define_say(obj, msg) # Get a handle to the singleton class of obj metaclass = class << obj; self; end # add the method using define_method instead of def x.say so we can use a closure metaclass.send :define_method, :say do puts msg end end ``` Usage (paste from IRB) ``` >> s = "my string" => "my string" >> define_say(s, "I am S") => #<Proc:0xb6ed55b0@(irb):11> >> s.say I am S => nil ``` For more info (and a little library which makes it less messy) read this: <http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html> As an aside, If you're a ruby programmer, and you HAVEN'T read that, go do it now~!
136,028
<p>I realize there is a somewhat related thread on this here: <a href="https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies">Loading assemblies and its dependencies</a></p> <p>But I am modifying something and this doesn't exactly apply. </p> <pre><code>string path = Path.GetDirectoryName( pathOfAssembly ); Environment.CurrentDirectory = path; Assembly.Load(Path.GetFileNameWithoutExtension(pastOfAssembly)); </code></pre> <p>Is there any really reason you would do it like this? Wouldn't it make more sense to just use:</p> <pre><code>Assembly.LoadFile(pathOfAssembly); </code></pre> <p>Any insight would be greatly appreciated.</p>
[ { "answer_id": 136072, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 4, "selected": true, "text": "<p>Looks like the \"Department of Redundancy Department.\"</p>\n\n<p>A lot more code than is necessary. Less is more!</p>\n...
2008/09/25
[ "https://Stackoverflow.com/questions/136028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
I realize there is a somewhat related thread on this here: [Loading assemblies and its dependencies](https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies) But I am modifying something and this doesn't exactly apply. ``` string path = Path.GetDirectoryName( pathOfAssembly ); Environment.CurrentDirectory = path; Assembly.Load(Path.GetFileNameWithoutExtension(pastOfAssembly)); ``` Is there any really reason you would do it like this? Wouldn't it make more sense to just use: ``` Assembly.LoadFile(pathOfAssembly); ``` Any insight would be greatly appreciated.
Looks like the "Department of Redundancy Department." A lot more code than is necessary. Less is more! **Edit:** On second thought, it could be that the assembly you are loading has dependencies that live in its own folder that may be required to use the first assembly.
136,034
<p>I've looked around for a good example of this, but I haven't run into one yet. I want to pass a custom string array from java to oracle and back, using the IBATIS framework. Does anyone have a good link to an example? I'm calling stored procs from IBATIS.</p> <p>Thanks</p>
[ { "answer_id": 137693, "author": "bsanders", "author_id": 22200, "author_profile": "https://Stackoverflow.com/users/22200", "pm_score": 2, "selected": false, "text": "<p>You've got to start with a custom instance of <code>TypeHandler</code>. We'd prefer to implement the simpler <code>Ty...
2008/09/25
[ "https://Stackoverflow.com/questions/136034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22365/" ]
I've looked around for a good example of this, but I haven't run into one yet. I want to pass a custom string array from java to oracle and back, using the IBATIS framework. Does anyone have a good link to an example? I'm calling stored procs from IBATIS. Thanks
You've got to start with a custom instance of `TypeHandler`. We'd prefer to implement the simpler `TypeHandlerCallback`, but in this scenario we need access to the underlying `Connection`. ``` public class ArrayTypeHandler implements TypeHandler { public void setParameter(PreparedStatement ps, int i, Object param, String jdbcType) throws SQLException { if (param == null) { ps.setNull(i, Types.ARRAY); } else { Connection conn = ps.getConnection(); Array loc = conn.createArrayOf("myArrayType", (Object[]) param); ps.setArray(i, loc); } } public Object getResult(CallableStatement statement, int i) throws SQLException { return statement.getArray(i).getArray(); } ... } ``` Then, to wire it up in the iBATIS config: ``` <?xml version="1.0"?> <!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd"> <sqlMap namespace="arrayTest"> <parameterMap id="storedprocParams" class="map"> <parameter property="result" mode="OUT" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/> <parameter property="argument" mode="IN" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/> </parameterMap> <procedure id="storedproc" parameterMap="arrayTest.storedprocParams"> {? = call My_Array_Function( ? )} </procedure> </sqlMap> ``` Hope this helps!
136,035
<p>It is discouraged to simply catch <code>System.Exception</code>. Instead, only the &quot;known&quot; exceptions should be caught.</p> <p>Now, this sometimes leads to unnecessary repetitive code, for example:</p> <pre><code>try { WebId = new Guid(queryString[&quot;web&quot;]); } catch (FormatException) { WebId = Guid.Empty; } catch (OverflowException) { WebId = Guid.Empty; } </code></pre> <p>I wonder: Is there a way to catch both exceptions and only call the <code>WebId = Guid.Empty</code> call once?</p> <p>The given example is rather simple, as it's only a <a href="http://en.wikipedia.org/wiki/Globally_unique_identifier" rel="noreferrer"><code>GUID</code></a>. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to &quot;reset&quot; the <code>object</code>. However, if there is an unexpected exception, I still want to throw that higher.</p>
[ { "answer_id": 136038, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 3, "selected": false, "text": "<p>Note that I did find one way to do it, but this looks more like material for <a href=\"https://en.wikipedia.org/wiki/The...
2008/09/25
[ "https://Stackoverflow.com/questions/136035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
It is discouraged to simply catch `System.Exception`. Instead, only the "known" exceptions should be caught. Now, this sometimes leads to unnecessary repetitive code, for example: ``` try { WebId = new Guid(queryString["web"]); } catch (FormatException) { WebId = Guid.Empty; } catch (OverflowException) { WebId = Guid.Empty; } ``` I wonder: Is there a way to catch both exceptions and only call the `WebId = Guid.Empty` call once? The given example is rather simple, as it's only a [`GUID`](http://en.wikipedia.org/wiki/Globally_unique_identifier). But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the `object`. However, if there is an unexpected exception, I still want to throw that higher.
Catch `System.Exception` and switch on the types ``` catch (Exception ex) { if (ex is FormatException || ex is OverflowException) { WebId = Guid.Empty; return; } throw; } ```
136,050
<p>Is there a way to prevent VS2008 creating browse info file files for C++ projects.<br> I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed.</p> <p>EDIT - it's also needed for go to declaration/definition</p>
[ { "answer_id": 136075, "author": "Jordan Parmer", "author_id": 20133, "author_profile": "https://Stackoverflow.com/users/20133", "pm_score": 3, "selected": false, "text": "<p>In the project properties, you will find the browse information under:</p>\n\n<p>Configuration Properties -> C/C+...
2008/09/25
[ "https://Stackoverflow.com/questions/136050", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10897/" ]
Is there a way to prevent VS2008 creating browse info file files for C++ projects. I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed. EDIT - it's also needed for go to declaration/definition
There is a registry key for this as well: `[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]` Intellisense ON ``` "IntellisenseOptions"=dword:00000000 ``` Intellisense OFF ``` "IntellisenseOptions"=dword:00000007 ``` Intellisense ON - NO Background UPDATE ``` "IntellisenseOptions"=dword:00000005 ``` More flags are available and you can [Control Intellisense through Macros](http://blogs.msdn.com/vcblog/archive/2007/11/19/controlling-intellisense-through-macros.aspx) as well. ``` ISENSE_NORMAL = 0 'normal (Intellisense On) ISENSE_NOBG = &H1 'no bg parsing (Intellisense Updating Off - although NCB file will be opened r/w and repersisted at shutdown) ISENSE_NOQUERY = &H2 'no queries (don't run any ISense queries) ISENSE_NCBRO = &H4 'no saving of NCB (must be set before opening NCB, doesn't affect updating or queries, just persisting of NCB) ISENSE_OFF = &H7 ```
136,097
<p>What is the difference between a function decorated with <a href="http://docs.python.org/library/functions.html#staticmethod" rel="noreferrer"><code>@staticmethod</code></a> and one decorated with <a href="http://docs.python.org/library/functions.html#classmethod" rel="noreferrer"><code>@classmethod</code></a>?</p>
[ { "answer_id": 136138, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 10, "selected": false, "text": "<p>A <strong>staticmethod</strong> is a method that knows nothing about the class or instance it was called on. It...
2008/09/25
[ "https://Stackoverflow.com/questions/136097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4766/" ]
What is the difference between a function decorated with [`@staticmethod`](http://docs.python.org/library/functions.html#staticmethod) and one decorated with [`@classmethod`](http://docs.python.org/library/functions.html#classmethod)?
Maybe a bit of example code will help: Notice the difference in the call signatures of `foo`, `class_foo` and `static_foo`: ``` class A(object): def foo(self, x): print(f"executing foo({self}, {x})") @classmethod def class_foo(cls, x): print(f"executing class_foo({cls}, {x})") @staticmethod def static_foo(x): print(f"executing static_foo({x})") a = A() ``` Below is the usual way an object instance calls a method. The object instance, `a`, is implicitly passed as the first argument. ``` a.foo(1) # executing foo(<__main__.A object at 0xb7dbef0c>, 1) ``` --- **With classmethods**, the class of the object instance is implicitly passed as the first argument instead of `self`. ``` a.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) ``` You can also call `class_foo` using the class. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance. `A.foo(1)` would have raised a TypeError, but `A.class_foo(1)` works just fine: ``` A.class_foo(1) # executing class_foo(<class '__main__.A'>, 1) ``` One use people have found for class methods is to create [inheritable alternative constructors](https://stackoverflow.com/a/1950927/190597). --- **With staticmethods**, neither `self` (the object instance) nor `cls` (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class: ``` a.static_foo(1) # executing static_foo(1) A.static_foo('hi') # executing static_foo(hi) ``` Staticmethods are used to group functions which have some logical connection with a class to the class. --- `foo` is just a function, but when you call `a.foo` you don't just get the function, you get a "partially applied" version of the function with the object instance `a` bound as the first argument to the function. `foo` expects 2 arguments, while `a.foo` only expects 1 argument. `a` is bound to `foo`. That is what is meant by the term "bound" below: ``` print(a.foo) # <bound method A.foo of <__main__.A object at 0xb7d52f0c>> ``` With `a.class_foo`, `a` is not bound to `class_foo`, rather the class `A` is bound to `class_foo`. ``` print(a.class_foo) # <bound method type.class_foo of <class '__main__.A'>> ``` Here, with a staticmethod, even though it is a method, `a.static_foo` just returns a good 'ole function with no arguments bound. `static_foo` expects 1 argument, and `a.static_foo` expects 1 argument too. ``` print(a.static_foo) # <function static_foo at 0xb7d479cc> ``` And of course the same thing happens when you call `static_foo` with the class `A` instead. ``` print(A.static_foo) # <function static_foo at 0xb7d479cc> ```
136,098
<p>Browsing to a dynamic web page built using Grails version 1.0.3 the console log shows the following errors for each page request:</p> <pre><code>[Fatal Error] :-1:-1: Premature end of file. </code></pre> <p>How do I stop this error from appearing for each request?</p>
[ { "answer_id": 136125, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 4, "selected": false, "text": "<p>This bug was already fixed:\n<a href=\"http://jira.codehaus.org/browse/GRAILS-3088\" rel=\"nofollow noreferrer\">ht...
2008/09/25
[ "https://Stackoverflow.com/questions/136098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16175/" ]
Browsing to a dynamic web page built using Grails version 1.0.3 the console log shows the following errors for each page request: ``` [Fatal Error] :-1:-1: Premature end of file. ``` How do I stop this error from appearing for each request?
The log entry occurs when http requests are made from Firefox 3 browsers. The workaround on Grails 1.0.3 is to open Config.groovy in your project and find the following: ``` grails.mime.types = [ html: ['text/html','application/xhtml+xml'], xml: ['text/xml', 'application/xml'], ... ``` The second line above, pertaining to xml should be removed. This is a GRAILS 1.0.3 bug that has been resolved, see <http://jira.codehaus.org/browse/GRAILS-3088> for full details.
136,104
<p>Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"?</p>
[ { "answer_id": 136109, "author": "Adam Tegen", "author_id": 4066, "author_profile": "https://Stackoverflow.com/users/4066", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms164303.aspx\" rel=\"noreferrer\">It turns out that Dev Studio only ...
2008/09/25
[ "https://Stackoverflow.com/questions/136104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ]
Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"?
[It turns out that Dev Studio only honors this setting for Web Services.](http://msdn.microsoft.com/en-us/library/ms164303.aspx) For non-web services you can get this to work by adding an AfterBuild target to your project file: ``` <Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)"> <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)"> <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" /> </SGen> </Target> ``` See also: * [SGen MSBuild Task](http://msdn.microsoft.com/en-us/library/ms164303.aspx) * [AfterBuild Event](http://msdn.microsoft.com/en-us/library/xzw8335a(VS.80).aspx)
136,129
<p>I am trying to set the disabled font characteristics for a Label Control. I can set all of the Font characteristics (size, bold, etc), but the color is overridden by the default windows behavior which seems to be one of these two colors:</p> <ul> <li>If background color is transparent then ForeColor is same as TextBox disabled Color.</li> <li>If background color is set to anything else, ForeColor is a Dark Gray color.</li> </ul> <p>The image below demonstrates the behavior -- Column 1 is Labels, Column 2 is TextBoxs, and Column 3 is ComboBoxes.</p> <p><img src="https://i.stack.imgur.com/60viN.png" alt="alt text"></p> <p>Edit -- Explaining the image: The first two rows are default styles for a label, textbox, and combobox. In the second two rows, I set the Background color to Red and Foreground to White. The disabled font style handling by Microsoft is inconsistent.</p>
[ { "answer_id": 136142, "author": "Austin Salonen", "author_id": 4068, "author_profile": "https://Stackoverflow.com/users/4068", "pm_score": 2, "selected": false, "text": "<p>Have you tried implementing the EnabledChanged event? Or are you looking for more of a \"styles\" property on the...
2008/09/25
[ "https://Stackoverflow.com/questions/136129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19242/" ]
I am trying to set the disabled font characteristics for a Label Control. I can set all of the Font characteristics (size, bold, etc), but the color is overridden by the default windows behavior which seems to be one of these two colors: * If background color is transparent then ForeColor is same as TextBox disabled Color. * If background color is set to anything else, ForeColor is a Dark Gray color. The image below demonstrates the behavior -- Column 1 is Labels, Column 2 is TextBoxs, and Column 3 is ComboBoxes. ![alt text](https://i.stack.imgur.com/60viN.png) Edit -- Explaining the image: The first two rows are default styles for a label, textbox, and combobox. In the second two rows, I set the Background color to Red and Foreground to White. The disabled font style handling by Microsoft is inconsistent.
Take a look at the [ControlPaint.DrawStringDisabled](http://msdn.microsoft.com/en-us/library/system.windows.forms.controlpaint.drawstringdisabled.aspx) method; it might be something helpful. I've used it when overriding the OnPaint event for custom controls. ``` ControlPaint.DrawStringDisabled(g, this.Text, this.Font, Color.Transparent, new Rectangle(CustomStringWidth, 5, StringSize2.Width, StringSize2.Height), StringFormat.GenericTypographic); ```
136,132
<p>I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:</p> <pre><code>RichTextBox rtb = new RichTextBox(); Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold); rtb.Text = "sometext"; rtb.SelectAll() rtb.SelectionFont = boldfont; rtb.SelectionIndent = 12; </code></pre> <p>There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?</p> <p>Edit: The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.</p>
[ { "answer_id": 136169, "author": "hova", "author_id": 2170, "author_profile": "https://Stackoverflow.com/users/2170", "pm_score": 2, "selected": false, "text": "<p>You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one o...
2008/09/25
[ "https://Stackoverflow.com/questions/136132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13776/" ]
I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so: ``` RichTextBox rtb = new RichTextBox(); Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold); rtb.Text = "sometext"; rtb.SelectAll() rtb.SelectionFont = boldfont; rtb.SelectionIndent = 12; ``` There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas? Edit: The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.
You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one of the common mistakes I used to make which made it seem "inelegant"
136,146
<p>Examples:</p> <pre><code>"1" yes "-1" yes "- 3" no "1.2" yes "1.2.3" no "7e4" no (though in some cases you may want to allow scientific notation) ".123" yes "123." yes "." no "-.5" yes "007" yes "00" yes </code></pre>
[ { "answer_id": 136157, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 2, "selected": false, "text": "<p>This allows for optional \"+\" and \"-\" in front. And allows trailing or initial whitespace.</p>\n\n<pre><code>/^\\s*[+...
2008/09/25
[ "https://Stackoverflow.com/questions/136146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
Examples: ``` "1" yes "-1" yes "- 3" no "1.2" yes "1.2.3" no "7e4" no (though in some cases you may want to allow scientific notation) ".123" yes "123." yes "." no "-.5" yes "007" yes "00" yes ```
This allows for optional "+" and "-" in front. And allows trailing or initial whitespace. ``` /^\s*[+-]?(?:\d+\.?\d*|\d*\.\d+)\s*$/ ```
136,168
<p>I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom.</p> <p>So I need a <code>tail()</code> method that can read <code>n</code> lines from the bottom and support an offset. This is hat I came up with:</p> <pre><code>def tail(f, n, offset=0): &quot;&quot;&quot;Reads a n lines from f with an offset of offset lines.&quot;&quot;&quot; avg_line_length = 74 to_read = n + offset while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) &gt;= to_read or pos == 0: return lines[-to_read:offset and -offset or None] avg_line_length *= 1.3 </code></pre> <p>Is this a reasonable approach? What is the recommended way to tail log files with offsets?</p>
[ { "answer_id": 136280, "author": "Mark", "author_id": 16363, "author_profile": "https://Stackoverflow.com/users/16363", "pm_score": 7, "selected": false, "text": "<p>Assumes a unix-like system on Python 2 you can do:</p>\n\n<pre><code>import os\ndef tail(f, n, offset=0):\n stdin,stdout ...
2008/09/25
[ "https://Stackoverflow.com/questions/136168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19990/" ]
I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom. So I need a `tail()` method that can read `n` lines from the bottom and support an offset. This is hat I came up with: ``` def tail(f, n, offset=0): """Reads a n lines from f with an offset of offset lines.""" avg_line_length = 74 to_read = n + offset while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: return lines[-to_read:offset and -offset or None] avg_line_length *= 1.3 ``` Is this a reasonable approach? What is the recommended way to tail log files with offsets?
The code I ended up using. I think this is the best so far: ``` def tail(f, n, offset=None): """Reads a n lines from f with an offset of offset lines. The return value is a tuple in the form ``(lines, has_more)`` where `has_more` is an indicator that is `True` if there are more lines in the file. """ avg_line_length = 74 to_read = n + (offset or 0) while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: return lines[-to_read:offset and -offset or None], \ len(lines) > to_read or pos > 0 avg_line_length *= 1.3 ```
136,172
<p>I have a single-threaded application that loads several assemblies at runtime using the following:</p> <pre><code>objDLL = Assembly.LoadFrom(strDLLs[i]); </code></pre> <p>I would like the assemblies loaded in this manner to use the same log4net.ILog reference as the rest of the assemblies do. But it appears the runtime loaded assemblies have a different reference altogether and need their own configuration. Does anyone know if a single log4net.ILog can be used across assemblies loaded at runtime using a .NET interface?</p> <p>Here is the log4net.ILog creation and supporting code in the Program class:</p> <pre><code> // Configure log4net using the .config file [assembly: log4net.Config.XmlConfigurator(Watch = true)] public static class Program { private static log4net.ILog m_Log = null; [STAThread] public static void Main(string[] args) { try { m_Log = log4net.LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } } </code></pre>
[ { "answer_id": 136305, "author": "JPrescottSanders", "author_id": 19444, "author_profile": "https://Stackoverflow.com/users/19444", "pm_score": 2, "selected": false, "text": "<p>If all your assemblies implement a common interface, then you could have a property or constructor parameter t...
2008/09/25
[ "https://Stackoverflow.com/questions/136172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a single-threaded application that loads several assemblies at runtime using the following: ``` objDLL = Assembly.LoadFrom(strDLLs[i]); ``` I would like the assemblies loaded in this manner to use the same log4net.ILog reference as the rest of the assemblies do. But it appears the runtime loaded assemblies have a different reference altogether and need their own configuration. Does anyone know if a single log4net.ILog can be used across assemblies loaded at runtime using a .NET interface? Here is the log4net.ILog creation and supporting code in the Program class: ``` // Configure log4net using the .config file [assembly: log4net.Config.XmlConfigurator(Watch = true)] public static class Program { private static log4net.ILog m_Log = null; [STAThread] public static void Main(string[] args) { try { m_Log = log4net.LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); } } } ```
If all your assemblies implement a common interface, then you could have a property or constructor parameter that allows you to pass your local instance of ILog to the dynamically loaded assemblies.
136,178
<p>I'm running <a href="http://www.git-scm.com/docs/git-diff" rel="noreferrer">git-diff</a> on a file, but the change is at the end of a long line.</p> <p>If I use cursor keys to move right, it loses colour-coding&mdash;and worse the lines don't line up&mdash;making it harder to track the change.</p> <p>Is there a way to prevent that problem or to simply make the lines wrap instead?</p> <p>I'm running Git 1.5.5 via mingw32.</p>
[ { "answer_id": 136396, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 2, "selected": false, "text": "<p>Not a perfect solution, but <code>gitk</code> and <code>git-gui</code> can both show this information,\nand have s...
2008/09/25
[ "https://Stackoverflow.com/questions/136178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ]
I'm running [git-diff](http://www.git-scm.com/docs/git-diff) on a file, but the change is at the end of a long line. If I use cursor keys to move right, it loses colour-coding—and worse the lines don't line up—making it harder to track the change. Is there a way to prevent that problem or to simply make the lines wrap instead? I'm running Git 1.5.5 via mingw32.
The display of the output of `git diff` is handled by whatever pager you are using. Commonly, under Linux, `less` would be used. You can tell git to use a different pager by setting the `GIT_PAGER` environment variable. If you don't mind about paging (for example, your terminal allows you to scroll back) you might try explicitly setting `GIT_PAGER` to empty to stop it using a pager. Under Linux: ```sh $ GIT_PAGER='' git diff ``` Without a pager, the lines will wrap. If your terminal doesn't support coloured output, you can also turn this off using either the `--no-color` argument, or putting an entry in the color section of your git config file. ```sh $ GIT_PAGER='' git diff --no-color ```
136,191
<p>Let's say I want to write a regular expression to change all <code>&lt;abc&gt;</code>, <code>&lt;def&gt;</code>, and <code>&lt;ghi&gt;</code> tags into <code>&lt;xyz&gt;</code> tags.. and I also want to change their closing tags to <code>&lt;/xyz&gt;</code>. This seems like a reasonable regex (ignore the backticks; StackOverflow has trouble with the less-than signs if I don't include them):</p> <pre><code>`s!&lt;(/)?(abc|def|ghi)&gt;!&lt;${1}xyz&gt;!g;` </code></pre> <p>And it works, too. The only problem is that for opening tags, the optional $1 variable gets assigned undef, and so I get a "Use of uninitialized value..." warning.</p> <p>What's an elegant way to fix this? I'd rather not make this into two separate regexs, one for opening tags and another for closing tags, because then there are two copies of the taglist that need to be maintained, instead of just one.</p> <p><strong>Edit:</strong> I know I could just turn off warnings in this region of the code, but I don't consider that "elegant".</p>
[ { "answer_id": 136267, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 1, "selected": false, "text": "<p>You could just make your first match be <code>(&lt;/?)</code>, and get rid of the hard-coded <code>&lt;</code> on t...
2008/09/25
[ "https://Stackoverflow.com/questions/136191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
Let's say I want to write a regular expression to change all `<abc>`, `<def>`, and `<ghi>` tags into `<xyz>` tags.. and I also want to change their closing tags to `</xyz>`. This seems like a reasonable regex (ignore the backticks; StackOverflow has trouble with the less-than signs if I don't include them): ``` `s!<(/)?(abc|def|ghi)>!<${1}xyz>!g;` ``` And it works, too. The only problem is that for opening tags, the optional $1 variable gets assigned undef, and so I get a "Use of uninitialized value..." warning. What's an elegant way to fix this? I'd rather not make this into two separate regexs, one for opening tags and another for closing tags, because then there are two copies of the taglist that need to be maintained, instead of just one. **Edit:** I know I could just turn off warnings in this region of the code, but I don't consider that "elegant".
Move the question mark inside the capturing bracket. That way $1 will always be defined, but may be a zero-length string.
136,195
<p>We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser. </p> <p>We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object. </p> <p>However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Test&lt;/TITLE&gt; &lt;SCRIPT type="text/javascript"&gt; var field = 'hello world'; &lt;/SCRIPT&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;input type="button" value="See field" onclick="javascript:alert(field);"/&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>We want to access the <em>field</em> variable and assign a value to it. In VB6 the code for this was pretty straightforward:</p> <pre><code>doc.Script.field = 'newValue' </code></pre> <p>However, in C# we've had to resort to other tricks, like this: </p> <pre><code>Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null); </code></pre> <p>The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".</p> <p>That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable <code>field</code>. </p> <p>Has anyone had any experience doing this type of operation before?</p>
[ { "answer_id": 136213, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 0, "selected": false, "text": "<p>The usual method we use is to add a hidden text input box (the ASP.Net control version) on the page. That way you can ...
2008/09/25
[ "https://Stackoverflow.com/questions/136195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14177/" ]
We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser. We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object. However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this: ``` <HTML> <HEAD> <TITLE>Test</TITLE> <SCRIPT type="text/javascript"> var field = 'hello world'; </SCRIPT> </HEAD> <BODY> <input type="button" value="See field" onclick="javascript:alert(field);"/> </BODY> </HTML> ``` We want to access the *field* variable and assign a value to it. In VB6 the code for this was pretty straightforward: ``` doc.Script.field = 'newValue' ``` However, in C# we've had to resort to other tricks, like this: ``` Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null); ``` The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue". That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable `field`. Has anyone had any experience doing this type of operation before?
These two articles helped us find a solution to our problem. They outline the basics of what one needs to know: [Microsoft Web Browser Automation using C#](http://www.codeproject.com/KB/cs/mshtml_automation.aspx) [Using MSHTML Advanced Hosting Interfaces](http://www.codeproject.com/KB/cs/advhost.aspx?target=idochostuihandler) So we implemented a DocHostUIHandler interface and that allowed us to set a UIHandler, allowing us to reference the method from Javascript.
136,204
<p>Not really getting the point of the map function. Can anyone explain with examples its use?</p> <p>Are there any performance benefits to using this instead of a loop or is it just sugar?</p>
[ { "answer_id": 136228, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 7, "selected": true, "text": "<p>Any time you want to generate a list based another list:</p>\n\n<pre><code># Double all elements of a list\nmy @do...
2008/09/25
[ "https://Stackoverflow.com/questions/136204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
Not really getting the point of the map function. Can anyone explain with examples its use? Are there any performance benefits to using this instead of a loop or is it just sugar?
Any time you want to generate a list based another list: ``` # Double all elements of a list my @double = map { $_ * 2 } (1,2,3,4,5); # @double = (2,4,6,8,10); ``` Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute: ``` # @user_objects is a list of objects having a unique_id() method my %users = map { $_->unique_id() => $_ } @user_objects; # %users = ( $id => $obj, $id => $obj, ...); ``` It's a really general purpose tool, you have to just start using it to find good uses in your applications. Some might prefer verbose looping code for readability purposes, but personally, I find `map` more readable.
136,233
<p>in tcsh I'm trying to redirect STDERR from a command from my .aliases file.</p> <p>I found that I can redirect STDERR from the command line like this. . .</p> <pre><code>$ (xemacs &gt; /dev/tty) &gt;&amp; /dev/null </code></pre> <p>. . . but when I put this in my .aliases file I get an alias loop. . .</p> <pre><code>$ cat .aliases alias xemacs '(xemacs &gt; /dev/tty ) &gt;&amp; /dev/null' $ xemacs &amp; Alias loop. $ </code></pre> <p>. . . so I put a backslash before the command in .aliases, which allows the command to run. . .</p> <pre><code>$ cat .aliases alias xemacs '(\xemacs &gt; /dev/tty ) &gt;&amp; /dev/null' $ xemacs &amp; [1] 17295 $ </code></pre> <p>. . . but now I can't give the command any arguments:</p> <pre><code>$ xemacs foo.txt &amp; Badly placed ()'s. [1] Done ( \xemacs &gt; /dev/tty ) &gt;&amp; /dev/null $ </code></pre> <p>Can anyone offer any solutions? Thank you in advance!</p> <hr> <p>UPDATE: I'm still curious if it's possible to redirect STDERR in tcsh from .aliases, but as has been suggested here, I ended up with a shell script:</p> <pre><code>#!/bin/sh # wrapper script to suppress messages sent to STDERR on launch # from the command line. /usr/bin/xemacs "$@" 2&gt;/dev/null </code></pre>
[ { "answer_id": 136313, "author": "Dominic Eidson", "author_id": 5042, "author_profile": "https://Stackoverflow.com/users/5042", "pm_score": 4, "selected": true, "text": "<p>I suspect this is a case where NOT using an alias is the best option - try using a shell script instead:</p>\n\n<pr...
2008/09/25
[ "https://Stackoverflow.com/questions/136233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
in tcsh I'm trying to redirect STDERR from a command from my .aliases file. I found that I can redirect STDERR from the command line like this. . . ``` $ (xemacs > /dev/tty) >& /dev/null ``` . . . but when I put this in my .aliases file I get an alias loop. . . ``` $ cat .aliases alias xemacs '(xemacs > /dev/tty ) >& /dev/null' $ xemacs & Alias loop. $ ``` . . . so I put a backslash before the command in .aliases, which allows the command to run. . . ``` $ cat .aliases alias xemacs '(\xemacs > /dev/tty ) >& /dev/null' $ xemacs & [1] 17295 $ ``` . . . but now I can't give the command any arguments: ``` $ xemacs foo.txt & Badly placed ()'s. [1] Done ( \xemacs > /dev/tty ) >& /dev/null $ ``` Can anyone offer any solutions? Thank you in advance! --- UPDATE: I'm still curious if it's possible to redirect STDERR in tcsh from .aliases, but as has been suggested here, I ended up with a shell script: ``` #!/bin/sh # wrapper script to suppress messages sent to STDERR on launch # from the command line. /usr/bin/xemacs "$@" 2>/dev/null ```
I suspect this is a case where NOT using an alias is the best option - try using a shell script instead: ``` #!/bin/tcsh (xemacs $* > /dev/tty ) >& /dev/null ```
136,278
<p>For example, I rarely need:</p> <pre><code>using System.Text; </code></pre> <p>but it's always there by default. I assume the application will use more memory if your code contains unnecessary <a href="http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx" rel="noreferrer">using directives</a>. But is there anything else I should be aware of?</p> <p>Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?</p> <hr> <p><em>Edit: Note that this question is not about the unrelated concept called a <a href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx" rel="noreferrer">using statement</a>, designed to help one manage resources by ensuring that when an object goes out of scope, its <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx" rel="noreferrer">IDisposable.Dispose</a> method is called. See <a href="https://stackoverflow.com/questions/75401/uses-of-using-in-c">Uses of "using" in C#</a>.</em></p>
[ { "answer_id": 136285, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 9, "selected": true, "text": "<p>It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that us...
2008/09/25
[ "https://Stackoverflow.com/questions/136278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ]
For example, I rarely need: ``` using System.Text; ``` but it's always there by default. I assume the application will use more memory if your code contains unnecessary [using directives](http://msdn.microsoft.com/en-us/library/aa664764(VS.71).aspx). But is there anything else I should be aware of? Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files? --- *Edit: Note that this question is not about the unrelated concept called a [using statement](http://msdn.microsoft.com/en-us/library/yh598w02.aspx), designed to help one manage resources by ensuring that when an object goes out of scope, its [IDisposable.Dispose](http://msdn.microsoft.com/en-us/library/system.idisposable.dispose.aspx) method is called. See [Uses of "using" in C#](https://stackoverflow.com/questions/75401/uses-of-using-in-c).*
It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded. Mainly, it's just to clean up for personal preference.
136,288
<p>I have this PHP code that I am trying to use to let a user edit a news record in a form and then when they hit the submit button, it will update the record in a database. The problem is that everything works but the record is not actually updated in the database.</p> <p>Could someone look at my code and see where a problem could occur?</p> <pre><code>&lt;?php $title = "Edit News"; include("../includes/header.php"); include("../includes/database.php"); $done = false; $expected = array('newstitle', 'newscontent', 'id'); if ($_GET &amp;&amp; !$_POST) { if (isset($_GET['id']) &amp;&amp; is_numeric($_GET['id'])) { $id = $_GET['id']; } else { $id = NULL; } if ($id) { $sql = "SELECT * FROM news WHERE id = $id"; $result = mysql_query($sql) or die ("Error connecting to database..."); $row = mysql_fetch_assoc($result); } // if form has been submitted, update record if (array_key_exists('update', $_POST)) { // prepare expected items for insertion into database foreach ($_POST as $key =&gt; $value) { if (in_array($key, $expected)) { ${$key} = mysql_real_escape_string($value); } } // abandon the process if primary key invalid if (!is_numeric($id)) { die('Invalid request'); } // prepare the SQL query $query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id"; // submit the query $done = mysql_query($query) or die("Error connecting to database..."); } } // redirect page if $id is invalid if ($done) { header("Location: $ROOT/admin/listnews.php"); exit; } ?&gt; </code></pre>
[ { "answer_id": 136316, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 0, "selected": false, "text": "<p>If you run that UPDATE from the mysql cli with the same data the user sends does it update?</p>\n\n<p>If not check for esc...
2008/09/25
[ "https://Stackoverflow.com/questions/136288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have this PHP code that I am trying to use to let a user edit a news record in a form and then when they hit the submit button, it will update the record in a database. The problem is that everything works but the record is not actually updated in the database. Could someone look at my code and see where a problem could occur? ``` <?php $title = "Edit News"; include("../includes/header.php"); include("../includes/database.php"); $done = false; $expected = array('newstitle', 'newscontent', 'id'); if ($_GET && !$_POST) { if (isset($_GET['id']) && is_numeric($_GET['id'])) { $id = $_GET['id']; } else { $id = NULL; } if ($id) { $sql = "SELECT * FROM news WHERE id = $id"; $result = mysql_query($sql) or die ("Error connecting to database..."); $row = mysql_fetch_assoc($result); } // if form has been submitted, update record if (array_key_exists('update', $_POST)) { // prepare expected items for insertion into database foreach ($_POST as $key => $value) { if (in_array($key, $expected)) { ${$key} = mysql_real_escape_string($value); } } // abandon the process if primary key invalid if (!is_numeric($id)) { die('Invalid request'); } // prepare the SQL query $query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id"; // submit the query $done = mysql_query($query) or die("Error connecting to database..."); } } // redirect page if $id is invalid if ($done) { header("Location: $ROOT/admin/listnews.php"); exit; } ?> ```
``` if ($_GET && !$_POST) { ``` ... ``` if (array_key_exists('update', $_POST)) { ``` Won't that ensure the update code never fires?
136,362
<p>Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness.</p> <p>Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try:</p> <pre><code>mvn compile </code></pre> <p>inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path.</p> <p>If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land.</p> <p>I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works.</p>
[ { "answer_id": 136395, "author": "Chris Vest", "author_id": 13251, "author_profile": "https://Stackoverflow.com/users/13251", "pm_score": 1, "selected": false, "text": "<p>I think the best way to handle it is to make Bar a Maven project just like Foo, and then <code>mvn install</code> it...
2008/09/25
[ "https://Stackoverflow.com/questions/136362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8178/" ]
Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness. Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try: ``` mvn compile ``` inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path. If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land. I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works.
Maybe you are referencing the other project via Eclipse configure-> build path only. This works as long as you use Eclipse to build your project. Try running first `mvn install` in project Bar (in order to put Bar in your Maven repository), and then add the dependency to Foo's pom.xml. That should work!.
136,401
<p>This could be weird, Have you ever come across a blog which you wanted to read in the chronological order? And that blog could be old, with several hundred posts. When i add this feed to my feed reader, say googlereader, the latest feed comes on top and as i scroll down further, the older posts appear. This could be frustrating if you want to read it from the beginning. Is there any reader that does this? Or, i would love to do this as a pet project, (preferably in c#), how exactly should i go about it? Also, are there any .NET libraries which i can use to work on RSS feeds? I have not done any RSS feed programming before.</p> <p><strong>EDIT</strong> I would like to know if there are any technical limitations to this. This was jsut one interesting problem that I encountered that i thought could be tackled programmatically.</p>
[ { "answer_id": 136416, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "<p>In Google Reader, when you're reading a feed, there is a \"Feed settings...\" menu with the options: \"Sort b...
2008/09/25
[ "https://Stackoverflow.com/questions/136401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ]
This could be weird, Have you ever come across a blog which you wanted to read in the chronological order? And that blog could be old, with several hundred posts. When i add this feed to my feed reader, say googlereader, the latest feed comes on top and as i scroll down further, the older posts appear. This could be frustrating if you want to read it from the beginning. Is there any reader that does this? Or, i would love to do this as a pet project, (preferably in c#), how exactly should i go about it? Also, are there any .NET libraries which i can use to work on RSS feeds? I have not done any RSS feed programming before. **EDIT** I would like to know if there are any technical limitations to this. This was jsut one interesting problem that I encountered that i thought could be tackled programmatically.
If you do decide to roll your own C# application to do this, it is very straightforward in the current version of the .NET Framework. Look for the [System.ServiceModel.Syndication](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.aspx) namespace. That has classes related to RSS and Atom feeds. I wrote some code recently that generates a feed from a database using these classes, and adds geocodes to the feed items. I had the same problem where i needed to reverse the order of the items in the feed, because my database query returned them in the opposite order I wanted my users to see. What I did was to simply hold the list of [SyndicationItem](http://msdn.microsoft.com/en-us/library/system.servicemodel.syndication.syndicationitem.aspx) objects for the feed in my own `List<SyndicationItem>` data structure until right before I want to write the feed to disk. Then I would do something like this: ``` private SyndicationFeed m_feed; private List<SyndicationItem> m_items; ...snip... m_items.Reverse(); m_feed.Items = m_items; ```
136,413
<p>I have a Flex application where I'm using a Canvas to contain several other components. On that Canvas there is a Button which is used to invoke a particular flow through the system. Clicking anywhere else on the Canvas should cause cause a details pane to appear showing more information about the record represented by this control.</p> <p>The problem I'm having is that because the button sits inside the Canvas any time the user clicks the Button the click event is fired on both the Button and the Canvas. Is there any way to avoid having the click event fired on the Canvas object if the user clicks on an area covered up by another component?</p> <p>I've created a simple little test application to demonstrate the problem:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"&gt; &lt;mx:Script&gt; &lt;![CDATA[ private function onCanvasClick(event:Event):void { text.text = text.text + "\n" + "Canvas Clicked"; } private function onButtonClick(event:Event):void { text.text = text.text + "\n" + "Button Clicked"; } ]]&gt; &lt;/mx:Script&gt; &lt;mx:Canvas x="97" y="91" width="200" height="200" backgroundColor="red" click="onCanvasClick(event)"&gt; &lt;mx:Button x="67" y="88" label="Button" click="onButtonClick(event)"/&gt; &lt;/mx:Canvas&gt; &lt;mx:Text id="text" x="97" y="330" text="Text" width="200" height="129"/&gt; &lt;/mx:Application&gt; </code></pre> <p>As it stands when you click the button you will see two entries made in the text box, "Button Clicked" followed by "Canvas Clicked" even though the mouse was clicked only once.</p> <p>I'd like to find a way that I could avoid having the second entry made such that when I click the Button only the "Button Clicked" entry is made, but if I were to click anywhere else in the Canvas the "Canvas Clicked" entry would still appear.</p>
[ { "answer_id": 136569, "author": "Laplie Anderson", "author_id": 14204, "author_profile": "https://Stackoverflow.com/users/14204", "pm_score": 4, "selected": true, "text": "<p>The event continues on because event.bubbles is set to true. This means everything in the display heirarchy get...
2008/09/25
[ "https://Stackoverflow.com/questions/136413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1247/" ]
I have a Flex application where I'm using a Canvas to contain several other components. On that Canvas there is a Button which is used to invoke a particular flow through the system. Clicking anywhere else on the Canvas should cause cause a details pane to appear showing more information about the record represented by this control. The problem I'm having is that because the button sits inside the Canvas any time the user clicks the Button the click event is fired on both the Button and the Canvas. Is there any way to avoid having the click event fired on the Canvas object if the user clicks on an area covered up by another component? I've created a simple little test application to demonstrate the problem: ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"> <mx:Script> <![CDATA[ private function onCanvasClick(event:Event):void { text.text = text.text + "\n" + "Canvas Clicked"; } private function onButtonClick(event:Event):void { text.text = text.text + "\n" + "Button Clicked"; } ]]> </mx:Script> <mx:Canvas x="97" y="91" width="200" height="200" backgroundColor="red" click="onCanvasClick(event)"> <mx:Button x="67" y="88" label="Button" click="onButtonClick(event)"/> </mx:Canvas> <mx:Text id="text" x="97" y="330" text="Text" width="200" height="129"/> </mx:Application> ``` As it stands when you click the button you will see two entries made in the text box, "Button Clicked" followed by "Canvas Clicked" even though the mouse was clicked only once. I'd like to find a way that I could avoid having the second entry made such that when I click the Button only the "Button Clicked" entry is made, but if I were to click anywhere else in the Canvas the "Canvas Clicked" entry would still appear.
The event continues on because event.bubbles is set to true. This means everything in the display heirarchy gets the event. To stop the event from continuing, you call ``` event.stopImmediatePropagation() ```
136,419
<p>I need to determine the current year in Java as an integer. I could just use <code>java.util.Date()</code>, but it is deprecated.</p>
[ { "answer_id": 136434, "author": "cagcowboy", "author_id": 19629, "author_profile": "https://Stackoverflow.com/users/19629", "pm_score": 11, "selected": true, "text": "<p>For Java 8 onwards:</p>\n<pre><code>int year = Year.now().getValue();\n</code></pre>\n<p>For older version of Java:</...
2008/09/25
[ "https://Stackoverflow.com/questions/136419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/318/" ]
I need to determine the current year in Java as an integer. I could just use `java.util.Date()`, but it is deprecated.
For Java 8 onwards: ``` int year = Year.now().getValue(); ``` For older version of Java: ``` int year = Calendar.getInstance().get(Calendar.YEAR); ```
136,432
<p>I have a client/server system that performs communication using XML transferred using HTTP requests and responses with the client using Perl's LWP and the server running Perl's CGI.pm through Apache. In addition the stream is encrypted using SSL with certificates for both the server and all clients.</p> <p>This system works well, except that periodically the client needs to send really large amounts of data. An obvious solution would be to compress the data on the client side, send it over, and decompress it on the server. Rather than implement this myself, I was hoping to use Apache's mod_deflate's "Input Decompression" as described <a href="http://httpd.apache.org/docs/2.0/mod/mod_deflate.html" rel="nofollow noreferrer">here</a>.</p> <p>The description warns:</p> <blockquote> <p>If you evaluate the request body yourself, don't trust the Content-Length header! The Content-Length header reflects the length of the incoming data from the client and not the byte count of the decompressed data stream.</p> </blockquote> <p>So if I provide a Content-Length value which matches the compressed data size, the data is truncated. This is because mod_deflate decompresses the stream, but CGI.pm only reads to the Content-Length limit.</p> <p>Alternatively, if I try to outsmart it and override the Content-Length header with the decompressed data size, LWP complains and resets the value to the compressed length, leaving me with the same problem.</p> <p>Finally, I attempted to hack the part of LWP which does the correction. The original code is:</p> <pre><code> # Set (or override) Content-Length header my $clen = $request_headers-&gt;header('Content-Length'); if (defined($$content_ref) &amp;&amp; length($$content_ref)) { $has_content = length($$content_ref); if (!defined($clen) || $clen ne $has_content) { if (defined $clen) { warn "Content-Length header value was wrong, fixed"; hlist_remove(\@h, 'Content-Length'); } push(@h, 'Content-Length' =&gt; $has_content); } } elsif ($clen) { warn "Content-Length set when there is no content, fixed"; hlist_remove(\@h, 'Content-Length'); } </code></pre> <p>And I changed the push line to:</p> <pre><code> push(@h, 'Content-Length' =&gt; $clen); </code></pre> <p>Unfortunately this causes some problem where content (truncated or not) doesn't even get to my CGI script.</p> <p>Has anyone made this work? I found <a href="http://hype-free.blogspot.com/2007/07/compressed-http.html" rel="nofollow noreferrer">this</a> which does compression on a file before uploading, but not compressing a generic request.</p>
[ { "answer_id": 137279, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": -1, "selected": false, "text": "<p>I am not sure if I am following you with what you want, but I have a custom get/post module, that I use to do some non st...
2008/09/25
[ "https://Stackoverflow.com/questions/136432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22410/" ]
I have a client/server system that performs communication using XML transferred using HTTP requests and responses with the client using Perl's LWP and the server running Perl's CGI.pm through Apache. In addition the stream is encrypted using SSL with certificates for both the server and all clients. This system works well, except that periodically the client needs to send really large amounts of data. An obvious solution would be to compress the data on the client side, send it over, and decompress it on the server. Rather than implement this myself, I was hoping to use Apache's mod\_deflate's "Input Decompression" as described [here](http://httpd.apache.org/docs/2.0/mod/mod_deflate.html). The description warns: > > If you evaluate the request body yourself, don't trust the Content-Length header! The Content-Length header reflects the length of the incoming data from the client and not the byte count of the decompressed data stream. > > > So if I provide a Content-Length value which matches the compressed data size, the data is truncated. This is because mod\_deflate decompresses the stream, but CGI.pm only reads to the Content-Length limit. Alternatively, if I try to outsmart it and override the Content-Length header with the decompressed data size, LWP complains and resets the value to the compressed length, leaving me with the same problem. Finally, I attempted to hack the part of LWP which does the correction. The original code is: ``` # Set (or override) Content-Length header my $clen = $request_headers->header('Content-Length'); if (defined($$content_ref) && length($$content_ref)) { $has_content = length($$content_ref); if (!defined($clen) || $clen ne $has_content) { if (defined $clen) { warn "Content-Length header value was wrong, fixed"; hlist_remove(\@h, 'Content-Length'); } push(@h, 'Content-Length' => $has_content); } } elsif ($clen) { warn "Content-Length set when there is no content, fixed"; hlist_remove(\@h, 'Content-Length'); } ``` And I changed the push line to: ``` push(@h, 'Content-Length' => $clen); ``` Unfortunately this causes some problem where content (truncated or not) doesn't even get to my CGI script. Has anyone made this work? I found [this](http://hype-free.blogspot.com/2007/07/compressed-http.html) which does compression on a file before uploading, but not compressing a generic request.
I don't think you can change the Content-Length like that. It would confuse Apache, because mod\_deflate wouldn't know how much compressed data to read. What about having the client add an X-Uncompressed-Length header, and then use a modified version of CGI.pm that uses X-Uncompressed-Length (if present) instead of Content-Length? (Actually, you probably don't need to modify CGI.pm. Just set `$ENV{'CONTENT_LENGTH'}` to the appropriate value before initializing the CGI object or calling any CGI functions.) Or, use a lower-level module that uses the bucket brigade to tell how much data to read.
136,435
<p>How to allow <code>TextBlock</code>'s text to be selectable?</p> <p>I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable?</p>
[ { "answer_id": 136675, "author": "Bruce", "author_id": 6310, "author_profile": "https://Stackoverflow.com/users/6310", "pm_score": 4, "selected": false, "text": "<p>I'm not sure if you can make a TextBlock selectable, but another option would be to use a RichTextBox - it is like a TextBo...
2008/09/25
[ "https://Stackoverflow.com/questions/136435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1133/" ]
How to allow `TextBlock`'s text to be selectable? I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable?
Use a `TextBox` with these settings instead to make it read only and to look like a `TextBlock` control. ``` <TextBox Background="Transparent" BorderThickness="0" Text="{Binding Text, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap" /> ```
136,436
<p>I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'. </p> <p>I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up?</p> <p>Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for. </p> <p>Thanks.</p>
[ { "answer_id": 136675, "author": "Bruce", "author_id": 6310, "author_profile": "https://Stackoverflow.com/users/6310", "pm_score": 4, "selected": false, "text": "<p>I'm not sure if you can make a TextBlock selectable, but another option would be to use a RichTextBox - it is like a TextBo...
2008/09/25
[ "https://Stackoverflow.com/questions/136436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/424554/" ]
I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'. I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up? Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for. Thanks.
Use a `TextBox` with these settings instead to make it read only and to look like a `TextBlock` control. ``` <TextBox Background="Transparent" BorderThickness="0" Text="{Binding Text, Mode=OneWay}" IsReadOnly="True" TextWrapping="Wrap" /> ```
136,443
<p>We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block:</p> <pre><code>public PageSizer(string href, int index) { HRef = href; PageIndex = index; } </code></pre> <p>Copy and pasted from IE7, ends up like this:</p> <pre> public PageSizer(string href, int index){ HRef = href; PageIndex = index; } </pre> <p>Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this:</p> <pre><code>&lt;pre&gt;&lt;code&gt;public PageSizer(string href, int index) { HRef = href; PageIndex = index; } &lt;/code&gt;&lt;/pre&gt; </code></pre> <p>So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way?</p> <blockquote> <p>Update: <strong>this specifically has to do with <code>&lt;pre&gt;</code> <code>&lt;code&gt;</code> blocks that are being modified at runtime via JavaScript.</strong> The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from.</p> </blockquote>
[ { "answer_id": 136510, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": -1, "selected": false, "text": "<p>Remove the inner <code>&lt;code&gt;</code>. IE's copy/paste behavior could see that as an inline tag and forge...
2008/09/25
[ "https://Stackoverflow.com/questions/136443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block: ``` public PageSizer(string href, int index) { HRef = href; PageIndex = index; } ``` Copy and pasted from IE7, ends up like this: ``` public PageSizer(string href, int index){ HRef = href; PageIndex = index; } ``` Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this: ``` <pre><code>public PageSizer(string href, int index) { HRef = href; PageIndex = index; } </code></pre> ``` So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way? > > Update: **this specifically has to do with `<pre>` `<code>` blocks that are being modified at runtime via JavaScript.** The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from. > > >
It seems that this is a known bug for IE6 and prettify.js has a workaround for it. Specifically it replaces the BR tags with '\r\n'. By modifying the check to allow for IE6 or 7 then the cut-and-paste will work correctly from IE7, but it will render with a *newline* followed by a *space*. By checking for IE7 and providing just a '\r' instead of a '\r\n' it will continue to cut-and-paste and render correctly. Add this code to prettify.js: ``` function _pr_isIE7() { var isIE7 = navigator && navigator.userAgent && /\bMSIE 7\./.test(navigator.userAgent); _pr_isIE7 = function () { return isIE7; }; return isIE7; } ``` and then modify the prettyPrint function as follows: ``` function prettyPrint(opt_whenDone) { var isIE6 = _pr_isIE6(); + var isIE7 = _pr_isIE7(); ``` ... ``` - if (isIE6 && cs.tagName === 'PRE') { + if ((isIE6 || isIE7) && cs.tagName === 'PRE') { var lineBreaks = cs.getElementsByTagName('br'); + var newline; + if (isIE6) { + newline = '\r\n'; + } else { + newline = '\r'; + } for (var j = lineBreaks.length; --j >= 0;) { var lineBreak = lineBreaks[j]; lineBreak.parentNode.replaceChild( - document.createTextNode('\r\n'), lineBreak); + document.createTextNode(newline), lineBreak); } ``` You can see a [working example here](http://andrjohn.myzen.co.uk/soTest/136443.html). **Note:** I haven't tested the original workaround in IE6, so I'm guessing it renders without the space caused by the '\n' that is seen in IE7, otherwise the fix is simpler.
136,444
<p>I'm working on an embedded linux system in C, I'm looking for the source code to the equivalet of SendARP in Windows. Any pointers?</p>
[ { "answer_id": 136492, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 0, "selected": false, "text": "<p>This may be of interest: <a href=\"http://cvs.linux-ha.org/viewcvs/viewcvs.cgi/linux-ha/resources/heartbeat/SendArp.in?re...
2008/09/25
[ "https://Stackoverflow.com/questions/136444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15797/" ]
I'm working on an embedded linux system in C, I'm looking for the source code to the equivalet of SendARP in Windows. Any pointers?
Take a look at [arping](http://freshmeat.net/projects/arping/). The quick and dirty way of sending an arp would be to do: ``` foo = system("/somepath/arping somehost"); ``` But a look through the arping source should be able to give you a better solution. For the all-out solution though, you can construct your own by hand and use either a raw socket or [libpcap](http://www.tcpdump.org/) to send it. --- btw. If all you're trying to do is force an arp to be sent (but necessarily from you) you could achieve that by deleting any arp entry that you already have for your host. The next access to that address will require an arp to be sent. eg. /usr/sbin/arp -d destination\_host\_ip
136,456
<p>I need to explain to the client why dupes are showing up between 2 supposedly different exams. It's been 20 years since Prob and Stats.</p> <p>I have a generated Multiple choice exam. There are 192 questions in the database, 100 are chosen at random (no dupes).</p> <p>Obviously, there is a 100% chance of there being at least 8 dupes between any two exams so generated. (Pigeonhole principle)</p> <p>How do I calculate the probability of there being 25 dupes? 50 dupes? 75 dupes?</p> <p>-- Edit after the fact -- I ran this through excel, taking sums of the probabilities from n-100, For this particular problem, the probabilities were</p> <pre><code>n P(n+ dupes) 40 97.5% 52 ~50% 61 ~0 </code></pre>
[ { "answer_id": 136471, "author": "Chris", "author_id": 19290, "author_profile": "https://Stackoverflow.com/users/19290", "pm_score": 0, "selected": false, "text": "<p>Its probably higher than you think. I won't attempt to duplicate this article: <a href=\"http://en.wikipedia.org/wiki/Bir...
2008/09/25
[ "https://Stackoverflow.com/questions/136456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18907/" ]
I need to explain to the client why dupes are showing up between 2 supposedly different exams. It's been 20 years since Prob and Stats. I have a generated Multiple choice exam. There are 192 questions in the database, 100 are chosen at random (no dupes). Obviously, there is a 100% chance of there being at least 8 dupes between any two exams so generated. (Pigeonhole principle) How do I calculate the probability of there being 25 dupes? 50 dupes? 75 dupes? -- Edit after the fact -- I ran this through excel, taking sums of the probabilities from n-100, For this particular problem, the probabilities were ``` n P(n+ dupes) 40 97.5% 52 ~50% 61 ~0 ```
Erm, this is really really hazy for me. But there are (192 choose 100) possible exams, right? And there are (100 choose N) ways of picking N dupes, each with (92 choose 100-N) ways of picking the rest of the questions, no? So isn't the probability of picking N dupes just: (100 choose N) \* (92 choose 100-N) / (192 choose 100) EDIT: So if you want the chances of *N or more* dupes instead of exactly N, you have to sum the top half of that fraction for all values of N from the minimum number of dupes up to 100. Errrr, maybe...
136,458
<p>How would I have a <a href="http://en.wikipedia.org/wiki/JavaScript" rel="noreferrer">JavaScript</a> action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used? </p> <p>It would also be nice if the back button would reload the original URL.</p> <p>I am trying to record JavaScript state in the URL.</p>
[ { "answer_id": 136496, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 4, "selected": false, "text": "<p>I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For exam...
2008/09/25
[ "https://Stackoverflow.com/questions/136458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ]
How would I have a [JavaScript](http://en.wikipedia.org/wiki/JavaScript) action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used? It would also be nice if the back button would reload the original URL. I am trying to record JavaScript state in the URL.
With HTML 5, use the [`history.pushState` function](http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html). As an example: ``` <script type="text/javascript"> var stateObj = { foo: "bar" }; function change_my_url() { history.pushState(stateObj, "page 2", "bar.html"); } var link = document.getElementById('click'); link.addEventListener('click', change_my_url, false); </script> ``` and a href: ``` <a href="#" id='click'>Click to change url to bar.html</a> ``` --- If you want to change the URL without adding an entry to the back button list, use `history.replaceState` instead.
136,467
<p>short:</p> <p>Is there a way in Ruby to DRY-ify this:</p> <pre><code>def entry_point_one begin do_something rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc =&gt; syn_err raise syn_err.exception(syn_err.message) end end def entry_point_two begin do_something_else rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc =&gt; syn_err raise syn_err.exception(syn_err.message) end end </code></pre> <p>longer:</p> <p>I'm building an interpreter. This interpreter can be called using different entry points. If I feed this interpreter a 'dirty' string, I expect it to raise an error. However, it would be nice if I don't get spammed by the by the entire back trace of every method called directly or indirectly by do_something, especially since the interpreter makes use of recursion.</p> <p>As you can see in the above snippet, I already know a way to re raise an error and thereby removing the back trace. What I would like do is remove the duplication in the above example. The closest I have come thus far is this:</p> <pre><code>def entry_point_one re_raise_known_exceptions {do_something} end def entry_point_two re_raise_known_exceptions {do_something_else} end def re_raise_known_exceptions yield rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc =&gt; syn_err raise syn_err.exception(syn_err.message) end </code></pre> <p>But that makes the method re-raise-known-exceptions show up in the back trace.</p> <p>edit: I guess what I want would be something like a C pre-processing macro</p>
[ { "answer_id": 136541, "author": "Patrick Huizinga", "author_id": 15200, "author_profile": "https://Stackoverflow.com/users/15200", "pm_score": 2, "selected": false, "text": "<p>while thinking about it a bit more, I came up with this:</p>\n\n<pre><code>interpreter_block {do_something}\n\...
2008/09/25
[ "https://Stackoverflow.com/questions/136467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15200/" ]
short: Is there a way in Ruby to DRY-ify this: ``` def entry_point_one begin do_something rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err raise syn_err.exception(syn_err.message) end end def entry_point_two begin do_something_else rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err raise syn_err.exception(syn_err.message) end end ``` longer: I'm building an interpreter. This interpreter can be called using different entry points. If I feed this interpreter a 'dirty' string, I expect it to raise an error. However, it would be nice if I don't get spammed by the by the entire back trace of every method called directly or indirectly by do\_something, especially since the interpreter makes use of recursion. As you can see in the above snippet, I already know a way to re raise an error and thereby removing the back trace. What I would like do is remove the duplication in the above example. The closest I have come thus far is this: ``` def entry_point_one re_raise_known_exceptions {do_something} end def entry_point_two re_raise_known_exceptions {do_something_else} end def re_raise_known_exceptions yield rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err raise syn_err.exception(syn_err.message) end ``` But that makes the method re-raise-known-exceptions show up in the back trace. edit: I guess what I want would be something like a C pre-processing macro
while thinking about it a bit more, I came up with this: ``` interpreter_block {do_something} def interpreter_block yield rescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc raise exc.exception(exc.message) end ``` Although it's still not quiet what I would like to have, at least now the extra entry in the back trace has become somewhat better looking.
136,474
<p>I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:</p> <pre><code>Vector itemsVector = getItems(); Collections.shuffle(itemsVector); itemsVector.setSize(5); </code></pre> <p>While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is</p> <pre><code>Vector itemsVector = getItems(); Random rand = new Random(System.currentTimeMillis()); // would make this static to the class List subsetList = new ArrayList(5); for (int i = 0; i &lt; 5; i++) { // be sure to use Vector.remove() or you may get the same item twice subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size()))); } </code></pre> <p>Any suggestions on better ways to draw out a random subset from a Collection?</p>
[ { "answer_id": 136513, "author": "qualidafial", "author_id": 13253, "author_profile": "https://Stackoverflow.com/users/13253", "pm_score": 2, "selected": false, "text": "<p>Your second solution of using Random to pick element seems sound, however:</p>\n\n<ul>\n<li><p>Depending on how sen...
2008/09/25
[ "https://Stackoverflow.com/questions/136474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4459/" ]
I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution: ``` Vector itemsVector = getItems(); Collections.shuffle(itemsVector); itemsVector.setSize(5); ``` While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is ``` Vector itemsVector = getItems(); Random rand = new Random(System.currentTimeMillis()); // would make this static to the class List subsetList = new ArrayList(5); for (int i = 0; i < 5; i++) { // be sure to use Vector.remove() or you may get the same item twice subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size()))); } ``` Any suggestions on better ways to draw out a random subset from a Collection?
Jon Bentley discusses this in either 'Programming Pearls' or 'More Programming Pearls'. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions - which is a useful saving when N << M. Knuth also discusses these algorithms - I believe that would be Vol 3 "Sorting and Searching", but my set is packed pending a move of house so I can't formally check that.
136,485
<p>I want to copy and paste text from a Office 2007 document (docx) into a textarea. On Window, using Firefox 3, there is additional jiberish that gets put into the field:</p> <pre><code>...Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 &lt;!--[if gte mso 9]&gt;... </code></pre> <p>Seems to be the style information and conditional comments from the newer document structure. Any ideas on how to parse this out, or prevent this from happening? Possibilities are Javascript on the front side, or Java on the back side.</p>
[ { "answer_id": 136567, "author": "Lincoln Johnson", "author_id": 13419, "author_profile": "https://Stackoverflow.com/users/13419", "pm_score": -1, "selected": false, "text": "<p>I find the easiest way to eliminate this random jibberish is to copy the text you want, paste it into notepad ...
2008/09/25
[ "https://Stackoverflow.com/questions/136485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21980/" ]
I want to copy and paste text from a Office 2007 document (docx) into a textarea. On Window, using Firefox 3, there is additional jiberish that gets put into the field: ``` ...Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 <!--[if gte mso 9]>... ``` Seems to be the style information and conditional comments from the newer document structure. Any ideas on how to parse this out, or prevent this from happening? Possibilities are Javascript on the front side, or Java on the back side.
Similar to Lincoln's idea, you can use [PureText](http://www.stevemiller.net/puretext/) to automate the process. Basically, you press its hotkey instead of `Ctrl`+`V` (I have mine set to `Win`+`V`), and it pastes the plain text version of whatever is on your clipboard. I'm not sure if that will remove the extra data that Office has added, but it's worth a try.
136,500
<p>I have a string in a node and I'd like to split the string on '?' and return the last item in the array.</p> <p>For example, in the block below:</p> <pre><code>&lt;a&gt; &lt;xsl:attribute name="href"&gt; /newpage.aspx?&lt;xsl:value-of select="someNode"/&gt; &lt;/xsl:attribute&gt; Link text &lt;/a&gt; </code></pre> <p>I'd like to split the <code>someNode</code> value.</p> <p>Edit: Here's the VB.Net that I use to load the Xsl for my Asp.Net page:</p> <pre><code>Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl") Dim myXsltSettings As New XsltSettings() Dim myXMLResolver As New XmlUrlResolver() myXsltSettings.EnableScript = True myXsltSettings.EnableDocumentFunction = True myXslDoc = New XslCompiledTransform(False) myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver) Dim myStringBuilder As New StringBuilder() Dim myXmlWriter As XmlWriter = Nothing Dim myXmlWriterSettings As New XmlWriterSettings() myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto myXmlWriterSettings.Indent = True myXmlWriterSettings.OmitXmlDeclaration = True myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings) myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter) Return myStringBuilder.ToString() </code></pre> <p><strong>Update:</strong> here's <a href="http://gist.github.com/360186" rel="noreferrer">an example of splitting XML on a particular node</a></p>
[ { "answer_id": 136531, "author": "Jacob", "author_id": 22107, "author_profile": "https://Stackoverflow.com/users/22107", "pm_score": 4, "selected": false, "text": "<p>If you can use XSLT 2.0 or higher, you can use <code>tokenize(string, separator)</code>: </p>\n\n<pre><code>tokenize(\"XP...
2008/09/25
[ "https://Stackoverflow.com/questions/136500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1414/" ]
I have a string in a node and I'd like to split the string on '?' and return the last item in the array. For example, in the block below: ``` <a> <xsl:attribute name="href"> /newpage.aspx?<xsl:value-of select="someNode"/> </xsl:attribute> Link text </a> ``` I'd like to split the `someNode` value. Edit: Here's the VB.Net that I use to load the Xsl for my Asp.Net page: ``` Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl") Dim myXsltSettings As New XsltSettings() Dim myXMLResolver As New XmlUrlResolver() myXsltSettings.EnableScript = True myXsltSettings.EnableDocumentFunction = True myXslDoc = New XslCompiledTransform(False) myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver) Dim myStringBuilder As New StringBuilder() Dim myXmlWriter As XmlWriter = Nothing Dim myXmlWriterSettings As New XmlWriterSettings() myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto myXmlWriterSettings.Indent = True myXmlWriterSettings.OmitXmlDeclaration = True myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings) myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter) Return myStringBuilder.ToString() ``` **Update:** here's [an example of splitting XML on a particular node](http://gist.github.com/360186)
Use a recursive method: ``` <xsl:template name="output-tokens"> <xsl:param name="list" /> <xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" /> <xsl:variable name="first" select="substring-before($newlist, ' ')" /> <xsl:variable name="remaining" select="substring-after($newlist, ' ')" /> <id> <xsl:value-of select="$first" /> </id> <xsl:if test="$remaining"> <xsl:call-template name="output-tokens"> <xsl:with-param name="list" select="$remaining" /> </xsl:call-template> </xsl:if> </xsl:template> ```
136,505
<p>I'm searching for UUIDs in blocks of text using a regex. Currently I'm relying on the assumption that all UUIDs will follow a patttern of 8-4-4-4-12 hexadecimal digits.</p> <p>Can anyone think of a use case where this assumption would be invalid and would cause me to miss some UUIDs?</p>
[ { "answer_id": 136532, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 3, "selected": false, "text": "<p>By definition, a UUID is 32 hexadecimal digits, separated in 5 groups by hyphens, just as you have described. You shouldn't mi...
2008/09/25
[ "https://Stackoverflow.com/questions/136505", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I'm searching for UUIDs in blocks of text using a regex. Currently I'm relying on the assumption that all UUIDs will follow a patttern of 8-4-4-4-12 hexadecimal digits. Can anyone think of a use case where this assumption would be invalid and would cause me to miss some UUIDs?
I agree that by definition your regex does not miss any UUID. However it may be useful to note that if you are searching especially for Microsoft's Globally Unique Identifiers (GUIDs), there are five equivalent string representations for a GUID: ``` "ca761232ed4211cebacd00aa0057b223" "CA761232-ED42-11CE-BACD-00AA0057B223" "{CA761232-ED42-11CE-BACD-00AA0057B223}" "(CA761232-ED42-11CE-BACD-00AA0057B223)" "{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x23}}" ```
136,536
<p>FYI: I am running on dotnet 3.5 SP1</p> <p>I am trying to retrieve the value of an identity column into my dataset after performing an update (using a SqlDataAdapter and SqlCommandBuilder). After performing SqlDataAdapter.Update(myDataset), I want to be able to read the auto-assigned value of <code>myDataset.tables(0).Rows(0)("ID")</code>, but it is System.DBNull (despite the fact that the row was inserted).</p> <p>(Note: I do not want to explicitly write a new stored procedure to do this!)</p> <p>One method often posted <a href="http://forums.asp.net/t/951025.aspx" rel="noreferrer">http://forums.asp.net/t/951025.aspx</a> modifies the SqlDataAdapter.InsertCommand and UpdatedRowSource like so:</p> <pre><code>SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()" InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord </code></pre> <p>Apparently, this seemed to work for many people in the past, but does not work for me.</p> <p>Another technique: <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&amp;SiteID=1" rel="noreferrer">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&amp;SiteID=1</a> doesn't work for me either, as after executing the SqlDataAdapter.Update, the SqlDataAdapter.InsertCommand.Parameters collection is reset to the original (losing the additional added parameter).</p> <p>Does anyone know the answer to this???</p>
[ { "answer_id": 137331, "author": "Jon Adams", "author_id": 2291, "author_profile": "https://Stackoverflow.com/users/2291", "pm_score": 1, "selected": false, "text": "<p>If those other methods didn't work for you, the .Net provided tools (SqlDataAdapter) etc. don't really offer much else ...
2008/09/25
[ "https://Stackoverflow.com/questions/136536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]
FYI: I am running on dotnet 3.5 SP1 I am trying to retrieve the value of an identity column into my dataset after performing an update (using a SqlDataAdapter and SqlCommandBuilder). After performing SqlDataAdapter.Update(myDataset), I want to be able to read the auto-assigned value of `myDataset.tables(0).Rows(0)("ID")`, but it is System.DBNull (despite the fact that the row was inserted). (Note: I do not want to explicitly write a new stored procedure to do this!) One method often posted <http://forums.asp.net/t/951025.aspx> modifies the SqlDataAdapter.InsertCommand and UpdatedRowSource like so: ``` SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()" InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord ``` Apparently, this seemed to work for many people in the past, but does not work for me. Another technique: <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&SiteID=1> doesn't work for me either, as after executing the SqlDataAdapter.Update, the SqlDataAdapter.InsertCommand.Parameters collection is reset to the original (losing the additional added parameter). Does anyone know the answer to this???
This is a problem that I've run into before, the bug seems to be that when you call da.Update(ds); the parameters array of the insert command gets reset to the inital list that was created form your command builder, it removes your added output parameters for the identity. The solution is to create a new dataAdapter and copy in the commands, then use this new one to do your da.update(ds); like ``` SqlDataAdapter da = new SqlDataAdapter("select Top 0 " + GetTableSelectList(dt) + "FROM " + tableName,_sqlConnectString); SqlCommandBuilder custCB = new SqlCommandBuilder(da); custCB.QuotePrefix = "["; custCB.QuoteSuffix = "]"; da.TableMappings.Add("Table", dt.TableName); da.UpdateCommand = custCB.GetUpdateCommand(); da.InsertCommand = custCB.GetInsertCommand(); da.DeleteCommand = custCB.GetDeleteCommand(); da.InsertCommand.CommandText = String.Concat(da.InsertCommand.CommandText, "; SELECT ",GetTableSelectList(dt)," From ", tableName, " where ",pKeyName,"=SCOPE_IDENTITY()"); SqlParameter identParam = new SqlParameter("@Identity", SqlDbType.BigInt, 0, pKeyName); identParam.Direction = ParameterDirection.Output; da.InsertCommand.Parameters.Add(identParam); da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord; //new adaptor for performing the update SqlDataAdapter daAutoNum = new SqlDataAdapter(); daAutoNum.DeleteCommand = da.DeleteCommand; daAutoNum.InsertCommand = da.InsertCommand; daAutoNum.UpdateCommand = da.UpdateCommand; daAutoNum.Update(dt); ```
136,548
<p>In C++ you can initialize a variable in an if statement, like so:</p> <pre><code>if (CThing* pThing = GetThing()) { } </code></pre> <p>Why would one consider this bad or good style? What are the benefits and disadvantages?</p> <p>Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:</p> <pre><code>if (CThing* pThing = GetThing() &amp;&amp; pThing-&gt;IsReallySomeThing()) { } </code></pre> <p>If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.</p> <p><a href="https://stackoverflow.com/questions/136373/initializing-a-variable-in-a-conditional-statment">Question borrowed from here, similar topic but PHP.</a></p>
[ { "answer_id": 136590, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 2, "selected": false, "text": "<p>This <strike><strong>should</strong></strike>doesn't work in C++ <strike>since</strike>even though it supports <a href=\"http:...
2008/09/25
[ "https://Stackoverflow.com/questions/136548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15328/" ]
In C++ you can initialize a variable in an if statement, like so: ``` if (CThing* pThing = GetThing()) { } ``` Why would one consider this bad or good style? What are the benefits and disadvantages? Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this: ``` if (CThing* pThing = GetThing() && pThing->IsReallySomeThing()) { } ``` If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why. [Question borrowed from here, similar topic but PHP.](https://stackoverflow.com/questions/136373/initializing-a-variable-in-a-conditional-statment)
The important thing is that a declaration in C++ is not an expression. ``` bool a = (CThing* pThing = GetThing()); // not legit!! ``` You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration. ``` if(A *a = new A) { // this is legit and a is scoped here } ``` How can we know whether a is defined between one term and another in an expression? ``` if((A *a = new A) && a->test()) { // was a really declared before a->test? } ``` Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit: ``` if (CThing* pThing = GetThing()) { if(pThing->IsReallySomeThing()) { } } ```
136,554
<p>I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt.</p> <p>Ideas?</p> <pre><code>#!/usr/bin/expect -- spawn $env(SHELL) match_max 100000 set timeout 2 send "echo This will print timed out\r" expect { timeout { puts "timed out at step 1" } "foo " { puts "it said foo at step 1"} } puts "Starting test two\r" send "echo This will not print timed out\r" expect -re { timeout { puts "timed out at step 2" ; exit } "foo " { puts "it said foo at step 2"} } </code></pre>
[ { "answer_id": 136590, "author": "Luke", "author_id": 327, "author_profile": "https://Stackoverflow.com/users/327", "pm_score": 2, "selected": false, "text": "<p>This <strike><strong>should</strong></strike>doesn't work in C++ <strike>since</strike>even though it supports <a href=\"http:...
2008/09/25
[ "https://Stackoverflow.com/questions/136554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10888/" ]
I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt. Ideas? ``` #!/usr/bin/expect -- spawn $env(SHELL) match_max 100000 set timeout 2 send "echo This will print timed out\r" expect { timeout { puts "timed out at step 1" } "foo " { puts "it said foo at step 1"} } puts "Starting test two\r" send "echo This will not print timed out\r" expect -re { timeout { puts "timed out at step 2" ; exit } "foo " { puts "it said foo at step 2"} } ```
The important thing is that a declaration in C++ is not an expression. ``` bool a = (CThing* pThing = GetThing()); // not legit!! ``` You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration. ``` if(A *a = new A) { // this is legit and a is scoped here } ``` How can we know whether a is defined between one term and another in an expression? ``` if((A *a = new A) && a->test()) { // was a really declared before a->test? } ``` Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit: ``` if (CThing* pThing = GetThing()) { if(pThing->IsReallySomeThing()) { } } ```
136,580
<p>I'm writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites. </p> <p>I wrote the following code:</p> <pre><code>composite.addListener (SWT.Paint, new Listener () { public void handleEvent (Event e) { GC gc = e.gc; Rectangle rect = composite.getClientArea (); Color color1 = new Color (display, 0, 0, 0); Color color2 = new Color (display, 255, 255, 255); gc.setForeground(color1); gc.setBackground(color2); gc.fillGradientRectangle (rect.x, rect.y, rect.width, rect.height , true); } }); </code></pre> <p>This draws the gradient fine on the composite, but we have Label/CLabels, Canvases and Links on top of the composite. </p> <p>In these areas, the background is just the plain gray you get when drawing an empty canvas. </p> <p>I've tried forcing the Labels to inherit the background like so:</p> <pre><code>label.setBackgroundMode(SWT.INHERIT_DEFAULT) //SWT.INHERIT_FORCE Doesn't work either </code></pre> <p>But this leaves me with the same default gray and no gradient behind the components on top of the Composite. </p> <p>Any suggestions for getting the gradient to be the background of each element?</p> <p>I wouldn't be opposed to drawing the Gradient onto a gc with an image supplied and then setting the background to that Image. However that method just hasn't been working at all, composite or any of its elements. </p> <p>Also it's not possible for me to set the gradient individually to my knowledge. We want the whole composite to be one uniform flowing gradient. </p> <p>[edit] I uploaded an example upto twitpic <a href="http://twitpic.com/d5qz" rel="nofollow noreferrer">here</a>.</p> <p>Thanks,</p> <p>Brian Gianforcaro</p>
[ { "answer_id": 136668, "author": "qualidafial", "author_id": 13253, "author_profile": "https://Stackoverflow.com/users/13253", "pm_score": -1, "selected": false, "text": "<p>The first thing I would try is to <a href=\"http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/org.eclipse.sw...
2008/09/25
[ "https://Stackoverflow.com/questions/136580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3415/" ]
I'm writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites. I wrote the following code: ``` composite.addListener (SWT.Paint, new Listener () { public void handleEvent (Event e) { GC gc = e.gc; Rectangle rect = composite.getClientArea (); Color color1 = new Color (display, 0, 0, 0); Color color2 = new Color (display, 255, 255, 255); gc.setForeground(color1); gc.setBackground(color2); gc.fillGradientRectangle (rect.x, rect.y, rect.width, rect.height , true); } }); ``` This draws the gradient fine on the composite, but we have Label/CLabels, Canvases and Links on top of the composite. In these areas, the background is just the plain gray you get when drawing an empty canvas. I've tried forcing the Labels to inherit the background like so: ``` label.setBackgroundMode(SWT.INHERIT_DEFAULT) //SWT.INHERIT_FORCE Doesn't work either ``` But this leaves me with the same default gray and no gradient behind the components on top of the Composite. Any suggestions for getting the gradient to be the background of each element? I wouldn't be opposed to drawing the Gradient onto a gc with an image supplied and then setting the background to that Image. However that method just hasn't been working at all, composite or any of its elements. Also it's not possible for me to set the gradient individually to my knowledge. We want the whole composite to be one uniform flowing gradient. [edit] I uploaded an example upto twitpic [here](http://twitpic.com/d5qz). Thanks, Brian Gianforcaro
Use **composite.setBackgroundMode(SWT.INHERIT\_DEFAULT)**, but do not paint the composite directly - paint an image and set it as the background image using **composite.setBackgroundImage(Image)**. Unless I'm missing a trick, this means you only have to regenerate the image when the composite is resized too. You should be able to cut'n'paste this code as is to see what I mean: ``` import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import org.eclipse.swt.widgets.*; /** * SWT composite with transparent label * * @author McDowell */ public class Sweet { private Image imageGradient; private Label label; private Composite composite; private void createComponents(Shell parent) { composite = new Composite(parent, SWT.NONE); composite.addListener(SWT.Resize, new Listener() { public void handleEvent(Event e) { changeImage(); } }); composite.setLayout(new FormLayout()); composite.setBackgroundMode(SWT.INHERIT_DEFAULT); label = new Label(composite, SWT.None); label.setText("Hello, World!"); } private void changeImage() { Image oldImage = imageGradient; Display display = composite.getDisplay(); Rectangle rect = composite.getClientArea(); imageGradient = new Image(display, rect.width, rect.height); GC gc = new GC(imageGradient); try { Color color1 = new Color(display, 200, 200, 255); try { Color color2 = new Color(display, 255, 255, 255); try { gc.setForeground(color1); gc.setBackground(color2); gc.fillGradientRectangle(rect.x, rect.y, rect.width, rect.height, true); } finally { color2.dispose(); } } finally { color1.dispose(); } } finally { gc.dispose(); } composite.setBackgroundImage(imageGradient); if (oldImage != null) { oldImage.dispose(); } } private void openShell(Display display) { Shell shell = new Shell(display); try { shell.setSize(200, 100); shell.setLayout(new FillLayout()); createComponents(shell); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } } finally { if (!shell.isDisposed()) { shell.dispose(); } } } public void run() { Display display = Display.getDefault(); try { openShell(display); } finally { display.dispose(); } } public void dispose() { if (imageGradient != null) { imageGradient.dispose(); } } public static void main(String[] args) { Sweet sweet = new Sweet(); try { sweet.run(); } finally { sweet.dispose(); } } } ```
136,581
<p>Is there a way to keep the "Loading..." graphic from appearing when cfdiv refreshes? I'd like to prevent the flicker of loading the graphic then loading the new html.</p>
[ { "answer_id": 140429, "author": "bhinks", "author_id": 5877, "author_profile": "https://Stackoverflow.com/users/5877", "pm_score": 1, "selected": false, "text": "<p>I don't think there is currently a way to do this programmatically within the <code>cfdiv</code> tag. If you really want t...
2008/09/25
[ "https://Stackoverflow.com/questions/136581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ]
Is there a way to keep the "Loading..." graphic from appearing when cfdiv refreshes? I'd like to prevent the flicker of loading the graphic then loading the new html.
By adding these lines at the bottom of the header, it overwrites the "Loading..." html and seems to prevent the flickering effect in both IE and FireFox: ``` <script language="JavaScript"> _cf_loadingtexthtml=""; </script> ``` While this seems to do the trick, it would be nice if there was an officially supported way to customize the loading animation on a per page or per control basis. Hopefully they add support for that in ColdFusion9.
136,604
<p>Sorry if the title is poorly descriptive, but I can't do better right now =(</p> <p>So, I have this master-detail scheme, with the detail being a tree structure (one to many self relation) with n levels (on SQLServer 2005)</p> <p>I need to copy a detail structure from one master to the another using a stored procedure, by passing the source master id and the target master id as parameters (the target is new, so it doesn't has details).</p> <p>I'm having troubles, and asking for your kind help in finding a way to keep track of parent id's and inserting the children without using cursors or nasty things like that...</p> <p><img src="https://i.stack.imgur.com/hBzdZ.jpg" alt="table model for the problem"></p> <p>This is a sample model, of course, and what I'm trying to do is to copy the detail structure from one master to other. In fact, I'm creating a new master using an existing one as template.</p>
[ { "answer_id": 136677, "author": "Mladen", "author_id": 21404, "author_profile": "https://Stackoverflow.com/users/21404", "pm_score": 0, "selected": false, "text": "<p>you'll have to provide create table and insert into statements for little sample data.\nand expected results based on th...
2008/09/25
[ "https://Stackoverflow.com/questions/136604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6359/" ]
Sorry if the title is poorly descriptive, but I can't do better right now =( So, I have this master-detail scheme, with the detail being a tree structure (one to many self relation) with n levels (on SQLServer 2005) I need to copy a detail structure from one master to the another using a stored procedure, by passing the source master id and the target master id as parameters (the target is new, so it doesn't has details). I'm having troubles, and asking for your kind help in finding a way to keep track of parent id's and inserting the children without using cursors or nasty things like that... ![table model for the problem](https://i.stack.imgur.com/hBzdZ.jpg) This is a sample model, of course, and what I'm trying to do is to copy the detail structure from one master to other. In fact, I'm creating a new master using an existing one as template.
If I understand the problem, this might be what you want: ``` INSERT dbo.Master VALUES (@NewMaster_ID, @NewDescription) INSERT dbo.Detail (parent_id, master_id, [name]) SELECT detail_ID, @NewMaster_ID, [name] FROM dbo.Detail WHERE master_id = @OldMaster_ID UPDATE NewChild SET parent_id = NewParent.detail_id FROM dbo.Detail NewChild JOIN dbo.Detail OldChild ON NewChild.parent_id = OldChild.detail_id JOIN dbo.Detail NewParent ON NewParent.parent_id = OldChild.parent_ID WHERE NewChild.master_id = @NewMaster_ID AND NewParent.master_id = @NewMaster_ID AND OldChild.master_id = @OldMaster_ID ``` The trick is to use the old `detail_id` as the new `parent_id` in the initial insert. Then join back to the old set of rows using this relationship, and update the new `parent_id` values. I assumed that `detail_id` is an IDENTITY value. If you assign them yourself, you'll need to provide details, but there's a similar solution.
136,615
<p>How can I <em>programmatically</em> determine if I have access to a server (TCP) with a given IP address and port using C#?</p>
[ { "answer_id": 136625, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 5, "selected": true, "text": "<p>Assuming you mean through a TCP socket:</p>\n\n<pre><code>IPAddress IP;\nif(IPAddress.TryParse(\"127.0.0.1\",out IP)){\n ...
2008/09/25
[ "https://Stackoverflow.com/questions/136615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I *programmatically* determine if I have access to a server (TCP) with a given IP address and port using C#?
Assuming you mean through a TCP socket: ``` IPAddress IP; if(IPAddress.TryParse("127.0.0.1",out IP)){ Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try{ s.Connect(IPs[0], port); } catch(Exception ex){ // something went wrong } } ``` For more information: <http://msdn.microsoft.com/en-us/library/4xzx2d41.aspx?ppud=4>
136,617
<p>How do I programmatically force an onchange event on an input?</p> <p>I've tried something like this:</p> <pre><code>var code = ele.getAttribute('onchange'); eval(code); </code></pre> <p>But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.</p>
[ { "answer_id": 136633, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": -1, "selected": false, "text": "<p>if you're using jQuery you would have:</p>\n\n<pre><code>$('#elementId').change(function() { alert('Do Stuff'); }...
2008/09/25
[ "https://Stackoverflow.com/questions/136617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3420/" ]
How do I programmatically force an onchange event on an input? I've tried something like this: ``` var code = ele.getAttribute('onchange'); eval(code); ``` But my end goal is to fire any listener functions, and that doesn't seem to work. Neither does just updating the 'value' attribute.
Create an `Event` object and pass it to the `dispatchEvent` method of the element: ``` var element = document.getElementById('just_an_example'); var event = new Event('change'); element.dispatchEvent(event); ``` This will trigger event listeners regardless of whether they were registered by calling the `addEventListener` method or by setting the `onchange` property of the element. --- By default, events created and dispatched like this don't propagate (bubble) up the DOM tree like events normally do. If you want the event to bubble, you need to pass a second argument to the `Event` constructor: ``` var event = new Event('change', { bubbles: true }); ``` --- Information about browser compability: * [dispatchEvent()](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent#Browser_Compatibility) * [Event()](https://developer.mozilla.org/en-US/docs/Web/API/Event/Event#Browser_compatibility)
136,628
<p>I have a model and two views set up like this:</p> <pre><code>Model ---&gt; OSortFilterProxyModel ---&gt; OListView Model ------------------------------&gt; OTableView </code></pre> <p>When the user selects something in one of the views, I want the other view to mirror that selection. So I thought I'd use a QSelectionModel to link them together. But this does not work. I have a feeling it is because the views think they have two different models, when in fact they have the same model. Is there a way to get this to work?</p>
[ { "answer_id": 136936, "author": "Caleb Huitt - cjhuitt", "author_id": 9876, "author_profile": "https://Stackoverflow.com/users/9876", "pm_score": 2, "selected": false, "text": "<p>What is probably happening is that the views do have two different models. One is your original model, the...
2008/09/25
[ "https://Stackoverflow.com/questions/136628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1585/" ]
I have a model and two views set up like this: ``` Model ---> OSortFilterProxyModel ---> OListView Model ------------------------------> OTableView ``` When the user selects something in one of the views, I want the other view to mirror that selection. So I thought I'd use a QSelectionModel to link them together. But this does not work. I have a feeling it is because the views think they have two different models, when in fact they have the same model. Is there a way to get this to work?
What is probably happening is that the views do have two different models. One is your original model, the other is the sort filter model. I'm not sure if this would work, and it depends on what Qt considers "activated", but you could connect a function to each of the view's activated slots. These will pass you a model index. You'll have to send the model index through the proxy model in the appropriate direction (mapFromSource and mapToSource). Then, call the setCurrentIndex on the other view. The documentation for the activated signal states that what is considered "activated" varies by platform. There might be other signals you could latch onto, such as the selection model's selection changed signal. You might have to do a different call to change the selection as seen by the user. And finally, it might be possible or even easier to do in a derived QSelectionModel, as long as you remember about mapping to/from the source model.
136,635
<p>We have a .NET 2.0 application which we normally run on IIS6, and used to run fine on IIS7, but recently after installing SP1 for Vista IIS7 seems to be choking on a line in the Web.Config file:</p> <pre><code>&lt;system.web AllowLocation="true"&gt; </code></pre> <p>Is it safe to remove the AllowLocation attribute? What does this attribute do?</p>
[ { "answer_id": 136676, "author": "ironsam", "author_id": 3539, "author_profile": "https://Stackoverflow.com/users/3539", "pm_score": 0, "selected": false, "text": "<p>Having this set to true should enable any <code>&lt;location&gt;</code> sections in your web.config, so you should be fin...
2008/09/25
[ "https://Stackoverflow.com/questions/136635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8432/" ]
We have a .NET 2.0 application which we normally run on IIS6, and used to run fine on IIS7, but recently after installing SP1 for Vista IIS7 seems to be choking on a line in the Web.Config file: ``` <system.web AllowLocation="true"> ``` Is it safe to remove the AllowLocation attribute? What does this attribute do?
From MSDN: > > When set to false, the AllowLocation property indicates that the section is accessed by native-code readers. Therefore, the use of the location attribute is not allowed, because the native-code readers do not support the concept of location. > > > The default value is true, so you should be able to remove it with no effect on your application.
136,642
<p>I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me.</p> <p>Example input:</p> <blockquote> <p>Is this thing on??? or what???</p> </blockquote> <p>Desired output:</p> <blockquote> <p>Is this thing on? or what?</p> </blockquote> <p>I'm using <a href="http://php.net/preg_replace" rel="nofollow noreferrer">preg_replace()</a> in PHP.</p>
[ { "answer_id": 136654, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 4, "selected": true, "text": "<pre><code>preg_replace('{\\?+}', '?', 'Is this thing on??? or what???');\n</code></pre>\n\n<p>That is, you only have to ...
2008/09/25
[ "https://Stackoverflow.com/questions/136642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ]
I'm having trouble coming up with the correct regex string to remove a sequence of multiple ? characters. I want to replace more than one sequential ? with a single ?, but which characters to escape...is escaping me. Example input: > > Is this thing on??? or what??? > > > Desired output: > > Is this thing on? or what? > > > I'm using [preg\_replace()](http://php.net/preg_replace) in PHP.
``` preg_replace('{\?+}', '?', 'Is this thing on??? or what???'); ``` That is, you only have to escape the question mark, the plus in "\?+" means that we're replacing every instance with one or more characters, though I suspect "\?{2,}" might be even better and more efficient (replacing every instance with two or more question mark characters.
136,672
<p>I'd like to log stuff in my Sharepoint Web Parts, but I want it to go into the ULS. Most examples that I've found log into the Event Log or some other file, but I did not really find one yet for logging into the ULS.</p> <p>Annoyingly, Microsoft.SharePoint.Diagnostics Classes are all marked Internal. I did find <a href="http://www.codeplex.com/SharePointOfView/SourceControl/FileView.aspx?itemId=244213&amp;changeSetId=13835" rel="nofollow noreferrer">one example</a> of how to use them anyway through reflection, but that looks really risky and unstable, because Microsoft may change that class with any hotfix they want.</p> <p>The Sharepoint Documentation wasn't really helpful either - lots of Administrator info about what ULS is and how to configure it, but i have yet to find an example of supported code to actually log my own events.</p> <p>Any hints or tips?</p> <p><strong>Edit:</strong> As you may see from the age of this question, this is for SharePoint 2007. In SharePoint 2010, you can use SPDiagnosticsService.Local and then <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spdiagnosticsservicebase.writetrace.aspx" rel="nofollow noreferrer">WriteTrace</a>. See the answer from Jürgen below.</p>
[ { "answer_id": 137836, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 4, "selected": true, "text": "<p>Yes this is possible, see this MSDN article: <a href=\"http://msdn2.microsoft.com/hi-in/library/aa979595(en-us)....
2008/09/25
[ "https://Stackoverflow.com/questions/136672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I'd like to log stuff in my Sharepoint Web Parts, but I want it to go into the ULS. Most examples that I've found log into the Event Log or some other file, but I did not really find one yet for logging into the ULS. Annoyingly, Microsoft.SharePoint.Diagnostics Classes are all marked Internal. I did find [one example](http://www.codeplex.com/SharePointOfView/SourceControl/FileView.aspx?itemId=244213&changeSetId=13835) of how to use them anyway through reflection, but that looks really risky and unstable, because Microsoft may change that class with any hotfix they want. The Sharepoint Documentation wasn't really helpful either - lots of Administrator info about what ULS is and how to configure it, but i have yet to find an example of supported code to actually log my own events. Any hints or tips? **Edit:** As you may see from the age of this question, this is for SharePoint 2007. In SharePoint 2010, you can use SPDiagnosticsService.Local and then [WriteTrace](http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.spdiagnosticsservicebase.writetrace.aspx). See the answer from Jürgen below.
Yes this is possible, see this MSDN article: <http://msdn2.microsoft.com/hi-in/library/aa979595(en-us).aspx> And here is some sample code in C#: ``` using System; using System.Runtime.InteropServices; using Microsoft.SharePoint.Administration; namespace ManagedTraceProvider { class Program { static void Main(string[] args) { TraceProvider.RegisterTraceProvider(); TraceProvider.WriteTrace(0, TraceProvider.TraceSeverity.High, Guid.Empty, "MyExeName", "Product Name", "Category Name", "Sample Message"); TraceProvider.WriteTrace(TraceProvider.TagFromString("abcd"), TraceProvider.TraceSeverity.Monitorable, Guid.NewGuid(), "MyExeName", "Product Name", "Category Name", "Sample Message"); TraceProvider.UnregisterTraceProvider(); } } static class TraceProvider { static UInt64 hTraceLog; static UInt64 hTraceReg; static class NativeMethods { internal const int TRACE_VERSION_CURRENT = 1; internal const int ERROR_SUCCESS = 0; internal const int ERROR_INVALID_PARAMETER = 87; internal const int WNODE_FLAG_TRACED_GUID = 0x00020000; internal enum TraceFlags { TRACE_FLAG_START = 1, TRACE_FLAG_END = 2, TRACE_FLAG_MIDDLE = 3, TRACE_FLAG_ID_AS_ASCII = 4 } // Copied from Win32 APIs [StructLayout(LayoutKind.Sequential)] internal struct EVENT_TRACE_HEADER_CLASS { internal byte Type; internal byte Level; internal ushort Version; } // Copied from Win32 APIs [StructLayout(LayoutKind.Sequential)] internal struct EVENT_TRACE_HEADER { internal ushort Size; internal ushort FieldTypeFlags; internal EVENT_TRACE_HEADER_CLASS Class; internal uint ThreadId; internal uint ProcessId; internal Int64 TimeStamp; internal Guid Guid; internal uint ClientContext; internal uint Flags; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct ULSTraceHeader { internal ushort Size; internal uint dwVersion; internal uint Id; internal Guid correlationID; internal TraceFlags dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] internal string wzExeName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] internal string wzProduct; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] internal string wzCategory; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 800)] internal string wzMessage; } [StructLayout(LayoutKind.Sequential)] internal struct ULSTrace { internal EVENT_TRACE_HEADER Header; internal ULSTraceHeader ULSHeader; } // Copied from Win32 APIs internal enum WMIDPREQUESTCODE { WMI_GET_ALL_DATA = 0, WMI_GET_SINGLE_INSTANCE = 1, WMI_SET_SINGLE_INSTANCE = 2, WMI_SET_SINGLE_ITEM = 3, WMI_ENABLE_EVENTS = 4, WMI_DISABLE_EVENTS = 5, WMI_ENABLE_COLLECTION = 6, WMI_DISABLE_COLLECTION = 7, WMI_REGINFO = 8, WMI_EXECUTE_METHOD = 9 } // Copied from Win32 APIs internal unsafe delegate uint EtwProc(NativeMethods.WMIDPREQUESTCODE requestCode, IntPtr requestContext, uint* bufferSize, IntPtr buffer); // Copied from Win32 APIs [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] internal static extern unsafe uint RegisterTraceGuids([In] EtwProc cbFunc, [In] void* context, [In] ref Guid controlGuid, [In] uint guidCount, IntPtr guidReg, [In] string mofImagePath, [In] string mofResourceName, out ulong regHandle); // Copied from Win32 APIs [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] internal static extern uint UnregisterTraceGuids([In]ulong regHandle); // Copied from Win32 APIs [DllImport("advapi32.dll", CharSet = CharSet.Unicode)] internal static extern UInt64 GetTraceLoggerHandle([In]IntPtr Buffer); // Copied from Win32 APIs [DllImport("advapi32.dll", SetLastError = true)] internal static extern uint TraceEvent([In]UInt64 traceHandle, [In]ref ULSTrace evnt); } public enum TraceSeverity { Unassigned = 0, CriticalEvent = 1, WarningEvent = 2, InformationEvent = 3, Exception = 4, Assert = 7, Unexpected = 10, Monitorable = 15, High = 20, Medium = 50, Verbose = 100, } public static void WriteTrace(uint tag, TraceSeverity level, Guid correlationGuid, string exeName, string productName, string categoryName, string message) { const ushort sizeOfWCHAR = 2; NativeMethods.ULSTrace ulsTrace = new NativeMethods.ULSTrace(); // Pretty standard code needed to make things work ulsTrace.Header.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTrace)); ulsTrace.Header.Flags = NativeMethods.WNODE_FLAG_TRACED_GUID; ulsTrace.ULSHeader.dwVersion = NativeMethods.TRACE_VERSION_CURRENT; ulsTrace.ULSHeader.dwFlags = NativeMethods.TraceFlags.TRACE_FLAG_ID_AS_ASCII; ulsTrace.ULSHeader.Size = (ushort)Marshal.SizeOf(typeof(NativeMethods.ULSTraceHeader)); // Variables communicated to SPTrace ulsTrace.ULSHeader.Id = tag; ulsTrace.Header.Class.Level = (byte)level; ulsTrace.ULSHeader.wzExeName = exeName; ulsTrace.ULSHeader.wzProduct = productName; ulsTrace.ULSHeader.wzCategory = categoryName; ulsTrace.ULSHeader.wzMessage = message; ulsTrace.ULSHeader.correlationID = correlationGuid; // Pptionally, to improve performance by reducing the amount of data copied around, // the Size parameters can be reduced by the amount of unused buffer in the Message if (message.Length < 800) { ushort unusedBuffer = (ushort) ((800 - (message.Length + 1)) * sizeOfWCHAR); ulsTrace.Header.Size -= unusedBuffer; ulsTrace.ULSHeader.Size -= unusedBuffer; } if (hTraceLog != 0) NativeMethods.TraceEvent(hTraceLog, ref ulsTrace); } public static unsafe void RegisterTraceProvider() { SPFarm farm = SPFarm.Local; Guid traceGuid = farm.TraceSessionGuid; uint result = NativeMethods.RegisterTraceGuids(ControlCallback, null, ref traceGuid, 0, IntPtr.Zero, null, null, out hTraceReg); System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS); } public static void UnregisterTraceProvider() { uint result = NativeMethods.UnregisterTraceGuids(hTraceReg); System.Diagnostics.Debug.Assert(result == NativeMethods.ERROR_SUCCESS); } public static uint TagFromString(string wzTag) { System.Diagnostics.Debug.Assert(wzTag.Length == 4); return (uint) (wzTag[0] << 24 | wzTag[1] << 16 | wzTag[2] << 8 | wzTag[3]); } static unsafe uint ControlCallback(NativeMethods.WMIDPREQUESTCODE RequestCode, IntPtr Context, uint* InOutBufferSize, IntPtr Buffer) { uint Status; switch (RequestCode) { case NativeMethods.WMIDPREQUESTCODE.WMI_ENABLE_EVENTS: hTraceLog = NativeMethods.GetTraceLoggerHandle(Buffer); Status = NativeMethods.ERROR_SUCCESS; break; case NativeMethods.WMIDPREQUESTCODE.WMI_DISABLE_EVENTS: hTraceLog = 0; Status = NativeMethods.ERROR_SUCCESS; break; default: Status = NativeMethods.ERROR_INVALID_PARAMETER; break; } *InOutBufferSize = 0; return Status; } } ``` }
136,682
<p>I've got a code like this : </p> <pre><code>Dim Document As New mshtml.HTMLDocument Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2) iDoc.write(html) iDoc.close() </code></pre> <p>However when I load an HTML like this it executes all Javascripts in it as well as doing request to some resources from "html" code.</p> <p>I want to disable javascript and all other popups (such as certificate error).</p> <p>My aim is to use DOM from mshtml document to extract some tags from the HTML in a reliable way (instead of bunch of regexes). </p> <p>Or is there another IE/Office DLL which I can just load an HTML wihtout thinking about IE related popups or active scripts?</p>
[ { "answer_id": 139224, "author": "scunliffe", "author_id": 6144, "author_profile": "https://Stackoverflow.com/users/6144", "pm_score": 1, "selected": false, "text": "<p>If you have the 'html' as a string already, and you just want access to the DOM view of it, why \"render\" it to a brow...
2008/09/25
[ "https://Stackoverflow.com/questions/136682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've got a code like this : ``` Dim Document As New mshtml.HTMLDocument Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2) iDoc.write(html) iDoc.close() ``` However when I load an HTML like this it executes all Javascripts in it as well as doing request to some resources from "html" code. I want to disable javascript and all other popups (such as certificate error). My aim is to use DOM from mshtml document to extract some tags from the HTML in a reliable way (instead of bunch of regexes). Or is there another IE/Office DLL which I can just load an HTML wihtout thinking about IE related popups or active scripts?
``` Dim Document As New mshtml.HTMLDocument Dim iDoc As mshtml.IHTMLDocument2 = CType(Document, mshtml.IHTMLDocument2) 'add this code iDoc.designMode="On" iDoc.write(html)iDoc.close() ```
136,696
<p>I have a Hashtable&lt;Integer, Sport> called sportMap and a list of sportIds (List&lt;Integer> sportIds) from my backing bean. The Sport object has a List&lt;String> equipmentList. Can I do the following using the unified EL to get the list of equipment for each sport?</p> <pre><code>&lt;h:dataTable value="#{bean.sportIds}" var="_sportId" &gt; &lt;c:forEach items="#{bean.sportMap[_sportId].equipmentList}" var="_eqp"&gt; &lt;h:outputText value="#{_eqp}"&gt;&lt;/h:outputText&gt; &lt;br/&gt; &lt;/c:forEach&gt; &lt;/h:dataTable&gt; </code></pre> <p>I get the following exception when trying to run this JSP code.</p> <pre> 15:57:59,438 ERROR [ExceptionFilter] exception root cause javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in &amp;lt;forEach&amp;gt;</pre> <p>Here's a print out of my environment</p> <pre> Server: JBossWeb/2.0.1.GA Servlet Specification: 2.5 JSP version: 2.1 JSTL version: 1.2 Java Version: 1.5.0_14 </pre> <p>Note: The following does work using a JSF tag. It prints out the list of equipment for each sport specified in the list of sportIds. </p> <pre><code>&lt;h:dataTable value="#{bean.sportIds}" var="_sportId" &gt; &lt;h:outputText value="#{bean.sportMap[_sportId].equipmentList}"&gt; &lt;/h:outputText&gt; &lt;/h:dataTable&gt; </code></pre> <p>I would like to use the c:forEach tag. Does anyone know if this is possible? If not, anyone have suggestions? In the end I want a stacked list instead of the comma seperated list provided by equipmentList.toString(); (Also, don't want to override toString()).</p>
[ { "answer_id": 137188, "author": "user13229", "author_id": 13229, "author_profile": "https://Stackoverflow.com/users/13229", "pm_score": -1, "selected": false, "text": "<p>Two issues: </p>\n\n<ol>\n<li>A dataTable can only have the following children: header facet, footer facet, column. ...
2008/09/25
[ "https://Stackoverflow.com/questions/136696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ]
I have a Hashtable<Integer, Sport> called sportMap and a list of sportIds (List<Integer> sportIds) from my backing bean. The Sport object has a List<String> equipmentList. Can I do the following using the unified EL to get the list of equipment for each sport? ``` <h:dataTable value="#{bean.sportIds}" var="_sportId" > <c:forEach items="#{bean.sportMap[_sportId].equipmentList}" var="_eqp"> <h:outputText value="#{_eqp}"></h:outputText> <br/> </c:forEach> </h:dataTable> ``` I get the following exception when trying to run this JSP code. ``` 15:57:59,438 ERROR [ExceptionFilter] exception root cause javax.servlet.ServletException: javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in &lt;forEach&gt; ``` Here's a print out of my environment ``` Server: JBossWeb/2.0.1.GA Servlet Specification: 2.5 JSP version: 2.1 JSTL version: 1.2 Java Version: 1.5.0_14 ``` Note: The following does work using a JSF tag. It prints out the list of equipment for each sport specified in the list of sportIds. ``` <h:dataTable value="#{bean.sportIds}" var="_sportId" > <h:outputText value="#{bean.sportMap[_sportId].equipmentList}"> </h:outputText> </h:dataTable> ``` I would like to use the c:forEach tag. Does anyone know if this is possible? If not, anyone have suggestions? In the end I want a stacked list instead of the comma seperated list provided by equipmentList.toString(); (Also, don't want to override toString()).
@[keith30xi.myopenid.com](https://stackoverflow.com/questions/136696/can-i-use-a-hashtable-in-a-unified-el-expression-on-a-cforeach-tag-using-jsf-12#137188) **Not TRUE in JSF 1.2**. According to the [java.net wiki faq](http://wiki.java.net/bin/view/Projects/JavaServerFacesSpecFaq#12coreTags) they should work together as expected. Here's an extract from each faq: > > **JSF 1.1 FAQ** > > Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when? > > > A. The forEach tag does not work with JavaServer Faces technology, version 1.0 and 1.1 tags due to an incompatibility between the strategies used by JSTL and and JavaServer > Faces technology. Instead, you could use a renderer, such as the Table renderer used by the dataTable tag, that performs its own iteration. The if, choose and when tags work, but the JavaServer Faces tags nested within these tags must have explicit identifiers. > > > ***This shortcoming has been fixed in JSF 1.2.*** > > > **JSF 1.2 FAQ** > > Q. Do JavaServer Faces tags interoperate with JSTL core tags, forEach, if, choose and when? > > > A. Yes. A new feature of JSP 2.1, called JSP Id Consumer allows these tags to work as expected. > > > Has anyone used JSF tags with JSTL core tags specifically forEach?
136,703
<p>I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++.</p> <p>Equivalent of this if you know Cocoa:</p> <pre><code>NSString *string = [NSString stringWithContentsOfFile:file]; </code></pre>
[ { "answer_id": 136710, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "<p>The standard C++ library doesn't provide a function to do this.</p>\n" }, { "answer_id": 136743, "author":...
2008/09/25
[ "https://Stackoverflow.com/questions/136703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
I need a quick easy way to get a string from a file in standard C++. I can write my own, but just want to know if there is already a standard way, in C++. Equivalent of this if you know Cocoa: ``` NSString *string = [NSString stringWithContentsOfFile:file]; ```
We can do it but it's a long line : ``` #include<fstream> #include<iostream> #include<iterator> #include<string> using namespace std; int main() { // The one-liner string fileContents(istreambuf_iterator<char>(ifstream("filename.txt")), istreambuf_iterator<char>()); // Check result cout << fileContents; } ``` Edited : use "istreambuf\_iterator" instead of "istream\_iterator"
136,727
<p>From my understanding of the CSS spec, a table above or below a paragraph should collapse vertical margins with it. However, that's not happening here:</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { margin: 100px; border: solid red 2px; } p { margin: 100px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; This is a one-celled table with 100px margin all around. &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p&gt;This is a paragraph with 100px margin all around.&lt;/p&gt;</code></pre> </div> </div> </p> <p>I thought there would be 100px between the two elements, but there are 200px -- the margins aren't collapsing. </p> <p>Why not?</p> <p><strong>Edit:</strong> It appears to be the table's fault: if I duplicate the table and duplicate the paragraph, the two paragraphs will collapse margins. The two tables won't. And, as noted above, a table won't collapse margins with a paragraph. Is this compliant behaviour?</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table { margin: 100px; border: solid red 2px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; This is a one-celled table with 100px margin all around. &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; This is a one-celled table with 100px margin all around. &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>p { margin: 100px }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; &lt;p&gt;This is a paragraph with 100px margin all around.&lt;/p&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 136774, "author": "flash", "author_id": 11539, "author_profile": "https://Stackoverflow.com/users/11539", "pm_score": 2, "selected": false, "text": "<p>I think this is down to different browser implementations of CSS. I've just tried your code, and Firefox3 doesn't collap...
2008/09/25
[ "https://Stackoverflow.com/questions/136727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
From my understanding of the CSS spec, a table above or below a paragraph should collapse vertical margins with it. However, that's not happening here: ```css table { margin: 100px; border: solid red 2px; } p { margin: 100px } ``` ```html <table> <tr> <td> This is a one-celled table with 100px margin all around. </td> </tr> </table> <p>This is a paragraph with 100px margin all around.</p> ``` I thought there would be 100px between the two elements, but there are 200px -- the margins aren't collapsing. Why not? **Edit:** It appears to be the table's fault: if I duplicate the table and duplicate the paragraph, the two paragraphs will collapse margins. The two tables won't. And, as noted above, a table won't collapse margins with a paragraph. Is this compliant behaviour? ```css table { margin: 100px; border: solid red 2px; } ``` ```html <table> <tr> <td> This is a one-celled table with 100px margin all around. </td> </tr> </table> <table> <tr> <td> This is a one-celled table with 100px margin all around. </td> </tr> </table> ``` ```css p { margin: 100px } ``` ```html <p>This is a paragraph with 100px margin all around.</p> <p>This is a paragraph with 100px margin all around.</p> ```
Margin collapsing is only defined for block elements. Try it - add `display: block` to the table styles, and suddenly it works (and alters the display of the table...) Tables are special. In the CSS specs, they're not *quite* block elements - special rules apply to size and position, both of their children (obviously), and of the `table` element itself. ### Relevant specs: <http://www.w3.org/TR/CSS21/box.html#collapsing-margins> <http://www.w3.org/TR/CSS21/visuren.html#block-box>
136,734
<p>Is it possible to make it appear to a system that a key was pressed, for example I need to make <kbd>A</kbd> key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python.</p> <p>A better way to put it, I need to emulate a key press, I.E. not capture a key press.</p> <p>More Info (as requested): I am running windows XP and need to send the keys to another application.</p>
[ { "answer_id": 136759, "author": "PabloG", "author_id": 394, "author_profile": "https://Stackoverflow.com/users/394", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.autohotkey.com/\" rel=\"noreferrer\">AutoHotKey</a> is perfect for this kind of tasks (keyboard automat...
2008/09/25
[ "https://Stackoverflow.com/questions/136734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
Is it possible to make it appear to a system that a key was pressed, for example I need to make `A` key be pressed thousands of times, and it is much to time consuming to do it manually, I would like to write something to do it for me, and the only thing I know well enough is Python. A better way to put it, I need to emulate a key press, I.E. not capture a key press. More Info (as requested): I am running windows XP and need to send the keys to another application.
Install the [pywin32](https://github.com/mhammond/pywin32) extensions. Then you can do the following: ``` import win32com.client as comclt wsh= comclt.Dispatch("WScript.Shell") wsh.AppActivate("Notepad") # select another application wsh.SendKeys("a") # send the keys you want ``` Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start [here](http://www.microsoft.com/technet/scriptcenter/guide/sas_wsh_pkoy.mspx?mfr=true), perhaps. **EDIT:** Sending F11 ``` import win32com.client as comctl wsh = comctl.Dispatch("WScript.Shell") # Google Chrome window title wsh.AppActivate("icanhazip.com") wsh.SendKeys("{F11}") ```
136,752
<p>I have a C++ tool that walks the call stack at one point. In the code, it first gets a copy of the live CPU registers (via RtlCaptureContext()), then uses a few "<code>#ifdef ...</code>" blocks to save the CPU-specific register names into <code>stackframe.AddrPC.Offset</code>, ...<code>AddrStack</code>..., and ...<code>AddrFrame</code>...; also, for each of the 3 <code>Addr</code>... members above, it sets <code>stackframe.Addr</code>...<code>.Mode = AddrModeFlat</code>. (This was borrowed from some example code I came across a while back.)</p> <p>With an x86 binary, this works great. With an x64 binary, though, StackWalk64() passes back bogus addresses. <i>(The first time the API is called, the only blatantly bogus address value appears in <code>AddrReturn</code> ( == <code>0xFFFFFFFF'FFFFFFFE</code> -- aka StackWalk64()'s 3rd arg, the pseudo-handle returned by GetCurrentThread()). If the API is called a second time, however, all <code>Addr</code>... variables receive bogus addresses.)</i> This happens regardless of how <code>AddrFrame</code> is set:</p> <ul> <li>using either of the recommended x64 "base/frame pointer" CPU registers: <code>rbp</code> (= <code>0xf</code>), or <code>rdi</code> (= <code>0x0</code>)</li> <li>using <code>rsp</code> <i>(didn't expect it to work, but tried it anyway)</i></li> <li>setting <code>AddrPC</code> and <code>AddrStack</code> normally, but leaving <code>AddrFrame</code> zeroed out <i>(seen in other example code)</i></li> <li>zeroing out all <code>Addr</code>... values, to let StackWalk64() fill them in from the passed-in CPU-register context <i>(seen in other example code)</i></li> </ul> <p>FWIW, the physical stack buffer's contents are also different on x64 vs. x86 (after accounting for different pointer widths &amp; stack buffer locations, of course). Regardless of the reason, StackWalk64() should still be able to walk the call stack correctly -- heck, the debugger is still able to walk the call stack, and it appears to use StackWalk64() itself behind the scenes. The oddity there is that the (correct) call stack reported by the debugger contains base-address &amp; return-address pointer values whose constituent bytes don't actually exist in the stack buffer (below or above the current stack pointer).</p> <p><i>(FWIW #2: Given the stack-buffer strangeness above, I did try disabling ASLR (<code>/dynamicbase:no</code>) to see if it made a difference, but the binary still exhibited the same behavior.)</i></p> <p>So. Any ideas why this would work fine on x86, but have problems on x64? Any suggestions on how to fix it?</p>
[ { "answer_id": 136942, "author": "Adam Mitz", "author_id": 2574, "author_profile": "https://Stackoverflow.com/users/2574", "pm_score": 2, "selected": false, "text": "<p>Given that fs.sf is a STACKFRAME64 structure, you need to initialize it like this before passing it to StackWalk64: (c ...
2008/09/25
[ "https://Stackoverflow.com/questions/136752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19505/" ]
I have a C++ tool that walks the call stack at one point. In the code, it first gets a copy of the live CPU registers (via RtlCaptureContext()), then uses a few "`#ifdef ...`" blocks to save the CPU-specific register names into `stackframe.AddrPC.Offset`, ...`AddrStack`..., and ...`AddrFrame`...; also, for each of the 3 `Addr`... members above, it sets `stackframe.Addr`...`.Mode = AddrModeFlat`. (This was borrowed from some example code I came across a while back.) With an x86 binary, this works great. With an x64 binary, though, StackWalk64() passes back bogus addresses. *(The first time the API is called, the only blatantly bogus address value appears in `AddrReturn` ( == `0xFFFFFFFF'FFFFFFFE` -- aka StackWalk64()'s 3rd arg, the pseudo-handle returned by GetCurrentThread()). If the API is called a second time, however, all `Addr`... variables receive bogus addresses.)* This happens regardless of how `AddrFrame` is set: * using either of the recommended x64 "base/frame pointer" CPU registers: `rbp` (= `0xf`), or `rdi` (= `0x0`) * using `rsp` *(didn't expect it to work, but tried it anyway)* * setting `AddrPC` and `AddrStack` normally, but leaving `AddrFrame` zeroed out *(seen in other example code)* * zeroing out all `Addr`... values, to let StackWalk64() fill them in from the passed-in CPU-register context *(seen in other example code)* FWIW, the physical stack buffer's contents are also different on x64 vs. x86 (after accounting for different pointer widths & stack buffer locations, of course). Regardless of the reason, StackWalk64() should still be able to walk the call stack correctly -- heck, the debugger is still able to walk the call stack, and it appears to use StackWalk64() itself behind the scenes. The oddity there is that the (correct) call stack reported by the debugger contains base-address & return-address pointer values whose constituent bytes don't actually exist in the stack buffer (below or above the current stack pointer). *(FWIW #2: Given the stack-buffer strangeness above, I did try disabling ASLR (`/dynamicbase:no`) to see if it made a difference, but the binary still exhibited the same behavior.)* So. Any ideas why this would work fine on x86, but have problems on x64? Any suggestions on how to fix it?
Given that fs.sf is a STACKFRAME64 structure, you need to initialize it like this before passing it to StackWalk64: (c is a CONTEXT structure) ``` DWORD machine = IMAGE_FILE_MACHINE_AMD64; RtlCaptureContext (&c); fs.sf.AddrPC.Offset = c.Rip; fs.sf.AddrFrame.Offset = c.Rsp; fs.sf.AddrStack.Offset = c.Rsp; fs.sf.AddrPC.Mode = AddrModeFlat; fs.sf.AddrFrame.Mode = AddrModeFlat; fs.sf.AddrStack.Mode = AddrModeFlat; ``` This code is taken from ACE (Adaptive Communications Environment), adapted from the StackWalker project on CodeProject.
136,771
<p>How can I drop sql server agent jobs, if (and only if) it exists?</p> <p>This is a well functioning script for <em>stored procedures</em>. How can I do the same to sql server agent jobs?</p> <pre><code>if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[storedproc] GO CREATE PROCEDURE [dbo].[storedproc] ... </code></pre>
[ { "answer_id": 137159, "author": "Codewerks", "author_id": 17729, "author_profile": "https://Stackoverflow.com/users/17729", "pm_score": 8, "selected": true, "text": "<p>Try something like this:</p>\n\n<pre><code>DECLARE @jobId binary(16)\n\nSELECT @jobId = job_id FROM msdb.dbo.sysjobs W...
2008/09/25
[ "https://Stackoverflow.com/questions/136771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ]
How can I drop sql server agent jobs, if (and only if) it exists? This is a well functioning script for *stored procedures*. How can I do the same to sql server agent jobs? ``` if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [dbo].[storedproc] GO CREATE PROCEDURE [dbo].[storedproc] ... ```
Try something like this: ``` DECLARE @jobId binary(16) SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job') IF (@jobId IS NOT NULL) BEGIN EXEC msdb.dbo.sp_delete_job @jobId END DECLARE @ReturnCode int EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=N'Name of Your Job' ``` Best to read the docs on all the parameters required for ['sp\_add\_job'](http://msdn.microsoft.com/en-us/library/ms182079.aspx) and ['sp\_delete\_job'](http://msdn.microsoft.com/en-us/library/ms188376.aspx)
136,782
<p>I have a <code>datetime</code> column in MySQL. </p> <p>How can I convert it to the display as <strong>mm/dd/yy H:M (AM/PM)</strong> using PHP?</p>
[ { "answer_id": 136796, "author": "flash", "author_id": 11539, "author_profile": "https://Stackoverflow.com/users/11539", "pm_score": 4, "selected": false, "text": "<p>An easier way would be to format the date directly in the MySQL query, instead of PHP. See the <a href=\"http://dev.mysq...
2008/09/25
[ "https://Stackoverflow.com/questions/136782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/70/" ]
I have a `datetime` column in MySQL. How can I convert it to the display as **mm/dd/yy H:M (AM/PM)** using PHP?
If you're looking for a way to normalize a date into MySQL format, use the following ``` $phpdate = strtotime( $mysqldate ); $mysqldate = date( 'Y-m-d H:i:s', $phpdate ); ``` The line `$phpdate = strtotime( $mysqldate )` accepts a string and performs a series of heuristics to turn that string into a unix timestamp. The line `$mysqldate = date( 'Y-m-d H:i:s', $phpdate )` uses that timestamp and PHP's [`date`](http://php.net) function to turn that timestamp back into MySQL's standard date format. (**Editor Note**: This answer is here because of an original question with confusing wording, and the general Google usefulness this answer provided even if it didnt' directly answer the question that now exists)
136,789
<p>Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <a href="http://gist.github.com/12978" rel="nofollow noreferrer">http://gist.github.com/12978</a>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM)</p> <p>Is it possible for this to go faster or is that a limitation on the language/database?</p>
[ { "answer_id": 136870, "author": "Mark Roddy", "author_id": 9940, "author_profile": "https://Stackoverflow.com/users/9940", "pm_score": 2, "selected": false, "text": "<p>Use bind variables instead of literal values in the sql statements and create a cursor for \neach unique sql statement...
2008/09/25
[ "https://Stackoverflow.com/questions/136789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15245/" ]
Right now I have a log parser reading through 515mb of plain-text files (a file for each day over the past 4 years). My code currently stands as this: <http://gist.github.com/12978>. I've used psyco (as seen in the code) and I'm also compiling it and using the compiled version. It's doing about 100 lines every 0.3 seconds. The machine is a standard 15" MacBook Pro (2.4ghz C2D, 2GB RAM) Is it possible for this to go faster or is that a limitation on the language/database?
Don't waste time profiling. The time is always in the database operations. Do as few as possible. Just the minimum number of inserts. Three Things. One. Don't SELECT over and over again to conform the Date, Hostname and Person dimensions. Fetch all the data ONCE into a Python dictionary and use it in memory. Don't do repeated singleton selects. Use Python. Two. Don't Update. Specifically, Do not do this. It's bad code for two reasons. ``` cursor.execute("UPDATE people SET chats_count = chats_count + 1 WHERE id = '%s'" % person_id) ``` It be replaced with a simple SELECT COUNT(\*) FROM ... . Never update to increment a count. Just count the rows that are there with a SELECT statement. [If you can't do this with a simple SELECT COUNT or SELECT COUNT(DISTINCT), you're missing some data -- your data model should always provide correct complete counts. Never update.] And. Never build SQL using string substitution. Completely dumb. If, for some reason the `SELECT COUNT(*)` isn't fast enough (benchmark first, before doing anything lame) you can cache the result of the count in another table. AFTER all of the loads. Do a `SELECT COUNT(*) FROM whatever GROUP BY whatever` and insert this into a table of counts. Don't Update. Ever. Three. Use Bind Variables. Always. ``` cursor.execute( "INSERT INTO ... VALUES( %(x)s, %(y)s, %(z)s )", {'x':person_id, 'y':time_to_string(time), 'z':channel,} ) ``` The SQL never changes. The values bound in change, but the SQL never changes. This is MUCH faster. Never build SQL statements dynamically. Never.
136,793
<p>I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name):</p> <pre><code>people = [] info = 'a' # must fill variable with something, otherwise loop won't execute while not info.empty? info = gets.chomp people += [Person.new(info)] if not info.empty? end </code></pre> <p>This code would look much nicer in a do ... while loop:</p> <pre><code>people = [] do info = gets.chomp people += [Person.new(info)] if not info.empty? while not info.empty? </code></pre> <p>In this code I don't have to assign info to some random string.</p> <p>Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?</p>
[ { "answer_id": 136815, "author": "hubbardr", "author_id": 22457, "author_profile": "https://Stackoverflow.com/users/22457", "pm_score": 8, "selected": false, "text": "<blockquote>\n<p>I found the following snippet while reading the source for <code>Tempfile#initialize</code> in the Ruby ...
2008/09/25
[ "https://Stackoverflow.com/questions/136793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/813/" ]
I'm using this code to let the user enter in names while the program stores them in an array until they enter an empty string (they must press enter after each name): ``` people = [] info = 'a' # must fill variable with something, otherwise loop won't execute while not info.empty? info = gets.chomp people += [Person.new(info)] if not info.empty? end ``` This code would look much nicer in a do ... while loop: ``` people = [] do info = gets.chomp people += [Person.new(info)] if not info.empty? while not info.empty? ``` In this code I don't have to assign info to some random string. Unfortunately this type of loop doesn't seem to exist in Ruby. Can anybody suggest a better way of doing this?
**CAUTION**: The `begin <code> end while <condition>` is rejected by Ruby's author Matz. Instead he suggests using `Kernel#loop`, e.g. ``` loop do # some code here break if <condition> end ``` Here's [an email exchange](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-core/6745) in 23 Nov 2005 where Matz states: ``` |> Don't use it please. I'm regretting this feature, and I'd like to |> remove it in the future if it's possible. | |I'm surprised. What do you regret about it? Because it's hard for users to tell begin <code> end while <cond> works differently from <code> while <cond> ``` [RosettaCode wiki](http://rosettacode.org/wiki/Loops/Do-while#Ruby) has a similar story: > > During November 2005, Yukihiro Matsumoto, the creator of Ruby, regretted this loop feature and suggested using Kernel#loop. > > >
136,823
<p>I am trying to integrate the SSRS report to my web page. The code is as follows:</p> <pre><code>ReportViewer1.ProcessingMode = rocessingMode.Remote; ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://localhost/reportserver"); ReportViewer1.ServerReport.ReportPath = "/Report Project1/Reconciliation"; List&lt;ReportParameter&gt; paramList = new List&lt;ReportParameter&gt;(); paramList.Add(new ReportParameter("StartDate", startdate.ToString(), false)); paramList.Add(new ReportParameter("EndDate", enddate.ToString(), false)); this.ReportViewer1.ServerReport.SetParameters(paramList); ReportViewer1.Visible = true; </code></pre> <p>I get this error when I try to run this report:</p> <pre><code>The permissions granted to user 'COMPUTERNAME\\ASPNET' are insufficient for performing this operation. (rsAccessDenied)"} System.Exception {Microsoft.Reporting.WebForms.ReportServerException} </code></pre> <p>Can anyone tell me what I am doing wrong?</p>
[ { "answer_id": 136853, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "<p>The problem is that your ASP.NET worker process does not have the permissions to do what you want.</p>\n\n<p>Edit this us...
2008/09/25
[ "https://Stackoverflow.com/questions/136823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14752/" ]
I am trying to integrate the SSRS report to my web page. The code is as follows: ``` ReportViewer1.ProcessingMode = rocessingMode.Remote; ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://localhost/reportserver"); ReportViewer1.ServerReport.ReportPath = "/Report Project1/Reconciliation"; List<ReportParameter> paramList = new List<ReportParameter>(); paramList.Add(new ReportParameter("StartDate", startdate.ToString(), false)); paramList.Add(new ReportParameter("EndDate", enddate.ToString(), false)); this.ReportViewer1.ServerReport.SetParameters(paramList); ReportViewer1.Visible = true; ``` I get this error when I try to run this report: ``` The permissions granted to user 'COMPUTERNAME\\ASPNET' are insufficient for performing this operation. (rsAccessDenied)"} System.Exception {Microsoft.Reporting.WebForms.ReportServerException} ``` Can anyone tell me what I am doing wrong?
To clarify Erikk's answer a little bit. The particular set of security permissions you want to set to fix this error (there are at least another two types of security settings in Reports Manager) are available in the "security" menu option of the "Properties" tab of the reports folder you are looking at. Obiously it goes without saying you should not give full permission to the "Everyone" group for the Home folder as this is inherited to all other items and subfolders and open a huge security hole.
136,829
<p>In VB.NET (or C#) how can I determine programmatically if a public variable in class helper.vb is used anywhere within a project?</p>
[ { "answer_id": 136847, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>You would need to use reflection and it would be complicated.</p>\n\n<p>Why are you doing this programmaticly? You know t...
2008/09/25
[ "https://Stackoverflow.com/questions/136829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22301/" ]
In VB.NET (or C#) how can I determine programmatically if a public variable in class helper.vb is used anywhere within a project?
From [MSDN](http://msdn.microsoft.com/en-us/library/aa300858(VS.71).aspx) The Find object allows you to search for and replace text in places of the environment that support such operations, such as the Code editor. It is intended primarily for macro recording purposes. The editor's macro recording mechanism uses Find rather than TextSelection.FindPattern so that you can discover the global find functionality, and because it generally is more useful than using the TextSelection Object for such operations as Find-in-files. If the search operation is asynchronous, such as Find All, then the **FindDone** Event occurs when the operation completes. ``` Sub ActionExample() Dim objFind As Find = objTextDoc.DTE.Find ' Set the find options. objFind.Action = vsFindAction.vsFindActionFindAll objFind.Backwards = False objFind.FilesOfType = "*.vb" objFind.FindWhat = "<Variable>" objFind.KeepModifiedDocumentsOpen = False objFind.MatchCase = True objFind.MatchInHiddenText = True objFind.MatchWholeWord = True objFind.PatternSyntax = vsFindPatternSyntax.vsFindPatternSyntaxLiteral objFind.ResultsLocation = vsFindResultsLocation.vsFindResultsNone objFind.SearchPath = "c:\<Your>\<Project>\<Path>" objFind.SearchSubfolders = False objFind.Target = vsFindTarget.vsFindTargetCurrentDocument ' Perform the Find operation. objFind.Execute() End Sub <System.ContextStaticAttribute()> _ Public WithEvents FindEvents As EnvDTE.FindEvents Public Sub FindEvents_FindDone(ByVal Result As EnvDTE.vsFindResult, _ ByVal Cancelled As Boolean) _ Handles FindEvents.FindDone Select Case Result case vsFindResultFound 'Found! case else 'Not Found Ens select End Sub ```
136,836
<p>What is the slickest way to initialize an array of dynamic size in C# that you know of?</p> <p>This is the best I could come up with</p> <pre><code>private bool[] GetPageNumbersToLink(IPagedResult result) { if (result.TotalPages &lt;= 9) return new bool[result.TotalPages + 1].Select(b =&gt; true).ToArray(); ... </code></pre>
[ { "answer_id": 136890, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 0, "selected": false, "text": "<p>Untested, but could you just do this?</p>\n\n<pre><code>return result.Select(p =&gt; true).ToArray();\n</code></pre>\...
2008/09/25
[ "https://Stackoverflow.com/questions/136836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ]
What is the slickest way to initialize an array of dynamic size in C# that you know of? This is the best I could come up with ``` private bool[] GetPageNumbersToLink(IPagedResult result) { if (result.TotalPages <= 9) return new bool[result.TotalPages + 1].Select(b => true).ToArray(); ... ```
use [Enumerable.Repeat](http://msdn.microsoft.com/en-us/library/bb348899%28v=vs.110%29.aspx) ``` Enumerable.Repeat(true, result.TotalPages + 1).ToArray() ```
136,837
<p>A few years ago I developed a web app for which we wanted to make sure the users weren't sharing credentials.</p> <p>One of the things we decided to to, was only allow the user to be logged in from one computer at a time. The way I did this, was to have a little iframe ping the server every N seconds; as long as the server had a heartbeat for a particular user (from a particular IP), that user was not allowed to log in from any other IP.</p> <p>The solution, although approved by my manger, always seemed hacky to me. Also, it seems like it would be easy to circumvent.</p> <p>Is there a good way to make sure a web app user only logs in once? To be honest, I never understood why management even wanted this feature. Does it make sense to enforce this on distributed apps?</p>
[ { "answer_id": 136862, "author": "Taptronic", "author_id": 14728, "author_profile": "https://Stackoverflow.com/users/14728", "pm_score": 1, "selected": false, "text": "<p>In a highly secure application, you may be required to do such. What you can do is keep a login count incrementing t...
2008/09/25
[ "https://Stackoverflow.com/questions/136837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
A few years ago I developed a web app for which we wanted to make sure the users weren't sharing credentials. One of the things we decided to to, was only allow the user to be logged in from one computer at a time. The way I did this, was to have a little iframe ping the server every N seconds; as long as the server had a heartbeat for a particular user (from a particular IP), that user was not allowed to log in from any other IP. The solution, although approved by my manger, always seemed hacky to me. Also, it seems like it would be easy to circumvent. Is there a good way to make sure a web app user only logs in once? To be honest, I never understood why management even wanted this feature. Does it make sense to enforce this on distributed apps?
I've implemented this by maintaining a hashtable of currently logged in users, the key was the username, the value was their last activity time. When logging in, you just check this hashtable for the key, and if it exists, reject the login. When the user does anything, you update the hashtable with the time (This is easy if you make it part of the core page framework). If the time in the hashtable is greater than 20 minutes of inactivity, you remove them. You can do this every time the hashtable is checked, so even if you only had one user, and the tried to login several hours later, during that initial check, it would remove them from the hashtable for being idle. Some examples in C# (Untested): ``` public Dictionary<String,DateTime> UserDictionary { get { if (HttpContext.Current.Cache["UserDictionary"] != null) { return HttpContext.Current.Cache["UserDictionary"] as Dictionary<String,DateTime>; } return new Dictionary<String,DateTime>(); } set { HttpContext.Current.Cache["UserDictionary"] = value; } } public bool IsUserAlreadyLoggedIn(string userName) { removeIdleUsers(); return UserDictionary.ContainsKey(userName); } public void UpdateUser(string userName) { UserDictionary[userName] = DateTime.Now; removeIdleUsers(); } private void removeIdleUsers() { for (int i = 0; i < UserDictionary.Length; i++) { if (user[i].Value < DateTime.Now.AddMinutes(-20)) user.RemoveAt(i); } } ```
136,880
<p>So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions:</p> <ol> <li><p>It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change <em>another</em> function somewhere else. Is this something that just gets easier with experience?</p></li> <li><p>Are the benefits of using const <em>really</em> enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it?</p></li> </ol> <p>I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications.</p>
[ { "answer_id": 136895, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 7, "selected": false, "text": "<p>Here's a piece of code with a common error that const correctness can protect you against:</p>\n\n<pre><code>void foo(con...
2008/09/25
[ "https://Stackoverflow.com/questions/136880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
So why exactly is it that it's always recommended to use const as often as possible? It seems to me that using const can be more of a pain than a help in C++. But then again, I'm coming at this from the python perspective: if you don't want something to be changed, don't change it. So with that said, here are a few questions: 1. It seems like every time I mark something as const, I get an error and have to change some other function somewhere to be const too. Then this causes me to have to change *another* function somewhere else. Is this something that just gets easier with experience? 2. Are the benefits of using const *really* enough to compensate for the trouble? If you don't intend on changing an object, why not just not write code that doesn't change it? I should note that at this point in time, I'm most focused on the benefits of using const for correctness and maintainability purposes, although it is also nice to have an idea of the performance implications.
This is the definitive article on "const correctness": <https://isocpp.org/wiki/faq/const-correctness>. In a nutshell, using const is good practice because... 1. It protects you from accidentally changing variables that aren't intended be changed, 2. It protects you from making accidental variable assignments, and 3. The compiler can optimize it. For instance, you are protected from ``` if( x = y ) // whoops, meant if( x == y ) ``` At the same time, the compiler can generate more efficient code because it knows exactly what the state of the variable/function will be at all times. If you are writing tight C++ code, this is good. You are correct in that it can be difficult to use const-correctness consistently, but the end code is more concise and safer to program with. When you do a lot of C++ development, the benefits of this quickly manifest.
136,884
<p>Is it possible to have a <code>&lt;div&gt;</code> simultaneously (1) not take up all available width and (2) collapse margins with its neighbors?</p> <p>I learned recently that setting a <code>div</code> to <code>display:table</code> will stop it from expanding to take up the whole width of the parent container -- but now I realize that this introduces a new problem: it stops collapsing margins with its neighbors.</p> <p>In the example below, the red div fails to collapse, and the blue div is too wide.</p> <pre><code>&lt;p style="margin:100px"&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; &lt;div style="margin: 100px; border: solid red 2px; display: table;"&gt; This is a div with 100px margin all around and display:table. &lt;br/&gt; The problem is that it doesn't collapse margins with its neighbors. &lt;/div&gt; &lt;p style="margin:100px"&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; &lt;div style="margin: 100px; border: solid blue 2px; display: block;"&gt; This is a div with 100px margin all around and display:block. &lt;br/&gt; The problem is that it expands to take up all available width. &lt;/div&gt; &lt;p style="margin:100px"&gt;This is a paragraph with 100px margin all around.&lt;/p&gt; </code></pre> <p>Is there a way to meet both criteria simultaneously?</p>
[ { "answer_id": 136921, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 2, "selected": true, "text": "<p>You could wrap the <code>display: table</code> <code>div</code> with another <code>div</code> and put the margin on...
2008/09/25
[ "https://Stackoverflow.com/questions/136884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
Is it possible to have a `<div>` simultaneously (1) not take up all available width and (2) collapse margins with its neighbors? I learned recently that setting a `div` to `display:table` will stop it from expanding to take up the whole width of the parent container -- but now I realize that this introduces a new problem: it stops collapsing margins with its neighbors. In the example below, the red div fails to collapse, and the blue div is too wide. ``` <p style="margin:100px">This is a paragraph with 100px margin all around.</p> <div style="margin: 100px; border: solid red 2px; display: table;"> This is a div with 100px margin all around and display:table. <br/> The problem is that it doesn't collapse margins with its neighbors. </div> <p style="margin:100px">This is a paragraph with 100px margin all around.</p> <div style="margin: 100px; border: solid blue 2px; display: block;"> This is a div with 100px margin all around and display:block. <br/> The problem is that it expands to take up all available width. </div> <p style="margin:100px">This is a paragraph with 100px margin all around.</p> ``` Is there a way to meet both criteria simultaneously?
You could wrap the `display: table` `div` with another `div` and put the margin on the wrapper `div` instead. Nasty, but it works. ``` <p style="margin:100px">This is a paragraph with 100px margin all around.</p> <div style="margin: 100px"><div style="border: solid red 2px; display: table;"> This is a div which had 100px margin all around and display:table, but the margin was moved to a wrapper div. <br/> The problem was that it didn't collapse margins with its neighbors. </div></div> <p style="margin:100px">This is a paragraph with 100px margin all around.</p> <div style="margin: 100px; border: solid blue 2px; display: block;"> This is a div with 100px margin all around and display:block. <br/> The problem is that it expands to take up all available width. </div> <p style="margin:100px">This is a paragraph with 100px margin all around.</p> ```
136,899
<p>In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error?</p> <p>If so, in what circumstances would you use this?</p> <p>Code examples are welcome.</p> <p>Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use</p> <pre><code>@fopen($file); </code></pre> <p>and then check afterwards... but you can get rid of the @ by doing</p> <pre><code>if (file_exists($file)) { fopen($file); } else { die('File not found'); } </code></pre> <p>or similar. </p> <p>I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner?</p>
[ { "answer_id": 136912, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 5, "selected": false, "text": "<p>Yes suppression makes sense.</p>\n\n<p>For example, the <code>fopen()</code> command returns <code>FALSE</code> if th...
2008/09/25
[ "https://Stackoverflow.com/questions/136899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20010/" ]
In your opinion, is it ever valid to use the @ operator to suppress an error/warning in PHP whereas you may be handling the error? If so, in what circumstances would you use this? Code examples are welcome. Edit: Note to repliers. I'm not looking to turn error reporting off, but, for example, common practice is to use ``` @fopen($file); ``` and then check afterwards... but you can get rid of the @ by doing ``` if (file_exists($file)) { fopen($file); } else { die('File not found'); } ``` or similar. I guess the question is - is there anywhere that @ HAS to be used to supress an error, that CANNOT be handled in any other manner?
I would suppress the error **and handle it**. Otherwise you may have a **TOCTOU** issue (Time-of-check, time-of-use. For example a file may get deleted after file\_exists returns true, but before fopen). But I wouldn't just suppress errors to make them go away. These better be visible.
136,937
<p>Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.</p>
[ { "answer_id": 136957, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 1, "selected": false, "text": "<p><code>onLocationChange</code> may also be useful. Not sure if this is a Mozilla-only thing though, appears that it might be.</...
2008/09/25
[ "https://Stackoverflow.com/questions/136937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10393/" ]
Is there a way to respond to the back button being hit (or backspace being pressed) in javascript when only the location hash changes? That is to say when the browser is not communicating with the server or reloading the page.
Use the [`hashchange`](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers.onhashchange) event: ``` window.addEventListener("hashchange", function(e) { // ... }) ``` If you need to support older browsers, check out the [`hashChange` Event section](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#hashchange-event) in Modernizr's HTML5 Cross Browser Polyfills wiki page.
136,946
<p>What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)?</p> <p>For example, when should one use</p> <pre><code>enum {BUFFER = 1234}; </code></pre> <p>over</p> <pre><code>#define BUFFER 1234 </code></pre>
[ { "answer_id": 136954, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 7, "selected": true, "text": "<p><code>enum</code> defines a syntactical element.</p>\n\n<p><code>#define</code> is a pre-preprocessor directive, execu...
2008/09/25
[ "https://Stackoverflow.com/questions/136946", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21539/" ]
What's the difference between using a define statement and an enum statement in C/C++ (and is there any difference when using them with either C or C++)? For example, when should one use ``` enum {BUFFER = 1234}; ``` over ``` #define BUFFER 1234 ```
`enum` defines a syntactical element. `#define` is a pre-preprocessor directive, executed *before* the compiler sees the code, and therefore is not a language element of C itself. Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a `#define` made by another. This can be hard to track down.
136,948
<p>I used to be able to launch a locally installed helper application by registering a given mime-type in the Windows registry. This enabled me to allow users to be able to click once on a link to the current install of our internal browser application. This worked fine in Internet Explorer 5 (most of the time) and Firefox but now does not work in Internet Explorer 7.</p> <p>The filename passed to my shell/open/command is not the full physical path to the downloaded install package. The path parameter I am handed by IE is</p> <pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ EIPortal_DEV_2_0_5_4[1].expd" </code></pre> <p>This unfortunately does not resolve to the physical file when calling <code>FileExists()</code> or when attempting to create a <code>TFileStream</code> object.</p> <p>The physical path is missing the Internet Explorer hidden caching sub-directory for Temporary Internet Files of <code>"Content.IE5\ALBKHO3Q"</code> whose absolute path would be expressed as</p> <pre><code>"C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ Content.IE5\ALBKHO3Q\EIPortal_DEV_2_0_5_4[1].expd" </code></pre> <p>Yes, the sub-directories are randomly generated by IE and that should not be a concern so long as IE passes the full path to my helper application, which it unfortunately is not doing.</p> <p>Installation of the mime helper application is not a concern. It is installed/updated by a global login script for all 10,000+ users worldwide. The mime helper is only invoked when the user clicks on an internal web page with a link to an installation of our Desktop browser application. That install is served back with a mime-type of <code>"application/x-expeditors"</code>. The registration of the <code>".expd"</code> / <code>"application/x-expeditors"</code> mime-type looks like this.</p> <pre><code>[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.expd] @="ExpeditorsInstaller" "Content Type"="application/x-expeditors" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller] "EditFlags"=hex:00,00,01,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell] [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open] @="" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open\command] @="\"C:\\projects\\desktop2\\WebInstaller\\WebInstaller.exe\" \"%1\"" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Content Type\application/x-expeditors] "Extension"=".expd" </code></pre> <p>I had considered enumerating all of a user's IE cache entries but I would be concerned with how long it may take to examine them all or that I may end up finding an older cache entry before the current entry I am looking for. However, the bracketed filename suffix <code>"[n]"</code> may be the unique key.</p> <p>I have tried wininet method <code>GetUrlCacheEntryInfo</code> but that requires the URL, not the virtual path handed over by IE.</p> <p>My hope is that there is a Shell function that given a virtual path will hand back the physical path.</p>
[ { "answer_id": 136954, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 7, "selected": true, "text": "<p><code>enum</code> defines a syntactical element.</p>\n\n<p><code>#define</code> is a pre-preprocessor directive, execu...
2008/09/25
[ "https://Stackoverflow.com/questions/136948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13183/" ]
I used to be able to launch a locally installed helper application by registering a given mime-type in the Windows registry. This enabled me to allow users to be able to click once on a link to the current install of our internal browser application. This worked fine in Internet Explorer 5 (most of the time) and Firefox but now does not work in Internet Explorer 7. The filename passed to my shell/open/command is not the full physical path to the downloaded install package. The path parameter I am handed by IE is ``` "C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ EIPortal_DEV_2_0_5_4[1].expd" ``` This unfortunately does not resolve to the physical file when calling `FileExists()` or when attempting to create a `TFileStream` object. The physical path is missing the Internet Explorer hidden caching sub-directory for Temporary Internet Files of `"Content.IE5\ALBKHO3Q"` whose absolute path would be expressed as ``` "C:\Document and Settings\chq-tomc\Local Settings\Temporary Internet Files\ Content.IE5\ALBKHO3Q\EIPortal_DEV_2_0_5_4[1].expd" ``` Yes, the sub-directories are randomly generated by IE and that should not be a concern so long as IE passes the full path to my helper application, which it unfortunately is not doing. Installation of the mime helper application is not a concern. It is installed/updated by a global login script for all 10,000+ users worldwide. The mime helper is only invoked when the user clicks on an internal web page with a link to an installation of our Desktop browser application. That install is served back with a mime-type of `"application/x-expeditors"`. The registration of the `".expd"` / `"application/x-expeditors"` mime-type looks like this. ``` [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.expd] @="ExpeditorsInstaller" "Content Type"="application/x-expeditors" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller] "EditFlags"=hex:00,00,01,00 [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell] [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open] @="" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\ExpeditorsInstaller\shell\open\command] @="\"C:\\projects\\desktop2\\WebInstaller\\WebInstaller.exe\" \"%1\"" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\MIME\Database\Content Type\application/x-expeditors] "Extension"=".expd" ``` I had considered enumerating all of a user's IE cache entries but I would be concerned with how long it may take to examine them all or that I may end up finding an older cache entry before the current entry I am looking for. However, the bracketed filename suffix `"[n]"` may be the unique key. I have tried wininet method `GetUrlCacheEntryInfo` but that requires the URL, not the virtual path handed over by IE. My hope is that there is a Shell function that given a virtual path will hand back the physical path.
`enum` defines a syntactical element. `#define` is a pre-preprocessor directive, executed *before* the compiler sees the code, and therefore is not a language element of C itself. Generally enums are preferred as they are type-safe and more easily discoverable. Defines are harder to locate and can have complex behavior, for example one piece of code can redefine a `#define` made by another. This can be hard to track down.
136,961
<p>I'm using the jQuery Form plugin to upload an image. I've assigned a fade animation to happen the <code>beforeSubmit</code> callback, but as I'm running locally, it doesn't have time to finish before the <code>success</code> function is called. </p> <p>I am using a callback function in my <code>fade();</code> call to make sure that one fade completes, before the next one begins, but that does not seem to guarantee that the function that's calling it is finished.</p> <p>Am I doing something wrong? Shouldn't <code>beforeSubmit</code> complete before the ajax call is submitted?</p> <p>Here's are the two callbacks:</p> <p>beforeSubmit:</p> <pre><code>function prepImageArea() { if (userImage) { userImage.fadeOut(1500, function() { ajaxSpinner.fadeIn(1500); }); } } </code></pre> <p>success:</p> <pre><code>function imageUploaded(data) { var data = evalJson(data); userImage.attr('src', data.large_thumb); ajaxSpinner.fadeOut(1500, function() { userImage.fadeIn(1500); }); } </code></pre>
[ { "answer_id": 137035, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 3, "selected": true, "text": "<p>I think you may be getting too fancy with those fade animations :)... In the beforeSubmit the fadeOut is setup but the functio...
2008/09/25
[ "https://Stackoverflow.com/questions/136961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4636/" ]
I'm using the jQuery Form plugin to upload an image. I've assigned a fade animation to happen the `beforeSubmit` callback, but as I'm running locally, it doesn't have time to finish before the `success` function is called. I am using a callback function in my `fade();` call to make sure that one fade completes, before the next one begins, but that does not seem to guarantee that the function that's calling it is finished. Am I doing something wrong? Shouldn't `beforeSubmit` complete before the ajax call is submitted? Here's are the two callbacks: beforeSubmit: ``` function prepImageArea() { if (userImage) { userImage.fadeOut(1500, function() { ajaxSpinner.fadeIn(1500); }); } } ``` success: ``` function imageUploaded(data) { var data = evalJson(data); userImage.attr('src', data.large_thumb); ajaxSpinner.fadeOut(1500, function() { userImage.fadeIn(1500); }); } ```
I think you may be getting too fancy with those fade animations :)... In the beforeSubmit the fadeOut is setup but the function returns immediately causing the submit to happen. I guess the upload is happening under 3 seconds causing the new image to appear before your animations are complete. So if you really really want this effect, then you will need to do the image fadeout, spinner fadein, and once that is complete triggering the upload. Something like this: ``` if (userImage) { userImage.fadeOut(1500, function() { ajaxSpinner.fadeIn(1500, function(){ //now trigger the upload and you don't need the before submit anymore }); }); } else { // trigger the upload right away } ```
136,975
<p>Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when the objects are deserialized it isn't getting the event handler.</p> <p>In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed.</p> <p>It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once.</p> <p>Is that possible?</p> <p>EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough. </p>
[ { "answer_id": 136994, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 4, "selected": false, "text": "<p>If this is the only handler, you can check to see if the event is null, if it isn't, the handler has been added.</p>\n...
2008/09/25
[ "https://Stackoverflow.com/questions/136975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17145/" ]
Is there a way to tell if an event handler has been added to an object? I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before. However now when the objects are deserialized it isn't getting the event handler. In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object. It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed. It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once. Is that possible? EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough.
From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a `+=` or a `-=`. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is `null` - if so, then no event handler has been added. If not, then maybe and you can loop through the values in [Delegate.GetInvocationList](http://msdn.microsoft.com/en-us/library/system.delegate.getinvocationlist.aspx). If one is equal to the delegate that you want to add as event handler, then you know it's there. ``` public bool IsEventHandlerRegistered(Delegate prospectiveHandler) { if ( this.EventHandler != null ) { foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() ) { if ( existingHandler == prospectiveHandler ) { return true; } } } return false; } ``` And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore `-=` and `+=`, as suggested by @Lou Franco. However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.
136,986
<p>2 tables: </p> <pre><code>Employees - EmployeeID - LeadCount Leads - leadID - employeeID </code></pre> <p>I want to update the <code>Employees.LeadCount</code> column by counting the # of leads in the <code>Leads</code> table that have the same <code>EmployeeID</code>.</p> <p>Note: There may be more than 1 lead with the same employeeID, so I have to do a <code>DISTINCT(SUM(employeeID))</code>.</p>
[ { "answer_id": 137001, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 1, "selected": false, "text": "<pre><code>UPDATE Employees SET LeadCount = (\n SELECT Distinct(SUM(employeeID)) FROM Leads WHERE Leads.employeeId = Em...
2008/09/25
[ "https://Stackoverflow.com/questions/136986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
2 tables: ``` Employees - EmployeeID - LeadCount Leads - leadID - employeeID ``` I want to update the `Employees.LeadCount` column by counting the # of leads in the `Leads` table that have the same `EmployeeID`. Note: There may be more than 1 lead with the same employeeID, so I have to do a `DISTINCT(SUM(employeeID))`.
``` UPDATE Employees E SET E.LeadCount = ( SELECT COUNT(L.EmployeeID) FROM Leads L WHERE L.EmployeeID = E.EmployeeID ) ```
137,006
<p>Is there any way to redefine a class or some of its methods without using typical inheritance? For example:</p> <pre><code>class third_party_library { function buggy_function() { return 'bad result'; } function other_functions(){ return 'blah'; } } </code></pre> <p>What can I do to replace <code>buggy_function()</code>? Obviously this is what I would like to do</p> <pre><code>class third_party_library redefines third_party_library{ function buggy_function() { return 'good result'; } function other_functions(){ return 'blah'; } } </code></pre> <p>This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method.</p> <p>I've found this <a href="http://pecl.php.net/package/classkit" rel="noreferrer">library</a> that says it can do it, but I'm wary as it's 4 years old.</p> <p>EDIT:</p> <p>I should have clarified that I cannot rename the class from <code>third_party_library</code> to <code>magical_third_party_library</code> or anything else because of framework limitations.</p> <p>For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a &quot;partial class.&quot;</p>
[ { "answer_id": 137017, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 1, "selected": false, "text": "<p>Zend Studio and PDT (eclipse based ide) have some built in refractoring tools. But there are no built in methods t...
2008/09/26
[ "https://Stackoverflow.com/questions/137006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
Is there any way to redefine a class or some of its methods without using typical inheritance? For example: ``` class third_party_library { function buggy_function() { return 'bad result'; } function other_functions(){ return 'blah'; } } ``` What can I do to replace `buggy_function()`? Obviously this is what I would like to do ``` class third_party_library redefines third_party_library{ function buggy_function() { return 'good result'; } function other_functions(){ return 'blah'; } } ``` This is my exact dilemma: I updated a third party library that breaks my code. I don't want to modify the library directly, as future updates could break the code again. I'm looking for a seamless way to replace the class method. I've found this [library](http://pecl.php.net/package/classkit) that says it can do it, but I'm wary as it's 4 years old. EDIT: I should have clarified that I cannot rename the class from `third_party_library` to `magical_third_party_library` or anything else because of framework limitations. For my purposes, would it be possible to just add a function to the class? I think you can do this in C# with something called a "partial class."
It's called [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch). But, PHP doesn't have native support for it. Though, as others have also pointed out, the [runkit library](http://docs.php.net/runkit) is available for adding support to the language and is the successor to [classkit](http://docs.php.net/manual/en/book.classkit.php). And, though it seemed to have been [abandoned](http://pecl.php.net/package/runkit) by its creator (having stated that it wasn't compatible with PHP 5.2 and later), the project does now appear to have a [new home and maintainer](https://github.com/zenovich/runkit). I still [can't say I'm a fan](https://stackoverflow.com/revisions/137028/3) of its approach. Making modifications by evaluating strings of code has always seemed to me to be potentially hazardous and difficult to debug. Still, [`runkit_method_redefine`](http://us2.php.net/manual/en/function.runkit-method-redefine.php) appears to be what you're looking for, and an example of its use can be found in [`/tests/runkit_method_redefine.phpt`](https://github.com/zenovich/runkit/blob/master/tests/runkit_method_redefine.phpt) in the repository: ```php runkit_method_redefine('third_party_library', 'buggy_function', '', 'return \'good result\'' ); ```
137,038
<p>How does one do this?</p> <p>If I want to analyze how something is getting compiled, how would I get the emitted assembly code?</p>
[ { "answer_id": 137044, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 5, "selected": false, "text": "<p>Use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S\" rel=\"nofollow noreferrer\">-S</a> sw...
2008/09/26
[ "https://Stackoverflow.com/questions/137038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
How does one do this? If I want to analyze how something is getting compiled, how would I get the emitted assembly code?
Use the [-S](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S) option to `gcc` (or `g++`), optionally with [-fverbose-asm](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm) which works well at the default [-O0](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0) to attach C names to asm operands as comments. It works less well at any optimization level, which you normally want to use to get asm worth looking at. ```none gcc -S helloworld.c ``` This will run the preprocessor (cpp) over *helloworld.c*, perform the initial compilation and then stop before the assembler is run. For useful compiler options to use in that case, see *[How to remove "noise" from GCC/clang assembly output?](https://stackoverflow.com/questions/38552116/how-to-remove-noise-from-gcc-clang-assembly-output)* (or just **look at your code on [Matt Godbolt's online Compiler Explorer](https://godbolt.org/)** which filters out directives and stuff, and has highlighting to match up source lines with asm using debug information.) By default, this will output the file `helloworld.s`. The output file can be still be set by using the [-o](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-o) option, including `-o -` to write to [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_.28stdout.29) for pipe into [less](https://en.wikipedia.org/wiki/Less_(Unix)). ```none gcc -S -o my_asm_output.s helloworld.c ``` Of course, this only works if you have the original source. An alternative if you only have the resultant object file is to use [objdump](https://linux.die.net/man/1/objdump), by setting the `--disassemble` option (or `-d` for the abbreviated form). ```none objdump -S --disassemble helloworld > helloworld.dump ``` `-S` interleaves source lines with normal disassembly output, so this option works best if debugging option is enabled for the object file ([-g](https://gcc.gnu.org/onlinedocs/gcc/Debugging-Options.html#index-g) at compilation time) and the file hasn't been stripped. Running `file helloworld` will give you some indication as to the level of detail that you will get by using *objdump*. Other useful `objdump` options include `-rwC` (to show symbol relocations, disable line-wrapping of long machine code, and demangle C++ names). And if you don't like AT&T syntax for x86, `-Mintel`. See [the man page](https://man7.org/linux/man-pages/man1/objdump.1.html). So for example, `objdump -drwC -Mintel -S foo.o | less`. `-r` is very important with a `.o` that only has `00 00 00 00` placeholders for symbol references, as opposed to a linked executable.
137,043
<p>When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this:</p> <pre><code> &lt;table&gt; &lt;tr&gt; &lt;td&gt;blah&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt; </code></pre> <p>...into this:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; blah &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
[ { "answer_id": 137139, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.delorie.com/gnu/docs/emacs/emacs_277.html\" rel=\"noreferrer\">http://www.delorie.com/gnu/docs/emacs/e...
2008/09/26
[ "https://Stackoverflow.com/questions/137043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7598/" ]
When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this: ``` <table> <tr> <td>blah</td></tr></table> ``` ...into this: ``` <table> <tr> <td> blah </td> </tr> </table> ```
By default, when you visit a `.html` file in Emacs (22 or 23), it will put you in `html-mode`. That is probably not what you want. You probably want `nxml-mode`, which is seriously fancy. `nxml-mode` seems to only come with Emacs 23, although you can download it for earlier versions of emacs from the [nXML web site](http://www.thaiopensource.com/nxml-mode/). There is also a Debian and Ubuntu package named `nxml-mode`. You can enter `nxml-mode` with: ``` M-x nxml-mode ``` You can view nxml mode documentation with: ``` C-h i g (nxml-mode) RET ``` All that being said, you will probably have to use something like [Tidy](http://tidy.sourceforge.net/) to re-format your xhtml example. `nxml-mode` will get you from ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body> <table> <tr> <td>blah</td></tr></table> </body> ``` to ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body> <table> <tr> <td>blah</td></tr></table> </body> </html> ``` but I don't see a more general facility to do line breaks on certain xml tags as you want. Note that `C-j` will insert a new line with proper indentation, so you may be able to do a quick macro or hack up a `defun` that will do your tables.
137,054
<p>How can I validate that my ASPNET AJAX installation is correct.</p> <p>I have Visual Studio 2008 and had never previously installed any AJAX version.</p> <p>My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it reverts back to 'normal' ASPX type behavior.</p> <p>I tried installing AJAX from <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&amp;displaylang=en" rel="nofollow noreferrer">MSDN</a> followed by an IISRESET yet still it is still not working properly.</p> <p>What can I check to diagnose the problem?</p> <p><strong>Update:</strong> When running within Visual Studio (Cassini) I get the following 3 requests shown in Fiddler:</p> <pre><code>http://localhost:1105/RRStatistics/WebResource.axd?d=k5J0oI4tNNc1xbK-2DAgZg2&amp;t=633564733834698722 http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4k3shu0R2ly5WhH2vI_IbNVcTbxej1dkbdYFXrN6c7Qw1&amp;t=ffffffff867086f6 http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4AsqNeJVXGSf6sCcCp1QK0jdKTlbRqIN1LFVP8w6R0lJ_vbk-CfopYINgjYsHpWfP0&amp;t=ffffffff867086f6 </code></pre> <p>but when I run within IIS i only get this single request :</p> <pre><code>http://www.example.com/RRStatistics/ScriptResource.axd?d=f_uL3BYT2usKhP7VtSYNUxxYRLVrX5rhnXUonvvzSEIc1qA5dLOlcdNr9xlkSQcnZKyBHj1nI523o9DjxNr45hRpHF7xxC5WlhImxu9TALw1&amp;t=ffffffff867086f6 </code></pre> <p>Now the second request in Cassini contains a javascript file with 'partial rendering' as one of the first comments. I'm sure this is the source of the problem, but I cannot figure out why in IIS i dont get the other requests.</p>
[ { "answer_id": 137139, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://www.delorie.com/gnu/docs/emacs/emacs_277.html\" rel=\"noreferrer\">http://www.delorie.com/gnu/docs/emacs/e...
2008/09/26
[ "https://Stackoverflow.com/questions/137054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
How can I validate that my ASPNET AJAX installation is correct. I have Visual Studio 2008 and had never previously installed any AJAX version. My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it reverts back to 'normal' ASPX type behavior. I tried installing AJAX from [MSDN](http://www.microsoft.com/downloads/details.aspx?FamilyID=ca9d90fa-e8c9-42e3-aa19-08e2c027f5d6&displaylang=en) followed by an IISRESET yet still it is still not working properly. What can I check to diagnose the problem? **Update:** When running within Visual Studio (Cassini) I get the following 3 requests shown in Fiddler: ``` http://localhost:1105/RRStatistics/WebResource.axd?d=k5J0oI4tNNc1xbK-2DAgZg2&t=633564733834698722 http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4k3shu0R2ly5WhH2vI_IbNVcTbxej1dkbdYFXrN6c7Qw1&t=ffffffff867086f6 http://localhost:1105/RRStatistics/ScriptResource.axd?d=N8BdmNpXVve13PiOuRcss0GMKpoTBFsi7UcScm-WmXE9jw5qOijeLDcIyiOsSQZ4AsqNeJVXGSf6sCcCp1QK0jdKTlbRqIN1LFVP8w6R0lJ_vbk-CfopYINgjYsHpWfP0&t=ffffffff867086f6 ``` but when I run within IIS i only get this single request : ``` http://www.example.com/RRStatistics/ScriptResource.axd?d=f_uL3BYT2usKhP7VtSYNUxxYRLVrX5rhnXUonvvzSEIc1qA5dLOlcdNr9xlkSQcnZKyBHj1nI523o9DjxNr45hRpHF7xxC5WlhImxu9TALw1&t=ffffffff867086f6 ``` Now the second request in Cassini contains a javascript file with 'partial rendering' as one of the first comments. I'm sure this is the source of the problem, but I cannot figure out why in IIS i dont get the other requests.
By default, when you visit a `.html` file in Emacs (22 or 23), it will put you in `html-mode`. That is probably not what you want. You probably want `nxml-mode`, which is seriously fancy. `nxml-mode` seems to only come with Emacs 23, although you can download it for earlier versions of emacs from the [nXML web site](http://www.thaiopensource.com/nxml-mode/). There is also a Debian and Ubuntu package named `nxml-mode`. You can enter `nxml-mode` with: ``` M-x nxml-mode ``` You can view nxml mode documentation with: ``` C-h i g (nxml-mode) RET ``` All that being said, you will probably have to use something like [Tidy](http://tidy.sourceforge.net/) to re-format your xhtml example. `nxml-mode` will get you from ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body> <table> <tr> <td>blah</td></tr></table> </body> ``` to ```html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body> <table> <tr> <td>blah</td></tr></table> </body> </html> ``` but I don't see a more general facility to do line breaks on certain xml tags as you want. Note that `C-j` will insert a new line with proper indentation, so you may be able to do a quick macro or hack up a `defun` that will do your tables.
137,089
<p>I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code:</p> <pre><code>#include &lt;boost/signal.hpp&gt; typedef boost::signal&lt;void (void)&gt; Event; int main(int argc, char* argv[]) { Event e; return 0; } </code></pre> <p>Thanks!</p> <p>Edit: This was Boost 1.36.0 compiled with Visual Studio 2008 w/ SP1. Boost::filesystem, like boost::signal also has a library that must be linked in, and it seems to work fine. All the other boost libraries I use are headers-only, I believe.</p>
[ { "answer_id": 137175, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": true, "text": "<p>I've tested your code on my system, and it works fine. I think that there's a mismatch between your compiler, and the comp...
2008/09/26
[ "https://Stackoverflow.com/questions/137089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114/" ]
I'm trying to use boost::signal to implement a callback mechanism, and I'm getting a memory access assert in the boost::signal code on even the most trivial usage of the library. I have simplified it down to this code: ``` #include <boost/signal.hpp> typedef boost::signal<void (void)> Event; int main(int argc, char* argv[]) { Event e; return 0; } ``` Thanks! Edit: This was Boost 1.36.0 compiled with Visual Studio 2008 w/ SP1. Boost::filesystem, like boost::signal also has a library that must be linked in, and it seems to work fine. All the other boost libraries I use are headers-only, I believe.
I've tested your code on my system, and it works fine. I think that there's a mismatch between your compiler, and the compiler that your Boost.Signals library is built on. Try to download the Boost source, and compile Boost.Signals using the same compiler as you use for building your code. Just for my info, what compiler (and version) are you using?
137,091
<p>At my new workplace, they represent a lot of dates as "days since epoch" (which I will hereafter call DSE). I'm running into issues in JavaScript converting from DSE to seconds since epoch (UNIX timestamps). Here's my function to do the conversion:</p> <pre><code>function daysToTimestamp(days) { return Math.round(+days * 86400); } </code></pre> <p>By way of example, when I pass in 13878 (expecting that this represents January 1, 2008), I get back 1199059200, not 1199098800 as I expect. Why?</p>
[ { "answer_id": 137119, "author": "pfranza", "author_id": 22221, "author_profile": "https://Stackoverflow.com/users/22221", "pm_score": 2, "selected": false, "text": "<p>It is because it is neither a linear representation of time nor a true representation of UTC (though it is frequently m...
2008/09/26
[ "https://Stackoverflow.com/questions/137091", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
At my new workplace, they represent a lot of dates as "days since epoch" (which I will hereafter call DSE). I'm running into issues in JavaScript converting from DSE to seconds since epoch (UNIX timestamps). Here's my function to do the conversion: ``` function daysToTimestamp(days) { return Math.round(+days * 86400); } ``` By way of example, when I pass in 13878 (expecting that this represents January 1, 2008), I get back 1199059200, not 1199098800 as I expect. Why?
It is because it is neither a linear representation of time nor a true representation of UTC (though it is frequently mistaken for both) as the times it represents are UTC but it has no way of representing UTC leap seconds <http://en.wikipedia.org/wiki/Unix_time>
137,092
<p>I will soon be working on AJAX driven web pages that have a lot of content generated from a Web Service (WCF).</p> <p>I've tested this sort of thing in the past (and found it easy) but not with this level of dynamic content.</p> <p>I'm developing in .NET 3.5 using Visual Studio 2008. I envisage this testing in:</p> <ol> <li>TestDriven.NET</li> <li>MBUnit (this is not <strong>Unit</strong> testing though)</li> <li>Some sort of automation tool to control browsers (Maybe Selenium, though it might be SWEA or Watin. I'm thinking IE,Firefox, and likely Opera and Safari.)</li> </ol> <p>In the past I've used delays when testing the browser. I don't particularly like doing that and it wastes time.</p> <p><strong>What experience and practice is there for doing things better</strong>, than using waits. Maybe introducing callbacks and a functional style of programming to run the tests in?</p> <hr> <p><strong>Notes 1. More detail after reviewing first 3 replies.</strong></p> <p>1) Thanks Alan, Eran and marxidad, your replies have set me on the track to getting my answer, hopefully without too much time spent.</p> <p>2) Another detail, I'm using <strong>jQuery</strong> to run the Ajax, so this is not built in Asp.NET AJAX.</p> <p>3) I found an article which <strong>illustrates the situation</strong> nicely. It's from <a href="http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/" rel="nofollow noreferrer" title="WatiN, Watir, Selenium review">http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/</a></p> <p>3.1) <strong>Selenium</strong> Sample (This and the next, WatiN, code sample do not show up in the original web page (on either IE or Firefox) so I've extracted them and listed them here.)</p> <pre><code>public void MinAndMaxPriceRestoredWhenOpenedAfterUsingBackButton(){ OpenBrowserTo("welcome/index.rails"); bot.Click("priceDT"); WaitForText("Price Range"); WaitForText("515 N. County Road"); bot.Select("MaxDropDownList", "$5,000,000"); WaitForText("Prewar 8 Off Fifth Avenue"); bot.Select("MinDropDownList", "$2,000,000"); WaitForText("of 86"); bot.Click("link=Prewar 8 Off Fifth Avenue"); WaitForText("Rarely available triple mint restoration"); bot.GoBack(); Thread.Sleep(20000); bot.Click("priceDT"); WaitForText("Price Range"); Assert.AreEqual("$5,000,000", bot.GetSelectedLabel("MaxDropDownList")); Assert.AreEqual("$2,000,000", bot.GetSelectedLabel("MinDropDownList"));} </code></pre> <p>3.2) <strong>WatiN</strong> sample</p> <pre><code>public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){ OpenBrowserTo("welcome/index.rails"); ClickLink("Price"); SelectMaxPrice("$5,000,000"); SelectMinPrice("$2,000,000"); ClickLink("Prewar 8 Off Fifth Avenue"); GoBack(); ClickLink("Price"); Assert.AreEqual("$5,000,000", SelectedMaxPrice()); Assert.AreEqual("$2,000,000", SelectedMinPrice());} </code></pre> <p>3.3) If you look at these, apparently equivalent, samples you can see that the WatiN sample has <strong>abstracted away the waits</strong>.</p> <p>3.4) However it may be that WatiN needs <strong>additional support</strong> for values changed by Ajax calls as noted in <a href="http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html" rel="nofollow noreferrer" title="Using WatiN with Ajax">http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html</a>. In that article the page is given an additional field which can be used to synthesize a changed event, like so:</p> <pre><code>// Wait until the value of the watintoken attribute is changed ie.SelectList("countries").WaitUntil(!Find.By("watintoken",watintoken)); </code></pre> <p>4) Now what I'm after is a way to do something <strong>like what we see in the WatiN code without that synthesized event</strong>. It could be a way to directly hook into events, like changed events. I wouldn't have problems with callbacks either though that could change the way tests are coded. I also think we'll see alternate ways of writing tests as the implications of new features in C# 3, VB 9 and F# start to sink in (and wouldn't mind exploring that).</p> <p>5) marxidad, my source didn't have a sample from WebAii so I haven't got any comments on this, interesting looking, tool.</p> <hr> <p><strong>Notes 2. 2008-09-29. After some feedback independent of this page.</strong></p> <p>5) I attempted to get more complete source for the WatiN sample code above. Unfortunately it's no longer available, the link is dead. When doing that I noticed talk of a DSL, presumably a model that maps between the web page and the automation tool. I found no details on that.</p> <p>6) For the WebAii it was suggested code like this (it's not tested) would be used:</p> <pre><code>public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){ ActiveBrowser.NavigateTo("welcome/index.rails"); Find.ByContent&lt;HtmlAnchor&gt;("Price").Click(); HtmlSelect maxPrice = Find.ById&lt;HtmlSelect&gt;("MaxDropDownList"); HtmlSelect minPrice = Find.ById&lt;HtmlSelect&gt;("MinDropDownList"); maxPrice.SelectByText("$5,000,000"); minPrice.SelectByText("$2,000,000"); Find.ByContent&lt;HtmlAnchor&gt;("Prewar 8 Off Fifth Avenue").Click(); ActiveBrowser.GoBack(); Find.ByContent&lt;HtmlAnchor&gt;("Price").Click(); maxPrice.AssertSelect().SelectedText("$5,000,000"); minPrice.AssertSelect().SelectedText("$2,000,000");} </code></pre> <p>6) From the code I can clearly avoid waits and delays, with some of the frameworks, but I will need to spend more time to see whether WatiN is right for me. </p>
[ { "answer_id": 137546, "author": "Alan", "author_id": 9916, "author_profile": "https://Stackoverflow.com/users/9916", "pm_score": 2, "selected": false, "text": "<p>Most automation frameworks have some synchronizationfunctions built in. Selenium is no exception, and includes functionality...
2008/09/26
[ "https://Stackoverflow.com/questions/137092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21930/" ]
I will soon be working on AJAX driven web pages that have a lot of content generated from a Web Service (WCF). I've tested this sort of thing in the past (and found it easy) but not with this level of dynamic content. I'm developing in .NET 3.5 using Visual Studio 2008. I envisage this testing in: 1. TestDriven.NET 2. MBUnit (this is not **Unit** testing though) 3. Some sort of automation tool to control browsers (Maybe Selenium, though it might be SWEA or Watin. I'm thinking IE,Firefox, and likely Opera and Safari.) In the past I've used delays when testing the browser. I don't particularly like doing that and it wastes time. **What experience and practice is there for doing things better**, than using waits. Maybe introducing callbacks and a functional style of programming to run the tests in? --- **Notes 1. More detail after reviewing first 3 replies.** 1) Thanks Alan, Eran and marxidad, your replies have set me on the track to getting my answer, hopefully without too much time spent. 2) Another detail, I'm using **jQuery** to run the Ajax, so this is not built in Asp.NET AJAX. 3) I found an article which **illustrates the situation** nicely. It's from [http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/](http://adamesterline.com/2007/04/23/watin-watir-and-selenium-reviewed/ "WatiN, Watir, Selenium review") 3.1) **Selenium** Sample (This and the next, WatiN, code sample do not show up in the original web page (on either IE or Firefox) so I've extracted them and listed them here.) ``` public void MinAndMaxPriceRestoredWhenOpenedAfterUsingBackButton(){ OpenBrowserTo("welcome/index.rails"); bot.Click("priceDT"); WaitForText("Price Range"); WaitForText("515 N. County Road"); bot.Select("MaxDropDownList", "$5,000,000"); WaitForText("Prewar 8 Off Fifth Avenue"); bot.Select("MinDropDownList", "$2,000,000"); WaitForText("of 86"); bot.Click("link=Prewar 8 Off Fifth Avenue"); WaitForText("Rarely available triple mint restoration"); bot.GoBack(); Thread.Sleep(20000); bot.Click("priceDT"); WaitForText("Price Range"); Assert.AreEqual("$5,000,000", bot.GetSelectedLabel("MaxDropDownList")); Assert.AreEqual("$2,000,000", bot.GetSelectedLabel("MinDropDownList"));} ``` 3.2) **WatiN** sample ``` public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){ OpenBrowserTo("welcome/index.rails"); ClickLink("Price"); SelectMaxPrice("$5,000,000"); SelectMinPrice("$2,000,000"); ClickLink("Prewar 8 Off Fifth Avenue"); GoBack(); ClickLink("Price"); Assert.AreEqual("$5,000,000", SelectedMaxPrice()); Assert.AreEqual("$2,000,000", SelectedMinPrice());} ``` 3.3) If you look at these, apparently equivalent, samples you can see that the WatiN sample has **abstracted away the waits**. 3.4) However it may be that WatiN needs **additional support** for values changed by Ajax calls as noted in [http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html](http://watinandmore.blogspot.com/2008/01/using-watin-to-test-select-lists-in.html "Using WatiN with Ajax"). In that article the page is given an additional field which can be used to synthesize a changed event, like so: ``` // Wait until the value of the watintoken attribute is changed ie.SelectList("countries").WaitUntil(!Find.By("watintoken",watintoken)); ``` 4) Now what I'm after is a way to do something **like what we see in the WatiN code without that synthesized event**. It could be a way to directly hook into events, like changed events. I wouldn't have problems with callbacks either though that could change the way tests are coded. I also think we'll see alternate ways of writing tests as the implications of new features in C# 3, VB 9 and F# start to sink in (and wouldn't mind exploring that). 5) marxidad, my source didn't have a sample from WebAii so I haven't got any comments on this, interesting looking, tool. --- **Notes 2. 2008-09-29. After some feedback independent of this page.** 5) I attempted to get more complete source for the WatiN sample code above. Unfortunately it's no longer available, the link is dead. When doing that I noticed talk of a DSL, presumably a model that maps between the web page and the automation tool. I found no details on that. 6) For the WebAii it was suggested code like this (it's not tested) would be used: ``` public void MinAndMaxPriceRestoredWhenOpenAfterUsingBackButton(){ ActiveBrowser.NavigateTo("welcome/index.rails"); Find.ByContent<HtmlAnchor>("Price").Click(); HtmlSelect maxPrice = Find.ById<HtmlSelect>("MaxDropDownList"); HtmlSelect minPrice = Find.ById<HtmlSelect>("MinDropDownList"); maxPrice.SelectByText("$5,000,000"); minPrice.SelectByText("$2,000,000"); Find.ByContent<HtmlAnchor>("Prewar 8 Off Fifth Avenue").Click(); ActiveBrowser.GoBack(); Find.ByContent<HtmlAnchor>("Price").Click(); maxPrice.AssertSelect().SelectedText("$5,000,000"); minPrice.AssertSelect().SelectedText("$2,000,000");} ``` 6) From the code I can clearly avoid waits and delays, with some of the frameworks, but I will need to spend more time to see whether WatiN is right for me.
Most automation frameworks have some synchronizationfunctions built in. Selenium is no exception, and includes functionality like waitForText, waitForElementPresent,etc. I just realized that you mentioned "waits" above, which I interpreted as Sleeps (which aren't good in automation). Let me know if I misinterpreted, and I can talk more about wait\* functions or alternatives.
137,114
<p>Whats the best way to round in VBA Access?</p> <p>My current method utilizes the Excel method</p> <pre><code>Excel.WorksheetFunction.Round(... </code></pre> <p>But I am looking for a means that does not rely on Excel.</p>
[ { "answer_id": 137136, "author": "inglesp", "author_id": 10439, "author_profile": "https://Stackoverflow.com/users/10439", "pm_score": 2, "selected": false, "text": "<p>Int and Fix are both useful rounding functions, which give you the integer part of a number.</p>\n\n<p>Int always round...
2008/09/26
[ "https://Stackoverflow.com/questions/137114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
Whats the best way to round in VBA Access? My current method utilizes the Excel method ``` Excel.WorksheetFunction.Round(... ``` But I am looking for a means that does not rely on Excel.
Be careful, the VBA Round function uses Banker's rounding, where it rounds .5 to an even number, like so: ``` Round (12.55, 1) would return 12.6 (rounds up) Round (12.65, 1) would return 12.6 (rounds down) Round (12.75, 1) would return 12.8 (rounds up) ``` Whereas the Excel Worksheet Function Round, always rounds .5 up. I've done some tests and it looks like .5 up rounding (symmetric rounding) is also used by cell formatting, and also for Column Width rounding (when using the General Number format). The 'Precision as displayed' flag doesn't appear to do any rounding itself, it just uses the rounded result of the cell format. I tried to implement the SymArith function from Microsoft in VBA for my rounding, but found that Fix has an error when you try to give it a number like 58.55; the function giving a result of 58.5 instead of 58.6. I then finally discovered that you can use the Excel Worksheet Round function, like so: > > **Application.Round(58.55, 1)** > > > This will allow you to do normal rounding in VBA, though it may not be as quick as some custom function. I realize that this has come full circle from the question, but wanted to include it for completeness.
137,147
<p>For example</p> <pre><code>int f(int a) { ... return a &gt; 10; } </code></pre> <p>is that considered acceptable (not legal, I mean is it ``good code''), or should it always be in a conditional, like this</p> <pre><code>int f(int a) { ... if (a &gt; 10) return 1; else return 0; } </code></pre>
[ { "answer_id": 137152, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "<p>This is absolutely acceptable! In fact, Joel mentioned this on the latest stackoverflow podcast. He said it was the on...
2008/09/26
[ "https://Stackoverflow.com/questions/137147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For example ``` int f(int a) { ... return a > 10; } ``` is that considered acceptable (not legal, I mean is it ``good code''), or should it always be in a conditional, like this ``` int f(int a) { ... if (a > 10) return 1; else return 0; } ```
This is absolutely acceptable! In fact, Joel mentioned this on the latest stackoverflow podcast. He said it was the one thing he's had to show almost every programmer that starts at Fog Creek.
137,181
<p>I need to rebuild an apache server, but the original source is no longer available. Is there any way ( command line switch to httpd? ) to get the build options which were originally used?</p>
[ { "answer_id": 137200, "author": "David Schlosnagle", "author_id": 1750, "author_profile": "https://Stackoverflow.com/users/1750", "pm_score": 4, "selected": true, "text": "<p>Try -V which \"Print the version and build parameters of httpd, and then exit.\"</p>\n\n<pre><code>httpd -V\n</c...
2008/09/26
[ "https://Stackoverflow.com/questions/137181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3839/" ]
I need to rebuild an apache server, but the original source is no longer available. Is there any way ( command line switch to httpd? ) to get the build options which were originally used?
Try -V which "Print the version and build parameters of httpd, and then exit." ``` httpd -V ``` Also, you can see the options for httpd via: ``` httpd -h ```
137,212
<p>If you want a cryptographically strong random numbers in Java, you use <code>SecureRandom</code>. Unfortunately, <code>SecureRandom</code> can be very slow. If it uses <code>/dev/random</code> on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty?</p> <p>Has anyone used <a href="https://uncommons-maths.dev.java.net/" rel="noreferrer">Uncommon Maths</a> as a solution to this problem?</p> <p>Can anybody confirm that this performance problem has been solved in JDK 6?</p>
[ { "answer_id": 137223, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "<p>I haven't hit against this problem myself, but I'd spawn a thread at program start which immediately tries to generate a see...
2008/09/26
[ "https://Stackoverflow.com/questions/137212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3150/" ]
If you want a cryptographically strong random numbers in Java, you use `SecureRandom`. Unfortunately, `SecureRandom` can be very slow. If it uses `/dev/random` on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty? Has anyone used [Uncommon Maths](https://uncommons-maths.dev.java.net/) as a solution to this problem? Can anybody confirm that this performance problem has been solved in JDK 6?
If you want true random data, then unfortunately you have to wait for it. This includes the seed for a `SecureRandom` PRNG. Uncommon Maths can't gather true random data any faster than `SecureRandom`, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than `/dev/random` where that's available. If you want a PRNG, do something like this: ``` SecureRandom.getInstance("SHA1PRNG"); ``` What strings are supported depends on the `SecureRandom` SPI provider, but you can enumerate them using `Security.getProviders()` and `Provider.getService()`. Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy. The exception is that if you don't call `setSeed()` before getting data, then the PRNG will seed itself once the first time you call `next()` or `nextBytes()`. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.
137,219
<p>I am looking for the way to mount NTFS hard disk on FreeBSD 6.2 in read/write mode.</p> <p>searching google, I found that NTFS-3G can be a help.</p> <p>Using NTFS-3G, there is no problem when I try to mount/unmount NTFS manually:</p> <p>mount: ntfs-3g /dev/ad1s1 /home/admin/data -o uid=1002,</p> <p>or</p> <p>umount: umount /home/admin/data</p> <p>But I have a problem when try to mount ntfs hard disk automatically at boot time.</p> <p>I have tried: </p> <ul> <li>adding fstab: /dev/ad1s1 /home/admin/data ntfs-3g uid=1002 0 0</li> <li>make a script, that automatically mount ntfs partition at start up, on /usr/local/etc/rc.d/ directory.</li> </ul> <p>But it is still failed. The script works well when it is executed manually.</p> <p>Does anyone know an alternative method/ solution to have read/write access NTFS on FreeBSD 6.2?</p> <p>Thanks.</p>
[ { "answer_id": 137223, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 2, "selected": false, "text": "<p>I haven't hit against this problem myself, but I'd spawn a thread at program start which immediately tries to generate a see...
2008/09/26
[ "https://Stackoverflow.com/questions/137219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am looking for the way to mount NTFS hard disk on FreeBSD 6.2 in read/write mode. searching google, I found that NTFS-3G can be a help. Using NTFS-3G, there is no problem when I try to mount/unmount NTFS manually: mount: ntfs-3g /dev/ad1s1 /home/admin/data -o uid=1002, or umount: umount /home/admin/data But I have a problem when try to mount ntfs hard disk automatically at boot time. I have tried: * adding fstab: /dev/ad1s1 /home/admin/data ntfs-3g uid=1002 0 0 * make a script, that automatically mount ntfs partition at start up, on /usr/local/etc/rc.d/ directory. But it is still failed. The script works well when it is executed manually. Does anyone know an alternative method/ solution to have read/write access NTFS on FreeBSD 6.2? Thanks.
If you want true random data, then unfortunately you have to wait for it. This includes the seed for a `SecureRandom` PRNG. Uncommon Maths can't gather true random data any faster than `SecureRandom`, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than `/dev/random` where that's available. If you want a PRNG, do something like this: ``` SecureRandom.getInstance("SHA1PRNG"); ``` What strings are supported depends on the `SecureRandom` SPI provider, but you can enumerate them using `Security.getProviders()` and `Provider.getService()`. Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy. The exception is that if you don't call `setSeed()` before getting data, then the PRNG will seed itself once the first time you call `next()` or `nextBytes()`. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.
137,221
<p>I've searched around for a while today, but I haven't been able to come up with an AutoComplete TextBox code sample for Silverlight 2 Beta 2. The most promising reference was found on <a href="http://www.nikhilk.net/Silverlight-AutoComplete.aspx/" rel="nofollow noreferrer">nikhilk.net</a> but the online demo doesn't currently render and after downloading a getting the code to compile with Beta 2, I couldn't get the Silverlight plugin it to render either. I think it is fair to say it is a compatibility issue, but I'm not sure. Does anyone have any alternate sample code or implementation suggestions?</p>
[ { "answer_id": 137231, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 1, "selected": false, "text": "<p>Take a look at the combobox(very close to a autocomplete text box) at worksight's blog <a href=\"http://worksightbl...
2008/09/26
[ "https://Stackoverflow.com/questions/137221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4115/" ]
I've searched around for a while today, but I haven't been able to come up with an AutoComplete TextBox code sample for Silverlight 2 Beta 2. The most promising reference was found on [nikhilk.net](http://www.nikhilk.net/Silverlight-AutoComplete.aspx/) but the online demo doesn't currently render and after downloading a getting the code to compile with Beta 2, I couldn't get the Silverlight plugin it to render either. I think it is fair to say it is a compatibility issue, but I'm not sure. Does anyone have any alternate sample code or implementation suggestions?
You may want to take a look at my blog: <http://weblogs.manas.com.ar/ary/2008/09/26/autocomplete-in-silverlight/> You simply write in your XAML: ``` manas:Autocomplete.Suggest="DoSuggest" ``` and then in the class file, you need to implement that method, which report suggestions to a delegate. The options can be hardcoded, requested to a web service, or whaterver.
137,227
<p>How can I list all the types that are declared by a module in Ruby?</p>
[ { "answer_id": 137311, "author": "Bruno Gomes", "author_id": 8669, "author_profile": "https://Stackoverflow.com/users/8669", "pm_score": 6, "selected": true, "text": "<p>Use the <em>constants</em> method defined in the <em>Module</em> module. From the Ruby documentation:</p>\n\n<blockquo...
2008/09/26
[ "https://Stackoverflow.com/questions/137227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
How can I list all the types that are declared by a module in Ruby?
Use the *constants* method defined in the *Module* module. From the Ruby documentation: > > Module.constants => array > > > Returns an array of the names of all > constants defined in the system. This > list includes the names of all modules > and classes. > > > p Module.constants.sort[1..5] > > > produces: > > > ["ARGV", "ArgumentError", "Array", > "Bignum", "Binding"] > > > You can call *constants* on any module or class you would like. ``` p Class.constants ```
137,255
<p>How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net?</p>
[ { "answer_id": 137294, "author": "Kepboy", "author_id": 21429, "author_profile": "https://Stackoverflow.com/users/21429", "pm_score": 2, "selected": false, "text": "<p>Are you talking about mapping a network share to a logical drive on you computer?</p>\n\n<p>If so you can use DriveInfo....
2008/09/26
[ "https://Stackoverflow.com/questions/137255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
How can I determine if a remote drive has enough space for me to upload a given file using C# in .Net?
There are two possible solutions. 1. Call the Win32 function GetDiskFreeSpaceEx. Here is a sample program: ``` internal static class Win32 { [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes); } class Program { static void Main(string[] args) { long freeBytesForUser; long totalBytes; long freeBytes; if (Win32.GetDiskFreeSpaceEx(@"\\prime\cargohold", out freeBytesForUser, out totalBytes, out freeBytes)) { Console.WriteLine(freeBytesForUser); Console.WriteLine(totalBytes); Console.WriteLine(freeBytes); } } } ``` 2. Use the system management interface. There is another answer in this post which describes this. This method is really designed for use in scripting languages such as PowerShell. It performs a lot of fluff just to get the right object. Ultimately, I suspect, this method boils down to calling GetDiskFreeSpaceEx. Anybody doing any serious Windows development in C# will probably end up calling many Win32 functions. The .NET framework just doesn't cover 100% of the Win32 API. Any large program will quickly uncover gaps in the .NET libraries that are only available through the Win32 API. I would get hold of one of the Win32 wrappers for .NET and include this in your project. This will give you instant access to just about every Win32 API.
137,258
<p>Here's a common code pattern I have to work with:</p> <pre><code>class foo { public: void InitMap(); void InvokeMethodsInMap(); static void abcMethod(); static void defMethod(); private: typedef std::map&lt;const char*, pMethod&gt; TMyMap; TMyMap m_MyMap; } void foo::InitMap() { m_MyMap["abc"] = &amp;foo::abcMethod; m_MyMap["def"] = &amp;foo::defMethod; } void foo::InvokeMethodsInMap() { for (TMyMap::const_iterator it = m_MyMap.begin(); it != m_MyMap.end(); it++) { (*it-&gt;second)(it-&gt;first); } } </code></pre> <p>However, I have found that the <em>order</em> that the map is processed in (within the for loop) can differ based upon whether the build configuration is Release or Debug. It seems that the compiler optimisation that occurs in Release builds affects this order.</p> <p>I thought that by using <code>begin()</code> in the loop above, and incrementing the iterator after each method call, it would process the map in order of initialisation. However, I also remember reading that a map is implemented as a hash table, and order cannot be guaranteed.</p> <p>This is particularly annoying, as most of the unit tests are run on a Debug build, and often strange order dependency bugs aren't found until the external QA team start testing (because they use a Release build).</p> <p>Can anyone explain this strange behaviour?</p>
[ { "answer_id": 137264, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "<p>Don't use <code>const char*</code> as the key for maps. That means the map is ordered by the addresses of the strings, not...
2008/09/26
[ "https://Stackoverflow.com/questions/137258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ]
Here's a common code pattern I have to work with: ``` class foo { public: void InitMap(); void InvokeMethodsInMap(); static void abcMethod(); static void defMethod(); private: typedef std::map<const char*, pMethod> TMyMap; TMyMap m_MyMap; } void foo::InitMap() { m_MyMap["abc"] = &foo::abcMethod; m_MyMap["def"] = &foo::defMethod; } void foo::InvokeMethodsInMap() { for (TMyMap::const_iterator it = m_MyMap.begin(); it != m_MyMap.end(); it++) { (*it->second)(it->first); } } ``` However, I have found that the *order* that the map is processed in (within the for loop) can differ based upon whether the build configuration is Release or Debug. It seems that the compiler optimisation that occurs in Release builds affects this order. I thought that by using `begin()` in the loop above, and incrementing the iterator after each method call, it would process the map in order of initialisation. However, I also remember reading that a map is implemented as a hash table, and order cannot be guaranteed. This is particularly annoying, as most of the unit tests are run on a Debug build, and often strange order dependency bugs aren't found until the external QA team start testing (because they use a Release build). Can anyone explain this strange behaviour?
Don't use `const char*` as the key for maps. That means the map is ordered by the addresses of the strings, not the contents of the strings. Use a `std::string` as the key type, instead. `std::map` is not a hash table, it's usually implemented as a red-black tree, and elements are guaranteed to be ordered by some criteria (by default, `<` comparison between keys).
137,260
<p>I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual.</p> <p>I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?</p>
[ { "answer_id": 137274, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<ul>\n<li>If you have users that override your virtual methods you can't seal them again without breaking code.</li>\n<l...
2008/09/26
[ "https://Stackoverflow.com/questions/137260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/493/" ]
I've been doing some mocking with RhinoMocks and it requires that mocked methods be made virtual. This is fine except we have a custom framework which contains the methods that I want to mock which are currently not marked as virtual. I can't forsee any problem with making these methods virtual but I was wondering what are some potential dangers of making methods virtual that I should look out for?
Actually it can be very problematic if the method is not designed to be overridden and someone overrides it. In particular, never call a virtual method from a constructor. Consider: ``` class Base { public Base() { InitializeComponent(); } protected virtual void InitializeComponent() { ... } } class Derived : Base { private Button button1; public Derived() : base() { button1 = new Button(); } protected override void InitializeComponent() { button1.Text = "I'm gonna throw a null reference exception" } } ``` The Derived class may not be aware that the virtual method call will result in its InitializeComponent method being called before a single line of its own constructor has run.
137,282
<p><a href="http://en.wikipedia.org/wiki/Diamond_problem" rel="noreferrer">http://en.wikipedia.org/wiki/Diamond_problem</a></p> <p>I know what it means, but what steps can I take to avoid it?</p>
[ { "answer_id": 137289, "author": "eduffy", "author_id": 7536, "author_profile": "https://Stackoverflow.com/users/7536", "pm_score": 4, "selected": false, "text": "<p>virtual inheritance. That's what it's there for.</p>\n" }, { "answer_id": 137317, "author": "Bob Somers", ...
2008/09/26
[ "https://Stackoverflow.com/questions/137282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
<http://en.wikipedia.org/wiki/Diamond_problem> I know what it means, but what steps can I take to avoid it?
A practical example: ``` class A {}; class B : public A {}; class C : public A {}; class D : public B, public C {}; ``` Notice how class D inherits from both B & C. But both B & C inherit from A. That will result in 2 copies of the class A being included in the vtable. To solve this, we need virtual inheritance. It's class A that needs to be virtually inherited. So, this will fix the issue: ``` class A {}; class B : virtual public A {}; class C : virtual public A {}; class D : public B, public C {}; ```
137,285
<p>What is the best way to read an HTTP response from GetResponseStream ?</p> <p>Currently I'm using the following approach.</p> <pre><code>Using SReader As StreamReader = New StreamReader(HttpRes.GetResponseStream) SourceCode = SReader.ReadToEnd() End Using </code></pre> <p>I'm not quite sure if this is the most efficient way to read an http response.</p> <p>I need the output as string, I've seen an <a href="http://www.informit.com/guides/content.aspx?g=dotnet&amp;seqNum=583" rel="noreferrer">article</a> with a different approach but I'm not quite if it's a good one. And in my tests that code had some encoding issues with in different websites.</p> <p>How do you read web responses?</p>
[ { "answer_id": 137300, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": false, "text": "<p>I use something like this to download a file from a URL:</p>\n\n<pre><code>if (!Directory.Exists(localFolder))\n{\n...
2008/09/26
[ "https://Stackoverflow.com/questions/137285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the best way to read an HTTP response from GetResponseStream ? Currently I'm using the following approach. ``` Using SReader As StreamReader = New StreamReader(HttpRes.GetResponseStream) SourceCode = SReader.ReadToEnd() End Using ``` I'm not quite sure if this is the most efficient way to read an http response. I need the output as string, I've seen an [article](http://www.informit.com/guides/content.aspx?g=dotnet&seqNum=583) with a different approach but I'm not quite if it's a good one. And in my tests that code had some encoding issues with in different websites. How do you read web responses?
I use something like this to download a file from a URL: ``` if (!Directory.Exists(localFolder)) { Directory.CreateDirectory(localFolder); } try { HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(Path.Combine(uri, filename)); httpRequest.Method = "GET"; // if the URI doesn't exist, an exception will be thrown here... using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse()) { using (Stream responseStream = httpResponse.GetResponseStream()) { using (FileStream localFileStream = new FileStream(Path.Combine(localFolder, filename), FileMode.Create)) { var buffer = new byte[4096]; long totalBytesRead = 0; int bytesRead; while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0) { totalBytesRead += bytesRead; localFileStream.Write(buffer, 0, bytesRead); } } } } } catch (Exception ex) { // You might want to handle some specific errors : Just pass on up for now... // Remove this catch if you don't want to handle errors here. throw; } ```
137,313
<p>I've been parsing through some log files and I've found that some of the lines are too long to display on one line so Terminal.app kindly wraps them onto the next line. However, I've been looking for a way to truncate a line after a certain number of characters so that Terminal doesn't wrap, making it much easier to spot patterns.</p> <p>I wrote a small Perl script to do this:</p> <pre><code>#!/usr/bin/perl die("need max length\n") unless $#ARGV == 0; while (&lt;STDIN&gt;) { $_ = substr($_, 0, $ARGV[0]); chomp($_); print "$_\n"; } </code></pre> <p>But I have a feeling that this functionality is probably built into some other tools (sed?) That I just don't know enough about to use for this task.</p> <p>So my question sort of a reverse question: how do I truncate a line of stdin Without writing a program to do it?</p>
[ { "answer_id": 137323, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 5, "selected": true, "text": "<p>Pipe output to:</p>\n\n<pre><code>cut -b 1-LIMIT\n</code></pre>\n\n<p>Where LIMIT is the desired line width.</p>\n" }, ...
2008/09/26
[ "https://Stackoverflow.com/questions/137313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
I've been parsing through some log files and I've found that some of the lines are too long to display on one line so Terminal.app kindly wraps them onto the next line. However, I've been looking for a way to truncate a line after a certain number of characters so that Terminal doesn't wrap, making it much easier to spot patterns. I wrote a small Perl script to do this: ``` #!/usr/bin/perl die("need max length\n") unless $#ARGV == 0; while (<STDIN>) { $_ = substr($_, 0, $ARGV[0]); chomp($_); print "$_\n"; } ``` But I have a feeling that this functionality is probably built into some other tools (sed?) That I just don't know enough about to use for this task. So my question sort of a reverse question: how do I truncate a line of stdin Without writing a program to do it?
Pipe output to: ``` cut -b 1-LIMIT ``` Where LIMIT is the desired line width.
137,314
<p>I've got a CAkePHP 1.2 site. I've got three related Models/tables: A Comment has exactly one Touch, a Touch has exactly one Touchtype.</p> <p>In each model, I have a belongs to, so I have Comments belongs to Touch, Touch belongs to Touchtype.</p> <p>I'm trying to get a list of comments that includes information about the touch stored in the touchtype table. </p> <pre><code>$this-&gt;Comment-&gt;find(...) </code></pre> <p>I pass in a fields list to the find(). I can grab fields from Touch and Comment, but not TouchType. Does the model connection only go 1 level? I tried tweaking recursive, but that didn't help.</p>
[ { "answer_id": 137323, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 5, "selected": true, "text": "<p>Pipe output to:</p>\n\n<pre><code>cut -b 1-LIMIT\n</code></pre>\n\n<p>Where LIMIT is the desired line width.</p>\n" }, ...
2008/09/26
[ "https://Stackoverflow.com/questions/137314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43/" ]
I've got a CAkePHP 1.2 site. I've got three related Models/tables: A Comment has exactly one Touch, a Touch has exactly one Touchtype. In each model, I have a belongs to, so I have Comments belongs to Touch, Touch belongs to Touchtype. I'm trying to get a list of comments that includes information about the touch stored in the touchtype table. ``` $this->Comment->find(...) ``` I pass in a fields list to the find(). I can grab fields from Touch and Comment, but not TouchType. Does the model connection only go 1 level? I tried tweaking recursive, but that didn't help.
Pipe output to: ``` cut -b 1-LIMIT ``` Where LIMIT is the desired line width.
137,326
<p>How do you embed a SWF file in an HTML page?</p>
[ { "answer_id": 137332, "author": "Ólafur Waage", "author_id": 22459, "author_profile": "https://Stackoverflow.com/users/22459", "pm_score": 7, "selected": false, "text": "<pre><code>&lt;object width=\"100\" height=\"100\"&gt;\n &lt;param name=\"movie\" value=\"file.swf\"&gt;\n &lt;...
2008/09/26
[ "https://Stackoverflow.com/questions/137326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18309/" ]
How do you embed a SWF file in an HTML page?
The best approach to embed a SWF into an HTML page is to use [SWFObject](https://github.com/swfobject/swfobject/). It is a simple open-source JavaScript library that is easy-to-use and standards-friendly method to embed Flash content. It also offers Flash player version detection. If the user does not have the version of Flash required or has JavaScript disabled, they will see an alternate content. You can also use this library to trigger a Flash player upgrade. Once the user has upgraded, they will be redirected back to the page. An example from the documentation: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>SWFObject dynamic embed - step 3</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script type="text/javascript" src="swfobject.js"></script> <script type="text/javascript"> swfobject.embedSWF("myContent.swf", "myContent", "300", "120", "9.0.0"); </script> </head> <body> <div id="myContent"> <p>Alternative content</p> </div> </body> </html> ``` A good tool to use along with this is the SWFObject HTML and JavaScript [generator](https://github.com/swfobject/swfobject/wiki/SWFObject-Generator). It basically generates the HTML and JavaScript you need to embed the Flash using SWFObject. Comes with a very simple UI for you to input your parameters. It Is highly recommended and very simple to use.