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
76,254
<p>Any advice on how to read auto-incrementing identity field assigned to newly created record from call through <code>java.sql.Statement.executeUpdate</code>?</p> <p>I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in <code>java.sql</code> to do this, and any input on people's experience with this across DB platforms.</p>
[ { "answer_id": 76292, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 0, "selected": false, "text": "<p>I've always had to make a second call using query after the insert.</p>\n\n<p>You could use an ORM like hibernate. I thi...
2008/09/16
[ "https://Stackoverflow.com/questions/76254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5446/" ]
Any advice on how to read auto-incrementing identity field assigned to newly created record from call through `java.sql.Statement.executeUpdate`? I know how to do this in SQL for several DB platforms, but would like to know what database independent interfaces exist in `java.sql` to do this, and any input on people's experience with this across DB platforms.
The following snibblet of code should do ya': ``` PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); // ... ResultSet res = stmt.getGeneratedKeys(); while (res.next()) System.out.println("Generated key: " + res.getInt(1)); ``` This is known to work on the following databases * Derby * MySQL * SQL Server For databases where it doesn't work (HSQLDB, Oracle, PostgreSQL, etc), you will need to futz with database-specific tricks. For example, on PostgreSQL you would make a call to `SELECT NEXTVAL(...)` for the sequence in question. Note that the parameters for `executeUpdate(...)` are analogous.
76,274
<p>In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following:</p> <pre><code>var local = il.DeclareLocal(typeof(Nullable&lt;int&gt;)); il.Emit(OpCodes.Stloc, local); il.Emit(OpCodes.Ldloca, local); var method = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); </code></pre> <p>However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like:</p> <pre><code>il.Emit(/* not sure */); var method = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); </code></pre> <p>The ldind family of instructions looks promising (particularly ldind_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might.</p> <p>I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas?</p> <p>**** Edit: Additional Notes ****</p> <p>Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True".</p> <pre><code>var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes); var il = m.GetILGenerator(); var ctor = typeof(Nullable&lt;int&gt;).GetConstructor(new[] { typeof(int) }); il.Emit(OpCodes.Ldc_I4_6); il.Emit(OpCodes.Newobj, ctor); //var local = il.DeclareLocal(typeof(Nullable&lt;int&gt;)); //il.Emit(OpCodes.Stloc, local); //il.Emit(OpCodes.Ldloca, local); var getValue = typeof(Nullable&lt;int&gt;).GetMethod("get_HasValue"); il.Emit(OpCodes.Call, getValue); il.Emit(OpCodes.Ret); Console.WriteLine(m.Invoke(null, null)); </code></pre> <p>So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type).</p> <p>What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.</p>
[ { "answer_id": 76320, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 3, "selected": true, "text": "<p>If the variable is already on the stack, you can go ahead and just emit the method call. </p>\n\n<p>It seems that ...
2008/09/16
[ "https://Stackoverflow.com/questions/76274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13552/" ]
In Microsoft IL, to call a method on a value type you need an indirect reference. Lets say we have an ILGenerator named "il" and that currently we have a Nullable on top of the stack, if we want to check whether it has a value then we could emit the following: ``` var local = il.DeclareLocal(typeof(Nullable<int>)); il.Emit(OpCodes.Stloc, local); il.Emit(OpCodes.Ldloca, local); var method = typeof(Nullable<int>).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); ``` However it would be nice to skip saving it as a local variable, and simply call the method on the address of the variable already on the stack, something like: ``` il.Emit(/* not sure */); var method = typeof(Nullable<int>).GetMethod("get_HasValue"); il.EmitCall(OpCodes.Call, method, null); ``` The ldind family of instructions looks promising (particularly ldind\_ref) but I can't find sufficient documentation to know whether this would cause boxing of the value, which I suspect it might. I've had a look at the C# compiler output, but it uses local variables to achieve this, which makes me believe the first way may be the only way. Anyone have any better ideas? \*\*\*\* Edit: Additional Notes \*\*\*\* Attempting to call the method directly, as in the following program with the lines commented out, doesn't work (the error will be "Operation could destabilise the runtime"). Uncomment the lines and you'll see that it does work as expected, returning "True". ``` var m = new DynamicMethod("M", typeof(bool), Type.EmptyTypes); var il = m.GetILGenerator(); var ctor = typeof(Nullable<int>).GetConstructor(new[] { typeof(int) }); il.Emit(OpCodes.Ldc_I4_6); il.Emit(OpCodes.Newobj, ctor); //var local = il.DeclareLocal(typeof(Nullable<int>)); //il.Emit(OpCodes.Stloc, local); //il.Emit(OpCodes.Ldloca, local); var getValue = typeof(Nullable<int>).GetMethod("get_HasValue"); il.Emit(OpCodes.Call, getValue); il.Emit(OpCodes.Ret); Console.WriteLine(m.Invoke(null, null)); ``` So you can't simply call the method with the value on the stack because it's a value type (though you could if it was a reference type). What I'd like to achieve (or to know whether it is possible) is to replace the three lines that are shown commented out, but keep the program working, without using a temporary local.
If the variable is already on the stack, you can go ahead and just emit the method call. It seems that the constructor doesn't push the variable on the stack in a typed form. After digging into the IL a bit, it appears there are two ways of using the variable after constructing it. You can load the variable that will store the reference onto the evaluation stack before calling the constructor, and then load that variable again after calling the constructor like so: ``` DynamicMethod method = new DynamicMethod("M", typeof(bool), Type.EmptyTypes); ILGenerator il = method.GetILGenerator(); Type nullable = typeof(Nullable<int>); ConstructorInfo ctor = nullable.GetConstructor(new Type[] { typeof(int) }); MethodInfo getValue = nullable.GetProperty("HasValue").GetGetMethod(); LocalBuilder value = il.DeclareLocal(nullable); // load the variable to assign the value from the ctor to il.Emit(OpCodes.Ldloca_S, value); // load constructor args il.Emit(OpCodes.Ldc_I4_6); il.Emit(OpCodes.Call, ctor); il.Emit(OpCodes.Ldloca_S, value); il.Emit(OpCodes.Call, getValue); il.Emit(OpCodes.Ret); Console.WriteLine(method.Invoke(null, null)); ``` The other option is doing it the way you have shown. The only reason for this that I can see is that the ctor methods return void, so they don't put their value on the stack like other methods. It does seem strange that you can call Setloc if the new object isn't on the stack.
76,275
<p>I have multiple users running attachemate on a Windows 2003 server. I want to kill attachemate.exe started by user_1 without killing attachemate.exe started by user_2.</p> <p>I want to use VBScript.</p>
[ { "answer_id": 76309, "author": "Colin Neller", "author_id": 12571, "author_profile": "https://Stackoverflow.com/users/12571", "pm_score": 2, "selected": false, "text": "<p>Shell out to pskill from <a href=\"http://sysinternals.com/\" rel=\"nofollow noreferrer\">http://sysinternals.com/<...
2008/09/16
[ "https://Stackoverflow.com/questions/76275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9882/" ]
I have multiple users running attachemate on a Windows 2003 server. I want to kill attachemate.exe started by user\_1 without killing attachemate.exe started by user\_2. I want to use VBScript.
You could use this to find out who the process owner is, then once you have that you can use Win32\_Process to kill the process by the process ID. [MSDN Win32\_Process class details](http://msdn.microsoft.com/en-us/library/aa394372.aspx) [MSDN Terminating a process with Win32\_Process](http://msdn.microsoft.com/en-us/library/aa393907(VS.85).aspx) There is surely a cleaner way to do this, but here's what I came up with. NOTE: This doesn't deal with multiple processes of the same name of course, but I figure you can work that part out with an array to hold them or something like that. :) ``` strComputer = "." strOwner = "A111111" strProcess = "'notepad.exe'" ' Connect to WMI service and Win32_Process filtering by name' Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _ & strComputer & "\root\cimv2") Set colProcessbyName = objWMIService.ExecQuery("Select * from Win32_Process Where Name = " _ & strProcess) ' Get the process ID for the process started by the user in question' For Each objProcess in colProcessbyName colProperties = objProcess.GetOwner(strUsername,strUserDomain) if strUsername = strOwner then strProcessID = objProcess.ProcessId end if next ' We have the process ID for the app in question for the user, now we kill it' Set colProcessList = objWMIService.ExecQuery("Select * from Win32_Process where ProcessId =" & strProcessID) For Each objProcess in colProcess objProcess.Terminate() Next ```
76,300
<p>In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is:</p> <pre><code>final ArrayList&lt;Integer&gt; result = new ArrayList&lt;Integer&gt;(); GUI.display().syncExec(new Runnable(){ public void run() { MessageBox mb = /* ... */; /* set up messagebox */ result.add(mb.open()); }}); if (SWT.OK == result.get(0)) { /* ... */ } </code></pre> <p>I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?</p>
[ { "answer_id": 76393, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "<p>ArrayList is <em>not</em> thread-safe. From the relevant <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayLi...
2008/09/16
[ "https://Stackoverflow.com/questions/76300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13581/" ]
In my SWT Java app I often want to return information from inside a Display.syncExec() call. The best way I've found so far to do this is: ``` final ArrayList<Integer> result = new ArrayList<Integer>(); GUI.display().syncExec(new Runnable(){ public void run() { MessageBox mb = /* ... */; /* set up messagebox */ result.add(mb.open()); }}); if (SWT.OK == result.get(0)) { /* ... */ } ``` I think this is allowed because ArrayList is thread-safe, but is there a better container I should be using, or an easier way altogether?
[`ArrayList` is not thread-safe](http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html). You can obtain a thread-safe `List` with [`Collections.synchronizedList`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29). However, it is much simpler to use an `AtomicInteger` in your case or `AtomicReference` in a more general case. ``` final AtomicInteger resultAtomicInteger = new AtomicInteger(); Display.getCurrent().syncExec(new Runnable() { public void run() { MessageBox mb = /* ... */; /* set up messagebox */ resultAtomicInteger.set(mb.open()); }}); if (SWT.OK == resultAtomicInteger.get()) { /* ... */ } ```
76,324
<p>I really want to get the google Calendar Api up an running. I found a <a href="http://www.ibm.com/developerworks/library/x-googleclndr/" rel="nofollow noreferrer">great article</a> about how to get started. I downloaded the Zend GData classes. I have php 5 running on my dev box and all the exetensions should be loading.</p> <p>I cant get openssl running and recieve the following error when I try to run any of the example page which should connect to my Google Calendar.</p> <pre><code>Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Unable to Connect to ssl://www.google.com:443. Error #24063472: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?' </code></pre> <p>I have looked in many places to try to get OpenSSL running on my machine and installed. </p> <p>Does anyone know of a simple failsafe tutorial to get this combination up and running?</p>
[ { "answer_id": 76608, "author": "DustinB", "author_id": 7888, "author_profile": "https://Stackoverflow.com/users/7888", "pm_score": 0, "selected": false, "text": "<p>Could you have mistyped the PROTOCOL in the URL? It should be HTTPS, not \"SSL\". For example, , not SSL://www.google.co...
2008/09/16
[ "https://Stackoverflow.com/questions/76324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6244/" ]
I really want to get the google Calendar Api up an running. I found a [great article](http://www.ibm.com/developerworks/library/x-googleclndr/) about how to get started. I downloaded the Zend GData classes. I have php 5 running on my dev box and all the exetensions should be loading. I cant get openssl running and recieve the following error when I try to run any of the example page which should connect to my Google Calendar. ``` Uncaught exception 'Zend_Gdata_App_HttpException' with message 'Unable to Connect to ssl://www.google.com:443. Error #24063472: Unable to find the socket transport "ssl" - did you forget to enable it when you configured PHP?' ``` I have looked in many places to try to get OpenSSL running on my machine and installed. Does anyone know of a simple failsafe tutorial to get this combination up and running?
I think this use of SSL is part of the Zend GData library so I assume it is correct. I think not having OpenSSL correctly installed is my main issue.
76,325
<p>How do I move an active directory group to another organizational unit using Powershell?</p> <p>ie.</p> <p>I would like to move the group "IT Department" from:</p> <pre><code> (CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca) </code></pre> <p>to:</p> <pre><code> (CN=IT Department, OU=Temporarily Moved Groups, DC=Company,DC=ca) </code></pre>
[ { "answer_id": 80253, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>I haven't tried this yet, but this should do it..</p>\n\n<pre><code>$objectlocation= 'CN=IT Department, OU=Technol...
2008/09/16
[ "https://Stackoverflow.com/questions/76325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
How do I move an active directory group to another organizational unit using Powershell? ie. I would like to move the group "IT Department" from: ``` (CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca) ``` to: ``` (CN=IT Department, OU=Temporarily Moved Groups, DC=Company,DC=ca) ```
Your script was really close to correct (and I really appreciate your response). The following script is what I used to solve my problem.: ``` $from = [ADSI]"LDAP://CN=IT Department, OU=Technology Department, OU=Departments,DC=Company,DC=ca" $to = [ADSI]"LDAP://OU=Temporarily Moved Groups, DC=Company,DC=ca" $from.PSBase.MoveTo($to,"cn="+$from.name) ```
76,327
<p>I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating <code>/tmp/hsperfdata_username</code> directories, which I would like to prevent. Is there any way to stop java from creating these files?</p>
[ { "answer_id": 76418, "author": "svrist", "author_id": 86, "author_profile": "https://Stackoverflow.com/users/86", "pm_score": 1, "selected": false, "text": "<p><em>EDIT: Cleanup info and summarize</em></p>\n\n<p>Summary:</p>\n\n<ul>\n<li>Its a feature, not a bug</li>\n<li>It can be turn...
2008/09/16
[ "https://Stackoverflow.com/questions/76327", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13582/" ]
I'm writing a Java application that runs on Linux (using Sun's JDK). It keeps creating `/tmp/hsperfdata_username` directories, which I would like to prevent. Is there any way to stop java from creating these files?
Try JVM option **-XX:-UsePerfData** [more info](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html) The following might be helpful that is from link <https://docs.oracle.com/javase/8/docs/technotes/tools/unix/java.html> ``` -XX:+UsePerfData Enables the perfdata feature. This option is enabled by default to allow JVM monitoring and performance testing. Disabling it suppresses the creation of the hsperfdata_userid directories. To disable the perfdata feature, specify -XX:-UsePerfData. ```
76,334
<p>Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in <strong>C</strong> (<strong>not C++</strong>, I know that template magic is available there)?</p> <p>I generally use <strong>GCC</strong> and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...).</p> <p>I'm looking for how to do this in <strong>GCC</strong> (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.</p>
[ { "answer_id": 76746, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 3, "selected": false, "text": "<p>I figured it out afterall...</p>\n\n<pre><code>#define GCD(a,b) ((a&gt;=b)*GCD_1(a,b)+(a&lt;b)*GCD_1(b,a))\n#define GCD_1(a,...
2008/09/16
[ "https://Stackoverflow.com/questions/76334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12713/" ]
Does anyone know a mechanism to calculate at compile-time the LCM (Least Common Multiple) and/or GCD (Greatest Common Denominator) of at least two number in **C** (**not C++**, I know that template magic is available there)? I generally use **GCC** and recall that it can calculate certain values at compile-time when all inputs are known (ex: sin, cos, etc...). I'm looking for how to do this in **GCC** (preferably in a manner that other compilers could handle) and hope the same mechanism would work in Visual Studio.
I figured it out afterall... ``` #define GCD(a,b) ((a>=b)*GCD_1(a,b)+(a<b)*GCD_1(b,a)) #define GCD_1(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_2((b), (a)%((b)+!(b)))) #define GCD_2(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_3((b), (a)%((b)+!(b)))) #define GCD_3(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_4((b), (a)%((b)+!(b)))) #define GCD_4(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_5((b), (a)%((b)+!(b)))) #define GCD_5(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_6((b), (a)%((b)+!(b)))) #define GCD_6(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_7((b), (a)%((b)+!(b)))) #define GCD_7(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_8((b), (a)%((b)+!(b)))) #define GCD_8(a,b) ((((!(b)))*(a)) + (!!(b))*GCD_last((b), (a)%((b)+!(b)))) #define GCD_last(a,b) (a) #define LCM(a,b) (((a)*(b))/GCD(a,b)) int main() { printf("%d, %d\n", GCD(21,6), LCM(21,6)); return 0; } ``` Note, depending on how large your integers go, you may need to include more intermediate steps (i.e. GCD\_9, GCD\_10, etc...). I hope this helps!
76,346
<p>I just got surprised by something in TSQL. I thought that if xact_abort was on, calling something like</p> <pre><code>raiserror('Something bad happened', 16, 1); </code></pre> <p>would stop execution of the stored procedure (or any batch).</p> <p>But my ADO.NET error message just proved the opposite. I got both the raiserror error message in the exception message, plus the next thing that broke after that.</p> <p>This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary:</p> <pre><code>if @somethingBadHappened begin; raiserror('Something bad happened', 16, 1); return; end; </code></pre> <p>The docs say this:</p> <blockquote> <p>When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back.</p> </blockquote> <p>Does that mean I must be using an explicit transaction?</p>
[ { "answer_id": 76416, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 6, "selected": false, "text": "<p>This is By Design<sup>TM</sup>, as you can see on <a href=\"http://connect.microsoft.com/SQLServer/feedback/ViewFee...
2008/09/16
[ "https://Stackoverflow.com/questions/76346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1219/" ]
I just got surprised by something in TSQL. I thought that if xact\_abort was on, calling something like ``` raiserror('Something bad happened', 16, 1); ``` would stop execution of the stored procedure (or any batch). But my ADO.NET error message just proved the opposite. I got both the raiserror error message in the exception message, plus the next thing that broke after that. This is my workaround (which is my habit anyway), but it doesn't seem like it should be necessary: ``` if @somethingBadHappened begin; raiserror('Something bad happened', 16, 1); return; end; ``` The docs say this: > > When SET XACT\_ABORT is ON, if a Transact-SQL statement raises a run-time error, the entire transaction is terminated and rolled back. > > > Does that mean I must be using an explicit transaction?
This is By DesignTM, as you can see on [Connect](http://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=275308) by the SQL Server team's response to a similar question: > > Thank you for your feedback. By design, the XACT\_ABORT set option does not impact the behavior of the RAISERROR statement. We will consider your feedback to modify this behavior for a future release of SQL Server. > > > Yes, this is a bit of an issue for some who hoped `RAISERROR` with a high severity (like `16`) would be the same as an SQL execution error - it's not. Your workaround is just about what you need to do, and using an explicit transaction doesn't have any effect on the behavior you want to change.
76,411
<p>How can I create a regular expression that will grab delimited text from a string? For example, given a string like </p> <pre><code>text ###token1### text text ###token2### text text </code></pre> <p>I want a regex that will pull out <code>###token1###</code>. Yes, I do want the delimiter as well. By adding another group, I can get both:</p> <pre><code>(###(.+?)###) </code></pre>
[ { "answer_id": 76427, "author": "David Beleznay", "author_id": 13359, "author_profile": "https://Stackoverflow.com/users/13359", "pm_score": 3, "selected": true, "text": "<pre><code>/###(.+?)###/\n</code></pre>\n\n<p>if you want the ###'s then you need</p>\n\n<pre><code>/(###.+?###)/\n<...
2008/09/16
[ "https://Stackoverflow.com/questions/76411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410/" ]
How can I create a regular expression that will grab delimited text from a string? For example, given a string like ``` text ###token1### text text ###token2### text text ``` I want a regex that will pull out `###token1###`. Yes, I do want the delimiter as well. By adding another group, I can get both: ``` (###(.+?)###) ```
``` /###(.+?)###/ ``` if you want the ###'s then you need ``` /(###.+?###)/ ``` the **?** means non greedy, if you didn't have the **?**, then it would grab too much. e.g. `'###token1### text text ###token2###'` would all get grabbed. My initial answer had a \* instead of a +. \* means 0 or more. + means 1 or more. \* was wrong because that would allow ###### as a valid thing to find. For playing around with regular expressions. I highly recommend <http://www.weitz.de/regex-coach/> for windows. You can type in the string you want and your regular expression and see what it's actually doing. Your selected text will be stored in \1 or $1 depending on where you are using your regular expression.
76,412
<p>When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this?</p> <pre class="lang-xml prettyprint-override"><code> &lt;UserControl x:Class=&quot;WpfApplication3.UserControl1&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt; &lt;StackPanel Background=&quot;LightCyan&quot;&gt; &lt;TextBox Margin=&quot;8&quot; Text=&quot;{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}&quot; /&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </code></pre> <pre class="lang-cs prettyprint-override"><code> using System; using System.Windows; using System.Windows.Controls; namespace WpfApplication3 { public partial class UserControl1 : UserControl { public static DependencyProperty TextProperty = DependencyProperty.Register(&quot;Text&quot;, typeof(string), typeof(UserControl1), new PropertyMetadata(null)); public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); } } public UserControl1() { InitializeComponent(); } } } </code></pre>
[ { "answer_id": 77094, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 5, "selected": true, "text": "<p>That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencin...
2008/09/16
[ "https://Stackoverflow.com/questions/76412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this? ```xml <UserControl x:Class="WpfApplication3.UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel Background="LightCyan"> <TextBox Margin="8" Text="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" /> </StackPanel> </UserControl> ``` ```cs using System; using System.Windows; using System.Windows.Controls; namespace WpfApplication3 { public partial class UserControl1 : UserControl { public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(UserControl1), new PropertyMetadata(null)); public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); } } public UserControl1() { InitializeComponent(); } } } ```
That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencing properties by the UserControl's name. ``` <UserControl x:Class="WpfApplication3.UserControl1" x:Name="UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel Background="LightCyan"> <TextBox Margin="8" Text="{Binding Path=Text, ElementName=UserControl1}" /> </StackPanel> </UserControl> ``` Sometimes we've found ourselves making too many things UserControl's though, and have often times scaled back our usage. I'd also follow the tradition of naming things like that textbox along the lines of PART\_TextDisplay or something, so that in the future you could template it out yet keep the code-behind the same.
76,424
<p>XmlElement.Attributes.Remove* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example:</p> <pre><code>XmlDocument doc = new XmlDocument(); doc.InnerXml = @"&lt;Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/&gt;"; doc.DocumentElement.Attributes.RemoveNamedItem("attr2"); Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]); doc.DocumentElement.Attributes.RemoveNamedItem("xmlns"); Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]); </code></pre> <p>The resulting output is</p> <pre><code>xmlns attr before removal=System.Xml.XmlAttribute xmlns attr after removal= &lt;Element1 attr1="value1" xmlns="http://mynamespace.com/" /&gt; </code></pre> <p>The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml. I guess it is because of the special meaning of this attribute.</p> <p>The question is how to remove the xmlns attribute using .NET XML API. Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API.</p> <p>@Edit: I'm talking about .NET 2.0.</p>
[ { "answer_id": 76513, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Yes, because its an ELEMENT name, you can't explicitly remove it. Using XmlTextWriter's WriteStartElement and WirteStartAttr...
2008/09/16
[ "https://Stackoverflow.com/questions/76424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
XmlElement.Attributes.Remove\* methods are working fine for arbitrary attributes resulting in the removed attributes being removed from XmlDocument.OuterXml property. Xmlns attribute however is different. Here is an example: ``` XmlDocument doc = new XmlDocument(); doc.InnerXml = @"<Element1 attr1=""value1"" xmlns=""http://mynamespace.com/"" attr2=""value2""/>"; doc.DocumentElement.Attributes.RemoveNamedItem("attr2"); Console.WriteLine("xmlns attr before removal={0}", doc.DocumentElement.Attributes["xmlns"]); doc.DocumentElement.Attributes.RemoveNamedItem("xmlns"); Console.WriteLine("xmlns attr after removal={0}", doc.DocumentElement.Attributes["xmlns"]); ``` The resulting output is ``` xmlns attr before removal=System.Xml.XmlAttribute xmlns attr after removal= <Element1 attr1="value1" xmlns="http://mynamespace.com/" /> ``` The attribute seems to be removed from the Attributes collection, but it is not removed from XmlDocument.OuterXml. I guess it is because of the special meaning of this attribute. The question is how to remove the xmlns attribute using .NET XML API. Obviously I can just remove the attribute from a String representation of this, but I wonder if it is possible to do the same thing using the API. @Edit: I'm talking about .NET 2.0.
.NET DOM API doesn't support modifying element's namespace which is what you are essentially trying to do. So, in order to solve your problem you have to construct a new document one way or another. You can use the same .NET DOM API and create a new element without specifying its namespace. Alternatively, you can create an XSLT stylesheet that transforms your original "namespaced" document to a new one in which the elements will be not namespace-qualified.
76,440
<p>As developers and as professional engineers have you been exposed to the tenants of Extreme Programming as defined in the "version 1" by Kent Beck. Which of those 12 core principles do you feel you have been either allowed to practice or at least be a part of in your current job or others?</p> <pre><code>* Pair programming[5] * Planning game * Test driven development * Whole team (being empowered to deliver) * Continuous integration * Refactoring or design improvement * Small releases * Coding standards * Collective code ownership * Simple design * System metaphor * Sustainable pace </code></pre> <p>From an engineers point of view I feel that the main engineering principles of XP arevastly superior to anything else I have been involved in. What is your opinion?</p>
[ { "answer_id": 76543, "author": "pmlarocque", "author_id": 7419, "author_profile": "https://Stackoverflow.com/users/7419", "pm_score": 1, "selected": false, "text": "<p>I consider myself lucky, all except \"Pair programming\" we can do it, but only to solve big issues not on a day-to-day...
2008/09/16
[ "https://Stackoverflow.com/questions/76440", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
As developers and as professional engineers have you been exposed to the tenants of Extreme Programming as defined in the "version 1" by Kent Beck. Which of those 12 core principles do you feel you have been either allowed to practice or at least be a part of in your current job or others? ``` * Pair programming[5] * Planning game * Test driven development * Whole team (being empowered to deliver) * Continuous integration * Refactoring or design improvement * Small releases * Coding standards * Collective code ownership * Simple design * System metaphor * Sustainable pace ``` From an engineers point of view I feel that the main engineering principles of XP arevastly superior to anything else I have been involved in. What is your opinion?
We are following these practices you've mentioned: * Planning game * Test driven development * Whole team (being empowered to deliver) * Continuous integration * Refactoring or design improvement * Small releases * Coding standards * Collective code ownership * Simple design And I must say that after one year I can't imagine working differently. As for Pair programming I must say that it makes sense in certain areas, where there is a very high difficult area or where an initial good design is essential (e.g. designing interfaces). However I don't consider this as very effective. In my opinion it is better to perform code and design reviews of smaller parts, where Pair programming would have made sense. As for the 'Whole team' practice I must admit that it has suffered as our team grew. It simply made the planning sessions too long, when everybody can give his personal inputs. Currently a core team is preparing the planning game by doing some initial, rough planning.
76,455
<p>In C#.NET I am trying to programmatically change the color of the border in a group box.</p> <p>Update: This question was asked when I was working on a winforms system before we switched to .NET.</p>
[ { "answer_id": 5629954, "author": "swajak", "author_id": 100258, "author_profile": "https://Stackoverflow.com/users/100258", "pm_score": 1, "selected": false, "text": "<p>I'm not sure this applies to every case, but thanks to this thread, we quickly hooked into the Paint event programmat...
2008/09/16
[ "https://Stackoverflow.com/questions/76455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/300930/" ]
In C#.NET I am trying to programmatically change the color of the border in a group box. Update: This question was asked when I was working on a winforms system before we switched to .NET.
Building on the previous answer, a better solution that includes the label for the group box: ``` groupBox1.Paint += PaintBorderlessGroupBox; private void PaintBorderlessGroupBox(object sender, PaintEventArgs p) { GroupBox box = (GroupBox)sender; p.Graphics.Clear(SystemColors.Control); p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0); } ``` You might want to adjust the x/y for the text, but for my use this is just right.
76,464
<p>I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting. I have a control that currently uses a Repeater control with templates. Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties? </p>
[ { "answer_id": 5629954, "author": "swajak", "author_id": 100258, "author_profile": "https://Stackoverflow.com/users/100258", "pm_score": 1, "selected": false, "text": "<p>I'm not sure this applies to every case, but thanks to this thread, we quickly hooked into the Paint event programmat...
2008/09/16
[ "https://Stackoverflow.com/questions/76464", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13100/" ]
I'd like to create a module in DNN that, similar to the Announcements control, offers a template that the portal admin can modify for formatting. I have a control that currently uses a Repeater control with templates. Is there a way to override the contents of the repeater ItemTemplate, HeaderTemplate, and FooterTemplate properties?
Building on the previous answer, a better solution that includes the label for the group box: ``` groupBox1.Paint += PaintBorderlessGroupBox; private void PaintBorderlessGroupBox(object sender, PaintEventArgs p) { GroupBox box = (GroupBox)sender; p.Graphics.Clear(SystemColors.Control); p.Graphics.DrawString(box.Text, box.Font, Brushes.Black, 0, 0); } ``` You might want to adjust the x/y for the text, but for my use this is just right.
76,472
<p>Is there a way in Ruby to find the version of a file, specifically a .dll file?</p>
[ { "answer_id": 76554, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 1, "selected": false, "text": "<p>For any file, you'd need to discover what format the file is in, and then open the file and read the necessary bytes to f...
2008/09/16
[ "https://Stackoverflow.com/questions/76472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way in Ruby to find the version of a file, specifically a .dll file?
For Windows EXE's and DLL's: ``` require "Win32API" FILENAME = "c:/ruby/bin/ruby.exe" #your filename here s="" vsize=Win32API.new('version.dll', 'GetFileVersionInfoSize', ['P', 'P'], 'L').call(FILENAME, s) p vsize if (vsize > 0) result = ' '*vsize Win32API.new('version.dll', 'GetFileVersionInfo', ['P', 'L', 'L', 'P'], 'L').call(FILENAME, 0, vsize, result) rstring = result.unpack('v*').map{|s| s.chr if s<256}*'' r = /FileVersion..(.*?)\000/.match(rstring) puts "FileVersion = #{r ? r[1] : '??' }" else puts "No Version Info" end ``` The 'unpack'+regexp part is a hack, the "proper" way is the VerQueryValue API, but this should work for most files. (probably fails miserably on extended character sets.)
76,482
<p>I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code:</p> <pre><code>cat tmp.log -encoding UTF8 &gt; new.log </code></pre> <p>The resulting file is still in UCS-2 Little Endian. Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?</p>
[ { "answer_id": 76734, "author": "driis", "author_id": 13627, "author_profile": "https://Stackoverflow.com/users/13627", "pm_score": 5, "selected": false, "text": "<p>I would do it like this:</p>\n\n<pre><code>get-content tmp.log -encoding Unicode | set-content new.log -encoding UTF8\n</c...
2008/09/16
[ "https://Stackoverflow.com/questions/76482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2582/" ]
I have a file saved as UCS-2 Little Endian I want to change the encoding so I ran the following code: ``` cat tmp.log -encoding UTF8 > new.log ``` The resulting file is still in UCS-2 Little Endian. Is this because the pipeline is always in that format? Is there an easy way to pipe this to a new file as UTF8?
As suggested [here](https://stackoverflow.com/questions/64860/best-way-to-convert-text-files-between-character-sets#64937): ``` Get-Content tmp.log | Out-File -Encoding UTF8 new.log ```
76,549
<p>An array of ints in java is stored as a block of 32-bit values in memory. How is an array of Integer objects stored? i.e.</p> <pre><code>int[] vs. Integer[] </code></pre> <p>I'd imagine that each element in the Integer array is a reference to an Integer object, and that the Integer object has object storage overheads, just like any other object.</p> <p>I'm hoping however that the JVM does some magical cleverness under the hood given that Integers are immutable and stores it just like an array of ints.</p> <p>Is my hope woefully naive? Is an Integer array much slower than an int array in an application where every last ounce of performance matters?</p>
[ { "answer_id": 76588, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 1, "selected": false, "text": "<p>I think your hope is woefully naive. Specifically, it needs to deal with the issue that Integer can potentially be ...
2008/09/16
[ "https://Stackoverflow.com/questions/76549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974/" ]
An array of ints in java is stored as a block of 32-bit values in memory. How is an array of Integer objects stored? i.e. ``` int[] vs. Integer[] ``` I'd imagine that each element in the Integer array is a reference to an Integer object, and that the Integer object has object storage overheads, just like any other object. I'm hoping however that the JVM does some magical cleverness under the hood given that Integers are immutable and stores it just like an array of ints. Is my hope woefully naive? Is an Integer array much slower than an int array in an application where every last ounce of performance matters?
No VM I know of will store an Integer[] array like an int[] array for the following reasons: 1. There can be **null** Integer objects in the array and you have no bits left for indicating this in an int array. The VM could store this 1-bit information per array slot in a hiden bit-array though. 2. You can synchronize in the elements of an Integer array. This is much harder to overcome as the first point, since you would have to store a monitor object for each array slot. 3. The elements of Integer[] can be compared for identity. You could for example create two Integer objects with the value 1 via **new** and store them in different array slots and later you retrieve them and compare them via ==. This must lead to false, so you would have to store this information somewhere. Or you keep a reference to one of the Integer objects somewhere and use this for comparison and you have to make sure one of the == comparisons is false and one true. This means the whole concept of object identity is quiet hard to handle for the *optimized* Integer array. 4. You can cast an Integer[] to e.g. Object[] and pass it to methods expecting just an Object[]. This means all the code which handles Object[] must now be able to handle the special Integer[] object too, making it slower and larger. Taking all this into account, it would probably be possible to make a special Integer[] which saves some space in comparison to a *naive* implementation, but the additional complexity will likely affect a lot of other code, making it slower in the end. The overhead of using Integer[] instead of int[] can be quiet large in space and time. On a typical 32 bit VM an Integer object will consume 16 byte (8 byte for the object header, 4 for the payload and 4 additional bytes for alignment) while the Integer[] uses as much space as int[]. In 64 bit VMs (using 64bit pointers, which is not always the case) an Integer object will consume 24 byte (16 for the header, 4 for the payload and 4 for alignment). In addition a slot in the Integer[] will use 8 byte instead of 4 as in the int[]. This means you can expect an overhead of **16 to 28** byte per slot, which is a **factor of 4 to 7** compared to plain int arrays. The performance overhead can be significant too for mainly two reasons: 1. Since you use more memory, you put on much more pressure on the memory subsystem, making it more likely to have cache misses in the case of Integer[]. For example if you traverse the contents of the int[] in a linear manner, the cache will have most of the entries already fetched when you need them (since the layout is linear too). But in case of the Integer array, the Integer objects itself might be scattered randomly in the heap, making it hard for the cache to guess where the next memory reference will point to. 2. The garbage collection has to do much more work because of the additional memory used and because it has to scan and move each Integer object separately, while in the case of int[] it is just one object and the contents of the object doesn't have to be scanned (they contain no reference to other objects). To sum it up, using an int[] in performance critical work will be both much faster and memory efficient than using an Integer array in current VMs and it is unlikely this will change much in the near future.
76,564
<p>All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it.</p> <p>I know I could just use an image; I'd rather not do that if I can help it.</p>
[ { "answer_id": 76603, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 3, "selected": false, "text": "<pre><code>&lt;ul&gt;\n &lt;li style=\"color: #888;\"&gt;&lt;span style=\"color: #000\"&gt;test&lt;/span&gt;&lt;/l...
2008/09/16
[ "https://Stackoverflow.com/questions/76564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
All I want is to be able to change the color of a bullet in a list to a light gray. It defaults to black, and I can't figure out how to change it. I know I could just use an image; I'd rather not do that if I can help it.
The bullet gets its color from the text. So if you want to have a different color bullet than text in your list you'll have to add some markup. Wrap the list text in a span: ``` <ul> <li><span>item #1</span></li> <li><span>item #2</span></li> <li><span>item #3</span></li> </ul> ``` Then modify your style rules slightly: ``` li { color: red; /* bullet color */ } li span { color: black; /* text color */ } ```
76,571
<p>In JavaScript, using the Prototype library, the following functional construction is possible:</p> <pre><code>var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"]; words.pluck('length'); //-&gt; [7, 8, 5, 16, 4] </code></pre> <p>Note that this example code is equivalent to</p> <pre><code>words.map( function(word) { return word.length; } ); </code></pre> <p>I wondered if something similar is possible in F#:</p> <pre><code>let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"] //val words: string list List.pluck 'Length' words //int list = [7; 8; 5; 16; 4] </code></pre> <p>without having to write:</p> <pre><code>List.map (fun (s:string) -&gt; s.Length) words </code></pre> <p>This would seem quite useful to me because then you don't have to write functions for every property to access them.</p>
[ { "answer_id": 79511, "author": "Gavin", "author_id": 2377, "author_profile": "https://Stackoverflow.com/users/2377", "pm_score": 1, "selected": false, "text": "<p>Prototype's <code>pluck</code> takes advantage of that in Javascript <code>object.method()</code> is the same as <code>objec...
2008/09/16
[ "https://Stackoverflow.com/questions/76571", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6264/" ]
In JavaScript, using the Prototype library, the following functional construction is possible: ``` var words = ["aqueous", "strength", "hated", "sesquicentennial", "area"]; words.pluck('length'); //-> [7, 8, 5, 16, 4] ``` Note that this example code is equivalent to ``` words.map( function(word) { return word.length; } ); ``` I wondered if something similar is possible in F#: ``` let words = ["aqueous"; "strength"; "hated";"sesquicentennial"; "area"] //val words: string list List.pluck 'Length' words //int list = [7; 8; 5; 16; 4] ``` without having to write: ``` List.map (fun (s:string) -> s.Length) words ``` This would seem quite useful to me because then you don't have to write functions for every property to access them.
I saw your request on the F# mailing list. Hope I can help. You could use type extension and reflection to allow this. We simple extend the generic list type with the pluck function. Then we can use pluck() on any list. An unknown property will return a list with the error string as its only contents. ``` type Microsoft.FSharp.Collections.List<'a> with member list.pluck property = try let prop = typeof<'a>.GetProperty property [for elm in list -> prop.GetValue(elm, [| |])] with e-> [box <| "Error: Property '" + property + "'" + " not found on type '" + typeof<'a>.Name + "'"] let a = ["aqueous"; "strength"; "hated"; "sesquicentennial"; "area"] a.pluck "Length" a.pluck "Unknown" ``` which produces the follow result in the interactive window: ``` > a.pluck "Length" ;; val it : obj list = [7; 8; 5; 16; 4] > a.pluck "Unknown";; val it : obj list = ["Error: Property 'Unknown' not found on type 'String'"] ``` warm regards, DannyAsher > > > > > NOTE: When using `<pre`> the angle brackets around ``` <'a> ``` didn't show though in the preview window it looked fine. The backtick didn't work for me. Had to resort you the colorized version which is all wrong. I don't think I'll post here again until FSharp syntax is fully supported.
76,581
<p>There's an MSDN article <a href="http://msdn.microsoft.com/en-us/library/aa919730.aspx" rel="nofollow noreferrer">here</a>, but I'm not getting very far:</p> <pre><code>p = 139; g = 5; CRYPT_DATA_BLOB pblob; pblob.cbData = sizeof( ULONG ); pblob.pbData = ( LPBYTE ) &amp;p; CRYPT_DATA_BLOB gblob; gblob.cbData = sizeof( ULONG ); gblob.pbData = ( LPBYTE ) &amp;g; HCRYPTKEY hKey; if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF, CRYPT_PREGEN, &amp;hKey ) ) { ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &amp;pblob, 0 ); </code></pre> <p>Fails here with <code>NTE_BAD_DATA</code>. I'm using <code>MS_DEF_DSS_DH_PROV</code>. What gives?</p>
[ { "answer_id": 78156, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>It looks to me that <code>KP_P</code>, <code>KP_G</code>, <code>KP_Q</code> are for DSS keys (Digital Signature Stand...
2008/09/16
[ "https://Stackoverflow.com/questions/76581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
There's an MSDN article [here](http://msdn.microsoft.com/en-us/library/aa919730.aspx), but I'm not getting very far: ``` p = 139; g = 5; CRYPT_DATA_BLOB pblob; pblob.cbData = sizeof( ULONG ); pblob.pbData = ( LPBYTE ) &p; CRYPT_DATA_BLOB gblob; gblob.cbData = sizeof( ULONG ); gblob.pbData = ( LPBYTE ) &g; HCRYPTKEY hKey; if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF, CRYPT_PREGEN, &hKey ) ) { ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 ); ``` Fails here with `NTE_BAD_DATA`. I'm using `MS_DEF_DSS_DH_PROV`. What gives?
It may be that it just doesn't like the very short keys you're using. I found [the desktop version of that article](http://msdn.microsoft.com/en-us/library/aa381969.aspx) which may help, as it has a full example. EDIT: The OP realised from the example that you have to tell CryptGenKey how long the keys are, which you do by setting the top 16-bits of the flags to the number of bits you want to use. If you leave this as 0, you get the default key length. This *is* documented in the **Remarks** section of the device documentation, and with the *dwFlags* parameter in the [desktop documentation](http://msdn.microsoft.com/en-us/library/aa379941(VS.85).aspx). For the Diffie-Hellman key-exchange algorithm, the Base provider defaults to 512-bit keys and the Enhanced provider (which is the default) defaults to 1024-bit keys, on Windows XP and later. There doesn't seem to be any documentation for the default lengths on CE. The code should therefore be: ``` BYTE p[64] = { 139 }; // little-endian, all other bytes set to 0 BYTE g[64] = { 5 }; CRYPT_DATA_BLOB pblob; pblob.cbData = sizeof( p); pblob.pbData = p; CRYPT_DATA_BLOB gblob; gblob.cbData = sizeof( g ); gblob.pbData = g; HCRYPTKEY hKey; if ( ::CryptGenKey( m_hCryptoProvider, CALG_DH_SF, ( 512 << 16 ) | CRYPT_PREGEN, &hKey ) ) { ::CryptSetKeyParam( hKey, KP_P, ( LPBYTE ) &pblob, 0 ); ```
76,624
<p>Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error.</p> <p>For some reason I thought the following might work:</p> <pre><code>enum MY_ENUM : unsigned __int64 { LARGE_VALUE = 0x1000000000000000, }; </code></pre>
[ { "answer_id": 76661, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "<p>An enum in C++ can be any integral type. You can, for example, have an enum of chars. IE:</p>\n\n<pre><code>enum MY_ENUM\n...
2008/09/16
[ "https://Stackoverflow.com/questions/76624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
Is there a way to have a 64 bit enum in C++? Whilst refactoring some code I came across bunch of #defines which would be better as an enum, but being greater than 32 bit causes the compiler to error. For some reason I thought the following might work: ``` enum MY_ENUM : unsigned __int64 { LARGE_VALUE = 0x1000000000000000, }; ```
I don't think that's possible with C++98. The underlying representation of enums is up to the compiler. In that case, you are better off using: ``` const __int64 LARGE_VALUE = 0x1000000000000000L; ``` As of C++11, it is possible to use enum classes to specify the base type of the enum: ``` enum class MY_ENUM : unsigned __int64 { LARGE_VALUE = 0x1000000000000000ULL }; ``` In addition enum classes introduce a new name scope. So instead of referring to `LARGE_VALUE`, you would reference `MY_ENUM::LARGE_VALUE`.
76,650
<p>This has me puzzled. This code worked on another server, but it's failing on Perl v5.8.8 with <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> loaded from CPAN today.</p> <pre><code>Warning: Use of uninitialized value in numeric lt (&lt;) at /home/downside/lib/Date/Manip.pm line 3327. at dailyupdate.pl line 13 main::__ANON__('Use of uninitialized value in numeric lt (&lt;) at /home/downsid...') called at /home/downside/lib/Date/Manip.pm line 3327 Date::Manip::Date_SecsSince1970GMT(09, 16, 2008, 00, 21, 22) called at /home/downside/lib/Date/Manip.pm line 1905 Date::Manip::UnixDate('today', '%Y-%m-%d') called at TICKER/SYMBOLS/updatesymbols.pm line 122 TICKER::SYMBOLS::updatesymbols::getdate() called at TICKER/SYMBOLS/updatesymbols.pm line 439 TICKER::SYMBOLS::updatesymbols::updatesymbol('DBI::db=HASH(0x87fcc34)', 'TICKER::SYMBOLS::symbol=HASH(0x8a43540)') called at TICKER/SYMBOLS/updatesymbols.pm line 565 TICKER::SYMBOLS::updatesymbols::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 149 EDGAR::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 180 EDGAR::dailyupdate() called at dailyupdate.pl line 193 </code></pre> <p>The code that's failing is simply:</p> <pre><code>sub getdate() { my $err; ## today &amp;Date::Manip::Date_Init('TZ=EST5EDT'); my $today = Date::Manip::UnixDate('today','%Y-%m-%d'); ## today's date ####print "Today is ",$today,"\n"; ## ***TEMP*** return($today); } </code></pre> <p>That's right; <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> is failing for <code>"today"</code>.</p> <p>The line in <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> that is failing is:</p> <pre><code> my($tz)=$Cnf{"ConvTZ"}; $tz=$Cnf{"TZ"} if (! $tz); $tz=$Zone{"n2o"}{lc($tz)} if ($tz !~ /^[+-]\d{4}$/); my($tzs)=1; $tzs=-1 if ($tz&lt;0); ### ERROR OCCURS HERE </code></pre> <p>So <a href="http://search.cpan.org/dist/Date-Manip" rel="nofollow noreferrer">Date::Manip</a> is assuming that <code>$Cnf</code> has been initialized with elements <code>"ConvTZ"</code> or <code>"TZ"</code>. Those are initialized in <code>Date_Init</code>, so that should have been taken care of.</p> <p>It's only failing in my large program. If I just extract "<code>getdate()</code>" above and run it standalone, there's no error. So there's something about the global environment that affects this.</p> <p>This seems to be a known, but not understood problem. If you search Google for "Use of uninitialized value date manip" there are about 2400 hits. This error has been reported with <a href="http://www.lemis.com/grog/videorecorder/mythsetup-sep-2006.html" rel="nofollow noreferrer">MythTV</a> and <a href="http://www.cpan.org/modules/by-module/Mail/grepmail-4.51.readme" rel="nofollow noreferrer">grepmail</a>.</p>
[ { "answer_id": 76698, "author": "Darren Meyer", "author_id": 7826, "author_profile": "https://Stackoverflow.com/users/7826", "pm_score": 2, "selected": false, "text": "<p>It's almost certain that your host doesn't have a definition for the timezone you're specifying, which is what's caus...
2008/09/16
[ "https://Stackoverflow.com/questions/76650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
This has me puzzled. This code worked on another server, but it's failing on Perl v5.8.8 with [Date::Manip](http://search.cpan.org/dist/Date-Manip) loaded from CPAN today. ``` Warning: Use of uninitialized value in numeric lt (<) at /home/downside/lib/Date/Manip.pm line 3327. at dailyupdate.pl line 13 main::__ANON__('Use of uninitialized value in numeric lt (<) at /home/downsid...') called at /home/downside/lib/Date/Manip.pm line 3327 Date::Manip::Date_SecsSince1970GMT(09, 16, 2008, 00, 21, 22) called at /home/downside/lib/Date/Manip.pm line 1905 Date::Manip::UnixDate('today', '%Y-%m-%d') called at TICKER/SYMBOLS/updatesymbols.pm line 122 TICKER::SYMBOLS::updatesymbols::getdate() called at TICKER/SYMBOLS/updatesymbols.pm line 439 TICKER::SYMBOLS::updatesymbols::updatesymbol('DBI::db=HASH(0x87fcc34)', 'TICKER::SYMBOLS::symbol=HASH(0x8a43540)') called at TICKER/SYMBOLS/updatesymbols.pm line 565 TICKER::SYMBOLS::updatesymbols::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 149 EDGAR::updatesymbols('DBI::db=HASH(0x87fcc34)', 1, 0, -1) called at dailyupdate.pl line 180 EDGAR::dailyupdate() called at dailyupdate.pl line 193 ``` The code that's failing is simply: ``` sub getdate() { my $err; ## today &Date::Manip::Date_Init('TZ=EST5EDT'); my $today = Date::Manip::UnixDate('today','%Y-%m-%d'); ## today's date ####print "Today is ",$today,"\n"; ## ***TEMP*** return($today); } ``` That's right; [Date::Manip](http://search.cpan.org/dist/Date-Manip) is failing for `"today"`. The line in [Date::Manip](http://search.cpan.org/dist/Date-Manip) that is failing is: ``` my($tz)=$Cnf{"ConvTZ"}; $tz=$Cnf{"TZ"} if (! $tz); $tz=$Zone{"n2o"}{lc($tz)} if ($tz !~ /^[+-]\d{4}$/); my($tzs)=1; $tzs=-1 if ($tz<0); ### ERROR OCCURS HERE ``` So [Date::Manip](http://search.cpan.org/dist/Date-Manip) is assuming that `$Cnf` has been initialized with elements `"ConvTZ"` or `"TZ"`. Those are initialized in `Date_Init`, so that should have been taken care of. It's only failing in my large program. If I just extract "`getdate()`" above and run it standalone, there's no error. So there's something about the global environment that affects this. This seems to be a known, but not understood problem. If you search Google for "Use of uninitialized value date manip" there are about 2400 hits. This error has been reported with [MythTV](http://www.lemis.com/grog/videorecorder/mythsetup-sep-2006.html) and [grepmail](http://www.cpan.org/modules/by-module/Mail/grepmail-4.51.readme).
It's almost certain that your host doesn't have a definition for the timezone you're specifying, which is what's causing a value to be undefined. Have you checked to make sure a TZ definition file of the same name actually exists on the host?
76,680
<p>I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; <code>messages (id, body)</code> and <code>messages_read (user_id, message_id)</code>.</p> <p>Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this?</p> <p>Thanks!</p>
[ { "answer_id": 76702, "author": "cynicalman", "author_id": 410, "author_profile": "https://Stackoverflow.com/users/410", "pm_score": 3, "selected": false, "text": "<p>Well, you could use</p>\n\n<pre><code>SELECT id FROM messages m WHERE m.id NOT IN(\n SELECT message_id FROM messages_r...
2008/09/16
[ "https://Stackoverflow.com/questions/76680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
I want to maintain a list of global messages that will be displayed to all users of a web app. I want each user to be able to mark these messages as read individually. I've created 2 tables; `messages (id, body)` and `messages_read (user_id, message_id)`. Can you provide an sql statement that selects the unread messages for a single user? Or do you have any suggestions for a better way to handle this? Thanks!
If the table definitions you mentioned are complete, you might want to include a date for each message, so you can order them by date. Also, this might be a slightly more efficient way to do the select: ``` SELECT id, message FROM messages LEFT JOIN messages_read ON messages_read.message_id = messages.id AND messages_read.[user_id] = @user_id WHERE messages_read.message_id IS NULL ```
76,700
<p>I'm looking for a little shell script that will take anything piped into it, and dump it to a file.. for email debugging purposes. Any ideas?</p>
[ { "answer_id": 76719, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 2, "selected": false, "text": "<p>Use Procmail. Procmail is your friend. Procmail is made for this sort of thing.</p>\n" }, { "answer_id": 76721, ...
2008/09/16
[ "https://Stackoverflow.com/questions/76700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12624/" ]
I'm looking for a little shell script that will take anything piped into it, and dump it to a file.. for email debugging purposes. Any ideas?
The unix command tee does this. ``` man tee ```
76,724
<p>I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.</p>
[ { "answer_id": 76783, "author": "Leigh Caldwell", "author_id": 3267, "author_profile": "https://Stackoverflow.com/users/3267", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT id, datefield, count(*) FROM tablename GROUP BY datefield\n HAVING count(*) &gt; 1\n</code></pre>\n...
2008/09/16
[ "https://Stackoverflow.com/questions/76724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to return a list of record id's from a table that may/may not have multiple entries with that record id on the same date. The same date criteria is key - if a record has three entries on 09/10/2008, then I need all three returned. If the record only has one entry on 09/12/2008, then I don't need it.
``` SELECT id, datefield, count(*) FROM tablename GROUP BY datefield HAVING count(*) > 1 ```
76,781
<p>I need to create a custom membership user and provider for an ASP.NET mvc app and I'm looking to use TDD. I have created a User class which inherits from the MembershipUser class, but when I try to test it I get an error that I can't figure out. How do I give it a valid provider name? Do I just need to add it to web.config? But I'm not even testing the web app at this point.</p> <p>[failure] UserTests.SetUp.UserShouldHaveMembershipUserProperties TestCase 'UserTests.SetUp.UserShouldHaveMembershipUserProperties' failed: The membership provider name specified is invalid. Parameter name: providerName System.ArgumentException Message: The membership provider name specified is invalid. Parameter name: providerName Source: System.Web</p>
[ { "answer_id": 76883, "author": "ssmith", "author_id": 13729, "author_profile": "https://Stackoverflow.com/users/13729", "pm_score": 1, "selected": false, "text": "<p>Yes, you need to configure it in your configuration file (probably not web.config for a test library, but app.config). Y...
2008/09/16
[ "https://Stackoverflow.com/questions/76781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9938/" ]
I need to create a custom membership user and provider for an ASP.NET mvc app and I'm looking to use TDD. I have created a User class which inherits from the MembershipUser class, but when I try to test it I get an error that I can't figure out. How do I give it a valid provider name? Do I just need to add it to web.config? But I'm not even testing the web app at this point. [failure] UserTests.SetUp.UserShouldHaveMembershipUserProperties TestCase 'UserTests.SetUp.UserShouldHaveMembershipUserProperties' failed: The membership provider name specified is invalid. Parameter name: providerName System.ArgumentException Message: The membership provider name specified is invalid. Parameter name: providerName Source: System.Web
The configuration to add to your unit test project configuration file would look something like this: ``` <connectionStrings> <remove name="LocalSqlServer"/> <add name="LocalSqlServer" connectionString="<connection string>" providerName="System.Data.SqlClient"/> </connectionStrings> <system.web> <membership defaultProvider="provider"> <providers> <add name="provider" applicationName="MyApp" type="System.Web.Security.SqlMembershipProvider" connectionStringName="LocalSqlServer" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" requiresQuestionAndAnswer="false" maxInvalidPasswordAttempts="3" passwordAttemptWindow="15"/> </providers> </membership> </system.web> ```
76,793
<p>I'm working on a set of classes that will be used to serialize to XML. The XML is not controlled by me and is organized rather well. Unfortunately, there are several sets of nested nodes, the purpose of some of them is just to hold a collection of their children. Based on my current knowledge of XML Serialization, those nodes require another class.</p> <p>Is there a way to make a class serialize to a set of XML nodes instead of just one. Because I feel like I'm being as clear as mud, say we have the xml:</p> <pre><code>&lt;root&gt; &lt;users&gt; &lt;user id=""&gt; &lt;firstname /&gt; &lt;lastname /&gt; ... &lt;/user&gt; &lt;user id=""&gt; &lt;firstname /&gt; &lt;lastname /&gt; ... &lt;/user&gt; &lt;/users&gt; &lt;groups&gt; &lt;group id="" groupname=""&gt; &lt;userid /&gt; &lt;userid /&gt; &lt;/group&gt; &lt;group id="" groupname=""&gt; &lt;userid /&gt; &lt;userid /&gt; &lt;/group&gt; &lt;/groups&gt; &lt;/root&gt; </code></pre> <p>Ideally, 3 classes would be best. A class <code>root</code> with collections of <code>user</code> and <code>group</code> objects. However, best I can figure is that I need a class for <code>root</code>, <code>users</code>, <code>user</code>, <code>groups</code> and <code>group</code>, where <code>users</code> and <code>groups</code> contain only collections of <code>user</code> and <code>group</code> respectively, and <code>root</code> contains a <code>users</code>, and <code>groups</code> object.</p> <p>Anyone out there who knows better than me? (don't lie, I know there are).</p>
[ { "answer_id": 76826, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "<p>Are you not using the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx\" rel=...
2008/09/16
[ "https://Stackoverflow.com/questions/76793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13611/" ]
I'm working on a set of classes that will be used to serialize to XML. The XML is not controlled by me and is organized rather well. Unfortunately, there are several sets of nested nodes, the purpose of some of them is just to hold a collection of their children. Based on my current knowledge of XML Serialization, those nodes require another class. Is there a way to make a class serialize to a set of XML nodes instead of just one. Because I feel like I'm being as clear as mud, say we have the xml: ``` <root> <users> <user id=""> <firstname /> <lastname /> ... </user> <user id=""> <firstname /> <lastname /> ... </user> </users> <groups> <group id="" groupname=""> <userid /> <userid /> </group> <group id="" groupname=""> <userid /> <userid /> </group> </groups> </root> ``` Ideally, 3 classes would be best. A class `root` with collections of `user` and `group` objects. However, best I can figure is that I need a class for `root`, `users`, `user`, `groups` and `group`, where `users` and `groups` contain only collections of `user` and `group` respectively, and `root` contains a `users`, and `groups` object. Anyone out there who knows better than me? (don't lie, I know there are).
Are you not using the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx)? It's pretty damn good and makes doing things like this real easy (I use it quite a lot!). You can simply decorate your class properties with some attributes and the rest is all done for you.. Have you considered using XmlSerializer or is there a particular reason why not? Heres a code snippet of all the work required to get the above to serialize (both ways): ``` [XmlArray("users"), XmlArrayItem("user")] public List<User> Users { get { return _users; } } ```
76,812
<p>What factors determine which approach is more appropriate?</p>
[ { "answer_id": 76832, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 0, "selected": false, "text": "<p>Not nearly enough information here. It depends if your language even supports the construct \"Thing.something\" or equ...
2008/09/16
[ "https://Stackoverflow.com/questions/76812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
What factors determine which approach is more appropriate?
I think both have their places. You shouldn't simply use `DoSomethingToThing(Thing n)` just because you think "Functional programming is good". Likewise you shouldn't simply use `Thing.DoSomething()` because "Object Oriented programming is good". I think it comes down to what you are trying to convey. Stop thinking about your code as a series of instructions, and start thinking about it like a paragraph or sentence of a story. Think about which parts are the most important from the point of view of the task at hand. For example, if the part of the 'sentence' you would like to stress is the object, you should use the OO style. Example: ``` fileHandle.close(); ``` Most of the time when you're passing around file handles, the main thing you are thinking about is keeping track of the file it represents. CounterExample: ``` string x = "Hello World"; submitHttpRequest( x ); ``` In this case submitting the HTTP request is far more important than the string which is the body, so `submitHttpRequst(x)` is preferable to `x.submitViaHttp()` Needless to say, these are not mutually exclusive. You'll probably actually have ``` networkConnection.submitHttpRequest(x) ``` in which you mix them both. The important thing is that you think about what parts are emphasized, and what you will be conveying to the future reader of the code.
76,870
<p>I want to load a different properties file based upon one variable.</p> <p>Basically, if doing a dev build use this properties file, if doing a test build use this other properties file, and if doing a production build use yet a third properties file.</p>
[ { "answer_id": 77099, "author": "Andy Whitfield", "author_id": 4805, "author_profile": "https://Stackoverflow.com/users/4805", "pm_score": 0, "selected": false, "text": "<p>The way I've done this kind of thing is to include seperate build files depending on the type of build using the <a...
2008/09/16
[ "https://Stackoverflow.com/questions/76870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9052/" ]
I want to load a different properties file based upon one variable. Basically, if doing a dev build use this properties file, if doing a test build use this other properties file, and if doing a production build use yet a third properties file.
**Step 1**: Define a property in your NAnt script to track the environment you're building for (local, test, production, etc.). ``` <property name="environment" value="local" /> ``` **Step 2**: If you don't already have a configuration or initialization target that all targets depends on, then create a configuration target, and make sure your other targets depend on it. ``` <target name="config"> <!-- configuration logic goes here --> </target> <target name="buildmyproject" depends="config"> <!-- this target builds your project, but runs the config target first --> </target> ``` **Step 3**: Update your configuration target to pull in an appropriate properties file based on the environment property. ``` <target name="config"> <property name="configFile" value="${environment}.config.xml" /> <if test="${file::exists(configFile)}"> <echo message="Loading ${configFile}..." /> <include buildfile="${configFile}" /> </if> <if test="${not file::exists(configFile) and environment != 'local'}"> <fail message="Configuration file '${configFile}' could not be found." /> </if> </target> ``` Note, I like to allow team members to define their own local.config.xml files that don't get committed to source control. This provides a nice place to store local connection strings or other local environment settings. **Step 4**: Set the environment property when you invoke NAnt, e.g.: * nant -D:environment=dev * nant -D:environment=test * nant -D:environment=production
76,891
<p>I have some curious behavior that I'm having trouble figuring out why is occurring. I'm seeing intermittent timeout exceptions. I'm pretty sure it's related to volume because it's not reproducible in our development environment. As a bandaid solution, I tried upping the sql command timeout to sixty seconds, but as I've found, this doesn't seem to help. Here's the strange part, when I check my logs on the process that is failing, here are the start and end times:</p> <ul> <li>09/16/2008 16:21:49</li> <li>09/16/2008 16:22:19</li> </ul> <p>So how could it be that it's timing out in thirty seconds when I've set the command timeout to sixty??</p> <p>Just for reference, here's the exception being thrown:</p> <pre><code>System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader() at SetClear.DataAccess.SqlHelper.ExecuteReader(CommandType commandType, String commandText, SqlParameter[] commandArgs) </code></pre>
[ { "answer_id": 76911, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 1, "selected": false, "text": "<p>Try changing the SqlConnection's timeout property, rather than that of the command</p>\n" }, { "answer_id": 76921,...
2008/09/16
[ "https://Stackoverflow.com/questions/76891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5416/" ]
I have some curious behavior that I'm having trouble figuring out why is occurring. I'm seeing intermittent timeout exceptions. I'm pretty sure it's related to volume because it's not reproducible in our development environment. As a bandaid solution, I tried upping the sql command timeout to sixty seconds, but as I've found, this doesn't seem to help. Here's the strange part, when I check my logs on the process that is failing, here are the start and end times: * 09/16/2008 16:21:49 * 09/16/2008 16:22:19 So how could it be that it's timing out in thirty seconds when I've set the command timeout to sixty?? Just for reference, here's the exception being thrown: ``` System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlDataReader.ConsumeMetaData() at System.Data.SqlClient.SqlDataReader.get_MetaData() at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) at System.Data.SqlClient.SqlCommand.ExecuteReader() at SetClear.DataAccess.SqlHelper.ExecuteReader(CommandType commandType, String commandText, SqlParameter[] commandArgs) ```
SQL commands time out because the query you're using takes longer than that to execute. Execute it in Query Analyzer or Management Studio, *with a representative amount of data in the database*, and look at the execution plan to find out what's slow. If something is taking a large percentage of the time and is described as a 'table scan' or 'clustered index scan', look at whether you can create an index that would turn that operation into a key lookup (an index seek or clustered index seek).
76,939
<p>Is it possible to install the x86 Remote Debugger as a Service on a 64bit machine? I need to attach a debugger to managed code in a Session 0 process. The process runs 32bit but the debugger service that gets installed is 64bit and wont attach to the 32bit process. </p> <p>I tried creating the Service using the SC command, and was able to get the service to start, and verified that it was running in Task manager processes. However, when I tried to connect to it with visual studio, it said that the remote debugger monitor wasn't enabled. When I stopped the x86 service, and started the x64 service and it was able to find the monitor, but still got an error.</p> <p>Here is the error when I try to use the remote debugger: Unable to attach to the process. The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) cannot debug 32-bit processes or 32-bit dumps. Please use the 32-bit version instead.</p> <p>Here is the error when I try to attach locally: Attaching to a process in a different terminal server session is not supported on this computer. Try remote debugging to the machine and running the Microsoft Visual Studio Remote Debugging Monitor in the process's session.</p> <p>If I try to run the 32bit remote debugger as an application, it wont work attach b/c the Remote Debugger is running in my session and not in session 0.</p>
[ { "answer_id": 77920, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>I haven't tried this, but here's a suggestion anyway:</p>\n\n<p>Try installing the x86 remote debugger service manu...
2008/09/16
[ "https://Stackoverflow.com/questions/76939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291/" ]
Is it possible to install the x86 Remote Debugger as a Service on a 64bit machine? I need to attach a debugger to managed code in a Session 0 process. The process runs 32bit but the debugger service that gets installed is 64bit and wont attach to the 32bit process. I tried creating the Service using the SC command, and was able to get the service to start, and verified that it was running in Task manager processes. However, when I tried to connect to it with visual studio, it said that the remote debugger monitor wasn't enabled. When I stopped the x86 service, and started the x64 service and it was able to find the monitor, but still got an error. Here is the error when I try to use the remote debugger: Unable to attach to the process. The 64-bit version of the Visual Studio Remote Debugging Monitor (MSVSMON.EXE) cannot debug 32-bit processes or 32-bit dumps. Please use the 32-bit version instead. Here is the error when I try to attach locally: Attaching to a process in a different terminal server session is not supported on this computer. Try remote debugging to the machine and running the Microsoft Visual Studio Remote Debugging Monitor in the process's session. If I try to run the 32bit remote debugger as an application, it wont work attach b/c the Remote Debugger is running in my session and not in session 0.
This works on my machine(TM) after installing rdbgsetup\_x64.exe and going through the configuration wizard: ``` sc stop msvsmon90 sc config msvsmon90 binPath= "C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\Remote Debugger\x86\msvsmon.exe /service msvsmon90" sc start msvsmon90 ```
76,967
<p>I know that that is not a question... erm anyway HERE is the question.</p> <p>I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries.</p> <pre><code>ID Species Afghanistan Albania Algeria American Samoa Andorra Angola .... Western Sahara Yemen Zambia Zimbabwe </code></pre> <p>A sample of the data would be something like this</p> <pre><code>id Species Afghanistan Albania American Samoa 1 SP1 null null null 2 SP2 1 1 null 3 SP3 null null 1 </code></pre> <p>It seems to me this is a typical many to many situation and I want 3 tables. Species, Country, and SpeciesFoundInCountry</p> <p>The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables.</p> <p>(It is hard to draw the diagram!)</p> <pre><code>Species SpeciesID SpeciesName Country CountryID CountryName SpeciesFoundInCountry CountryID SpeciesID </code></pre> <p>Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table?</p> <p>I can do it for one Country (this is a select to show what I want out)</p> <pre><code>SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan")); </code></pre> <p>(the mega table is called species)</p> <p>But using this strategy I would need to do the query for each column in the original table. </p> <p>Is there a way of doing this in sql?</p> <p>I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though!</p> <p>Any thoughts (or clarification required)?</p>
[ { "answer_id": 76999, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "<p>Why do you want to do it in SQL? Just write a little script that does the conversion.</p>\n" }, { "answer_id"...
2008/09/16
[ "https://Stackoverflow.com/questions/76967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5552/" ]
I know that that is not a question... erm anyway HERE is the question. I have inherited a database that has 1(one) table in that looks much like this. Its aim is to record what species are found in the various (200 odd) countries. ``` ID Species Afghanistan Albania Algeria American Samoa Andorra Angola .... Western Sahara Yemen Zambia Zimbabwe ``` A sample of the data would be something like this ``` id Species Afghanistan Albania American Samoa 1 SP1 null null null 2 SP2 1 1 null 3 SP3 null null 1 ``` It seems to me this is a typical many to many situation and I want 3 tables. Species, Country, and SpeciesFoundInCountry The link table (SpeciesFoundInCountry) would have foreign keys in both the species and Country tables. (It is hard to draw the diagram!) ``` Species SpeciesID SpeciesName Country CountryID CountryName SpeciesFoundInCountry CountryID SpeciesID ``` Is there a magic way I can generate an insert statement that will get the CountryID from the new Country table based on the column name and the SpeciesID where there is a 1 in the original mega table? I can do it for one Country (this is a select to show what I want out) ``` SELECT Species.ID, Country.CountryID FROM Country, Species WHERE (((Species.Afghanistan)=1)) AND (((Country.Country)="Afghanistan")); ``` (the mega table is called species) But using this strategy I would need to do the query for each column in the original table. Is there a way of doing this in sql? I guess I can OR a load of my where clauses together and write a script to make the sql, seems inelegant though! Any thoughts (or clarification required)?
I would use a script to generate all the individual queries, since this is a one-off import process. Some programs such as Excel are good at mixing different dimensions of data (comparing column names to data inside rows) but relational databases rarely are. However, you might find that some systems (such as Microsoft Access, surprisingly) have convenient tools which you can use to normalise the data. Personally I'd find it quicker to write the script but your relative skills with Access and scripting might be different to mine.
76,976
<p>Is it possible to get the progress of an XMLHttpRequest (bytes uploaded, bytes downloaded)? </p> <p>This would be useful to show a progress bar when the user is uploading a large file. The standard API doesn't seem to support it, but maybe there's some non-standard extension in any of the browsers out there? It seems like a pretty obvious feature to have after all, since the client knows how many bytes were uploaded/downloaded.</p> <p>note: I'm aware of the "poll the server for progress" alternative (it's what I'm doing right now). the main problem with this (other than the complicated server-side code) is that typically, while uploading a big file, the user's connection is completely hosed, because most ISPs offer poor upstream. So making extra requests is not as responsive as I'd hoped. I was hoping there'd be a way (maybe non-standard) to get this information, which the browser has at all times.</p>
[ { "answer_id": 77075, "author": "Sean McMains", "author_id": 2041950, "author_profile": "https://Stackoverflow.com/users/2041950", "pm_score": 3, "selected": false, "text": "<p>One of the most promising approaches seems to be opening a second communication channel back to the server to a...
2008/09/16
[ "https://Stackoverflow.com/questions/76976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is it possible to get the progress of an XMLHttpRequest (bytes uploaded, bytes downloaded)? This would be useful to show a progress bar when the user is uploading a large file. The standard API doesn't seem to support it, but maybe there's some non-standard extension in any of the browsers out there? It seems like a pretty obvious feature to have after all, since the client knows how many bytes were uploaded/downloaded. note: I'm aware of the "poll the server for progress" alternative (it's what I'm doing right now). the main problem with this (other than the complicated server-side code) is that typically, while uploading a big file, the user's connection is completely hosed, because most ISPs offer poor upstream. So making extra requests is not as responsive as I'd hoped. I was hoping there'd be a way (maybe non-standard) to get this information, which the browser has at all times.
For the bytes uploaded it is quite easy. Just monitor the `xhr.upload.onprogress` event. The browser knows the size of the files it has to upload and the size of the uploaded data, so it can provide the progress info. For the bytes downloaded (when getting the info with `xhr.responseText`), it is a little bit more difficult, because the browser doesn't know how many bytes will be sent in the server request. The only thing that the browser knows in this case is the size of the bytes it is receiving. There is a solution for this, it's sufficient to set a `Content-Length` header on the server script, in order to get the total size of the bytes the browser is going to receive. For more go to <https://developer.mozilla.org/en/Using_XMLHttpRequest> . Example: My server script reads a zip file (it takes 5 seconds): ``` $filesize=filesize('test.zip'); header("Content-Length: " . $filesize); // set header length // if the headers is not set then the evt.loaded will be 0 readfile('test.zip'); exit 0; ``` Now I can monitor the download process of the server script, because I know it's total length: ``` function updateProgress(evt) { if (evt.lengthComputable) { // evt.loaded the bytes the browser received // evt.total the total bytes set by the header // jQuery UI progress bar to show the progress on screen var percentComplete = (evt.loaded / evt.total) * 100; $('#progressbar').progressbar( "option", "value", percentComplete ); } } function sendreq(evt) { var req = new XMLHttpRequest(); $('#progressbar').progressbar(); req.onprogress = updateProgress; req.open('GET', 'test.php', true); req.onreadystatechange = function (aEvt) { if (req.readyState == 4) { //run any callback here } }; req.send(); } ```
76,993
<p>How can I set the protected <code>DoubleBuffered</code> property of the controls on a form that are suffering from flicker?</p>
[ { "answer_id": 77023, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 4, "selected": false, "text": "<pre><code>public void EnableDoubleBuffering()\n{\n this.SetStyle(ControlStyles.DoubleBuffer | \n ControlStyles.UserPai...
2008/09/16
[ "https://Stackoverflow.com/questions/76993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
How can I set the protected `DoubleBuffered` property of the controls on a form that are suffering from flicker?
Here's a more generic version of [Dummy's solution](https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form#77041). We can use reflection to get at the protected [DoubleBuffered](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.doublebuffered.aspx) property, and then it can be set to **true**. **Note**: You should [pay your developer taxes](https://devblogs.microsoft.com/oldnewthing/20050822-11/?p=34483) and not [use double-buffering if the user is running in a terminal services session](https://devblogs.microsoft.com/oldnewthing/20060103-12/?p=32793) (e.g. Remote Desktop) This helper method will not turn on double buffering if the person is running in remote desktop. ``` public static void SetDoubleBuffered(System.Windows.Forms.Control c) { //Taxes: Remote Desktop Connection and painting //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx if (System.Windows.Forms.SystemInformation.TerminalServerSession) return; System.Reflection.PropertyInfo aProp = typeof(System.Windows.Forms.Control).GetProperty( "DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); aProp.SetValue(c, true, null); } ```
77,005
<p>I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace.</p> <p>My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using <code>gcc</code>).</p> <p>I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?</p>
[ { "answer_id": 76867, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 3, "selected": false, "text": "<pre><code>ulimit -c unlimited\n</code></pre>\n\n<p>is a system variable, wich will allow to create a core dump after your app...
2008/09/16
[ "https://Stackoverflow.com/questions/77005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
I am working on Linux with the GCC compiler. When my C++ program crashes I would like it to automatically generate a stacktrace. My program is being run by many different users and it also runs on Linux, Windows and Macintosh (all versions are compiled using `gcc`). I would like my program to be able to generate a stack trace when it crashes and the next time the user runs it, it will ask them if it is ok to send the stack trace to me so I can track down the problem. I can handle the sending the info to me but I don't know how to generate the trace string. Any ideas?
For Linux and I believe Mac OS X, if you're using gcc, or any compiler that uses glibc, you can use the backtrace() functions in `execinfo.h` to print a stacktrace and exit gracefully when you get a segmentation fault. Documentation can be found [in the libc manual](http://www.gnu.org/software/libc/manual/html_node/Backtraces.html). Here's an example program that installs a `SIGSEGV` handler and prints a stacktrace to `stderr` when it segfaults. The `baz()` function here causes the segfault that triggers the handler: ``` #include <stdio.h> #include <execinfo.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> void handler(int sig) { void *array[10]; size_t size; // get void*'s for all entries on the stack size = backtrace(array, 10); // print out all the frames to stderr fprintf(stderr, "Error: signal %d:\n", sig); backtrace_symbols_fd(array, size, STDERR_FILENO); exit(1); } void baz() { int *foo = (int*)-1; // make a bad pointer printf("%d\n", *foo); // causes segfault } void bar() { baz(); } void foo() { bar(); } int main(int argc, char **argv) { signal(SIGSEGV, handler); // install our handler foo(); // this will call foo, bar, and baz. baz segfaults. } ``` Compiling with `-g -rdynamic` gets you symbol info in your output, which glibc can use to make a nice stacktrace: ``` $ gcc -g -rdynamic ./test.c -o test ``` Executing this gets you this output: ``` $ ./test Error: signal 11: ./test(handler+0x19)[0x400911] /lib64/tls/libc.so.6[0x3a9b92e380] ./test(baz+0x14)[0x400962] ./test(bar+0xe)[0x400983] ./test(foo+0xe)[0x400993] ./test(main+0x28)[0x4009bd] /lib64/tls/libc.so.6(__libc_start_main+0xdb)[0x3a9b91c4bb] ./test[0x40086a] ``` This shows the load module, offset, and function that each frame in the stack came from. Here you can see the signal handler on top of the stack, and the libc functions before `main` in addition to `main`, `foo`, `bar`, and `baz`.
77,025
<p>I want to set a breakpoint on the <code>__DoPostBack</code> method, but it's a pain to find the correct file to set the breakpoint in.</p> <p>The method <code>__DoPostBack</code> is contained in an auto-generated js file called something like: </p> <pre><code>ScriptResource.axd?d=P_lo2... </code></pre> <p>After a few post-backs visual studio gets littered with many of these files, and it's a bit of a bear to check which one the current page is referencing. Any thoughts?</p>
[ { "answer_id": 77032, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "<p>Anything that you like and feel that you can contribute to.</p>\n" }, { "answer_id": 77049, "author": "benefac...
2008/09/16
[ "https://Stackoverflow.com/questions/77025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7936/" ]
I want to set a breakpoint on the `__DoPostBack` method, but it's a pain to find the correct file to set the breakpoint in. The method `__DoPostBack` is contained in an auto-generated js file called something like: ``` ScriptResource.axd?d=P_lo2... ``` After a few post-backs visual studio gets littered with many of these files, and it's a bit of a bear to check which one the current page is referencing. Any thoughts?
How about this one <http://sourceforge.net/projects/sqlitebrowser/>: > > SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface. > > >
77,171
<p>After reading Evan's and Nilsson's books I am still not sure how to manage Data access in a domain driven project. Should the CRUD methods be part of the repositories, i.e. OrderRepository.GetOrdersByCustomer(customer) or should they be part of the entities: Customer.GetOrders(). The latter approach seems more OO, but it will distribute Data Access for a single entity type among multiple objects, i.e. Customer.GetOrders(), Invoice.GetOrders(), ShipmentBatch.GetOrders() ,etc. What about Inserting and updating?</p>
[ { "answer_id": 77244, "author": "Vin", "author_id": 1747, "author_profile": "https://Stackoverflow.com/users/1747", "pm_score": 2, "selected": false, "text": "<p>Even in a DDD, I would keep Data Access classes and routines separate from Entities.</p>\n\n<p>Reasons are,</p>\n\n<ol>\n<li>T...
2008/09/16
[ "https://Stackoverflow.com/questions/77171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
After reading Evan's and Nilsson's books I am still not sure how to manage Data access in a domain driven project. Should the CRUD methods be part of the repositories, i.e. OrderRepository.GetOrdersByCustomer(customer) or should they be part of the entities: Customer.GetOrders(). The latter approach seems more OO, but it will distribute Data Access for a single entity type among multiple objects, i.e. Customer.GetOrders(), Invoice.GetOrders(), ShipmentBatch.GetOrders() ,etc. What about Inserting and updating?
CRUD-ish methods should be part of the Repository...ish. But I think you should ask why you have a bunch of CRUD methods. What do they *really* do? What are they *really* for? If you actually call out the data access patterns your application uses I think it makes the repository a lot more useful and keeps you from having to do shotgun surgery when certain types of changes happen to your domain. ``` CustomerRepo.GetThoseWhoHaventPaidTheirBill() // or GetCustomer(new HaventPaidBillSpecification()) // is better than foreach (var customer in GetCustomer()) { /* logic leaking all over the floor */ } ``` "Save" type methods should also be part of the repository. If you have aggregate roots, this keeps you from having a Repository explosion, or having logic spread out all over: You don't have 4 x # of entities data access patterns, just the ones you actually use on the aggregate roots. That's my $.02.
77,172
<p>Do you guys keep track of stored procedures and database schema in your source control system of choice?</p> <p>When you make a change (add a table, update an stored proc, how do you get the changes into source control? </p> <p>We use SQL Server at work, and I've begun using darcs for versioning, but I'd be curious about general strategies as well as any handy tools.</p> <p><em>Edit:</em> Wow, thanks for all the great suggestions, guys! I wish I could select more than one "Accepted Answer"!</p>
[ { "answer_id": 77187, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>We keep stored procedures in source control. </p>\n" }, { "answer_id": 77196, "author": "ahockley", "autho...
2008/09/16
[ "https://Stackoverflow.com/questions/77172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7856/" ]
Do you guys keep track of stored procedures and database schema in your source control system of choice? When you make a change (add a table, update an stored proc, how do you get the changes into source control? We use SQL Server at work, and I've begun using darcs for versioning, but I'd be curious about general strategies as well as any handy tools. *Edit:* Wow, thanks for all the great suggestions, guys! I wish I could select more than one "Accepted Answer"!
We choose to script everything, and that includes all stored procedures and schema changes. No wysiwyg tools, and no fancy 'sync' programs are necessary. Schema changes are easy, all you need to do is create and maintain a single file for that version, including all schema and data changes. This becomes your conversion script from version x to x+1. You can then run it against a production backup and integrate that into your 'daily build' to verify that it works without errors. Note it's important not to change or delete already written schema / data loading sql as you can end up breaking any sql written later. ``` -- change #1234 ALTER TABLE asdf ADD COLUMN MyNewID INT GO -- change #5678 ALTER TABLE asdf DROP COLUMN SomeOtherID GO ``` For stored procedures, we elect for a single file per sproc, and it uses the drop/create form. All stored procedures are recreated at deployment. The downside is that if a change was done outside source control, the change is lost. At the same time, that's true for any code, but your DBA'a need to be aware of this. This really stops people outside the team mucking with your stored procedures, as their changes are lost in an upgrade. Using Sql Server, the syntax looks like this: ``` if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[usp_MyProc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1) drop procedure [usp_MyProc] GO CREATE PROCEDURE [usp_MyProc] ( @UserID INT ) AS SET NOCOUNT ON -- stored procedure logic. SET NOCOUNT OFF GO ``` The only thing left to do is write a utility program that collates all the individual files and creates a new file with the entire set of updates (as a single script). Do this by first adding the schema changes then recursing the directory structure and including all the stored procedure files. As an upside to scripting everything, you'll become much better at reading and writing SQL. You can also make this entire process more elaborate, but this is the basic format of how to source-control all sql without any special software. addendum: Rick is correct that you will lose permissions on stored procedures with DROP/CREATE, so you may need to write another script will re-enable specific permissions. This permission script would be the last to run. Our experience found more issues with ALTER verses DROP/CREATE semantics. YMMV
77,213
<p>I have a large number of Enums that implement this interface:</p> <pre><code>/** * Interface for an enumeration, each element of which can be uniquely identified by its code */ public interface CodableEnum { /** * Get the element with a particular code * @param code * @return */ public CodableEnum getByCode(String code); /** * Get the code that identifies an element of the enum * @return */ public String getCode(); } </code></pre> <p>A typical example is:</p> <pre><code>public enum IMType implements CodableEnum { MSN_MESSENGER("msn_messenger"), GOOGLE_TALK("google_talk"), SKYPE("skype"), YAHOO_MESSENGER("yahoo_messenger"); private final String code; IMType (String code) { this.code = code; } public String getCode() { return code; } public IMType getByCode(String code) { for (IMType e : IMType.values()) { if (e.getCode().equalsIgnoreCase(code)) { return e; } } } } </code></pre> <p>As you can imagine these methods are virtually identical in all implementations of CodableEnum. I would like to eliminate this duplication, but frankly don't know how. I tried using a class such as the following:</p> <pre><code>public abstract class DefaultCodableEnum implements CodableEnum { private final String code; DefaultCodableEnum(String code) { this.code = code; } public String getCode() { return this.code; } public abstract CodableEnum getByCode(String code); } </code></pre> <p>But this turns out to be fairly useless because:</p> <ol> <li>An enum cannot extend a class</li> <li>Elements of an enum (SKYPE, GOOGLE_TALK, etc.) cannot extend a class</li> <li>I cannot provide a default implementation of getByCode(), because DefaultCodableEnum is not itself an Enum. I tried changing DefaultCodableEnum to extend java.lang.Enum, but this doesn't appear to be allowed.</li> </ol> <p>Any suggestions that do not rely on reflection? Thanks, Don</p>
[ { "answer_id": 77298, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>Unfortunately, I don't think that there is a way to do this. Your best bet would pro ably be to give up in emums a...
2008/09/16
[ "https://Stackoverflow.com/questions/77213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I have a large number of Enums that implement this interface: ``` /** * Interface for an enumeration, each element of which can be uniquely identified by its code */ public interface CodableEnum { /** * Get the element with a particular code * @param code * @return */ public CodableEnum getByCode(String code); /** * Get the code that identifies an element of the enum * @return */ public String getCode(); } ``` A typical example is: ``` public enum IMType implements CodableEnum { MSN_MESSENGER("msn_messenger"), GOOGLE_TALK("google_talk"), SKYPE("skype"), YAHOO_MESSENGER("yahoo_messenger"); private final String code; IMType (String code) { this.code = code; } public String getCode() { return code; } public IMType getByCode(String code) { for (IMType e : IMType.values()) { if (e.getCode().equalsIgnoreCase(code)) { return e; } } } } ``` As you can imagine these methods are virtually identical in all implementations of CodableEnum. I would like to eliminate this duplication, but frankly don't know how. I tried using a class such as the following: ``` public abstract class DefaultCodableEnum implements CodableEnum { private final String code; DefaultCodableEnum(String code) { this.code = code; } public String getCode() { return this.code; } public abstract CodableEnum getByCode(String code); } ``` But this turns out to be fairly useless because: 1. An enum cannot extend a class 2. Elements of an enum (SKYPE, GOOGLE\_TALK, etc.) cannot extend a class 3. I cannot provide a default implementation of getByCode(), because DefaultCodableEnum is not itself an Enum. I tried changing DefaultCodableEnum to extend java.lang.Enum, but this doesn't appear to be allowed. Any suggestions that do not rely on reflection? Thanks, Don
You could factor the duplicated code into a `CodeableEnumHelper` class: ``` public class CodeableEnumHelper { public static CodeableEnum getByCode(String code, CodeableEnum[] values) { for (CodeableEnum e : values) { if (e.getCode().equalsIgnoreCase(code)) { return e; } } return null; } } ``` Each `CodeableEnum` class would still have to implement a `getByCode` method, but the actual implementation of the method has at least been centralized to a single place. ``` public enum IMType implements CodeableEnum { ... public IMType getByCode(String code) { return (IMType)CodeableEnumHelper.getByCode(code, this.values()); } } ```
77,258
<p>I am trying to solve the current problem using GPU capabilities: "given a point cloud P and an oriented plane described by a point and a normal (Pp, Np) return the points in the cloud which lye at a distance equal or less than EPSILON from the plane".</p> <p>Talking with a colleague of mine I converged toward the following solution:</p> <p>1) prepare a vertex buffer of the points with an attached texture coordinate such that every point has a different vertex coordinate 2) set projection status to orthogonal 3) rotate the mesh such that the normal of the plane is aligned with the -z axis and offset it such that x,y,z=0 corresponds to Pp 4) set the z-clipping plane such that z:[-EPSILON;+EPSILON] 5) render to a texture 6) retrieve the texture from the graphic card 7) read the texture from the graphic card and see what points were rendered (in terms of their indexes), which are the points within the desired distance range.</p> <p>Now the problems are the following: q1) Do I need to open a window-frame to be able to do such operation? I am working within MATLAB and calling MEX-C++. By experience I know that as soon as you open a new frame the whole suit crashes miserably! q2) what's the primitive to give a GLPoint a texture coordinate? q3) I am not too clear how the render to a texture would be implemented? any reference, tutorial would be awesome... q4) How would you retrieve this texture from the card? again, any reference, tutorial would be awesome...</p> <p>I am on a tight schedule, thus, it would be nice if you could point me out the names of the techniques I should learn about, rather to the GLSL specification document and the OpenGL API as somebody has done. Those are a tiny bit too vague answers to my question.</p> <p>Thanks a lot for any comment.</p> <p>p.s. Also notice that I would rather not use any resource like CUDA if possible, thus, getting something which uses as much OpenGL elements as possible without requiring me to write a new shader. </p> <p>Note: cross posted at <a href="http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&amp;Number=245911#Post245911" rel="nofollow noreferrer">http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&amp;Number=245911#Post245911</a></p>
[ { "answer_id": 77543, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 0, "selected": false, "text": "<p>Ok first as a little disclaimer: I know nothing about 3D programming.</p>\n\n<p>Now my purely mathematical idea:</p>\...
2008/09/16
[ "https://Stackoverflow.com/questions/77258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to solve the current problem using GPU capabilities: "given a point cloud P and an oriented plane described by a point and a normal (Pp, Np) return the points in the cloud which lye at a distance equal or less than EPSILON from the plane". Talking with a colleague of mine I converged toward the following solution: 1) prepare a vertex buffer of the points with an attached texture coordinate such that every point has a different vertex coordinate 2) set projection status to orthogonal 3) rotate the mesh such that the normal of the plane is aligned with the -z axis and offset it such that x,y,z=0 corresponds to Pp 4) set the z-clipping plane such that z:[-EPSILON;+EPSILON] 5) render to a texture 6) retrieve the texture from the graphic card 7) read the texture from the graphic card and see what points were rendered (in terms of their indexes), which are the points within the desired distance range. Now the problems are the following: q1) Do I need to open a window-frame to be able to do such operation? I am working within MATLAB and calling MEX-C++. By experience I know that as soon as you open a new frame the whole suit crashes miserably! q2) what's the primitive to give a GLPoint a texture coordinate? q3) I am not too clear how the render to a texture would be implemented? any reference, tutorial would be awesome... q4) How would you retrieve this texture from the card? again, any reference, tutorial would be awesome... I am on a tight schedule, thus, it would be nice if you could point me out the names of the techniques I should learn about, rather to the GLSL specification document and the OpenGL API as somebody has done. Those are a tiny bit too vague answers to my question. Thanks a lot for any comment. p.s. Also notice that I would rather not use any resource like CUDA if possible, thus, getting something which uses as much OpenGL elements as possible without requiring me to write a new shader. Note: cross posted at <http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=245911#Post245911>
It's simple: Let n be the normal of the plane and x be the point. ``` n_u = n/norm(n) //this is a normal vector of unit length d = scalarprod(n,x) //this is the distance of the plane to the origin for each point p_i d_i = abs(scalarprod(p_i,n) - d) //this is the distance of the point to the plane ``` Obviously "scalarprod" means "scalar product" and "abs" means "absolute value". If you wonder why just read the article on scalar products at wikipedia.
77,266
<p>Can I persuade <code>operator&gt;&gt;</code> in C++ to read both a <code>hex</code> value AND and a <code>decimal</code> value? The following program demonstrates how reading hex goes wrong. I'd like the same <code>istringstream</code> to be able to read both <code>hex</code> and <code>decimal</code>.</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; int main(int argc, char** argv) { int result = 0; // std::istringstream is(&quot;5&quot;); // this works std::istringstream is(&quot;0x5&quot;); // this fails while ( is.good() ) { if ( is.peek() != EOF ) is &gt;&gt; result; else break; } if ( is.fail() ) std::cout &lt;&lt; &quot;failed to read string&quot; &lt;&lt; std::endl; else std::cout &lt;&lt; &quot;successfully read string&quot; &lt;&lt; std::endl; std::cout &lt;&lt; &quot;result: &quot; &lt;&lt; result &lt;&lt; std::endl; } </code></pre>
[ { "answer_id": 77359, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 4, "selected": false, "text": "<p>You need to tell C++ what your base is going to be.</p>\n\n<p>Want to parse a hex number? Change your \"is >> result\" l...
2008/09/16
[ "https://Stackoverflow.com/questions/77266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1359466/" ]
Can I persuade `operator>>` in C++ to read both a `hex` value AND and a `decimal` value? The following program demonstrates how reading hex goes wrong. I'd like the same `istringstream` to be able to read both `hex` and `decimal`. ``` #include <iostream> #include <sstream> int main(int argc, char** argv) { int result = 0; // std::istringstream is("5"); // this works std::istringstream is("0x5"); // this fails while ( is.good() ) { if ( is.peek() != EOF ) is >> result; else break; } if ( is.fail() ) std::cout << "failed to read string" << std::endl; else std::cout << "successfully read string" << std::endl; std::cout << "result: " << result << std::endl; } ```
Use [`std::setbase(0)`](http://en.cppreference.com/w/cpp/io/manip/setbase) which enables prefix dependent parsing. It will be able to parse `10` (dec) as 10 decimal, `0x10` (hex) as 16 decimal and `010` (octal) as 8 decimal. ``` #include <iomanip> is >> std::setbase(0) >> result; ```
77,287
<p>I have a <code>modal dialog</code> form which has some "help links" within it which should open other non-modal panels or dialogs on top of it (while keeping the main dialog otherwise modal). </p> <p>However, these always end up behind the mask. <code>YUI</code> seems to be recognizing the highest <code>z-index</code> out there and setting the mask and modal dialog to be higher than that.</p> <p>If i wait to panel-ize the help content, then i can set those to have a higher z-index. So far, so good. The problem then is that fields within the secondary, non-modal dialogs are unfocusable. The modal dialog beneath them seems to somehow be preventing the focus from going to anything not in the initial, modal dialog.</p> <p>It would also be acceptable if i could do this "dialog group modality" with jQuery, if YUI simply won't allow this.</p> <p>Help!</p>
[ { "answer_id": 81688, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 0, "selected": false, "text": "<p>The original dialog can't be modal if the user is supposed to interact with other elements—that's the definition of modal...
2008/09/16
[ "https://Stackoverflow.com/questions/77287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8131/" ]
I have a `modal dialog` form which has some "help links" within it which should open other non-modal panels or dialogs on top of it (while keeping the main dialog otherwise modal). However, these always end up behind the mask. `YUI` seems to be recognizing the highest `z-index` out there and setting the mask and modal dialog to be higher than that. If i wait to panel-ize the help content, then i can set those to have a higher z-index. So far, so good. The problem then is that fields within the secondary, non-modal dialogs are unfocusable. The modal dialog beneath them seems to somehow be preventing the focus from going to anything not in the initial, modal dialog. It would also be acceptable if i could do this "dialog group modality" with jQuery, if YUI simply won't allow this. Help!
By default, YUI manages the z-index of anything that extends YAHOO.widget.Overlay and uses an overlay panel. It does this through the YAHOO.widget.Overlay's "bringToTop" method. You can turn this off by simply changing the "bringToTop" method to be an empty function: ``` YAHOO.widget.Overlay.prototype.bringToTop = function() { }; ``` That code would turn it off for good and you could just put this at the bottom of the container.js file. I find that approach to be a little bit too much of a sledge hammer approach, so we extend the YUI classes and after calling "super.constuctor" write: ``` this.bringToTop = function() { }; ``` If you do this, you are essentially telling YUI that you will manage the z-indices of your elements yourself. That's probably fine, but something to consider before doing it.
77,293
<p>I would like to keep the overhead at a minimum. Right now I have:</p> <pre><code>// Launch a Message Box with advice to the user DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation); // The test will only be launched if the user has selected Yes on the Message Box if(result == DialogResult::Yes) { // Execute code } </code></pre> <p>Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.</p>
[ { "answer_id": 77457, "author": "Corin Blaikie", "author_id": 1736, "author_profile": "https://Stackoverflow.com/users/1736", "pm_score": 3, "selected": true, "text": "<p>You can use \"OK\" and \"Cancel\"</p>\n\n<p>By substituting <code>MessageBoxButtons::YesNo</code> with <code>MessageB...
2008/09/16
[ "https://Stackoverflow.com/questions/77293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9058/" ]
I would like to keep the overhead at a minimum. Right now I have: ``` // Launch a Message Box with advice to the user DialogResult result = MessageBox::Show("This may take awhile, do you wish to continue?", "Warning", MessageBoxButtons::YesNo, MessageBoxIcon::Exclamation); // The test will only be launched if the user has selected Yes on the Message Box if(result == DialogResult::Yes) { // Execute code } ``` Unfortunately my client would prefer "Continue" and "Cancel" in place of the default "Yes" and "No" button text. It seems like there should be an easy way to do this.
You can use "OK" and "Cancel" By substituting `MessageBoxButtons::YesNo` with `MessageBoxButtons::OKCancel` [MessageBoxButtons Enum](http://msdn.microsoft.com/en-us/library/system.windows.forms.messageboxbuttons.aspx) Short of that you would have to create a new form, as I don't believe the Enum can be extended.
77,382
<p>I have a class with a public array of bytes. Lets say its</p> <pre><code>Public myBuff as byte() </code></pre> <p>Events within the class get chunks of data in byte array. How do i tell the event code to stick the get chunk on the end? Lets say</p> <pre><code>Private Sub GetChunk Dim chunk as byte '... get stuff in chunk Me.myBuff += chunk '(stick chunk on end of public array) End sub </code></pre> <p>Or am I totally missing the point?</p>
[ { "answer_id": 77390, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>if i remember right, in vb you want to redim with preserve to grow an array.</p>\n" }, { "answer_id": 77402, "...
2008/09/16
[ "https://Stackoverflow.com/questions/77382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a class with a public array of bytes. Lets say its ``` Public myBuff as byte() ``` Events within the class get chunks of data in byte array. How do i tell the event code to stick the get chunk on the end? Lets say ``` Private Sub GetChunk Dim chunk as byte '... get stuff in chunk Me.myBuff += chunk '(stick chunk on end of public array) End sub ``` Or am I totally missing the point?
if i remember right, in vb you want to redim with preserve to grow an array.
77,387
<p>In the Java collections framework, the Collection interface declares the following method:</p> <blockquote> <p><a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5B%5D)" rel="noreferrer"><code>&lt;T&gt; T[] toArray(T[] a)</code></a></p> <p>Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.</p> </blockquote> <p>If you wanted to implement this method, how would you create an array of the type of <strong>a</strong>, known only at runtime?</p>
[ { "answer_id": 77426, "author": "Arno", "author_id": 13685, "author_profile": "https://Stackoverflow.com/users/13685", "pm_score": 2, "selected": false, "text": "<pre><code>Array.newInstance(Class componentType, int length)\n</code></pre>\n" }, { "answer_id": 77429, "author":...
2008/09/16
[ "https://Stackoverflow.com/questions/77387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13979/" ]
In the Java collections framework, the Collection interface declares the following method: > > [`<T> T[] toArray(T[] a)`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html#toArray(T%5B%5D)) > > > Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection. > > > If you wanted to implement this method, how would you create an array of the type of **a**, known only at runtime?
Use the static method ``` java.lang.reflect.Array.newInstance(Class<?> componentType, int length) ``` A tutorial on its use can be found here: <http://java.sun.com/docs/books/tutorial/reflect/special/arrayInstance.html>
77,434
<p>Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the <code>length()</code> function? Something ala PERL's <code>$#</code> special var?</p> <p>So I would like something like:</p> <pre><code>dat$vec1$vec2[$#] </code></pre> <p>instead of</p> <pre><code>dat$vec1$vec2[length(dat$vec1$vec2)] </code></pre>
[ { "answer_id": 83162, "author": "Gregg Lind", "author_id": 15842, "author_profile": "https://Stackoverflow.com/users/15842", "pm_score": 7, "selected": false, "text": "<p>If you're looking for something as nice as Python's x[-1] notation, I think you're out of luck. The standard idiom i...
2008/09/16
[ "https://Stackoverflow.com/questions/77434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14008/" ]
Suppose I have a vector that is nested in a dataframe one or two levels. Is there a quick and dirty way to access the last value, without using the `length()` function? Something ala PERL's `$#` special var? So I would like something like: ``` dat$vec1$vec2[$#] ``` instead of ``` dat$vec1$vec2[length(dat$vec1$vec2)] ```
I use the `tail` function: ``` tail(vector, n=1) ``` The nice thing with `tail` is that it works on dataframes too, unlike the `x[length(x)]` idiom.
77,503
<p>I am trying to compare two large datasets from a SQL query. Right now the SQL query is done externally and the results from each dataset is saved into its own csv file. My little C# console application loads up the two text/csv files and compares them for differences and saves the differences to a text file.</p> <p>Its a very simple application that just loads all the data from the first file into an arraylist and does a .compare() on the arraylist as each line is read from the second csv file. Then saves the records that don't match.</p> <p>The application works but I would like to improve the performance. I figure I can greatly improve performance if I can take advantage of the fact that both files are sorted, but I don't know a datatype in C# that keeps order and would allow me to select a specific position. Theres a basic array, but I don't know how many items are going to be in each list. I could have over a million records. Is there a data type available that I should be looking at? </p>
[ { "answer_id": 77546, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 0, "selected": false, "text": "<p>Well, there are several approaches that would work. You could write your own data structure that did this. Or you can t...
2008/09/16
[ "https://Stackoverflow.com/questions/77503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8664/" ]
I am trying to compare two large datasets from a SQL query. Right now the SQL query is done externally and the results from each dataset is saved into its own csv file. My little C# console application loads up the two text/csv files and compares them for differences and saves the differences to a text file. Its a very simple application that just loads all the data from the first file into an arraylist and does a .compare() on the arraylist as each line is read from the second csv file. Then saves the records that don't match. The application works but I would like to improve the performance. I figure I can greatly improve performance if I can take advantage of the fact that both files are sorted, but I don't know a datatype in C# that keeps order and would allow me to select a specific position. Theres a basic array, but I don't know how many items are going to be in each list. I could have over a million records. Is there a data type available that I should be looking at?
If data in both of your CSV files is already sorted and have the same number of records, you could skip the data structure entirely and do in-place analysis. ``` StreamReader one = new StreamReader("C:\file1.csv"); StreamReader two = new StreamReader("C:\file2.csv"); String lineOne; String lineTwo; StreamWriter differences = new StreamWriter("Output.csv"); while (!one.EndOfStream) { lineOne = one.ReadLine(); lineTwo = two.ReadLine(); // do your comparison. bool areDifferent = true; if (areDifferent) differences.WriteLine(lineOne + lineTwo); } one.Close(); two.Close(); differences.Close(); ```
77,528
<p>I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account.</p> <p>I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively." Here's a sample command:</p> <pre><code>AT 12:00 /interactive cmd.exe </code></pre> <p>Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe. </p> <pre><code>C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact C:\sc start RunCMDAsLSA </code></pre> <p>In this case the service fails to start and results it the following error message:</p> <pre><code>FAILED 1053: The service did not respond to the start or control request in a timely fashion. </code></pre> <p>The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them.</p> <p>I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task.</p> <p>Thus far, each of my attempts have ended in failure. Any suggestions?</p>
[ { "answer_id": 77615, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 3, "selected": false, "text": "<p>Found an answer <a href=\"http://blogs.msdn.com/adioltean/articles/271063.aspx\" rel=\"noreferrer\">here</a> which seems ...
2008/09/16
[ "https://Stackoverflow.com/questions/77528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4115/" ]
I'm currently running Vista and I would like to manually complete the same operations as my Windows Service. Since the Windows Service is running under the Local System Account, I would like to emulate this same behavior. Basically, I would like to run CMD.EXE under the Local System Account. I found information online which suggests lauching the CMD.exe using the DOS Task Scheduler AT command, but I received a Vista warning that "due to security enhancements, this task will run at the time excepted but not interactively." Here's a sample command: ``` AT 12:00 /interactive cmd.exe ``` Another solution suggested creating a secondary Windows Service via the Service Control (sc.exe) which merely launches CMD.exe. ``` C:\sc create RunCMDAsLSA binpath= "cmd" type=own type=interact C:\sc start RunCMDAsLSA ``` In this case the service fails to start and results it the following error message: ``` FAILED 1053: The service did not respond to the start or control request in a timely fashion. ``` The third suggestion was to launch CMD.exe via a Scheduled Task. Though you may run scheduled tasks under various accounts, I don't believe the Local System Account is one of them. I've tried using the Runas as well, but think I'm running into the same restriction as found when running a scheduled task. Thus far, each of my attempts have ended in failure. Any suggestions?
Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated. However, I came across this [article](http://verbalprocessor.com/2007/12/05/running-a-cmd-prompt-as-local-system) which demonstrates the use of [PSTools](http://download.sysinternals.com/files/PSTools.zip) from [SysInternals](http://sysinternals.com/) (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic: ``` psexec -i -s cmd.exe ``` PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem. Many thanks to those who offered help.
77,552
<p>Why is it bad to name a variable <code>id</code> in Python?</p>
[ { "answer_id": 77563, "author": "ahockley", "author_id": 8209, "author_profile": "https://Stackoverflow.com/users/8209", "pm_score": -1, "selected": false, "text": "<p>Because it's the name of a builtin function.</p>\n" }, { "answer_id": 77600, "author": "Toni Ruža", "aut...
2008/09/16
[ "https://Stackoverflow.com/questions/77552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5926/" ]
Why is it bad to name a variable `id` in Python?
`id()` is a fundamental built-in: > > Help on built-in function `id` in module > `__builtin__`: > > > > ```none > id(...) > > id(object) -> integer > > Return the identity of an object. This is guaranteed to be unique among > simultaneously existing objects. (Hint: it's the object's memory > address.) > > ``` > > In general, using variable names that eclipse a keyword or built-in function in any language is a bad idea, even if it is allowed.
77,558
<p>I want to write a raw byte/byte stream to a position in a file. This is what I have currently:</p> <pre><code>$fpr = fopen($out, 'r+'); fseek($fpr, 1); //seek to second byte fwrite($fpr, 0x63); fclose($fpr); </code></pre> <p>This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99.</p> <p>Thanks for your time.</p>
[ { "answer_id": 77585, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 4, "selected": true, "text": "<p><code>fwrite()</code> takes strings. Try <code>chr(0x63)</code> if you want to write a <code>0x63</code> byte to the file....
2008/09/16
[ "https://Stackoverflow.com/questions/77558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10333/" ]
I want to write a raw byte/byte stream to a position in a file. This is what I have currently: ``` $fpr = fopen($out, 'r+'); fseek($fpr, 1); //seek to second byte fwrite($fpr, 0x63); fclose($fpr); ``` This currently writes the actually string value of "99" starting at byte offset 1. IE, it writes bytes "9" and "9". I just want to write the actual one byte value 0x63 which happens to represent number 99. Thanks for your time.
`fwrite()` takes strings. Try `chr(0x63)` if you want to write a `0x63` byte to the file.
77,582
<p>I am looking for a tool for regression testing a suite of equipment we are building.</p> <p>The current concept is that you create an input file (text/csv) to the tool specifying inputs to the system under test. The tool then captures the outputs from the system and records the inputs and outputs to an output file. </p> <p>The output is in the same format as the original input file and can be used as an input for following runs of the tool, with the measured outputs matched with the values from the previous run. </p> <p>The results of two runs will not be exact matches, there are some timing differences that depend on the state of the battery, or which depend on other internal state of the equipment.</p> <p>We would have to write our own interfaces to pass the commands from the tool to the equipment and to capture the output of the equipment.</p> <p>This is a relatively simple task, but I am looking for an existing tool / package / library to avoid re-inventing the wheel / steal lessons from.</p>
[ { "answer_id": 77684, "author": "apenwarr", "author_id": 42219, "author_profile": "https://Stackoverflow.com/users/42219", "pm_score": 0, "selected": false, "text": "<p>You can just use any test framework. The hard part is writing the tools to send/retrieve the data from your test syste...
2008/09/16
[ "https://Stackoverflow.com/questions/77582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13923/" ]
I am looking for a tool for regression testing a suite of equipment we are building. The current concept is that you create an input file (text/csv) to the tool specifying inputs to the system under test. The tool then captures the outputs from the system and records the inputs and outputs to an output file. The output is in the same format as the original input file and can be used as an input for following runs of the tool, with the measured outputs matched with the values from the previous run. The results of two runs will not be exact matches, there are some timing differences that depend on the state of the battery, or which depend on other internal state of the equipment. We would have to write our own interfaces to pass the commands from the tool to the equipment and to capture the output of the equipment. This is a relatively simple task, but I am looking for an existing tool / package / library to avoid re-inventing the wheel / steal lessons from.
I recently built a system like this on top of git (<http://git.or.cz/>). Basically, write a program that takes all your input files, sends them to the server, reads the output back, and writes it to a set of output files. After the first run, commit the output files to git. For future runs, your success is determined by whether the git repository is clean after the run finishes: ``` test 0 == $(git diff data/output/ | wc -l) ``` As a bonus, you can use all the git tools to compare differences, and commit them if it turns out the differences were an improvement, so that future runs will pass. It also works great when merging between branches.
77,659
<p>I have a .NET <strong>2.0</strong> WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx" rel="noreferrer">MSDN article</a> doesn't mention this, however. I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of.</p> <p>Anyone have any experience using one of these and successfully blocking <strong>all</strong> dialogs, script errors, etc?</p> <p><strong>EDIT</strong></p> <p>This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, <strong>AxSHDocVW</strong>?</p> <p><strong>EDIT again</strong></p> <p>Sorry I forgot to mention this... I'm trying to block a <strong>JavaScript alert()</strong>, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?</p>
[ { "answer_id": 98543, "author": "William", "author_id": 14829, "author_profile": "https://Stackoverflow.com/users/14829", "pm_score": 0, "selected": false, "text": "<p>Are you trying to implement a web robot? I have little experience in using the hosted IE control but I did completed a f...
2008/09/16
[ "https://Stackoverflow.com/questions/77659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13791/" ]
I have a .NET **2.0** WebBrowser control used to navigate some pages with no user interaction (don't ask...long story). Because of the user-less nature of this application, I have set the WebBrowser control's ScriptErrorsSuppressed property to true, which the documentation included with VS 2005 states will [...]"hide all its dialog boxes that originate from the underlying ActiveX control, not just script errors." The [MSDN article](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.scripterrorssuppressed(VS.80).aspx) doesn't mention this, however. I have managed to cancel the NewWindow event, which prevents popups, so that's taken care of. Anyone have any experience using one of these and successfully blocking **all** dialogs, script errors, etc? **EDIT** This isn't a standalone instance of IE, but an instance of a WebBrowser control living on a Windows Form application. Anyone have any experience with this control, or the underlying one, **AxSHDocVW**? **EDIT again** Sorry I forgot to mention this... I'm trying to block a **JavaScript alert()**, with just an OK button. Maybe I can cast into an IHTMLDocument2 object and access the scripts that way, I've used MSHTML a little bit, anyone know?
This is most definitely hacky, but if you do any work with the WebBrowser control, you'll find yourself doing a lot of hacky stuff. This is the easiest way that I know of to do this. You need to inject JavaScript to override the alert function... something along the lines of injecting this JavaScript function: ``` window.alert = function () { } ``` There are *many ways to do this*, but it is very possible to do. One possibility is to hook an implementation of the [DWebBrowserEvents2](http://msdn.microsoft.com/en-us/library/aa768283.aspx) interface. Once this is done, you can then plug into the NavigateComplete, the DownloadComplete, or the DocumentComplete (or, as we do, some variation thereof) and then call an InjectJavaScript method that you've implemented that performs this overriding of the window.alert method. Like I said, hacky, but it works :) I can go into more details if I need to.
77,683
<p>For example, <a href="http://reductiotest.org/" rel="nofollow noreferrer">Reductio</a> (for Java/Scala) and <a href="http://www.cs.chalmers.se/~rjmh/QuickCheck/" rel="nofollow noreferrer">QuickCheck</a> (for Haskell). The kind of framework I'm thinking of would provide "generators" for built-in data types and allow the programmer to define new generators. Then, the programmer would define a test method that asserts some property, taking variables of the appropriate types as parameters. The framework then generates a bunch of random data for the parameters, and runs hundreds of tests of that method.</p> <p>For example, if I implemented a Vector class, and it had an add() method, I might want to check that my addition commutes. So I would write something like (in pseudocode):</p> <pre><code>boolean testAddCommutes(Vector v1, Vector v2) { return v1.add(v2).equals(v2.add(v1)); } </code></pre> <p>I could run testAddCommutes() on two particular vectors to see if that addition commutes. But instead of writing a few invocations of testAddCommutes, I write a procedure than generates arbitrary Vectors. Given this, the framework can run testAddCommutes on hundreds of different inputs.</p> <p>Does this ring a bell for anyone?</p>
[ { "answer_id": 77720, "author": "Adam Driscoll", "author_id": 13688, "author_profile": "https://Stackoverflow.com/users/13688", "pm_score": -1, "selected": false, "text": "<p>I might not understand you correctly but check this out...</p>\n\n<p><a href=\"http://www.ayende.com/projects/rhi...
2008/09/16
[ "https://Stackoverflow.com/questions/77683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14113/" ]
For example, [Reductio](http://reductiotest.org/) (for Java/Scala) and [QuickCheck](http://www.cs.chalmers.se/~rjmh/QuickCheck/) (for Haskell). The kind of framework I'm thinking of would provide "generators" for built-in data types and allow the programmer to define new generators. Then, the programmer would define a test method that asserts some property, taking variables of the appropriate types as parameters. The framework then generates a bunch of random data for the parameters, and runs hundreds of tests of that method. For example, if I implemented a Vector class, and it had an add() method, I might want to check that my addition commutes. So I would write something like (in pseudocode): ``` boolean testAddCommutes(Vector v1, Vector v2) { return v1.add(v2).equals(v2.add(v1)); } ``` I could run testAddCommutes() on two particular vectors to see if that addition commutes. But instead of writing a few invocations of testAddCommutes, I write a procedure than generates arbitrary Vectors. Given this, the framework can run testAddCommutes on hundreds of different inputs. Does this ring a bell for anyone?
There's FsCheck, a port from QuickCheck to F# and thus C#, although most of the doc seems to be for f#. I've been exploring the ideas myself aswell. see : <http://kilfour.wordpress.com/2009/08/02/testing-tool-tour-quicknet-preview/>
77,695
<p>What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?</p>
[ { "answer_id": 77722, "author": "mopoke", "author_id": 14054, "author_profile": "https://Stackoverflow.com/users/14054", "pm_score": 2, "selected": false, "text": "<p>Try <a href=\"http://search.cpan.org/perldoc/CPAN::Mini\" rel=\"nofollow noreferrer\">CPAN::Mini</a>.</p>\n" }, { ...
2008/09/16
[ "https://Stackoverflow.com/questions/77695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9532/" ]
What do I need to set up and maintain a local CPAN mirror? What scripts and best practices should I be aware of?
[CPAN::Mini](http://search.cpan.org/perldoc?CPAN::Mini) is the way to go. Once you've mirrored CPAN locally, you'll want to set your mirror URL in CPAN.pm or CPANPLUS to the local directory using a "file:" URL like this: ``` file:///path/to/my/cpan/mirror ``` If you'd like your mirror to have copies of development versions of CPAN distribution, you can use [CPAN::Mini::Devel](http://search.cpan.org/perldoc?CPAN::Mini::Devel). Update: The ["What do I need to mirror CPAN?"](http://www.cpan.org/misc/cpan-faq.html#How_mirror_CPAN) FAQ given in another answer is for mirroring *all* of CPAN, usually to provide another public mirror. That includes old, outdated versions of distributions. CPAN::Mini just mirrors the latest versions. This is much smaller and for most users is generally what people would use for local or disconnected (laptop) access to CPAN.
77,718
<p>Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading?</p> <p>Isn't <code>Complex a, b, c; a = b + c;</code> much simpler than <code>Complex a, b, c; a = b.add(c);</code>?</p> <p>Is there a known reason for this, valid arguments for <em>not</em> allowing operator overloading? Is the reason arbitrary, or lost to time?</p>
[ { "answer_id": 77738, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "<p>Well you can really shoot yourself in the foot with operator overloading. It's like with pointers people make stupid ...
2008/09/16
[ "https://Stackoverflow.com/questions/77718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Coming from C++ to Java, the obvious unanswered question is why didn't Java include operator overloading? Isn't `Complex a, b, c; a = b + c;` much simpler than `Complex a, b, c; a = b.add(c);`? Is there a known reason for this, valid arguments for *not* allowing operator overloading? Is the reason arbitrary, or lost to time?
Assuming you wanted to overwrite the previous value of the object referred to by `a`, then a member function would have to be invoked. ``` Complex a, b, c; // ... a = b.add(c); ``` In C++, this expression tells the compiler to create three (3) objects on the stack, perform addition, and *copy* the resultant value from the temporary object into the existing object `a`. However, in Java, `operator=` doesn't perform value copy for reference types, and users can only create new reference types, not value types. So for a user-defined type named `Complex`, assignment means to copy a reference to an existing value. Consider instead: ``` b.set(1, 0); // initialize to real number '1' a = b; b.set(2, 0); assert( !a.equals(b) ); // this assertion will fail ``` In C++, this copies the value, so the comparison will result not-equal. In Java, `operator=` performs reference copy, so `a` and `b` are now referring to the same value. As a result, the comparison will produce 'equal', since the object will compare equal to itself. The difference between copies and references only adds to the confusion of operator overloading. As @Sebastian mentioned, Java and C# both have to deal with value and reference equality separately -- `operator+` would likely deal with values and objects, but `operator=` is already implemented to deal with references. In C++, you should only be dealing with one kind of comparison at a time, so it can be less confusing. For example, on `Complex`, `operator=` and `operator==` are both working on values -- copying values and comparing values respectively.
77,744
<p>I have a command line program, which outputs logging to the screen.</p> <p>I want error lines to show up in red. Is there some special character codes I can output to switch the text color to red, then switch it back to white?</p> <p>I'm using ruby but I imagine this would be the same in any other language.</p> <p>Something like:</p> <pre><code>red = "\0123" # character code white = "\0223" print "#{red} ERROR: IT BROKE #{white}" print "other stuff" </code></pre>
[ { "answer_id": 77795, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>As far as I know it is not possible with a command line, it is just one color...</p>\n" }, { "answer_id"...
2008/09/16
[ "https://Stackoverflow.com/questions/77744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
I have a command line program, which outputs logging to the screen. I want error lines to show up in red. Is there some special character codes I can output to switch the text color to red, then switch it back to white? I'm using ruby but I imagine this would be the same in any other language. Something like: ``` red = "\0123" # character code white = "\0223" print "#{red} ERROR: IT BROKE #{white}" print "other stuff" ```
You need to access the [Win32 Console API](https://learn.microsoft.com/en-us/windows/console/console-functions). Unfortunately, I don't know how you'd do that from Ruby. In Perl, I'd use the [Win32::Console](http://search.cpan.org/perldoc?Win32::Console) module. The Windows console does not respond to ANSI escape codes. According to the [article on colorizing Ruby output](http://kpumuk.info/ruby-on-rails/colorizing-console-ruby-script-output/) that artur02 mentioned, you need to install & load the win32console gem.
77,748
<p>We have a server with 10 running mongrel_cluster instances with apache in front of them, and every now and then one or some of them hang. No activity is seen in the database (we're using activerecord sessions). Mysql with innodb tables. show innodb status shows no locks. show processlist shows nothing.</p> <p>The server is linux debian 4.0</p> <p>Ruby is: ruby 1.8.6 (2008-03-03 patchlevel 114) [i486-linux]</p> <p>Rails is: Rails 1.1.2 (yes, quite old)</p> <p>We're using the native mysql connector (gem install mysql)</p> <p>"strace -p PID" gives the following in a loop for the hung mongrel process:</p> <pre><code>gettimeofday({1219834026, 235289}, NULL) = 0 select(4, [3], [0], [], {0, 905241}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235477}, NULL) = 0 select(4, [3], [0], [], {0, 905053}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235654}, NULL) = 0 select(4, [3], [0], [], {0, 904875}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235829}, NULL) = 0 select(4, [3], [0], [], {0, 904700}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236017}, NULL) = 0 select(4, [3], [0], [], {0, 904513}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236192}, NULL) = 0 select(4, [3], [0], [], {0, 904338}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236367}, NULL) = 0 ... </code></pre> <p>I used lsof and found that the process used 67 file descriptors (lsof -p PID |wc -l)</p> <p>Is there any other way I can debug this, so that I could for example determine which file descriptor is "bad"? Any other info or suggestions? Anybody else seen this?</p> <p>The site is fairly used, but not overly so, load averages usually around 0.3.</p> <hr> <p>Some additional info. I installed mongrelproctitle to show what the hung processes were doing, and it seems they are hanging on a method that displays images using file_column / images from the database / rmagick to resize and make the images greyscale. </p> <p>Not conclusive the problem is here, but it is a suspicion. Is there something obviously wrong with the following? The method displays a static image if the order doesn't contain an image, else the image resized from the order. The cache stuff is so that the image gets updated in the browser every time. The image is inserted in the page with a normal image tag.</p> <p>code:</p> <pre><code> def preview_image @order = session[:order] if @order.image.nil? @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(EMPTY_PIC.to_blob, :filename =&gt; "img.jpg", :type =&gt; "image/jpeg", :disposition =&gt; "inline") else @pic = Image.read(@order.image)[0] if (@order.crop) @pic.crop!(@order.crop[:x1].to_i, @order.crop[:y1].to_i, @order.crop[:width].to_i, @order.crop[:height].to_i, true) end @pic.resize!(103,130) @pic = @pic.quantize(256, Magick::GRAYColorspace) @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(@pic.to_blob, :filename =&gt; "img.jpg", :type =&gt; "image/jpeg", :disposition =&gt; "inline") end end </code></pre> <p>Here is the lsof output if anybody can find any problems in it. Don't know how it will format in this message...</p> <pre><code>lsof: WARNING: can't stat() ext3 file system /dev/.static/dev Output information may be incomplete. COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME mongrel_r 11628 username cwd DIR 9,2 4096 1870688 /home/domains/example.com/usernameOrder/releases/20080831121802 mongrel_r 11628 username rtd DIR 9,1 4096 2 / mongrel_r 11628 username txt REG 9,1 3564 167172 /usr/bin/ruby1.8 mongrel_r 11628 username mem REG 0,0 0 [heap] (stat: No such file or directory) mongrel_r 11628 username DEL REG 0,8 15560245 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560242 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560602 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560601 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560684 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560683 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560685 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560568 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560607 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560569 /dev/zero mongrel_r 11628 username mem REG 9,1 1933648 456972 /usr/lib/libmysqlclient.so.15.0.0 mongrel_r 11628 username DEL REG 0,8 15442414 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560546 /dev/zero mongrel_r 11628 username mem REG 9,1 67408 457393 /lib/i686/cmov/libresolv-2.7.so mongrel_r 11628 username mem REG 9,1 17884 457386 /lib/i686/cmov/libnss_dns-2.7.so mongrel_r 11628 username DEL REG 0,8 15560541 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560246 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560693 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560608 /dev/zero mongrel_r 11628 username mem REG 9,1 25700 164963 /usr/lib/gconv/gconv-modules.cache mongrel_r 11628 username mem REG 9,1 83708 457384 /lib/i686/cmov/libnsl-2.7.so mongrel_r 11628 username mem REG 9,1 140602 506903 /var/lib/gems/1.8/gems/mysql-2.7/lib/mysql.so mongrel_r 11628 username mem REG 9,1 1282816 180935 ... mongrel_r 11628 username 1w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 2w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 3u IPv4 15442350 TCP localhost:8001 (LISTEN) mongrel_r 11628 username 4w REG 9,2 118943548 1575355 /home/domains/example.com/usernameOrder/shared/log/production.log mongrel_r 11628 username 5u REG 9,1 145306 234226 /tmp/mongrel.11628.0 (deleted) mongrel_r 11628 username 7u unix 0xc3c12480 15442417 socket mongrel_r 11628 username 11u REG 9,1 50 234180 /tmp/CGI.11628.2 mongrel_r 11628 username 12u REG 9,1 26228 234227 /tmp/CGI.11628.3 </code></pre> <p>I have installed monit to monitor the server. No automatic restarts yet because of the PID file issue, but maybe I will get the newest version which supports deleting stale PID-files.<br> It would be nice though to actually fix the problem, because somebody will get disconnects etc if the server need to be restarted all the time (~10 times a day)</p> <p>The mongrel-processes don't take any large amount of memory when this is happening, and the machine isn't even swapping, so it's probably not a memory leak. </p> <pre><code> total used free shared buffers cached Mem: 4152796 4083000 69796 0 616624 2613364 -/+ buffers/cache: 853012 3299784 Swap: 1999992 52 1999940 </code></pre>
[ { "answer_id": 78044, "author": "sean lynch", "author_id": 14232, "author_profile": "https://Stackoverflow.com/users/14232", "pm_score": 1, "selected": false, "text": "<p>Chapter 6.3 in the book Deploying Rails Applications (A Step by Step Guide) has a good section on installing and conf...
2008/09/16
[ "https://Stackoverflow.com/questions/77748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13709/" ]
We have a server with 10 running mongrel\_cluster instances with apache in front of them, and every now and then one or some of them hang. No activity is seen in the database (we're using activerecord sessions). Mysql with innodb tables. show innodb status shows no locks. show processlist shows nothing. The server is linux debian 4.0 Ruby is: ruby 1.8.6 (2008-03-03 patchlevel 114) [i486-linux] Rails is: Rails 1.1.2 (yes, quite old) We're using the native mysql connector (gem install mysql) "strace -p PID" gives the following in a loop for the hung mongrel process: ``` gettimeofday({1219834026, 235289}, NULL) = 0 select(4, [3], [0], [], {0, 905241}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235477}, NULL) = 0 select(4, [3], [0], [], {0, 905053}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235654}, NULL) = 0 select(4, [3], [0], [], {0, 904875}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 235829}, NULL) = 0 select(4, [3], [0], [], {0, 904700}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236017}, NULL) = 0 select(4, [3], [0], [], {0, 904513}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236192}, NULL) = 0 select(4, [3], [0], [], {0, 904338}) = -1 EBADF (Bad file descriptor) gettimeofday({1219834026, 236367}, NULL) = 0 ... ``` I used lsof and found that the process used 67 file descriptors (lsof -p PID |wc -l) Is there any other way I can debug this, so that I could for example determine which file descriptor is "bad"? Any other info or suggestions? Anybody else seen this? The site is fairly used, but not overly so, load averages usually around 0.3. --- Some additional info. I installed mongrelproctitle to show what the hung processes were doing, and it seems they are hanging on a method that displays images using file\_column / images from the database / rmagick to resize and make the images greyscale. Not conclusive the problem is here, but it is a suspicion. Is there something obviously wrong with the following? The method displays a static image if the order doesn't contain an image, else the image resized from the order. The cache stuff is so that the image gets updated in the browser every time. The image is inserted in the page with a normal image tag. code: ``` def preview_image @order = session[:order] if @order.image.nil? @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(EMPTY_PIC.to_blob, :filename => "img.jpg", :type => "image/jpeg", :disposition => "inline") else @pic = Image.read(@order.image)[0] if (@order.crop) @pic.crop!(@order.crop[:x1].to_i, @order.crop[:y1].to_i, @order.crop[:width].to_i, @order.crop[:height].to_i, true) end @pic.resize!(103,130) @pic = @pic.quantize(256, Magick::GRAYColorspace) @headers['Pragma'] = 'no-cache' @headers['Cache-Control'] = 'no-cache, must-revalidate' send_data(@pic.to_blob, :filename => "img.jpg", :type => "image/jpeg", :disposition => "inline") end end ``` Here is the lsof output if anybody can find any problems in it. Don't know how it will format in this message... ``` lsof: WARNING: can't stat() ext3 file system /dev/.static/dev Output information may be incomplete. COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME mongrel_r 11628 username cwd DIR 9,2 4096 1870688 /home/domains/example.com/usernameOrder/releases/20080831121802 mongrel_r 11628 username rtd DIR 9,1 4096 2 / mongrel_r 11628 username txt REG 9,1 3564 167172 /usr/bin/ruby1.8 mongrel_r 11628 username mem REG 0,0 0 [heap] (stat: No such file or directory) mongrel_r 11628 username DEL REG 0,8 15560245 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560242 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560602 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560601 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560684 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560683 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560685 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560568 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560607 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560569 /dev/zero mongrel_r 11628 username mem REG 9,1 1933648 456972 /usr/lib/libmysqlclient.so.15.0.0 mongrel_r 11628 username DEL REG 0,8 15442414 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560546 /dev/zero mongrel_r 11628 username mem REG 9,1 67408 457393 /lib/i686/cmov/libresolv-2.7.so mongrel_r 11628 username mem REG 9,1 17884 457386 /lib/i686/cmov/libnss_dns-2.7.so mongrel_r 11628 username DEL REG 0,8 15560541 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560246 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560693 /dev/zero mongrel_r 11628 username DEL REG 0,8 15560608 /dev/zero mongrel_r 11628 username mem REG 9,1 25700 164963 /usr/lib/gconv/gconv-modules.cache mongrel_r 11628 username mem REG 9,1 83708 457384 /lib/i686/cmov/libnsl-2.7.so mongrel_r 11628 username mem REG 9,1 140602 506903 /var/lib/gems/1.8/gems/mysql-2.7/lib/mysql.so mongrel_r 11628 username mem REG 9,1 1282816 180935 ... mongrel_r 11628 username 1w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 2w REG 9,2 462923 1575329 /home/domains/example.com/usernameOrder/shared/log/mongrel.8001.log mongrel_r 11628 username 3u IPv4 15442350 TCP localhost:8001 (LISTEN) mongrel_r 11628 username 4w REG 9,2 118943548 1575355 /home/domains/example.com/usernameOrder/shared/log/production.log mongrel_r 11628 username 5u REG 9,1 145306 234226 /tmp/mongrel.11628.0 (deleted) mongrel_r 11628 username 7u unix 0xc3c12480 15442417 socket mongrel_r 11628 username 11u REG 9,1 50 234180 /tmp/CGI.11628.2 mongrel_r 11628 username 12u REG 9,1 26228 234227 /tmp/CGI.11628.3 ``` I have installed monit to monitor the server. No automatic restarts yet because of the PID file issue, but maybe I will get the newest version which supports deleting stale PID-files. It would be nice though to actually fix the problem, because somebody will get disconnects etc if the server need to be restarted all the time (~10 times a day) The mongrel-processes don't take any large amount of memory when this is happening, and the machine isn't even swapping, so it's probably not a memory leak. ``` total used free shared buffers cached Mem: 4152796 4083000 69796 0 616624 2613364 -/+ buffers/cache: 853012 3299784 Swap: 1999992 52 1999940 ```
Consider using [ImageScience](http://seattlerb.rubyforge.org/ImageScience.html), RMagick is known to leak massive amounts of memory and lock.
77,813
<p>Does anyone have any pointers on how to read the Windows EventLog without using JNI? Or if you <em>have to</em> use JNI, are there any good open-source libraries for doing so?</p>
[ { "answer_id": 78015, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://bloggingabout.net/blogs/wellink/archive/2005/04/08/3289.aspx\" rel=\"nofollow noreferrer\">http://blogg...
2008/09/16
[ "https://Stackoverflow.com/questions/77813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693/" ]
Does anyone have any pointers on how to read the Windows EventLog without using JNI? Or if you *have to* use JNI, are there any good open-source libraries for doing so?
JNA 3.2.8 has both an implementation for all event logging functions and a Java iterator. Read [this](http://code.dblock.org/ShowPost.aspx?id=125). ``` EventLogIterator iter = new EventLogIterator("Application"); while(iter.hasNext()) { EventLogRecord record = iter.next(); System.out.println(record.getRecordId() + ": Event ID: " + record.getEventId() + ", Event Type: " + record.getType() + ", Event Source: " + record.getSource()); } ```
77,826
<p>One thing I've started doing more often recently is <strong>retrieving some data</strong> at the beginning of a task <strong>and storing it in a $_SESSION['myDataForTheTask']</strong>. </p> <p>Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is regularly done by programmers with more expertise or is it more of an amateur thing to do?</p> <p><strong>For example:</strong></p> <pre><code>if (!isset($_SESSION['dataentry'])) { $query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']); $result_taskinfo = $db-&gt;query($query_taskinfo); $row_taskinfo = $result_taskinfo-&gt;fetch_row(); $dataentry = array("pcode" =&gt; $row_taskinfo[0], "modules" =&gt; $row_taskinfo[1], "data_id" =&gt; 0, "wavenum" =&gt; $row_taskinfo[2], "prequest" =&gt; FALSE, "highlight" =&gt; array()); $_SESSION['dataentry'] = $dataentry; } </code></pre>
[ { "answer_id": 77846, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 1, "selected": false, "text": "<p>$_SESSION items are stored in the session, which is, by default, kept on disk. There is no need to make your own array an...
2008/09/16
[ "https://Stackoverflow.com/questions/77826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11995/" ]
One thing I've started doing more often recently is **retrieving some data** at the beginning of a task **and storing it in a $\_SESSION['myDataForTheTask']**. Now it seems very convenient to do so but I don't know anything about performance, security risks or similar, using this approach. Is it something which is regularly done by programmers with more expertise or is it more of an amateur thing to do? **For example:** ``` if (!isset($_SESSION['dataentry'])) { $query_taskinfo = "SELECT participationcode, modulearray, wavenum FROM mng_wave WHERE wave_id=" . mysql_real_escape_string($_GET['wave_id']); $result_taskinfo = $db->query($query_taskinfo); $row_taskinfo = $result_taskinfo->fetch_row(); $dataentry = array("pcode" => $row_taskinfo[0], "modules" => $row_taskinfo[1], "data_id" => 0, "wavenum" => $row_taskinfo[2], "prequest" => FALSE, "highlight" => array()); $_SESSION['dataentry'] = $dataentry; } ```
Well Session variables are really one of the only ways (and probably the most efficient) of having these variables available for the entire time that visitor is on the website, there's no real way for a user to edit them (other than an exploit in your code, or in the PHP interpreter) so they are fairly secure. It's a good way of storing settings that can be changed by the user, as you can read the settings from database once at the beginning of a session and it is available for that entire session, you only need to make further database calls if the settings are changed and of course, as you show in your code, it's trivial to find out whether the settings already exist or whether they need to be extracted from database. I can't think of any other way of storing temporary variables securely (since cookies can easily be modified and this will be undesirable in most cases) so $\_SESSION would be the way to go
77,835
<p>I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script. </p> <p>My goal is to use phpunit with Selenium RC in CruiseControl &amp; phpUnderControl. This is what the test looks like:</p> <pre><code>require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; class WebTest extends PHPUnit_Extensions_SeleniumTestCase { protected function setUp() { $this-&gt;setBrowser('*firefox'); $this-&gt;setBrowserUrl('http://www.example.com/'); } public function testTitle() { $this-&gt;open('http://www.example.com/'); $this-&gt;assertTitleEquals('Example Web Page'); } } </code></pre> <p>I also got PEAR in the include_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem. </p> <p>Any help would be very much appreciated. </p> <p>Thanks, Remy</p>
[ { "answer_id": 77955, "author": "Ciaran", "author_id": 5048, "author_profile": "https://Stackoverflow.com/users/5048", "pm_score": 1, "selected": false, "text": "<p>Have a look at one of the comments in the require_once entry in the php manual..</p>\n\n<p><a href=\"http://ie.php.net/manu...
2008/09/16
[ "https://Stackoverflow.com/questions/77835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12645/" ]
I am trying to run a SeleniumTestCase with phpunit but I cannot get it to run with the phpunit.bat script. My goal is to use phpunit with Selenium RC in CruiseControl & phpUnderControl. This is what the test looks like: ``` require_once 'PHPUnit/Extensions/SeleniumTestCase.php'; class WebTest extends PHPUnit_Extensions_SeleniumTestCase { protected function setUp() { $this->setBrowser('*firefox'); $this->setBrowserUrl('http://www.example.com/'); } public function testTitle() { $this->open('http://www.example.com/'); $this->assertTitleEquals('Example Web Page'); } } ``` I also got PEAR in the include\_path and PHPUnit installed with the Selenium extension. I installed these with the pear installer so I guess that's not the problem. Any help would be very much appreciated. Thanks, Remy
hopefully this is a more definitive answer then the ones given here (which did not solve me problem). If you are getting this error, check your PEAR folder and see if the "SeleniumTestCase.php" file is actually there: ``` /PEAR/PHPUnit/Extensions/SeleniumTestCase.php ``` If it is NOT, the easiest thing to do is to uninstall and reinstall PHPUnit using PEAR ... ``` pear uninstall phpunit/PHPUnit pear uninstall phpunit/PHPUnit_Selenium pear install phpunit/PHPUnit ``` After doing the above and doing just the single install, PHPUnit\_Selenium was also auto installed, I'm not sure if this is typical, so some might have to do... ``` pear install phpunit/PHPUnit_Selenium ``` Also see <http://www.phpunit.de/manual/3.5/en/installation.html> for PEAR channel info if needed...
77,873
<p>Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files?</p>
[ { "answer_id": 77930, "author": "pix0r", "author_id": 72, "author_profile": "https://Stackoverflow.com/users/72", "pm_score": 1, "selected": false, "text": "<p>Looks like this has been <a href=\"https://stackoverflow.com/questions/7364/pdf-editing-in-php\">covered before</a>. Click thro...
2008/09/16
[ "https://Stackoverflow.com/questions/77873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14166/" ]
Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files?
The libraries and frameworks mentioned here are good, but if all you want to do is fill in a form and flatten it, I recommend the command line tool called pdftk (PDF Toolkit). See <https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/> You can call the command line from php, and the command is `pdftk` *formfile.pdf* `fill_form` *fieldinfo.fdf* `output` *outputfile.pdf* `flatten` You will need to find the format of an FDF file in order to generate the info to fill in the fields. Here's a good link for that: <http://www.tgreer.com/fdfServe.html> [Edit: The above link seems to be out of commission. Here is some more info...] The pdftk command can generate an FDF file from a PDF form file. You can then use the generated FDF file as a sample. The form fields are the portion of the FDF file that looks like ``` ... << /T(f1-1) /V(text of field) >> << /T(f1-2) /V(text of another field) >> ... ``` You might also check out [php-pdftk](https://github.com/mikehaertl/php-pdftk), which is a library specific to PHP. I have not used it, but commenter Álvaro (below) recommends it.
77,887
<p>As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul?</p> <p>ie (the only dump I have on hand with me actually)</p> <pre>>b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94 b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255 b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0 b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000</pre> <p>I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[</p>
[ { "answer_id": 77921, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "<p>It might help to include an example of the stack you are trying to read. A good tip is to ensure you have correct...
2008/09/16
[ "https://Stackoverflow.com/questions/77887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14173/" ]
As someone who is just starting to learn the intricacies of computer debugging, for the life of me, I can't understand how to read the Stack Text of a dump in Windbg. I've no idea of where to start on how to interpret them or how to go about it. Can anyone offer direction to this poor soul? ie (the only dump I have on hand with me actually) ``` >b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94 b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255 b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0 b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000 ``` I know the problem is to do with the Nvidia display driver, but what I want to know is how to actually read the stack (eg, what is b69dd8f4?) :-[
First, you need to have the proper symbols configured. The symbols will allow you to match memory addresses to function names. In order to do this you have to create a local folder in your machine in which you will store a local cache of symbols (for example: C:\symbols). Then you need to specify the symbols server path. To do this just go to: File > Symbol File Path and type: ``` SRV*c:\symbols*http://msdl.microsoft.com/download/symbols ``` You can find more information on how to correctly configure the symbols [here](http://www.microsoft.com/whdc/devtools/debugging/debugstart.mspx#a). Once you have properly configured the Symbols server you can open the minidump from: File > Open Crash Dump. Once the minidump is opened it will show you on the left side of the command line the thread that was executing when the dump was generated. If you want to see what this thread was executing type: ``` kpn 200 ``` This might take some time the first you execute it since it has to download the necessary public Microsoft related symbols the first time. Once all the symbols are downloaded you'll get something like: ``` 01 MODULE!CLASS.FUNCTIONNAME1(...) 02 MODULE!CLASS.FUNCTIONNAME2(...) 03 MODULE!CLASS.FUNCTIONNAME3(...) 04 MODULE!CLASS.FUNCTIONNAME4(...) ``` Where: * **THE FIRST NUMBER**: Indicates the frame number * **MODULE**: The DLL that contains the code * **CLASS**: (Only on C++ code) will show you the class that contains the code * **FUNCTIONAME**: The method that was called. If you have the correct symbols you will also see the parameters. You might also see something like ``` 01 MODULE!+989823 ``` This indicates that you don't have the proper Symbol for this DLL and therefore you are only able to see the method offset. So, what is a callstack? Imagine you have this code: ``` void main() { method1(); } void method1() { method2(); } int method2() { return 20/0; } ``` In this code method2 basically will throw an Exception since we are trying to divide by 0 and this will cause the process to crash. If we got a minidump when this occurred we would see the following callstack: ``` 01 MYDLL!method2() 02 MYDLL!method1() 03 MYDLL!main() ``` You can follow from this callstack that "main" called "method1" that then called "method2" and it failed. In your case you've got this callstack (which I guess is the result of running "kb" command) ``` b69dd8f0 bfa1e255 016d2fc0 89efc000 00000040 nv4_disp+0x48b94 b69dd8f4 016d2fc0 89efc000 00000040 00000006 nv4_disp+0x49255 b69dd8f8 89efc000 00000040 00000006 bfa1dcc0 0x16d2fc0 b69dd8fc 00000000 00000006 bfa1dcc0 e1e71018 0x89efc000 ``` The first column indicates the Child Frame Pointer, the second column indicates the Return address of the method that is executing, the next three columns show the first 3 parameters that were passed to the method, and the last part is the DLL name (nv4\_disp) and the offset of the method that is being executed (+0x48b94). Since you don't have the symbols you are not able to see the method name. I doubt tha NVIDIA offers public access to their symbols so I gues you can't get much information from here. I recommend you run "kpn 200". This will show you the full callstack and you might be able to see the origin of the method that caused this crash (if it was a Microsoft DLL you should have the proper symbols in the steps that I provided you). At least you know it's related to a NVIDIA bug ;-) Try upgrading the DLLs of this driver to the latest version. In case you want to learn more about WinDBG debugging I recommend the following links: * [If broken it is, fix it you should](http://blogs.msdn.com/tess/default.aspx) * [TechNet Webcast: Windows Hang and Crash Dump Analysis](http://www.microsoft.com/events/EventDetails.aspx?CMTYSvcSource=MSCOMMedia&Params=~CMTYDataSvcParams%5E~arg+Name%3D%22ID%22+Value%3D%221032298076%22%2F%5E~arg+Name%3D%22ProviderID%22+Value%3D%22A6B43178-497C-4225-BA42-DF595171F04C%22%2F%5E~arg+Name%3D%22lang%22+Value%3D%22en%22%2F%5E~arg+Name%3D%22cr%22+Value%3D%22US%22%2F%5E~sParams%5E~%2FsParams%5E~%2FCMTYDataSvcParams%5E) * [Delicious.com popular links on WinDBG](http://delicious.com/popular/windbg)
77,890
<p>I am writing some code to see if there is a hole in the firewall exception list for <strong>WinXP</strong> and <strong>Vista</strong> for a specific port used by our client software. </p> <p>I can see that I can use the <code>NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts</code> to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. </p> <p>My latest try is listed below. It's giving me an access violation when I use <code>port_list.Item</code>. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated.</p> <pre><code>function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; var i, h: integer; port_list, port: OleVariant; begin Result := False; port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts; for i := 0 to port_list.Count - 1 do begin port := port_list.Item[i]; if (port.PortNumber = iPortNumber) then begin Result := True; break; end; end; end; </code></pre>
[ { "answer_id": 78144, "author": "Jim McKeeth", "author_id": 255, "author_profile": "https://Stackoverflow.com/users/255", "pm_score": 0, "selected": false, "text": "<p>Without setting up an application to test with, I'll suggest the following. Let me know if it works.</p>\n\n<p>I looked...
2008/09/16
[ "https://Stackoverflow.com/questions/77890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12425/" ]
I am writing some code to see if there is a hole in the firewall exception list for **WinXP** and **Vista** for a specific port used by our client software. I can see that I can use the `NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts` to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. My latest try is listed below. It's giving me an access violation when I use `port_list.Item`. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated. ``` function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; var i, h: integer; port_list, port: OleVariant; begin Result := False; port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts; for i := 0 to port_list.Count - 1 do begin port := port_list.Item[i]; if (port.PortNumber = iPortNumber) then begin Result := True; break; end; end; end; ```
OK, I think that I have it figured out. I had to create a type library file of the hnetcfg.dll. I did that when I first started but have learned a lot about the firewall objects since then. It didn't work then, but its working now. You can create your own file from Component|Import Component. And then follow the wizard. The wrapping code uses exceptions which I normally don't like to do, but I don't know how to tell whether an Interface that is returning an Interface is actually returning data that I can work off of... So that would be an improvement if somebody can point me in the right direction. And now to the code, with a thanks to Jim for his response. ``` constructor TFirewallUtility.Create; begin inherited Create; CoInitialize(nil); mxCurrentFirewallProfile := INetFwMgr(CreateOLEObject('HNetCfg.FwMgr')).LocalPolicy.CurrentProfile; end; function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; begin try Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Port = iPortNumber; except Result := False; end; end; function TFirewallUtility.IsPortEnabled(iPortNumber: integer): boolean; begin try Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Enabled; except Result := False; end; end; procedure TFirewallUtility.SetPortEnabled(iPortNumber: integer; sPortName: string; xProtocol: TFirewallPortProtocol); begin try mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, CFirewallPortProtocalConsts[xProtocol]).Enabled := True; except HaltIf(True, 'xFirewallManager.TFirewallUtility.IsPortEnabled: Port not in exception list.'); end; end; procedure TFirewallUtility.AddPortToFirewall(sPortName: string; iPortNumber: Cardinal; xProtocol: TFirewallPortProtocol); var port: INetFwOpenPort; begin port := INetFwOpenPort(CreateOLEObject('HNetCfg.FWOpenPort')); port.Name := sPortName; port.Protocol := CFirewallPortProtocalConsts[xProtocol]; port.Port := iPortNumber; port.Scope := NET_FW_SCOPE_ALL; port.Enabled := true; mxCurrentFirewallProfile.GloballyOpenPorts.Add(port); end; ```
77,900
<p>Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control.</p> <p>I think it would likely be a fairly simple routine, ie: </p> <pre><code>Dim ctlParent As Control = Me.txtTest.Parent Dim ctlOLD As TextBox = Me.txtTest Dim ctlNEW As Label = New Label ctlNEW.Width = ctlOLD.Width ctlNEW.Text = ctlOLD.Text ctlParent.Controls.Remove(ctlOLD) ctlParent.Controls.Add(ctlNEW) </code></pre> <p>...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations.</p> <p>Update:<br> - Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that. - Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid.</p> <p>Thanks!!</p>
[ { "answer_id": 77938, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 2, "selected": false, "text": "<p>You could use a multiview and just have a display view and an edit view.. then do your assignments as:</p>\n\n<...
2008/09/16
[ "https://Stackoverflow.com/questions/77900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]
Has anyone ever written a function that can convert all of the controls on an aspx page into a read only version? For example, if UserDetails.aspx is used to edit and save a users information, if someone with inappropriate permissions enter the page, I would like to render it as read-only. So, most controls would be converted to labels, loaded with the corresponding data from the editable original control. I think it would likely be a fairly simple routine, ie: ``` Dim ctlParent As Control = Me.txtTest.Parent Dim ctlOLD As TextBox = Me.txtTest Dim ctlNEW As Label = New Label ctlNEW.Width = ctlOLD.Width ctlNEW.Text = ctlOLD.Text ctlParent.Controls.Remove(ctlOLD) ctlParent.Controls.Add(ctlNEW) ``` ...is really all you need for a textbox --> label conversion, but I was hoping someone might know of an existing function out there as there are likely a few pitfalls here and there with certain controls and situations. Update: - Just setting the ReadOnly property to true is not a viable solution, as it looks dumb having things greyed out like that. - Avoiding manually creating a secondary view is the entire point of this, so using an ingenious way to display a read only version of the user interface that was built by hand using labels is wat I am trying to avoid. Thanks!!
You could use a multiview and just have a display view and an edit view.. then do your assignments as: ``` lblWhatever.Text = txtWhatever.Text = whateverOriginatingSource; lblSomethingElse.Text = txtSomethingElse.Text = somethingElseOriginatingSource; myViews.SelectedIndex = myConditionOrVariableThatDeterminesEditable ? 0 : 1; ``` then swap the views based on permissions. not the most elegant but will probably work for your situation. Maybe I should elaborate a little.. dismiss the psuedo (not sure if I have the selectedindex yada yada right.. but you get the point). ``` <asp:Multiview ID="myViews" SelectedIndex="1"> <asp:View ID="EditView"> <asp:TextBox ID="txtWhatever" /><br /> <asp:TextBox ID="txtSomethingElse" /> </asp:View> <asp:View ID="DisplayView"> <asp:Label ID="lblWhatever" /><br /> <asp:Label ID="lblSomethingElse" /> </asp:View> </asp:Multiview> ```
77,934
<p>I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?</p>
[ { "answer_id": 78937, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 2, "selected": false, "text": "<p>Tk does not natively support windows bitmap files. However, the \"Img\" extension does and is freely available on jus...
2008/09/16
[ "https://Stackoverflow.com/questions/77934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1994377/" ]
I have written code to read a windows bitmap and would now like to display it with ltk. How can I construct an appropriate object? Is there such functionality in ltk? If not how can I do it directly interfacing to tk?
It has been a while since I used LTK for anything, but the simplest way to display an image with LTK is as follows: ``` (defpackage #:ltk-image-example (:use #:cl #:ltk)) (in-package #:ltk-image-example) (defun image-example () (with-ltk () (let ((image (make-image))) (image-load image "testimage.gif") (let ((canvas (make-instance 'canvas))) (create-image canvas 0 0 :image image) (configure canvas :width 800) (configure canvas :height 640) (pack canvas))))) ``` Unfortunately what you can do with the image by default is fairly limited, and you can only use gif or ppm images - but the [ppm file format](http://en.wikipedia.org/wiki/Portable_pixmap) is very simple, you could easily create a ppm image from your bitmap. However you say you want to manipulate the displayed image, and looking at the code that defines the image object: ``` (defclass photo-image(tkobject) ((data :accessor data :initform nil :initarg :data) ) ) (defmethod widget-path ((photo photo-image)) (name photo)) (defmethod initialize-instance :after ((p photo-image) &key width height format grayscale data) (check-type data (or null string)) (setf (name p) (create-name)) (format-wish "image create photo ~A~@[ -width ~a~]~@[ -height ~a~]~@[ -format \"~a\"~]~@[ -grayscale~*~]~@[ -data ~s~]" (name p) width height format grayscale data)) (defun make-image () (let* ((name (create-name)) (i (make-instance 'photo-image :name name))) ;(create i) i)) (defgeneric image-load (p filename)) (defmethod image-load((p photo-image) filename) ;(format t "loading file ~a~&" filename) (send-wish (format nil "~A read {~A} -shrink" (name p) filename)) p) ``` It looks like the the actual data for the image is stored by the Tcl/Tk interpreter and not accessible from within lisp. If you wanted to access it you would probably need to write your own functions using **format-wish** and **send-wish**. Of course you could simply render each pixel individually on a canvas object, but I don't think you would get very good performance doing that, the canvas widget gets a bit slow once you are trying to display more than a few thousand different things on it. So to summarize - if you don't care about doing anything in real time, you could save your bitmap as a .ppm image every time you wanted to display it and then simply load it using the code above - that would be the easiest. Otherwise you could try to access the data from tk itself (after loading it once as a ppm image), finally if none of that works you could switch to another toolkit. Most of the decent lisp GUI toolkits are for linux, so you may be out of luck if you are using windows.
77,936
<p>As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in:</p> <pre><code>centroid = average(x), average(y), average(z) </code></pre> <p>where <code>x</code>, <code>y</code> and <code>z</code> are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.</p>
[ { "answer_id": 77978, "author": "deemer", "author_id": 11192, "author_profile": "https://Stackoverflow.com/users/11192", "pm_score": 4, "selected": false, "text": "<p>Nope, that is the only formula for the centroid of a collection of points. See Wikipedia: <a href=\"http://en.wikipedia....
2008/09/16
[ "https://Stackoverflow.com/questions/77936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/676/" ]
As part of a project at work I have to calculate the centroid of a set of points in 3D space. Right now I'm doing it in a way that seems simple but naive -- by taking the average of each set of points, as in: ``` centroid = average(x), average(y), average(z) ``` where `x`, `y` and `z` are arrays of floating-point numbers. I seem to recall that there is a way to get a more accurate centroid, but I haven't found a simple algorithm for doing so. Anyone have any ideas or suggestions? I'm using Python for this, but I can adapt examples from other languages.
Contrary to the common refrain here, there are different ways to define (and calculate) a center of a point cloud. The first and most common solution has been suggested by you already and I will **not** argue that there is anything wrong with this: `centroid = average(x), average(y), average(z)` The "problem" here is that it will "distort" your center-point depending on the distribution of your points. If, for example, you assume that all your points are within a cubic box or some other geometric shape, but most of them happen to be placed in the upper half, your center-point will also shift in that direction. As an alternative you could use the mathematical middle (the mean of the extrema) in each dimension to avoid this: `middle = middle(x), middle(y), middle(z)` You can use this when you don't care much about the number of points, but more about the global bounding box, because that's all this is - the center of the bounding box around your points. Lastly, you could also use the `median` (the element in the middle) in each dimension: `median = median(x), median(y), median(z)` Now this will sort of do the opposite to the `middle` and actually help you ignore outliers in your point cloud and find a centerpoint **based on** the distribution of your points. A more and robust way to find a "good" centerpoint might be to ignore the top and bottom 10% in each dimension and then calculate the `average` or `median`. As you can see you can define the centerpoint in different ways. Below I am showing you examples of 2 2D point clouds with these suggestions in mind. The dark blue dot is the average (mean) centroid. The median is shown in green. And the middle is shown in red. In the second image you will see exactly what I was talking about earlier: The green dot is "closer" to the densest part of the point cloud, while the red dot is further way from it, taking into account the most extreme boundaries of the point cloud. [![enter image description here](https://i.stack.imgur.com/8qSQA.png)](https://i.stack.imgur.com/8qSQA.png) [![enter image description here](https://i.stack.imgur.com/iZSSi.png)](https://i.stack.imgur.com/iZSSi.png)
77,954
<p>How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that <code>use strict;</code> isn't sufficient for this purpose.</p>
[ { "answer_id": 77969, "author": "Neil", "author_id": 14193, "author_profile": "https://Stackoverflow.com/users/14193", "pm_score": 2, "selected": false, "text": "<p>Include this:</p>\n\n<pre><code>use Carp ();\n</code></pre>\n\n<p>Then include <em>one</em> of these lines at the top of yo...
2008/09/16
[ "https://Stackoverflow.com/questions/77954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14193/" ]
How do you get Perl to stop and give a stack trace when you reference an undef value, rather than merely warning? It seems that `use strict;` isn't sufficient for this purpose.
``` use warnings FATAL => 'uninitialized'; use Carp (); $SIG{__DIE__} = \&Carp::confess; ``` The first line makes the warning fatal. The next two cause a stack trace when your program dies. See also `man 3pm warnings` for more details.
77,957
<p>I'm using Visual Studio 2008 for an ASP .Net application, and Visual Studio keeps adding blank lines to my aspx file whenever I save, switch to design mode and back to code view, switch to split mode, or switch between files. Before I save, I will have:</p> <pre><code> &lt;/ContentTemplate&gt;&lt;/asp:UpdatePanel&gt; &lt;/ContentTemplate&gt; &lt;/ajax:TabPanel&gt; &lt;/ajax:TabContainer&gt; </code></pre> <p>Then, it will magically transform into:</p> <pre><code> &lt;/ContentTemplate&gt;&lt;/asp:UpdatePanel&gt; &lt;/ContentTemplate&gt; &lt;/ajax:TabPanel&gt; &lt;/ajax:TabContainer&gt; </code></pre> <p>I know it's mostly an aesthetics issue, but it's also adding 17 lines of nothing to each tab container (and making the file that much longer to scroll through) and it's very annoying. I've checked that I don't have a misplaced quotation mark, there's no misaligned tags earlier in the file, any ideas?</p>
[ { "answer_id": 78486, "author": "LizB", "author_id": 13616, "author_profile": "https://Stackoverflow.com/users/13616", "pm_score": 0, "selected": false, "text": "<p>I can't say I've ever experience this with any Visual Studio yet, but try this</p>\n\n<p><strong>Ctrl-E, D</strong> command...
2008/09/16
[ "https://Stackoverflow.com/questions/77957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13208/" ]
I'm using Visual Studio 2008 for an ASP .Net application, and Visual Studio keeps adding blank lines to my aspx file whenever I save, switch to design mode and back to code view, switch to split mode, or switch between files. Before I save, I will have: ``` </ContentTemplate></asp:UpdatePanel> </ContentTemplate> </ajax:TabPanel> </ajax:TabContainer> ``` Then, it will magically transform into: ``` </ContentTemplate></asp:UpdatePanel> </ContentTemplate> </ajax:TabPanel> </ajax:TabContainer> ``` I know it's mostly an aesthetics issue, but it's also adding 17 lines of nothing to each tab container (and making the file that much longer to scroll through) and it's very annoying. I've checked that I don't have a misplaced quotation mark, there's no misaligned tags earlier in the file, any ideas?
The only time I've seen Visual Studio do something close to this is when the XML/HTML in question is invalid, for example you are missing a closing tag somewhere.
77,996
<p>Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)</p>
[ { "answer_id": 78013, "author": "epatel", "author_id": 842, "author_profile": "https://Stackoverflow.com/users/842", "pm_score": 1, "selected": false, "text": "<p>Think you should read a little about <a href=\"http://en.wikipedia.org/wiki/Design_pattern_(computer_science)\" rel=\"nofollo...
2008/09/16
[ "https://Stackoverflow.com/questions/77996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13790/" ]
Is it possible to create custom events in C++? For example, say I have the variable X, and the variable Y. Whenever X changes, I would like to execute a function that sets Y equal to 3X. Is there a way to create such a trigger/event? (triggers are common in some databases)
This is basically an instance of the Observer pattern (as others have mentioned and linked). However, you can use template magic to render it a little more syntactically palettable. Consider something like... ``` template <typename T> class Observable { T underlying; public: Observable<T>& operator=(const T &rhs) { underlying = rhs; fireObservers(); return *this; } operator T() { return underlying; } void addObserver(ObsType obs) { ... } void fireObservers() { /* Pass every event handler a const & to this instance /* } }; ``` Then you can write... ``` Observable<int> x; x.registerObserver(...); x = 5; int y = x; ``` What method you use to write your observer callback functions are entirely up to you; I suggest <http://www.boost.org>'s function or functional modules (you can also use simple functors). I also caution you to be careful about this type of operator overloading. Whilst it can make certain coding styles clearer, reckless use an render something like seemsLikeAnIntToMe = 10; a *very* expensive operation, that might well explode, and cause debugging nightmares for years to come.
78,053
<p>I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do:</p> <pre><code>Excel::HPageBreaksPtr pHPageBreaks = pSheet-&gt;GetHPageBreaks(); long count = pHPageBreaks-&gt;Count; for (long i=0; i &lt; count; ++i) { Excel::HPageBreakPtr pHPageBreak = pHPageBreaks-&gt;GetItem(i+1); Excel::RangePtr pLocation = pHPageBreak-&gt;GetLocation(); printf("Page break at row %d\n", pLocation-&gt;Row); pLocation.Release(); pHPageBreak.Release(); } pHPageBreaks.Release(); </code></pre> <p>I expect this to print out the row numbers of each of the horizontal page breaks in <code>pSheet</code>. The problem I'm having is that although <code>count</code> correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling <code>pHPageBreaks-&gt;GetItem(i)</code> throws an exception, with error number 0x8002000b, "invalid index".</p> <p>Attempting to use <code>pHPageBreaks-&gt;Get_NewEnum()</code> to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to <code>Get_NewEnum()</code>.</p> <p>I've looked around for a solution, and the closest thing I've found so far is <a href="http://support.microsoft.com/kb/210663/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/210663/en-us</a>. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help.</p> <p>If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome!</p> <p>Thank you.</p> <p>@Joel: Yes, I have tried displaying the user interface, and then setting <code>ScreenUpdating</code> to true - it produced the same results. Also, I have since tried combinations of setting <code>pSheet-&gt;PrintArea</code> to the entire worksheet and/or calling <code>pSheet-&gt;ResetAllPageBreaks()</code> before my call to get the <code>HPageBreaks</code> collection, which didn't help either.</p> <p>@Joel: I've used <code>pSheet-&gt;UsedRange</code> to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.</p>
[ { "answer_id": 78519, "author": "Joel Spolsky", "author_id": 4, "author_profile": "https://Stackoverflow.com/users/4", "pm_score": 0, "selected": false, "text": "<p>Did you set ScreenUpdating to True, as mentioned in the KB article?</p>\n\n<p>You may want to actually toggle it to True to...
2008/09/16
[ "https://Stackoverflow.com/questions/78053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14238/" ]
I've been trying to retrieve the locations of all the page breaks on a given Excel 2003 worksheet over COM. Here's an example of the kind of thing I'm trying to do: ``` Excel::HPageBreaksPtr pHPageBreaks = pSheet->GetHPageBreaks(); long count = pHPageBreaks->Count; for (long i=0; i < count; ++i) { Excel::HPageBreakPtr pHPageBreak = pHPageBreaks->GetItem(i+1); Excel::RangePtr pLocation = pHPageBreak->GetLocation(); printf("Page break at row %d\n", pLocation->Row); pLocation.Release(); pHPageBreak.Release(); } pHPageBreaks.Release(); ``` I expect this to print out the row numbers of each of the horizontal page breaks in `pSheet`. The problem I'm having is that although `count` correctly indicates the number of page breaks in the worksheet, I can only ever seem to retrieve the first one. On the second run through the loop, calling `pHPageBreaks->GetItem(i)` throws an exception, with error number 0x8002000b, "invalid index". Attempting to use `pHPageBreaks->Get_NewEnum()` to get an enumerator to iterate over the collection also fails with the same error, immediately on the call to `Get_NewEnum()`. I've looked around for a solution, and the closest thing I've found so far is <http://support.microsoft.com/kb/210663/en-us>. I have tried activating various cells beyond the page breaks, including the cells just beyond the range to be printed, as well as the lower-right cell (IV65536), but it didn't help. If somebody can tell me how to get Excel to return the locations of all of the page breaks in a sheet, that would be awesome! Thank you. @Joel: Yes, I have tried displaying the user interface, and then setting `ScreenUpdating` to true - it produced the same results. Also, I have since tried combinations of setting `pSheet->PrintArea` to the entire worksheet and/or calling `pSheet->ResetAllPageBreaks()` before my call to get the `HPageBreaks` collection, which didn't help either. @Joel: I've used `pSheet->UsedRange` to determine the row to scroll past, and Excel does scroll past all the horizontal breaks, but I'm still having the same issue when I try to access the second one. Unfortunately, switching to Excel 2007 did not help either.
Experimenting with Excel 2007 from Visual Basic, I discovered that the page break isn't known unless it has been displayed on the screen at least once. The best workaround I could find was to page down, from the top of the sheet to the last row containing data. Then you can enumerate all the page breaks. Here's the VBA code... let me know if you have any problem converting this to COM: ``` Range("A1").Select numRows = Range("A1").End(xlDown).Row While ActiveWindow.ScrollRow < numRows ActiveWindow.LargeScroll Down:=1 Wend For Each x In ActiveSheet.HPageBreaks Debug.Print x.Location.Row Next ``` This code made one simplifying assumption: * I used the .End(xlDown) method to figure out how far the data goes... this assumes that you have continuous data from A1 down to the bottom of the sheet. If you don't, you need to use some other method to figure out how far to keep scrolling.
78,064
<p>I've read this <a href="https://stackoverflow.com/questions/40122/exceptions-in-web-services">thread</a> for WCF has inbuilt Custom Fault codes and stuff.</p> <p>But what is the best practice for <em>ASP.Net</em> web services? Do I throw exceptions and let the client handle the exception or send an Error code (success, failure etc) that the client would rely upon to do its processing.</p> <p>Update: Just to discuss further in case of <em>SOAP</em>, let's say the client makes a <em>web svc</em> call which is supposed to be a notification message (no return value expected), so everything goes smooth and no exceptions are thrown by the svc. </p> <p>Now how will the client know if the notification call has gotten lost due to a communication/network problem or something in between the server and the client? compare this with not having any exception thrown. Client might assume it's a success. But it's not. The call got lost somewhere.</p> <p>Does send a 'success' error code ensures to the client that the call went smooth? is there any other way to achieve this or is the scenario above even possible?</p>
[ { "answer_id": 78171, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 1, "selected": false, "text": "<p>Depends on how you are going to consume the web service - i.e. which protocol are you going to use.</p>\n\n<p>If it ...
2008/09/16
[ "https://Stackoverflow.com/questions/78064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1747/" ]
I've read this [thread](https://stackoverflow.com/questions/40122/exceptions-in-web-services) for WCF has inbuilt Custom Fault codes and stuff. But what is the best practice for *ASP.Net* web services? Do I throw exceptions and let the client handle the exception or send an Error code (success, failure etc) that the client would rely upon to do its processing. Update: Just to discuss further in case of *SOAP*, let's say the client makes a *web svc* call which is supposed to be a notification message (no return value expected), so everything goes smooth and no exceptions are thrown by the svc. Now how will the client know if the notification call has gotten lost due to a communication/network problem or something in between the server and the client? compare this with not having any exception thrown. Client might assume it's a success. But it's not. The call got lost somewhere. Does send a 'success' error code ensures to the client that the call went smooth? is there any other way to achieve this or is the scenario above even possible?
Jeff Atwood posted [an interesting aerticle](http://www.codinghorror.com/blog/archives/000054.html) about this subject some time ago. Allthough a .NET exception is converted to a SoapFault, which is compatible with most other toolkits, the information in the faults isn't very good. Therefor, the conlusion of the article is that .NET webservices don't throw very good exception messages and you should add additional information: ``` Private Sub WebServiceExceptionHandler(ByVal ex As Exception) Dim ueh As New AspUnhandledExceptionHandler ueh.HandleException(ex) '-- Build the detail element of the SOAP fault. Dim doc As New System.Xml.XmlDocument Dim node As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _ SoapException.DetailElementName.Name, _ SoapException.DetailElementName.Namespace) '-- append our error detail string to the SOAP detail element Dim details As System.Xml.XmlNode = doc.CreateNode(XmlNodeType.Element, _ "ExceptionInfo", _ SoapException.DetailElementName.Namespace) details.InnerText = ueh.ExceptionToString(ex) node.AppendChild(details) '-- re-throw the exception so we can package additional info Throw New SoapException("Unhandled Exception: " & ex.Message, _ SoapException.ClientFaultCode, _ Context.Request.Url.ToString, node) End Sub ``` More info why soapfaults are better [in this question](https://stackoverflow.com/questions/81306/wcf-faults-exceptions-versus-messages).
78,077
<p>What is the best/fastest way to sort Alphanumeric fields? </p>
[ { "answer_id": 78096, "author": "senfo", "author_id": 10792, "author_profile": "https://Stackoverflow.com/users/10792", "pm_score": 0, "selected": false, "text": "<p>You will find that most development libraries ship with an implementation of the quicksort algorithm, which is often the f...
2008/09/16
[ "https://Stackoverflow.com/questions/78077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14239/" ]
What is the best/fastest way to sort Alphanumeric fields?
You don't specify your target language, but whatever it is, it should have reliable, built-in sorting methods, so use one of them! For PHP... Load into an array and sort($array); [php sort](http://ie.php.net/sort)... ``` $fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); foreach ($fruits as $key => $val) { echo "fruits[" . $key . "] = " . $val . "\n"; } ``` Output: ``` fruits[0] = apple fruits[1] = banana fruits[2] = lemon fruits[3] = orange ```
78,125
<p>The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc &amp; g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care):</p> <pre><code>char **a; const char** b = a; </code></pre> <p>I can understand and accept this.<br> The C++ solution to this problem is to change b to be a const char * const *, which disallows reassignment of the pointers and prevents you from circumventing const-correctness (<a href="http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17" rel="nofollow noreferrer">C++ FAQ</a>).<br></p> <pre><code>char **a; const char* const* b = a; </code></pre> <p>However, in pure C, the corrected version (using const char * const *) still gives a warning, and I don't understand why. Is there a way to get around this without using a cast?</p> <p>To clarify:<br> 1) Why does this generate a warning in C? It should be entirely const-safe, and the C++ compiler seems to recognize it as such.<br> 2) What is the correct way to go about accepting this char** as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to? For example, if I wanted to write a function:</p> <pre><code>void f(const char* const* in) { // Only reads the data from in, does not write to it } </code></pre> <p>And I wanted to invoke it on a char**, what would be the correct type for the parameter?</p>
[ { "answer_id": 78202, "author": "Kevin", "author_id": 6386, "author_profile": "https://Stackoverflow.com/users/6386", "pm_score": 7, "selected": true, "text": "<p>I had this same problem a few years ago and it irked me to no end.</p>\n\n<p>The rules in C are more simply stated (i.e. they...
2008/09/16
[ "https://Stackoverflow.com/questions/78125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14266/" ]
The following code snippet (correctly) gives a warning in C and an error in C++ (using gcc & g++ respectively, tested with versions 3.4.5 and 4.2.1; MSVC does not seem to care): ``` char **a; const char** b = a; ``` I can understand and accept this. The C++ solution to this problem is to change b to be a const char \* const \*, which disallows reassignment of the pointers and prevents you from circumventing const-correctness ([C++ FAQ](http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.17)). ``` char **a; const char* const* b = a; ``` However, in pure C, the corrected version (using const char \* const \*) still gives a warning, and I don't understand why. Is there a way to get around this without using a cast? To clarify: 1) Why does this generate a warning in C? It should be entirely const-safe, and the C++ compiler seems to recognize it as such. 2) What is the correct way to go about accepting this char\*\* as a parameter while saying (and having the compiler enforce) that I will not be modifying the characters it points to? For example, if I wanted to write a function: ``` void f(const char* const* in) { // Only reads the data from in, does not write to it } ``` And I wanted to invoke it on a char\*\*, what would be the correct type for the parameter?
I had this same problem a few years ago and it irked me to no end. The rules in C are more simply stated (i.e. they don't list exceptions like converting `char**` to `const char*const*`). Consequenlty, it's just not allowed. With the C++ standard, they included more rules to allow cases like this. In the end, it's just a problem in the C standard. I hope the next standard (or technical report) will address this.
78,141
<h2>Edit - New Question</h2> <p>Ok lets rephrase the question more generically. </p> <p>Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods.</p> <p>I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class.</p> <h2>Background</h2> <p>We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be disposed of, those implement the <strong>IDisposable</strong> interface.</p> <h2>The Problem</h2> <p>Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable, to "automatically" call <strong>base.Dispose(bDisposing)</strong> if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing or stops implementing IDisposable that will be taken care of automatically.</p> <p>The issue is two folds. </p> <ul> <li>First, finding if any ancestors implements IDisposable. </li> <li>Second, calling base.Dispose(bDisposing) conditionally.</li> </ul> <p>The first part, finding about ancestors implementing IDisposable, I have been able to deal with. </p> <p>The second part is the tricky one. Despite all my efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever.</p> <p>The main issue is that you <strong>cannot actually refer to base.Dispose()</strong> directly in your code if there is no such thing as an ancestor implementing it (<em>be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such a thing happens in the future</em>). That leave us with the <strong>Reflection</strong> mechanisms, but I did not find a proper way of doing it. Our code is quite filled with advanced reflection techniques and I think I did not miss anything obvious there.</p> <h2>My Solution</h2> <p>My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build (if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called).</p> <p>Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose() methods throughout the hierarchy. Any new classes are created from templates that also includes this code. </p> <pre><code>public class MyOtherClassBase { // ... } public class MyDerivedClass : MyOtherClassBase, ICalibrable { private bool m_bDisposed = false; ~MyDerivedClass() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool bDisposing) { if (!m_bDisposed) { if (bDisposing) { // Dispose managed resources } // Dispose unmanaged resources } m_bDisposed = true; Type baseType = typeof(MyDerivedClass).BaseType; if (baseType != null) { if (baseType.GetInterface("IDisposable") != null) { // If you have no ancestors implementing base.Dispose(...), comment // the following line AND uncomment the throw. // // This way, if any of your ancestors decide one day to implement // IDisposable you will know about it right away and proceed to // uncomment the base.Dispose(...) in addition to commenting the throw. //base.Dispose(bDisposing); throw new ApplicationException("Ancestor base.Dispose(...) not called - " + baseType.ToString()); } } } } </code></pre> <p><strong>So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?</strong></p> <h2>More Background</h2> <p>There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable. If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.</p>
[ { "answer_id": 78226, "author": "Bryant", "author_id": 10893, "author_profile": "https://Stackoverflow.com/users/10893", "pm_score": 2, "selected": false, "text": "<p>Personally, I think you might be better off handling this with something like FxCop. You should be able to write a rule t...
2008/09/16
[ "https://Stackoverflow.com/questions/78141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7984/" ]
Edit - New Question ------------------- Ok lets rephrase the question more generically. Using reflection, is there a way to dynamically call at runtime a base class method that you may be overriding. You cannot use the 'base' keyword at compile time because you cannot be sure it exists. At runtime I want to list my ancestors methods and call the ancestor methods. I tried using GetMethods() and such but all they return are "pointers" to the most derived implementation of the method. Not an implementation on a base class. Background ---------- We are developing a system in C# 3.0 with a relatively big class hierarchy. Some of these classes, anywhere in the hierarchy, have resources that need to be disposed of, those implement the **IDisposable** interface. The Problem ----------- Now, to facilitate maintenance and refactoring of the code I would like to find a way, for classes implementing IDisposable, to "automatically" call **base.Dispose(bDisposing)** if any ancestors also implements IDisposable. This way, if some class higher up in the hierarchy starts implementing or stops implementing IDisposable that will be taken care of automatically. The issue is two folds. * First, finding if any ancestors implements IDisposable. * Second, calling base.Dispose(bDisposing) conditionally. The first part, finding about ancestors implementing IDisposable, I have been able to deal with. The second part is the tricky one. Despite all my efforts, I haven't been able to call base.Dispose(bDisposing) from a derived class. All my attempts failed. They either caused compilation errors or called the wrong Dispose() method, that is the most derived one, thus looping forever. The main issue is that you **cannot actually refer to base.Dispose()** directly in your code if there is no such thing as an ancestor implementing it (*be reminded that there might have no ancestors yet implementing IDisposable, but I want the derived code to be ready when and if such a thing happens in the future*). That leave us with the **Reflection** mechanisms, but I did not find a proper way of doing it. Our code is quite filled with advanced reflection techniques and I think I did not miss anything obvious there. My Solution ----------- My best shot yet was to have some conditional code using in commented code. Changing the IDisposable hierarchy would either break the build (if no IDisposable ancestor exists) or throw an exception (if there are IDisposable ancestors but base.Dispose is not called). Here is some code I am posting to show you what my Dispose(bDisposing) method looks like. I am putting this code at the end of all the Dispose() methods throughout the hierarchy. Any new classes are created from templates that also includes this code. ``` public class MyOtherClassBase { // ... } public class MyDerivedClass : MyOtherClassBase, ICalibrable { private bool m_bDisposed = false; ~MyDerivedClass() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool bDisposing) { if (!m_bDisposed) { if (bDisposing) { // Dispose managed resources } // Dispose unmanaged resources } m_bDisposed = true; Type baseType = typeof(MyDerivedClass).BaseType; if (baseType != null) { if (baseType.GetInterface("IDisposable") != null) { // If you have no ancestors implementing base.Dispose(...), comment // the following line AND uncomment the throw. // // This way, if any of your ancestors decide one day to implement // IDisposable you will know about it right away and proceed to // uncomment the base.Dispose(...) in addition to commenting the throw. //base.Dispose(bDisposing); throw new ApplicationException("Ancestor base.Dispose(...) not called - " + baseType.ToString()); } } } } ``` **So, I am asking is there a way to call base.Dispose() automatically/conditionally instead?** More Background --------------- There is another mechanism in the application where all objects are registered with a main class. The class checks if they implement IDisposable. If so, they are disposed of properly by the application. This avoids having the code using the classes to deal with calling Dispose() all around by themselves. Thus, adding IDisposable to a class that has no ancestor history of IDisposable still works perfectly.
The standard pattern is for your base class to implement IDisposable and the non-virtual Dispose() method, and to implement a virtual Dispose(bool) method, which those classes which hold disposable resources must override. They should always call their base Dispose(bool) method, which will chain up to the top class in the hierarchy eventually. Only those classes which override it will be called, so the chain is usually quite short. Finalizers, spelled ~Class in C#: Don't. Very few classes will need one, and it's very easy to accidentally keep large object graphs around, because the finalizers require at least two collections before the memory is released. On the first collection after the object is no longer referenced, it's put on a queue of finalizers to be run. These are run *on a separate, dedicated thread* which only runs finalizers (if it gets blocked, no more finalizers run and your memory usage explodes). Once the finalizer has run, the next collection that collects the appropriate generation will free the object and anything else it was referencing that isn't otherwise referenced. Unfortunately, because it survives the first collection, it will be placed into the older generation which is collected less frequently. For this reason, you should Dispose early and often. Generally, you should implement a small resource wrapper class that *only* manages the resource lifetime and implement a finalizer on that class, plus IDisposable. The user of the class should then call Dispose on this when it is disposed. There shouldn't be a back-link to the user. That way, only the thing that actually needs finalization ends up on the finalization queue. If you are going to need them anywhere in the hierarchy, the base class that implements IDisposable should implement the finalizer and call Dispose(bool), passing false as the parameter. WARNING for Windows Mobile developers (VS2005 and 2008, .NET Compact Framework 2.0 and 3.5): many non-controls that you drop onto your designer surface, e.g. menu bars, timers, HardwareButtons, derive from System.ComponentModel.Component, which implements a finalizer. For desktop projects, Visual Studio adds the components to a System.ComponentModel.Container named `components`, which it generates code to Dispose when the form is Disposed - it in turn Disposes all the components that have been added. For the mobile projects, the code to Dispose `components` is generated, *but dropping a component onto the surface does not generate the code to add it to `components`*. You have to do this yourself in your constructor after calling InitializeComponent.
78,161
<p>In a C++ app, I have an hWnd pointing to a window running in a third party process. This window contains controls which extend the COM TreeView control. I am interested in obtaining the CheckState of this control.<br> I use the hWnd to get an HTREEITEM using TreeView_GetRoot(hwnd) from commctrl.h</p> <p>hwnd points to the window and hItem is return value from TreeView_GetRoot(hwnd). They are used as follows:</p> <pre><code>int iCheckState = TreeView_GetCheckState(hwnd, hItem); switch (iCheckState) { case 0: // (unchecked) case 1: // checked ... } </code></pre> <p>I'm looking to port this code into a C# app which does the same thing (switches off the CheckState of the TreeView control). I have never used COM and am quite unfamiliar.</p> <p>I have tried using the .NET mscomctl but can't find equivalent methods to TreeView_GetRoot or TreeView_GetCheckState. I'm totally stuck and don't know how to recreate this code in C# :(</p> <p>Suggestions?</p>
[ { "answer_id": 78229, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "<p>Why are you not using a Windows Forms TreeView control? If you are using this control, set the control's CheckBoxes p...
2008/09/16
[ "https://Stackoverflow.com/questions/78161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/165305/" ]
In a C++ app, I have an hWnd pointing to a window running in a third party process. This window contains controls which extend the COM TreeView control. I am interested in obtaining the CheckState of this control. I use the hWnd to get an HTREEITEM using TreeView\_GetRoot(hwnd) from commctrl.h hwnd points to the window and hItem is return value from TreeView\_GetRoot(hwnd). They are used as follows: ``` int iCheckState = TreeView_GetCheckState(hwnd, hItem); switch (iCheckState) { case 0: // (unchecked) case 1: // checked ... } ``` I'm looking to port this code into a C# app which does the same thing (switches off the CheckState of the TreeView control). I have never used COM and am quite unfamiliar. I have tried using the .NET mscomctl but can't find equivalent methods to TreeView\_GetRoot or TreeView\_GetCheckState. I'm totally stuck and don't know how to recreate this code in C# :( Suggestions?
We have these definitions from CommCtrl.h: ``` #define TreeView_SetItemState(hwndTV, hti, data, _mask) \ { TVITEM _ms_TVi;\ _ms_TVi.mask = TVIF_STATE; \ _ms_TVi.hItem = (hti); \ _ms_TVi.stateMask = (_mask);\ _ms_TVi.state = (data);\ SNDMSG((hwndTV), TVM_SETITEM, 0, (LPARAM)(TV_ITEM *)&_ms_TVi);\ } #define TreeView_SetCheckState(hwndTV, hti, fCheck) \ TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck)?2:1), TVIS_STATEIMAGEMASK) ``` We can translate this to C# using PInvoke. First, we implement these macros as functions, and then add whatever other support is needed to make those functions work. Here is my first shot at it. You should double check my code especially when it comes to the marshalling of the struct. Further, you may want to Post the message cross-thread instead of calling SendMessage. Lastly, I am not sure if this will work at all since I believe that the common controls use WM\_USER+ messages. When these messages are sent cross-process, the data parameter's addresses are unmodified and the resulting process may cause an Access Violation. This would be a problem in whatever language you use (C++ or C#), so perhaps I am wrong here (you say you have a working C++ program). ``` static class Interop { public static IntPtr TreeView_SetCheckState(HandleRef hwndTV, IntPtr hti, bool fCheck) { return TreeView_SetItemState(hwndTV, hti, INDEXTOSTATEIMAGEMASK((fCheck) ? 2 : 1), (uint)TVIS.TVIS_STATEIMAGEMASK); } public static IntPtr TreeView_SetItemState(HandleRef hwndTV, IntPtr hti, uint data, uint _mask) { TVITEM _ms_TVi = new TVITEM(); _ms_TVi.mask = (uint)TVIF.TVIF_STATE; _ms_TVi.hItem = (hti); _ms_TVi.stateMask = (_mask); _ms_TVi.state = (data); IntPtr p = Marshal.AllocCoTaskMem(Marshal.SizeOf(_ms_TVi)); Marshal.StructureToPtr(_ms_TVi, p, false); IntPtr r = SendMessage(hwndTV, (int)TVM.TVM_SETITEMW, IntPtr.Zero, p); Marshal.FreeCoTaskMem(p); return r; } private static uint INDEXTOSTATEIMAGEMASK(int i) { return ((uint)(i) << 12); } [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr SendMessage(HandleRef hWnd, int msg, IntPtr wParam, IntPtr lParam); private enum TVIF : uint { TVIF_STATE = 0x0008 } private enum TVIS : uint { TVIS_STATEIMAGEMASK = 0xF000 } private enum TVM : int { TV_FIRST = 0x1100, TVM_SETITEMA = (TV_FIRST + 13), TVM_SETITEMW = (TV_FIRST + 63) } private struct TVITEM { public uint mask; public IntPtr hItem; public uint state; public uint stateMask; public IntPtr pszText; public int cchTextMax; public int iImage; public int iSelectedImage; public int cChildren; public IntPtr lParam; } } ```
78,181
<p>If I am given a <code>MemoryStream</code> that I know has been populated with a <code>String</code>, how do I get a <code>String</code> back out?</p>
[ { "answer_id": 78189, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 6, "selected": false, "text": "<p>use a <a href=\"http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx\" rel=\"nofollow noreferrer\">StreamRe...
2008/09/16
[ "https://Stackoverflow.com/questions/78181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320/" ]
If I am given a `MemoryStream` that I know has been populated with a `String`, how do I get a `String` back out?
This sample shows how to read and write a string to a MemoryStream. --- ``` Imports System.IO Module Module1 Sub Main() ' We don't need to dispose any of the MemoryStream ' because it is a managed object. However, just for ' good practice, we'll close the MemoryStream. Using ms As New MemoryStream Dim sw As New StreamWriter(ms) sw.WriteLine("Hello World") ' The string is currently stored in the ' StreamWriters buffer. Flushing the stream will ' force the string into the MemoryStream. sw.Flush() ' If we dispose the StreamWriter now, it will close ' the BaseStream (which is our MemoryStream) which ' will prevent us from reading from our MemoryStream 'sw.Dispose() ' The StreamReader will read from the current ' position of the MemoryStream which is currently ' set at the end of the string we just wrote to it. ' We need to set the position to 0 in order to read ' from the beginning. ms.Position = 0 Dim sr As New StreamReader(ms) Dim myStr = sr.ReadToEnd() Console.WriteLine(myStr) ' We can dispose our StreamWriter and StreamReader ' now, though this isn't necessary (they don't hold ' any resources open on their own). sw.Dispose() sr.Dispose() End Using Console.WriteLine("Press any key to continue.") Console.ReadKey() End Sub End Module ```
78,233
<p>I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this:</p> <ol> <li><p>Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable.</p></li> <li><p>If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers.</p></li> </ol> <p>Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work?</p> <p>The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.</p>
[ { "answer_id": 78246, "author": "sgwill", "author_id": 1204, "author_profile": "https://Stackoverflow.com/users/1204", "pm_score": 1, "selected": false, "text": "<p>What if you save the file as an xlsx, the extension for XML-Excel?</p>\n" }, { "answer_id": 78292, "author": "M...
2008/09/16
[ "https://Stackoverflow.com/questions/78233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2916/" ]
I have a dataset that I have modified into an xml document and then used a xsl sheet to transform into an Excel xml format in order to allow the data to be opened programatically from my application. I have run into two problems with this: 1. Excel is not the default Windows application to open Excel files, therefore when Program.Start("xmlfilename.xml") is run, IE is opened and the XML file is not very readable. 2. If you rename the file to .xlsx, you receive a warning, "This is not an excel file, do you wish to continue". This is not ideal for customers. Ideally, I would like Windows to open the file in Excel without modifying the default OS setting for opening Excel files. Office interop is a possibility, but seems like a little overkill for this application. Does anyone have any ideas to make this work? The solution is in .Net/C#, but I am open to other possibilities to create a clean solution.
``` Process.Start(@"C:\Program Files\Microsoft Office\Officexx\excel.exe", "yourfile.xml"); ``` That being said, you will still get the message box. I suppose that you could use the Interop, but I am not sure how well it will work for you.
78,277
<p>When can 64-bit writes be guaranteed to be atomic, when programming in C on an Intel x86-based platform (in particular, an Intel-based Mac running MacOSX 10.4 using the Intel compiler)? For example:</p> <pre><code>unsigned long long int y; y = 0xfedcba87654321ULL; /* ... a bunch of other time-consuming stuff happens... */ y = 0x12345678abcdefULL; </code></pre> <p>If another thread is examining the value of y after the first assignment to y has finished executing, I would like to ensure that it sees either the value 0xfedcba87654321 or the value 0x12345678abcdef, and not some blend of them. I would like to do this without any locking, and if possible without any extra code. My hope is that, when using a 64-bit compiler (the 64-bit Intel compiler), on an operating system capable of supporting 64-bit code (MacOSX 10.4), that these 64-bit writes will be atomic. Is this always true?</p>
[ { "answer_id": 78285, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 1, "selected": false, "text": "<p>GCC has intrinsics for atomic operations; I suspect you can do similar with other compilers, too. Never rely on th...
2008/09/16
[ "https://Stackoverflow.com/questions/78277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When can 64-bit writes be guaranteed to be atomic, when programming in C on an Intel x86-based platform (in particular, an Intel-based Mac running MacOSX 10.4 using the Intel compiler)? For example: ``` unsigned long long int y; y = 0xfedcba87654321ULL; /* ... a bunch of other time-consuming stuff happens... */ y = 0x12345678abcdefULL; ``` If another thread is examining the value of y after the first assignment to y has finished executing, I would like to ensure that it sees either the value 0xfedcba87654321 or the value 0x12345678abcdef, and not some blend of them. I would like to do this without any locking, and if possible without any extra code. My hope is that, when using a 64-bit compiler (the 64-bit Intel compiler), on an operating system capable of supporting 64-bit code (MacOSX 10.4), that these 64-bit writes will be atomic. Is this always true?
Your best bet is to avoid trying to build your own system out of primitives, and instead use locking unless it **really** shows up as a hot spot when profiling. (If you think you can be clever and avoid locks, don't. You aren't. That's the general "you" which includes me and everybody else.) You should at minimum use a spin lock, see [spinlock(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html). And whatever you do, **don't** try to implement "your own" locks. You will get it wrong. Ultimately, you need to use whatever locking or atomic operations your operating system provides. Getting these sorts of things **exactly right** in **all cases** is **extremely difficult**. Often it can involve knowledge of things like the errata for specific versions of specific processor. ("Oh, version 2.0 of that processor didn't do the cache-coherency snooping at the right time, it's fixed in version 2.0.1 but on 2.0 you need to insert a `NOP`.") Just slapping a `volatile` keyword on a variable in C is almost always insufficient. On Mac OS X, that means you need to use the functions listed in [atomic(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html) to perform truly atomic-across-all-CPUs operations on 32-bit, 64-bit, and pointer-sized quantities. (Use the latter for any atomic operations on pointers so you're 32/64-bit compatible automatically.) That goes whether you want to do things like atomic compare-and-swap, increment/decrement, spin locking, or stack/queue management. Fortunately the [spinlock(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/spinlock.3.html), [atomic(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atomic.3.html), and [barrier(3)](http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/barrier.3.html) functions should all work correctly on all CPUs that are supported by Mac OS X.
78,278
<p>How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.</p>
[ { "answer_id": 78301, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>Use sub references, and closures. A good perlish example of this</p>\n\n<pre><code>sort { lc($a) cmp lc($b) } @ite...
2008/09/16
[ "https://Stackoverflow.com/questions/78278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1227001/" ]
How do I write a clean implementation of the strategy pattern in Perl? I want to do it in a way that leverages Perl's features.
It really depends on what you mean by "clean implementation". As in any other language, you can use Perl's object system with polymorphism to do this for you. However, since Perl has first class functions, this pattern isn't normally coded explicitly. Leon Timmermans' example of ``` sort { lc($a) cmp lc($b) } @items ``` demonstrates this quite elegantly. However, if you're looking for a "formal" implementation as you would do in C++, here's what it may look like using Perl+[Moose](http://search.cpan.org/dist/Moose). This is just a translation of the C++ code from [Wikipedia -- Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern), except I'm using Moose's support for delegation. ``` package StrategyInterface; use Moose::Role; requires 'run'; package Context; use Moose; has 'strategy' => ( is => 'rw', isa => 'StrategyInterface', handles => [ 'run' ], ); package SomeStrategy; use Moose; with 'StrategyInterface'; sub run { warn "applying SomeStrategy!\n"; } package AnotherStrategy; use Moose; with 'StrategyInterface'; sub run { warn "applying AnotherStrategy!\n"; } ############### package main; my $contextOne = Context->new( strategy => SomeStrategy->new() ); my $contextTwo = Context->new( strategy => AnotherStrategy->new() ); $contextOne->run(); $contextTwo->run(); ```
78,296
<p>What are some reasons why PHP would force errors to show, no matter what you tell it to disable?</p> <p>I have tried </p> <pre><code>error_reporting(0); ini_set('display_errors', 0); </code></pre> <p>with no luck.</p>
[ { "answer_id": 78324, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 5, "selected": true, "text": "<p>Note the caveat in the manual at <a href=\"http://uk.php.net/error_reporting\" rel=\"noreferrer\">http://uk.php.net/err...
2008/09/16
[ "https://Stackoverflow.com/questions/78296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14322/" ]
What are some reasons why PHP would force errors to show, no matter what you tell it to disable? I have tried ``` error_reporting(0); ini_set('display_errors', 0); ``` with no luck.
Note the caveat in the manual at <http://uk.php.net/error_reporting>: > > > > > > Most of E\_STRICT errors are evaluated at the compile time thus such errors are not reported in the file where error\_reporting is enhanced to include E\_STRICT errors (and vice versa). > > > > > > > > > If your underlying system is configured to report E\_STRICT errors, these may be output before your code is even considered. Don't forget, error\_reporting/ini\_set are runtime evaluations, and anything performed in a "before-run" phase will not see their effects. --- Based on your comment that your error is... > > Parse error: syntax error, unexpected T\_VARIABLE, expecting ',' or ';' in /usr/home/REDACTED/public\_html/dev.php on line 11 > > > Then the same general concept applies. Your code is never run, as it is syntactically invalid (you forgot a ';'). Therefore, your change of error reporting is never encountered. Fixing this requires a change of the system level error reporting. For example, on Apache you may be able to place... php\_value error\_reporting 0 in a .htaccess file to suppress them all, but this is system configuration dependent. Pragmatically, don't write files with syntax errors :)
78,389
<p>I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood.</p> <p>I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests.</p> <p>This is what I'm doing so far:</p> <pre><code>public void CreateSomethingIfUserHasAdminPermissions() { User user = _mocks.StrictMock&lt;User&gt;(); SetupResult.For(user.IsAdministrator).Return(true); // do something with my User object } </code></pre> <p>Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property.</p> <p>Can someone explain how I can achieve my goal here?</p>
[ { "answer_id": 78428, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 1, "selected": false, "text": "<p>Make sure IsAdministrator is virtual.</p>\n\n<p>Also, be sure you call _mocks.ReplayAll()</p>\n" }, { "answ...
2008/09/16
[ "https://Stackoverflow.com/questions/78389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/769/" ]
I'm new to RhinoMocks, and trying to get a grasp on the syntax in addition to what is happening under the hood. I have a user object, we'll call it User, which has a property called IsAdministrator. The value for IsAdministrator is evaluated via another class that checks the User's security permissions, and returns either true or false based on those permissions. I'm trying to mock this User class, and fake the return value for IsAdministrator in order to isolate some Unit Tests. This is what I'm doing so far: ``` public void CreateSomethingIfUserHasAdminPermissions() { User user = _mocks.StrictMock<User>(); SetupResult.For(user.IsAdministrator).Return(true); // do something with my User object } ``` Now, I'm expecting that Rhino is going to 'fake' the call to the property getter, and just return true to me. Is this incorrect? Currently I'm getting an exception because of dependencies in the IsAdministrator property. Can someone explain how I can achieve my goal here?
One quick note before I jump into this. Typically you want to avoid the use of a "Strict" mock because it makes for a brittle test. A strict mock will throw an exception if anything occurs that you do not explicitly tell Rhino will happen. Also I think you may be misunderstanding exactly what Rhino is doing when you make a call to create a mock. Think of it as a custom Object that has either been derived from, or implements the System.Type you defined. If you did it yourself it would look like this: ``` public class FakeUserType: User { //overriding code here } ``` Since IsAdministrator is probably just a public property on the User type you can't override it in the inheriting type. As far as your question is concerned there are multiple ways you could handle this. You could implement IsAdministrator as a virtual property on your user class as [aaronjensen](https://stackoverflow.com/questions/78389/rhinomocks-correct-way-to-mock-property-getter#78428) mentioned as follows: ``` public class User { public virtual Boolean IsAdministrator { get; set; } } ``` This is an ok approach, but only if you plan on inheriting from your User class. Also if you wan't to fake other members on this class they would also have to be virtual, which is probably not the desired behavior. Another way to accomplish this is through the use of interfaces. If it is truly the User class you are wanting to Mock then I would extract an interface from it. Your above example would look something like this: ``` public interface IUser { Boolean IsAdministrator { get; } } public class User : IUser { private UserSecurity _userSecurity = new UserSecurity(); public Boolean IsAdministrator { get { return _userSecurity.HasAccess("AdminPermissions"); } } } public void CreateSomethingIfUserHasAdminPermissions() { IUser user = _mocks.StrictMock<IUser>(); SetupResult.For(user.IsAdministrator).Return(true); // do something with my User object } ``` You can get fancier if you want by using [dependency injection and IOC](http://martinfowler.com/articles/injection.html) but the basic principle is the same across the board. Typically you want your classes to depend on interfaces rather than concrete implementations anyway. I hope this helps. I have been using RhinoMocks for a long time on a major project now so don't hesitate to ask me questions about TDD and mocking.
78,392
<p>I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC.</p> <p>Now we are moving to the <a href="http://en.wikipedia.org/wiki/Aspire_One" rel="nofollow noreferrer">Acer Aspire One</a> but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.</p>
[ { "answer_id": 87995, "author": "X-Istence", "author_id": 13986, "author_profile": "https://Stackoverflow.com/users/13986", "pm_score": 0, "selected": false, "text": "<p>If you could give us more to go on than just trouble making it compile; we might be better able to help you with your ...
2008/09/16
[ "https://Stackoverflow.com/questions/78392", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7946/" ]
I have an application that works pretty well in Ubuntu, Windows and the Xandros that come with the Asus EeePC. Now we are moving to the [Acer Aspire One](http://en.wikipedia.org/wiki/Aspire_One) but I'm having a lot of trouble making php-gtk to compile under the Fedora-like (Linpus Linux Lite) Linux that come with it.
Hi Guys well I finally got this thing to work the basic workflow was this: ``` #!/bin/bash sudo yum install yum-utils #We don't want to update the main gtk2 by mistake so we download them #manually and install with no-deps[1](and forced because gtk version #version of AA1 and the gtk2-devel aren't compatible). sudo yumdownloader --disablerepo=updates gtk2-devel glib2-devel sudo rpm --force --nodeps -i gtk2*rpm glib2*rpm #We install the rest of the libraries needed. sudo yum --disablerepo=updates install atk-devel pango-devel libglade2-devel sudo yum install php-cli php-devel make gcc #We Download and compile php-gtk wget http://gtk.php.net/do_download.php?download_file=php-gtk-2.0.1.tar.gz tar -xvzf php-gtk-2.0.1.tar.gz cd php-gtk-2.0.1 ./buildconf ./configure make sudo make install ``` If you want to add more libraries like gtk-extra please type `./configure -help` before making it to see the different options available. After installing you'll need to add `php_gtk2.so` to the *Dynamic Extensions* of `/etc/php.ini` ``` extension=php_gtk2.so ``` Sources: [1]: [Dependency problems on Acer Aspire One Linux](http://macles.blogspot.com/2008/08/dependency-problems-on-acer-aspire-one.html)
78,423
<p>The error I'm getting:</p> <pre><code>in /Users/robert/Documents/funWithFrameworks/build/Debug-iphonesimulator/funWithFrameworks.framework/funWithFrameworks, can't link with a main executable </code></pre> <p>Cliff notes:</p> <ul> <li>trying to include framework</li> <li>doesn't want to link</li> </ul> <p>More detail: I'm developing for a <em>mobile device... hint, hint</em> using Xcode and I'm trying to make my own custom framework which I can include from another application. So far, I've done the following:</p> <ol> <li>Create a new project; an iPhone OS window based app.</li> <li>Go to target info-> under packaging, change the wrapper extension from app to framework</li> <li>Go to Action->new build phase -> copy headers. Change roles of headers to 'public'</li> <li>From my application, I add the framework to the frameworks group.</li> </ol>
[ { "answer_id": 79109, "author": "amrox", "author_id": 4468, "author_profile": "https://Stackoverflow.com/users/4468", "pm_score": 0, "selected": false, "text": "<p>I haven't tried it for so called <em>mobile device</em>, but I would guess its very similar to the method for a regular Coco...
2008/09/16
[ "https://Stackoverflow.com/questions/78423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The error I'm getting: ``` in /Users/robert/Documents/funWithFrameworks/build/Debug-iphonesimulator/funWithFrameworks.framework/funWithFrameworks, can't link with a main executable ``` Cliff notes: * trying to include framework * doesn't want to link More detail: I'm developing for a *mobile device... hint, hint* using Xcode and I'm trying to make my own custom framework which I can include from another application. So far, I've done the following: 1. Create a new project; an iPhone OS window based app. 2. Go to target info-> under packaging, change the wrapper extension from app to framework 3. Go to Action->new build phase -> copy headers. Change roles of headers to 'public' 4. From my application, I add the framework to the frameworks group.
Apple clearly said that you can **not** use dynamic libraries on their mobiles. And a private framework is just this. You can, however, use static libraries.
78,431
<p>I would like to replicate this in python:</p> <pre><code>gvimdiff &lt;(hg cat file.txt) file.txt </code></pre> <p>(hg cat file.txt outputs the most recently committed version of file.txt)</p> <p>I know how to pipe the file to gvimdiff, but it won't accept another file:</p> <pre><code>$ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" </code></pre> <p>Getting to the python part...</p> <pre><code># hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "&lt;(hg cat %s)" % file, file]) </code></pre> <p>When subprocess is called it merely passes <code>&lt;(hg cat file)</code> onto <code>gvimdiff</code> as a filename.</p> <p>So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff:</p> <pre><code>diff &lt;(cat file.txt) file.txt </code></pre>
[ { "answer_id": 78459, "author": "Mark Hattarki", "author_id": 14424, "author_profile": "https://Stackoverflow.com/users/14424", "pm_score": 2, "selected": false, "text": "<p>There is also the commands module:</p>\n\n<pre><code>import commands\n\nstatus, output = commands.getstatusoutput(...
2008/09/16
[ "https://Stackoverflow.com/questions/78431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12650/" ]
I would like to replicate this in python: ``` gvimdiff <(hg cat file.txt) file.txt ``` (hg cat file.txt outputs the most recently committed version of file.txt) I know how to pipe the file to gvimdiff, but it won't accept another file: ``` $ hg cat file.txt | gvimdiff file.txt - Too many edit arguments: "-" ``` Getting to the python part... ``` # hgdiff.py import subprocess import sys file = sys.argv[1] subprocess.call(["gvimdiff", "<(hg cat %s)" % file, file]) ``` When subprocess is called it merely passes `<(hg cat file)` onto `gvimdiff` as a filename. So, is there any way to redirect a command as bash does? For simplicity's sake just cat a file and redirect it to diff: ``` diff <(cat file.txt) file.txt ```
It can be done. As of Python 2.5, however, this mechanism is Linux-specific and not portable: ``` import subprocess import sys file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen([ 'gvimdiff', '/proc/self/fd/%s' % p1.stdout.fileno(), file]) p2.wait() ``` That said, in the specific case of diff, you can simply take one of the files from stdin, and remove the need to use the bash-alike functionality in question: ``` file = sys.argv[1] p1 = subprocess.Popen(['hg', 'cat', file], stdout=subprocess.PIPE) p2 = subprocess.Popen(['diff', '-', file], stdin=p1.stdout) diff_text = p2.communicate()[0] ```
78,447
<p>How to create a DOM from a User's input in PHP5?</p>
[ { "answer_id": 78465, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 2, "selected": false, "text": "<p>I would use the DOM API that has been part of the core since 5. For an XML string $xml, you can build a DOM object wit...
2008/09/16
[ "https://Stackoverflow.com/questions/78447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12854/" ]
How to create a DOM from a User's input in PHP5?
I would use the DOM API that has been part of the core since 5. For an XML string $xml, you can build a DOM object with ``` $dom = new DOMDocument(); $dom->loadXML($xml); ``` Manipulate it with the rest of the DOM API, defined at <http://uk.php.net/DOM>
78,450
<p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br> According to the <a href="http://www.reportlab.com/docs/userguide.pdf" rel="noreferrer">user guide</a>,</p> <blockquote> <p>Special TableStyle Indeces [sic]</p> <p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p> </blockquote> <p>I've tried using several style elements, including:</p> <pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black) </code></pre> <p>and none of these seems to work. The first generates a TypeError with the message: </p> <pre><code>TypeError: cannot concatenate 'str' and 'int' objects </code></pre> <p>and the latter two generate TypeErrors with the message:</p> <pre><code>TypeError: an integer is required </code></pre> <p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
[ { "answer_id": 78702, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>[...] In any style command <strong>the first row\n index</strong> may be set to one of the special strings [....
2008/09/16
[ "https://Stackoverflow.com/questions/78450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14382/" ]
I'm trying to use Python with ReportLab 2.2 to create a PDF report. According to the [user guide](http://www.reportlab.com/docs/userguide.pdf), > > Special TableStyle Indeces [sic] > > > In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split. > > > I've tried using several style elements, including: ``` ('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black) ``` and none of these seems to work. The first generates a TypeError with the message: ``` TypeError: cannot concatenate 'str' and 'int' objects ``` and the latter two generate TypeErrors with the message: ``` TypeError: an integer is required ``` Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?
Well, it looks as if I will be answering my own question. First, the documentation flat out lies where it reads "In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation." In the current release, the "splitlast" and "splitfirst" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds. My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors. However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code: ``` class XTable(Table): def onSplit(self, T, byRow=1): T.setStyle(TableStyle([ ('TEXTCOLOR', (0, 1), (1, 1), colors.black)])) ``` What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.
78,468
<p>I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables:</p> <p>Company, CompanyProduct, Product</p> <p>The CompanyProduct is linked to its two parent tables, Company and Product.</p> <p>I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows: </p> <pre><code>SELECT * FROM Company AS C LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID WHERE P.ProductID = 14 OR P.ProductID IS NULL </code></pre> <p>My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables. </p> <p>So how do you write the same kind of join in LINQ to Entity to acheive a similiar result? </p> <p>I have tried a few different things but can't get the syntax correct.</p> <p>Thanks.</p>
[ { "answer_id": 78714, "author": "dimarzionist", "author_id": 10778, "author_profile": "https://Stackoverflow.com/users/10778", "pm_score": 0, "selected": false, "text": "<p>Please try something like this:</p>\n\n<pre><code>from s in db.Employees\njoin e in db.Employees on s.ReportsTo equ...
2008/09/16
[ "https://Stackoverflow.com/questions/78468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to understand left outer joins in LINQ to Entity. For example I have the following 3 tables: Company, CompanyProduct, Product The CompanyProduct is linked to its two parent tables, Company and Product. I want to return all of the Company records and the associated CompanyProduct whether the CompanyProduct exists or not for a given product. In Transact SQL I would go from the Company table using left outer joins as follows: ``` SELECT * FROM Company AS C LEFT OUTER JOIN CompanyProduct AS CP ON C.CompanyID=CP.CompanyID LEFT OUTER JOIN Product AS P ON CP.ProductID=P.ProductID WHERE P.ProductID = 14 OR P.ProductID IS NULL ``` My database has 3 companies, and 2 CompanyProduct records assocaited with the ProductID of 14. So the results from the SQL query are the expected 3 rows, 2 of which are connected to a CompanyProduct and Product and 1 which simply has the Company table and nulls in the CompanyProduct and Product tables. So how do you write the same kind of join in LINQ to Entity to acheive a similiar result? I have tried a few different things but can't get the syntax correct. Thanks.
Solved it! **Final Output:** ``` theCompany.id: 1 theProduct.id: 14 theCompany.id: 2 theProduct.id: 14 theCompany.id: 3 ``` --- **Here is the Scenario** **1 - The Database** ```sql --Company Table CREATE TABLE [theCompany]( [id] [int] IDENTITY(1,1) NOT NULL, [value] [nvarchar](50) NULL, CONSTRAINT [PK_theCompany] PRIMARY KEY CLUSTERED ( [id] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]; GO --Products Table CREATE TABLE [theProduct]( [id] [int] IDENTITY(1,1) NOT NULL, [value] [nvarchar](50) NULL, CONSTRAINT [PK_theProduct] PRIMARY KEY CLUSTERED ( [id] ASC ) WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]; GO --CompanyProduct Table CREATE TABLE [dbo].[CompanyProduct]( [fk_company] [int] NOT NULL, [fk_product] [int] NOT NULL ) ON [PRIMARY]; GO ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT [FK_CompanyProduct_theCompany] FOREIGN KEY([fk_company]) REFERENCES [theCompany] ([id]); GO ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT [FK_CompanyProduct_theCompany]; GO ALTER TABLE [CompanyProduct] WITH CHECK ADD CONSTRAINT [FK_CompanyProduct_theProduct] FOREIGN KEY([fk_product]) REFERENCES [dbo].[theProduct] ([id]); GO ALTER TABLE [dbo].[CompanyProduct] CHECK CONSTRAINT [FK_CompanyProduct_theProduct]; ``` **2 - The Data** ``` SELECT [id] ,[value] FROM theCompany id value ----------- -------------------------------------------------- 1 company1 2 company2 3 company3 SELECT [id] ,[value] FROM theProduct id value ----------- -------------------------------------------------- 14 Product 1 SELECT [fk_company],[fk_product] FROM CompanyProduct; fk_company fk_product ----------- ----------- 1 14 2 14 ``` **3 - The Entity in VS.NET 2008** [alt text http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png](http://i478.photobucket.com/albums/rr148/KyleLanser/companyproduct.png) The Entity Container Name is 'testEntities' (as seen in model Properties window) **4 - The Code (FINALLY!)** ```c# testEntities entity = new testEntities(); var theResultSet = from c in entity.theCompany select new { company_id = c.id, product_id = c.theProduct.Select(e=>e) }; foreach(var oneCompany in theResultSet) { Debug.WriteLine("theCompany.id: " + oneCompany.company_id); foreach(var allProducts in oneCompany.product_id) { Debug.WriteLine("theProduct.id: " + allProducts.id); } } ``` **5 - The Final Output** ``` theCompany.id: 1 theProduct.id: 14 theCompany.id: 2 theProduct.id: 14 theCompany.id: 3 ```
78,474
<p>Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?</p>
[ { "answer_id": 78485, "author": "nutbar", "author_id": 14425, "author_profile": "https://Stackoverflow.com/users/14425", "pm_score": 2, "selected": false, "text": "<p>I suppose you could step through the string and check if there are any <code>.</code> characters in it. That's just the ...
2008/09/16
[ "https://Stackoverflow.com/questions/78474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9418/" ]
Using only ANSI C, what is the best way to, with fair certainty, determine if a C style string is either a integer or a real number (i.e float/double)?
Don't use atoi and atof as these functions return 0 on failure. Last time I checked 0 is a valid integer and float, therefore no use for determining type. use the strto{l,ul,ull,ll,d} functions, as these set errno on failure, and also report where the converted data ended. strtoul: <http://www.opengroup.org/onlinepubs/007908799/xsh/strtoul.html> this example assumes that the string contains a single value to be converted. ``` #include <errno.h> char* to_convert = "some string"; char* p = to_convert; errno = 0; unsigned long val = strtoul(to_convert, &p, 10); if (errno != 0) // conversion failed (EINVAL, ERANGE) if (to_convert == p) // conversion failed (no characters consumed) if (*p != 0) // conversion failed (trailing data) ``` Thanks to Jonathan Leffler for pointing out that I forgot to set errno to 0 first.
78,497
<p>Does anyone know of any resources that talk about best practices or design patterns for shell scripts (sh, bash etc.)?</p>
[ { "answer_id": 78509, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Easy:\nuse python instead of shell scripts.\nYou get a near 100 fold increase in readablility, without having to complicate ...
2008/09/17
[ "https://Stackoverflow.com/questions/78497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14437/" ]
Does anyone know of any resources that talk about best practices or design patterns for shell scripts (sh, bash etc.)?
I wrote quite complex shell scripts and my first suggestion is "don't". The reason is that is fairly easy to make a small mistake that hinders your script, or even make it dangerous. That said, I don't have other resources to pass you but my personal experience. Here is what I normally do, which is overkill, but tends to be solid, although *very* verbose. **Invocation** make your script accept long and short options. be careful because there are two commands to parse options, getopt and getopts. Use getopt as you face less trouble. ``` CommandLineOptions__config_file="" CommandLineOptions__debug_level="" getopt_results=`getopt -s bash -o c:d:: --long config_file:,debug_level:: -- "$@"` if test $? != 0 then echo "unrecognized option" exit 1 fi eval set -- "$getopt_results" while true do case "$1" in --config_file) CommandLineOptions__config_file="$2"; shift 2; ;; --debug_level) CommandLineOptions__debug_level="$2"; shift 2; ;; --) shift break ;; *) echo "$0: unparseable option $1" EXCEPTION=$Main__ParameterException EXCEPTION_MSG="unparseable option $1" exit 1 ;; esac done if test "x$CommandLineOptions__config_file" == "x" then echo "$0: missing config_file parameter" EXCEPTION=$Main__ParameterException EXCEPTION_MSG="missing config_file parameter" exit 1 fi ``` Another important point is that a program should always return zero if completes successfully, non-zero if something went wrong. **Function calls** You can call functions in bash, just remember to define them before the call. Functions are like scripts, they can only return numeric values. This means that you have to invent a different strategy to return string values. My strategy is to use a variable called RESULT to store the result, and returning 0 if the function completed cleanly. Also, you can raise exceptions if you are returning a value different from zero, and then set two "exception variables" (mine: EXCEPTION and EXCEPTION\_MSG), the first containing the exception type and the second a human readable message. When you call a function, the parameters of the function are assigned to the special vars $0, $1 etc. I suggest you to put them into more meaningful names. declare the variables inside the function as local: ``` function foo { local bar="$0" } ``` **Error prone situations** In bash, unless you declare otherwise, an unset variable is used as an empty string. This is very dangerous in case of typo, as the badly typed variable will not be reported, and it will be evaluated as empty. use ``` set -o nounset ``` to prevent this to happen. Be careful though, because if you do this, the program will abort every time you evaluate an undefined variable. For this reason, the only way to check if a variable is not defined is the following: ``` if test "x${foo:-notset}" == "xnotset" then echo "foo not set" fi ``` You can declare variables as readonly: ``` readonly readonly_var="foo" ``` **Modularization** You can achieve "python like" modularization if you use the following code: ``` set -o nounset function getScriptAbsoluteDir { # @description used to get the script path # @param $1 the script $0 parameter local script_invoke_path="$1" local cwd=`pwd` # absolute path ? if so, the first character is a / if test "x${script_invoke_path:0:1}" = 'x/' then RESULT=`dirname "$script_invoke_path"` else RESULT=`dirname "$cwd/$script_invoke_path"` fi } script_invoke_path="$0" script_name=`basename "$0"` getScriptAbsoluteDir "$script_invoke_path" script_absolute_dir=$RESULT function import() { # @description importer routine to get external functionality. # @description the first location searched is the script directory. # @description if not found, search the module in the paths contained in $SHELL_LIBRARY_PATH environment variable # @param $1 the .shinc file to import, without .shinc extension module=$1 if test "x$module" == "x" then echo "$script_name : Unable to import unspecified module. Dying." exit 1 fi if test "x${script_absolute_dir:-notset}" == "xnotset" then echo "$script_name : Undefined script absolute dir. Did you remove getScriptAbsoluteDir? Dying." exit 1 fi if test "x$script_absolute_dir" == "x" then echo "$script_name : empty script path. Dying." exit 1 fi if test -e "$script_absolute_dir/$module.shinc" then # import from script directory . "$script_absolute_dir/$module.shinc" elif test "x${SHELL_LIBRARY_PATH:-notset}" != "xnotset" then # import from the shell script library path # save the separator and use the ':' instead local saved_IFS="$IFS" IFS=':' for path in $SHELL_LIBRARY_PATH do if test -e "$path/$module.shinc" then . "$path/$module.shinc" return fi done # restore the standard separator IFS="$saved_IFS" fi echo "$script_name : Unable to find module $module." exit 1 } ``` you can then import files with the extension .shinc with the following syntax import "AModule/ModuleFile" Which will be searched in SHELL\_LIBRARY\_PATH. As you always import in the global namespace, remember to prefix all your functions and variables with a proper prefix, otherwise you risk name clashes. I use double underscore as the python dot. Also, put this as first thing in your module ``` # avoid double inclusion if test "${BashInclude__imported+defined}" == "defined" then return 0 fi BashInclude__imported=1 ``` **Object oriented programming** In bash, you cannot do object oriented programming, unless you build a quite complex system of allocation of objects (I thought about that. it's feasible, but insane). In practice, you can however do "Singleton oriented programming": you have one instance of each object, and only one. What I do is: i define an object into a module (see the modularization entry). Then I define empty vars (analogous to member variables) an init function (constructor) and member functions, like in this example code ``` # avoid double inclusion if test "${Table__imported+defined}" == "defined" then return 0 fi Table__imported=1 readonly Table__NoException="" readonly Table__ParameterException="Table__ParameterException" readonly Table__MySqlException="Table__MySqlException" readonly Table__NotInitializedException="Table__NotInitializedException" readonly Table__AlreadyInitializedException="Table__AlreadyInitializedException" # an example for module enum constants, used in the mysql table, in this case readonly Table__GENDER_MALE="GENDER_MALE" readonly Table__GENDER_FEMALE="GENDER_FEMALE" # private: prefixed with p_ (a bash variable cannot start with _) p_Table__mysql_exec="" # will contain the executed mysql command p_Table__initialized=0 function Table__init { # @description init the module with the database parameters # @param $1 the mysql config file # @exception Table__NoException, Table__ParameterException EXCEPTION="" EXCEPTION_MSG="" EXCEPTION_FUNC="" RESULT="" if test $p_Table__initialized -ne 0 then EXCEPTION=$Table__AlreadyInitializedException EXCEPTION_MSG="module already initialized" EXCEPTION_FUNC="$FUNCNAME" return 1 fi local config_file="$1" # yes, I am aware that I could put default parameters and other niceties, but I am lazy today if test "x$config_file" = "x"; then EXCEPTION=$Table__ParameterException EXCEPTION_MSG="missing parameter config file" EXCEPTION_FUNC="$FUNCNAME" return 1 fi p_Table__mysql_exec="mysql --defaults-file=$config_file --silent --skip-column-names -e " # mark the module as initialized p_Table__initialized=1 EXCEPTION=$Table__NoException EXCEPTION_MSG="" EXCEPTION_FUNC="" return 0 } function Table__getName() { # @description gets the name of the person # @param $1 the row identifier # @result the name EXCEPTION="" EXCEPTION_MSG="" EXCEPTION_FUNC="" RESULT="" if test $p_Table__initialized -eq 0 then EXCEPTION=$Table__NotInitializedException EXCEPTION_MSG="module not initialized" EXCEPTION_FUNC="$FUNCNAME" return 1 fi id=$1 if test "x$id" = "x"; then EXCEPTION=$Table__ParameterException EXCEPTION_MSG="missing parameter identifier" EXCEPTION_FUNC="$FUNCNAME" return 1 fi local name=`$p_Table__mysql_exec "SELECT name FROM table WHERE id = '$id'"` if test $? != 0 ; then EXCEPTION=$Table__MySqlException EXCEPTION_MSG="unable to perform select" EXCEPTION_FUNC="$FUNCNAME" return 1 fi RESULT=$name EXCEPTION=$Table__NoException EXCEPTION_MSG="" EXCEPTION_FUNC="" return 0 } ``` **Trapping and handling signals** I found this useful to catch and handle exceptions. ``` function Main__interruptHandler() { # @description signal handler for SIGINT echo "SIGINT caught" exit } function Main__terminationHandler() { # @description signal handler for SIGTERM echo "SIGTERM caught" exit } function Main__exitHandler() { # @description signal handler for end of the program (clean or unclean). # probably redundant call, we already call the cleanup in main. exit } trap Main__interruptHandler INT trap Main__terminationHandler TERM trap Main__exitHandler EXIT function Main__main() { # body } # catch signals and exit trap exit INT TERM EXIT Main__main "$@" ``` **Hints and tips** If something does not work for some reason, try to reorder the code. Order is important and not always intuitive. do not even consider working with tcsh. it does not support functions, and it's horrible in general. Hope it helps, although please note. If you have to use the kind of things I wrote here, it means that your problem is too complex to be solved with shell. use another language. I had to use it due to human factors and legacy.
78,536
<p>I want to do something like:</p> <pre><code>MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); </code></pre> <p>And then make changes to the new object that are not reflected in the original object.</p> <p>I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation.</p> <p>How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?</p>
[ { "answer_id": 78552, "author": "HappyDude", "author_id": 14266, "author_profile": "https://Stackoverflow.com/users/14266", "pm_score": 4, "selected": false, "text": "<p>In general, you implement the ICloneable interface and implement Clone yourself.\nC# objects have a built-in Memberwis...
2008/09/17
[ "https://Stackoverflow.com/questions/78536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ]
I want to do something like: ``` MyObject myObj = GetMyObj(); // Create and fill a new object MyObject newObj = myObj.Clone(); ``` And then make changes to the new object that are not reflected in the original object. I don't often need this functionality, so when it's been necessary, I've resorted to creating a new object and then copying each property individually, but it always leaves me with the feeling that there is a better or more elegant way of handling the situation. How can I clone or deep copy an object so that the cloned object can be modified without any changes being reflected in the original object?
Whereas one approach is to implement the [`ICloneable`](http://msdn.microsoft.com/en-us/library/system.icloneable.aspx) interface (described [here](https://stackoverflow.com/questions/78536/cloning-objects-in-c/78568#78568), so I won't regurgitate), here's a nice deep clone object copier I found on [The Code Project](http://www.codeproject.com/Articles/23832/Implementing-Deep-Cloning-via-Serializing-objects) a while ago and incorporated it into our code. As mentioned elsewhere, it requires your objects to be serializable. ``` using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; /// <summary> /// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx /// Provides a method for performing a deep copy of an object. /// Binary Serialization is used to perform the copy. /// </summary> public static class ObjectCopier { /// <summary> /// Perform a deep copy of the object via serialization. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>A deep copy of the object.</returns> public static T Clone<T>(T source) { if (!typeof(T).IsSerializable) { throw new ArgumentException("The type must be serializable.", nameof(source)); } // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(source, null)) return default; using var Stream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, source); stream.Seek(0, SeekOrigin.Begin); return (T)formatter.Deserialize(stream); } } ``` The idea is that it serializes your object and then deserializes it into a fresh object. The benefit is that you don't have to concern yourself about cloning everything when an object gets too complex. In case of you prefer to use the new [extension methods](http://en.wikipedia.org/wiki/Extension_method) of C# 3.0, change the method to have the following signature: ``` public static T Clone<T>(this T source) { // ... } ``` Now the method call simply becomes `objectBeingCloned.Clone();`. **EDIT** (January 10 2015) Thought I'd revisit this, to mention I recently started using (Newtonsoft) Json to do this, it [should be](http://maxondev.com/serialization-performance-comparison-c-net-formats-frameworks-xmldatacontractserializer-xmlserializer-binaryformatter-json-newtonsoft-servicestack-text/) lighter, and avoids the overhead of [Serializable] tags. (**NB** @atconway has pointed out in the comments that private members are not cloned using the JSON method) ``` /// <summary> /// Perform a deep Copy of the object, using Json as a serialization method. NOTE: Private members are not cloned using this method. /// </summary> /// <typeparam name="T">The type of object being copied.</typeparam> /// <param name="source">The object instance to copy.</param> /// <returns>The copied object.</returns> public static T CloneJson<T>(this T source) { // Don't serialize a null object, simply return the default for that object if (ReferenceEquals(source, null)) return default; // initialize inner objects individually // for example in default constructor some list property initialized with some values, // but in 'source' these items are cleaned - // without ObjectCreationHandling.Replace default constructor values will be added to result var deserializeSettings = new JsonSerializerSettings {ObjectCreationHandling = ObjectCreationHandling.Replace}; return JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(source), deserializeSettings); } ```
78,548
<p>What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules?</p> <p>Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.</p>
[ { "answer_id": 78571, "author": "Ian P", "author_id": 10853, "author_profile": "https://Stackoverflow.com/users/10853", "pm_score": 3, "selected": false, "text": "<p>Abstract controllers are a good idea, and I haven't found a better way. I'm interested to see what other people have done,...
2008/09/17
[ "https://Stackoverflow.com/questions/78548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/347616/" ]
What is your way of passing data to Master Page (using ASP.NET MVC) without breaking MVC rules? Personally, I prefer to code abstract controller (base controller) or base class which is passed to all views.
If you prefer your views to have strongly typed view data classes this might work for you. Other solutions are probably more *correct* but this is a nice balance between design and practicality IMHO. The master page takes a strongly typed view data class containing only information relevant to it: ``` public class MasterViewData { public ICollection<string> Navigation { get; set; } } ``` Each view using that master page takes a strongly typed view data class containing its information and deriving from the master pages view data: ``` public class IndexViewData : MasterViewData { public string Name { get; set; } public float Price { get; set; } } ``` Since I don't want individual controllers to know anything about putting together the master pages data I encapsulate that logic into a factory which is passed to each controller: ``` public interface IViewDataFactory { T Create<T>() where T : MasterViewData, new() } public class ProductController : Controller { public ProductController(IViewDataFactory viewDataFactory) ... public ActionResult Index() { var viewData = viewDataFactory.Create<ProductViewData>(); viewData.Name = "My product"; viewData.Price = 9.95; return View("Index", viewData); } } ``` Inheritance matches the master to view relationship well but when it comes to rendering partials / user controls I will compose their view data into the pages view data, e.g. ``` public class IndexViewData : MasterViewData { public string Name { get; set; } public float Price { get; set; } public SubViewData SubViewData { get; set; } } <% Html.RenderPartial("Sub", Model.SubViewData); %> ``` *This is example code only and is not intended to compile as is. Designed for ASP.Net MVC 1.0.*
78,592
<p>In perl one would simply do the following to store and iterate over a list of names</p> <pre><code>my @fruit = (apple, orange, kiwi); foreach (@fruit) { print $_; } </code></pre> <p>What would the equivalent be in bash?</p>
[ { "answer_id": 78600, "author": "JBB", "author_id": 12332, "author_profile": "https://Stackoverflow.com/users/12332", "pm_score": 2, "selected": false, "text": "<pre>\nfor i in apple orange kiwi\ndo\n echo $i\ndone\n</pre>\n" }, { "answer_id": 78601, "author": "emk", "au...
2008/09/17
[ "https://Stackoverflow.com/questions/78592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10747/" ]
In perl one would simply do the following to store and iterate over a list of names ``` my @fruit = (apple, orange, kiwi); foreach (@fruit) { print $_; } ``` What would the equivalent be in bash?
bash (unlike POSIX sh) supports arrays: ``` fruits=(apple orange kiwi "dried mango") for fruit in "${fruits[@]}"; do echo "${fruit}" done ``` This has the advantage that array elements may contain spaces or other members of $IFS; as long as they were correctly inserted as separate elements, they are read out the same way.
78,717
<p>I have a 'foreach' macro I use frequently in C++ that works for most STL containers:</p> <pre><code>#define foreach(var, container) \ for(typeof((container).begin()) var = (container).begin(); \ var != (container).end(); \ ++var) </code></pre> <p>(Note that 'typeof' is a gcc extension.) It is used like this:</p> <pre><code>std::vector&lt; Blorgus &gt; blorgi = ...; foreach(blorgus, blorgi) { blorgus-&gt;draw(); } </code></pre> <p>I would like to make something similar that iterates over a map's values. Call it "foreach_value", perhaps. So instead of writing</p> <pre><code>foreach(pair, mymap) { pair-&gt;second-&gt;foo(); } </code></pre> <p>I would write</p> <pre><code>foreach_value(v, mymap) { v.foo(); } </code></pre> <p>I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach_value call, but then it will conflict with other instances of the foreach_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.</p>
[ { "answer_id": 78754, "author": "Tyler", "author_id": 3561, "author_profile": "https://Stackoverflow.com/users/3561", "pm_score": 0, "selected": false, "text": "<p>You could define a template class that takes the type of mymap as a template parameter, and acts like an iterator over the v...
2008/09/17
[ "https://Stackoverflow.com/questions/78717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14528/" ]
I have a 'foreach' macro I use frequently in C++ that works for most STL containers: ``` #define foreach(var, container) \ for(typeof((container).begin()) var = (container).begin(); \ var != (container).end(); \ ++var) ``` (Note that 'typeof' is a gcc extension.) It is used like this: ``` std::vector< Blorgus > blorgi = ...; foreach(blorgus, blorgi) { blorgus->draw(); } ``` I would like to make something similar that iterates over a map's values. Call it "foreach\_value", perhaps. So instead of writing ``` foreach(pair, mymap) { pair->second->foo(); } ``` I would write ``` foreach_value(v, mymap) { v.foo(); } ``` I can't come up with a macro that will do this, because it requires declaring two variables: the iterator and the value variable ('v', above). I don't know how to do that in the initializer of a for loop, even using gcc extensions. I could declare it just before the foreach\_value call, but then it will conflict with other instances of the foreach\_value macro in the same scope. If I could suffix the current line number to the iterator variable name, it would work, but I don't know how to do that.
You can do this using two loops. The first declares the iterator, with a name which is a function of the container variable (and you can make this uglier if you're worried about conflicts with your own code). The second declares the value variable. ``` #define ci(container) container ## iter #define foreach_value(var, container) \ for (typeof((container).begin()) ci(container) = container.begin(); \ ci(container) != container.end(); ) \ for (typeof(ci(container)->second)* var = &ci(container)->second; \ ci(container) != container.end(); \ (++ci(container) != container.end()) ? \ (var = &ci(container)->second) : var) ``` By using the same loop termination condition, the outer loop only happens once (and if you're lucky, gets optimized away). Also, you avoid calling ->second on the iterator if the map is empty. That's the same reason for the ternary operator in the increment of the inner loop; at the end, we just leave var at the last value, since it won't be referenced again. You could inline ci(container), but I think it makes the macro more readable.
78,723
<p>Considering such code:</p> <pre><code>class ToBeTested { public: void doForEach() { for (vector&lt;Contained&gt;::iterator it = m_contained.begin(); it != m_contained.end(); it++) { doOnce(*it); doTwice(*it); doTwice(*it); } } void doOnce(Contained &amp; c) { // do something } void doTwice(Contained &amp; c) { // do something } // other methods private: vector&lt;Contained&gt; m_contained; } </code></pre> <p>I want to test that if I fill vector with 3 values my functions will be called in proper order and quantity. For example my test can look something like this:</p> <pre><code>tobeTested.AddContained(one); tobeTested.AddContained(two); tobeTested.AddContained(three); BEGIN_PROC_TEST() SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) tobeTested.doForEach() END_PROC_TEST() </code></pre> <p>How do you recommend to test this? Are there any means to do this with CppUnit or GoogleTest frameworks? Maybe some other unit test framework allow to perform such tests?</p> <p>I understand that probably this is impossible without calling any debug functions from these functions, but at least can it be done automatically in some test framework. I don't like to scan trace logs and check their correctness.</p> <p><em>UPD</em>: I'm trying to check not only the <strong>state</strong> of an objects, but also the <strong>execution order</strong> to avoid performance issues on the earliest possible stage (and in general I want to know that my code is executed exactly as I expected).</p>
[ { "answer_id": 78764, "author": "Doug R", "author_id": 3271, "author_profile": "https://Stackoverflow.com/users/3271", "pm_score": 0, "selected": false, "text": "<p>Some mocking frameworks allow you to set up ordered expectations, which lets you say exactly which function calls you expec...
2008/09/17
[ "https://Stackoverflow.com/questions/78723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14535/" ]
Considering such code: ``` class ToBeTested { public: void doForEach() { for (vector<Contained>::iterator it = m_contained.begin(); it != m_contained.end(); it++) { doOnce(*it); doTwice(*it); doTwice(*it); } } void doOnce(Contained & c) { // do something } void doTwice(Contained & c) { // do something } // other methods private: vector<Contained> m_contained; } ``` I want to test that if I fill vector with 3 values my functions will be called in proper order and quantity. For example my test can look something like this: ``` tobeTested.AddContained(one); tobeTested.AddContained(two); tobeTested.AddContained(three); BEGIN_PROC_TEST() SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) SHOULD_BE_CALLED(doOnce, 1) SHOULD_BE_CALLED(doTwice, 2) tobeTested.doForEach() END_PROC_TEST() ``` How do you recommend to test this? Are there any means to do this with CppUnit or GoogleTest frameworks? Maybe some other unit test framework allow to perform such tests? I understand that probably this is impossible without calling any debug functions from these functions, but at least can it be done automatically in some test framework. I don't like to scan trace logs and check their correctness. *UPD*: I'm trying to check not only the **state** of an objects, but also the **execution order** to avoid performance issues on the earliest possible stage (and in general I want to know that my code is executed exactly as I expected).
If you're interested in performance, I recommend that you write a test that measures performance. Check the current time, run the method you're concerned about, then check the time again. Assert that the total time taken is less than some value. The problem with check that methods are called in a certain order is that your code is going to have to change, and you don't want to have to update your tests when that happens. You should focus on testing the *actual requirement* instead of testing the implementation detail that meets that requirement. That said, if you really want to test that your methods are called in a certain order, you'll need to do the following: 1. Move them to another class, call it Collaborator 2. Add an instance of this other class to the ToBeTested class 3. Use a mocking framework to set the instance variable on ToBeTested to be a mock of the Collborator class 4. Call the method under test 5. Use your mocking framework to assert that the methods were called on your mock in the correct order. I'm not a native cpp speaker so I can't comment on which mocking framework you should use, but I see some other commenters have added their suggestions on this front.
78,752
<p>I have read that using database keys in a URL is a bad thing to do.</p> <p>For instance,</p> <p>My table has 3 fields: <code>ID:int</code>, <code>Title:nvarchar(5)</code>, <code>Description:Text</code></p> <p>I want to create a page that displays a record. Something like ...</p> <pre><code>http://server/viewitem.aspx?id=1234 </code></pre> <ol> <li><p>First off, could someone elaborate on why this is a bad thing to do?</p></li> <li><p>and secondly, what are some ways to work around using primary keys in a url?</p></li> </ol>
[ { "answer_id": 78760, "author": "Aaron Jensen", "author_id": 11229, "author_profile": "https://Stackoverflow.com/users/11229", "pm_score": 0, "selected": false, "text": "<p>It's a bit pedantic at times, but you want to use a unique business identifier for things rather than the surrogate...
2008/09/17
[ "https://Stackoverflow.com/questions/78752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14396/" ]
I have read that using database keys in a URL is a bad thing to do. For instance, My table has 3 fields: `ID:int`, `Title:nvarchar(5)`, `Description:Text` I want to create a page that displays a record. Something like ... ``` http://server/viewitem.aspx?id=1234 ``` 1. First off, could someone elaborate on why this is a bad thing to do? 2. and secondly, what are some ways to work around using primary keys in a url?
I think it's perfectly reasonable to use primary keys in the URL. Some considerations, however: 1) Avoid SQL injection attacks. If you just blindly accept the value of the id URL parameter and pass it into the DB, you are at risk. Make sure you sanitise the input so that it matches whatever format of key you have (e.g. strip any non-numeric characters). 2) SEO. It helps if your URL contains some context about the item (e.g. "big fluffy rabbit" rather than 1234). This helps search engines see that your page is relevant. It can also be useful for your users (I can tell from my browser history which record is which without having to remember a number).
78,757
<p>How can I programmatically make a query in MS Access default to landscape when printed, specifically when viewing it as a PivotChart? I'm currently attempting this in MS Access 2003, but would like to see a solution for any version.</p>
[ { "answer_id": 79635, "author": "ahockley", "author_id": 8209, "author_profile": "https://Stackoverflow.com/users/8209", "pm_score": 3, "selected": true, "text": "<p>The following function should do the trick:</p>\n\n<pre><code>Function SetLandscape()\n Application.Printer.Orientation ...
2008/09/17
[ "https://Stackoverflow.com/questions/78757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
How can I programmatically make a query in MS Access default to landscape when printed, specifically when viewing it as a PivotChart? I'm currently attempting this in MS Access 2003, but would like to see a solution for any version.
The following function should do the trick: ``` Function SetLandscape() Application.Printer.Orientation = acPRORLandscape End Function ``` Should be able to call this from the autoexec function to ensure it always runs.
78,799
<p>What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right?</p> <p>I have code that looks something like this:</p> <pre><code>class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) </code></pre> <p>But now I'm wondering if there's a situation where nesting would be better. Something like:</p> <pre><code>class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) </code></pre>
[ { "answer_id": 78858, "author": "dF.", "author_id": 3002, "author_profile": "https://Stackoverflow.com/users/3002", "pm_score": 8, "selected": true, "text": "<p>You might want to do this when the \"inner\" class is a one-off, which will never be used outside the <em>definition</em> of th...
2008/09/17
[ "https://Stackoverflow.com/questions/78799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
What I'm talking about here are nested classes. Essentially, I have two classes that I'm modeling. A DownloadManager class and a DownloadThread class. The obvious OOP concept here is composition. However, composition doesn't necessarily mean nesting, right? I have code that looks something like this: ``` class DownloadThread: def foo(self): pass class DownloadManager(): def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadThread()) ``` But now I'm wondering if there's a situation where nesting would be better. Something like: ``` class DownloadManager(): class DownloadThread: def foo(self): pass def __init__(self): dwld_threads = [] def create_new_thread(): dwld_threads.append(DownloadManager.DownloadThread()) ```
You might want to do this when the "inner" class is a one-off, which will never be used outside the *definition* of the outer class. For example to use a metaclass, it's sometimes handy to do ``` class Foo(object): class __metaclass__(type): .... ``` instead of defining a metaclass separately, if you're only using it once. The only other time I've used nested classes like that, I used the outer class only as a namespace to group a bunch of closely related classes together: ``` class Group(object): class cls1(object): ... class cls2(object): ... ``` Then from another module, you can import Group and refer to these as Group.cls1, Group.cls2 etc. However one might argue that you can accomplish exactly the same (perhaps in a less confusing way) by using a module.
78,801
<p>Running a rails site right now using SQLite3.</p> <p>About once every 500 requests or so, I get a</p> <p>ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:...</p> <p>What's the way to fix this that would be minimally invasive to my code?</p> <p>I'm using SQLLite at the moment because you can store the DB in source control which makes backing up natural and you can push changes out very quickly. However, it's obviously not really set up for concurrent access. I'll migrate over to MySQL tomorrow morning.</p>
[ { "answer_id": 78817, "author": "Sargun Dhillon", "author_id": 10432, "author_profile": "https://Stackoverflow.com/users/10432", "pm_score": -1, "selected": false, "text": "<p>I believe this happens when a transaction times out. You really should be using a \"real\" database. Something l...
2008/09/17
[ "https://Stackoverflow.com/questions/78801", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559/" ]
Running a rails site right now using SQLite3. About once every 500 requests or so, I get a ActiveRecord::StatementInvalid (SQLite3::BusyException: database is locked:... What's the way to fix this that would be minimally invasive to my code? I'm using SQLLite at the moment because you can store the DB in source control which makes backing up natural and you can push changes out very quickly. However, it's obviously not really set up for concurrent access. I'll migrate over to MySQL tomorrow morning.
By default, sqlite returns immediatly with a blocked, busy error if the database is busy and locked. You can ask for it to wait and keep trying for a while before giving up. This usually fixes the problem, unless you do have 1000s of threads accessing your db, when I agree sqlite would be inappropriate. ``` // set SQLite to wait and retry for up to 100ms if database locked sqlite3_busy_timeout( db, 100 ); ```
78,826
<p>How do you use <code>gen_udp</code> in Erlang to do <a href="https://en.wikipedia.org/wiki/Multicast" rel="nofollow noreferrer">multicasting</a>? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.</p>
[ { "answer_id": 78886, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 0, "selected": false, "text": "<p><strong>Multicast is specified by IP Address</strong></p>\n\n<p>It's the same in erlang as for all languages. The IP ...
2008/09/17
[ "https://Stackoverflow.com/questions/78826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10432/" ]
How do you use `gen_udp` in Erlang to do [multicasting](https://en.wikipedia.org/wiki/Multicast)? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.
Here is example code on how to listen in on Bonjour / Zeroconf traffic. ``` -module(zcclient). -export([open/2,start/0]). -export([stop/1,receiver/0]). open(Addr,Port) -> {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]), inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]), S. close(S) -> gen_udp:close(S). start() -> S=open({224,0,0,251},5353), Pid=spawn(?MODULE,receiver,[]), gen_udp:controlling_process(S,Pid), {S,Pid}. stop({S,Pid}) -> close(S), Pid ! stop. receiver() -> receive {udp, _Socket, IP, InPortNo, Packet} -> io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]), receiver(); stop -> true; AnythingElse -> io:format("RECEIVED: ~p~n",[AnythingElse]), receiver() end. ```