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
58,280
<p>Is it possible to use an UnhandledException Handler in a Windows Service?</p> <p>Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn’t achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points:</p> <pre> <code> Protected Overrides Sub OnStart(ByVal args() As String) ' Add code here to start your service. This method should set things ' in motion so your service can do its work. Try MyServiceComponent.Start() Catch ex As Exception 'call into our exception handler MyExceptionHandlingComponent.ManuallyHandleException (ex) 'zero is the default ExitCode for a successfull exit, so if we set it to non-zero ExitCode = -1 'So, we use Environment.Exit, it seems to be the most appropriate thing to use 'we pass an exit code here as well, just in case. System.Environment.Exit(-1) End Try End Sub </code> </pre> <p>Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing?</p>
[ { "answer_id": 58408, "author": "Garo Yeriazarian", "author_id": 2655, "author_profile": "https://Stackoverflow.com/users/2655", "pm_score": 2, "selected": false, "text": "<p>You can subscribe to the <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.as...
2008/09/12
[ "https://Stackoverflow.com/questions/58280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6042/" ]
Is it possible to use an UnhandledException Handler in a Windows Service? Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn’t achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points: ``` Protected Overrides Sub OnStart(ByVal args() As String) ' Add code here to start your service. This method should set things ' in motion so your service can do its work. Try MyServiceComponent.Start() Catch ex As Exception 'call into our exception handler MyExceptionHandlingComponent.ManuallyHandleException (ex) 'zero is the default ExitCode for a successfull exit, so if we set it to non-zero ExitCode = -1 'So, we use Environment.Exit, it seems to be the most appropriate thing to use 'we pass an exit code here as well, just in case. System.Environment.Exit(-1) End Try End Sub ``` Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing?
Ok, I’ve done a little more research into this now. When you create a windows service in .Net, you create a class that inherits from System.ServiceProcess.ServiceBase (In VB this is hidden in the .Designer.vb file). You then override the OnStart and OnStop function, and OnPause and OnContinue if you choose to. These methods are invoked from within the base class so I did a little poking around with reflector. OnStart is invoked by a method in System.ServiceProcess.ServiceBase called ServiceQueuedMainCallback. The vesion on my machine "System.ServiceProcess, Version=2.0.0.0" decompiles like this: ``` Private Sub ServiceQueuedMainCallback(ByVal state As Object) Dim args As String() = DirectCast(state, String()) Try Me.OnStart(args) Me.WriteEventLogEntry(Res.GetString("StartSuccessful")) Me.status.checkPoint = 0 Me.status.waitHint = 0 Me.status.currentState = 4 Catch exception As Exception Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { exception.ToString }), EventLogEntryType.Error) Me.status.currentState = 1 Catch obj1 As Object Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { String.Empty }), EventLogEntryType.Error) Me.status.currentState = 1 End Try Me.startCompletedSignal.Set End Sub ``` So because Me.OnStart(args) is called from within the Try portion of a Try Catch block I assume that anything that happens within the OnStart method is effectively wrapped by that Try Catch block and therefore any exceptions that occur aren't technically unhandled as they are actually handled in the ServiceQueuedMainCallback Try Catch. So CurrentDomain.UnhandledException never actually happens at least during the startup routine. The other 3 entry points (OnStop, OnPause and OnContinue) are all called from the base class in a similar way. So I ‘think’ that explains why my Exception Handling component can’t catch UnhandledException on Start and Stop, but I’m not sure if it explains why timers that are setup in OnStart can’t cause an UnhandledException when they fire.
58,305
<p>Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?</p>
[ { "answer_id": 58326, "author": "David Citron", "author_id": 5309, "author_profile": "https://Stackoverflow.com/users/5309", "pm_score": 9, "selected": true, "text": "<p>Believe it or not, you can actually use <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScre...
2008/09/12
[ "https://Stackoverflow.com/questions/58305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?
Believe it or not, you can actually use [`java.awt.Robot`](http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)) to "create an image containing pixels read from the screen." You can then write that image to a file on disk. I just tried it, and the whole thing ends up like: ``` Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage capture = new Robot().createScreenCapture(screenRect); ImageIO.write(capture, "bmp", new File(args[0])); ``` NOTE: This will only capture the primary monitor. See [GraphicsConfiguration](http://java.sun.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html) for multi-monitor support.
58,306
<p>I am trying to determine the best time efficient algorithm to accomplish the task described below.</p> <p>I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges.</p> <p>All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set).</p> <p>I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only).</p> <p>Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles).</p> <p>For example:</p> <pre> If I have the following records: A, B, C, D, E and the following represents the connections: (A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E), (C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E) [where (A,B) means record A connects to record B] </pre> <p>If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E.</p> <pre> All paths connecting B to E: B->E B->F->E B->F->C->E B->A->C->E B->A->C->F->E </pre> <p>This is an example, in practice I may have sets containing hundreds of thousands of records.</p>
[ { "answer_id": 58321, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I have solved a similar problem to this recently, instead of all solutions I was only interested in the shortest.</p>\n\n<p>...
2008/09/12
[ "https://Stackoverflow.com/questions/58306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3534/" ]
I am trying to determine the best time efficient algorithm to accomplish the task described below. I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges. All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set). I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only). Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles). For example: ``` If I have the following records: A, B, C, D, E and the following represents the connections: (A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E), (C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E) [where (A,B) means record A connects to record B] ``` If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E. ``` All paths connecting B to E: B->E B->F->E B->F->C->E B->A->C->E B->A->C->F->E ``` This is an example, in practice I may have sets containing hundreds of thousands of records.
It appears that this can be accomplished with a depth-first search of the graph. **The depth-first search will find all non-cyclical paths between two nodes.** This algorithm should be very fast and scale to large graphs (The graph data structure is sparse so it only uses as much memory as it needs to). I noticed that the graph you specified above has only one edge that is directional (B,E). Was this a typo or is it really a directed graph? This solution works regardless. Sorry I was unable to do it in C, I'm a bit weak in that area. I expect that you will be able to translate this Java code without too much trouble though. **Graph.java:** ```java import java.util.HashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; public class Graph { private Map<String, LinkedHashSet<String>> map = new HashMap(); public void addEdge(String node1, String node2) { LinkedHashSet<String> adjacent = map.get(node1); if(adjacent==null) { adjacent = new LinkedHashSet(); map.put(node1, adjacent); } adjacent.add(node2); } public void addTwoWayVertex(String node1, String node2) { addEdge(node1, node2); addEdge(node2, node1); } public boolean isConnected(String node1, String node2) { Set adjacent = map.get(node1); if(adjacent==null) { return false; } return adjacent.contains(node2); } public LinkedList<String> adjacentNodes(String last) { LinkedHashSet<String> adjacent = map.get(last); if(adjacent==null) { return new LinkedList(); } return new LinkedList<String>(adjacent); } } ``` **Search.java:** ```java import java.util.LinkedList; public class Search { private static final String START = "B"; private static final String END = "E"; public static void main(String[] args) { // this graph is directional Graph graph = new Graph(); graph.addEdge("A", "B"); graph.addEdge("A", "C"); graph.addEdge("B", "A"); graph.addEdge("B", "D"); graph.addEdge("B", "E"); // this is the only one-way connection graph.addEdge("B", "F"); graph.addEdge("C", "A"); graph.addEdge("C", "E"); graph.addEdge("C", "F"); graph.addEdge("D", "B"); graph.addEdge("E", "C"); graph.addEdge("E", "F"); graph.addEdge("F", "B"); graph.addEdge("F", "C"); graph.addEdge("F", "E"); LinkedList<String> visited = new LinkedList(); visited.add(START); new Search().depthFirst(graph, visited); } private void depthFirst(Graph graph, LinkedList<String> visited) { LinkedList<String> nodes = graph.adjacentNodes(visited.getLast()); // examine adjacent nodes for (String node : nodes) { if (visited.contains(node)) { continue; } if (node.equals(END)) { visited.add(node); printPath(visited); visited.removeLast(); break; } } for (String node : nodes) { if (visited.contains(node) || node.equals(END)) { continue; } visited.addLast(node); depthFirst(graph, visited); visited.removeLast(); } } private void printPath(LinkedList<String> visited) { for (String node : visited) { System.out.print(node); System.out.print(" "); } System.out.println(); } } ``` Program Output: ```java B E B A C E B A C F E B F E B F C E ```
58,380
<p>The following bit of code catches the EOS Exception</p> <pre><code>using (var reader = new BinaryReader(httpRequestBodyStream)) { try { while (true) { bodyByteList.Add(reader.ReadByte()); } } catch (EndOfStreamException) { } } </code></pre> <p>So why do I still receive first-chance exceptions in my console? </p> <blockquote> <p>A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll</p> </blockquote> <p>Is there a way to hide these first chance exception messages?</p>
[ { "answer_id": 58381, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": -1, "selected": false, "text": "<p>I think the stream is throwing this exception, so your try is scoped to narrow to catch it.</p>\n\n<p>Add a few m...
2008/09/12
[ "https://Stackoverflow.com/questions/58380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
The following bit of code catches the EOS Exception ``` using (var reader = new BinaryReader(httpRequestBodyStream)) { try { while (true) { bodyByteList.Add(reader.ReadByte()); } } catch (EndOfStreamException) { } } ``` So why do I still receive first-chance exceptions in my console? > > A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll > > > Is there a way to hide these first chance exception messages?
The point of "first-chance" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A "second-chance" exception is one that has no appropriate handler. Sometimes you want to catch "first-chance" exceptions because it's important to see what's happening when it's being thrown, even if someone is catching it. There's nothing to be concerned with. This is normal behavior.
58,384
<p>I am facing a problem with .NET generics. The thing I want to do is saving an array of generics types (GraphicsItem):</p> <pre><code>public class GraphicsItem&lt;T&gt; { private T _item; public void Load(T item) { _item = item; } } </code></pre> <p>How can I save such open generic type in an array?</p>
[ { "answer_id": 58401, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "<p>If you want to store heterogeneous GrpahicsItem's i.e. GraphicsItem&lt; X> and GrpahicsItem&lt; Y> you need to derive them fro...
2008/09/12
[ "https://Stackoverflow.com/questions/58384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078/" ]
I am facing a problem with .NET generics. The thing I want to do is saving an array of generics types (GraphicsItem): ``` public class GraphicsItem<T> { private T _item; public void Load(T item) { _item = item; } } ``` How can I save such open generic type in an array?
Implement a non-generic interface and use that: ``` public class GraphicsItem<T> : IGraphicsItem { private T _item; public void Load(T item) { _item = item; } public void SomethingWhichIsNotGeneric(int i) { // Code goes here... } } public interface IGraphicsItem { void SomethingWhichIsNotGeneric(int i); } ``` Then use that interface as the item in the list: ``` var values = new List<IGraphicsItem>(); ```
58,425
<p>I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException".</p> <p>The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception."</p> <p>Here is my app.xaml:</p> <pre><code>&lt;Application x:Class="MyNamespace.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;Application.Resources&gt; &lt;/Application.Resources&gt; &lt;/Application&gt; </code></pre> <p>And here is my app.xaml.cs (exception thrown at "public App()"):</p> <pre><code>public partial class App : Application { public App() { Bootstrapper bootStrapper = new Bootstrapper(); bootStrapper.Run(); } } </code></pre> <p>I have set the "App" class as the startup object in the project.</p> <p>What is going astray?</p>
[ { "answer_id": 58447, "author": "ima", "author_id": 5733, "author_profile": "https://Stackoverflow.com/users/5733", "pm_score": 3, "selected": false, "text": "<p>Do you use .config file? If so, check it for errors. Initialization errors of such sort are often triggered by invalid XML: if...
2008/09/12
[ "https://Stackoverflow.com/questions/58425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148/" ]
I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException". The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception." Here is my app.xaml: ``` <Application x:Class="MyNamespace.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Application.Resources> </Application.Resources> </Application> ``` And here is my app.xaml.cs (exception thrown at "public App()"): ``` public partial class App : Application { public App() { Bootstrapper bootStrapper = new Bootstrapper(); bootStrapper.Run(); } } ``` I have set the "App" class as the startup object in the project. What is going astray?
Thanks @ima, your answer pointed me in the right direction. I was using an app.config file and it contained this: ``` <configuration> <startup> <supportedRuntime version="v2.0.50727" sku="Client"/> </startup> <configSections> <section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/> </configSections> <modules> <module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/> </modules> </configuration> ``` It seems the problem was the <startup> element because when I removed it the application ran fine. I was confused because Visual Studio 2008 added that when I checked the box to utilise the "Client Profile" available in 3.5 SP1. After some mucking about checking and un-checking the box I ended up with a configuration file like this: ``` <configuration> <configSections> <section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/> </configSections> <modules> <module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/> </modules> <startup> <supportedRuntime version="v2.0.50727" sku="Client"/> </startup> </configuration> ``` Which works! I'm not sure why the order of elements in the app.config is important - but it seems it is.
58,429
<p>How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.<p> I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range. <p>For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:</p> <pre><code>select sum(n) from numbers where n between 100 and 200 </code></pre> <p>Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.</p> <p>[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. <a href="https://stackoverflow.com/questions/58429/sql-set-based-range#59657">See below.</a></p>
[ { "answer_id": 58511, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 0, "selected": false, "text": "<p>If using SQL Server 2000 or greater, you could use the <strong>table datatype</strong> to avoid creating a normal or...
2008/09/12
[ "https://Stackoverflow.com/questions/58429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4489/" ]
How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop. I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range. For example, if I had that table I could make a select to find the sum of numbers 100-200 like this: ``` select sum(n) from numbers where n between 100 and 200 ``` Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay. [Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. [See below.](https://stackoverflow.com/questions/58429/sql-set-based-range#59657)
I think the very short answer to your question is to use WITH clauses to generate your own. Unfortunately, the big names in databases don't have built-in queryable number-range pseudo-tables. Or, more generally, easy pure-SQL data generation features. Personally, I think this is a **huge** failing, because if they did it would be possible to move a lot of code that is currently locked up in procedural scripts (T-SQL, PL/SQL, etc.) into pure-SQL, which has a number of benefits to performance and code complexity. So anyway, it sounds like what you need in a general sense is the ability to generate data on the fly. Oracle and T-SQL both support a WITH clause that can be used to do this. They work a little differently in the different DBMS's, and MS calls them "common table expressions", but they are very similar in form. Using these with recursion, you can generate a sequence of numbers or text values fairly easily. Here is what it might look like... In Oracle SQL: ``` WITH digits AS -- Limit recursion by just using it for digits. (SELECT LEVEL - 1 AS num FROM DUAL WHERE LEVEL < 10 CONNECT BY num = (PRIOR num) + 1), numrange AS (SELECT ones.num + (tens.num * 10) + (hundreds.num * 100) AS num FROM digits ones CROSS JOIN digits tens CROSS JOIN digits hundreds WHERE hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed. SELECT -- Some columns and operations FROM numrange -- Join to other data if needed ``` This is admittedly quite verbose. Oracle's recursion functionality is limited. The syntax is clunky, it's not performant, and it is limited to 500 (I think) nested levels. This is why I chose to use recursion only for the first 10 digits, and then cross (cartesian) joins to combine them into actual numbers. I haven't used SQL Server's Common Table Expressions myself, but since they allow self-reference, recursion is MUCH simpler than it is in Oracle. Whether performance is comparable, and what the nesting limits are, I don't know. At any rate, recursion and the WITH clause are very useful tools in creating queries that require on-the-fly generated data sets. Then by querying this data set, doing operations on the values, you can get all sorts of different types of generated data. Aggregations, duplications, combinations, permutations, and so on. You can even use such generated data to aid in rolling up or drilling down into other data. **UPDATE:** I just want to add that, once you start working with data in this way, it opens your mind to new ways of thinking about SQL. It's not just a scripting language. It's a fairly robust data-driven [declarative language](http://en.wikipedia.org/wiki/Declarative_programming_language). Sometimes it's a pain to use because for years it has suffered a dearth of enhancements to aid in reducing the redundancy needed for complex operations. But nonetheless it is very powerful, and a fairly intuitive way to work with data sets as both the target and the driver of your algorithms.
58,431
<p>I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".</p> <p>Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented. When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string). I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).</p> <p>Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?</p>
[ { "answer_id": 58437, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 4, "selected": false, "text": "<p>The most elegant solution i found for problems like this is something like this (in pseudocode)</p>\n\n<pre><code>separato...
2008/09/12
[ "https://Stackoverflow.com/questions/58431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4991/" ]
I have wondered for some time, what a nice, clean solution for joining an array of strings might look like. Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma". Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented. When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string). I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?). Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?
The most elegant solution i found for problems like this is something like this (in pseudocode) ``` separator = "" foreach(item in stringCollection) { concatenatedString += separator + item separator = "," } ``` You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop.
58,457
<p>How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows?</p> <p>For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight.</p>
[ { "answer_id": 58459, "author": "Dane", "author_id": 2929, "author_profile": "https://Stackoverflow.com/users/2929", "pm_score": 3, "selected": false, "text": "<p>You simply need to sum the weights of all candidate rows, then choose a random point within that sum, then select the record ...
2008/09/12
[ "https://Stackoverflow.com/questions/58457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2929/" ]
How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows? For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight.
Dane's answer includes a self joins in a way that introduces a square law. `(n*n/2)` rows after the join where there are n rows in the table. What would be more ideal is to be able to just parse the table once. ``` DECLARE @id int, @weight_sum int, @weight_point int DECLARE @table TABLE (id int, weight int) INSERT INTO @table(id, weight) VALUES(1, 50) INSERT INTO @table(id, weight) VALUES(2, 25) INSERT INTO @table(id, weight) VALUES(3, 25) SELECT @weight_sum = SUM(weight) FROM @table SELECT @weight_point = FLOOR(((@weight_sum - 1) * RAND() + 1)) SELECT @id = CASE WHEN @weight_point < 0 THEN @id ELSE [table].id END, @weight_point = @weight_point - [table].weight FROM @table [table] ORDER BY [table].Weight DESC ``` This will go through the table, setting `@id` to each record's `id` value while at the same time decrementing `@weight` point. Eventually, the `@weight_point` will go negative. This means that the `SUM` of all preceding weights is greater than the randomly chosen target value. This is the record we want, so from that point onwards we set `@id` to itself (ignoring any IDs in the table). This runs through the table just once, but does have to run through the entire table even if the chosen value is the first record. Because the average position is half way through the table (and less if ordered by ascending weight) writing a loop could possibly be faster... (Especially if the weightings are in common groups): ``` DECLARE @id int, @weight_sum int, @weight_point int, @next_weight int, @row_count int DECLARE @table TABLE (id int, weight int) INSERT INTO @table(id, weight) VALUES(1, 50) INSERT INTO @table(id, weight) VALUES(2, 25) INSERT INTO @table(id, weight) VALUES(3, 25) SELECT @weight_sum = SUM(weight) FROM @table SELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0) SELECT @next_weight = MAX(weight) FROM @table SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight SET @weight_point = @weight_point - (@next_weight * @row_count) WHILE (@weight_point > 0) BEGIN SELECT @next_weight = MAX(weight) FROM @table WHERE weight < @next_weight SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight SET @weight_point = @weight_point - (@next_weight * @row_count) END -- # Once the @weight_point is less than 0, we know that the randomly chosen record -- # is in the group of records WHERE [table].weight = @next_weight SELECT @row_count = FLOOR(((@row_count - 1) * RAND() + 1)) SELECT @id = CASE WHEN @row_count < 0 THEN @id ELSE [table].id END, @row_count = @row_count - 1 FROM @table [table] WHERE [table].weight = @next_weight ORDER BY [table].Weight DESC ```
58,482
<p>I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:</p> <pre><code>foo = ["goo", "baz"] </code></pre> <p>How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?</p> <p>Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:</p> <pre><code> [foo, goo, bar].each { |param| if param.class != Array puts "param_name wasn't an Array. It was a/an #{param.class}" return "Error: param_name wasn't an Array" end } </code></pre> <p>My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala <a href="https://stackoverflow.com/questions/58482/ruby-get-a-variables-name#58870">dbr's answer</a>) </p>
[ { "answer_id": 58492, "author": "Josh Moore", "author_id": 5004, "author_profile": "https://Stackoverflow.com/users/5004", "pm_score": 2, "selected": false, "text": "<p>I do not know of any way to get a local variable name. But, you can use the <code>instance_variables</code> method, th...
2008/09/12
[ "https://Stackoverflow.com/questions/58482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/422/" ]
I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet: ``` foo = ["goo", "baz"] ``` How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)? Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this: ``` [foo, goo, bar].each { |param| if param.class != Array puts "param_name wasn't an Array. It was a/an #{param.class}" return "Error: param_name wasn't an Array" end } ``` My question is then: Can I replace the instances of 'param\_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala [dbr's answer](https://stackoverflow.com/questions/58482/ruby-get-a-variables-name#58870))
What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names: ``` ["foo", "goo", "bar"].each { |param_name| param = eval(param_name) if param.class != Array puts "#{param_name} wasn't an Array. It was a/an #{param.class}" return "Error: #{param_name} wasn't an Array" end } ``` If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add "rescue nil" to the end of the "param = ..." line to keep the eval from throwing an exception...
58,513
<p>How do I Unit Test a MVC redirection?</p> <pre><code>public ActionResult Create(Product product) { _productTask.Save(product); return RedirectToAction("Success"); } public ActionResult Success() { return View(); } </code></pre> <p>Is <a href="http://www.ayende.com/Blog/archive/2007/12/13/Dont-like-visibility-levels-change-that.aspx" rel="nofollow noreferrer">Ayende's</a> approach still the best way to go, with preview 5:</p> <pre><code> public static void RenderView(this Controller self, string action) { typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} ); } </code></pre> <p>Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable.</p>
[ { "answer_id": 58789, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>You can assert on the ActionResult that is returned, you'll need to cast it to the appropriate type but it does allow you t...
2008/09/12
[ "https://Stackoverflow.com/questions/58513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/230/" ]
How do I Unit Test a MVC redirection? ``` public ActionResult Create(Product product) { _productTask.Save(product); return RedirectToAction("Success"); } public ActionResult Success() { return View(); } ``` Is [Ayende's](http://www.ayende.com/Blog/archive/2007/12/13/Dont-like-visibility-levels-change-that.aspx) approach still the best way to go, with preview 5: ``` public static void RenderView(this Controller self, string action) { typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} ); } ``` Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable.
``` [TestFixture] public class RedirectTester { [Test] public void Should_redirect_to_success_action() { var controller = new RedirectController(); var result = controller.Index() as RedirectToRouteResult; Assert.That(result, Is.Not.Null); Assert.That(result.Values["action"], Is.EqualTo("success")); } } public class RedirectController : Controller { public ActionResult Index() { return RedirectToAction("success"); } } ```
58,517
<p>Is there a way to combine Enums in VB.net?</p>
[ { "answer_id": 58524, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 0, "selected": false, "text": "<p>If you taking about using enum flags() there is a good article <a href=\"http://www.codeguru.com/vb/sample_chapter/article.ph...
2008/09/12
[ "https://Stackoverflow.com/questions/58517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
Is there a way to combine Enums in VB.net?
I believe what you want is a flag type enum. You need to add the Flags attribute to the top of the enum, and then you can combine enums with the 'Or' keyword. Like this: ``` <Flags()> _ Enum CombinationEnums As Integer HasButton = 1 TitleBar = 2 [ReadOnly] = 4 ETC = 8 End Enum ``` **Note:** The numbers to the right are always twice as big (powers of 2) - this is needed to be able to separate the individual flags that have been set. Combine the desired flags using the Or keyword: ``` Dim settings As CombinationEnums settings = CombinationEnums.TitleBar Or CombinationEnums.Readonly ``` This sets TitleBar and Readonly into the enum To check what's been set: ``` If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then Window.TitleBar = True End If ```
58,538
<p>I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.</p> <p>Does anyone know the best way to do this using the WiX framework.</p>
[ { "answer_id": 58686, "author": "Paul Lalonde", "author_id": 5782, "author_profile": "https://Stackoverflow.com/users/5782", "pm_score": 7, "selected": true, "text": "<p>Wix has out-of-the-box support for creating event log sources.</p>\n\n<p>Assuming you use Wix 3, you first need to add...
2008/09/12
[ "https://Stackoverflow.com/questions/58538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5182/" ]
I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation. Does anyone know the best way to do this using the WiX framework.
Wix has out-of-the-box support for creating event log sources. Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component : ``` <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension"> <Component ...> ... <util:EventSource Log="Application" Name="*source name*" EventMessageFile="*path to message file*"/> ... </Component> ``` If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file.
58,540
<p>When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error:</p> <blockquote> <p>Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable.<br> ADDITIONAL INFORMATION:<br> Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle) </p> </blockquote> <p>I have tried following the suggestion here but don't quite understand what is required:<a href="http://microsoftdw.blogspot.com/2005/11/parameterized-queries-against-oracle.html" rel="noreferrer">Parameterized queries against Oracle</a></p> <p>Any ideas?</p>
[ { "answer_id": 59116, "author": "Rich Lawrence", "author_id": 1281, "author_profile": "https://Stackoverflow.com/users/1281", "pm_score": 5, "selected": true, "text": "<p>To expand on the link given in the question:</p>\n\n<ol>\n<li>Create a package variable</li>\n<li>Double click on the...
2008/09/12
[ "https://Stackoverflow.com/questions/58540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1281/" ]
When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error: > > Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable. > > ADDITIONAL INFORMATION: > > Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle) > > > I have tried following the suggestion here but don't quite understand what is required:[Parameterized queries against Oracle](http://microsoftdw.blogspot.com/2005/11/parameterized-queries-against-oracle.html) Any ideas?
To expand on the link given in the question: 1. Create a package variable 2. Double click on the package variable name. (This allows you to access the properties of the variable) 3. Set the property 'EvaluateAsExpression' to true 4. Enter the query in the expression builder. 5. Set the OLE DB source query to SQL Command from Variable The expression builder can dynamically create expressions using variable to create 'parametised queries'. So the following 'normal' query: ``` select * from book where book.BOOK_ID = ? ``` Can be written in the expression builder as: ``` "select * from book where book.BOOK_ID = " + @[User::BookID] ``` You can then do null handling and data conversion using the expression builder.
58,543
<p>I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an <code>&lt;iframe&gt;</code>.</p> <p>Easy: just set <code>height</code> and <code>width</code> to <code>100%</code>! Except, it doesn't work.</p> <p>I did find out about setting <code>frameborder</code> to <code>0</code>, so it at least <em>looks</em> like part of the site, but I'd prefer not to have an ugly scrollbar <em>inside</em> a page that allready has one.</p> <p>Do you know of any tricks to do this?</p> <p><strong>EDIT:</strong> I think I need to clarify my question somewhat:</p> <ul> <li>the company CMS displays the fluff and stuff for our whole website</li> <li>most pages created through the CMS</li> <li>my application isn't, but they will let me embedd it in an <code>&lt;iframe&gt;</code></li> <li>I have no control over the <code>iframe</code>, so any solution must work from the referenced page (according to the <code>src</code> attribute of the <code>iframe</code> tag)</li> <li>the CMS displays a footer, so setting the height to 1 million pixels is not a good idea</li> </ul> <p>Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible...</p> <p>This technique seems to work (<a href="http://bytes.com/forum/thread91876.html" rel="noreferrer">gleaned</a> from several sources, but inspired by the <a href="http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe" rel="noreferrer">link</a> from the accepted answer:</p> <p>In parent document:</p> <pre><code>&lt;iframe id="MyIFRAME" name="MyIFRAME" src="http://localhost/child.html" scrolling="auto" width="100%" frameborder="0"&gt; no iframes supported... &lt;/iframe&gt; </code></pre> <p>In child:</p> <pre><code>&lt;!-- ... --&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; function resizeIframe() { var docHeight; if (typeof document.height != 'undefined') { docHeight = document.height; } else if (document.compatMode &amp;&amp; document.compatMode != 'BackCompat') { docHeight = document.documentElement.scrollHeight; } else if (document.body &amp;&amp; typeof document.body.scrollHeight != 'undefined') { docHeight = document.body.scrollHeight; } // magic number: suppress generation of scrollbars... docHeight += 20; parent.document.getElementById('MyIFRAME').style.height = docHeight + "px"; } parent.document.getElementById('MyIFRAME').onload = resizeIframe; parent.window.onresize = resizeIframe; &lt;/script&gt; &lt;/body&gt; </code></pre> <p><strong>BTW:</strong> This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons...</p>
[ { "answer_id": 58553, "author": "ralfe", "author_id": 340241, "author_profile": "https://Stackoverflow.com/users/340241", "pm_score": 3, "selected": true, "text": "<p>You could either just use a scripting language to include the page into the parent page, other wise, you might want to tr...
2008/09/12
[ "https://Stackoverflow.com/questions/58543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an `<iframe>`. Easy: just set `height` and `width` to `100%`! Except, it doesn't work. I did find out about setting `frameborder` to `0`, so it at least *looks* like part of the site, but I'd prefer not to have an ugly scrollbar *inside* a page that allready has one. Do you know of any tricks to do this? **EDIT:** I think I need to clarify my question somewhat: * the company CMS displays the fluff and stuff for our whole website * most pages created through the CMS * my application isn't, but they will let me embedd it in an `<iframe>` * I have no control over the `iframe`, so any solution must work from the referenced page (according to the `src` attribute of the `iframe` tag) * the CMS displays a footer, so setting the height to 1 million pixels is not a good idea Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible... This technique seems to work ([gleaned](http://bytes.com/forum/thread91876.html) from several sources, but inspired by the [link](http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe) from the accepted answer: In parent document: ``` <iframe id="MyIFRAME" name="MyIFRAME" src="http://localhost/child.html" scrolling="auto" width="100%" frameborder="0"> no iframes supported... </iframe> ``` In child: ``` <!-- ... --> <body> <script type="text/javascript"> function resizeIframe() { var docHeight; if (typeof document.height != 'undefined') { docHeight = document.height; } else if (document.compatMode && document.compatMode != 'BackCompat') { docHeight = document.documentElement.scrollHeight; } else if (document.body && typeof document.body.scrollHeight != 'undefined') { docHeight = document.body.scrollHeight; } // magic number: suppress generation of scrollbars... docHeight += 20; parent.document.getElementById('MyIFRAME').style.height = docHeight + "px"; } parent.document.getElementById('MyIFRAME').onload = resizeIframe; parent.window.onresize = resizeIframe; </script> </body> ``` **BTW:** This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons...
You could either just use a scripting language to include the page into the parent page, other wise, you might want to try one of these javascript methods: <http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe> <http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html>
58,547
<p>In C++ we acquiring a resource in a constructor and release it in a destructor.</p> <p>So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.</p> <p>AFAIK java classes don't have destructors. So how does one do the resource management in Java.</p> <p>For example:</p> <pre><code>public int foo() { Resource f = new Resource(); DoSomething(f); f.Release(); } </code></pre> <p>How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?</p>
[ { "answer_id": 58552, "author": "qbeuek", "author_id": 5348, "author_profile": "https://Stackoverflow.com/users/5348", "pm_score": 3, "selected": true, "text": "<p>Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand \"using\" statement, but in ...
2008/09/12
[ "https://Stackoverflow.com/questions/58547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1007/" ]
In C++ we acquiring a resource in a constructor and release it in a destructor. So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever. AFAIK java classes don't have destructors. So how does one do the resource management in Java. For example: ``` public int foo() { Resource f = new Resource(); DoSomething(f); f.Release(); } ``` How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?
Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand "using" statement, but in Java you are stuck with: ``` public int foo() { Resource f = new Resource(); try { DoSomething(f); } finally { f.Release(); } } ```
58,554
<p>I'm using Eclipse as my IDE for a C++ project, and I would love for it to tell me where a given symbol is defined and what the parameters are for a function.</p> <p>However, there's a catch: I also use <a href="http://www.lazycplusplus.com/" rel="nofollow noreferrer">Lazy C++</a>, a tool that takes a single source file and generates the .h and the .cpp files. Those .lzz files look like headers, but this tool supports some very mild syntactic benefits, like combining nested namespaces into a qualified name. Additionally, it has some special tags to tell the tool specifically where to put what (in header or in source file).</p> <p>So my typical SourceFile.lzz looks like this:</p> <pre><code>$hdr #include &lt;iosfwd&gt; #include "ProjectA/BaseClass.h" $end $src #include &lt;iostream&gt; #include "ProjectB/OtherClass.h" $end // Forward declarations namespace BigScope::ProjectB { class OtherClass; } namespace BigScope::ProjectA { class MyClass : public ProjectA::BaseClass { void SomeMethod(const ProjectB::OtherClass&amp; Foo) { } } } </code></pre> <p>As you see, it's still recognizable C++, but with a few extras.</p> <p>For some reason, CDT's indexer does not seem to want to index anything, and I don't know what's wrong. In the Indexer View, it shows me an empty tree, but tells me that it has some 15000 symbols and more stuff, none of which I can seem to access.</p> <p>So here's my <strong>question</strong>: how can I make the Indexer output some more information about what it's doing and why it fails when it does so, and can I tweak it more than with just the GUI-accessible options?</p> <p>Thanks,</p> <p>Carl</p>
[ { "answer_id": 59251, "author": "Mike McQuaid", "author_id": 5355, "author_profile": "https://Stackoverflow.com/users/5355", "pm_score": 2, "selected": false, "text": "<p>I'd imagine its one of:</p>\n\n<ul>\n<li><p>Eclipse doesn't want to display non-C++ resources in the tree (I've had p...
2008/09/12
[ "https://Stackoverflow.com/questions/58554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2095/" ]
I'm using Eclipse as my IDE for a C++ project, and I would love for it to tell me where a given symbol is defined and what the parameters are for a function. However, there's a catch: I also use [Lazy C++](http://www.lazycplusplus.com/), a tool that takes a single source file and generates the .h and the .cpp files. Those .lzz files look like headers, but this tool supports some very mild syntactic benefits, like combining nested namespaces into a qualified name. Additionally, it has some special tags to tell the tool specifically where to put what (in header or in source file). So my typical SourceFile.lzz looks like this: ``` $hdr #include <iosfwd> #include "ProjectA/BaseClass.h" $end $src #include <iostream> #include "ProjectB/OtherClass.h" $end // Forward declarations namespace BigScope::ProjectB { class OtherClass; } namespace BigScope::ProjectA { class MyClass : public ProjectA::BaseClass { void SomeMethod(const ProjectB::OtherClass& Foo) { } } } ``` As you see, it's still recognizable C++, but with a few extras. For some reason, CDT's indexer does not seem to want to index anything, and I don't know what's wrong. In the Indexer View, it shows me an empty tree, but tells me that it has some 15000 symbols and more stuff, none of which I can seem to access. So here's my **question**: how can I make the Indexer output some more information about what it's doing and why it fails when it does so, and can I tweak it more than with just the GUI-accessible options? Thanks, Carl
I'd imagine its one of: * Eclipse doesn't want to display non-C++ resources in the tree (I've had problems with this) * You don't have "Preferences > C/C++ > Indexer > Index All Files" enabled. * You want to use the "Full C/C++ Indexer" rather than the "Fast C/C++ Indexer"
58,561
<p>I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?</p> <p>An example :</p> <pre><code>final StringBuilder hql = new StringBuilder(); hql.append( "select bob.id from " ) .append( bob.class.getName() ).append( " bob " ) .append( "where bob.id &gt; 10"); final Query query = session.createQuery( hql.toString() ); return query.list(); </code></pre>
[ { "answer_id": 58624, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 6, "selected": false, "text": "<p>I think you could do that with Projections, something like</p>\n\n<pre><code>Criteria.forClass(bob.class.getName())\n ...
2008/09/12
[ "https://Stackoverflow.com/questions/58561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ? An example : ``` final StringBuilder hql = new StringBuilder(); hql.append( "select bob.id from " ) .append( bob.class.getName() ).append( " bob " ) .append( "where bob.id > 10"); final Query query = session.createQuery( hql.toString() ); return query.list(); ```
I think you could do that with Projections, something like ``` Criteria.forClass(bob.class.getName()) .add(Restrictions.gt("id", 10)) .setProjection(Projections.property("id")) ); ```
58,564
<p>I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug.</p>
[ { "answer_id": 58578, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 1, "selected": false, "text": "<p>A core dump is a copy of the memory the process had access to when crashed. Depending on how the leak is occurring...
2008/09/12
[ "https://Stackoverflow.com/questions/58564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148773/" ]
I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug.
If you have a core file and you have compiled the program with debugging options (-g), you can see where the core was dumped: ``` $ gcc -g -o something something.c $ ./something Segmentation fault (core dumped) $ gdb something core ``` You can use this to do some post-morten debugging. A few gdb commands: bt prints the stack, fr jumps to given stack frame (see the output of bt). Now if you want to see which files are opened at a segmentation fault, just handle the SIGSEGV signal, and in the handler, just dump the contents of the /proc/PID/fd directory (i.e. with system('ls -l /proc/PID/fs') or execv). With these information at hand you can easily find what caused the crash, which files are opened and if the crash and the file descriptor leak are connected.
58,584
<p>Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse?</p> <p>I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions?</p> <p>And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?</p>
[ { "answer_id": 58585, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "<p>Use the visual block command v (or V for whole lines and <kbd>C</kbd>-<kbd>V</kbd> for rectangular blocks). While in vi...
2008/09/12
[ "https://Stackoverflow.com/questions/58584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse? I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions? And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?
Well, first of all, you can set `vim` to work with the mouse, which would allow you to select text just like you would in `Eclipse`. You can also use the Visual selection - `v`, by default. Once selected, you can `yank`, `cut`, etc. As far as commenting out the block, I usually select it with `VISUAL`, then do ``` :'<,'>s/^/# / ``` Replacing the beginning of each line with a `#`. (The `'<` and `'>` markers are the beginning and and of the visual selection.
58,614
<p>I'm developing a multi-threaded app for a Linux embedded platform.</p> <p>At the moment I'm setting the stack size for each thread (via pthread_set_attr) to a fairly large default value. I would like to fine tune that value for each thread to something smaller to reduce my application's memory usage. I could go through the trial and error route of setting each thread's stack size to progressively smaller values until the program crashed, but the application uses ~15 threads each with completely different functionality/attributes so that approach would be extremely time consuming.</p> <p>I would much rather prefer being able to directly measure each thread's stack usage. Is there some utility people can recommend to do this? (For example, I come from a vxWorks background and using the 'ti' command from the vxWorks shell directly gives stats on the stack usage as well as other useful info on the task status.)</p> <p>Thanks</p>
[ { "answer_id": 58628, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 2, "selected": false, "text": "<p>I do not know any good tools but as last resort you could include some code in your application to check it, similar to the f...
2008/09/12
[ "https://Stackoverflow.com/questions/58614", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6089/" ]
I'm developing a multi-threaded app for a Linux embedded platform. At the moment I'm setting the stack size for each thread (via pthread\_set\_attr) to a fairly large default value. I would like to fine tune that value for each thread to something smaller to reduce my application's memory usage. I could go through the trial and error route of setting each thread's stack size to progressively smaller values until the program crashed, but the application uses ~15 threads each with completely different functionality/attributes so that approach would be extremely time consuming. I would much rather prefer being able to directly measure each thread's stack usage. Is there some utility people can recommend to do this? (For example, I come from a vxWorks background and using the 'ti' command from the vxWorks shell directly gives stats on the stack usage as well as other useful info on the task status.) Thanks
Here are two tools that measure (native pthreads) stack usage in Linux applications: * [Valgrind](http://valgrind.org "Valgrind") * [Stackusage](https://github.com/d99kris/stackusage "stackusage") **Valgrind** Usage: ``` valgrind --tool=drd --show-stack-usage=yes PROG ``` Valgrind is a stable and powerful tool, useful not only for measuring stack usage. It may not support all embedded CPU models though. **Stackusage** Usage: ``` stackusage PROG ``` Stackusage is a light-weight tool specifically designed for measuring thread stack usage which should be portable for most embedded Linux platforms equipped with glibc. It is likely not as well-tested or mature as Valgrind/drd at this point. Full disclosure: I'm the author of Stackusage.
58,620
<p>How do I create a button control (with <code>CreateWindow</code> of a <code>BUTTON</code> window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications? I should of course take DPI into account and probably other settings.</p> <blockquote> <p><strong>Remark:</strong> Using <code>USE_CW_DEFAULT</code> for width and height results in a 0, 0 size button, so that's not a solution.</p> </blockquote>
[ { "answer_id": 58636, "author": "Timbo", "author_id": 1810, "author_profile": "https://Stackoverflow.com/users/1810", "pm_score": 3, "selected": false, "text": "<p>This is what MSDN has to say: <a href=\"http://msdn.microsoft.com/en-us/library/ms997619.aspx\" rel=\"noreferrer\">Design Sp...
2008/09/12
[ "https://Stackoverflow.com/questions/58620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5049/" ]
How do I create a button control (with `CreateWindow` of a `BUTTON` window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications? I should of course take DPI into account and probably other settings. > > **Remark:** Using `USE_CW_DEFAULT` for width and height results in a 0, 0 size button, so that's not a solution. > > >
In the perfect, hassle-free world... ------------------------------------ To create a standard size button we would have to do this: ``` LONG units = GetDialogBaseUnits(); m_hButton = CreateWindow(TEXT("BUTTON"), TEXT("Close"), WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, 0, 0, MulDiv(LOWORD(units), 50, 4), MulDiv(HIWORD(units), 14, 8), hwnd, NULL, hInst, NULL); ``` where **50** and **14** are respective DLU dimensions, **4** and **8** are horizontal and vertical dialog template units respectively, based on [`GetDialogBaseUnits()` function](http://msdn.microsoft.com/en-us/library/ms645475(VS.85).aspx) documentation remarks. --- Nothing's perfect ----------------- **BUT** as Anders pointed out, those metrics are based on the system font. If your window uses a shell dialog font or simply anything not making your eyes bleed, you're pretty much on your own. To get your own "dialog" base units, you have to retrieve current text metrics with `GetTextMetrics()` and use character height and average width (`tmHeight` and `tmAveCharWidth` of the `TEXTMETRIC` struct respectively) and translate them with MulDiv by your own, **unless** you are in a dialog, then `MapDialogRect()` will do all the job for you. Note that `tmAveCharWidth` only approximates the actual average character width so it's recommended to use a [`GetTextExtentPoint32()`](http://msdn.microsoft.com/en-us/library/dd144938.aspx) function on an alphabetic character set instead. See: * [How to calculate dialog box units based on the current font in Visual C++](http://support.microsoft.com/kb/145994) * [How To Calculate Dialog Base Units with Non-System-Based Font](http://support.microsoft.com/kb/125681) --- Simpler alternative ------------------- If buttons are the only control you want to resize automatically, you can also use [`BCM_GETIDEALSIZE`](http://msdn.microsoft.com/en-us/library/bb775961(VS.85).aspx) message [`Button_GetIdealSize()`](http://msdn.microsoft.com/en-us/library/bb761851(VS.85).aspx) macro (Windows XP and up only) to retrieve optimal width and height that fits anything the button contains, though it looks pretty ugly without any margins applied around the button's text.
58,621
<p>How do I make an MD5 hash of a string with Delphi?</p>
[ { "answer_id": 58626, "author": "devstopfix", "author_id": 3366, "author_profile": "https://Stackoverflow.com/users/3366", "pm_score": 5, "selected": false, "text": "<p>If you want an MD5 digest and have the <a href=\"http://www.indyproject.org\" rel=\"nofollow noreferrer\">Indy</a> comp...
2008/09/12
[ "https://Stackoverflow.com/questions/58621", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3366/" ]
How do I make an MD5 hash of a string with Delphi?
If you want an MD5 digest and have the [Indy](http://www.indyproject.org) components installed, you can do this: ``` uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest; with TIdHashMessageDigest5.Create do try Result := TIdHash128.AsHex(HashValue('Hello, world')); finally Free; end; ``` Most popular algorithms are supported in the [Delphi Cryptography Package](http://www.cityinthesky.co.uk/opensource/dcpcrypt/): * Haval * MD4, MD5 * RipeMD-128, RipeMD-160 * SHA-1, SHA-256, SHA-384, SHA-512, * Tiger **Update** `DCPCrypt` is now maintained by [Warren Postma](https://stackoverflow.com/users/84704/warren-p) and source can be found [here](https://bitbucket.org/wpostma/dcpcrypt2010).
58,622
<p>I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have <code>/* .. */</code> comments, and also has its own self-documentation facility which seems to be the pythonic way to document.</p> <p>Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?</p>
[ { "answer_id": 58701, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 7, "selected": true, "text": "<p>This is <a href=\"http://www.doxygen.nl/manual/docblocks.html#pythonblocks\" rel=\"noreferrer\">documented on the doxy...
2008/09/12
[ "https://Stackoverflow.com/questions/58622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have `/* .. */` comments, and also has its own self-documentation facility which seems to be the pythonic way to document. Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?
This is [documented on the doxygen website](http://www.doxygen.nl/manual/docblocks.html#pythonblocks), but to summarize here: You can use doxygen to document your Python code. You can either use the Python documentation string syntax: ``` """@package docstring Documentation for this module. More details. """ def func(): """Documentation for a function. More details. """ pass ``` In which case the comments will be extracted by doxygen, but you won't be able to use any of the [special doxygen commands](http://www.doxygen.nl/manual/commands.html#cmd_intro). **Or** you can (similar to C-style languages under doxygen) double up the comment marker (`#`) on the first line before the member: ``` ## @package pyexample # Documentation for this module. # # More details. ## Documentation for a function. # # More details. def func(): pass ``` In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting `OPTMIZE_OUTPUT_JAVA` to `YES`. Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?
58,630
<p>I have written some code in my VB.NET application to send an HTML e-mail (in this case, a lost password reminder).</p> <p>When I test the e-mail, it gets eaten by my spam filter. One of the things that it's scoring badly on is because of the following problem:</p> <pre>MIME_QP_LONG_LINE RAW: Quoted-printable line longer than 76 chars</pre> <p>I've been through the source of the e-mail, and I've broken each line longer than 76 characters into two lines with a CR+LF in between, but that hasn't fixed the problem.</p> <p>Can anyone point me in the right direction?</p> <p>Thanks!</p>
[ { "answer_id": 58667, "author": "pilif", "author_id": 5083, "author_profile": "https://Stackoverflow.com/users/5083", "pm_score": 4, "selected": true, "text": "<p>Quoted printable expands 8 bit characters to \"={HEX-Code}\", thus making the messages longer. Maybe you are just hitting thi...
2008/09/12
[ "https://Stackoverflow.com/questions/58630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475/" ]
I have written some code in my VB.NET application to send an HTML e-mail (in this case, a lost password reminder). When I test the e-mail, it gets eaten by my spam filter. One of the things that it's scoring badly on is because of the following problem: ``` MIME_QP_LONG_LINE RAW: Quoted-printable line longer than 76 chars ``` I've been through the source of the e-mail, and I've broken each line longer than 76 characters into two lines with a CR+LF in between, but that hasn't fixed the problem. Can anyone point me in the right direction? Thanks!
Quoted printable expands 8 bit characters to "={HEX-Code}", thus making the messages longer. Maybe you are just hitting this limit? Have you tried to break the message at, say, 70 characters? That should provide space for a couple of characters per line. Or you just encode the email with Base64 - all mail client can handle that. Or you just set Content-Transfer-Encoding to 8bit and send the data unencoded. I know of no mail server unable to handle 8bit bytes these days.
58,649
<p>I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...). </p> <p>Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically? Thanks!</p>
[ { "answer_id": 58662, "author": "goldenmean", "author_id": 2759376, "author_profile": "https://Stackoverflow.com/users/2759376", "pm_score": 3, "selected": false, "text": "<p>Getting EXIF data from a JPEG image involves:</p>\n\n<ol>\n<li>Seeking to the JPEG markers which mentions the beg...
2008/09/12
[ "https://Stackoverflow.com/questions/58649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6091/" ]
I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...). Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically? Thanks!
Check out this [metadata extractor](https://www.drewnoakes.com/code/exif/). It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use. --- **EDIT** *metadata-extractor* supports .NET too. It's a very fast and simple library for accessing metadata from images and videos. It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ... ``` var directories = ImageMetadataReader.ReadMetadata(imagePath); // print out all metadata foreach (var directory in directories) foreach (var tag in directory.Tags) Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}"); // access the date time var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault(); var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime); ``` It's available via [NuGet](https://www.nuget.org/packages/MetadataExtractor/) and the [code's on GitHub](https://github.com/drewnoakes/metadata-extractor-dotnet).
58,670
<p>Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher? Open CD tray exists, but I can't seem to make it close especially under W2k. </p> <p>I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.</p>
[ { "answer_id": 58678, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.nirsoft.net/utils/nircmd.html\" rel=\"nofollow noreferrer\">Nircmd</a> is a very handy freeware co...
2008/09/12
[ "https://Stackoverflow.com/questions/58670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3225/" ]
Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher? Open CD tray exists, but I can't seem to make it close especially under W2k. I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.
Here is an easy way using the Win32 API: ``` [DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi)] protected static extern int mciSendString(string lpstrCommand,StringBuilder lpstrReturnString,int uReturnLength,IntPtr hwndCallback); public void OpenCloseCD(bool Open) { if (Open) { mciSendString("set cdaudio door open", null, 0, IntPtr.Zero); } else { mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero); } } ```
58,697
<p>The situation: I have a pieceofcrapuous laptop. One of the things that make it pieceofcrapuous is that the battery is dead, and the power cable pulls out of the back with little effort.</p> <p>I recently received a non-pieceofcrapuous laptop, and I am in the process of copying everything from old to new. I'm trying to xcopy c:*.* from the old machine to an external hard drive, but because the cord pulls out so frequently, the xcopy is interrupted fairly often.</p> <p>What I need is a switch in XCopy that will copy eveything except for files that already exist in the destination folder -- the exact opposite of the behavior of the /U switch. </p> <p>Does anyone know of a way to do this? </p>
[ { "answer_id": 58700, "author": "Edward Wilde", "author_id": 5182, "author_profile": "https://Stackoverflow.com/users/5182", "pm_score": 4, "selected": false, "text": "<p>I find RoboCopy is a good alternative to xcopy. It supports high latency connections much better and supports resumin...
2008/09/12
[ "https://Stackoverflow.com/questions/58697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
The situation: I have a pieceofcrapuous laptop. One of the things that make it pieceofcrapuous is that the battery is dead, and the power cable pulls out of the back with little effort. I recently received a non-pieceofcrapuous laptop, and I am in the process of copying everything from old to new. I'm trying to xcopy c:\*.\* from the old machine to an external hard drive, but because the cord pulls out so frequently, the xcopy is interrupted fairly often. What I need is a switch in XCopy that will copy eveything except for files that already exist in the destination folder -- the exact opposite of the behavior of the /U switch. Does anyone know of a way to do this?
/D may be what you are looking for. I find it works quite fast for backing-up as existing files are not copied. ``` xcopy "O:\*.*" N:\Whatever /C /D /S /H /C Continues copying even if errors occur. /D:m-d-y Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time. /S Copies directories and subdirectories except empty ones. /H Copies hidden and system files also. ``` More information: <http://www.computerhope.com/xcopyhlp.htm>
58,709
<p>I'm using ADO.NET to access SQL Server 2005 and would like to be able to log from inside the T-SQL stored procedures that I'm calling. Is that somehow possible?</p> <p>I'm unable to see output from the 'print'-statement when using ADO.NET and since I want to use logging just for debuging the ideal solution would be to emit messages to DebugView from SysInternals.</p>
[ { "answer_id": 58716, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": false, "text": "<p>You can either log to a table, by simply inserting a new row, or you can implement a CLR stored procedure to write to...
2008/09/12
[ "https://Stackoverflow.com/questions/58709", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4164/" ]
I'm using ADO.NET to access SQL Server 2005 and would like to be able to log from inside the T-SQL stored procedures that I'm calling. Is that somehow possible? I'm unable to see output from the 'print'-statement when using ADO.NET and since I want to use logging just for debuging the ideal solution would be to emit messages to DebugView from SysInternals.
I solved this by writing a SQLCLR-procedure as Eric Z Beard suggested. The assembly must be signed with a strong name key file. ``` using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static int Debug(string s) { System.Diagnostics.Debug.WriteLine(s); return 0; } } } ``` Created a key and a login: ``` USE [master] CREATE ASYMMETRIC KEY DebugProcKey FROM EXECUTABLE FILE = 'C:\..\SqlServerProject1\bin\Debug\SqlServerProject1.dll' CREATE LOGIN DebugProcLogin FROM ASYMMETRIC KEY DebugProcKey GRANT UNSAFE ASSEMBLY TO DebugProcLogin ``` Imported it into SQL Server: ``` USE [mydb] CREATE ASSEMBLY SqlServerProject1 FROM 'C:\..\SqlServerProject1\bin\Debug\SqlServerProject1.dll' WITH PERMISSION_SET = unsafe CREATE FUNCTION dbo.Debug( @message as nvarchar(200) ) RETURNS int AS EXTERNAL NAME SqlServerProject1.[StoredProcedures].Debug ``` Then I was able to log in T-SQL procedures using ``` exec Debug @message = 'Hello World' ```
58,711
<p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p> <pre><code>Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end </code></pre> <p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p> <p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin =&gt; 10</code>), and from ruby (extensively using blocks in sensible ways)</p> <p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p> <pre><code>def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) </code></pre> <p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p> <p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p> <pre><code>class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action </code></pre> <p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p> <p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
[ { "answer_id": 58917, "author": "Justin Voss", "author_id": 5616, "author_profile": "https://Stackoverflow.com/users/5616", "pm_score": 4, "selected": true, "text": "<p>You could actually pull this off, but it would require using metaclasses, which are <em>deep</em> magic (there be drago...
2008/09/12
[ "https://Stackoverflow.com/questions/58711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way: ``` Shoes.app do t = para "Not clicked!" button "The Label" do alert "You clicked the button!" # when clicked, make an alert t.replace "Clicked!" # ..and replace the label's text end end ``` This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C\* library (In the case of GTK, Tk, wx, QT etc etc) Shoes takes things from web devlopment (like `#f0c2f0` style colour notation, CSS layout techniques, like `:margin => 10`), and from ruby (extensively using blocks in sensible ways) Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible: ``` def Shoeless(Shoes.app): self.t = para("Not clicked!") def on_click_func(self): alert("You clicked the button!") self.t.replace("clicked!") b = button("The label", click=self.on_click_func) ``` No where near as clean, and wouldn't be *nearly* as flexible, and I'm not even sure if it would be implementable. Using decorators seems like an interesting way to map blocks of code to a specific action: ``` class BaseControl: def __init__(self): self.func = None def clicked(self, func): self.func = func def __call__(self): if self.func is not None: self.func() class Button(BaseControl): pass class Label(BaseControl): pass # The actual applications code (that the end-user would write) class MyApp: ok = Button() la = Label() @ok.clicked def clickeryHappened(): print "OK Clicked!" if __name__ == '__main__': a = MyApp() a.ok() # trigger the clicked action ``` Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed. The scope of various stuff (say, the `la` label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..
You could actually pull this off, but it would require using metaclasses, which are *deep* magic (there be dragons). If you want an intro to metaclasses, there's a series of [articles from IBM](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) which manage to introduce the ideas without melting your brain. The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax.
58,743
<p>As an example take the following code:</p> <pre><code>public enum ExampleEnum { FooBar, BarFoo } public class ExampleClass : INotifyPropertyChanged { private ExampleEnum example; public ExampleEnum ExampleProperty { get { return example; } { /* set and notify */; } } } </code></pre> <p>I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this:</p> <pre><code>&lt;ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" /&gt; </code></pre> <p>Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually.</p> <p>Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now.</p> <p><strong>Edit</strong></p> <p>So one question was answered: How do I populate the ComboBox with the right values.</p> <p>Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method:</p> <pre><code>&lt;Window.Resources&gt; &lt;ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="ExampleEnumValues"&gt; &lt;ObjectDataProvider.MethodParameters&gt; &lt;x:Type TypeName="ExampleEnum" /&gt; &lt;/ObjectDataProvider.MethodParameters&gt; &lt;/ObjectDataProvider&gt; &lt;/Window.Resources&gt; </code></pre> <p>This I can use as an ItemsSource for my ComboBox:</p> <pre><code>&lt;ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/&gt; </code></pre>
[ { "answer_id": 58766, "author": "rudigrobler", "author_id": 5147, "author_profile": "https://Stackoverflow.com/users/5147", "pm_score": 5, "selected": false, "text": "<p>I don't know if it is possible in XAML-only but try the following:</p>\n\n<p>Give your ComboBox a name so you can acce...
2008/09/12
[ "https://Stackoverflow.com/questions/58743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1733/" ]
As an example take the following code: ``` public enum ExampleEnum { FooBar, BarFoo } public class ExampleClass : INotifyPropertyChanged { private ExampleEnum example; public ExampleEnum ExampleProperty { get { return example; } { /* set and notify */; } } } ``` I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this: ``` <ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" /> ``` Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually. Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now. **Edit** So one question was answered: How do I populate the ComboBox with the right values. Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method: ``` <Window.Resources> <ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="ExampleEnumValues"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="ExampleEnum" /> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> ``` This I can use as an ItemsSource for my ComboBox: ``` <ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/> ```
You can create a custom markup extension. Example of usage: ``` enum Status { [Description("Available.")] Available, [Description("Not here right now.")] Away, [Description("I don't have time right now.")] Busy } ``` At the top of your XAML: ``` xmlns:my="clr-namespace:namespace_to_enumeration_extension_class ``` and then... ``` <ComboBox ItemsSource="{Binding Source={my:Enumeration {x:Type my:Status}}}" DisplayMemberPath="Description" SelectedValue="{Binding CurrentStatus}" SelectedValuePath="Value" /> ``` And the implementation... ``` public class EnumerationExtension : MarkupExtension { private Type _enumType; public EnumerationExtension(Type enumType) { if (enumType == null) throw new ArgumentNullException("enumType"); EnumType = enumType; } public Type EnumType { get { return _enumType; } private set { if (_enumType == value) return; var enumType = Nullable.GetUnderlyingType(value) ?? value; if (enumType.IsEnum == false) throw new ArgumentException("Type must be an Enum."); _enumType = value; } } public override object ProvideValue(IServiceProvider serviceProvider) // or IXamlServiceProvider for UWP and WinUI { var enumValues = Enum.GetValues(EnumType); return ( from object enumValue in enumValues select new EnumerationMember{ Value = enumValue, Description = GetDescription(enumValue) }).ToArray(); } private string GetDescription(object enumValue) { var descriptionAttribute = EnumType .GetField(enumValue.ToString()) .GetCustomAttributes(typeof (DescriptionAttribute), false) .FirstOrDefault() as DescriptionAttribute; return descriptionAttribute != null ? descriptionAttribute.Description : enumValue.ToString(); } public class EnumerationMember { public string Description { get; set; } public object Value { get; set; } } } ```
58,744
<p>I want to copy the entire contents of a directory from one location to another in C#.</p> <p>There doesn't appear to be a way to do this using <code>System.IO</code> classes without lots of recursion.</p> <p>There is a method in VB that we can use if we add a reference to <code>Microsoft.VisualBasic</code>:</p> <pre><code>new Microsoft.VisualBasic.Devices.Computer(). FileSystem.CopyDirectory( sourceFolder, outputFolder ); </code></pre> <p>This seems like a rather ugly hack. Is there a better way?</p>
[ { "answer_id": 58759, "author": "Josef", "author_id": 5581, "author_profile": "https://Stackoverflow.com/users/5581", "pm_score": 6, "selected": false, "text": "<p>Or, if you want to go the hard way, add a reference to your project for Microsoft.VisualBasic and then use the following:</p...
2008/09/12
[ "https://Stackoverflow.com/questions/58744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
I want to copy the entire contents of a directory from one location to another in C#. There doesn't appear to be a way to do this using `System.IO` classes without lots of recursion. There is a method in VB that we can use if we add a reference to `Microsoft.VisualBasic`: ``` new Microsoft.VisualBasic.Devices.Computer(). FileSystem.CopyDirectory( sourceFolder, outputFolder ); ``` This seems like a rather ugly hack. Is there a better way?
Much easier ``` private static void CopyFilesRecursively(string sourcePath, string targetPath) { //Now Create all of the directories foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)); } //Copy all the files & Replaces any files with the same name foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories)) { File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true); } } ```
58,750
<p>Is it possible to obtain raw logs from Google Analytic? Is there any tool that can generate the raw logs from GA?</p>
[ { "answer_id": 58756, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 2, "selected": false, "text": "<p>No. But why don't you just use your webserver's logs? The value of GA is not in the data they collect, but the...
2008/09/12
[ "https://Stackoverflow.com/questions/58750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/370899/" ]
Is it possible to obtain raw logs from Google Analytic? Is there any tool that can generate the raw logs from GA?
No you can't get the raw logs, but there's nothing stopping you from getting the exact same data logged to your own web server logs. Have a look at the [Urchin code](https://ssl.google-analytics.com/urchin.js) and borrow that, changing the following two lines to point to your web server instead. ``` var _ugifpath2="http://www.google-analytics.com/__utm.gif"; if (_udl.protocol=="https:") _ugifpath2="https://ssl.google-analytics.com/__utm.gif"; ``` You'll want to create a `__utm.gif` file so that they don't show up in the logs as 404s. Obviously you'll need to parse the variables out of the hits into your web server logs. The log line in Apache looks something like this. You'll have lots of "fun" parsing out all the various stuff you want from that, but everything Google Analytics gets from the basic JavaScript tagging comes in like this. ``` 127.0.0.1 - - [02/Oct/2008:10:17:18 +1000] "GET /__utm.gif?utmwv=1.3&utmn=172543292&utmcs=ISO-8859-1&utmsr=1280x1024&utmsc=32-bit&utmul=en-us&utmje=1&utmfl=9.0%20%20r124&utmdt=My%20Web%20Page&utmhn=www.mydomain.com&utmhid=979599568&utmr=-&utmp=/urlgoeshere/&utmac=UA-1715941-2&utmcc=__utma%3D113887236.511203954.1220404968.1222846275.1222906638.33%3B%2B__utmz%3D113887236.1222393496.27.2.utmccn%3D(organic)%7Cutmcsr%3Dgoogle%7Cutmctr%3Dsapphire%2Btechnologies%2Bsite%253Arumble.net%7Cutmcmd%3Dorganic%3B%2B HTTP/1.0" 200 35 "http://www.mydomain.com/urlgoeshere/" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19" ```
58,755
<p>What is the best way to do per-user database connections in <code>Rails</code>? </p> <p>I realize this is a poor Rails design practice, but we're gradually replacing an existing web application that uses one database per user. A complete redesign/rewrite is not feasible.</p>
[ { "answer_id": 58767, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 1, "selected": false, "text": "<p>Take a look at <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001397\" rel=\"nofollow noreferrer\"...
2008/09/12
[ "https://Stackoverflow.com/questions/58755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/624/" ]
What is the best way to do per-user database connections in `Rails`? I realize this is a poor Rails design practice, but we're gradually replacing an existing web application that uses one database per user. A complete redesign/rewrite is not feasible.
Put something like this in your application controller. I'm using the subdomain plus "\_clientdb" to pick the name of the database. I have all the databases using the same username and password, so I can grab that from the db config file. Hope this helps! ``` class ApplicationController < ActionController::Base before_filter :hijack_db def hijack_db db_name = request.subdomains.first + "_clientdb" # lets manually connect to the proper db ActiveRecord::Base.establish_connection( :adapter => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['adapter'], :host => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['host'], :username => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['username'], :password => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['password'], :database => db_name ) end end ```
58,774
<p>I want to paste something I have cut from my desktop into a file open in Vi.</p> <p>But if I paste the tabs embed on top of each other across the page.</p> <p>I think it is some sort of visual mode change but can't find the command.</p>
[ { "answer_id": 58788, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 2, "selected": false, "text": "<p>If you are using VIM, you can use \"*p (i.e. double quotes, asterisk, letter p).</p>\n" }, { "answer_id": 58794, ...
2008/09/12
[ "https://Stackoverflow.com/questions/58774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6096/" ]
I want to paste something I have cut from my desktop into a file open in Vi. But if I paste the tabs embed on top of each other across the page. I think it is some sort of visual mode change but can't find the command.
If you're using plain vi: ------------------------- You probably have `autoindent` on. To turn it off while pasting: ``` <Esc> :set noai <paste all you want> <Esc> :set ai ``` I have in my `.exrc` the following shortcuts: ``` map ^P :set noai^M map ^N :set ai^M ``` Note that these have to be the actual control characters - insert them using `Ctrl`-`V` `Ctrl`-`P` and so on. If you're using vim: -------------------- Use the [`paste`](http://www.vim.org/htmldoc/options.html#%27paste%27) option. In addition to disabling `autoindent` it will also set other options such as `textwidth` and `wrapmargin` to paste-friendly defaults: ``` <Esc> :set paste <paste all you want> <Esc> :set nopaste ``` You can also set a key to toggle the paste mode. My `.vimrc` has the following line: ``` set pastetoggle=<C-P> " Ctrl-P toggles paste mode ```
58,831
<p>My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix:</p> <pre><code>select PTNO,PTNM,CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD); </code></pre> <p>and here it is after the fix:</p> <pre><code>select PTNO,PTNM,PARTS.CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD); </code></pre> <p>The bug was, that null values were being shown for column CATCD, i.e. the query results included results from table CATEGORIES instead of PARTS. Here's what I don't understand: if there was ambiguity in the original query, why didn't Oracle throw an error? As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity. Am I wrong, or just not thinking about this problem correctly?</p> <p>Update:</p> <p>Here's a revised example, where the ambiguity error is not thrown:</p> <pre><code>CREATE TABLE PARTS (PTNO NUMBER, CATCD NUMBER, SECCD NUMBER); CREATE TABLE CATEGORIES(CATCD NUMBER); CREATE TABLE SECTIONS(SECCD NUMBER, CATCD NUMBER); select PTNO,CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD) left join SECTIONS on (SECTIONS.SECCD=PARTS.SECCD) ; </code></pre> <p>Anybody have a clue?</p>
[ { "answer_id": 58896, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 0, "selected": false, "text": "<p>It is generally advised to be specific and fully qualify all column names anyway, as it saves the optimizer a li...
2008/09/12
[ "https://Stackoverflow.com/questions/58831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix: ``` select PTNO,PTNM,CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD); ``` and here it is after the fix: ``` select PTNO,PTNM,PARTS.CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD); ``` The bug was, that null values were being shown for column CATCD, i.e. the query results included results from table CATEGORIES instead of PARTS. Here's what I don't understand: if there was ambiguity in the original query, why didn't Oracle throw an error? As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity. Am I wrong, or just not thinking about this problem correctly? Update: Here's a revised example, where the ambiguity error is not thrown: ``` CREATE TABLE PARTS (PTNO NUMBER, CATCD NUMBER, SECCD NUMBER); CREATE TABLE CATEGORIES(CATCD NUMBER); CREATE TABLE SECTIONS(SECCD NUMBER, CATCD NUMBER); select PTNO,CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD) left join SECTIONS on (SECTIONS.SECCD=PARTS.SECCD) ; ``` Anybody have a clue?
I'm afraid I can't tell you why you're not getting an exception, but I can postulate as to why it chose CATEGORIES' version of the column over PARTS' version. > > As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity > > > It's not clear whether by "main" you mean simply the left table in a left join, or the "driving" table, as you see the query conceptually... But in either case, what you see as the "main" table in the query as you've written it will not necessarily be the "main" table in the actual execution of that query. My guess is that Oracle is simply using the column from the first table it hits in executing the query. And since most individual operations in SQL do not require one table to be hit before the other, the DBMS will decide at parse time which is the most efficient one to scan first. Try getting an execution plan for the query. I suspect it may reveal that it's hitting CATEGORIES first and then PARTS.
58,841
<p>How can I get precompiled headers working with GCC?</p> <p>I have had no luck in my attempts and I haven't seen many good examples for how to set it up. I've tried on <a href="https://en.wikipedia.org/wiki/Cygwin" rel="nofollow noreferrer">Cygwin</a> GCC 3.4.4 and using 4.0 on <a href="https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="nofollow noreferrer">Ubuntu</a>.</p>
[ { "answer_id": 58987, "author": "Paul", "author_id": 5841, "author_profile": "https://Stackoverflow.com/users/5841", "pm_score": 3, "selected": false, "text": "<p>I have managed to get precompiled headers working under gcc once in the past, and I recall having problems then as well. The ...
2008/09/12
[ "https://Stackoverflow.com/questions/58841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5200/" ]
How can I get precompiled headers working with GCC? I have had no luck in my attempts and I haven't seen many good examples for how to set it up. I've tried on [Cygwin](https://en.wikipedia.org/wiki/Cygwin) GCC 3.4.4 and using 4.0 on [Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29).
[Firstly, see the documentation here](http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html). You compile headers just like any other file but you put the output inside a file with a suffix of `.gch`. So for example if you precompile stdafx.h you will have a precompiled header that will be automatically searched for called `stdafx.h.gch` anytime you include `stdafx.h` Example: stdafx.h: ``` #include <string> #include <stdio.h> ``` a.cpp: ``` #include "stdafx.h" int main(int argc, char**argv) { std::string s = "Hi"; return 0; } ``` Then compile as: > > `> g++ -c stdafx.h -o stdafx.h.gch` > > `> g++ a.cpp` > > `> ./a.out` > > > Your compilation will work even if you remove stdafx.h after step 1.
58,851
<p>I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.</p>
[ { "answer_id": 58892, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 3, "selected": false, "text": "<p>I just tried the following:</p>\n\n<pre><code> $ cat gdbtest.c\n int abc = 43;\n\n int main()\n {\n abc = 10;\n }\n $ g...
2008/09/12
[ "https://Stackoverflow.com/questions/58851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3022/" ]
I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.
*watch* only breaks on write, *rwatch* let you break on read, and *awatch* let you break on read/write. You can set read watchpoints on memory locations: ``` gdb$ rwatch *0xfeedface Hardware read watchpoint 2: *0xfeedface ``` but one limitation applies to the rwatch and awatch commands; you can't use gdb variables in expressions: ``` gdb$ rwatch $ebx+0xec1a04f Expression cannot be implemented with read/access watchpoint. ``` So you have to expand them yourself: ``` gdb$ print $ebx $13 = 0x135700 gdb$ rwatch *0x135700+0xec1a04f Hardware read watchpoint 3: *0x135700 + 0xec1a04f gdb$ c Hardware read watchpoint 3: *0x135700 + 0xec1a04f Value = 0xec34daf 0x9527d6e7 in objc_msgSend () ``` **Edit:** Oh, and by the way. You need either hardware **or software support**. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the *can-use-hw-watchpoints* environment setting. ``` gdb$ show can-use-hw-watchpoints Debugger's willingness to use watchpoint hardware is 1. ```
58,872
<p>I've read in several places that the rectangle functions in emacs are very useful. I've read a bit about them, and I can't quite figure why. I mean, when you want to kill a paragraph, you mark the first row/column and then the last one, and that's actually a rectangle, right? But you can still use the normal kill...</p> <p>So what kind of transformations would you do with them?</p>
[ { "answer_id": 58885, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 6, "selected": true, "text": "<p>If you have data in columns in a text file with <code>M-x delete-rectangle</code> or <code>M-x kill-rectangle</code> you...
2008/09/12
[ "https://Stackoverflow.com/questions/58872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3785/" ]
I've read in several places that the rectangle functions in emacs are very useful. I've read a bit about them, and I can't quite figure why. I mean, when you want to kill a paragraph, you mark the first row/column and then the last one, and that's actually a rectangle, right? But you can still use the normal kill... So what kind of transformations would you do with them?
If you have data in columns in a text file with `M-x delete-rectangle` or `M-x kill-rectangle` you can delete a single column of data. Similarly, `M-x yank-rectangle` will paste in a column of text. For example, take the following text: ``` 1. alligator alphorn 2. baboon bugle 3. crocodile cornet 4. dog didgeridoo 5. elephant euphonium 6. fish flugelhorn 7. gopher guitar ``` Select from the a of alligator to the g of guitar. The beginning and end of the selection mark out two opposite corners of the rectangle. Enter `M-x kill-rectangle` and you immediately have: ``` 1. alphorn 2. bugle 3. cornet 4. didgeridoo 5. euphonium 6. flugelhorn 7. guitar ``` Next put the mark at the end of the top line, add a few spaces if required and enter `M-x yank-rectangle` and ta-da! You have re-ordered the columns: ``` 1. alphorn alligator 2. bugle baboon 3. cornet crocodile 4. didgeridoo dog 5. euphonium elephant 6. flugelhorn fish 7. guitar gopher ```
58,916
<p>Suppose I have a table called Companies that has a DepartmentID column. There's also a Departaments table that has as EmployeeID column. Of course I have an Employee table as well. The problem is that I want to delete a company, so first i have to delete all the employees for every departament and then all the departaments in the company. Cascade Delete is not an option, therefore i wish to use nested transactions. I'm new to SQL so I would appreciate your help.</p>
[ { "answer_id": 58943, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 0, "selected": false, "text": "<p>I'm not answering your question, but foreign Keys <em>is</em> the way to go, why is it not an option?</p>\n\n<p>As...
2008/09/12
[ "https://Stackoverflow.com/questions/58916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360/" ]
Suppose I have a table called Companies that has a DepartmentID column. There's also a Departaments table that has as EmployeeID column. Of course I have an Employee table as well. The problem is that I want to delete a company, so first i have to delete all the employees for every departament and then all the departaments in the company. Cascade Delete is not an option, therefore i wish to use nested transactions. I'm new to SQL so I would appreciate your help.
I'm not sure why you need nested transactions here. You only need one actual transaction: ``` BEGIN TRAN DELETE FROM Employee FROM Employee INNER JOIN Department ON Employee.DepartmentID = Department.DepartmentID INNER JOIN Company ON Department.CompanyID = Company.CompanyID WHERE Company.CompanyID = @CompanyID DELETE FROM Department FROM Department INNER JOIN Company ON Department.CompanyID = Company.CompanyID WHERE Company.CompanyID = @CompanyID DELETE FROM Company WHERE Company.CompanyID = @CompanyID COMMIT TRAN ``` Note the double FROM, that is not a typo, it's the correct SQL syntax for performing a JOIN in a DELETE. Each statement is atomic, either the entire DELETE will succeed or fail, which isn't that important in this case because the entire batch will either succeed or fail. BTW- I think you had your relationships backwards. The Department would not have an EmployeeID, the Employee would have a DepartmentID.
58,925
<p>I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?</p>
[ { "answer_id": 58931, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 6, "selected": true, "text": "<p>This appears to work.</p>\n\n<pre><code>public string RenderControlToHtml(Control ControlToRender)\n{\n System.Tex...
2008/09/12
[ "https://Stackoverflow.com/questions/58925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2469/" ]
I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?
This appears to work. ``` public string RenderControlToHtml(Control ControlToRender) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); System.IO.StringWriter stWriter = new System.IO.StringWriter(sb); System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter); ControlToRender.RenderControl(htmlWriter); return sb.ToString(); } ```
58,937
<p>Using VB.NET, how do I toggle the state of Caps Lock? </p>
[ { "answer_id": 58941, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 4, "selected": true, "text": "<p>From: <a href=\"http://www.vbforums.com/showthread.php?referrerid=61394&amp;t=537891\" rel=\"noreferrer\">http://www.vbforu...
2008/09/12
[ "https://Stackoverflow.com/questions/58937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133/" ]
Using VB.NET, how do I toggle the state of Caps Lock?
From: <http://www.vbforums.com/showthread.php?referrerid=61394&t=537891> ``` Imports System.Runtime.InteropServices Public Class Form2 Private Declare Sub keybd_event Lib "user32" ( _ ByVal bVk As Byte, _ ByVal bScan As Byte, _ ByVal dwFlags As Integer, _ ByVal dwExtraInfo As Integer _ ) Private Const VK_CAPITAL As Integer = &H14 Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1 Private Const KEYEVENTF_KEYUP As Integer = &H2 Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs _ ) Handles Button1.Click ' Toggle CapsLock ' Simulate the Key Press keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0) ' Simulate the Key Release keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0) End Sub End Class ```
58,939
<p>I'm trying to get an event to fire whenever a choice is made from a <code>JComboBox</code>.</p> <p>The problem I'm having is that there is no obvious <code>addSelectionListener()</code> method.</p> <p>I've tried to use <code>actionPerformed()</code>, but it never fires.</p> <p>Short of overriding the model for the <code>JComboBox</code>, I'm out of ideas.</p> <p>How do I get notified of a selection change on a <code>JComboBox</code>?**</p> <p><strong>Edit:</strong> I have to apologize. It turns out I was using a misbehaving subclass of <code>JComboBox</code>, but I'll leave the question up since your answer is good.</p>
[ { "answer_id": 58963, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 9, "selected": true, "text": "<p>It should respond to <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html\" rel=\"norefe...
2008/09/12
[ "https://Stackoverflow.com/questions/58939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
I'm trying to get an event to fire whenever a choice is made from a `JComboBox`. The problem I'm having is that there is no obvious `addSelectionListener()` method. I've tried to use `actionPerformed()`, but it never fires. Short of overriding the model for the `JComboBox`, I'm out of ideas. How do I get notified of a selection change on a `JComboBox`?\*\* **Edit:** I have to apologize. It turns out I was using a misbehaving subclass of `JComboBox`, but I'll leave the question up since your answer is good.
It should respond to [ActionListeners](http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html), like this: ``` combo.addActionListener (new ActionListener () { public void actionPerformed(ActionEvent e) { doSomething(); } }); ``` [@John Calsbeek](https://stackoverflow.com/a/58965/1429387) rightly points out that `addItemListener()` will work, too. You may get 2 `ItemEvents`, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!
58,940
<p>I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?</p> <pre><code>CREATE PROCEDURE getOrder (@orderId as numeric) AS BEGIN select order_address, order_number from order_table where order_id = @orderId select item, number_of_items, cost from order_line where order_id = @orderId END </code></pre> <p>I need to be able to iterate through both result sets individually.</p> <p>EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.</p> <p>The result sets returned by the procedures are not the same data types or number of columns.</p>
[ { "answer_id": 58960, "author": "Kilhoffer", "author_id": 5469, "author_profile": "https://Stackoverflow.com/users/5469", "pm_score": 0, "selected": false, "text": "<p>You could select them into temp tables or write table valued functions to return result sets. Are asking how to iterate ...
2008/09/12
[ "https://Stackoverflow.com/questions/58940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1836/" ]
I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure? ``` CREATE PROCEDURE getOrder (@orderId as numeric) AS BEGIN select order_address, order_number from order_table where order_id = @orderId select item, number_of_items, cost from order_line where order_id = @orderId END ``` I need to be able to iterate through both result sets individually. EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option. The result sets returned by the procedures are not the same data types or number of columns.
The short answer is: you can't do it. From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested. To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax: ``` INSERT INTO #Table (...columns...) EXEC MySproc ...parameters... ``` You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.
58,969
<p>I'm starting to learn how to use PHPUnit to test the website I'm working on. The problem I'm running into is that I have five different user types defined and I need to be able to test every class with the different types. I currently have a user class and I would like to pass this to each function but I can't figure out how to pass this or test the different errors that could come back as being correct or not.</p> <p><b>Edit:</b> I should have said. I have a user class and I want to pass a different instance of this class to each unit test. </p>
[ { "answer_id": 58982, "author": "Peter Bernier", "author_id": 6112, "author_profile": "https://Stackoverflow.com/users/6112", "pm_score": 1, "selected": false, "text": "<p>If you're looking to test the actual UI, you could try using something like Selenium (www.openqa.org). It lets you w...
2008/09/12
[ "https://Stackoverflow.com/questions/58969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4437/" ]
I'm starting to learn how to use PHPUnit to test the website I'm working on. The problem I'm running into is that I have five different user types defined and I need to be able to test every class with the different types. I currently have a user class and I would like to pass this to each function but I can't figure out how to pass this or test the different errors that could come back as being correct or not. **Edit:** I should have said. I have a user class and I want to pass a different instance of this class to each unit test.
If your various user classes inherit from a parent user class, then I recommend you use the same inheritance structure for your test case classes. Consider the following sample classes: ``` class User { public function commonFunctionality() { return 'Something'; } public function modifiedFunctionality() { return 'One Thing'; } } class SpecialUser extends User { public function specialFunctionality() { return 'Nothing'; } public function modifiedFunctionality() { return 'Another Thing'; } } ``` You could do the following with your test case classes: ``` class Test_User extends PHPUnit_Framework_TestCase { public function create() { return new User(); } public function testCommonFunctionality() { $user = $this->create(); $this->assertEquals('Something', $user->commonFunctionality); } public function testModifiedFunctionality() { $user = $this->create(); $this->assertEquals('One Thing', $user->commonFunctionality); } } class Test_SpecialUser extends Test_User { public function create() { return new SpecialUser(); } public function testSpecialFunctionality() { $user = $this->create(); $this->assertEquals('Nothing', $user->commonFunctionality); } public function testModifiedFunctionality() { $user = $this->create(); $this->assertEquals('Another Thing', $user->commonFunctionality); } } ``` Because each test depends on a create method which you can override, and because the test methods are inherited from the parent test class, all tests for the parent class will be run against the child class, unless you override them to change the expected behavior. This has worked great in my limited experience.
58,976
<p>How do I find out whether or not Caps Lock is activated, using VB.NET?</p> <p>This is a follow-up to my <a href="https://stackoverflow.com/questions/58937/how-do-i-toggle-caps-lock-in-vbnet">earlier question</a>.</p>
[ { "answer_id": 58991, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "<p>I'm not an expert in VB.NET so only PInvoke comes to my mind:</p>\n\n<pre><code>Declare Function GetKeyState Lib \"user32\" \n...
2008/09/12
[ "https://Stackoverflow.com/questions/58976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/133/" ]
How do I find out whether or not Caps Lock is activated, using VB.NET? This is a follow-up to my [earlier question](https://stackoverflow.com/questions/58937/how-do-i-toggle-caps-lock-in-vbnet).
[Control.IsKeyLocked(Keys) Method - MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.iskeylocked.aspx) ``` Imports System Imports System.Windows.Forms Imports Microsoft.VisualBasic Public Class CapsLockIndicator Public Shared Sub Main() if Control.IsKeyLocked(Keys.CapsLock) Then MessageBox.Show("The Caps Lock key is ON.") Else MessageBox.Show("The Caps Lock key is OFF.") End If End Sub 'Main End Class 'CapsLockIndicator ``` --- C# version: ```cs using System; using System.Windows.Forms; public class CapsLockIndicator { public static void Main() { if (Control.IsKeyLocked(Keys.CapsLock)) { MessageBox.Show("The Caps Lock key is ON."); } else { MessageBox.Show("The Caps Lock key is OFF."); } } } ```
59,013
<p>Context: I'm in charge of running a service written in .NET. Proprietary application. It uses a SQL Server database. It ran as a user member of the Administrators group in the local machine. It worked alright before I added the machine to a domain.</p> <p>So, I added the machine to a domain (Win 2003) and changed the user to a member of the Power Users group and now, the</p> <p>Problem: Some of the SQL sentences it tries to execute are "magically" in spanish localization (where , separates floating point numbers instead of .), leading to errors. </p> <blockquote> <p>There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)</p> </blockquote> <p>Operating System and Regional Settings in the machine are in English. I asked the provider of the application and he said:</p> <blockquote> <p>Looks like you have a combination of code running under Spanish locale, and SQL server under English locale. So the SQL expects '15.28' and not '15,28'</p> </blockquote> <p>Which looks wrong to me in various levels (how can SQL Server distinguish between commas to separate arguments and commas belonging to a floating point number?).</p> <p>So, the code seems to be grabbing the spanish locale from somewhere, I don't know if it's the user it runs as, or someplace else (global policy, maybe?). But the question is</p> <p>What are the places where localization is defined on a machine/user/domain basis?</p> <p>I don't know all the places I must search for the culprit, so please help me to find it!</p>
[ { "answer_id": 59070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can set it in the thread context in which your code is executing.</p>\n\n<p>System.Threading.Thread.CurrentThread.Curren...
2008/09/12
[ "https://Stackoverflow.com/questions/59013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
Context: I'm in charge of running a service written in .NET. Proprietary application. It uses a SQL Server database. It ran as a user member of the Administrators group in the local machine. It worked alright before I added the machine to a domain. So, I added the machine to a domain (Win 2003) and changed the user to a member of the Power Users group and now, the Problem: Some of the SQL sentences it tries to execute are "magically" in spanish localization (where , separates floating point numbers instead of .), leading to errors. > > There are fewer columns in the INSERT > statement than values specified in the > VALUES clause. The number of values in > the VALUES clause must match the > number of columns specified in the > INSERT statement. at > System.Data.SqlClient.SqlConnection.OnError(SqlException > exception, Boolean breakConnection) > > > Operating System and Regional Settings in the machine are in English. I asked the provider of the application and he said: > > Looks like you have a combination of > code running under Spanish locale, and > SQL server under English locale. So > the SQL expects '15.28' and not > '15,28' > > > Which looks wrong to me in various levels (how can SQL Server distinguish between commas to separate arguments and commas belonging to a floating point number?). So, the code seems to be grabbing the spanish locale from somewhere, I don't know if it's the user it runs as, or someplace else (global policy, maybe?). But the question is What are the places where localization is defined on a machine/user/domain basis? I don't know all the places I must search for the culprit, so please help me to find it!
There are two types of localisation in .NET, both the settings for the cultures can be found in these variables (fire up a .NET command line app on the machine to see what it says): System.Thread.CurrentThread.CurrentCulture & System.Thread.CurrentThread.CurrentUICulture <http://msdn.microsoft.com/en-us/library/system.threading.thread_members.aspx> They relate to the settings in the control panel (in the regional settings part). Create a .NET command line app, then just call ToString() on the above properties, that should tell you which property to look at. **Edit:** It turns out the setting for the locales per user are held here: ``` HKEY_CURRENT_USER\Control Panel\International ``` It might be worth inspecting the registry of the user with the spanish locale, and comparing it to one who is set to US or whichever locale you require.
59,044
<p>Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)</p>
[ { "answer_id": 59055, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 8, "selected": true, "text": "<p>The following query replace each and every <code>a</code> character with a <code>b</code> character.</p>\n\n<pre><code>UPDA...
2008/09/12
[ "https://Stackoverflow.com/questions/59044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2908/" ]
Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)
The following query replace each and every `a` character with a `b` character. ``` UPDATE YourTable SET Column1 = REPLACE(Column1,'a','b') WHERE Column1 LIKE '%a%' ``` This will not work on SQL server 2003.
59,075
<p>How do I save each sheet in an Excel workbook to separate <code>CSV</code> files with a macro?</p> <p>I have an excel with multiple sheets and I was looking for a macro that will save each sheet to a separate <code>CSV (comma separated file)</code>. Excel will not allow you to save all sheets to different <code>CSV</code> files.</p>
[ { "answer_id": 59078, "author": "Alex Duggleby", "author_id": 5790, "author_profile": "https://Stackoverflow.com/users/5790", "pm_score": 4, "selected": false, "text": "<p>And here's my solution should work with Excel > 2000, but tested only on 2007:</p>\n\n<pre><code>Private Sub SaveAll...
2008/09/12
[ "https://Stackoverflow.com/questions/59075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
How do I save each sheet in an Excel workbook to separate `CSV` files with a macro? I have an excel with multiple sheets and I was looking for a macro that will save each sheet to a separate `CSV (comma separated file)`. Excel will not allow you to save all sheets to different `CSV` files.
Here is one that will give you a visual file chooser to pick the folder you want to save the files to and also lets you choose the CSV delimiter (I use pipes '|' because my fields contain commas and I don't want to deal with quotes): ``` ' ---------------------- Directory Choosing Helper Functions ----------------------- ' Excel and VBA do not provide any convenient directory chooser or file chooser ' dialogs, but these functions will provide a reference to a system DLL ' with the necessary capabilities Private Type BROWSEINFO ' used by the function GetFolderName hOwner As Long pidlRoot As Long pszDisplayName As String lpszTitle As String ulFlags As Long lpfn As Long lParam As Long iImage As Long End Type Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _ Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long Private Declare Function SHBrowseForFolder Lib "shell32.dll" _ Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long Function GetFolderName(Msg As String) As String ' returns the name of the folder selected by the user Dim bInfo As BROWSEINFO, path As String, r As Long Dim X As Long, pos As Integer bInfo.pidlRoot = 0& ' Root folder = Desktop If IsMissing(Msg) Then bInfo.lpszTitle = "Select a folder." ' the dialog title Else bInfo.lpszTitle = Msg ' the dialog title End If bInfo.ulFlags = &H1 ' Type of directory to return X = SHBrowseForFolder(bInfo) ' display the dialog ' Parse the result path = Space$(512) r = SHGetPathFromIDList(ByVal X, ByVal path) If r Then pos = InStr(path, Chr$(0)) GetFolderName = Left(path, pos - 1) Else GetFolderName = "" End If End Function '---------------------- END Directory Chooser Helper Functions ---------------------- Public Sub DoTheExport() Dim FName As Variant Dim Sep As String Dim wsSheet As Worksheet Dim nFileNum As Integer Dim csvPath As String Sep = InputBox("Enter a single delimiter character (e.g., comma or semi-colon)", _ "Export To Text File") 'csvPath = InputBox("Enter the full path to export CSV files to: ") csvPath = GetFolderName("Choose the folder to export CSV files to:") If csvPath = "" Then MsgBox ("You didn't choose an export directory. Nothing will be exported.") Exit Sub End If For Each wsSheet In Worksheets wsSheet.Activate nFileNum = FreeFile Open csvPath & "\" & _ wsSheet.Name & ".csv" For Output As #nFileNum ExportToTextFile CStr(nFileNum), Sep, False Close nFileNum Next wsSheet End Sub Public Sub ExportToTextFile(nFileNum As Integer, _ Sep As String, SelectionOnly As Boolean) Dim WholeLine As String Dim RowNdx As Long Dim ColNdx As Integer Dim StartRow As Long Dim EndRow As Long Dim StartCol As Integer Dim EndCol As Integer Dim CellValue As String Application.ScreenUpdating = False On Error GoTo EndMacro: If SelectionOnly = True Then With Selection StartRow = .Cells(1).Row StartCol = .Cells(1).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With Else With ActiveSheet.UsedRange StartRow = .Cells(1).Row StartCol = .Cells(1).Column EndRow = .Cells(.Cells.Count).Row EndCol = .Cells(.Cells.Count).Column End With End If For RowNdx = StartRow To EndRow WholeLine = "" For ColNdx = StartCol To EndCol If Cells(RowNdx, ColNdx).Value = "" Then CellValue = "" Else CellValue = Cells(RowNdx, ColNdx).Value End If WholeLine = WholeLine & CellValue & Sep Next ColNdx WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep)) Print #nFileNum, WholeLine Next RowNdx EndMacro: On Error GoTo 0 Application.ScreenUpdating = True End Sub ```
59,099
<p>Visually both of the following snippets produce the same UI. So why are there 2 controls..<br> <strong>Snippet1</strong> </p> <pre><code>&lt;TextBlock&gt;Name:&lt;/TextBlock&gt; &lt;TextBox Name="nameTextBox" /&gt; </code></pre> <p><strong>Snippet2</strong></p> <pre><code>&lt;Label&gt;Name:&lt;/Label&gt; &lt;TextBox Name="nameTextBox" /&gt; </code></pre> <p>(<em>Well I am gonna answer this myself... thought this is a useful tidbit I learnt today from <a href="https://rads.stackoverflow.com/amzn/click/com/0596510373" rel="noreferrer" rel="nofollow noreferrer">Programming WPF</a></em>) </p>
[ { "answer_id": 59104, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 4, "selected": false, "text": "<p>Label has an important <strong>focus handling</strong> responsibility.Its purpose is to allow you to place a caption with an...
2008/09/12
[ "https://Stackoverflow.com/questions/59099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
Visually both of the following snippets produce the same UI. So why are there 2 controls.. **Snippet1** ``` <TextBlock>Name:</TextBlock> <TextBox Name="nameTextBox" /> ``` **Snippet2** ``` <Label>Name:</Label> <TextBox Name="nameTextBox" /> ``` (*Well I am gonna answer this myself... thought this is a useful tidbit I learnt today from [Programming WPF](https://rads.stackoverflow.com/amzn/click/com/0596510373)*)
The WPF Textblock inherits from **FrameworkElement** instead of deriving from **System.Windows.Control** like the Label Control. This means that the Textblock is much more lightweight. The downside of using a textblock is no support for Access/Accerelator Keys and there is no link to other controls as target. ***When you want to display text by itself use the TextBlock***. The benefit is a light, performant way to display text. ***When you want to associate text with another control like a TextBox use the Label control***. The benefits are access keys and references to target control.
59,102
<p>Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter?</p> <p>Example 1 - separate parameters: function convertTemperature("celsius", "fahrenheit", 22)</p> <p>Example 2 - combined parameter: function convertTemperature("c-f", 22)</p> <p>The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow.</p> <p>Thoughts?</p>
[ { "answer_id": 59108, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 5, "selected": true, "text": "<p>Go with the first option, but rather than allow literal strings (which are error prone), take constant values or an enume...
2008/09/12
[ "https://Stackoverflow.com/questions/59102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6126/" ]
Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter? Example 1 - separate parameters: function convertTemperature("celsius", "fahrenheit", 22) Example 2 - combined parameter: function convertTemperature("c-f", 22) The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow. Thoughts?
Go with the first option, but rather than allow literal strings (which are error prone), take constant values or an enumeration if your language supports it, like this: ``` convertTemperature (TempScale.CELSIUS, TempScale.FAHRENHEIT, 22) ```
59,107
<p>I'm converting an application to use Java 1.5 and have found the following method:</p> <pre><code> /** * Compare two Comparables, treat nulls as -infinity. * @param o1 * @param o2 * @return -1 if o1&amp;lt;o2, 0 if o1==o2, 1 if o1&amp;gt;o2 */ protected static int nullCompare(Comparable o1, Comparable o2) { if (o1 == null) { if (o2 == null) { return 0; } else { return -1; } } else if (o2 == null) { return 1; } else { return o1.compareTo(o2); } } </code></pre> <p>Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how? </p> <p>I thought the following would do the trick:</p> <pre><code>protected static &lt;T extends Comparable&gt; int nullCompare(T o1, T o2) { </code></pre> <p>but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line:</p> <pre><code>return o1.compareTo(o2); </code></pre>
[ { "answer_id": 59119, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 5, "selected": true, "text": "<p>Change it to:</p>\n\n<pre><code>protected static &lt;T extends Comparable&lt;T&gt;&gt; int nullCompare(T o1, T o2) {\n</c...
2008/09/12
[ "https://Stackoverflow.com/questions/59107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4389/" ]
I'm converting an application to use Java 1.5 and have found the following method: ``` /** * Compare two Comparables, treat nulls as -infinity. * @param o1 * @param o2 * @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2 */ protected static int nullCompare(Comparable o1, Comparable o2) { if (o1 == null) { if (o2 == null) { return 0; } else { return -1; } } else if (o2 == null) { return 1; } else { return o1.compareTo(o2); } } ``` Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how? I thought the following would do the trick: ``` protected static <T extends Comparable> int nullCompare(T o1, T o2) { ``` but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line: ``` return o1.compareTo(o2); ```
Change it to: ``` protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) { ``` You need that because Comparable is itself a generic type.
59,120
<p>I am getting this error now that I hit version number 1.256.0: Error 4 Invalid product version '1.256.0'. Must be of format '##.##.####'</p> <p>The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like. I found this stated on msdn.com: The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. (<a href="http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx</a>)</p> <p>Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above.</p> <p>Does anyone have any ideas on why this would be failing now?</p>
[ { "answer_id": 59119, "author": "jodonnell", "author_id": 4223, "author_profile": "https://Stackoverflow.com/users/4223", "pm_score": 5, "selected": true, "text": "<p>Change it to:</p>\n\n<pre><code>protected static &lt;T extends Comparable&lt;T&gt;&gt; int nullCompare(T o1, T o2) {\n</c...
2008/09/12
[ "https://Stackoverflow.com/questions/59120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5967/" ]
I am getting this error now that I hit version number 1.256.0: Error 4 Invalid product version '1.256.0'. Must be of format '##.##.####' The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like. I found this stated on msdn.com: The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. (<http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx>) Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above. Does anyone have any ideas on why this would be failing now?
Change it to: ``` protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) { ``` You need that because Comparable is itself a generic type.
59,166
<p>So I have an object which has some fields, doesn't really matter what. I have a generic list of these objects.</p> <pre><code>List&lt;MyObject&gt; myObjects = new List&lt;MyObject&gt;(); myObjects.Add(myObject1); myObjects.Add(myObject2); myObjects.Add(myObject3); </code></pre> <p>So I want to remove objects from my list based on some criteria. For instance, <code>myObject.X &gt;= 10.</code> I would like to use the <code>RemoveAll(Predicate&lt;T&gt; match)</code> method for to do this.</p> <p>I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.</p>
[ { "answer_id": 59172, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 7, "selected": true, "text": "<p>There's two options, an explicit delegate or a delegate disguised as a lamba construct:</p>\n<p>explicit delegate</p>...
2008/09/12
[ "https://Stackoverflow.com/questions/59166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/454247/" ]
So I have an object which has some fields, doesn't really matter what. I have a generic list of these objects. ``` List<MyObject> myObjects = new List<MyObject>(); myObjects.Add(myObject1); myObjects.Add(myObject2); myObjects.Add(myObject3); ``` So I want to remove objects from my list based on some criteria. For instance, `myObject.X >= 10.` I would like to use the `RemoveAll(Predicate<T> match)` method for to do this. I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.
There's two options, an explicit delegate or a delegate disguised as a lamba construct: explicit delegate ``` myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; }); ``` lambda ``` myObjects.RemoveAll(m => m.X >= 10); ``` --- Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs
59,181
<p>I have a WCF service that gets called from client side JavaScript. The call fails with a Service is null JavaScript error. WebDevelopment helper trace shows that the calls to load the jsdebug support file results in a 404 (file not found) error. </p> <p>Restarting IIS or clearing out the Temp ASP.Net files or setting batch="false" on the compilation tag in web.config does not resolve the problem</p> <p>From the browser </p> <p><a href="https://Myserver/MyApp/Services/MyService.svc" rel="nofollow noreferrer">https://Myserver/MyApp/Services/MyService.svc</a> displays the service metadata</p> <p>however </p> <p><a href="https://Myserver/MyApp/Services/MyService.svc/jsdebug" rel="nofollow noreferrer">https://Myserver/MyApp/Services/MyService.svc/jsdebug</a> results in a 404.</p> <p>The issue seems to be with the https protocol. With http /jsdebug downloads the supporting JS file.</p> <p>Any ideas?</p> <p>TIA</p>
[ { "answer_id": 59764, "author": "rams", "author_id": 3635, "author_profile": "https://Stackoverflow.com/users/3635", "pm_score": 5, "selected": true, "text": "<p>Figured it out!</p>\n\n<p>Here is the services configuration section from web.config</p>\n\n<p>Look at the bindingConfiguratio...
2008/09/12
[ "https://Stackoverflow.com/questions/59181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3635/" ]
I have a WCF service that gets called from client side JavaScript. The call fails with a Service is null JavaScript error. WebDevelopment helper trace shows that the calls to load the jsdebug support file results in a 404 (file not found) error. Restarting IIS or clearing out the Temp ASP.Net files or setting batch="false" on the compilation tag in web.config does not resolve the problem From the browser <https://Myserver/MyApp/Services/MyService.svc> displays the service metadata however <https://Myserver/MyApp/Services/MyService.svc/jsdebug> results in a 404. The issue seems to be with the https protocol. With http /jsdebug downloads the supporting JS file. Any ideas? TIA
Figured it out! Here is the services configuration section from web.config Look at the bindingConfiguration attribute on the endpoint. The value "webBinding" points to the binding name="webBinding" tag in the bindings and that is what tells the service to use Transport level security it HTTPS. In my case the attribute value was empty causing the webservice request to the /js or /jsdebug file over HTTPS to fail and throw a 404 error. ``` <services> <service name="MyService"> <endpoint address="" behaviorConfiguration="MyServiceAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="Services.MyService" /> </service> </services> <bindings> <webHttpBinding> <binding name="webBinding"> <security mode="Transport"> </security> </binding> </webHttpBinding> </bindings> ``` Note that the bindingConfiguration attribute should be empty ("") if the service is accessed via http instead of https (when testing on local machine with no certs) Hope this helps someone.
59,182
<p>What is the best way to keep an asp:button from displaying it's URL on the status bar of the browser? The button is currently defines like this:</p> <pre><code>&lt;asp:button id="btnFind" runat="server" Text="Find Info" onclick="btnFind_Click"&gt; &lt;/asp:button&gt; </code></pre> <p><strong>Update:</strong></p> <p>This appears to be specific to IE7, IE6 and FF do not show the URL in the status bar.</p>
[ { "answer_id": 59189, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": true, "text": "<p>I use FF so never noticed this, but the link does in fact appear in the status bar in IE..</p>\n<p>I dont think you can ov...
2008/09/12
[ "https://Stackoverflow.com/questions/59182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/206/" ]
What is the best way to keep an asp:button from displaying it's URL on the status bar of the browser? The button is currently defines like this: ``` <asp:button id="btnFind" runat="server" Text="Find Info" onclick="btnFind_Click"> </asp:button> ``` **Update:** This appears to be specific to IE7, IE6 and FF do not show the URL in the status bar.
I use FF so never noticed this, but the link does in fact appear in the status bar in IE.. I dont think you can overwrite it :( I initially thought maybe setting the ToolTip (al la "title") property might do it.. Seems it does not.. Looking at the source, what appears is nowhere to be found, so I would say this is a *browser* issue, I don't think you can do anything in code.. :( Update ------ Yeah, Looks like IE always posts whatever the form action is.. Can't see a way to override it, as yet.. Perhaps try explicitly setting it via JS? Update II --------- Done some more Googleing. Don't think there really is a "nice" way of doing it.. Unless you remove the form all together and post data some other way.. **Is it really worth that much? Generally this just tends to be the page name?**
59,217
<p>Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array?</p> <p>The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format.</p> <p>I'm looking to avoid writing my own function to accomplish this if possible.</p>
[ { "answer_id": 59230, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 3, "selected": false, "text": "<p>I think you can use <a href=\"http://msdn.microsoft.com/en-us/library/y5s0whfd.aspx\" rel=\"noreferrer\">Array.Copy</a> fo...
2008/09/12
[ "https://Stackoverflow.com/questions/59217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3058/" ]
Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array? The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format. I'm looking to avoid writing my own function to accomplish this if possible.
If you can manipulate one of the arrays, you can resize it before performing the copy: ``` T[] array1 = getOneArray(); T[] array2 = getAnotherArray(); int array1OriginalLength = array1.Length; Array.Resize<T>(ref array1, array1OriginalLength + array2.Length); Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length); ``` Otherwise, you can make a new array ``` T[] array1 = getOneArray(); T[] array2 = getAnotherArray(); T[] newArray = new T[array1.Length + array2.Length]; Array.Copy(array1, newArray, array1.Length); Array.Copy(array2, 0, newArray, array1.Length, array2.Length); ``` [More on available Array methods on MSDN](http://msdn.microsoft.com/en-us/library/system.array.aspx).
59,220
<p>I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use.</p> <p>What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View.</p> <p>As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done.</p> <p>What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it:</p> <pre><code>String FilePath = Path.GetDirectoryName(FileName); System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName); </code></pre> <p>That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter:</p> <pre><code>AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies(); </code></pre> <p>That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case.</p> <p>So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc.</p> <p>I know that tools like Reflector do this, I just can't find the syntax for getting at it. </p>
[ { "answer_id": 59243, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 5, "selected": true, "text": "<p>Couple of options here:</p>\n\n<ol>\n<li>Attach to <code>AppDomain.AssemblyResolve</code> and do another <code>LoadFi...
2008/09/12
[ "https://Stackoverflow.com/questions/59220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124/" ]
I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use. What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View. As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done. What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it: ``` String FilePath = Path.GetDirectoryName(FileName); System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName); ``` That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter: ``` AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies(); ``` That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case. So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc. I know that tools like Reflector do this, I just can't find the syntax for getting at it.
Couple of options here: 1. Attach to `AppDomain.AssemblyResolve` and do another `LoadFile` based on the requested assembly. 2. Spin up another `AppDomain` with the directory as its base and load the assemblies in that `AppDomain`. I'd highly recommend pursuing option 2, since that will likely be cleaner and allow you to unload all those assemblies after. Also, consider loading assemblies in the reflection-only context if you only need to reflect over them (see `Assembly.ReflectionOnlyLoad`).
59,232
<p>What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table?</p> <p>For example: I have a <code>JOBS</code> table with the column <code>JOB_NUMBER</code>. How can I find out if I have any duplicate <code>JOB_NUMBER</code>s, and how many times they're duplicated?</p>
[ { "answer_id": 59242, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 10, "selected": true, "text": "<p>Aggregate the column by COUNT, then use a HAVING clause to find values that appear greater than one time.</p>\n<pr...
2008/09/12
[ "https://Stackoverflow.com/questions/59232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table? For example: I have a `JOBS` table with the column `JOB_NUMBER`. How can I find out if I have any duplicate `JOB_NUMBER`s, and how many times they're duplicated?
Aggregate the column by COUNT, then use a HAVING clause to find values that appear greater than one time. ``` SELECT column_name, COUNT(column_name) FROM table_name GROUP BY column_name HAVING COUNT(column_name) > 1; ```
59,267
<p>Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no longer supported.</p> <p>The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.</p>
[ { "answer_id": 59271, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "<p>Just write <code>&lt;input type=\"button\" ... /&gt;</code> into your html. There's nothing special at all with the...
2008/09/12
[ "https://Stackoverflow.com/questions/59267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no longer supported. The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.
I figured it out. It goes something like this: ``` <form method="post" action="<%= Html.AttributeEncode(Url.Action("CastUpVote")) %>"> <input type="submit" value="<%=ViewData.Model.UpVotes%> up votes" /> </form> ```
59,280
<p>I need to update a <code>combobox</code> with a new value so it changes the reflected text in it. The cleanest way to do this is after the <code>combobox</code>has been initialised and with a message.</p> <p>So I am trying to craft a <code>postmessage</code> to the hwnd that contains the <code>combobox</code>.</p> <p>So if I want to send a message to it, changing the currently selected item to the nth item, what would the <code>postmessage</code> look like?</p> <p>I am guessing that it would involve <code>ON_CBN_SELCHANGE</code>, but I can't get it to work right.</p>
[ { "answer_id": 59317, "author": "Simon Steele", "author_id": 4591, "author_profile": "https://Stackoverflow.com/users/4591", "pm_score": 4, "selected": true, "text": "<p>You want <a href=\"http://msdn.microsoft.com/en-us/library/bb856484(VS.85).aspx\" rel=\"nofollow noreferrer\">ComboBox...
2008/09/12
[ "https://Stackoverflow.com/questions/59280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/342/" ]
I need to update a `combobox` with a new value so it changes the reflected text in it. The cleanest way to do this is after the `combobox`has been initialised and with a message. So I am trying to craft a `postmessage` to the hwnd that contains the `combobox`. So if I want to send a message to it, changing the currently selected item to the nth item, what would the `postmessage` look like? I am guessing that it would involve `ON_CBN_SELCHANGE`, but I can't get it to work right.
You want [ComboBox\_SetCurSel](http://msdn.microsoft.com/en-us/library/bb856484(VS.85).aspx): ``` ComboBox_SetCurSel(hWndCombo, n); ``` or if it's an MFC CComboBox control you can probably do: ``` m_combo.SetCurSel(2); ``` I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN\_SELCHANGE is the notification that the control sends *back to you* when the selection is changed. Finally, you might want to add the c++ tag to this question.
59,294
<p>I have the following query:</p> <pre><code>select column_name, count(column_name) from table group by column_name having count(column_name) &gt; 1; </code></pre> <p>What would be the difference if I replaced all calls to <code>count(column_name)</code> to <code>count(*)</code>?</p> <p>This question was inspired by <a href="https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle">How do I find duplicate values in a table in Oracle?</a>.</p> <hr> <p>To clarify the accepted answer (and maybe my question), replacing <code>count(column_name)</code> with <code>count(*)</code> would return an extra row in the result that contains a <code>null</code> and the count of <code>null</code> values in the column.</p>
[ { "answer_id": 59302, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 9, "selected": true, "text": "<p><code>count(*)</code> counts NULLs and <code>count(column)</code> does not</p>\n\n<p>[edit] added this code so that people ...
2008/09/12
[ "https://Stackoverflow.com/questions/59294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
I have the following query: ``` select column_name, count(column_name) from table group by column_name having count(column_name) > 1; ``` What would be the difference if I replaced all calls to `count(column_name)` to `count(*)`? This question was inspired by [How do I find duplicate values in a table in Oracle?](https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle). --- To clarify the accepted answer (and maybe my question), replacing `count(column_name)` with `count(*)` would return an extra row in the result that contains a `null` and the count of `null` values in the column.
`count(*)` counts NULLs and `count(column)` does not [edit] added this code so that people can run it ``` create table #bla(id int,id2 int) insert #bla values(null,null) insert #bla values(1,null) insert #bla values(null,1) insert #bla values(1,null) insert #bla values(null,1) insert #bla values(1,null) insert #bla values(null,null) select count(*),count(id),count(id2) from #bla ``` results 7 3 2
59,309
<p>What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.</p> <p><img src="https://content.screencast.com/users/jessegavin/folders/Jing/media/ba5c2688-0aad-4e89-878a-8911946f8612/2008-09-12_1027.png" alt="alt text"></p>
[ { "answer_id": 59324, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 4, "selected": false, "text": "<p>This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic m...
2008/09/12
[ "https://Stackoverflow.com/questions/59309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5651/" ]
What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup. ![alt text](https://content.screencast.com/users/jessegavin/folders/Jing/media/ba5c2688-0aad-4e89-878a-8911946f8612/2008-09-12_1027.png)
Just add ``` position: relative; top: 50%; transform: translateY(-50%); ``` to the inner div. What it does is moving the inner div's top border to the half height of the outer div (`top: 50%;`) and then the inner div up by half its height (`transform: translateY(-50%)`). This will work with `position: absolute` or `relative`. Keep in mind that `transform` and `translate` have vendor prefixes which are not included for simplicity. Codepen: <http://codepen.io/anon/pen/ZYprdb>
59,313
<p>I remember watching a webcast from Mark Russinovich showing the sequence of keyboard keys for a user initiated kernel dump. Can somebody refresh my memory on the exact order of the keys.</p> <p>Please note this is for XP.</p>
[ { "answer_id": 59358, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>I don't know of any keyboard short cuts, but are you looking for like in task manager, when you right click on a process a...
2008/09/12
[ "https://Stackoverflow.com/questions/59313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4337/" ]
I remember watching a webcast from Mark Russinovich showing the sequence of keyboard keys for a user initiated kernel dump. Can somebody refresh my memory on the exact order of the keys. Please note this is for XP.
<http://psacake.com/web/jr.asp> contains full instructions, and here's an excerpt: ``` While it may seem odd to think about purposefully causing a Blue Screen Of Death (BSOD), Microsoft includes such a provision in Windows XP. This might come in handy for testing and troubleshooting your Startup And Recovery settings, Event logging, and for demonstration purposes. Here's how to create a BSOD: Launch the Registry Editor (Regedit.exe). Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters. Go to Edit, select New | DWORD Value and name the new value CrashOnCtrlScroll. Double-click the CrashOnCtrlScroll DWORD Value, type 1 in the Value Data textbox, and click OK. Close the Registry Editor and restart Windows XP. When you want to cause a BSOD, press and hold down the [Ctrl] key on the right side of your keyboard, and then tap the [ScrollLock] key twice. Now you should see the BSOD. If your system reboots instead of displaying the BSOD, you'll have to disable the Automatically Restart setting in the System Properties dialog box. To do so, follow these steps: Press [Windows]-Break. Select the Advanced tab. Click the Settings button in the Startup And Recovery panel. Clear the Automatically Restart check box in the System Failure panel. Click OK twice. Here's how you remove the BSOD configuration: Launch the Registry Editor (Regedit.exe). Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters. Select the CrashOnCtrlScroll value, pull down the Edit menu, and select the Delete command. Close the Registry Editor and restart Windows XP. Note: Editing the registry is risky, so make sure you have a verified backup before making any changes. ``` And I may be wrong in assuming you want BSOD, so this is a Microsoft Page showing how to capture kernel dumps: <https://web.archive.org/web/20151014034039/https://support.microsoft.com/fr-ma/kb/316450>
59,322
<p>I have the following code:</p> <pre><code>SELECT &lt;column&gt;, count(*) FROM &lt;table&gt; GROUP BY &lt;column&gt; HAVING COUNT(*) &gt; 1; </code></pre> <p>Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')?</p> <p>(This question is related to a <a href="https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count">previous one</a>)</p>
[ { "answer_id": 59385, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 2, "selected": false, "text": "<p>The major performance difference is that COUNT(*) can be satisfied by examining the primary key on the table.</p>\n\n<p>i....
2008/09/12
[ "https://Stackoverflow.com/questions/59322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5662/" ]
I have the following code: ``` SELECT <column>, count(*) FROM <table> GROUP BY <column> HAVING COUNT(*) > 1; ``` Is there any difference to the results or performance if I replace the COUNT(\*) with COUNT('x')? (This question is related to a [previous one](https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count))
To say that `SELECT COUNT(*) vs COUNT(1)` results in your DBMS returning "columns" is pure bunk. That *may* have been the case long, long ago but any self-respecting query optimizer will choose some fast method to count the rows in the table - there is **NO** performance difference between `SELECT COUNT(*), COUNT(1), COUNT('this is a silly conversation')` Moreover, `SELECT(1) vs SELECT(*)` will NOT have any difference in INDEX usage -- most DBMS will actually optimize `SELECT( n ) into SELECT(*)` anyway. See the ASK TOM: Oracle has been optimizing `SELECT(n) into SELECT(*)` for the better part of a decade, if not longer: <http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789> > > problem is in count(col) to count(*) > conversion* \*\*03/23/00 05:46 pm \*\*\* one workaround is to set event 10122 to > turn off count(col) ->count(*) > optimization. Another work around is > to change the count(col) to count(*), > it means the same, when the col has a > NOT NULL constraint. The bug number is > 1215372. > > > One thing to note - if you are using COUNT(col) (don't!) and col is marked NULL, then it will actually have to count the number of occurrences in the table (either via index scan, histogram, etc. if they exist, or a full table scan otherwise). Bottom line: if what you want is the count of rows in a table, use COUNT(\*)
59,331
<p>Suppose I have <code>fileA.h</code> which declares a class <code>classA</code> with template function <code>SomeFunc&lt;T&gt;()</code>. This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of <code>SomeFunc()</code> (like for <code>SomeFunc&lt;int&gt;()</code>) in <code>fileA.C</code> (ie. not in the header file).</p> <p>If I now call <code>SomeFunc&lt;int&gt;()</code> from some other code (maybe also from another library), would it call the generic version, or the specialization?</p> <p>I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.</p>
[ { "answer_id": 59359, "author": "Brandon", "author_id": 5959, "author_profile": "https://Stackoverflow.com/users/5959", "pm_score": 0, "selected": false, "text": "<p>Unless the specialized template function is also listed in the header file, the other application will have no knowledge o...
2008/09/12
[ "https://Stackoverflow.com/questions/59331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148773/" ]
Suppose I have `fileA.h` which declares a class `classA` with template function `SomeFunc<T>()`. This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of `SomeFunc()` (like for `SomeFunc<int>()`) in `fileA.C` (ie. not in the header file). If I now call `SomeFunc<int>()` from some other code (maybe also from another library), would it call the generic version, or the specialization? I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.
It is **an error** to have a specialization for a template which is not visible at the point of call. Unfortunately, compilers are not required to diagnose this error, and can then do what they like with your code (in standardese it is "ill formed, no diagnostic required"). Technically, you need to define the specialization in the header file, but just about every compiler will handle this as you might expect: this is fixed in C++11 with the new "extern template" facility: ``` extern template<> SomeFunc<int>(); ``` This explicitly declares that the particular specialization is defined elsewhere. Many compilers support this already, some with and some without the `extern`.
59,380
<p>I have a wildcard subdomain enabled and dynamically parse the URL by passing it as-is to my <code>index.php</code> (ex. <code>somecity.domain.com</code>). </p> <p>Now, I wish to create a few subdomains that are static where I can install different application and not co-mingle with my current one (ex. <code>blog.domain.com</code>).</p> <p>My <code>.htaccess</code> currently reads:</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </code></pre> <p>Can I manipulate this <code>.htaccess</code> to achieve what I need? Can it be done through Apache?</p>
[ { "answer_id": 59382, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 0, "selected": false, "text": "<p>You'll have to configure apache for those static sub-domains. The \"catch-all\" site will be the default site configured...
2008/09/12
[ "https://Stackoverflow.com/questions/59380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6140/" ]
I have a wildcard subdomain enabled and dynamically parse the URL by passing it as-is to my `index.php` (ex. `somecity.domain.com`). Now, I wish to create a few subdomains that are static where I can install different application and not co-mingle with my current one (ex. `blog.domain.com`). My `.htaccess` currently reads: ``` RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] ``` Can I manipulate this `.htaccess` to achieve what I need? Can it be done through Apache?
Your .htaccess does nothing useful, as Apache is probably configured with DirectoryIndex index.php. Well, it does move domain.com/a to domain.com/index.php, but I doubt that is what you want. Your wildcard virtualhost works because you probably have ServerAlias \*.domain.com in your configuration, or a single virtualhost and DNS pointing to the address of your server. (When you have a single virtualhost, it shows up for any request, and the first listed virtualhost is the default one) You have to create new VirtualHosts for the static domains, leaving the default one as, well, the default one :) Check [these](http://httpd.apache.org/docs/2.2/vhosts/examples.html) [tutorials](http://wiki.apache.org/httpd/ExampleVhosts) that explain it all.
59,390
<p>In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?</p> <p>Am I going to get myself into trouble if I change this:</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset variables.foo = "a private instance variable"&gt; &lt;cffunction name = "doSomething"&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #variables.foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre> <p>to this?</p> <pre><code>&lt;cfcomponent&gt; &lt;cfset foo = "a private instance variable"&gt; &lt;cffunction name = "doSomething"&gt; &lt;cfset var bar = "a function local variable"&gt; &lt;cfreturn "I have #foo# and #bar#."&gt; &lt;/cffunction&gt; &lt;/cfcomponent&gt; </code></pre>
[ { "answer_id": 59554, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 4, "selected": true, "text": "<p>It won't matter to specify \"variables\" when you create the variable, because foo will be placed in the variables scope ...
2008/09/12
[ "https://Stackoverflow.com/questions/59390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437/" ]
In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables? Am I going to get myself into trouble if I change this: ``` <cfcomponent> <cfset variables.foo = "a private instance variable"> <cffunction name = "doSomething"> <cfset var bar = "a function local variable"> <cfreturn "I have #variables.foo# and #bar#."> </cffunction> </cfcomponent> ``` to this? ``` <cfcomponent> <cfset foo = "a private instance variable"> <cffunction name = "doSomething"> <cfset var bar = "a function local variable"> <cfreturn "I have #foo# and #bar#."> </cffunction> </cfcomponent> ```
It won't matter to specify "variables" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable. ``` <cfcomponent> <cfset foo = "a private instance variable"> <cffunction name="doSomething"> <cfargument name="foo" required="yes"/> <cfset var bar = "a function local variable"> <cfreturn "I have #foo# and #bar#."> </cffunction> <cffunction name="doAnotherThing"> <cfargument name="foo" required="yes"/> <cfset var bar = "a function local variable"> <cfreturn "I have #variables.foo# and #bar#."> </cffunction> </cfcomponent> ``` doSomething("args") returns "I have **args** and a **function local variable**" doAnotherThing("args") returns "I have **a private instance of a variable** and a **function local variable**."
59,396
<p>I have a Data Access Object TransactionDao. When you call TransactionDao.Save(transaction) I would like for it to setting a transaction.IsSaved=true flag (this is a simplification the actual thing I'm trying to do is not quite so banal). So when mocking my TransactionDao with RhinoMocks how can I indicate that it should transform its input?</p> <p>Ideally I would like to write something like this:</p> <pre><code>Expect.Call(delegate {dao.Save(transaction);}).Override(x =&gt; x.IsSaved=true); </code></pre> <p>Does anyone know how to do this?</p> <hr> <p>Though I got a hint how to do it from the answer specified below the actual type signature is off, you have to do something like this: Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:</p> <pre><code>public delegate void FakeSave(Transaction t); ... Expect.Call(delegate {dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.IsSaved = true; })); </code></pre>
[ { "answer_id": 59420, "author": "chrissie1", "author_id": 2936, "author_profile": "https://Stackoverflow.com/users/2936", "pm_score": -1, "selected": false, "text": "<p>you should mock the transaction and make it return true fo IsSaved, if you can mock the transaction of course.</p>\n\n<...
2008/09/12
[ "https://Stackoverflow.com/questions/59396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have a Data Access Object TransactionDao. When you call TransactionDao.Save(transaction) I would like for it to setting a transaction.IsSaved=true flag (this is a simplification the actual thing I'm trying to do is not quite so banal). So when mocking my TransactionDao with RhinoMocks how can I indicate that it should transform its input? Ideally I would like to write something like this: ``` Expect.Call(delegate {dao.Save(transaction);}).Override(x => x.IsSaved=true); ``` Does anyone know how to do this? --- Though I got a hint how to do it from the answer specified below the actual type signature is off, you have to do something like this: Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this: ``` public delegate void FakeSave(Transaction t); ... Expect.Call(delegate {dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.IsSaved = true; })); ```
Gorge, The simplest solution, which I found, applied to your question is the following: ``` Expect.Call(() => dao.Save(transaction)) .Do(new Action<Transaction>(x => x.IsSaved = true)); ``` So you don't need to create a special delegate or anything else. Just use Action which is in standard .NET 3.5 libraries. Hope this help. Frantisek
59,422
<p>Is accessing a <strong>bool</strong> field atomic in C#? In particular, do I need to put a lock around:</p> <pre><code>class Foo { private bool _bar; //... in some function on any thread (or many threads) _bar = true; //... same for a read if (_bar) { ... } } </code></pre>
[ { "answer_id": 59430, "author": "Larsenal", "author_id": 337, "author_profile": "https://Stackoverflow.com/users/337", "pm_score": 8, "selected": true, "text": "<p><strong>Yes.</strong></p>\n\n<blockquote>\n <p>Reads and writes of the following data types are atomic: bool, char, byte, s...
2008/09/12
[ "https://Stackoverflow.com/questions/59422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/838/" ]
Is accessing a **bool** field atomic in C#? In particular, do I need to put a lock around: ``` class Foo { private bool _bar; //... in some function on any thread (or many threads) _bar = true; //... same for a read if (_bar) { ... } } ```
**Yes.** > > Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. > > > as found in [C# Language Spec](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references). Edit: It's probably also worthwhile understanding the [**volatile**](https://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.140).aspx) keyword.
59,423
<p>I've got the following in my .css file creating a little image next to each link on my site:</p> <pre class="lang-css prettyprint-override"><code>div.post .text a[href^="http:"] { background: url(../../pics/remote.gif) right top no-repeat; padding-right: 10px; white-space: nowrap; } </code></pre> <p>How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves?</p>
[ { "answer_id": 59448, "author": "Thunder3", "author_id": 2832, "author_profile": "https://Stackoverflow.com/users/2832", "pm_score": 1, "selected": false, "text": "<p>It might be worth it to add a class to those <code>&lt;a&gt;</code> tags and then add another declaration to remove the b...
2008/09/12
[ "https://Stackoverflow.com/questions/59423", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1683/" ]
I've got the following in my .css file creating a little image next to each link on my site: ```css div.post .text a[href^="http:"] { background: url(../../pics/remote.gif) right top no-repeat; padding-right: 10px; white-space: nowrap; } ``` How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves?
If you set the background color and have a negative right margin on the image, the image will cover the external link image. Example: ```css a[href^="http:"] { background: url(http://en.wikipedia.org/skins-1.5/monobook/external.png) right center no-repeat; padding-right: 14px; white-space: nowrap; } a[href^="http:"] img { margin-right: -14px; border: medium none; background-color: red; } ``` ```html <a href="http://www.google.ca">Google</a> <br/> <a href="http://www.google.ca"> <img src="http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/50px-Commons-logo.svg.png" /> </a> ``` edit: If you've got a patterned background this isn't going to look great for images that have transparency. Also, your `href^=` selector won't work on IE7 but you probably knew that already
59,425
<p>I'm using MySQL in particular, but I'm hoping for a cross-vendor solution. I'm using the NOW() function to add a timestamp as a column for each record.</p> <pre><code>INSERT INTO messages (typeId, messageTime, stationId, message) VALUES (?, NOW(), ?, ?) </code></pre>
[ { "answer_id": 59437, "author": "Alexander Morland", "author_id": 4013, "author_profile": "https://Stackoverflow.com/users/4013", "pm_score": 3, "selected": true, "text": "<pre><code>SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) &lt;= messageTime\n</code></pre>\n" }, ...
2008/09/12
[ "https://Stackoverflow.com/questions/59425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
I'm using MySQL in particular, but I'm hoping for a cross-vendor solution. I'm using the NOW() function to add a timestamp as a column for each record. ``` INSERT INTO messages (typeId, messageTime, stationId, message) VALUES (?, NOW(), ?, ?) ```
``` SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime ```
59,444
<p>Is there a system stored procedure to get the version #?</p>
[ { "answer_id": 59449, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 5, "selected": false, "text": "<p>SELECT @@VERSION</p>\n" }, { "answer_id": 59457, "author": "Joe Kuemerle", "author_id": 4273, "author_...
2008/09/12
[ "https://Stackoverflow.com/questions/59444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
Is there a system stored procedure to get the version #?
Try ``` SELECT @@VERSION ``` or for SQL Server 2000 and above the following is easier to parse :) ``` SELECT SERVERPROPERTY('productversion') , SERVERPROPERTY('productlevel') , SERVERPROPERTY('edition') ``` From: <http://support.microsoft.com/kb/321185>
59,451
<p>How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.</p> <p>Edit: Here's the code I'm now using this for, based on the answer from Santiago below.</p> <pre><code>public DataTemplate Create(Type type) { return (DataTemplate)XamlReader.Load( @"&lt;DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""&gt; &lt;" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/&gt; &lt;/DataTemplate&gt;" ); } </code></pre> <p>This works really nicely and allows me to change the binding on the fly. </p>
[ { "answer_id": 62871, "author": "jarda", "author_id": 6601, "author_profile": "https://Stackoverflow.com/users/6601", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.datatemplate%28v=vs.95%29.aspx\" rel=\"nofollow noreferrer\...
2008/09/12
[ "https://Stackoverflow.com/questions/59451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5932/" ]
How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight. Edit: Here's the code I'm now using this for, based on the answer from Santiago below. ``` public DataTemplate Create(Type type) { return (DataTemplate)XamlReader.Load( @"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/> </DataTemplate>" ); } ``` This works really nicely and allows me to change the binding on the fly.
Although you cannot programatically create it, you can load it from a XAML string in code like this: ``` public static DataTemplate Create(Type type) { return (DataTemplate) XamlReader.Load( @"<DataTemplate xmlns=""http://schemas.microsoft.com/client/2007""> <" + type.Name + @"/> </DataTemplate>" ); } ``` The snippet above creates a data template containing a single control, which may be a user control with the contents you need.
59,456
<p>I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.</p> <p>Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, _File</p> <p>However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?</p> <pre><code>&lt;Menu&gt; &lt;MenuItem&gt; &lt;MenuItem.Header&gt; &lt;UserControl&gt; &lt;Image Source="..." /&gt; &lt;Label Text="_Open" /&gt; &lt;/UserControl&gt; &lt;/MenuItem.Header&gt; &lt;/MenuItem&gt; ... </code></pre>
[ { "answer_id": 59706, "author": "Alan Le", "author_id": 1133, "author_profile": "https://Stackoverflow.com/users/1133", "pm_score": 2, "selected": false, "text": "<p>The problem is you placed the image inside of the content of the MenuHeader which means that you'll lose the accelerator k...
2008/09/12
[ "https://Stackoverflow.com/questions/59456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item. Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, \_File However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following? ``` <Menu> <MenuItem> <MenuItem.Header> <UserControl> <Image Source="..." /> <Label Text="_Open" /> </UserControl> </MenuItem.Header> </MenuItem> ... ```
I think the Icon property fits your needs. However to answer the original question, it is possible to retain the Accelerator functionality when you compose the content of your menuitem. **If you have nested content in a MenuItem you need to define the AccessText property explicitly** like in the first one below. When you use the inline form, this is automagically taken care of. ``` <Menu> <MenuItem> <MenuItem.Header> <StackPanel Orientation="Horizontal"> <Image Source="Images/Open.ico" /> <AccessText>_Open..</AccessText> </StackPanel> </MenuItem.Header> </MenuItem> <MenuItem Header="_Close" /> </Menu> ```
59,465
<p>By default the webjump hotlist has the following which I use quite often:</p> <pre><code>M-x webjump RET Google M-x webjump RET Wikipedia </code></pre> <p>How can I add 'Stackoverflow' to my list?</p>
[ { "answer_id": 59476, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 2, "selected": true, "text": "<p>Here's some example code in <a href=\"http://www.opensource.apple.com/darwinsource/10.0/emacs-39/emacs/lisp/webjump.el\" ...
2008/09/12
[ "https://Stackoverflow.com/questions/59465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
By default the webjump hotlist has the following which I use quite often: ``` M-x webjump RET Google M-x webjump RET Wikipedia ``` How can I add 'Stackoverflow' to my list?
Here's some example code in [a webjump.el file on a site run by Apple:](http://www.opensource.apple.com/darwinsource/10.0/emacs-39/emacs/lisp/webjump.el) ``` ;; (require 'webjump) ;; (global-set-key "\C-cj" 'webjump) ;; (setq webjump-sites ;; (append '( ;; ("My Home Page" . "www.someisp.net/users/joebobjr/") ;; ("Pop's Site" . "www.joebob-and-son.com/") ;; ) ;; webjump-sample-sites)) ```
59,472
<p>Is there a way (or shortcut) to tell VS 2008 that it cuts a line like this:</p> <p><strong>Before:</strong></p> <pre><code>Some Text here This gets cut Some Code there </code></pre> <p><strong>After:</strong></p> <pre><code>Some Text here Some Code there </code></pre> <p><strong>What I want:</strong></p> <pre><code>Some Text here Some Code there </code></pre> <p>PS: I don't want to select the whole line or something like this... only the text I want to cut.</p>
[ { "answer_id": 59513, "author": "Tomas Sedovic", "author_id": 2239, "author_profile": "https://Stackoverflow.com/users/2239", "pm_score": 3, "selected": true, "text": "<p>Unless I misunderstood you:<br>\nJust place cursor on the line you want to cut (no selection) and press <kbd>Ctrl</kb...
2008/09/12
[ "https://Stackoverflow.com/questions/59472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6143/" ]
Is there a way (or shortcut) to tell VS 2008 that it cuts a line like this: **Before:** ``` Some Text here This gets cut Some Code there ``` **After:** ``` Some Text here Some Code there ``` **What I want:** ``` Some Text here Some Code there ``` PS: I don't want to select the whole line or something like this... only the text I want to cut.
Unless I misunderstood you: Just place cursor on the line you want to cut (no selection) and press `Ctrl` + `x`. That cuts the line (leaving no blanks) and puts the text in the Clipboard. (tested in *MS VC# 2008 Express* with no additional settings I'm aware of) Is that what you want?
59,483
<pre><code>1167 ptr = (void*)getcwd(cwd, MAX_PATH_LENGTH-1); (gdb) n 1168 if (!ptr) { (gdb) print ptr $1 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa" (gdb) print &amp;cwd $2 = (char (*)[3500]) 0xbff2d96c (gdb) print strlen(cwd) $3 = 36 (gdb) print "%s",cwd $4 = "/media/MMC-SD/partition1/aaaaaaaaaaa", '\0' &lt;repeats 912 times&gt;, "��O�001\000\000\000\000��027\000\000\000�3����EL鷠3�000��027\000\000\000\000\000\000\000\027\000\000\000\000��/�027\000\000\000�3����N����\230���鷠3�000��027\000\000\000\000\000\000\000��000\000\000\000\001\000\000\000��M鷠3����\000\000\000\000.\231�027��w\005\b\001\000"... (gdb) print "%s", ptr $5 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa" (gdb) Quit </code></pre> <p>Why is ptr printing the string correctly but cwd not; this also affects the program and it crashes if I try to use the cwd...</p> <p>[edit: turns out that crash was caused by a stupid buffer overflow on this var... grr...not gdb, but the print question was still valid]</p>
[ { "answer_id": 59509, "author": "oliver", "author_id": 2148773, "author_profile": "https://Stackoverflow.com/users/2148773", "pm_score": 1, "selected": false, "text": "<p>That <code>ptr</code> is displayed as nicely-formatted string and <code>cwd</code> as \"byte buffer\" is probably spe...
2008/09/12
[ "https://Stackoverflow.com/questions/59483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5330/" ]
``` 1167 ptr = (void*)getcwd(cwd, MAX_PATH_LENGTH-1); (gdb) n 1168 if (!ptr) { (gdb) print ptr $1 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa" (gdb) print &cwd $2 = (char (*)[3500]) 0xbff2d96c (gdb) print strlen(cwd) $3 = 36 (gdb) print "%s",cwd $4 = "/media/MMC-SD/partition1/aaaaaaaaaaa", '\0' <repeats 912 times>, "��O�001\000\000\000\000��027\000\000\000�3����EL鷠3�000��027\000\000\000\000\000\000\000\027\000\000\000\000��/�027\000\000\000�3����N����\230���鷠3�000��027\000\000\000\000\000\000\000��000\000\000\000\001\000\000\000��M鷠3����\000\000\000\000.\231�027��w\005\b\001\000"... (gdb) print "%s", ptr $5 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa" (gdb) Quit ``` Why is ptr printing the string correctly but cwd not; this also affects the program and it crashes if I try to use the cwd... [edit: turns out that crash was caused by a stupid buffer overflow on this var... grr...not gdb, but the print question was still valid]
The reason that `cwd` is printed differently in `gdb` is because `gdb` knows that `ptr` is a `char *` (I guess) and that `cwd` is an array of length `3500` (as shown in your output). So when printing `ptr` it prints the pointer value (and as a service also the string it points to) and when printing `cwd` it prints the *whole* array. I don't see any reason why using `cwd` instead of `ptr` would lead to problems, but I would need to see some code to be sure.
59,515
<p>I am new to all the anonymous features and need some help. I have gotten the following to work:</p> <pre><code>public void FakeSaveWithMessage(Transaction t) { t.Message = "I drink goats blood"; } public delegate void FakeSave(Transaction t); public void SampleTestFunction() { Expect.Call(delegate { _dao.Save(t); }).Do(new FakeSave(FakeSaveWithMessage)); } </code></pre> <p>But this is totally ugly and I would like to have the inside of the Do to be an anonymous method or even a lambda if it is possible. I tried:</p> <pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(delegate(Transaction t2) { t2.Message = "I drink goats blood"; }); </code></pre> <p>and</p> <pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(delegate { t.Message = "I drink goats blood"; }); </code></pre> <p>but these give me</p> <blockquote> <p>Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type** compile errors.</p> </blockquote> <p>What am I doing wrong?</p> <hr> <p>Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:</p> <pre><code>public delegate void FakeSave(Transaction t); Expect.Call(delegate { _dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.Message = expected_msg; })); </code></pre>
[ { "answer_id": 59531, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "<p>Try something like:</p>\n\n<pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(new EventHandler(delegate(Transac...
2008/09/12
[ "https://Stackoverflow.com/questions/59515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I am new to all the anonymous features and need some help. I have gotten the following to work: ``` public void FakeSaveWithMessage(Transaction t) { t.Message = "I drink goats blood"; } public delegate void FakeSave(Transaction t); public void SampleTestFunction() { Expect.Call(delegate { _dao.Save(t); }).Do(new FakeSave(FakeSaveWithMessage)); } ``` But this is totally ugly and I would like to have the inside of the Do to be an anonymous method or even a lambda if it is possible. I tried: ``` Expect.Call(delegate { _dao.Save(t); }).Do(delegate(Transaction t2) { t2.Message = "I drink goats blood"; }); ``` and ``` Expect.Call(delegate { _dao.Save(t); }).Do(delegate { t.Message = "I drink goats blood"; }); ``` but these give me > > Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type\*\* compile errors. > > > What am I doing wrong? --- Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this: ``` public delegate void FakeSave(Transaction t); Expect.Call(delegate { _dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.Message = expected_msg; })); ```
That's a well known error message. Check the link below for a more detailed discussion. <http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/> Basically you just need to put a cast in front of your anonymous delegate (your lambda expression). In case the link ever goes down, here is a copy of the post: > > **They are Anonymous Methods, not > Anonymous Delegates.** > > Posted on December 22, 2007 by staceyw1 > > > It is not just a talking point because > we want to be difficult. It helps us > reason about what exactly is going on. > To be clear, there is \*no such thing > as an anonymous delegate. They don’t > exist (not yet). They are "Anonymous > Methods" – period. It matters in how > we think of them and how we talk about > them. Lets take a look at the > anonymous method statement "delegate() > {…}". This is actually two different > operations and when we think of it > this way, we will never be confused > again. The first thing the compiler > does is create the anonymous method > under the covers using the inferred > delegate signature as the method > signature. It is not correct to say > the method is "unnamed" because it > does have a name and the compiler > assigns it. It is just hidden from > normal view. The next thing it does > is create a delegate object of the > required type to wrap the method. This > is called delegate inference and can > be the source of this confusion. For > this to work, the compiler must be > able to figure out (i.e. infer) what > delegate type it will create. It has > to be a known concrete type. Let > write some code to see why. > > > ``` private void MyMethod() { } ``` > > **Does not compile:** > > > ``` 1) Delegate d = delegate() { }; // Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type 2) Delegate d2 = MyMethod; // Cannot convert method group ‘MyMethod’ to non-delegate type ‘System.Delegate’ 3) Delegate d3 = (WaitCallback)MyMethod; // No overload for ‘MyMethod’ matches delegate ‘System.Threading.WaitCallback’ ``` > > Line 1 does not compile because the > compiler can not infer any delegate > type. It can plainly see the signature > we desire, but there is no concrete > delegate type the compiler can see. > It could create an anonymous type of > type delegate for us, but it does not > work like that. Line 2 does not > compile for a similar reason. Even > though the compiler knows the method > signature, we are not giving it a > delegate type and it is not just going > to pick one that would happen to work > (not what side effects that could > have). Line 3 does not work because > we purposely mismatched the method > signature with a delegate having a > different signature (as WaitCallback > takes and object). > > > **Compiles:** > > > ``` 4) Delegate d4 = (MethodInvoker)MyMethod; // Works because we cast to a delegate type of the same signature. 5) Delegate d5 = (Action)delegate { }; // Works for same reason as d4. 6) Action d6 = MyMethod; // Delegate inference at work here. New Action delegate is created and assigned. ``` > > In contrast, these work. Line 1 works > because we tell the compiler what > delegate type to use and they match, > so it works. Line 5 works for the > same reason. Note we used the special > form of "delegate" without the parens. > The compiler infers the method > signature from the cast and creates > the anonymous method with the same > signature as the inferred delegate > type. Line 6 works because the > MyMethod() and Action use same > signature. > > > I hope this helps. > > > Also see: > <http://msdn.microsoft.com/msdnmag/issues/04/05/C20/> > > >
59,544
<p>I have the following tables, the <code>groups</code> table which contains hierarchically ordered groups and <code>group_member</code> which stores which groups a user belongs to. </p> <pre><code>groups --------- id parent_id name group_member --------- id group_id user_id ID PARENT_ID NAME --------------------------- 1 NULL Cerebra 2 1 CATS 3 2 CATS 2.0 4 1 Cerepedia 5 4 Cerepedia 2.0 6 1 CMS ID GROUP_ID USER_ID --------------------------- 1 1 3 2 1 4 3 1 5 4 2 7 5 2 6 6 4 6 7 5 12 8 4 9 9 1 10 </code></pre> <p>I want to retrieve the visible groups for a given user. That it is to say groups a user belongs to and children of these groups. For example, with the above data: </p> <pre><code>USER VISIBLE_GROUPS 9 4, 5 3 1,2,4,5,6 12 5 </code></pre> <p>I am getting these values using recursion and several database queries. But I would like to know if it is possible to do this with a single SQL query to improve my app performance. I am using MySQL. </p>
[ { "answer_id": 59594, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 0, "selected": false, "text": "<p>I don't think that this can be accomplished without using recursion. You can accomplish it with with a single stored pro...
2008/09/12
[ "https://Stackoverflow.com/questions/59544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I have the following tables, the `groups` table which contains hierarchically ordered groups and `group_member` which stores which groups a user belongs to. ``` groups --------- id parent_id name group_member --------- id group_id user_id ID PARENT_ID NAME --------------------------- 1 NULL Cerebra 2 1 CATS 3 2 CATS 2.0 4 1 Cerepedia 5 4 Cerepedia 2.0 6 1 CMS ID GROUP_ID USER_ID --------------------------- 1 1 3 2 1 4 3 1 5 4 2 7 5 2 6 6 4 6 7 5 12 8 4 9 9 1 10 ``` I want to retrieve the visible groups for a given user. That it is to say groups a user belongs to and children of these groups. For example, with the above data: ``` USER VISIBLE_GROUPS 9 4, 5 3 1,2,4,5,6 12 5 ``` I am getting these values using recursion and several database queries. But I would like to know if it is possible to do this with a single SQL query to improve my app performance. I am using MySQL.
Two things come to mind: **1 -** You can repeatedly outer-join the table to itself to recursively walk up your tree, as in: ``` SELECT * FROM MY_GROUPS MG1 ,MY_GROUPS MG2 ,MY_GROUPS MG3 ,MY_GROUPS MG4 ,MY_GROUPS MG5 ,MY_GROUP_MEMBERS MGM WHERE MG1.PARENT_ID = MG2.UNIQID (+) AND MG1.UNIQID = MGM.GROUP_ID (+) AND MG2.PARENT_ID = MG3.UNIQID (+) AND MG3.PARENT_ID = MG4.UNIQID (+) AND MG4.PARENT_ID = MG5.UNIQID (+) AND MGM.USER_ID = 9 ``` That's gonna give you results like this: ``` UNIQID PARENT_ID NAME UNIQID_1 PARENT_ID_1 NAME_1 UNIQID_2 PARENT_ID_2 NAME_2 UNIQID_3 PARENT_ID_3 NAME_3 UNIQID_4 PARENT_ID_4 NAME_4 UNIQID_5 GROUP_ID USER_ID 4 2 Cerepedia 2 1 CATS 1 null Cerebra null null null null null null 8 4 9 ``` The limit here is that you must add a new join for each "level" you want to walk up the tree. If your tree has less than, say, 20 levels, then you could probably get away with it by creating a view that showed 20 levels from every user. **2 -** The only other approach that I know of is to create a recursive database function, and call that from code. You'll still have some lookup overhead that way (i.e., your # of queries will still be equal to the # of levels you are walking on the tree), but overall it should be faster since it's all taking place within the database. I'm not sure about MySql, but in Oracle, such a function would be similar to this one (you'll have to change the table and field names; I'm just copying something I did in the past): ``` CREATE OR REPLACE FUNCTION GoUpLevel(WO_ID INTEGER, UPLEVEL INTEGER) RETURN INTEGER IS BEGIN DECLARE iResult INTEGER; iParent INTEGER; BEGIN IF UPLEVEL <= 0 THEN iResult := WO_ID; ELSE SELECT PARENT_ID INTO iParent FROM WOTREE WHERE ID = WO_ID; iResult := GoUpLevel(iParent,UPLEVEL-1); --recursive END; RETURN iResult; EXCEPTION WHEN NO_DATA_FOUND THEN RETURN NULL; END; END GoUpLevel; / ```
59,557
<p>is there an easy way to transform HTML into markdown with JAVA?</p> <p>I am currently using the Java <strong><a href="http://code.google.com/p/markdownj/" rel="noreferrer">MarkdownJ</a></strong> library to transform markdown to html.</p> <pre><code>import com.petebevin.markdown.MarkdownProcessor; ... public static String getHTML(String markdown) { MarkdownProcessor markdown_processor = new MarkdownProcessor(); return markdown_processor.markdown(markdown); } public static String getMarkdown(String html) { /* TODO Ask stackoverflow */ } </code></pre>
[ { "answer_id": 178278, "author": "myabc", "author_id": 3789, "author_profile": "https://Stackoverflow.com/users/3789", "pm_score": 2, "selected": false, "text": "<p>I am working on the same issue, and experimenting with a couple different techniques.</p>\n\n<p>The answer above could work...
2008/09/12
[ "https://Stackoverflow.com/questions/59557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
is there an easy way to transform HTML into markdown with JAVA? I am currently using the Java **[MarkdownJ](http://code.google.com/p/markdownj/)** library to transform markdown to html. ``` import com.petebevin.markdown.MarkdownProcessor; ... public static String getHTML(String markdown) { MarkdownProcessor markdown_processor = new MarkdownProcessor(); return markdown_processor.markdown(markdown); } public static String getMarkdown(String html) { /* TODO Ask stackoverflow */ } ```
There is a great library for JS called [Turndown](https://github.com/domchristie/turndown), you can try it online [here](https://mixmark-io.github.io/turndown/). It works for htmls that the accepted answer errors out. I needed it for Java (as the question), so I ported it. The library for Java is called [CopyDown](https://github.com/furstenheim/copy-down), it has the same test suite as Turndown and I've tried it with real examples that the accepted answer was throwing errors. To install with gradle: ``` dependencies { compile 'io.github.furstenheim:copy_down:1.0' } ``` Then to use it: ```java CopyDown converter = new CopyDown(); String myHtml = "<h1>Some title</h1><div>Some html<p>Another paragraph</p></div>"; String markdown = converter.convert(myHtml); System.out.println(markdown); > Some title\n==========\n\nSome html\n\nAnother paragraph\n ``` PS. It has MIT license
59,599
<p>I have a large classic ASP app that I have to maintain, and I repeatedly find myself thwarted by the lack of short-circuit evaluation capability. E.g., VBScript won't let you get away with:</p> <pre><code>if not isNull(Rs("myField")) and Rs("myField") &lt;&gt; 0 then ... </code></pre> <p>...because if Rs("myField") is null, you get an error in the second condition, comparing null to 0. So I'll typically end up doing this instead:</p> <pre><code>dim myField if isNull(Rs("myField")) then myField = 0 else myField = Rs("myField") end if if myField &lt;&gt; 0 then ... </code></pre> <p>Obviously, the verboseness is pretty appalling. Looking around this large code base, the best workaround I've found is to use a function the original programmer wrote, called TernaryOp, which basically grafts in ternary operator-like functionality, but I'm still stuck using a temporary variable that would not be necessary in a more full-featured language. Is there a better way? Some super-secret way that short-circuiting really does exist in VBScript?</p>
[ { "answer_id": 59606, "author": "busse", "author_id": 5702, "author_profile": "https://Stackoverflow.com/users/5702", "pm_score": 3, "selected": false, "text": "<p>Nested IFs (only slightly less verbose):</p>\n\n<pre><code>if not isNull(Rs(\"myField\")) Then\n if Rs(\"myField\") &lt;&g...
2008/09/12
[ "https://Stackoverflow.com/questions/59599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1818/" ]
I have a large classic ASP app that I have to maintain, and I repeatedly find myself thwarted by the lack of short-circuit evaluation capability. E.g., VBScript won't let you get away with: ``` if not isNull(Rs("myField")) and Rs("myField") <> 0 then ... ``` ...because if Rs("myField") is null, you get an error in the second condition, comparing null to 0. So I'll typically end up doing this instead: ``` dim myField if isNull(Rs("myField")) then myField = 0 else myField = Rs("myField") end if if myField <> 0 then ... ``` Obviously, the verboseness is pretty appalling. Looking around this large code base, the best workaround I've found is to use a function the original programmer wrote, called TernaryOp, which basically grafts in ternary operator-like functionality, but I'm still stuck using a temporary variable that would not be necessary in a more full-featured language. Is there a better way? Some super-secret way that short-circuiting really does exist in VBScript?
Maybe not the best way, but it certainly works... Also, if you are in vb6 or .net, you can have different methods that cast to proper type too. ``` if cint( getVal( rs("blah"), "" ) )<> 0 then 'do something end if function getVal( v, replacementVal ) if v is nothing then getVal = replacementVal else getVal = v end if end function ```
59,628
<p>I have a page results page (you get there after submitting your search query elsewhere) whit a whole bunch of gridviews for different type of data objects.</p> <p>Obviously, some of the queries take longer than the others. How can I make each gridview render as soon as it has the data it needs?</p> <p>This has been tricky for me because it must work on a postback as well as a pageload. Also, the object data sources just fire automatically on page load/postback; I'm not calling any methods programatically to get the data. Will I have to change this? </p>
[ { "answer_id": 59652, "author": "Gareth Jenkins", "author_id": 1521, "author_profile": "https://Stackoverflow.com/users/1521", "pm_score": 0, "selected": false, "text": "<p>Could you put the DataGrids inside panels that have their visibility set to false, then call a client-side javascri...
2008/09/12
[ "https://Stackoverflow.com/questions/59628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/781/" ]
I have a page results page (you get there after submitting your search query elsewhere) whit a whole bunch of gridviews for different type of data objects. Obviously, some of the queries take longer than the others. How can I make each gridview render as soon as it has the data it needs? This has been tricky for me because it must work on a postback as well as a pageload. Also, the object data sources just fire automatically on page load/postback; I'm not calling any methods programatically to get the data. Will I have to change this?
@Gareth Jenkins The page will execute all of the queries before returning even the first update panel, so he won't save any time there. The trick to do this is to move each of your complex gridviews into a user control, in the user control, get rid of the Object DataSource crap, and do your binding in the code behind. Write your bind code so that it only binds in this situation: ``` if (this.isPostBack && ScriptManager.IsInAsyncPostback) ``` Then, in the page, programaticly refresh the update panel using javascript once the page has loaded, and you'll get each individual gridview rendering once its ready.
59,635
<p>Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system.</p> <p>Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning.</p> <p>First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version.</p> <p>So I added the define for <code>_BIND_TO_CURRENT_VCLIBS_VERSION=1</code> to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this.</p> <p>I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors. </p> <p>Running the app still gets the following error:</p> <blockquote> <blockquote> <p>The application failed to initialize properly (0xc0150002). Click on OK to terminate the application.</p> </blockquote> </blockquote> <p>None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message).</p> <p>Any one had any similar problem with SP1?</p> <p>Options:<ul> <li>Find the problem and fix it so it works as it should (preferred) <li>Install the redist <li>dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!)</ul></p> <p><b>Edit:</b> I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error:</p> <blockquote> <p>c:\Program Files\...\...\X.exe</p> <p>This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.</p> </blockquote> <p>Has no-one else had to deal with this issue?</p> <p><b>Edit:</b> Just for grins, I downloaded and ran the vcredist_x86.exe for VS2008SP1 on my test machine. <b><i>It</i></b> works. With the SP1 DLLs. And my RTM linked app. But <b>NOT</b> in a private side-by-side distribution that worked pre-SP1.</p>
[ { "answer_id": 70808, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 6, "selected": true, "text": "<p>I have battled this problem myself last week and consider myself somewhat of an expert now ;)</p>\n\n<p>I'm 99% sure that no...
2008/09/12
[ "https://Stackoverflow.com/questions/59635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1441/" ]
Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system. Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning. First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version. So I added the define for `_BIND_TO_CURRENT_VCLIBS_VERSION=1` to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this. I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors. Running the app still gets the following error: > > > > > > The application failed to initialize properly (0xc0150002). Click on OK to terminate the application. > > > > > > > > > None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message). Any one had any similar problem with SP1? Options:* Find the problem and fix it so it works as it should (preferred) * Install the redist * dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!) **Edit:** I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error: > > c:\Program Files\...\...\X.exe > > > This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. > > > Has no-one else had to deal with this issue? **Edit:** Just for grins, I downloaded and ran the vcredist\_x86.exe for VS2008SP1 on my test machine. ***It*** works. With the SP1 DLLs. And my RTM linked app. But **NOT** in a private side-by-side distribution that worked pre-SP1.
I have battled this problem myself last week and consider myself somewhat of an expert now ;) I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put ``` #define _BIND_TO_CURRENT_MFC_VERSION 1 #define _BIND_TO_CURRENT_CRT_VERSION 1 ``` into *every* project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled. There are more flags that define what versions to bind to; it's documented on <http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx> . As an alternative to the lines above, you can also put ``` #define _BIND_TO_CURRENT_VCLIBS_VERSION 1 ``` which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP). Then, check what the embedded manifest says. Download XM Resource Editor: <http://www.wilsonc.demon.co.uk/d10resourceeditor.htm>. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version. What I found is that in many cases, *both* versions were included in the manifest. This means that some libraries use the sp1 version and others don't. A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the `_BIND_TO_CURRENT_CRT_VERSION` preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere. Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.
59,642
<p>What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application. </p>
[ { "answer_id": 70808, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 6, "selected": true, "text": "<p>I have battled this problem myself last week and consider myself somewhat of an expert now ;)</p>\n\n<p>I'm 99% sure that no...
2008/09/12
[ "https://Stackoverflow.com/questions/59642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2723/" ]
What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application.
I have battled this problem myself last week and consider myself somewhat of an expert now ;) I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put ``` #define _BIND_TO_CURRENT_MFC_VERSION 1 #define _BIND_TO_CURRENT_CRT_VERSION 1 ``` into *every* project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled. There are more flags that define what versions to bind to; it's documented on <http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx> . As an alternative to the lines above, you can also put ``` #define _BIND_TO_CURRENT_VCLIBS_VERSION 1 ``` which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP). Then, check what the embedded manifest says. Download XM Resource Editor: <http://www.wilsonc.demon.co.uk/d10resourceeditor.htm>. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version. What I found is that in many cases, *both* versions were included in the manifest. This means that some libraries use the sp1 version and others don't. A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the `_BIND_TO_CURRENT_CRT_VERSION` preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere. Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.
59,648
<p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: <em><a href="http://www.gallup.com" rel="nofollow noreferrer">www.gallup.com</a></em> and <em><a href="http://www.rassmussenreports.com" rel="nofollow noreferrer">www.rassmussenreports.com</a></em></p> <p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)</p> <p>Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations.</p> <p>And this is my problem. At the end of the test I have an array in a single variable that looks something like this:</p> <pre><code>[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0] </code></pre> <p>The program currently produces one array for each correct simulation. <em>I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?</em></p> <p>How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.</p> <p>Code testing for McCain:</p> <pre><code> test = [] while x &lt; 5: test = round(100*random.random()) mctest.append(test) x = x +1 mctestavg = (mctest[0] + mctest[1] + mctest[2])/3 #mcavg is real data if mctestavg == mcavg[2]: mcwork = mctest </code></pre> <p>How do I repeat without creating multiple mcwork vars?</p>
[ { "answer_id": 59662, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 2, "selected": false, "text": "<p>Are you talking about doing this?</p>\n\n<pre><code>&gt;&gt;&gt; a = [ ['a', 'b'], ['c', 'd'] ]\n&gt;&gt;&gt; a[1]...
2008/09/12
[ "https://Stackoverflow.com/questions/59648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6163/" ]
I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: *[www.gallup.com](http://www.gallup.com)* and *[www.rassmussenreports.com](http://www.rassmussenreports.com)* I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages) Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations. And this is my problem. At the end of the test I have an array in a single variable that looks something like this: ``` [40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0] ``` The program currently produces one array for each correct simulation. *I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?* How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want. Code testing for McCain: ``` test = [] while x < 5: test = round(100*random.random()) mctest.append(test) x = x +1 mctestavg = (mctest[0] + mctest[1] + mctest[2])/3 #mcavg is real data if mctestavg == mcavg[2]: mcwork = mctest ``` How do I repeat without creating multiple mcwork vars?
Would something like this work? ``` from random import randint mcworks = [] for n in xrange(NUM_ITERATIONS): mctest = [randint(0, 100) for i in xrange(5)] if sum(mctest[:3])/3 == mcavg[2]: mcworks.append(mctest) # mcavg is real data ``` In the end, you are left with a list of valid `mctest` lists. What I changed: * Used a [list comprehension](https://web.archive.org/web/20080928230016/http://docs.python.org:80/tut/node7.html#SECTION007140000000000000000) to build the data instead of a for loop * Used `random.randint` to get random integers * Used [slices](http://docs.python.org/tut/node5.html) and `sum` to calculate the average of the first three items * (To answer your actual question :-) ) Put the results in a list `mcworks`, instead of creating a new variable for every iteration
59,651
<p>I have a web page that I have hooked up to a <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="nofollow noreferrer">stored procedure</a>. In this SQL data source, I have a parameter that I'm passing back to the stored procedure of type int. </p> <p><a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> seems to want to default to <em>int32</em>, but the number won't get higher than 6. Is it ok to override the ASP.NET default and put in 16 or will there be a conflict somewhere down the road?</p> <p>specification: the database field has a length of 4 and precision of 10, if that makes a difference in the answer.</p>
[ { "answer_id": 59662, "author": "Nick Stinemates", "author_id": 4960, "author_profile": "https://Stackoverflow.com/users/4960", "pm_score": 2, "selected": false, "text": "<p>Are you talking about doing this?</p>\n\n<pre><code>&gt;&gt;&gt; a = [ ['a', 'b'], ['c', 'd'] ]\n&gt;&gt;&gt; a[1]...
2008/09/12
[ "https://Stackoverflow.com/questions/59651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I have a web page that I have hooked up to a [stored procedure](http://en.wikipedia.org/wiki/Stored_procedure). In this SQL data source, I have a parameter that I'm passing back to the stored procedure of type int. [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) seems to want to default to *int32*, but the number won't get higher than 6. Is it ok to override the ASP.NET default and put in 16 or will there be a conflict somewhere down the road? specification: the database field has a length of 4 and precision of 10, if that makes a difference in the answer.
Would something like this work? ``` from random import randint mcworks = [] for n in xrange(NUM_ITERATIONS): mctest = [randint(0, 100) for i in xrange(5)] if sum(mctest[:3])/3 == mcavg[2]: mcworks.append(mctest) # mcavg is real data ``` In the end, you are left with a list of valid `mctest` lists. What I changed: * Used a [list comprehension](https://web.archive.org/web/20080928230016/http://docs.python.org:80/tut/node7.html#SECTION007140000000000000000) to build the data instead of a for loop * Used `random.randint` to get random integers * Used [slices](http://docs.python.org/tut/node5.html) and `sum` to calculate the average of the first three items * (To answer your actual question :-) ) Put the results in a list `mcworks`, instead of creating a new variable for every iteration
59,653
<p>Is there a way to get at the ItemContaner of a selected item in a listbox? In Silverlight 2.0 Beta 1 I could, but the container is hidden in Beta 2 of Silverlight 2.0. </p> <p>I'm trying to resize the listbox item when it is unselected to a specific size and when selected to a variable size. I also want to get the relative position of the selected item for animations. Growing to a variable size and getting the relative pasition is why i need to get to the listbox item.</p> <p>I should clarify i'm not adding items to the listbox explicitly. I am using data binding in xaml and DataTemplates. What I have trouble accessing is the ItemContainer of the selected item's DataTemplate.</p>
[ { "answer_id": 86980, "author": "dcstraw", "author_id": 10391, "author_profile": "https://Stackoverflow.com/users/10391", "pm_score": 0, "selected": false, "text": "<p>If you are adding non-UI elements to the listbox (such as strings or non-UI data objects), then this is probably pretty ...
2008/09/12
[ "https://Stackoverflow.com/questions/59653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580/" ]
Is there a way to get at the ItemContaner of a selected item in a listbox? In Silverlight 2.0 Beta 1 I could, but the container is hidden in Beta 2 of Silverlight 2.0. I'm trying to resize the listbox item when it is unselected to a specific size and when selected to a variable size. I also want to get the relative position of the selected item for animations. Growing to a variable size and getting the relative pasition is why i need to get to the listbox item. I should clarify i'm not adding items to the listbox explicitly. I am using data binding in xaml and DataTemplates. What I have trouble accessing is the ItemContainer of the selected item's DataTemplate.
There is a way to obtain the Panel containing the item's UIElement and the mapping of items to UIElements. You have to inherit from ListBox (this actually works for any ItemsControl) and override PrepareContainerForItemOverride: ``` protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { base.PrepareContainerForItemOverride(element, item); var el = element as FrameworkElement; if (el != null) { // here is the elements's panel: _itemsHost = el.Parent as Panel; // item is original item inserted in Items or ItemsSource // we can save the mapping between items and FrameworElements: _elementMapping[item] = el; } } ``` This is kind of hackish, but it works just fine.
59,655
<p>Given a controller method like: </p> <pre><code>def show @model = Model.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml =&gt; model } end end </code></pre> <p>What's the best way to write an integration test that asserts that the return has the expected XML?</p>
[ { "answer_id": 59714, "author": "Michael Sepcot", "author_id": 6033, "author_profile": "https://Stackoverflow.com/users/6033", "pm_score": 0, "selected": false, "text": "<p>Set the request objects accept header:</p>\n\n<pre><code>@request.accept = 'text/xml' # or 'application/xml' I forg...
2008/09/12
[ "https://Stackoverflow.com/questions/59655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4748/" ]
Given a controller method like: ``` def show @model = Model.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => model } end end ``` What's the best way to write an integration test that asserts that the return has the expected XML?
A combination of using the format and assert\_select in an integration test works great: ``` class ProductsTest < ActionController::IntegrationTest def test_contents_of_xml get '/index/1.xml' assert_select 'product name', /widget/ end end ``` For more details check out [assert\_select](http://apidock.com/rails/ActionController/Assertions/SelectorAssertions/assert_select) in the Rails docs.
59,670
<p>I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:</p> <blockquote> <p>warning: deprecated conversion from string constant to ‘char*’</p> </blockquote> <p>Obviously, the correct way to fix this is to find every declaration like</p> <pre><code>char *s = &quot;constant string&quot;; </code></pre> <p>or function call like:</p> <pre><code>void foo(char *s); foo(&quot;constant string&quot;); </code></pre> <p>and make them <code>const char</code> pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror" rel="nofollow noreferrer">-Werror</a>, so I need some way to stifle these warnings. How can I do that?</p>
[ { "answer_id": 59687, "author": "DGentry", "author_id": 4761, "author_profile": "https://Stackoverflow.com/users/4761", "pm_score": 9, "selected": true, "text": "<p>I believe passing <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings\" rel=\"nofollo...
2008/09/12
[ "https://Stackoverflow.com/questions/59670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3830/" ]
I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning: > > warning: deprecated conversion from string constant to ‘char\*’ > > > Obviously, the correct way to fix this is to find every declaration like ``` char *s = "constant string"; ``` or function call like: ``` void foo(char *s); foo("constant string"); ``` and make them `const char` pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with [-Werror](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror), so I need some way to stifle these warnings. How can I do that?
I believe passing [-Wno-write-strings](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings) to GCC will suppress this warning.
59,680
<p>In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server?</p>
[ { "answer_id": 59683, "author": "Derek", "author_id": 5440, "author_profile": "https://Stackoverflow.com/users/5440", "pm_score": 3, "selected": false, "text": "<pre><code>Set s = New NotesSession\nSet db = s.CurrentDatabase\n\nIf db.Server &lt;&gt; \"\" Then\n Set sName = New NotesName...
2008/09/12
[ "https://Stackoverflow.com/questions/59680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5440/" ]
In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server?
``` Set s = New NotesSession Set db = s.CurrentDatabase If db.Server <> "" Then Set sName = New NotesName(db.Server) Else Set sName = New NotesName(s.Username) End If ```
59,711
<p>Is there an equivalent operator to Haskell's list difference operator <code>\\</code> in F#?</p>
[ { "answer_id": 59814, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 3, "selected": false, "text": "<p>Nope... Just write it and make it an infix operator --using the set of special characters. Backslash (<code>\\</code>) is ...
2008/09/12
[ "https://Stackoverflow.com/questions/59711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4592/" ]
Is there an equivalent operator to Haskell's list difference operator `\\` in F#?
Was bounced, yet I believe it is worth to write here the implementation of `( /-/ )` (the F# version of Haskell's `\\`): ``` let flip f x y = f y x let rec delete x = function | [] -> [] | h :: t when x = h -> t | h :: t -> h :: delete x t let inline ( /-/ ) xs ys = List.fold (flip delete) xs ys ``` This will operate as Haskell's `\\`, so that `(xs @ ys) /-/ xs = ys`. For example: `(7 :: [1 .. 5] @ [5 .. 11]) /-/ [4 .. 7]` evaluates into `[1; 2; 3; 5; 7; 8; 9; 10; 11]`.
59,719
<p>I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).</p> <p>Basically, I need to check for IsPostBack in JavaScript.</p> <p>Thank you.</p>
[ { "answer_id": 59724, "author": "NerdFury", "author_id": 6146, "author_profile": "https://Stackoverflow.com/users/6146", "pm_score": 2, "selected": false, "text": "<p>You could put a hidden input on the page, and after the page loads, give it a value. Then you can check that field, if i...
2008/09/12
[ "https://Stackoverflow.com/questions/59719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3661/" ]
I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback). Basically, I need to check for IsPostBack in JavaScript. Thank you.
Server-side, write: ``` if(IsPostBack) { // NOTE: the following uses an overload of RegisterClientScriptBlock() // that will surround our string with the needed script tags ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true); } ``` Then, in your script which runs for the onLoad, check for the existence of that variable: ``` if(isPostBack) { // do your thing } ``` --- You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.
59,726
<p>Is there a way in .net 2.0 to discover the network alias for the machine that my code is running on? Specifically, if my workgroup sees my machine as //jekkedev01, how do I retrieve that name programmatically?</p>
[ { "answer_id": 59738, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 0, "selected": false, "text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.aspx\" rel=\"nofollow noreferrer\">System....
2008/09/12
[ "https://Stackoverflow.com/questions/59726", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5287/" ]
Is there a way in .net 2.0 to discover the network alias for the machine that my code is running on? Specifically, if my workgroup sees my machine as //jekkedev01, how do I retrieve that name programmatically?
Since you can have multiple network interfaces, each of which can have multiple IPs, and any single IP can have multiple names that can resolve to it, there may be more than one. If you want to know all the names by which your DNS server knows your machine, you can loop through them all like this: ``` public ArrayList GetAllDnsNames() { ArrayList names = new ArrayList(); IPHostEntry host; //check each Network Interface foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { //check each IP address claimed by this Network Interface foreach (UnicastIPAddressInformation i in nic.GetIPProperties().UnicastAddresses) { //get the DNS host entry for this IP address host = System.Net.Dns.GetHostEntry(i.Address.ToString()); if (!names.Contains(host.HostName)) { names.Add(host.HostName); } //check each alias, adding each to the list foreach (string s in host.Aliases) { if (!names.Contains(s)) { names.Add(s); } } } } //add "simple" host name - above loop returns fully qualified domain names (FQDNs) //but this method returns just the machine name without domain information names.Add(System.Net.Dns.GetHostName()); return names; } ```
59,734
<p>My application is using <strong>Dojo 1.1.1</strong> on an <em>SSL-only</em> website. It is currently taking advantage of <code>dijit.ProgressBar</code> and a <code>dijit.form.DateTextBox</code>.</p> <p>Everything works fabulous in <em>Firefox 2 &amp; 3</em>, but as soon as I try the same scripts in <em>IE7</em> the results are an annoying Security Information dialog:</p> <blockquote> <p>This page contains both secure and non-secure items. Do you want to display the non-secure items?</p> </blockquote> <p>I have scrutinized the page for any <em>non-HTTPS</em> reference to no avail. It appears to be something specific to <code>dojo.js</code>. There use to be an <code>iframe</code> glitch where the <code>src</code> was set to nothing, but this appears to be fixed now (on review of the source).</p> <p>Anyone else having this problem? What are the best-practices for getting <em>Dojo</em> to play well with <em>IE</em> on an <em>SSL-only</em> web server?</p>
[ { "answer_id": 60433, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 1, "selected": false, "text": "<p>If your page is loading files from a non-https URL Firefox should tell you the same thing. Instead of an error the lock symbo...
2008/09/12
[ "https://Stackoverflow.com/questions/59734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/644/" ]
My application is using **Dojo 1.1.1** on an *SSL-only* website. It is currently taking advantage of `dijit.ProgressBar` and a `dijit.form.DateTextBox`. Everything works fabulous in *Firefox 2 & 3*, but as soon as I try the same scripts in *IE7* the results are an annoying Security Information dialog: > > This page contains both secure and non-secure items. Do you want to display the non-secure items? > > > I have scrutinized the page for any *non-HTTPS* reference to no avail. It appears to be something specific to `dojo.js`. There use to be an `iframe` glitch where the `src` was set to nothing, but this appears to be fixed now (on review of the source). Anyone else having this problem? What are the best-practices for getting *Dojo* to play well with *IE* on an *SSL-only* web server?
After reviewing the JavaScript sourcecode for Dijit, I thought it was likely the error results from an "insecure" refrence to a dynamically generated IFRAME. Note there are two versions of the script file, the uncompressed represents the original source (dijit.js.uncompressed.js) and the standard (dijit.js) has been compressed for optimal transfer time. Since the uncompressed version is the most readable, I will describe my solution based on that. At line #1023, an IFRAME is rendered in JavaScript: ``` if(dojo.isIE){ var html="<iframe src='javascript:\"\"'" + " style='position: absolute; left: 0px; top: 0px;" + "z-index: -1; filter:Alpha(Opacity=\"0\");'>"; iframe = dojo.doc.createElement(html); }else{... ``` What's the problem? IE doesn't know if the src for the IFRAME is "secure" - so I replaced it with the following: ``` if(dojo.isIE){ var html="<iframe src='javascript:void(0);'" + " style='position: absolute; left: 0px; top: 0px;" + "z-index: -1; filter:Alpha(Opacity=\"0\");'>"; iframe = dojo.doc.createElement(html); }else{... ``` This is the most common problem with JavaScript toolkits and SSL in IE. Since IFRAME's are used as shims due to poor overlay support for DIV's, this problem is extremely prevalent. My first 5-10 page reloads are fine, but then the security error starts popping up again. How is this possible? The same page is "secure" for 5 reloads and then it is selected by IE as "insecure" when loaded the 6th time. As it turns out, there is also a background image being set in the onload event for dijit.wai (line #1325). This reads something like this; ``` div.style.cssText = 'border: 1px solid;' + 'border-color:red green;' + 'position: absolute;' + 'height: 5px;' + 'top: -999px;' + 'background-image: url("' + dojo.moduleUrl("dojo", "resources/blank.gif") + '");'; ``` This won't work because the background-image tag doesn't include HTTPs. Despite the fact that the location is relative, IE7 doesn't know if it's secure so the warning is posed. In this particular instance, this CSS is used to test for Accessibility (A11y) in Dojo. Since this is not something my application will support and since there are other general buggy issues with this method, I opted to remove everything in the onload() for dijit.wai. All is good! No sporadic security problems with the page loads.
59,743
<p>How many possible combinations of the variables a,b,c,d,e are possible if I know that:</p> <pre><code>a+b+c+d+e = 500 </code></pre> <p>and that they are all integers and >= 0, so I know they are finite.</p>
[ { "answer_id": 59748, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>If they are a real numbers then infinite ... otherwise it is a bit trickier.</p>\n\n<p>(OK, for any computer representa...
2008/09/12
[ "https://Stackoverflow.com/questions/59743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1815/" ]
How many possible combinations of the variables a,b,c,d,e are possible if I know that: ``` a+b+c+d+e = 500 ``` and that they are all integers and >= 0, so I know they are finite.
@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose `a` as `1` and `b` as `2`, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing `a` as `2` and `b` as `1`. (The number of such coincidences explodes as the numbers grow.) The traditional way to attack such a problem is [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming): build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of *n* variables add up to *k*?" is the sum of the solutions to "how many combinations of *n-1* variables add up to *j*?" with 0 <= *j* <= *k*). ``` public static long getCombos( int n, int sum ) { // tab[i][j] is how many combinations of (i+1) vars add up to j long[][] tab = new long[n][sum+1]; // # of combos of 1 var for any sum is 1 for( int j=0; j < tab[0].length; ++j ) { tab[0][j] = 1; } for( int i=1; i < tab.length; ++i ) { for( int j=0; j < tab[i].length; ++j ) { // # combos of (i+1) vars adding up to j is the sum of the # // of combos of i vars adding up to k, for all 0 <= k <= j // (choosing i vars forces the choice of the (i+1)st). tab[i][j] = 0; for( int k=0; k <= j; ++k ) { tab[i][j] += tab[i-1][k]; } } } return tab[n-1][sum]; } ``` ``` $ time java Combos 2656615626 real 0m0.151s user 0m0.120s sys 0m0.012s ```
59,761
<p>I need to disable specific keys (Ctrl and Backspace) in Internet Explorer 6. Is there a registry hack to do this. It has to be IE6. Thanks.</p> <p>Long Edit: </p> <p>@apandit: Whoops. I need to more specific about the backspace thing. When I say disable backspace, I mean disable the ability for Backspace to mimic the Back browser button. In IE, pressing Backspace when the focus is not in a text entry field is equivalent to pressing Back (browsing to the previous page).</p> <p>As for the Ctrl key. There are some pages which have links which create new IE windows. I have the popup blocker turned on, which block this. But, Ctrl clicking result in the new window being launched.</p> <p>This is for a kiosk application, which is currently a web based application. Clients do not have the funds at this time to make their site kiosk friendly. Things like URL filtering and disabling the URL entry field is already done.</p> <p>Thanks.</p>
[ { "answer_id": 59748, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "<p>If they are a real numbers then infinite ... otherwise it is a bit trickier.</p>\n\n<p>(OK, for any computer representa...
2008/09/12
[ "https://Stackoverflow.com/questions/59761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/78/" ]
I need to disable specific keys (Ctrl and Backspace) in Internet Explorer 6. Is there a registry hack to do this. It has to be IE6. Thanks. Long Edit: @apandit: Whoops. I need to more specific about the backspace thing. When I say disable backspace, I mean disable the ability for Backspace to mimic the Back browser button. In IE, pressing Backspace when the focus is not in a text entry field is equivalent to pressing Back (browsing to the previous page). As for the Ctrl key. There are some pages which have links which create new IE windows. I have the popup blocker turned on, which block this. But, Ctrl clicking result in the new window being launched. This is for a kiosk application, which is currently a web based application. Clients do not have the funds at this time to make their site kiosk friendly. Things like URL filtering and disabling the URL entry field is already done. Thanks.
@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose `a` as `1` and `b` as `2`, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing `a` as `2` and `b` as `1`. (The number of such coincidences explodes as the numbers grow.) The traditional way to attack such a problem is [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming): build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of *n* variables add up to *k*?" is the sum of the solutions to "how many combinations of *n-1* variables add up to *j*?" with 0 <= *j* <= *k*). ``` public static long getCombos( int n, int sum ) { // tab[i][j] is how many combinations of (i+1) vars add up to j long[][] tab = new long[n][sum+1]; // # of combos of 1 var for any sum is 1 for( int j=0; j < tab[0].length; ++j ) { tab[0][j] = 1; } for( int i=1; i < tab.length; ++i ) { for( int j=0; j < tab[i].length; ++j ) { // # combos of (i+1) vars adding up to j is the sum of the # // of combos of i vars adding up to k, for all 0 <= k <= j // (choosing i vars forces the choice of the (i+1)st). tab[i][j] = 0; for( int k=0; k <= j; ++k ) { tab[i][j] += tab[i-1][k]; } } } return tab[n-1][sum]; } ``` ``` $ time java Combos 2656615626 real 0m0.151s user 0m0.120s sys 0m0.012s ```
59,766
<p>I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the &lt;head> tag. Am I doing anything wrong?</p>
[ { "answer_id": 59770, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 7, "selected": true, "text": "<p>At the top of your external JavaScript file, add the following:</p>\n\n<pre><code>/// &lt;reference path=\"jQuery.js\...
2008/09/12
[ "https://Stackoverflow.com/questions/59766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?
At the top of your external JavaScript file, add the following: ``` /// <reference path="jQuery.js"/> ``` Make sure the path is correct, relative to the file's position in the folder structure, etc. Also, any references need to be at the top of the file, before *any* other text, including comments - literally, the very first thing in the file. Hopefully future version of Visual Studio will work regardless of where it is in the file, or maybe they will do something altogether different... Once you have done that and *saved the file*, hit `Ctrl` + `Shift` + `J` to force Visual Studio to update Intellisense.
59,790
<p>I have been hearing the podcast blog for a while, I hope I dont break this. The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code. </p> <p>I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes. </p>
[ { "answer_id": 59882, "author": "HigherAbstraction", "author_id": 5945, "author_profile": "https://Stackoverflow.com/users/5945", "pm_score": 0, "selected": false, "text": "<p>If your XML conforms to a particular XSD schema, you can look into using the \"xsd.exe\" command line tool to ge...
2008/09/12
[ "https://Stackoverflow.com/questions/59790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have been hearing the podcast blog for a while, I hope I dont break this. The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp\_xml\_preparedocument that is used to get transfer XMLs to an object and throught code. I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes.
In an attempt to try and help, we may need some clarification. Maybe by restating the problem you can let us know if this is what you're asking: **How can one import existing xml into a SQL 2005 database, without relying on the built-in xml type?** A fairly straight forward solution that you already mentioned is the *sp\_xml\_preparedocument*, combined with *openxml*. Hopefully the following example illustrates the correct usage. For a more complete example checkout the MSDN docs on [Using OPENXML](http://msdn.microsoft.com/en-us/library/ms187897(SQL.90).aspx). ``` declare @XmlDocumentHandle int declare @XmlDocument nvarchar(1000) set @XmlDocument = N'<ROOT> <Customer> <FirstName>Will</FirstName> <LastName>Smith</LastName> </Customer> </ROOT>' -- Create temp table to insert data into create table #Customer ( FirstName varchar(20), LastName varchar(20) ) -- Create an internal representation of the XML document. exec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument -- Insert using openxml allows us to read the structure insert into #Customer select FirstName = XmlFirstName, LastName = XmlLastName from openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 ) with ( XmlFirstName varchar(20) 'FirstName', XmlLastName varchar(20) 'LastName' ) where ( XmlFirstName = 'Will' and XmlLastName = 'Smith' ) -- Cleanup xml document exec sp_xml_removedocument @XmlDocumentHandle -- Show the data select * from #Customer -- Drop tmp table drop table #Customer ``` If you have an xml file and are using C#, then defining a stored procedure that does something like the above and then passing the entire xml file contents to the stored procedure as a *string* should give you a fairly straight forward way of importing xml into your existing table(s).
59,816
<p>I'm having some problems integrating MS MapPoint 2009 into my WinForms .Net 2.0 application in C#. I've added the ActiveX MapPoint control onto a form and have no problems getting it to display a maps and locations; my concern is the time it takes to load a map once it is created. </p> <p>The tests on my development machine have shown the average load time to be between 3 and 5 seconds, during which the application is totally locked. While this isn't totally unacceptable, it's an awfully long time to lose control of the application. Also, because the GUI thread is locked, I cannot show a loading dialog or something to mask the load time. </p> <p>The line that hangs is this: (where axMappointControl1 is the MapPoint control)</p> <pre><code>axMappointControl1.NewMap(MapPoint.GeoMapRegion.geoMapNorthAmerica); </code></pre> <p>I've tried executing the NewMap method on another thread but the GUI thread still ends up being blocked.</p> <p>My questions are: </p> <ul> <li>What can I do to speed up MapPoint when it loads?</li> <li>Is there any way to load MapPoint so that it won't block the GUI thread?</li> </ul> <p>Any help is greatly appreciated.</p>
[ { "answer_id": 96314, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 3, "selected": true, "text": "<p>According to <a href=\"http://www.mapforums.com/load-new-map-separate-thread-keep-ui-responsive-4605.html\" rel=\"nofollow n...
2008/09/12
[ "https://Stackoverflow.com/questions/59816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1314/" ]
I'm having some problems integrating MS MapPoint 2009 into my WinForms .Net 2.0 application in C#. I've added the ActiveX MapPoint control onto a form and have no problems getting it to display a maps and locations; my concern is the time it takes to load a map once it is created. The tests on my development machine have shown the average load time to be between 3 and 5 seconds, during which the application is totally locked. While this isn't totally unacceptable, it's an awfully long time to lose control of the application. Also, because the GUI thread is locked, I cannot show a loading dialog or something to mask the load time. The line that hangs is this: (where axMappointControl1 is the MapPoint control) ``` axMappointControl1.NewMap(MapPoint.GeoMapRegion.geoMapNorthAmerica); ``` I've tried executing the NewMap method on another thread but the GUI thread still ends up being blocked. My questions are: * What can I do to speed up MapPoint when it loads? * Is there any way to load MapPoint so that it won't block the GUI thread? Any help is greatly appreciated.
According to [these](http://www.mapforums.com/load-new-map-separate-thread-keep-ui-responsive-4605.html) [threads](http://www.mapforums.com/activex-performance-net-3415.html) at mapforums.com the slowness of ActiveX startup is well known and unavoidable (though the question of threading to help with GUI responsiveness is still open. One thing suggested was to abandon the ActiveX version in favor of the MapPoint.Application object instead. Hope that helps.