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
104,952
<p>I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests:</p> <ol> <li>See how much of my referenced code under test is getting executed</li> <li>See how many methods of my code under test (if any) are not unit tested at all</li> </ol> <p>Setting up the VSTS code coverage tool (see the <a href="https://blogs.msdn.com/ms_joc/articles/406608.aspx" rel="nofollow noreferrer" title="MSDN Code Coverage Blog">link text</a>) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code. </p> <pre><code>class CodeCoverageTarget { public: std::string ThisMethodRuns() { return "Running"; } std::string ThisMethodDoesNotRun() { return "Not Running"; } }; #include &lt;iostream&gt; #include "CodeCoverageTarget.h" using namespace std; int main() { CodeCoverageTarget cct; cout&lt;&lt;cct.ThisMethodRuns()&lt;&lt;endl; } </code></pre> <p>When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool? </p> <p>Thanks in advance, KGB</p>
[ { "answer_id": 104974, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>Turn off inlining of functions. The easiest way to do this is to just compile in Debug mode.</p>\n\n<p><strong>Edit:...
2008/09/19
[ "https://Stackoverflow.com/questions/104952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests: 1. See how much of my referenced code under test is getting executed 2. See how many methods of my code under test (if any) are not unit tested at all Setting up the VSTS code coverage tool (see the [link text](https://blogs.msdn.com/ms_joc/articles/406608.aspx "MSDN Code Coverage Blog")) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code. ``` class CodeCoverageTarget { public: std::string ThisMethodRuns() { return "Running"; } std::string ThisMethodDoesNotRun() { return "Not Running"; } }; #include <iostream> #include "CodeCoverageTarget.h" using namespace std; int main() { CodeCoverageTarget cct; cout<<cct.ThisMethodRuns()<<endl; } ``` When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool? Thanks in advance, KGB
You could try adding a line of code to call the function only if some condition is true, and guarantee that that condition will never be true. Just make sure the compiler can't figure that out. For example, ``` int main(int argc, char **argv) { if(argv == NULL) // C runtime says this won't happen someMethodWhichIsntReallyEverCalled(); } ```
104,953
<p>I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using <code>DIVs</code> with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph.</p> <p>In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property <code>float: left</code>. However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated.</p> <p>I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's:</p> <ol> <li>Cross-browser (ideally without too many browser hacks)</li> <li>Runs in Quirks mode</li> <li>As clear/clean as possible, to facilitate customizations</li> <li>Done without JavaScript if possible.</li> </ol>
[ { "answer_id": 104965, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 4, "selected": false, "text": "<p>You have to explicitly set the position of the parent container along with the position of the child container. Th...
2008/09/19
[ "https://Stackoverflow.com/questions/104953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using `DIVs` with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph. In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property `float: left`. However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated. I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's: 1. Cross-browser (ideally without too many browser hacks) 2. Runs in Quirks mode 3. As clear/clean as possible, to facilitate customizations 4. Done without JavaScript if possible.
You are right that CSS positioning is the way to go. Here's a quick run down: `position: relative` will layout an element relative to *itself.* In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour). However, you're most likely interested in `position: absolute` which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has `position: relative` or `position: absolute` set on it, then it will act as the parent for positioning coordinates for its children. To demonstrate: ```css #container { position: relative; border: 1px solid red; height: 100px; } #box { position: absolute; top: 50px; left: 20px; } ``` ```html <div id="container"> <div id="box">absolute</div> </div> ``` In that example, the top left corner of `#box` would be 100px down and 50px left of the top left corner of `#container`. If `#container` did not have `position: relative` set, the coordinates of `#box` would be relative to the top left corner of the browser view port.
104,967
<p>As a pet-project, I'd like to attempt to implement a basic language of my own design that can be used as a web-scripting language. It's trivial to run a C++ program as an Apache CGI, so the real work lies in how to parse an input file containing non-code (HTML/CSS markup) and server-side code.</p> <p>In my undergrad compiler course, we used <a href="http://www.gnu.org/software/flex/" rel="nofollow noreferrer">Flex</a> and <a href="http://www.gnu.org/software/bison/" rel="nofollow noreferrer">Bison</a> to generate a scanner and a parser for a simple language. We were given a copy of the grammar and wrote a parser that translated the simple language to a simple assembly for a virtual machine. The flex scanner tokenizes the input, and passes the tokens to the Bison parser.</p> <p>The difference between that and what I'd like to do is that like PHP, this language could have plain HTML markup and the scripting language interspersed like the following:</p> <pre><code>&lt;p&gt;Hello, &lt;? echo "World ?&gt; &lt;/p&gt; </code></pre> <p>Am I incorrect in assuming that it would be efficient to parse the input file as follows:</p> <ol> <li>Scan input until a script start tag is found (' <li>Second scanner tokenizes the server-side script section of the input file (from the open tag: '') and passes the token to the parser, which has no need to know about the markup in the file.</li> <li>Control is returned to the first scanner that continues this general pattern.</li> </ol> <p>Basically, the first scanner only differentiates between Markup (which is returned directly to the browser unmodified) and code, which is passed to the second scanner, which in turn tokenizes the code and passes the tokens to the parser. </p> <p>If this is <em>not</em> a solid design pattern, how do languages such as PHP handle scanning input and parsing code efficiently?</p>
[ { "answer_id": 105082, "author": "Kris Erickson", "author_id": 3798, "author_profile": "https://Stackoverflow.com/users/3798", "pm_score": 2, "selected": false, "text": "<p>PHP doesn't differentiate between the scanning and the Markup. It simply outputs to buffer when in Markup mode, an...
2008/09/19
[ "https://Stackoverflow.com/questions/104967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8636/" ]
As a pet-project, I'd like to attempt to implement a basic language of my own design that can be used as a web-scripting language. It's trivial to run a C++ program as an Apache CGI, so the real work lies in how to parse an input file containing non-code (HTML/CSS markup) and server-side code. In my undergrad compiler course, we used [Flex](http://www.gnu.org/software/flex/) and [Bison](http://www.gnu.org/software/bison/) to generate a scanner and a parser for a simple language. We were given a copy of the grammar and wrote a parser that translated the simple language to a simple assembly for a virtual machine. The flex scanner tokenizes the input, and passes the tokens to the Bison parser. The difference between that and what I'd like to do is that like PHP, this language could have plain HTML markup and the scripting language interspersed like the following: ``` <p>Hello, <? echo "World ?> </p> ``` Am I incorrect in assuming that it would be efficient to parse the input file as follows: 1. Scan input until a script start tag is found (' - Second scanner tokenizes the server-side script section of the input file (from the open tag: '') and passes the token to the parser, which has no need to know about the markup in the file. - Control is returned to the first scanner that continues this general pattern. Basically, the first scanner only differentiates between Markup (which is returned directly to the browser unmodified) and code, which is passed to the second scanner, which in turn tokenizes the code and passes the tokens to the parser. If this is *not* a solid design pattern, how do languages such as PHP handle scanning input and parsing code efficiently?
You want to look at start conditions. For example: ``` "<?" { BEGIN (PHP); } <PHP>[a-zA-Z]* { return PHP_TOKEN; } <PHP>">?" { BEGIN (0); } [a-zA-Z]* { return HTML_TOKEN; } ``` You start off in state 0, use the BEGIN macro to change states. To match a RE only while in a particular state, prefix the RE with the state name surrounded by angle-brackets. In the example above, "PHP" is state. "PHP\_TOKEN" and "HTML\_TOKEN" are \_%token\_s defined by your yacc file.
104,971
<p>I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear &lt; k number of times?</p>
[ { "answer_id": 104984, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT * FROM [MyTable] WHERE [Date] IN\n(\n SELECT [Date] \n FROM [MyTable] \n GROUP By [Date] \n...
2008/09/19
[ "https://Stackoverflow.com/questions/104971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?
``` select dates from table t group by dates having count(dates) < k ; ``` Hopefully, it works for ORACLE. HTH
105,014
<p>A while ago I came across some code that marked a member variable of a class with the <code>mutable</code> keyword. As far as I can see it simply allows you to modify a variable in a <code>const</code> method:</p> <pre><code>class Foo { private: mutable bool done_; public: void doSomething() const { ...; done_ = true; } }; </code></pre> <p>Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a <code>boost::mutex</code> as mutable allowing <code>const</code> functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.</p>
[ { "answer_id": 105038, "author": "Frank Szczerba", "author_id": 8964, "author_profile": "https://Stackoverflow.com/users/8964", "pm_score": 6, "selected": false, "text": "<p>Your use with boost::mutex is exactly what this keyword is intended for. Another use is for internal result cachin...
2008/09/19
[ "https://Stackoverflow.com/questions/105014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
A while ago I came across some code that marked a member variable of a class with the `mutable` keyword. As far as I can see it simply allows you to modify a variable in a `const` method: ``` class Foo { private: mutable bool done_; public: void doSomething() const { ...; done_ = true; } }; ``` Is this the only use of this keyword or is there more to it than meets the eye? I have since used this technique in a class, marking a `boost::mutex` as mutable allowing `const` functions to lock it for thread-safety reasons, but, to be honest, it feels like a bit of a hack.
It allows the differentiation of bitwise const and logical const. Logical const is when an object doesn't change in a way that is visible through the public interface, like your locking example. Another example would be a class that computes a value the first time it is requested, and caches the result. Since c++11 `mutable` can be used on a lambda to denote that things captured by value are modifiable (they aren't by default): ``` int x = 0; auto f1 = [=]() mutable {x = 42;}; // OK auto f2 = [=]() {x = 42;}; // Error: a by-value capture cannot be modified in a non-mutable lambda ```
105,031
<p>Using C#, I want to get the total amount of RAM that my computer has. With the PerformanceCounter I can get the amount of Available ram, by setting:</p> <pre><code>counter.CategoryName = "Memory"; counter.Countername = "Available MBytes"; </code></pre> <p>But I can't seem to find a way to get the total amount of memory. How would I go about doing this?</p> <p><strong>Update:</strong></p> <p>MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.</p>
[ { "answer_id": 105053, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 0, "selected": false, "text": "<p>.NET has a memory amount limit that it can access.\nIn Windows XP 2GB was the &quot;hard ceiling&quot;.\nFor inst...
2008/09/19
[ "https://Stackoverflow.com/questions/105031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13713/" ]
Using C#, I want to get the total amount of RAM that my computer has. With the PerformanceCounter I can get the amount of Available ram, by setting: ``` counter.CategoryName = "Memory"; counter.Countername = "Available MBytes"; ``` But I can't seem to find a way to get the total amount of memory. How would I go about doing this? **Update:** MagicKat: I saw that when I was searching, but it doesn't work - "Are you missing an assembly or reference?". I've looked to add that to the References, but I don't see it there.
The Windows API function [`GlobalMemoryStatusEx`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-globalmemorystatusex) can be called with p/invoke: ``` [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] private class MEMORYSTATUSEX { public uint dwLength; public uint dwMemoryLoad; public ulong ullTotalPhys; public ulong ullAvailPhys; public ulong ullTotalPageFile; public ulong ullAvailPageFile; public ulong ullTotalVirtual; public ulong ullAvailVirtual; public ulong ullAvailExtendedVirtual; public MEMORYSTATUSEX() { this.dwLength = (uint)Marshal.SizeOf(typeof(NativeMethods.MEMORYSTATUSEX)); } } [return: MarshalAs(UnmanagedType.Bool)] [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern bool GlobalMemoryStatusEx([In, Out] MEMORYSTATUSEX lpBuffer); ``` Then use like: ``` ulong installedMemory; MEMORYSTATUSEX memStatus = new MEMORYSTATUSEX(); if( GlobalMemoryStatusEx( memStatus)) { installedMemory = memStatus.ullTotalPhys; } ``` Or you can use WMI (managed but slower) to query `TotalPhysicalMemory` in the `Win32_ComputerSystem` class.
105,095
<p>If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?</p> <p>If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?</p> <p>sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines. </p> <p>same thing would apply to any other language implementation that has a GIL.</p>
[ { "answer_id": 105127, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 1, "selected": false, "text": "<p>You still need to use locks (your code could be interrupted at any time to execute another thread and this can cause dat...
2008/09/19
[ "https://Stackoverflow.com/questions/105095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16148/" ]
If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all? If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect? sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines. same thing would apply to any other language implementation that has a GIL.
You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code. For example: ``` #!/usr/bin/env python import threading shared_balance = 0 class Deposit(threading.Thread): def run(self): for _ in xrange(1000000): global shared_balance balance = shared_balance balance += 100 shared_balance = balance class Withdraw(threading.Thread): def run(self): for _ in xrange(1000000): global shared_balance balance = shared_balance balance -= 100 shared_balance = balance threads = [Deposit(), Withdraw()] for thread in threads: thread.start() for thread in threads: thread.join() print shared_balance ``` Here, your code can be interrupted between reading the shared state (`balance = shared_balance`) and writing the changed result back (`shared_balance = balance`), causing a lost update. The result is a random value for the shared state. To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have [some way to detect when the shared state had changed since it was read](http://en.wikipedia.org/wiki/Software_transactional_memory).
105,125
<p>Our project uses Cruise Control to both build and hot deploy a web application to a remote server (via FTP) running Tomcat in the form of a .war file. Unfortunately, "hot" deploys don't appear to work properly, causing us to reboot Tomcat in response to each deployment. We would really like to do this auto-magically, much like the build itself. Is there an easy way to do this?</p> <p>Side note: both machines are running Windows (XP or server, I think).</p> <p>Side note 2: Performance doesn't really matter. This is an integration box.</p>
[ { "answer_id": 105289, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 1, "selected": false, "text": "<p>if you have regularly scheduled builds you could easily put something in the cron like this</p>\n\n<pre><code>crontab ...
2008/09/19
[ "https://Stackoverflow.com/questions/105125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7357/" ]
Our project uses Cruise Control to both build and hot deploy a web application to a remote server (via FTP) running Tomcat in the form of a .war file. Unfortunately, "hot" deploys don't appear to work properly, causing us to reboot Tomcat in response to each deployment. We would really like to do this auto-magically, much like the build itself. Is there an easy way to do this? Side note: both machines are running Windows (XP or server, I think). Side note 2: Performance doesn't really matter. This is an integration box.
if you have regularly scheduled builds you could easily put something in the cron like this ``` crontab -e ``` then stop tomcat at say 1:30 am ``` 30 1 * * * ./path_to_tamcat/bin/catalina.sh stop ``` then start it up again 2 mins later ``` 32 1 * * * ./path_to_tamcat/bin/catalina.sh start ``` granted this isn't the best for irregular deployment, but you could easily have regular deployment with scheduled restart.
105,198
<p>I'm still a little unclear and when to wrap a <em>lock</em> around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge:</p> <pre><code>class Foo { private static readonly string bar = "O_o"; private bool TrySomething() { string bar; lock(Foo.objectToLockOn) { bar = Foo.bar; } // Do something with bar } } </code></pre> <p>That just doesn't make sense to me--why would there by concurrency issues with READING a register?</p> <p>Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL...</p> <pre><code>class Foo { private static string joke = "yo momma"; private string GetJoke() { lock(Foo.objectToLockOn) { return Foo.joke; } } } </code></pre> <p>vs.</p> <pre><code>class Foo { private static string joke = "yo momma"; private string GetJoke() { string joke; lock(Foo.objectToLockOn) { joke = Foo.joke; } return joke; } } </code></pre>
[ { "answer_id": 105218, "author": "easeout", "author_id": 10906, "author_profile": "https://Stackoverflow.com/users/10906", "pm_score": 1, "selected": false, "text": "<p>If you're just writing a value to a pointer, you don't need to lock, since that action is atomic. Generally, you shoul...
2008/09/19
[ "https://Stackoverflow.com/questions/105198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
I'm still a little unclear and when to wrap a *lock* around some code. My general rule-of-thumb is to wrap an operation in a lock when it reads or writes to a static variable. But when a static variable is ONLY read (e.g. it's a readonly that is set during type initialization), accessing it doesn't need to be wrapped in a lock statement, right? I recently saw some code that looked like the following example, and it made me think there may be some gaps in my multithreading knowledge: ``` class Foo { private static readonly string bar = "O_o"; private bool TrySomething() { string bar; lock(Foo.objectToLockOn) { bar = Foo.bar; } // Do something with bar } } ``` That just doesn't make sense to me--why would there by concurrency issues with READING a register? Also, this example brings up another question. Is one of these better than the other? (E.g. example two holds the lock for less time?) I suppose I could disassemble the MSIL... ``` class Foo { private static string joke = "yo momma"; private string GetJoke() { lock(Foo.objectToLockOn) { return Foo.joke; } } } ``` vs. ``` class Foo { private static string joke = "yo momma"; private string GetJoke() { string joke; lock(Foo.objectToLockOn) { joke = Foo.joke; } return joke; } } ```
Since none of the code you've written modifies the static field after initialization, there is no need for any locking. Just replacing the string with a new value won't need synchronization either, unless the new value depends on the results of a read of the old value. Static fields aren't the only things that need synchronization, any shared reference which could be modified is vulnerable to synchronization issues. ```csharp class Foo { private int count = 0; public void TrySomething() { count++; } } ``` You might suppose that two threads executing the TrySomething method would be fine. But its not. 1. Thread A reads the value of count (0) into a register so it can be incremented. 2. Context switch! The thread scheduler decides thread A has had enough execution time. Next in line is Thread B. 3. Thread B reads the value of count (0) into a register. 4. Thread B increments the register. 5. Thread B saves the result (1) to count. 6. Context switch back to A. 7. Thread A reloads the register with the value of count (0) saved on its stack. 8. Thread A increments the register. 9. Thread A saves the result (1) to count. So, even though we called count++ twice, the value of count has just gone from 0 to 1. Lets make the code thread-safe: ```csharp class Foo { private int count = 0; private readonly object sync = new object(); public void TrySomething() { lock(sync) count++; } } ``` Now when Thread A gets interrupted Thread B cannot mess with count because it will hit the lock statement and then block until Thread A has released sync. By the way, there is an alternative way to make incrementing Int32s and Int64s thread-safe: ```csharp class Foo { private int count = 0; public void TrySomething() { System.Threading.Interlocked.Increment(ref count); } } ``` Regarding the second part of your question, I think I would just go with whichever is easier to read, any performance difference there will be negligible. Early optimisation is the root of all evil, etc. [Why threading is hard](https://learn.microsoft.com/en-us/archive/blogs/jmstall/why-threading-is-hard)
105,212
<p>Suppose I have a directory <code>/dir</code> inside which there are 3 symlinks to other directories <code>/dir/dir11</code>, <code>/dir/dir12</code>, and <code>/dir/dir13</code>. I want to list all the files in <code>dir</code> including the ones in <code>dir11</code>, <code>dir12</code> and <code>dir13</code>.</p> <p>To be more generic, I want to list all files including the ones in the directories which are symlinks. <code>find .</code>, <code>ls -R</code>, etc stop at the symlink without navigating into them to list further.</p>
[ { "answer_id": 105249, "author": "Michael Ridley", "author_id": 4838, "author_profile": "https://Stackoverflow.com/users/4838", "pm_score": 9, "selected": true, "text": "<p>The <code>-L</code> option to <code>ls</code> will accomplish what you want. It dereferences symbolic links.</p>\n\...
2008/09/19
[ "https://Stackoverflow.com/questions/105212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18072/" ]
Suppose I have a directory `/dir` inside which there are 3 symlinks to other directories `/dir/dir11`, `/dir/dir12`, and `/dir/dir13`. I want to list all the files in `dir` including the ones in `dir11`, `dir12` and `dir13`. To be more generic, I want to list all files including the ones in the directories which are symlinks. `find .`, `ls -R`, etc stop at the symlink without navigating into them to list further.
The `-L` option to `ls` will accomplish what you want. It dereferences symbolic links. So your command would be: ``` ls -LR ``` You can also accomplish this with ``` find -follow ``` The `-follow` option directs find to follow symbolic links to directories. On Mac OS X use ``` find -L ``` as `-follow` has been deprecated.
105,252
<p>How do I convert between big-endian and little-endian values in C++?</p> <p>For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here.</p> <hr /> <p>Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.</p>
[ { "answer_id": 105297, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 3, "selected": false, "text": "<p>If you're doing this to transfer data between different platforms look at the ntoh and hton functions.</p>\n" }, { "...
2008/09/19
[ "https://Stackoverflow.com/questions/105252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19129/" ]
How do I convert between big-endian and little-endian values in C++? For clarity, I have to translate binary data (double-precision floating point values and 32-bit and 64-bit integers) from one CPU architecture to another. This doesn't involve networking, so ntoh() and similar functions won't work here. --- Note: The answer I accepted applies directly to compilers I'm targeting (which is why I chose it). However, there are other very good, more portable answers here.
If you're using **Visual C++** do the following: You include intrin.h and call the following functions: For 16 bit numbers: ``` unsigned short _byteswap_ushort(unsigned short value); ``` For 32 bit numbers: ``` unsigned long _byteswap_ulong(unsigned long value); ``` For 64 bit numbers: ``` unsigned __int64 _byteswap_uint64(unsigned __int64 value); ``` 8 bit numbers (chars) don't need to be converted. Also these are only defined for unsigned values they work for signed integers as well. For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa. Other compilers have similar intrinsics as well. In **GCC** for example you can directly call [some builtins as documented here](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html): ``` uint32_t __builtin_bswap32 (uint32_t x) uint64_t __builtin_bswap64 (uint64_t x) ``` (no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well. 16 bit swap it's just a bit-rotate. Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..
105,264
<p>I'm new to the WCSF and can't seem to find anything related to "building a custom template" for creating the views/presenters/code-behinds/etc with your own flavor ...</p> <p>Can anyone point me in the right direction?</p>
[ { "answer_id": 105297, "author": "Andrew", "author_id": 826, "author_profile": "https://Stackoverflow.com/users/826", "pm_score": 3, "selected": false, "text": "<p>If you're doing this to transfer data between different platforms look at the ntoh and hton functions.</p>\n" }, { "...
2008/09/19
[ "https://Stackoverflow.com/questions/105264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ]
I'm new to the WCSF and can't seem to find anything related to "building a custom template" for creating the views/presenters/code-behinds/etc with your own flavor ... Can anyone point me in the right direction?
If you're using **Visual C++** do the following: You include intrin.h and call the following functions: For 16 bit numbers: ``` unsigned short _byteswap_ushort(unsigned short value); ``` For 32 bit numbers: ``` unsigned long _byteswap_ulong(unsigned long value); ``` For 64 bit numbers: ``` unsigned __int64 _byteswap_uint64(unsigned __int64 value); ``` 8 bit numbers (chars) don't need to be converted. Also these are only defined for unsigned values they work for signed integers as well. For floats and doubles it's more difficult as with plain integers as these may or not may be in the host machines byte-order. You can get little-endian floats on big-endian machines and vice versa. Other compilers have similar intrinsics as well. In **GCC** for example you can directly call [some builtins as documented here](https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html): ``` uint32_t __builtin_bswap32 (uint32_t x) uint64_t __builtin_bswap64 (uint64_t x) ``` (no need to include something). Afaik bits.h declares the same function in a non gcc-centric way as well. 16 bit swap it's just a bit-rotate. Calling the intrinsics instead of rolling your own gives you the best performance and code density btw..
105,308
<p>I want to take the url: <a href="http://www.mydomain.com/signup-12345" rel="nofollow noreferrer">http://www.mydomain.com/signup-12345</a></p> <p>And actually give them: <a href="http://www.mydomain.com/signup/?aff=12345" rel="nofollow noreferrer">http://www.mydomain.com/signup/?aff=12345</a></p> <p>I have NO history with mod_rewrite, HELP!</p>
[ { "answer_id": 105336, "author": "CodeRot", "author_id": 14134, "author_profile": "https://Stackoverflow.com/users/14134", "pm_score": 3, "selected": false, "text": "<p>Try this : </p>\n\n<p>RewriteRule ^/signup-(\\d+)/$ /signup/?aff=$1 [I]</p>\n" }, { "answer_id": 111010, "a...
2008/09/19
[ "https://Stackoverflow.com/questions/105308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13704/" ]
I want to take the url: <http://www.mydomain.com/signup-12345> And actually give them: <http://www.mydomain.com/signup/?aff=12345> I have NO history with mod\_rewrite, HELP!
Something that I found relatively hard to find out was how to do the reverse of what you are doing, whereby you need to find out the value of part of the query string. So for example: If you wanted to rewrite the Url: <http://www.example.com/signup->**old**-script.**asp**?**aff**=12345 to: <http://www.example.com/signup->**new**-script.**php**?**affID**=12345 you could use: ``` RewriteCond %{query_string}& ^aff=((.+&)|&)$ RewriteRule ^/signup-old-script.asp$ /signup-new-script.php?affID=%2 [L,R] ``` Notice the **%** sign in the rewrite rule instead of the **$** sign. I had to do this so I could support old flash maps in a new site that had links to ".cfm" files with an ID in the query string.
105,349
<p>I am using bash in os X Terminal app, and my custom $PS1 breaks when I scroll through my history.</p> <pre><code>PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\n\[${red}\$${NC}\]" </code></pre> <p>also tried PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\r\n[${red}\$${NC}]" </p> <p>The problem seems to be in the newline. I have used this bash prompt on Slackware no prob.</p>
[ { "answer_id": 105363, "author": "apandit", "author_id": 6128, "author_profile": "https://Stackoverflow.com/users/6128", "pm_score": 0, "selected": false, "text": "<p>If the problem seems to be with the newline, try putting \\r\\n instead of just \\n and see if it makes a difference.</p>...
2008/09/19
[ "https://Stackoverflow.com/questions/105349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
I am using bash in os X Terminal app, and my custom $PS1 breaks when I scroll through my history. ``` PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\n\[${red}\$${NC}\]" ``` also tried PS1="${BLUE}\u${CYAN}@${RED}\h${BLUE}\w\r\n[${red}\$${NC}]" The problem seems to be in the newline. I have used this bash prompt on Slackware no prob.
You need the [ and ] arond every escape sequence; do $BLUE and the like include these? If not, they need to be bracketed with these calls.
105,372
<p>How can you enumerate an <code>enum</code> in C#?</p> <p>E.g. the following code does not compile:</p> <pre class="lang-cs prettyprint-override"><code>public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } </code></pre> <p>And it gives the following compile-time error:</p> <blockquote> <p>'Suit' is a 'type' but is used like a 'variable'</p> </blockquote> <p>It fails on the <code>Suit</code> keyword, the second one.</p>
[ { "answer_id": 105401, "author": "Tom Carr", "author_id": 14954, "author_profile": "https://Stackoverflow.com/users/14954", "pm_score": 6, "selected": false, "text": "<p>I think you can use</p>\n\n<pre><code>Enum.GetNames(Suit)\n</code></pre>\n" }, { "answer_id": 105402, "aut...
2008/09/19
[ "https://Stackoverflow.com/questions/105372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
How can you enumerate an `enum` in C#? E.g. the following code does not compile: ```cs public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } ``` And it gives the following compile-time error: > > 'Suit' is a 'type' but is used like a 'variable' > > > It fails on the `Suit` keyword, the second one.
``` foreach (Suit suit in (Suit[]) Enum.GetValues(typeof(Suit))) { } ``` **Note**: The cast to `(Suit[])` is not strictly necessary, [but it does make the code 0.5 ns faster](https://gist.github.com/bartoszkp/9e059c3edccc07a5e588#gistcomment-2625454).
105,477
<p>I think I've got it down to the most basic case:</p> <pre><code>int main(int argc, char ** argv) { int * arr; foo(arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1; } void foo(int * arr) { arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69; } </code></pre> <p>The output is this:</p> <pre class="lang-none prettyprint-override"><code>&gt; ./a.out car[3]=-1869558540 a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer being freed *** set a breakpoint in malloc_error_break to debug &gt; </code></pre> <p>If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.</p>
[ { "answer_id": 105507, "author": "terminus", "author_id": 9232, "author_profile": "https://Stackoverflow.com/users/9232", "pm_score": 3, "selected": false, "text": "<p>You've allocated arr in foo, but that pointers value is stored in the call stack. If you want to do this, do it like thi...
2008/09/19
[ "https://Stackoverflow.com/questions/105477", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I think I've got it down to the most basic case: ``` int main(int argc, char ** argv) { int * arr; foo(arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1; } void foo(int * arr) { arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69; } ``` The output is this: ```none > ./a.out car[3]=-1869558540 a.out(4100) malloc: *** error for object 0x8fe01037: Non-aligned pointer being freed *** set a breakpoint in malloc_error_break to debug > ``` If anyone can shed light on where my understanding is failing, it'd be greatly appreciated.
You pass the pointer by value, not by reference, so whatever you do with arr inside foo will not make a difference outside the foo-function. As m\_pGladiator wrote one way is to declare a reference to pointer like this (only possible in C++ btw. C does not know about references): ``` int main(int argc, char ** argv) { int * arr; foo(arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1; } void foo(int * &arr ) { arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69; } ``` Another (better imho) way is to not pass the pointer as an argument but to return a pointer: ``` int main(int argc, char ** argv) { int * arr; arr = foo(); printf("car[3]=%d\n",arr[3]); free (arr); return 1; } int * foo(void ) { int * arr; arr = (int*) malloc( sizeof(int)*25 ); arr[3] = 69; return arr; } ``` And you can pass a pointer to a pointer. That's the C way to pass by reference. Complicates the syntax a bit but well - that's how C is... ``` int main(int argc, char ** argv) { int * arr; foo(&arr); printf("car[3]=%d\n",arr[3]); free (arr); return 1; } void foo(int ** arr ) { (*arr) = (int*) malloc( sizeof(int)*25 ); (*arr)[3] = 69; } ```
105,499
<p>I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy. </p> <p>If I use the web service, then it is possible to set proxy. </p>
[ { "answer_id": 108530, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 1, "selected": false, "text": "<p>Not sure if this is what you are looking for but the below is a working code sample to authenticate using the clien...
2008/09/19
[ "https://Stackoverflow.com/questions/105499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19146/" ]
I have a problem to connect to my WCF service if customer is using proxy with credentials. I'm unable to find the way to set credential to generated client proxy. If I use the web service, then it is possible to set proxy.
I'm not entirely sure if this is what you are looking for but here you go. ``` MyClient client = new MyClient(); client.ClientCredentials.UserName.UserName = "u"; client.ClientCredentials.UserName.Password = "p"; ```
105,504
<p>When retrieving a lookup code value from a table, some folks do this...</p> <pre><code>Dim dtLookupCode As New LookupCodeDataTable() Dim taLookupCode AS New LookupCodeTableAdapter() Dim strDescription As String dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL") strDescription = dtLookupCode.Item(0).Meaning </code></pre> <p>...however, I've also seen things done "chained" like this...</p> <pre><code>strDescription = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL").Item(0).Meaning </code></pre> <p>...which bypasses having a lookup code data table in the first place since the table adapter knows what the structure of its result set looks like.</p> <p>Does using the "chained" method save the overhead of creating the data table object, or does it effectively get created anyway in order to properly handle the .Item(0).Meaning statement?</p>
[ { "answer_id": 105520, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 2, "selected": false, "text": "<p>Yeah, don't say \"inline\" because that means something specific in other languages. Most likely the performance differenc...
2008/09/19
[ "https://Stackoverflow.com/questions/105504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
When retrieving a lookup code value from a table, some folks do this... ``` Dim dtLookupCode As New LookupCodeDataTable() Dim taLookupCode AS New LookupCodeTableAdapter() Dim strDescription As String dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL") strDescription = dtLookupCode.Item(0).Meaning ``` ...however, I've also seen things done "chained" like this... ``` strDescription = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL").Item(0).Meaning ``` ...which bypasses having a lookup code data table in the first place since the table adapter knows what the structure of its result set looks like. Does using the "chained" method save the overhead of creating the data table object, or does it effectively get created anyway in order to properly handle the .Item(0).Meaning statement?
Straying from the "inline" part of this, actually, the two sets of code won't compile out to the same thing. The issue comes in with: ``` Dim dtLookupCode As New LookupCodeDataTable() Dim taLookupCode AS New LookupCodeTableAdapter() ``` In VB, this will create new objects with the appropriately-named references. Followed by: ``` dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL") ``` We immediately replace the original `dtLookupCode` reference with a new object, which creates garbage to be collected (an unreachable object in RAM). In the exact, original scenario, therefore, what's referred to as the "inline" technique is, *technically*, more performant. (However, you're unlikely to physically see that difference in this small an example.) The place where the code would essentially be the same is if the original sample read as follows: ``` Dim taLookupCode AS New LookupCodeTableAdapter Dim dtLookupCode As LookupCodeDataTable Dim strDescription As String dtLookupCode = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL") strDescription = dtLookupCode.Item(0).Meaning ``` In this world, we only have the existing references, and are not creating junk objects. I reordered the statements slightly for readability, but the gist is the same. Also, you could easily single-line-initialize the references with something like this, and have the same basic idea: ``` Dim taLookupCode AS New LookupCodeTableAdapter Dim dtLookupCode As LookupCodeDataTable = taLookupCode.GetDataByCodeAndValue("EmpStatus", "FULL") Dim strDescription As String = dtLookupCode.Item(0).Meaning ```
105,522
<p>OK, so things have progressed significantly with my DSL since I asked <a href="https://stackoverflow.com/questions/82776/how-do-i-reference-a-diagram-in-a-dsl-t4-template">this question</a> a few days ago.</p> <p>As soon as I've refactored my code, I'll post my own answer to that one, but for now, I'm having another problem.</p> <p>I'm dynamically generating sub-diagrams from a DSL-created model, saving those diagrams as images and then generating a Word document with those images embedded. So far, so good.</p> <p> But where my shapes have compartments (for examples, Operations on a Service Contract - can you guess what it is, yet?), the compartment header is displayed but <b>none of the items</b>.</p> <p>If I examine my shape object, it has a single nested child - an ElementListCompartment which in turn, has a number of items that I'm expecting to be displayed. The ElementListCompartment.IsExpanded property is set to true (and the compartment header has a little 'collapse' icon on it) but where, oh where, are my items?</p> <p>The shape was added to the diagram using</p> <pre><code>parentShape.FixupChildShapes(modelElement); </code></pre> <p>So, can anyone guide me on my merry way?</p>
[ { "answer_id": 149768, "author": "Luis Filipe", "author_id": 20335, "author_profile": "https://Stackoverflow.com/users/20335", "pm_score": 1, "selected": false, "text": "<p>Maybe my answer is a little bit too late, but did you confirm using DSL Explorer that your compartments have items?...
2008/09/19
[ "https://Stackoverflow.com/questions/105522", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5806/" ]
OK, so things have progressed significantly with my DSL since I asked [this question](https://stackoverflow.com/questions/82776/how-do-i-reference-a-diagram-in-a-dsl-t4-template) a few days ago. As soon as I've refactored my code, I'll post my own answer to that one, but for now, I'm having another problem. I'm dynamically generating sub-diagrams from a DSL-created model, saving those diagrams as images and then generating a Word document with those images embedded. So far, so good. But where my shapes have compartments (for examples, Operations on a Service Contract - can you guess what it is, yet?), the compartment header is displayed but **none of the items**. If I examine my shape object, it has a single nested child - an ElementListCompartment which in turn, has a number of items that I'm expecting to be displayed. The ElementListCompartment.IsExpanded property is set to true (and the compartment header has a little 'collapse' icon on it) but where, oh where, are my items? The shape was added to the diagram using ``` parentShape.FixupChildShapes(modelElement); ``` So, can anyone guide me on my merry way?
I've recently faced a related problem, and managed to make it work, so here's the story. The task I was implementing was to load and display a domain model and an associated diagram generated by ActiveWriter's DSL package. Here's how I've implemented the required functionality (all the methods below belong to the Form1 class I've created to play around): ``` private Store LoadStore() { var store = new Store(); store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel)); return store; } private void LoadDiagram(Store store) { using (var tx = store.TransactionManager.BeginTransaction("tx", true)) { var validator = new ValidationController(); var deserializer = ActiveWriterSerializationHelper.Instance; deserializer.LoadModelAndDiagram(store, @"..\..\ActiveWriter1.actiw", @"..\..\ActiveWriter1.actiw.diagram", null, validator); tx.Commit(); } } private DiagramView CreateDiagramView() { var store = LoadStore(); LoadDiagram(store); using (var tx = store.TransactionManager.BeginTransaction("tx2", true)) { var dir = store.DefaultPartition.ElementDirectory; var diag = dir.FindElements<ActiveRecordMapping>().SingleOrDefault(); var view = new DiagramView(){Diagram = diag}; diag.Associate(view); tx.Commit(); view.Dock = DockStyle.Fill; return view; } } protected override void OnLoad(EventArgs e) { var view = CreateDiagramView(); this.Controls.Add(view); } ``` This stuff worked mostly finely: it correctly loaded the diagram from files created with Visual Studio, drew the diagram within my custom windows form, supported scrolling the canvas and even allowed me to drag shapes here. However, one thing was bugging me - the compartments were empty and had default name, i.e. "Compartment". Google didn't help at all, so I had to dig in by myself. It wasn't very easy but with the help of Reflector and after spending a couple of hours I've managed to make this scenario work as expected! The problem was as follows. To my surprise DSL libraries do not correctly draw certain diagram elements immediately after they are added to the diagram. Sometimes, only stubs of certain shapes are drawn (as it's displayed in the first picture). Thus, sometimes we need to manually ask the library to redraw diagram shapes. This functionality can be implemented with so called "rules" that in fact are event handlers that get triggered by certain diagram events. Basically what we have to do is attach certain handler to an element-added event of the diagram and ensure shape initialization. Luckily we don't even have to write any code since DSL designer autogenerates both fixup rules and an utility method that attaches those rules to the diagram (see the EnableDiagramRules below). All we have to do is to call this method right after the store has been created (prior to loading model and diagram). ``` private Store LoadStore() { var store = new Store(); store.LoadDomainModels(typeof(CoreDesignSurfaceDomainModel), typeof(ActiveWriterDomainModel)); ActiveWriterDomainModel.EnableDiagramRules(store); return store; } /// <summary> /// Enables rules in this domain model related to diagram fixup for the given store. /// If diagram data will be loaded into the store, this method should be called first to ensure /// that the diagram behaves properly. /// </summary> public static void EnableDiagramRules(DslModeling::Store store) { if(store == null) throw new global::System.ArgumentNullException("store"); DslModeling::RuleManager ruleManager = store.RuleManager; ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.FixUpDiagram)); ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.ConnectorRolePlayerChanged)); ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemAddRule)); ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemDeleteRule)); ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerChangeRule)); ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemRolePlayerPositionChangeRule)); ruleManager.EnableRule(typeof(global::Altinoren.ActiveWriter.CompartmentItemChangeRule)); } ``` The code above works as follows: 1. Upon new element being added to the diagram (e.g. during deserialization of diagram) the rule "FixUpDiagram" gets triggered. 2. The rule then calls `Diagram.FixUpDiagram(parentElement, childElement)`, where `childElement` stands for an element being added and `parentElement` stands for its logical parent (determined using tricky conditional logic, so I didn't try to reproduce it by myself). 3. Down the stack trace FixUpDiagram method calls `EnsureCompartments` methods of all class shapes in the diagram. 4. The EnsureCompartments method redraws class' compartments turning the stub "[-] Compartment" graphic into full-blown "Properties" shape as displayed in the picture linked above. P.S. Steve, I've noticed that you did call the fixup but it still didn't work. Well, I'm not a pro in DSL SDK (just started using it a couple of days ago), so cannot explain why you might have troubles. Maybe, you've called the fixup with wrong arguments. Or maybe Diagram.FixupDiagram(parent, newChild) does something differently from what parent.FixupChildShapes(newChild) does. However here's my variant that just works. Hope this also helps.
105,535
<p>I have a VmWare virtual machine that is coming dangerously close to it's primarry HDD's limit and I need to extend it. How do I do this? I'm working with VmWare Workstation 6.0.5</p>
[ { "answer_id": 105547, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://www.seandeasy.com/expanding-a-drive-within-a-vmware-image/\" rel=\"nofollow noreferrer\">This link</a> g...
2008/09/19
[ "https://Stackoverflow.com/questions/105535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1980/" ]
I have a VmWare virtual machine that is coming dangerously close to it's primarry HDD's limit and I need to extend it. How do I do this? I'm working with VmWare Workstation 6.0.5
[This link](http://www.seandeasy.com/expanding-a-drive-within-a-vmware-image/) gives two approaches that should help. It looks like this is the most straightforward method: ``` vmware-vdiskmanager -x 12GB path\to\disk.vmdk ``` where 12GB is the desired size of the expanded volume.
105,551
<p>This exception peppers our production catalina logs on a simple 'getParameter()' call.</p> <pre> WARNING: Parameters: Character decoding failed. Parameter skipped. java.io.CharConversionException: EOF at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:82) at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48) at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509) at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266) at org.apache.catalina.connector.Request.parseParameters(Request.java:2361) at org.apache.catalina.connector.Request.getParameter(Request.java:1005) at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353) at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158) </pre> <p>Or Sometimes:</p> <pre> java.io.CharConversionException: isHexDigit at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:87) at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48) at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509) at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266) at org.apache.catalina.connector.Request.parseParameters(Request.java:2361) at org.apache.catalina.connector.Request.getParameter(Request.java:1005) at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353) at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158) </pre>
[ { "answer_id": 105968, "author": "Alexander", "author_id": 16724, "author_profile": "https://Stackoverflow.com/users/16724", "pm_score": 4, "selected": true, "text": "<p>Just hypothesizing here. Seems like the URL-decoding of parameters or their values fails (URL-encoding means encoding ...
2008/09/19
[ "https://Stackoverflow.com/questions/105551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17123/" ]
This exception peppers our production catalina logs on a simple 'getParameter()' call. ``` WARNING: Parameters: Character decoding failed. Parameter skipped. java.io.CharConversionException: EOF at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:82) at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48) at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509) at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266) at org.apache.catalina.connector.Request.parseParameters(Request.java:2361) at org.apache.catalina.connector.Request.getParameter(Request.java:1005) at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353) at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158) ``` Or Sometimes: ``` java.io.CharConversionException: isHexDigit at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:87) at org.apache.tomcat.util.buf.UDecoder.convert(UDecoder.java:48) at org.apache.tomcat.util.http.Parameters.urlDecode(Parameters.java:411) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:393) at org.apache.tomcat.util.http.Parameters.processParameters(Parameters.java:509) at org.apache.tomcat.util.http.Parameters.handleQueryParameters(Parameters.java:266) at org.apache.catalina.connector.Request.parseParameters(Request.java:2361) at org.apache.catalina.connector.Request.getParameter(Request.java:1005) at org.apache.catalina.connector.RequestFacade.getParameter(RequestFacade.java:353) at javax.servlet.ServletRequestWrapper.getParameter(ServletRequestWrapper.java:158) ```
Just hypothesizing here. Seems like the URL-decoding of parameters or their values fails (URL-encoding means encoding some characters using the %XX or %XXXX notation where XX or XXXX is the hexadecimal code of the character in ISO-8859-1 or Unicode). In the first case the error might be happening because there aren't enough hexadecimal characters after the % character. In the second case this might be happening because a character after the % character isn't hexadecimal.
105,556
<p>We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents?</p>
[ { "answer_id": 105591, "author": "Cyberherbalist", "author_id": 16964, "author_profile": "https://Stackoverflow.com/users/16964", "pm_score": 2, "selected": true, "text": "<p>You could use XSD. No, I'm serious. Go to a command prompt and type xsd and press Enter.</p>\n\n<p>Here's what ...
2008/09/19
[ "https://Stackoverflow.com/questions/105556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
We are attempting to use a SQL Server 2003 database for our test records and want a quick way to take NUnit and NAnt output and produce SQL schema and data. Is there a simple way to generate SQL Schema using the XSD file describing these XML documents?
You could use XSD. No, I'm serious. Go to a command prompt and type xsd and press Enter. Here's what you will see (truncated): ``` I:\>xsd Microsoft (R) Xml Schemas/DataTypes support utility [Microsoft (R) .NET Framework, Version 1.0.3705.0] Copyright (C) Microsoft Corporation 1998-2001. All rights reserved. xsd.exe - Utility to generate schema or class files from given source. xsd.exe <schema>.xsd /classes|dataset [/e:] [/l:] [/n:] [/o:] [/uri:] xsd.exe <assembly>.dll|.exe [/outputdir:] [/type: [...]] xsd.exe <instance>.xml [/outputdir:] xsd.exe <schema>.xdr [/outputdir:] ``` Just follow the instructions.
105,564
<p>The original query looks like this (MySQL):</p> <pre><code>SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date </code></pre> <p>Would it be possible to rewrite it (without unions or procedures), so that result will look like this:</p> <ul> <li>list of books where title matches query ordered by date, followed by:</li> <li>list of books where description matches query ordered by date</li> </ul> <p>So basically just give a higher priority to matching titles over descriptions.</p>
[ { "answer_id": 105580, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": -1, "selected": false, "text": "<p>The union command will help you. Something along these lines:</p>\n\n<pre><code>SELECT *, 1 as order from books...
2008/09/19
[ "https://Stackoverflow.com/questions/105564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
The original query looks like this (MySQL): ``` SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date ``` Would it be possible to rewrite it (without unions or procedures), so that result will look like this: * list of books where title matches query ordered by date, followed by: * list of books where description matches query ordered by date So basically just give a higher priority to matching titles over descriptions.
In sql server I would do the following: ``` select * from books where title like '%text%' or description like '%text%' order by case when title like '%text%' then 1 else 2 end, date ``` I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well.
105,602
<p>I have inherited a monster.</p> <p>It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.</p> <p>To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.</p> <p>This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.</p> <p>My question is, what methods would you suggest to refactor or restructure such a thing?</p> <p>I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.</p> <p>Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.</p> <p>Thanks for any and all ideas.</p>
[ { "answer_id": 105618, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 2, "selected": false, "text": "<p>A <a href=\"http://en.wikipedia.org/wiki/Finite_state_machine\" rel=\"nofollow noreferrer\">state machine</a> seem...
2008/09/19
[ "https://Stackoverflow.com/questions/105602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19304/" ]
I have inherited a monster. It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction. To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies. This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep. My question is, what methods would you suggest to refactor or restructure such a thing? I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go. Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1. Thanks for any and all ideas.
I just had some legacy code at work this week that was similar (although not as dire) as what you are describing. There is no one thing that will get you out of this. The [state machine](http://en.wikipedia.org/wiki/Finite_state_machine) might be the final form your code takes, but thats *not* going to help you get there, nor should you decide on such a solution before untangling the mess you already have. First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test. Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net. Now Refactor! A couple things I did that i found useful: **Invert `if` statements** A huge problem I had was just reading the code when I couldn't find the corresponding `else` statement, I noticed that a lot of the blocks looked like this ``` if (someCondition) { 100+ lines of code { ... } } else { simple statement here } ``` By inverting the `if` I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding. **Extract Method** I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication. Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood *procedural* code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work). Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions. [Refactoring to Patterns](https://rads.stackoverflow.com/amzn/click/com/0321213351) is a great book to assist in explainging patterns that are helpful in these situations. You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck.
105,604
<p>I've just installed MediaWiki on a web server. Obviously it needs lots of privileges during installation to set up its database correctly. Now that it's installed can I safely revoke some privileges (e.g. create table, drop table?) Or might it need to create more tables later (when they are first needed?) If not then I would prefer to grant it as few privileges as possible.</p>
[ { "answer_id": 105919, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 0, "selected": false, "text": "<p>Change the user that mediawiki connects as in LocalSettings.php and then using phpMyAdmin, you can edit the privileges of...
2008/09/19
[ "https://Stackoverflow.com/questions/105604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12048/" ]
I've just installed MediaWiki on a web server. Obviously it needs lots of privileges during installation to set up its database correctly. Now that it's installed can I safely revoke some privileges (e.g. create table, drop table?) Or might it need to create more tables later (when they are first needed?) If not then I would prefer to grant it as few privileges as possible.
After the installation, MediaWiki doesn't need to create any more tables. I'd suggest giving the user insert, select, and lock permission. ``` grant select,lock tables,insert on media_wiki_db.* to 'wiki'@'localhost' identified by 'password'; ```
105,609
<p>I have an enum that looks as follows:</p> <pre><code>public enum TransactionStatus { Open = 'O', Closed = 'C'}; </code></pre> <p>and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed.</p> <p>now because the data comes out of the database as an object I am having a heck of a time writing comparison code.</p> <p>The best I can do is to write:</p> <pre><code>protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) { return ((char)enum_status).ToString() == obj_status.ToString(); } </code></pre> <p>However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. <a href="http://blogs.msdn.com/abhinaba/archive/2006/01/14/enumerting-all-values-of-an-enum.aspx" rel="nofollow noreferrer">Supposedly all enums inherit from System.Enum</a> but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question.</p> <p>I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing?</p>
[ { "answer_id": 105638, "author": "Jake Pearson", "author_id": 632, "author_profile": "https://Stackoverflow.com/users/632", "pm_score": -1, "selected": false, "text": "<p>I would take a look at Enum.Parse. It will let you parse your char back into the proper enum. I believe it works al...
2008/09/19
[ "https://Stackoverflow.com/questions/105609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have an enum that looks as follows: ``` public enum TransactionStatus { Open = 'O', Closed = 'C'}; ``` and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed. now because the data comes out of the database as an object I am having a heck of a time writing comparison code. The best I can do is to write: ``` protected bool CharEnumEqualsCharObj(TransactionStatus enum_status, object obj_status) { return ((char)enum_status).ToString() == obj_status.ToString(); } ``` However, this is not the only character enum that I have to deal with, I have 5 or 6 and writting the same method for them is annoying to say the least. [Supposedly all enums inherit from System.Enum](http://blogs.msdn.com/abhinaba/archive/2006/01/14/enumerting-all-values-of-an-enum.aspx) but if I try to set that as the input type I get compilation errors. This is also in .NET 1.1 so generics are out of the question. I've been struggling with this for a while. Does anyone have a better way of writing this method? Also, can anyone clarify the whole enums inherit from System.Enum but are not polymorphic thing?
``` static void Main(string[] args) { object val = 'O'; Console.WriteLine(EnumEqual(TransactionStatus.Open, val)); val = 'R'; Console.WriteLine(EnumEqual(DirectionStatus.Left, val)); Console.ReadLine(); } public static bool EnumEqual(Enum e, object boxedValue) { return e.Equals(Enum.ToObject(e.GetType(), (char)boxedValue)); } public enum TransactionStatus { Open = 'O', Closed = 'C' }; public enum DirectionStatus { Left = 'L', Right = 'R' }; ```
105,613
<p>Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the <code>lizard</code> and <code>pig</code> elements from this example:</p> <pre><code>&lt;pets&gt; &lt;cat&gt; &lt;foo&gt;don't care about this&lt;/foo&gt; &lt;/cat&gt; &lt;dog&gt; &lt;foo&gt;not this one either&lt;/foo&gt; &lt;/dog&gt; &lt;lizard&gt; &lt;bar&gt;lizard should be returned, because it has a child of bar&lt;/bar&gt; &lt;/lizard&gt; &lt;pig&gt; &lt;bar&gt;return pig, too&lt;/bar&gt; &lt;/pig&gt; &lt;/pets&gt; </code></pre> <p>This Xpath gives me all pets: <code>"/pets/*"</code>, but I only want the pets that have a child node of name <code>'bar'</code>.</p>
[ { "answer_id": 105628, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 7, "selected": true, "text": "<p>Here it is, in all its glory</p>\n\n<pre><code>/pets/*[bar]\n</code></pre>\n\n<p>English: Give me all children of ...
2008/09/19
[ "https://Stackoverflow.com/questions/105613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10876/" ]
Is it possible to use XPath to select only the nodes that have a particular child elements? For example, from this XML I only want the elements in pets that have a child of 'bar'. So the resulting dataset would contain the `lizard` and `pig` elements from this example: ``` <pets> <cat> <foo>don't care about this</foo> </cat> <dog> <foo>not this one either</foo> </dog> <lizard> <bar>lizard should be returned, because it has a child of bar</bar> </lizard> <pig> <bar>return pig, too</bar> </pig> </pets> ``` This Xpath gives me all pets: `"/pets/*"`, but I only want the pets that have a child node of name `'bar'`.
Here it is, in all its glory ``` /pets/*[bar] ``` English: Give me all children of `pets` that have a child `bar`
105,642
<p><strong>Update</strong>: Looks like the query does not throw any timeout. The connection is timing out.</p> <p>This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception.</p> <p>I <strong>cannot</strong> use any of these techniques: 1) Increase timeout. 2) Run it asynchronously with a callback. This needs to run in a synchronous manner.</p> <p>please suggest any other techinques to keep the connection alive while executing a time consuming query?</p> <pre><code>private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); } } </code></pre>
[ { "answer_id": 105655, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 0, "selected": false, "text": "<pre><code>command.CommandTimeout *= 2;\n</code></pre>\n\n<p>That will double the default time-out, which is 30 seconds.</p>\...
2008/09/19
[ "https://Stackoverflow.com/questions/105642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306/" ]
**Update**: Looks like the query does not throw any timeout. The connection is timing out. This is a sample code for executing a query. Sometimes, while executing time consuming queries, it throws a timeout exception. I **cannot** use any of these techniques: 1) Increase timeout. 2) Run it asynchronously with a callback. This needs to run in a synchronous manner. please suggest any other techinques to keep the connection alive while executing a time consuming query? ``` private static void CreateCommand(string queryString, string connectionString) { using (SqlConnection connection = new SqlConnection( connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); command.Connection.Open(); command.ExecuteNonQuery(); } } ```
Since you are using ExecuteNonQuery which does not return any rows, you can try this polling based approach. It executes the query in an asyc manner (without callback) but the application will wait (inside a while loop) until the query is complete. From [MSDN](http://msdn.microsoft.com/en-us/library/ca56w9se(VS.80).aspx). This should solve the timeout problem. Please try it out. But, I agree with others that you should think more about optimizing the query to perform under 30 seconds. ``` IAsyncResult result = command.BeginExecuteNonQuery(); int count = 0; while (!result.IsCompleted) { Console.WriteLine("Waiting ({0})", count++); System.Threading.Thread.Sleep(1000); } Console.WriteLine("Command complete. Affected {0} rows.", command.EndExecuteNonQuery(result)); ```
105,645
<p>Tackling a strange scenario here. </p> <p>We use a proprietary workstation management application which uses mySQL to store its data. Within the application they provide number of reports, such as which user logged into which machine at what time, all the software products installed on the monitored machines, so on and so forth. We are looking to do a different set of reports, however, they do not support custom reports.</p> <p>Since their data is being stored in mySQL, I gather I can do the reporting manually. I don't have valid credentials to connect to the mySQL server though. <b>Is there anyway for me to create a user account in the mySQL server?</b> I do not want to reset the root password or anything account that might be in there, as it might break the application.</p> <hr> <p>I have full access to the Windows 2003 server. I can stop and restart services, including the mySQL server. To the actual mySQL server, I only have basic access through the GUI provided by the software. I can't connect to it directly through CLI or through another tool (due to the lack of credentials). </p> <hr> <p>I apologize if it came off as if I'm trying to get unauthorized access to the mySQL server. I have contacted the software company, and as of today it's been two weeks without a response from them. I need to get to the data. I have full access to the physical box, I have admin privileges on it.</p>
[ { "answer_id": 105657, "author": "Brent", "author_id": 10680, "author_profile": "https://Stackoverflow.com/users/10680", "pm_score": 0, "selected": false, "text": "<p>Do you have access to the MySQL server in question?</p>\n\n<p>As in, what access do you have beyond what a regular user w...
2008/09/19
[ "https://Stackoverflow.com/questions/105645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16522/" ]
Tackling a strange scenario here. We use a proprietary workstation management application which uses mySQL to store its data. Within the application they provide number of reports, such as which user logged into which machine at what time, all the software products installed on the monitored machines, so on and so forth. We are looking to do a different set of reports, however, they do not support custom reports. Since their data is being stored in mySQL, I gather I can do the reporting manually. I don't have valid credentials to connect to the mySQL server though. **Is there anyway for me to create a user account in the mySQL server?** I do not want to reset the root password or anything account that might be in there, as it might break the application. --- I have full access to the Windows 2003 server. I can stop and restart services, including the mySQL server. To the actual mySQL server, I only have basic access through the GUI provided by the software. I can't connect to it directly through CLI or through another tool (due to the lack of credentials). --- I apologize if it came off as if I'm trying to get unauthorized access to the mySQL server. I have contacted the software company, and as of today it's been two weeks without a response from them. I need to get to the data. I have full access to the physical box, I have admin privileges on it.
You'll want to use the MySQL password recovery process. Follow [these instructions](http://dev.mysql.com/doc/refman/5.0/en/resetting-permissions.html#resetting-permissions-windows), except replace the password reset query with a query to [add a new user](http://dev.mysql.com/doc/refman/5.0/en/adding-users.html). The new user query would be something like: ``` GRANT ALL ON *.* TO 'myuser'@'localhost' IDENTIFIED BY 'mypassword' WITH GRANT OPTION; ``` That will create a new user "myuser" with the password "mypassword", who may log in to MySQL through the local system's CLI. You can then use the MySQL Administrator GUI ([download here](http://dev.mysql.com/downloads/gui-tools/5.0.html)) and update user permissions so you can log in from other systems on the network. Or use the [`GRANT` statement](http://dev.mysql.com/doc/refman/5.0/en/grant.html) from the CLI, if that's more your style.
105,651
<p>How can I print wstring in gdb?</p>
[ { "answer_id": 105900, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 1, "selected": false, "text": "<p>Suppose you've got a <code>std::wstring str</code>. The following should work in gdb:</p>\n\n<pre><code>call printf(\"%...
2008/09/19
[ "https://Stackoverflow.com/questions/105651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18382/" ]
How can I print wstring in gdb?
`call printf %ls` only works sometimes, but to get it to work at all in gdb 6.3 you need the `void` cast and linefeed `\n` shown here: ``` call (void)printf("\"%ls\"\n",str.c_str()) ``` here is a more reliable command you can put in your .gdbinit that also shows non-ASCII code points: ``` define wc_print echo " set $c = (wchar_t*)$arg0 while ( *$c ) if ( *$c > 0x7f ) printf "[%x]", *$c else printf "%c", *$c end set $c++ end echo "\n end ``` just enter `wc` (short for `wc_print`) with either a `std::wstring` or `wchar_t*`. More detail at <http://www.firstobject.com/wchar_t-gdb.htm>
105,653
<p>I'm having some issues with producing an int matrix without creating memory leaks. I want to be able to make a given (global) matrix into any size dynamically via read_matrix(). But then i want to be able to free the memory later on. So in my main method the second printf should result in a bus error since it should not have any memory allocated to it. How would i go about creating this?</p> <pre><code>int** first_matrix; int** second_matrix; int** result_matrix; int** read_matrix(int size_x, int size_y) { int** matrix; matrix = calloc(size_x, sizeof(int*)); for(int i = 0;i&lt;size_x;i++) { matrix[i] = calloc(size_y, sizeof(int)); } for(int i = 0;i&lt;size_x;i++) { for(int j = 0;j&lt;size_y;j++) { matrix[i][j] = i*10+j; } } return matrix; } int main(int stackc, char** stack) { first_matrix = read_matrix(10,10); printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]); free(*first_matrix); free(first_matrix); printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]); } </code></pre>
[ { "answer_id": 105677, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>You need to free each row individually:</p>\n\n<pre><code>\nvoid free_matrix(int **matrix, int size_x)\n{\n fo...
2008/09/19
[ "https://Stackoverflow.com/questions/105653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9191/" ]
I'm having some issues with producing an int matrix without creating memory leaks. I want to be able to make a given (global) matrix into any size dynamically via read\_matrix(). But then i want to be able to free the memory later on. So in my main method the second printf should result in a bus error since it should not have any memory allocated to it. How would i go about creating this? ``` int** first_matrix; int** second_matrix; int** result_matrix; int** read_matrix(int size_x, int size_y) { int** matrix; matrix = calloc(size_x, sizeof(int*)); for(int i = 0;i<size_x;i++) { matrix[i] = calloc(size_y, sizeof(int)); } for(int i = 0;i<size_x;i++) { for(int j = 0;j<size_y;j++) { matrix[i][j] = i*10+j; } } return matrix; } int main(int stackc, char** stack) { first_matrix = read_matrix(10,10); printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]); free(*first_matrix); free(first_matrix); printf("9:3 %d - 4:6 %d \n", first_matrix[9][3], first_matrix[4][6]); } ```
Just because the memory has been free'd doesn't mean you can't access it! Of course, it's a **very bad** idea to access it after it's been free'd, but that's why it works in your example. Note that `free( *first_matrix )` only free's `first_matrix[0]`, not the other arrays. You probably want some kind of marker to signify the last array (unless you will always know when you free the outer array how many inner arrays you allocated). Something like: ``` int** read_matrix(int size_x, int size_y) { int** matrix; matrix = calloc(size_x, 1+sizeof(int*)); // alloc one extra ptr for(int i = 0;i<size_x;i++) { matrix[i] = calloc(size_y, sizeof(int)); } matrix[size_x] = NULL; // set the extra ptr to NULL for(int i = 0;i<size_x;i++) { for(int j = 0;j<size_y;j++) { matrix[i][j] = i*10+j; } } return matrix; } ``` Then when you're freeing them: ``` // keep looping until you find the NULL one for( int i=0; first_matrix[i] != NULL; i++ ) { free( first_matrix[i] ); } free( first_matrix ); ```
105,671
<p>Does any one have a preference on how to check if a value is <code>DBNull</code>? I've found these two statements give me the results I want, but just wondering if there's a preference?</p> <p><code>if (any is System.DBNull)</code></p> <p>same as:</p> <p><code>if (any == System.DBNull.Value)</code></p> <p>Thanks!</p>
[ { "answer_id": 105678, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 3, "selected": true, "text": "<pre><code>if (any == System.DBNull.Value) ...\n</code></pre>\n\n<p>I prefer that one, simply because I read that as compari...
2008/09/19
[ "https://Stackoverflow.com/questions/105671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19314/" ]
Does any one have a preference on how to check if a value is `DBNull`? I've found these two statements give me the results I want, but just wondering if there's a preference? `if (any is System.DBNull)` same as: `if (any == System.DBNull.Value)` Thanks!
``` if (any == System.DBNull.Value) ... ``` I prefer that one, simply because I read that as comparing values, not types.
105,676
<p>Greetings,</p> <p>I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. </p> <p>Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work.</p>
[ { "answer_id": 105693, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 1, "selected": false, "text": "<p>Ping everything in the rage, then you can get netbios info from the systems that respond to identify it's name.</p>\n" ...
2008/09/19
[ "https://Stackoverflow.com/questions/105676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5021/" ]
Greetings, I need a way (either via C# or in a .bat file) to get a list of all the computers on a given network. Normally, I use "net view", but this tends to work (from my understanding) only within your domain. I need the names (or at least the IP Addresses) of all computers available on my network. Being able to get all computers on a domain that isn't mine (in which case I'd use WORKGROUP, or whatever the default is) would also work.
[Nmap](http://nmap.org/) is good for this - use the -O option for OS fingerprinting and -oX "filename.xml" for [output](http://nmap.org/book/man-output.html) as xml that you can then parse from c#. A suitable commandline would be (where 192.168.0.0/24 is the subnet to scan): ``` nmap -O -oX "filename.xml" 192.168.0.0/24 ``` leave out the -O if you aren't interested in guessing the OS - if you just want a ping sweep use -sP, or read the docs for the myriad other options.
105,688
<p>I have an application with a REST style interface that takes XML documents via POST from clients. This application is written in Java and uses XML beans to process the posted message. </p> <p>The XML schema definition for a field in the message looks like this:</p> <pre><code>&lt;xs:element name="value" type="xs:string" nillable="true" /&gt; </code></pre> <p>How do I send a null value that meets this spec?</p> <p>I sent <code>&lt;value xsi:nil="true" /&gt;</code> but this caused the XML parser to barf.</p>
[ { "answer_id": 105713, "author": "aaronsw", "author_id": 4300, "author_profile": "https://Stackoverflow.com/users/4300", "pm_score": 4, "selected": false, "text": "<p>What about <code>&lt;value xsi:nil=\"true\"&gt;&lt;/value&gt;</code>? That's what's <a href=\"http://www.w3.org/TR/xmlsch...
2008/09/19
[ "https://Stackoverflow.com/questions/105688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7222/" ]
I have an application with a REST style interface that takes XML documents via POST from clients. This application is written in Java and uses XML beans to process the posted message. The XML schema definition for a field in the message looks like this: ``` <xs:element name="value" type="xs:string" nillable="true" /> ``` How do I send a null value that meets this spec? I sent `<value xsi:nil="true" />` but this caused the XML parser to barf.
That's the right way of sending a nil value (assuming that the default namespace and the `xsi` namespace are set to the correct values, namely `"http://www.w3.org/2001/XMLSchema-instance"` for `xsi`.) so it looks like you might have come up against a bug in the CML parser you're using. What's the error message? You might try using `xsi:nil="1"` or using separate open and close tags (`<value xsi:nil="true"></value>`) to try working around the bug.
105,702
<p>I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django.</p> <p>I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block.</p> <p>How should I do this? It's a fairly large project, so adding code to every view is far from ideal.</p> <hr> <p>That solution works well. The Middleware Class I ended up with this this:</p> <pre><code>from django.http import HttpResponseRedirect class BetaMiddleware(object): """ Require beta code session key in order to view any page. """ def process_request(self, request): if request.path != '/beta/' and not request.session.get('in_beta'): return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path)) </code></pre>
[ { "answer_id": 105756, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 0, "selected": false, "text": "<p>You should be able to add <code>@login_required</code> decorators across the board and be done with it. Unless you have...
2008/09/19
[ "https://Stackoverflow.com/questions/105702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6007/" ]
I'm about to put a beta version of the site I'm working on up on the web. It needs to have a beta code to restrict access. The site is written in django. I don't want to change the fundamental Auth system to accommodate a beta code, and I don't care particularly that the security of the beta code is iron-clad, just that it's a significant stumbling block. How should I do this? It's a fairly large project, so adding code to every view is far from ideal. --- That solution works well. The Middleware Class I ended up with this this: ``` from django.http import HttpResponseRedirect class BetaMiddleware(object): """ Require beta code session key in order to view any page. """ def process_request(self, request): if request.path != '/beta/' and not request.session.get('in_beta'): return HttpResponseRedirect('%s?next=%s' % ('/beta/', request.path)) ```
Start with [this Django snippet](http://www.djangosnippets.org/snippets/136/), but modify it to check `request.session['has_beta_access']`. If they don't have it, then have it return a redirect to a "enter beta code" page that, when posted to with the right code, sets that session variable to `True`. Making it a public beta then just consists of removing that middleware from your `MIDDLEWARE_CLASSES` setting.
105,724
<p>In this code I am debugging, I have this code snipit:</p> <pre><code>ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0'); </code></pre> <p>What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year.</p> <p>UPDATE: Thanks everyone. I don't do a lot of .NET development so setting up a quick test isn't as quick for me.</p>
[ { "answer_id": 105752, "author": "RKitson", "author_id": 16947, "author_profile": "https://Stackoverflow.com/users/16947", "pm_score": 0, "selected": false, "text": "<p>It looks like it's grabbing the substring from the 3rd character (if 0 based) to the end, then if the substring has a l...
2008/09/19
[ "https://Stackoverflow.com/questions/105724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2535/" ]
In this code I am debugging, I have this code snipit: ``` ddlExpYear.SelectedItem.Value.Substring(2).PadLeft(2, '0'); ``` What does this return? I really can't run this too much as it is part of a live credit card application. The DropDownList as you could imagine from the name contains the 4-digit year. UPDATE: Thanks everyone. I don't do a lot of .NET development so setting up a quick test isn't as quick for me.
It takes the last two digits of the year and pads the left side with zeroes to a maximum of 2 characters. Looks like a "just in case" for expiration years ending in 08, 07, etc., making sure that the leading zero is present.
105,725
<p>I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source. </p> <p>some solutions --</p> <p><a href="http://www.cprogramming.com/challenges/solutions/self_print.html" rel="noreferrer">http://www.cprogramming.com/challenges/solutions/self_print.html</a></p> <p><strong><a href="http://www.nyx.net/~gthompso/quine.htm" rel="noreferrer">Quine Page solution in many languages</a></strong></p> <p>There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...</p>
[ { "answer_id": 105745, "author": "Roland", "author_id": 15965, "author_profile": "https://Stackoverflow.com/users/15965", "pm_score": -1, "selected": false, "text": "<p>In ruby:</p>\n\n<p>puts File.read(_ _ FILE _ _)</p>\n" }, { "answer_id": 105755, "author": "aaronsw", "...
2008/09/19
[ "https://Stackoverflow.com/questions/105725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8786/" ]
I have seen a lot of C/C++ based solutions to this problem where we have to write a program that upon execution prints its own source. some solutions -- <http://www.cprogramming.com/challenges/solutions/self_print.html> **[Quine Page solution in many languages](http://www.nyx.net/~gthompso/quine.htm)** There are many more solutions on the net, each different from the other. I wonder how do we approach to such a problem, what goes inside the mind of the one who solves it. Lend me some insights into this problem... While solutions in interpreted languages like perl, php, ruby, etc might be easy... i would like to know how does one go about designing it in compiled languages...
Aside from cheating¹ there is no difference between compiled and interpreted languages. The generic approach to quines is quite easy. First, whatever the program looks like, at some point it has to print something: ``` print ... ``` However, what should it print? Itself. So it needs to print the "print" command: ``` print "print ..." ``` What should it print next? Well, in the mean time the program grew, so it needs to print the string starting with "print", too: ``` print "print \"print ...\"" ``` Now the program grew again, so there's again more to print: ``` print "print \"print \\\"...\\\"\"" ``` And so on. With every added code there's more code to print. This approach is getting nowhere, but it reveals an interesting pattern: The string "print \"" is repeated over and over again. It would be nice to put the repeating part into a variable: ``` a = "print \"" print a ``` However, the program just changed, so we need to adjust a: ``` a = "a = ...\nprint a" print a ``` When we now try to fill in the "...", we run into the same problems as before. Ultimately, we want to write something like this: ``` a = "a = " + (quoted contents of a) + "\nprint a" print a ``` But that is not possible, because even if we had such a function `quoted()` for quoting, there's still the problem that we define `a` in terms of itself: ``` a = "a = " + quoted(a) + "\nprint a" print a ``` So the only thing we can do is putting a place holder into `a`: ``` a = "a = @\nprint a" print a ``` And that's the whole trick! Anything else is now clear. Simply replace the place holder with the quoted contents of `a`: ``` a = "a = @\nprint a" print a.replace("@", quoted(a)) ``` Since we have changed the code, we need to adjust the string: ``` a = "a = @\nprint a.replace(\"@\", quoted(a))" print a.replace("@", quoted(a)) ``` And that's it! All quines in all languages work that way (except the cheating ones). Well, you should ensure that you replace only the first occurence of the place holder. And if you use a second place holder, you can avoid needing to quote the string. But those are minor issues and easy to solve. If fact, the realization of `quoted()` and `replace()` are the only details in which the various quines really differ. --- ¹ by making the program read its source file
105,731
<p>How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC?</p> <p>I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on.</p> <p>The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class.</p> <p>I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either. </p> <p>Does anyone have a sample of how to get this to work?</p>
[ { "answer_id": 106421, "author": "ctacke", "author_id": 13154, "author_profile": "https://Stackoverflow.com/users/13154", "pm_score": 3, "selected": true, "text": "<p>What's \"not working\" with the CCommandBar for you? You should be able to add a CCommandBar member to your dialog class...
2008/09/19
[ "https://Stackoverflow.com/questions/105731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3494/" ]
How do I use the softkeys with a CDialog based application in windows mobile 6 via MFC? I have a CDialog based Windows Mobile 6 (touchscreen) Professional app that I am workign on. The default behavior of a CDialog based app in WM6 Professional is to not use any softkeys by default... I want to map the softkeys to "Cancel" and "OK" functionality that sends IDOK and IDCANCEL to my Main Dialog class. I have been trying to work with CCommandBar with no luck, and SHCreateMenuBar was not working out for me either. Does anyone have a sample of how to get this to work?
What's "not working" with the CCommandBar for you? You should be able to add a CCommandBar member to your dialog class, then in teh DIalog's InitDialog you call Create and InsertMenuBar on the command bar - something like this: ``` m_cmdBar.Create(this); m_cmdBar.InsertMenuBar(IDR_MENU_RESRC_ID); ``` Your menu resource might look something like this: ``` IDR_MENU_RESRC_ID MENU DISCARDABLE BEGIN MENUITEM "OK", IDOK MENUITEM "Cancel", IDCANCEL END ```
105,754
<p>We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using <code>mod_proxy_jk</code> as the connector.</p> <p>Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant). Both Apache and Tomcat are running on separate machines and have copious amounts of ram (4gb each).</p> <p>Relevant server.xml portions:</p> <pre><code>&lt;Connector port="8009" address="${jboss.bind.address}" protocol="AJP/1.3" emptySessionPath="true" enableLookups="false" redirectPort="8443" maxThreads="320" connectionTimeout="45000" /&gt; </code></pre> <p>Relevant httpd.conf portions: </p> <pre><code>&lt;IfModule prefork.c&gt; StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 0 &lt;/IfModule&gt; </code></pre>
[ { "answer_id": 105928, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 3, "selected": false, "text": "<h3>MaxClients</h3>\n\n<p>This is the fundamental cap of parallel client connections your apache should handle at once...
2008/09/19
[ "https://Stackoverflow.com/questions/105754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4419/" ]
We are currently using Apache 2.2.3 and Tomcat 5 (Embedded in JBoss 4.2.2) using `mod_proxy_jk` as the connector. Can someone shed some light on the the correct way to calculate / configure the values below (as well as anything else that may be relevant). Both Apache and Tomcat are running on separate machines and have copious amounts of ram (4gb each). Relevant server.xml portions: ``` <Connector port="8009" address="${jboss.bind.address}" protocol="AJP/1.3" emptySessionPath="true" enableLookups="false" redirectPort="8443" maxThreads="320" connectionTimeout="45000" /> ``` Relevant httpd.conf portions: ``` <IfModule prefork.c> StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 0 </IfModule> ```
You should consider the workload the servers might get. The most important factor might be the number of simultaneously connected clients at peak times. Try to determine it and tune your settings in a way where: * there are enough processing threads in both Apache and Tomcat that they don't need to spawn new threads when the server is heavily loaded * there are not way more processing threads in the servers than needed as they would waste resources. With this kind of setup you can minimize the internal maintenance overhead of the servers, that could help a lot, especially when your load is sporadic. For example consider an application where you have ~300 new requests/second. Each request requires on average 2.5 seconds to serve. It means that at any given time you have ~750 requests that need to be handled simultaneously. In this situation you probably want to tune your servers so that they have ~750 processing threads at startup and you might want to add something like ~1000 processing threads at maximum to handle extremely high loads. Also consider for exactly what do you require a thread for. In the previous example each request was independent from the others, there was no session tracking used. In a more "web-ish" scenario you might have users logged in to your website, and depending on your software used, Apache and/or Tomcat might need to use the same thread to serve the requests that come in one session. In this case, you might need more threads. However as I know Tomcat at least, you won't really need to consider this as it works with thread pools internally anyways.
105,770
<p>I want to add a comma in the thousands place for a number.</p> <p>Would <code>String.Format()</code> be the correct path to take? What format would I use?</p>
[ { "answer_id": 105793, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 12, "selected": true, "text": "<pre><code>String.Format(\"{0:n}\", 1234); // Output: 1,234.00\nString.Format(\"{0:n0}\", 9876); // No digits after the decima...
2008/09/19
[ "https://Stackoverflow.com/questions/105770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
I want to add a comma in the thousands place for a number. Would `String.Format()` be the correct path to take? What format would I use?
``` String.Format("{0:n}", 1234); // Output: 1,234.00 String.Format("{0:n0}", 9876); // No digits after the decimal point. Output: 9,876 ```
105,776
<p>I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine.</p> <p>I tried using MySQL Administrator, but I got the following error:</p> <blockquote> <p>The selected file was generated by mysqldump and cannot be restored by this application.</p> </blockquote> <p>How do I get this working?</p>
[ { "answer_id": 105798, "author": "Justin Bennett", "author_id": 271, "author_profile": "https://Stackoverflow.com/users/271", "pm_score": 10, "selected": true, "text": "<p>It should be as simple as running this: </p>\n\n<pre><code>mysql -u &lt;user&gt; -p &lt; db_backup.dump\n</code></pr...
2008/09/19
[ "https://Stackoverflow.com/questions/105776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I was given a MySQL database file that I need to restore as a database on my Windows Server 2008 machine. I tried using MySQL Administrator, but I got the following error: > > The selected file was generated by > mysqldump and cannot be restored by > this application. > > > How do I get this working?
It should be as simple as running this: ``` mysql -u <user> -p < db_backup.dump ``` If the dump is of a single database you may have to add a line at the top of the file: ``` USE <database-name-here>; ``` If it was a dump of many databases, the use statements are already in there. To run these commands, open up a command prompt (in Windows) and `cd` to the directory where the `mysql.exe` executable is (you may have to look around a bit for it, it'll depend on how you installed mysql, i.e. standalone or as part of a package like WAMP). Once you're in that directory, you should be able to just type the command as I have it above.
105,777
<p>I've an issue with the same piece of code running fine on my live website but not on my local development server.</p> <p>I've an Ajax function that updates a div. The following code works on the live site:</p> <pre>self.xmlHttpReq.open("POST", PageURL, true); self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length); //..update div stuff... self.xmlHttpReq.send(QueryString);</pre> <p>When I try to run this on my local machine, nothing is passed to the QueryString.</p> <p>However, to confuse matters, the following code <strong>does</strong> work locally:</p> <pre>self.xmlHttpReq.open("POST", PageURL+"?"+QueryString, true); self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); //..div update stuff.. self.xmlHttpReq.send(QueryString);</pre> <p>But, I can't use the code that works on my local machine as it doesn't work on the live server (they've changed their policy on querystrings for security reasons)!</p> <p>I can alert the Querystring out so I know it's passed into the function on my local machine. The only thing I can think of is that it's a hardware/update issue.</p> <p>Live Site is running IIS 6 (on a WIN 2003 box I think)</p> <p>Local Site is running IIS 5.1 (On XP Pro)</p> <p>Are there some updates or something I'm missing or something?</p>
[ { "answer_id": 105828, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 1, "selected": false, "text": "<p>Is there a reason you're explicitly setting the <code>Content-Length</code> header in the first example? You... <em>shouldn't...
2008/09/19
[ "https://Stackoverflow.com/questions/105777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I've an issue with the same piece of code running fine on my live website but not on my local development server. I've an Ajax function that updates a div. The following code works on the live site: ``` self.xmlHttpReq.open("POST", PageURL, true); self.xmlHttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length); //..update div stuff... self.xmlHttpReq.send(QueryString); ``` When I try to run this on my local machine, nothing is passed to the QueryString. However, to confuse matters, the following code **does** work locally: ``` self.xmlHttpReq.open("POST", PageURL+"?"+QueryString, true); self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); //..div update stuff.. self.xmlHttpReq.send(QueryString); ``` But, I can't use the code that works on my local machine as it doesn't work on the live server (they've changed their policy on querystrings for security reasons)! I can alert the Querystring out so I know it's passed into the function on my local machine. The only thing I can think of is that it's a hardware/update issue. Live Site is running IIS 6 (on a WIN 2003 box I think) Local Site is running IIS 5.1 (On XP Pro) Are there some updates or something I'm missing or something?
Is there a reason you're explicitly setting the `Content-Length` header in the first example? You... *shouldn't* need to do this, and i wouldn't be surprised to find it causing problems. Oh, and check your encoding routine. The rules are not *quite* the same for querystrings and POSTed form data.
105,810
<p>Part of our app parses RTF documents and we've come across a special character that is not translating well. When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85).</p> <p>In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...)</p> <p>Here's the code in C# - problem is this doesn't work for values above 127. Any ideas?</p> <p>Calling code :</p> <pre><code>// S is Hex number!!! return Convert.ToChar(HexStringToInt(s)).ToString(); </code></pre> <p>Helper method:</p> <pre><code>private static int HexStringToInt(string hexString) { int i; try { i = Int32.Parse(hexString, NumberStyles.HexNumber); } catch (Exception ex) { throw new ApplicationException("Error trying to convert hex value: " + hexString, ex); } return i; } </code></pre>
[ { "answer_id": 105823, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 0, "selected": false, "text": "<pre><code>private static int HexStringToInt(string hexString)\n{\n try\n {\n return Convert.ToChar(hexString);\...
2008/09/19
[ "https://Stackoverflow.com/questions/105810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19327/" ]
Part of our app parses RTF documents and we've come across a special character that is not translating well. When viewed in Word the character is an elipsis (...), and it's encoded in the RTF as ('85). In our vb code we converted the hex (85) to int(133) and then did Chr(133) to return (...) Here's the code in C# - problem is this doesn't work for values above 127. Any ideas? Calling code : ``` // S is Hex number!!! return Convert.ToChar(HexStringToInt(s)).ToString(); ``` Helper method: ``` private static int HexStringToInt(string hexString) { int i; try { i = Int32.Parse(hexString, NumberStyles.HexNumber); } catch (Exception ex) { throw new ApplicationException("Error trying to convert hex value: " + hexString, ex); } return i; } ```
This looks like a character encoding issue to me. Unicode doesn't include any characters with numbers in the upper-ASCII 128-255 range, so trying to convert character 133 will fail. Need to convert it first to a character using the proper decoding, Convert.toChar appears to be using UTF-16. Sometimes there's a manual bit manipulation hack to convert the character from upper ASCII to the appropriate unicode char, but since the ellipsis wasn't in most of the widely used extended ASCII codepages, that's unlikely to work here. What you really want to do is use the [Encoding.GetString(Byte[])](http://msdn.microsoft.com/en-us/library/744y86tc.aspx) method, with the proper encoding. Put your value into a byte array, then GetString to get the C# native string for the character. You can learn more about RTF character encodings on the [RTF Wikipedia page](http://en.wikipedia.org/wiki/Rich_Text_Format#Character_encoding). FYI: The horizontal ellipsis is [character U+2026 (pdf)](http://unicode.org/charts/PDF/U2000.pdf).
105,816
<p>I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char ** (array of strings). If I declare my function as <code>(_fun _pointer -&gt; _pointer)</code>, how do I convert the result to a list of strings in scheme?</p> <p>Here are the relevant C-declarations:</p> <pre><code>typedef char **MYSQL_ROW; /* return data as array of strings */ // ... MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); </code></pre>
[ { "answer_id": 105938, "author": "Jonathan Arkell", "author_id": 11052, "author_profile": "https://Stackoverflow.com/users/11052", "pm_score": 0, "selected": false, "text": "<p>I know it's not exactly what you are looking for, but it might help a little bit. I've done some work on a bas...
2008/09/19
[ "https://Stackoverflow.com/questions/105816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18180/" ]
I'm mocking about with plt-scheme's ffi and I have a C-function that returns a char \*\* (array of strings). If I declare my function as `(_fun _pointer -> _pointer)`, how do I convert the result to a list of strings in scheme? Here are the relevant C-declarations: ``` typedef char **MYSQL_ROW; /* return data as array of strings */ // ... MYSQL_ROW STDCALL mysql_fetch_row(MYSQL_RES *result); ```
I *think* that what you want is the cvector: <http://docs.plt-scheme.org/foreign/Derived_Utilities.html#(part._foreign~3acvector)> A cvector of \_string/utf-8 or whichever encoding you need seems reasanable. But that's from a quick survey of the docs - I haven't tried this myself. Please let me know if it works!
105,852
<p>After reading "<a href="http://web.archive.org/web/20090117062700/http://stackoverflow.com:80/questions/20702/whats-youra-good-limit-for-cyclomatic-complexity" rel="noreferrer">What’s your/a good limit for cyclomatic complexity?</a>", I realize many of my colleagues were quite annoyed with this new <a href="http://en.wikipedia.org/wiki/Quality_assurance" rel="noreferrer">QA</a> policy on our project: no more 10 <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="noreferrer">cyclomatic complexity</a> per function.</p> <p>Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in '<a href="https://stackoverflow.com/questions/105007/do-you-test-private-method#105114">Do you test private method?</a>', such a policy has many good side-effects.</p> <p>But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of '<a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" rel="noreferrer">Aspect-oriented programming</a>' approach for logs).</p> <pre><code>myLogger.info("A String"); myLogger.fine("A more complicated String"); ... </code></pre> <p>And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the <em>log parameters</em> (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place!</p> <p>So QA came back and urged our programmers to do conditional logging. Always.</p> <pre><code>if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String"); if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String"); ... </code></pre> <p>But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity!</p> <p>So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be <em>really</em> part of said complexity of that function...</p> <p>How would you address this situation ?<br> I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first.</p> <hr> <p>Thank you for all the answers.<br> I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)<br> So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the <em>obligation</em> to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...)</p> <p>I now get the '<a href="http://en.wikipedia.org/wiki/Variadic_function" rel="noreferrer">variadic</a> function' point advanced by some of you (thank you John).<br> Note: a quick test in java6 shows that my <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html" rel="noreferrer">varargs function</a> does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it.</p> <p>I have now posted my experience on this topic.<br> I will leave it there until next Tuesday for voting, then I will select one of your answers.<br> Again, thank you for all the suggestions :)</p>
[ { "answer_id": 105876, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>In C or C++ I'd use the preprocessor instead of the if statements for the conditional logging.</p>\n" }, { "an...
2008/09/19
[ "https://Stackoverflow.com/questions/105852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6309/" ]
After reading "[What’s your/a good limit for cyclomatic complexity?](http://web.archive.org/web/20090117062700/http://stackoverflow.com:80/questions/20702/whats-youra-good-limit-for-cyclomatic-complexity)", I realize many of my colleagues were quite annoyed with this new [QA](http://en.wikipedia.org/wiki/Quality_assurance) policy on our project: no more 10 [cyclomatic complexity](http://en.wikipedia.org/wiki/Cyclomatic_complexity) per function. Meaning: no more than 10 'if', 'else', 'try', 'catch' and other code workflow branching statement. Right. As I explained in '[Do you test private method?](https://stackoverflow.com/questions/105007/do-you-test-private-method#105114)', such a policy has many good side-effects. But: At the beginning of our (200 people - 7 years long) project, we were happily logging (and no, we can not easily delegate that to some kind of '[Aspect-oriented programming](http://en.wikipedia.org/wiki/Aspect-oriented_programming)' approach for logs). ``` myLogger.info("A String"); myLogger.fine("A more complicated String"); ... ``` And when the first versions of our System went live, we experienced huge memory problem not because of the logging (which was at one point turned off), but because of the *log parameters* (the strings), which are always calculated, then passed to the 'info()' or 'fine()' functions, only to discover that the level of logging was 'OFF', and that no logging were taking place! So QA came back and urged our programmers to do conditional logging. Always. ``` if(myLogger.isLoggable(Level.INFO) { myLogger.info("A String"); if(myLogger.isLoggable(Level.FINE) { myLogger.fine("A more complicated String"); ... ``` But now, with that 'can-not-be-moved' 10 cyclomatic complexity level per function limit, they argue that the various logs they put in their function is felt as a burden, because each "if(isLoggable())" is counted as +1 cyclomatic complexity! So if a function has 8 'if', 'else' and so on, in one tightly-coupled not-easily-shareable algorithm, and 3 critical log actions... they breach the limit even though the conditional logs may not be *really* part of said complexity of that function... How would you address this situation ? I have seen a couple of interesting coding evolution (due to that 'conflict') in my project, but I just want to get your thoughts first. --- Thank you for all the answers. I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing) So when a wrote above "A String", I actually meant aFunction(), with aFunction() returning a String, and being a call to a complicated method collecting and computing all kind of log data to be displayed by the logger... or not (hence the issue, and the *obligation* to use conditional logging, hence the actual issue of artificial increase of 'cyclomatic complexity'...) I now get the '[variadic](http://en.wikipedia.org/wiki/Variadic_function) function' point advanced by some of you (thank you John). Note: a quick test in java6 shows that my [varargs function](http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html) does evaluate its arguments before being called, so it can not be applied for function call, but for 'Log retriever object' (or 'function wrapper'), on which the toString() will only be called if needed. Got it. I have now posted my experience on this topic. I will leave it there until next Tuesday for voting, then I will select one of your answers. Again, thank you for all the suggestions :)
In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting. ``` log.info ("a = %s, b = %s", a, b) ``` You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc). --- This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing `mylist.toString()` will take a while to no benefit, as the result will be thrown away. So you pass `mylist` as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed. --- Since the OP's question specifically mentions Java, here's how the above can be used: > > I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing) > > > The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination. Say you have a function `get_everything()`. It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called `LazyGetEverything`: ``` public class MainClass { private class LazyGetEverything { @Override public String toString() { return getEverything().toString(); } } private Object getEverything() { /* returns what you want to .toString() in the inner class */ } public void logEverything() { log.info(new LazyGetEverything()); } } ``` In this code, the call to `getEverything()` is wrapped so that it won't actually be executed until it's needed. The logging function will execute `toString()` on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full `getEverything()` call.
105,884
<p>I have an .Net MVC application which runs fine if I use the build in Visual Studio Webserver. If I use the projects property pages to switch to IIS as the webserver and create a virtual directory for my project, any request I send to the server results in a "Directory listing denied" failure.</p> <p>Does anyone know a solution for this?</p>
[ { "answer_id": 105876, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>In C or C++ I'd use the preprocessor instead of the if statements for the conditional logging.</p>\n" }, { "an...
2008/09/19
[ "https://Stackoverflow.com/questions/105884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
I have an .Net MVC application which runs fine if I use the build in Visual Studio Webserver. If I use the projects property pages to switch to IIS as the webserver and create a virtual directory for my project, any request I send to the server results in a "Directory listing denied" failure. Does anyone know a solution for this?
In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting. ``` log.info ("a = %s, b = %s", a, b) ``` You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc). --- This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing `mylist.toString()` will take a while to no benefit, as the result will be thrown away. So you pass `mylist` as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed. --- Since the OP's question specifically mentions Java, here's how the above can be used: > > I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing) > > > The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination. Say you have a function `get_everything()`. It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called `LazyGetEverything`: ``` public class MainClass { private class LazyGetEverything { @Override public String toString() { return getEverything().toString(); } } private Object getEverything() { /* returns what you want to .toString() in the inner class */ } public void logEverything() { log.info(new LazyGetEverything()); } } ``` In this code, the call to `getEverything()` is wrapped so that it won't actually be executed until it's needed. The logging function will execute `toString()` on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full `getEverything()` call.
105,932
<p>It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list:</p> <ul> <li>Window position same as it was <ul> <li>Unless the screen has resized and the old position is now off screen.</li> </ul></li> <li>Splitters should retain their position</li> <li>Tab containers should retain their selection</li> <li>Some dropdowns should retain their selection</li> <li>Window state (maximize, minimize, normal) is the same as it was. <ul> <li>Maybe you should never start minimized, I haven't decided.</li> </ul></li> </ul> <p>I'll add my current solutions as an answer along with the limitations.</p>
[ { "answer_id": 105969, "author": "Don Kirkby", "author_id": 4794, "author_profile": "https://Stackoverflow.com/users/4794", "pm_score": 3, "selected": false, "text": "<p>The simplest solution I've found is to use data binding with the application settings. I bind the location and clientS...
2008/09/19
[ "https://Stackoverflow.com/questions/105932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4794/" ]
It seems like a standard requirement: next time the user launches the application, open the window in the same position and state as it was before. Here's my wish list: * Window position same as it was + Unless the screen has resized and the old position is now off screen. * Splitters should retain their position * Tab containers should retain their selection * Some dropdowns should retain their selection * Window state (maximize, minimize, normal) is the same as it was. + Maybe you should never start minimized, I haven't decided. I'll add my current solutions as an answer along with the limitations.
My other option is to write more custom code around the application settings and execute it on formLoad and formClosed. This doesn't use data binding. Drawbacks: * More code to write. * Very fiddly. The order you set the properties on formLoad is confusing. For example, you have to make sure you've set the window size before you set the splitter distance. Right now, this is my preferred solution, but it seems like too much work. To reduce the work, I created a WindowSettings class that serializes the window location, size, state, and any splitter positions to a single application setting. Then I can just create a setting of that type for each form in my application, save on close, and restore on load. I posted [the source code](https://github.com/donkirkby/donkirkby/blob/master/WindowSettings/WindowSettings.cs), including the WindowSettings class and some forms that use it. Instructions on adding it to a project are included in the WindowSettings.cs file. The trickiest part was figuring out how to add an application setting with a custom type. You choose Browse... from the type dropdown, and then manually enter the namespace and class name. Types from your project don't show up in the list. **Update:** I added some static methods to simplify the boilerplate code that you add to each form. Once you've followed the instructions for adding the WindowSettings class to your project and creating an application setting, here's an example of the code that has to be added to each form whose position you want to record and restore. ``` private void MyForm_FormClosing(object sender, FormClosingEventArgs e) { Settings.Default.CustomWindowSettings = WindowSettings.Record( Settings.Default.CustomWindowSettings, this, splitContainer1); } private void MyForm_Load(object sender, EventArgs e) { WindowSettings.Restore( Settings.Default.CustomWindowSettings, this, splitContainer1); } ```
105,935
<p>This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.</p>
[ { "answer_id": 106125, "author": "Sparr", "author_id": 13675, "author_profile": "https://Stackoverflow.com/users/13675", "pm_score": 1, "selected": false, "text": "<p>Unfortunately there is no more efficient way than a linear search, unless you know that your listbox is sorted or indexed...
2008/09/19
[ "https://Stackoverflow.com/questions/105935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3155/" ]
This request is based in MS Access VBA. I would like to know what the most efficient way is, to see if an item exists in a listbox control.
Here is a sample function that might be adapted to suit. ``` Function CheckForItem(strItem, ListB As ListBox) As Boolean Dim rs As DAO.Recordset Dim db As Database Dim tdf As TableDef Set db = CurrentDb CheckForItem = False Select Case ListB.RowSourceType Case "Value List" CheckForItem = InStr(ListB.RowSource, strItem) > 0 Case "Table/Query" Set rs = db.OpenRecordset(ListB.RowSource) For i = 0 To rs.Fields.Count - 1 strList = strList & " & "","" & " & rs.Fields(i).Name Next rs.FindFirst "Instr(" & Mid(strList, 10) & ",'" & strItem & "')>0" If Not rs.EOF Then CheckForItem = True Case "Field List" Set tdf = db.TableDefs(ListB.RowSource) For Each itm In tdf.Fields If itm.Name = strItem Then CheckForItem = True Next End Select End Function ```
105,950
<p>I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.</p>
[ { "answer_id": 105965, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 5, "selected": true, "text": "<p>from: <a href=\"http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm\" rel=\"noreferrer\">http://doc.ddart.net/mssql/s...
2008/09/19
[ "https://Stackoverflow.com/questions/105950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320/" ]
I can't seem to figure out how to set the default database in Sql Server from code. This can be either .Net code or T-Sql (T-Sql would be nice since it would be easy to use in any language). I searched Google and could only find how to do it in Sql Server Management Studio.
from: <http://doc.ddart.net/mssql/sql70/sp_da-di_6.htm> ``` sp_defaultdb [@loginame =] 'login' , [@defdb =] 'database' ```
105,971
<p>I am working on a bash script where I need to conditionally execute some things if a particular file exists. This is happening multiple times, so I abstracted the following function:</p> <pre><code>function conditional-do { if [ -f $1 ] then echo "Doing stuff" $2 else echo "File doesn't exist!" end } </code></pre> <p>Now, when I want to execute this, I do something like:</p> <pre><code>function exec-stuff { echo "do some command" echo "do another command" } conditional-do /path/to/file exec-stuff </code></pre> <p>The problem is, I am bothered that I am defining 2 things: the function of a group of commands to execute, and then invoking my first function.</p> <p>I would like to pass this block of commands (often 2 or more) directly to "conditional-do" in a clean manner, but I have no idea how this is doable (or if it is even possible)... does anyone have any ideas?</p> <p>Note, I need it to be a readable solution... otherwise I would rather stick with what I have.</p>
[ { "answer_id": 105982, "author": "Alex Gartrell", "author_id": 10307, "author_profile": "https://Stackoverflow.com/users/10307", "pm_score": 0, "selected": false, "text": "<p>One (possibly-hack) solution is to store the separate functions as separate scripts altogether.</p>\n" }, { ...
2008/09/19
[ "https://Stackoverflow.com/questions/105971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I am working on a bash script where I need to conditionally execute some things if a particular file exists. This is happening multiple times, so I abstracted the following function: ``` function conditional-do { if [ -f $1 ] then echo "Doing stuff" $2 else echo "File doesn't exist!" end } ``` Now, when I want to execute this, I do something like: ``` function exec-stuff { echo "do some command" echo "do another command" } conditional-do /path/to/file exec-stuff ``` The problem is, I am bothered that I am defining 2 things: the function of a group of commands to execute, and then invoking my first function. I would like to pass this block of commands (often 2 or more) directly to "conditional-do" in a clean manner, but I have no idea how this is doable (or if it is even possible)... does anyone have any ideas? Note, I need it to be a readable solution... otherwise I would rather stick with what I have.
This should be readable to most C programmers: ``` function file_exists { if ( [ -e $1 ] ) then echo "Doing stuff" else echo "File $1 doesn't exist" false fi } file_exists filename && ( echo "Do your stuff..." ) ``` or the one-liner ``` file_exists filename && echo "Do your stuff..." ``` Now, if you really want the code to be run from the function, this is how you can do that: ``` function file_exists { if ( [ -e $1 ] ) then echo "Doing stuff" shift $* else echo "File $1 doesn't exist" false fi } file_exists filename echo "Do your stuff..." ``` I don't like that solution though, because you will eventually end up doing escaping of the command string. EDIT: Changed "eval $\*" to $ \*. Eval is not required, actually. As is common with bash scripts, it was written when I had had a couple of beers ;-)
105,996
<ul> <li>I want to obtain maximum performance out of a process with many variables, many of which cannot be controlled. </li> <li>I cannot run thousands of experiments, so it'd be nice if I could run hundreds of experiments and <ul> <li>vary many controllable parameters</li> <li>collect data on many parameters indicating performance</li> <li>'correct,' as much as possible, for those parameters I couldn't control</li> <li>Tease out the 'best' values for those things I can control, and start all over again</li> </ul></li> </ul> <p>It feels like this would be called data mining, where you're going through tons of data which doesn't immediately appear to relate, but does show correlation after some effort.</p> <p>So... Where do I start looking at algorithms, concepts, theory of this sort of thing? Even related terms for purposes of search would be useful.</p> <p>Background: I like to do ultra-marathon cycling, and keep logs of each ride. I'd like to keep more data, and after hundreds of rides be able to pull out information about how I perform.</p> <p>However, everything varies - routes, environment (temp, pres., hum., sun load, wind, precip., etc), fuel, attitude, weight, water load, etc, etc, etc. I can control a few things, but running the same route 20 times to test out a new fuel regime would just be depressing, and take years to perform all the experiments that I'd like to do. I can, however, record all these things and more(telemetry on bicycle FTW).</p>
[ { "answer_id": 106013, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 3, "selected": true, "text": "<p>It sounds like you want to do some <a href=\"http://en.wikipedia.org/wiki/Regression_analysis\" rel=\"nofollow norefer...
2008/09/19
[ "https://Stackoverflow.com/questions/105996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
* I want to obtain maximum performance out of a process with many variables, many of which cannot be controlled. * I cannot run thousands of experiments, so it'd be nice if I could run hundreds of experiments and + vary many controllable parameters + collect data on many parameters indicating performance + 'correct,' as much as possible, for those parameters I couldn't control + Tease out the 'best' values for those things I can control, and start all over again It feels like this would be called data mining, where you're going through tons of data which doesn't immediately appear to relate, but does show correlation after some effort. So... Where do I start looking at algorithms, concepts, theory of this sort of thing? Even related terms for purposes of search would be useful. Background: I like to do ultra-marathon cycling, and keep logs of each ride. I'd like to keep more data, and after hundreds of rides be able to pull out information about how I perform. However, everything varies - routes, environment (temp, pres., hum., sun load, wind, precip., etc), fuel, attitude, weight, water load, etc, etc, etc. I can control a few things, but running the same route 20 times to test out a new fuel regime would just be depressing, and take years to perform all the experiments that I'd like to do. I can, however, record all these things and more(telemetry on bicycle FTW).
It sounds like you want to do some [regression analysis](http://en.wikipedia.org/wiki/Regression_analysis). You certainly have plenty of data! --- Regression analysis is an extremely common modeling technique in statistics and science. (It could be argued that statistics is the art and science of regression analysis.) There are many statistics packages out there to do the computation you'll need. (I'd recommend one, but I'm years out of date.) Data mining has gotten a bad name because far too often people assume correlation equals causation. I found that a good technique is to start with variables you know have an influence and build a statistical model around them first. So you know that wind, weight and climb have an influence on how fast you can travel and statistical software can take your dataset and calculate what the correlation between those factors are. That will give you a statistical model or linear equation: ``` speed = x*weight + y*wind + z*climb + constant ``` When you explore new variables, you will be able to see if the model is improved or not by comparing a goodness of fit metric like R-squared. So you might check if temperature or time of day adds anything to the model. You may want to apply a transformation to you data. For instance, you might find that you perform better on colder days. But really cold days and really hot days might hurt performance. In that case, you could assign temperatures to bins or [segments](http://en.wikipedia.org/wiki/Segmented_regression): < 0°C; 0°C to 40°C; > 40°C, or some such. The key is to transform the data in a way that matches a rational model of what is going on in the real world, not just the data itself. --- In case someone thinks this is not a programming related topic, notice that you can use these same techniques to analyze system performance.
105,998
<p>According to what I have found so far, I can use the following code:</p> <pre> LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean)super.getApplicationContext().getBean("&sessionFactory"); System.out.println(sessionFactory.getConfiguration().buildSettings().getJdbcBatchSize()); </pre> <p>but then I get a Hibernate Exception:</p> <blockquote> <p>org.hibernate.HibernateException: No local DataSource found for configuration - dataSource property must be set on LocalSessionFactoryBean</p> </blockquote> <p>Can somebody shed some light?</p>
[ { "answer_id": 106165, "author": "Matt Solnit", "author_id": 6198, "author_profile": "https://Stackoverflow.com/users/6198", "pm_score": 3, "selected": true, "text": "<p>Try the following (I can't test it since I don't use Spring):</p>\n\n<pre><code>System.out.println(sessionFactory.getC...
2008/09/19
[ "https://Stackoverflow.com/questions/105998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14068/" ]
According to what I have found so far, I can use the following code: ``` LocalSessionFactoryBean sessionFactory = (LocalSessionFactoryBean)super.getApplicationContext().getBean("&sessionFactory"); System.out.println(sessionFactory.getConfiguration().buildSettings().getJdbcBatchSize()); ``` but then I get a Hibernate Exception: > > org.hibernate.HibernateException: No local DataSource found for > configuration - dataSource property must be set on > LocalSessionFactoryBean > > > Can somebody shed some light?
Try the following (I can't test it since I don't use Spring): ``` System.out.println(sessionFactory.getConfiguration().getProperty("hibernate.jdbc.batch_size")) ```
106,000
<p>I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list?</p> <p>I have been searching for awhile but I cannot seem to find a comprehensive list.</p> <p>Thanks :)</p>
[ { "answer_id": 106165, "author": "Matt Solnit", "author_id": 6198, "author_profile": "https://Stackoverflow.com/users/6198", "pm_score": 3, "selected": true, "text": "<p>Try the following (I can't test it since I don't use Spring):</p>\n\n<pre><code>System.out.println(sessionFactory.getC...
2008/09/19
[ "https://Stackoverflow.com/questions/106000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14281/" ]
I have been tasked with coming up with a compatibility guide for SharePoint 2007 comparing Office 2003 and Office 2007. Does anyone know where to find such a list? I have been searching for awhile but I cannot seem to find a comprehensive list. Thanks :)
Try the following (I can't test it since I don't use Spring): ``` System.out.println(sessionFactory.getConfiguration().getProperty("hibernate.jdbc.batch_size")) ```
106,001
<p>I have some code which utilizes parameterized queries to prevent against injection, but I also need to be able to dynamically construct the query regardless of the structure of the table. What is the proper way to do this?</p> <p>Here's an example, say I have a table with columns Name, Address, Telephone. I have a web page where I run <b>Show Columns</b> and populate a select drop-down with them as options.</p> <p>Next, I have a textbox called <b>Search</b>. This textbox is used as the parameter.</p> <p>Currently my code looks something like this:</p> <pre> result = pquery('SELECT * FROM contacts WHERE `' + escape(column) + '`=?', search); </pre> <p>I get an icky feeling from it though. The reason I'm using parameterized queries is to avoid using <b>escape</b>. Also, <b>escape</b> is likely not designed for escaping column names.</p> <p>How can I make sure this works the way I intend?</p> <p><b>Edit:</b> The reason I require dynamic queries is that the schema is user-configurable, and I will not be around to fix anything hard-coded.</p>
[ { "answer_id": 106014, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 4, "selected": true, "text": "<p>Instead of passing the column names, just pass an identifier that you code will translate to a column name using a hardcode...
2008/09/19
[ "https://Stackoverflow.com/questions/106001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ]
I have some code which utilizes parameterized queries to prevent against injection, but I also need to be able to dynamically construct the query regardless of the structure of the table. What is the proper way to do this? Here's an example, say I have a table with columns Name, Address, Telephone. I have a web page where I run **Show Columns** and populate a select drop-down with them as options. Next, I have a textbox called **Search**. This textbox is used as the parameter. Currently my code looks something like this: ``` result = pquery('SELECT * FROM contacts WHERE `' + escape(column) + '`=?', search); ``` I get an icky feeling from it though. The reason I'm using parameterized queries is to avoid using **escape**. Also, **escape** is likely not designed for escaping column names. How can I make sure this works the way I intend? **Edit:** The reason I require dynamic queries is that the schema is user-configurable, and I will not be around to fix anything hard-coded.
Instead of passing the column names, just pass an identifier that you code will translate to a column name using a hardcoded table. This means you don't need to worry about malicious data being passed, since all the data is either translated legally, or is known to be invalid. Psudoish code: ``` @columns = qw/Name Address Telephone/; if ($columns[$param]) { $query = "select * from contacts where $columns[$param] = ?"; } else { die "Invalid column!"; } run_sql($query, $search); ```
106,033
<p>Suppose I am writing an application in C++ and C#. I want to write the low level parts in C++ and write the high level logic in C#. How can I load a .NET assembly from my C++ program and start calling methods and accessing the properties of my C# classes?</p>
[ { "answer_id": 106050, "author": "QBziZ", "author_id": 11572, "author_profile": "https://Stackoverflow.com/users/11572", "pm_score": 0, "selected": false, "text": "<p>You can wrap the .NET component in a COM component - which is quite easy with the .NET tools - and call it via COM.</p>\n...
2008/09/19
[ "https://Stackoverflow.com/questions/106033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4828/" ]
Suppose I am writing an application in C++ and C#. I want to write the low level parts in C++ and write the high level logic in C#. How can I load a .NET assembly from my C++ program and start calling methods and accessing the properties of my C# classes?
``` [Guid("123565C4-C5FA-4512-A560-1D47F9FDFA20")] public interface IConfig { [DispId(1)] string Destination{ get; } [DispId(2)] void Unserialize(); [DispId(3)] void Serialize(); } [ComVisible(true)] [Guid("12AC8095-BD27-4de8-A30B-991940666927")] [ClassInterface(ClassInterfaceType.None)] public sealed class Config : IConfig { public Config() { } public string Destination { get { return ""; } } public void Serialize() { } public void Unserialize() { } } ``` After that, you need to regasm your assembly. Regasm will add the necessary registry entries to allow your .NET component to be see as a COM Component. After, you can call your .NET Component in C++ in the same way as any other COM component.
106,053
<p>I already know the obvious answer to this question: "just download &lt;insert favorite windows grep or grep-like tool here&gt;". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep":</p> <pre> perl -n -e "print $_ if (m![expression]!);" [filename] </pre> <p>How do I write a batch script that I can do something like, for example:</p> <pre> dir | grep.bat mypattern grep.bat mypattern myfile.txt </pre> <p><strong>EDIT</strong>: Even though I marked another "answer", I wanted to give kudos to <a href="https://stackoverflow.com/questions/106053/how-to-make-a-batch-file-to-act-like-a-simple-grep-using-perl#106099">Ray Hayes answer</a>, as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted.</p>
[ { "answer_id": 106099, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 5, "selected": false, "text": "<p>Most of the power of grep is already available on your machine in the Windows application FindStr.exe which is part of ...
2008/09/19
[ "https://Stackoverflow.com/questions/106053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13140/" ]
I already know the obvious answer to this question: "just download <insert favorite windows grep or grep-like tool here>". However, I work in an environment with strict controls by the local IT staff as to what we're allowed to have on our computers. Suffice it to say: I have access to Perl on Windows XP. Here's a quick Perl script I came up with that does what I want, but I haven't figured up how to set up a batch file such that I can either pipe a command output into it, or pass a file (or list of files?) as an argument after the "expression to grep": ``` perl -n -e "print $_ if (m![expression]!);" [filename] ``` How do I write a batch script that I can do something like, for example: ``` dir | grep.bat mypattern grep.bat mypattern myfile.txt ``` **EDIT**: Even though I marked another "answer", I wanted to give kudos to [Ray Hayes answer](https://stackoverflow.com/questions/106053/how-to-make-a-batch-file-to-act-like-a-simple-grep-using-perl#106099), as it is really the "Windows Way" to do it, even if another answer is technically closer to what I wanted.
I wrote this a while back: ``` @rem = '--*-Perl-*-- @echo off perl -x -S %0 %* goto endofperl @rem -- BEGIN PERL -- '; #!d:/Perl/bin/perl.exe -w #line 10 use strict; #use Test::Setup; use Getopt::Long; Getopt::Long::Configure ("bundling"); my $ignore_case = 0; my $number_line = 0; my $invert_results = 0; my $verbose = 0; my $result = GetOptions( 'i|ignore_case' => \$ignore_case, 'n|number' => \$number_line, 'v|invert' => \$invert_results, 'verbose' => \$verbose, ); my $regex = shift; if ( $ignore_case ) { $regex = "(?i:$regex)"; } $regex = qr/$regex/; print "\$regex=$regex\n"; if ( $verbose ) { print "Verbose: Ignoring case.\n" if $ignore_case; print "Verbose: Printing file name and line number.\n" if $number_line; print "Verbose: Inverting result set.\n" if $invert_results; print "\n"; } @ARGV = map { glob "$_" } @ARGV; while ( <> ) { my $matches = m/$regex/; next unless $matches ^ $invert_results; print "$ARGV\:$.:" if $number_line; print; } __END__ :endofperl ```
106,058
<p>Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some.</p> <p>Is there a <em>practical</em> code example of Lisp's power?<br/>(Preferably alongside equivalent logic coded in a regular language.)</p>
[ { "answer_id": 106075, "author": "William Keller", "author_id": 17095, "author_profile": "https://Stackoverflow.com/users/17095", "pm_score": 3, "selected": false, "text": "<p>Have you taken a look at <a href=\"https://web.archive.org/web/20170702100142/http://www.weitz.de/macros.lisp\" ...
2008/09/19
[ "https://Stackoverflow.com/questions/106058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ]
Someone is trying to sell Lisp to me, as a super powerful language that can do everything ever, and then some. Is there a *practical* code example of Lisp's power? (Preferably alongside equivalent logic coded in a regular language.)
I like macros. Here's code to stuff away attributes for people from LDAP. I just happened to have that code lying around and fiigured it'd be useful for others. Some people are confused over a supposed runtime penalty of macros, so I've added an attempt at clarifying things at the end. In The Beginning, There Was Duplication ======================================= ``` (defun ldap-users () (let ((people (make-hash-table :test 'equal))) (ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))")) (let ((mail (car (ldap:attr-value ent 'mail))) (uid (car (ldap:attr-value ent 'uid))) (name (car (ldap:attr-value ent 'cn))) (phonenumber (car (ldap:attr-value ent 'telephonenumber)))) (setf (gethash uid people) (list mail name phonenumber)))) people)) ``` You can think of a "let binding" as a local variable, that disappears outside the LET form. Notice the form of the bindings -- they are very similar, differing only in the attribute of the LDAP entity and the name ("local variable") to bind the value to. Useful, but a bit verbose and contains duplication. On the Quest for Beauty ======================= Now, wouldn't it be nice if we didn't have to have all that duplication? A common idiom is is WITH-... macros, that binds values based on an expression that you can grab the values from. Let's introduce our own macro that works like that, WITH-LDAP-ATTRS, and replace it in our original code. ``` (defun ldap-users () (let ((people (make-hash-table :test 'equal))) ; equal so strings compare equal! (ldap:dosearch (ent (ldap:search *ldap* "(&(telephonenumber=*) (cn=*))")) (with-ldap-attrs (mail uid name phonenumber) ent (setf (gethash uid people) (list mail name phonenumber)))) people)) ``` Did you see how a bunch of lines suddenly disappeared, and was replaced with just one single line? How to do this? Using macros, of course -- code that writes code! Macros in Lisp is a totally different animal than the ones you can find in C/C++ through the use of the pre-processor: here, you can run *real* Lisp code (not the `#define` fluff in cpp) that generates Lisp code, before the other code is compiled. Macros can use any real Lisp code, i.e., ordinary functions. Essentially no limits. Getting Rid of Ugly =================== So, let's see how this was done. To replace one attribute, we define a function. ``` (defun ldap-attr (entity attr) `(,attr (car (ldap:attr-value ,entity ',attr)))) ``` The backquote syntax looks a bit hairy, but what it does is easy. When you call LDAP-ATTRS, it'll spit out a list that contains the *value* of `attr` (that's the comma), followed by `car` ("first element in the list" (cons pair, actually), and there is in fact a function called `first` you can use, too), which receives the first value in the list returned by `ldap:attr-value`. Because this isn't code we want to run when we compile the code (getting the attribute values is what we want to do when we *run* the program), we don't add a comma before the call. Anyway. Moving along, to the rest of the macro. ``` (defmacro with-ldap-attrs (attrs ent &rest body) `(let ,(loop for attr in attrs collecting `,(ldap-attr ent attr)) ,@body)) ``` The `,@`-syntax is to put the contents of a list somewhere, instead of the actual list. Result ====== You can easily verify that this will give you the right thing. Macros are often written this way: you start off with code you want to make simpler (the output), what you want to write instead (the input), and then you start molding the macro until your input gives the correct output. The function `macroexpand-1` will tell you if your macro is correct: ``` (macroexpand-1 '(with-ldap-attrs (mail phonenumber) ent (format t "~a with ~a" mail phonenumber))) ``` evaluates to ``` (let ((mail (car (trivial-ldap:attr-value ent 'mail))) (phonenumber (car (trivial-ldap:attr-value ent 'phonenumber)))) (format t "~a with ~a" mail phonenumber)) ``` If you compare the LET-bindings of the expanded macro with the code in the beginning, you'll find that it is in the same form! Compile-time vs Runtime: Macros vs Functions ============================================ A macro is code that is run at *compile-time*, with the added twist that they can call any *ordinary* function or macro as they please! It's not much more than a fancy filter, taking some arguments, applying some transformations and then feeding the compiler the resulting s-exps. Basically, it lets you write your code in verbs that can be found in the problem domain, instead of low-level primitives from the language! As a silly example, consider the following (if `when` wasn't already a built-in):: ``` (defmacro my-when (test &rest body) `(if ,test (progn ,@body))) ``` `if` is a built-in primitive that will only let you execute *one* form in the branches, and if you want to have more than one, well, you need to use `progn`:: ``` ;; one form (if (numberp 1) (print "yay, a number")) ;; two forms (if (numberp 1) (progn (assert-world-is-sane t) (print "phew!")))) ``` With our new friend, `my-when`, we could both a) use the more appropriate verb if we don't have a false branch, and b) add an implicit sequencing operator, i.e. `progn`:: ``` (my-when (numberp 1) (assert-world-is-sane t) (print "phew!")) ``` The compiled code will never contain `my-when`, though, because in the first pass, all macros are expanded so there is *no runtime penalty* involved! ``` Lisp> (macroexpand-1 '(my-when (numberp 1) (print "yay!"))) (if (numberp 1) (progn (print "yay!"))) ``` Note that `macroexpand-1` only does one level of expansions; it's possible (most likely, in fact!) that the expansion continues further down. However, eventually you'll hit the compiler-specific implementation details which are often not very interesting. But continuing expanding the result will eventually either get you more details, or just your input s-exp back. Hope that clarifies things. Macros is a powerful tool, and one of the features in Lisp I like.
106,067
<p>In java, which regular expression can be used to replace these, for example:</p> <p>before: aaabbb after: ab</p> <p>before: 14442345 after: 142345</p> <p>thanks!</p>
[ { "answer_id": 106096, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 6, "selected": true, "text": "<p>In perl</p>\n\n<pre><code>s/(.)\\1+/$1/g;\n</code></pre>\n\n<p>Does the trick, I assume if java has perl compatible regexps it s...
2008/09/19
[ "https://Stackoverflow.com/questions/106067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18300/" ]
In java, which regular expression can be used to replace these, for example: before: aaabbb after: ab before: 14442345 after: 142345 thanks!
In perl ``` s/(.)\1+/$1/g; ``` Does the trick, I assume if java has perl compatible regexps it should work too. Edit: Here is what it means ``` s { (.) # match any charater ( and capture it ) \1 # if it is followed by itself + # One or more times }{$1}gx; # And replace the whole things by the first captured character (with g modifier to replace all occurences) ``` Edit: As others have pointed out, the syntax in Java would become ``` original.replaceAll("(.)\\1+", "$1"); ``` remember to escape the \1
106,095
<p>Using ASP.NET 2.0, I have a web app where I am trying to use JavaScript to make one tab in a tab-container the active tab.</p> <p>The recommendations have been based on:</p> <pre><code>var mX=document.getElementById('&lt;%= tc1.ClientID%&gt;') $find('&lt;%= tc1.ClientID%&gt;').set_activeTabIndex(1); </code></pre> <p>Which both produce the error:</p> <pre><code>The Controls collection cannot be modified because the control contains code blocks (i.e. &lt;% ... %&gt;). </code></pre> <p>I've tried moving the code out of the head tag and into the body tag; same error.</p> <p>I've also tried the alternative <code>&lt;%# tc1.ClientID%&gt;</code>, as in:</p> <pre><code>var mX = document.getElementById('&lt;%# tc1.ClientID %&gt;') mX.ActiveTabIndex="2"; </code></pre> <p>Generates a null error - code above is rendered in the html as: </p> <pre><code>var mX = document.getElementById('') mX.ActiveTabIndex="2"; </code></pre> <p>Can anyone explain in plain(er) language what this means and what the solution is?</p>
[ { "answer_id": 106139, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 0, "selected": false, "text": "<p>It looks and sounds like the code snippets are not themselves offensive, but some <em>other</em> code that was modifying th...
2008/09/19
[ "https://Stackoverflow.com/questions/106095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Using ASP.NET 2.0, I have a web app where I am trying to use JavaScript to make one tab in a tab-container the active tab. The recommendations have been based on: ``` var mX=document.getElementById('<%= tc1.ClientID%>') $find('<%= tc1.ClientID%>').set_activeTabIndex(1); ``` Which both produce the error: ``` The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>). ``` I've tried moving the code out of the head tag and into the body tag; same error. I've also tried the alternative `<%# tc1.ClientID%>`, as in: ``` var mX = document.getElementById('<%# tc1.ClientID %>') mX.ActiveTabIndex="2"; ``` Generates a null error - code above is rendered in the html as: ``` var mX = document.getElementById('') mX.ActiveTabIndex="2"; ``` Can anyone explain in plain(er) language what this means and what the solution is?
I've actually run into that before. **Here's an explanation: <http://west-wind.com/WebLog/posts/6148.aspx>** For example, if your markup looks like: ``` <asp:Panel id="whatever" runat="server"> <script type="text/javascript"> var mX=document.getElementById('<%= tc1.ClientID%>'); //and so on... </script> </asp:Panel> ``` And if you try to programatically add a control to that Panel it'll fail with the error you're getting. One solution is to put your Javascript somewhere else in the page. Another way (although a hack) is this: ``` <asp:Panel id="whatever" runat="server"> <asp:PlaceHolder id="dontCare" runat="server"> <script type="text/javascript"> var mX=document.getElementById('<%= tc1.ClientID%>'); //and so on... </script> </asp:PlaceHolder> </asp:Panel> ``` Now the <%= ... %> part is inside the PlaceHolder, not directly inside the Panel. Adding controls in your C# or VB code to the Panel should now work (although adding controls to the PlaceHolder would fail.) **EDIT:** Yeah, I tried using <%# ... %> instead too, but that's only for inside a DataBound control. For example, that would work if it was in the middle of a DataGrid and I called it's DataBind() method this PostBack.
106,117
<p>Please bear with me, I'm just learning C++. </p> <p>I'm trying to write my header file (for class) and I'm running into an odd error.</p> <pre><code>cards.h:21: error: expected unqualified-id before ')' token cards.h:22: error: expected `)' before "str" cards.h:23: error: expected `)' before "r" </code></pre> <p>What does "expected unqualified-id before ')' token" mean? And what am I doing wrong? </p> <p>Edit: Sorry, I didn't post the entire code.</p> <pre><code>/* Card header file [Author] */ // NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/ #define Card #define Hand #define AppError #include &lt;string&gt; using namespace std; // TODO: Docs here class Card { // line 17 public: enum Suit {Club, Diamond, Spade, Heart}; enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}; Card(); // line 22 Card(string str); Card(Rank r, Suit s); </code></pre> <p>Edit: I'm just trying to compile the header file by itself using "g++ file.h". </p> <p>Edit: Closed question. My code is working now. Thanks everyone! Edit: Reopened question after reading <a href="https://stackoverflow.com/questions/34456/etiquette-closing-your-posts">Etiquette: Closing your posts</a></p>
[ { "answer_id": 106126, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 0, "selected": false, "text": "<p>Remove the <strong>#define Card</strong>.</p>\n" }, { "answer_id": 106127, "author": "John Millikin", ...
2008/09/19
[ "https://Stackoverflow.com/questions/106117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16204/" ]
Please bear with me, I'm just learning C++. I'm trying to write my header file (for class) and I'm running into an odd error. ``` cards.h:21: error: expected unqualified-id before ')' token cards.h:22: error: expected `)' before "str" cards.h:23: error: expected `)' before "r" ``` What does "expected unqualified-id before ')' token" mean? And what am I doing wrong? Edit: Sorry, I didn't post the entire code. ``` /* Card header file [Author] */ // NOTE: Lanugage Docs here http://www.cplusplus.com/doc/tutorial/ #define Card #define Hand #define AppError #include <string> using namespace std; // TODO: Docs here class Card { // line 17 public: enum Suit {Club, Diamond, Spade, Heart}; enum Rank {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace}; Card(); // line 22 Card(string str); Card(Rank r, Suit s); ``` Edit: I'm just trying to compile the header file by itself using "g++ file.h". Edit: Closed question. My code is working now. Thanks everyone! Edit: Reopened question after reading [Etiquette: Closing your posts](https://stackoverflow.com/questions/34456/etiquette-closing-your-posts)
Your issue is your `#define`. You did `#define Card`, so now everywhere `Card` is seen as a token, it will be replaced. Usually a `#define Token` with no additional token, as in `#define Token Replace` will use the value `1`. Remove the `#define Card`, it's making line 22 read: `1();` or `();`, which is causing the complaint.
106,137
<p>When you want to add whitespace between HTML elements (using CSS), to which element do you attach it?</p> <p>I'm regularly in situations along these lines:</p> <pre><code>&lt;body&gt; &lt;h1&gt;This is the heading&lt;/h1&gt; &lt;p&gt;This is a paragraph&lt;/p&gt; &lt;h1&gt;Here's another heading&lt;/h1&gt; &lt;div&gt;This is a footer&lt;/div&gt; &lt;/body&gt; </code></pre> <p>Now, say I wanted 1em of space between each of these elements, but none above the first h1 or below the last div. To which elements would I attach it?</p> <p>Obviously, there's no real <strong>technical</strong> difference between this:</p> <pre><code>h1, p { margin-bottom: 1em; } </code></pre> <p>...and this...</p> <pre><code>div { margin-top: 1em; } p { margin-top: 1em; margin-bottom: 1em } </code></pre> <p>What I'm interested is secondary factors: </p> <ol> <li>Consistency</li> <li>Applicability to all situations</li> <li>Ease / Simplicity</li> <li>Ease of making changes</li> </ol> <p>For example: in this particular scenario, I'd say that the first solution is better than the second, as it's simpler; you're only attaching a margin-bottom to two elements in a single property definition. However, I'm looking for a more general-purpose solution. Every time I do CSS work, I get the feeling that there's a good rule of thumb to apply... but I'm not sure what it is. Does anyone have a good argument?</p>
[ { "answer_id": 106153, "author": "Pavling", "author_id": 18197, "author_profile": "https://Stackoverflow.com/users/18197", "pm_score": 4, "selected": true, "text": "<p>I tend to use a bottom margin on elements when I want them to have space before the next element, and then to use a \".l...
2008/09/19
[ "https://Stackoverflow.com/questions/106137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3488/" ]
When you want to add whitespace between HTML elements (using CSS), to which element do you attach it? I'm regularly in situations along these lines: ``` <body> <h1>This is the heading</h1> <p>This is a paragraph</p> <h1>Here's another heading</h1> <div>This is a footer</div> </body> ``` Now, say I wanted 1em of space between each of these elements, but none above the first h1 or below the last div. To which elements would I attach it? Obviously, there's no real **technical** difference between this: ``` h1, p { margin-bottom: 1em; } ``` ...and this... ``` div { margin-top: 1em; } p { margin-top: 1em; margin-bottom: 1em } ``` What I'm interested is secondary factors: 1. Consistency 2. Applicability to all situations 3. Ease / Simplicity 4. Ease of making changes For example: in this particular scenario, I'd say that the first solution is better than the second, as it's simpler; you're only attaching a margin-bottom to two elements in a single property definition. However, I'm looking for a more general-purpose solution. Every time I do CSS work, I get the feeling that there's a good rule of thumb to apply... but I'm not sure what it is. Does anyone have a good argument?
I tend to use a bottom margin on elements when I want them to have space before the next element, and then to use a ".last" class in the css to remove the margin from the last element. ``` <body> <h1>This is the heading</h1> <p>This is a paragraph</p> <h1>Here's another heading</h1> <div class="last">This is a footer</div> </body> ``` ```css div { margin-bottom: 1em; } p { margin-bottom: 1em; } h1 { margin-bottom: 1em; } .last {margin-bottom: 0; } ``` In your example though, this probably isn't *that* applicable, as a footer div would most likely have it's own class and specific styling. Still the ".last" approach I used works for me when I have several identical elements one after the other (paragraphs and what-not). Of course, I cherry-picked the technique from the "Elements" CSS framework.
106,175
<p><a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="nofollow noreferrer">VB.NET</a> has a very handy "with" statement, but it also lets you use it on an unnamed variable, like this:</p> <pre><code>With New FancyClass() .Level = "SuperSpiffy" .Style = Slimming .Execute() End With </code></pre> <p>Is there a way to get at the "hidden" instance, so I can view its properties in the Immediate window? I doubt I'll get it in the watch windows, so immediate is fine.</p> <p>If you try to access the instance the same way (say, when <code>.Execute()</code> throws an exception) from the Immediate window, you get an error:</p> <pre><code>? .Style 'With' contexts and statements are not valid in debug windows. </code></pre> <p>Is there any trick that can be used to get this, or do I have to convert the code to another style? If <code>With</code> functioned more like a <code>Using</code> statement, (e.g. "With v = New FancyClass()") this wouldn't pose a problem.</p> <p>I know how <code>With</code> is working, what alternatives exist, what the compiler does, etc. I just want to know if this is possible.</p>
[ { "answer_id": 106284, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "<p>What's wrong with defining a variable on one line and using it in a with-statement on the next? I realise it keeps the vari...
2008/09/19
[ "https://Stackoverflow.com/questions/106175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15127/" ]
[VB.NET](http://en.wikipedia.org/wiki/Visual_Basic_.NET) has a very handy "with" statement, but it also lets you use it on an unnamed variable, like this: ``` With New FancyClass() .Level = "SuperSpiffy" .Style = Slimming .Execute() End With ``` Is there a way to get at the "hidden" instance, so I can view its properties in the Immediate window? I doubt I'll get it in the watch windows, so immediate is fine. If you try to access the instance the same way (say, when `.Execute()` throws an exception) from the Immediate window, you get an error: ``` ? .Style 'With' contexts and statements are not valid in debug windows. ``` Is there any trick that can be used to get this, or do I have to convert the code to another style? If `With` functioned more like a `Using` statement, (e.g. "With v = New FancyClass()") this wouldn't pose a problem. I know how `With` is working, what alternatives exist, what the compiler does, etc. I just want to know if this is possible.
As answered, the simple answer is "no". But isn't another way to do it: instead of declaring and then cleaning up the variable is to use the "Using". ``` Using fc as new FancyClass() With fc .Level = "SuperSpiffy" .Style = Slimming .Execute() End With End Using ``` Then you can use fc in the immediate window and don't have to remember to write a ``` fc=nothing ``` line. Just some more thoughts on it ;)
106,179
<p>Does anyone have a regular expression handy that will match any legal DNS hostname or IP address?</p> <p>It's easy to write one that works 95% of the time, but I'm hoping to get something that's well tested to exactly match the latest RFC specs for DNS hostnames.</p>
[ { "answer_id": 106223, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 10, "selected": true, "text": "<p>You can use the following regular expressions separately or by combining them in a joint OR expression.</p>\n<pre>...
2008/09/19
[ "https://Stackoverflow.com/questions/106179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10452/" ]
Does anyone have a regular expression handy that will match any legal DNS hostname or IP address? It's easy to write one that works 95% of the time, but I'm hoping to get something that's well tested to exactly match the latest RFC specs for DNS hostnames.
You can use the following regular expressions separately or by combining them in a joint OR expression. ``` ValidIpAddressRegex = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$"; ValidHostnameRegex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$"; ``` **ValidIpAddressRegex** matches valid IP addresses and **ValidHostnameRegex** valid host names. Depending on the language you use \ could have to be escaped with \. --- **ValidHostnameRegex** is valid as per [RFC 1123](https://www.rfc-editor.org/rfc/rfc1123). Originally, [RFC 952](https://www.rfc-editor.org/rfc/rfc952) specified that hostname segments could not start with a digit. <http://en.wikipedia.org/wiki/Hostname> > > The original specification of > hostnames in [RFC > 952](https://www.rfc-editor.org/rfc/rfc952), > mandated that labels could not start > with a digit or with a hyphen, and > must not end with a hyphen. However, a > subsequent specification ([RFC > 1123](https://www.rfc-editor.org/rfc/rfc1123)) > permitted hostname labels to start > with digits. > > > ``` Valid952HostnameRegex = "^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$"; ```
106,201
<p>In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here. </p> <p><strong>Problem</strong></p> <p>I have:</p> <p>An application that has to be installed on on Redhat or SuSE enterprise. </p> <p>It has huge system requirements and requires OpenGL.</p> <p>It is part of a suite of tools that need to operate together on one machine.</p> <p>This application is used for a time intensive task in terms of man hours.</p> <p>I don't want to sit in the server room working on this application.</p> <p>So, the question came up... how do I run this application from a remote windows machine?</p> <p>I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme.</p>
[ { "answer_id": 106218, "author": "scubabbl", "author_id": 9450, "author_profile": "https://Stackoverflow.com/users/9450", "pm_score": 5, "selected": true, "text": "<p><strong>Solution</strong></p>\n\n<p>I installed two pieces of software:</p>\n\n<p><a href=\"http://www.chiark.greenend.or...
2008/09/19
[ "https://Stackoverflow.com/questions/106201", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
In the spirit of being helpful, this is a problem I had and solved, so I will answer the question here. **Problem** I have: An application that has to be installed on on Redhat or SuSE enterprise. It has huge system requirements and requires OpenGL. It is part of a suite of tools that need to operate together on one machine. This application is used for a time intensive task in terms of man hours. I don't want to sit in the server room working on this application. So, the question came up... how do I run this application from a remote windows machine? I'll outline my solution. Feel free to comment on alternatives. This solution should work for simpler environments as well. My case is somewhat extreme.
**Solution** I installed two pieces of software: [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/) [XMing-mesa](http://www.straightrunning.com/XmingNotes/) The mesa part is important. **PuTTY configuration** ``` Connection->Seconds Between Keepalives: 30 Connection->Enable TCP Keepalives: Yes Connection->SSH->X11->Enable X11 forwarding: Yes Connection->SSH->X11->X display location: localhost:0:0 ``` **Lauching** Run *Xming* which will put simply start a process and put an icon in your system tray. Launch putty, pointing to your linux box, with the above configuration. Run program Hopefully, **Success!**
106,206
<p>I'm writing an import utility that is using phone numbers as a unique key within the import.</p> <p>I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is <strong>slow</strong> and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index.</p> <p>I tried using the script from this post:<br> <a href="https://stackoverflow.com/questions/52315/t-sql-trim-nbsp-and-other-non-alphanumeric-characters">T-SQL trim &amp;nbsp (and other non-alphanumeric characters)</a></p> <p>But that didn't speed it up any.</p> <p>Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared.</p> <p>Whatever is done needs to perform <strong>fast</strong>.</p> <p><strong>Update</strong><br> Given what people responded with, I think I'm going to have to clean the fields before I run the import utility. </p> <p>To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records). </p> <p>Could comparing BIGINT to BIGINT be slowing things down?</p> <p>I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.</p>
[ { "answer_id": 106217, "author": "Dan Williams", "author_id": 4230, "author_profile": "https://Stackoverflow.com/users/4230", "pm_score": 1, "selected": false, "text": "<p>can you remove them in a nightly process, storing them in a separate field, then do an update on changed records rig...
2008/09/19
[ "https://Stackoverflow.com/questions/106206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I'm writing an import utility that is using phone numbers as a unique key within the import. I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is **slow** and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index. I tried using the script from this post: [T-SQL trim &nbsp (and other non-alphanumeric characters)](https://stackoverflow.com/questions/52315/t-sql-trim-nbsp-and-other-non-alphanumeric-characters) But that didn't speed it up any. Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared. Whatever is done needs to perform **fast**. **Update** Given what people responded with, I think I'm going to have to clean the fields before I run the import utility. To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records). Could comparing BIGINT to BIGINT be slowing things down? I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.
I may misunderstand, but you've got two sets of data to remove the strings from one for current data in the database and then a new set whenever you import. For updating the existing records, I would just use SQL, that only has to happen once. However, SQL isn't optimized for this sort of operation, since you said you are writing an import utility, I would do those updates in the context of the import utility itself, not in SQL. This would be much better performance wise. What are you writing the utility in? Also, I may be completely misunderstanding the process, so I apologize if off-base. **Edit:** For the initial update, if you are using SQL Server 2005, you could try a CLR function. Here's a quick one using regex. Not sure how the performance would compare, I've never used this myself except for a quick test right now. ``` using System; using System.Data; using System.Text.RegularExpressions; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static SqlString StripNonNumeric(SqlString input) { Regex regEx = new Regex(@"\D"); return regEx.Replace(input.Value, ""); } }; ``` After this is deployed, to update you could just use: ``` UPDATE table SET phoneNumber = dbo.StripNonNumeric(phoneNumber) ```
106,234
<p>lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data.</p> <p>What are some of the most common and useful ways of using lsof, and which command-line switches are used for that? </p>
[ { "answer_id": 106249, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "<p><code>lsof -i</code> will provide a list of open network sockets. The <code>-n</code> option will prevent DNS looku...
2008/09/19
[ "https://Stackoverflow.com/questions/106234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ]
lsof is an increadibly powerful command-line utility for unix systems. It lists open files, displaying information about them. And since most everything is a file on unix systems, lsof can give sysadmins a ton of useful diagnostic data. What are some of the most common and useful ways of using lsof, and which command-line switches are used for that?
To show all networking related to a given `port`: ``` lsof -iTCP -i :port lsof -i :22 ``` To show connections to a specific host, use `@host` ``` lsof -i@192.168.1.5 ``` Show connections based on the host and the port using `@host:port` lsof -i@192.168.1.5:22 `grep`ping for `LISTEN` shows what ports your system is waiting for connections on: ``` lsof -i| grep LISTEN ``` Show what a given user has open using `-u`: ``` lsof -u daniel ``` See what files and network connections a command is using with `-c` ``` lsof -c syslog-ng ``` The `-p` switch lets you see what a given process ID has open, which is good for learning more about unknown processes: ``` lsof -p 10075 ``` The `-t` option returns just a `PID` ``` lsof -t -c Mail ``` Using the `-t` and `-c` options together you can `HUP` processes ``` kill -HUP $(lsof -t -c sshd) ``` You can also use the `-t` with `-u` to kill everything a user has open ``` kill -9 $(lsof -t -u daniel) ```
106,251
<p>In my model I have:</p> <pre><code>validate :my_custom_validation def my_custom_validation errors.add_to_base("error message") if condition.exists? end </code></pre> <p>I would like to add some parameters to mycustomer vaildation like so:</p> <pre><code>validate :my_custom_validation, :parameter1 =&gt; x, :parameter2 =&gt; y </code></pre> <p>How do I write the mycustomvalidation function to account for parameters? </p>
[ { "answer_id": 106267, "author": "Bill Turner", "author_id": 17773, "author_profile": "https://Stackoverflow.com/users/17773", "pm_score": 1, "selected": false, "text": "<p>You can just do something like this:</p>\n\n<pre><code>def validate\n errors.add('That particular field', 'can not...
2008/09/19
[ "https://Stackoverflow.com/questions/106251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1396/" ]
In my model I have: ``` validate :my_custom_validation def my_custom_validation errors.add_to_base("error message") if condition.exists? end ``` I would like to add some parameters to mycustomer vaildation like so: ``` validate :my_custom_validation, :parameter1 => x, :parameter2 => y ``` How do I write the mycustomvalidation function to account for parameters?
Validators usualy have an array parameter indicating, first, the fields to validate and lastly (if it exists) a hash with the options. In your example: ``` :my_custom_validation, parameter1: x, parameter2: y ``` :my\_custom\_validation would be a field name, while parameter1: x, parameter2: y would be a hash: ``` { parameter1: x, parameter2: y} ``` Therefore, you'd do something like: ``` def my_custom_validation(*attr) options = attr.pop if attr.last.is_a? Hash # do something with options errors.add_to_base("error message") if condition.exists? end ```
106,275
<p>If I have a table field named 'description', what would be the SQL (using MS SQL) to get a list of records of all distinct words used in this field.</p> <p>For example:</p> <p>If the table contains the following for the 'description' field:</p> <pre><code>Record1 "The dog jumped over the fence." Record2 "The giant tripped on the fence." ... </code></pre> <p>The SQL record output would be:</p> <pre><code>"The","giant","dog","jumped","tripped","on","over","fence" </code></pre>
[ { "answer_id": 106280, "author": "Jeremy", "author_id": 8557, "author_profile": "https://Stackoverflow.com/users/8557", "pm_score": 0, "selected": false, "text": "<p>it'd be a messy stored procedure with a temp table and a SELECT DISTINCT at the end.</p>\n\n<p>if you had the words alread...
2008/09/19
[ "https://Stackoverflow.com/questions/106275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/889/" ]
If I have a table field named 'description', what would be the SQL (using MS SQL) to get a list of records of all distinct words used in this field. For example: If the table contains the following for the 'description' field: ``` Record1 "The dog jumped over the fence." Record2 "The giant tripped on the fence." ... ``` The SQL record output would be: ``` "The","giant","dog","jumped","tripped","on","over","fence" ```
I do not think you can do this with a SELECT. The best chance is to write a user defined function that returns a table with all the words and then do SELECT DISTINCT on it. --- **Disclaimer:** Function **dbo.Split** is from <http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=50648> ``` CREATE TABLE test ( id int identity(1, 1) not null, description varchar(50) not null ) INSERT INTO test VALUES('The dog jumped over the fence') INSERT INTO test VALUES('The giant tripped on the fence') CREATE FUNCTION dbo.Split ( @RowData nvarchar(2000), @SplitOn nvarchar(5) ) RETURNS @RtnValue table ( Id int identity(1,1), Data nvarchar(100) ) AS BEGIN Declare @Cnt int Set @Cnt = 1 While (Charindex(@SplitOn,@RowData)>0) Begin Insert Into @RtnValue (data) Select Data = ltrim(rtrim(Substring(@RowData,1,Charindex(@SplitOn,@RowData)-1))) Set @RowData = Substring(@RowData,Charindex(@SplitOn,@RowData)+1,len(@RowData)) Set @Cnt = @Cnt + 1 End Insert Into @RtnValue (data) Select Data = ltrim(rtrim(@RowData)) Return END CREATE FUNCTION dbo.SplitAll(@SplitOn nvarchar(5)) RETURNS @RtnValue table ( Id int identity(1,1), Data nvarchar(100) ) AS BEGIN DECLARE My_Cursor CURSOR FOR SELECT Description FROM dbo.test DECLARE @description varchar(50) OPEN My_Cursor FETCH NEXT FROM My_Cursor INTO @description WHILE @@FETCH_STATUS = 0 BEGIN INSERT INTO @RtnValue SELECT Data FROM dbo.Split(@description, @SplitOn) FETCH NEXT FROM My_Cursor INTO @description END CLOSE My_Cursor DEALLOCATE My_Cursor RETURN END SELECT DISTINCT Data FROM dbo.SplitAll(N' ') ```
106,298
<p>You may think that this is a coincidence that the topic of my question is similar to the name of the forum but I actually got here by googling the term "stack overflow".</p> <p>I use the OPNET network simulator in which I program using C. I think I am having a problem with big array sizes. It seems that I am hitting some sort of memory allocation limitation. It may have to do with OPNET, Windows, my laptop memory or most likely C language. The problem is caused when I try to use nested arrays with a total number of elements coming to several thousand integers. I think I am exceeding an overall memory allocation limit and I am wondering if there is a way to increase this cap. Here's the exact problem description:</p> <p>I basically have a routing table. Let's call it routing_tbl[n], meaning I am supporting 30 nodes (routers). Now, for each node in this table, I keep info. about many (hundreds) available paths, in an array called paths[p]. Again, for each path in this array, I keep the list of nodes that belong to it in an array called hops[h]. So, I am using at least nph integers worth of memory but this table contains other information as well. In the same function, I am also using another nested array that consumes almost 40,000 integers as well. As soon as I run my simulation, it quits complaining about stack overflow. It works when I reduce the total size of the routing table. What do you think causes the problem and how can it be solved? Much appreciated Ali</p>
[ { "answer_id": 106306, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 3, "selected": false, "text": "<p>It may help if you post some code. Edit the question to include the problem function and the error.</p>\n\n<p>Mea...
2008/09/19
[ "https://Stackoverflow.com/questions/106298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You may think that this is a coincidence that the topic of my question is similar to the name of the forum but I actually got here by googling the term "stack overflow". I use the OPNET network simulator in which I program using C. I think I am having a problem with big array sizes. It seems that I am hitting some sort of memory allocation limitation. It may have to do with OPNET, Windows, my laptop memory or most likely C language. The problem is caused when I try to use nested arrays with a total number of elements coming to several thousand integers. I think I am exceeding an overall memory allocation limit and I am wondering if there is a way to increase this cap. Here's the exact problem description: I basically have a routing table. Let's call it routing\_tbl[n], meaning I am supporting 30 nodes (routers). Now, for each node in this table, I keep info. about many (hundreds) available paths, in an array called paths[p]. Again, for each path in this array, I keep the list of nodes that belong to it in an array called hops[h]. So, I am using at least nph integers worth of memory but this table contains other information as well. In the same function, I am also using another nested array that consumes almost 40,000 integers as well. As soon as I run my simulation, it quits complaining about stack overflow. It works when I reduce the total size of the routing table. What do you think causes the problem and how can it be solved? Much appreciated Ali
It may help if you post some code. Edit the question to include the problem function and the error. Meanwhile, here's a very generic answer: The two principal causes of a stack overflow are 1) a recursive function, or 2) the allocation of a large number of local variables. **Recursion** if your function calls itself, like this: ``` int recurse(int number) { return (recurse(number)); } ``` Since local variables and function arguments are stored on the stack, then it will in fill the stack and cause a stack overflow. **Large local variables** If you try to allocate a large array of local variables then you can overflow the stack in one easy go. A function like this may cause the issue: ``` void hugeStack (void) { unsigned long long reallyBig[100000000][1000000000]; ... } ``` There is quite a detailed answer to this [similar question](https://stackoverflow.com/questions/26158/how-does-a-stack-overflow-occur-and-how-do-you-prevent-it).
106,323
<p>Anyone have a good set of sqlplus configuration directives to help transform a given sql query into nicely tab separated output for pulling into a spreadsheet or further processing?</p>
[ { "answer_id": 106398, "author": "Eddie Awad", "author_id": 17273, "author_profile": "https://Stackoverflow.com/users/17273", "pm_score": -1, "selected": true, "text": "<p>Check out the Oracle documentation:</p>\n\n<ul>\n<li><a href=\"http://68.142.116.68/docs/cd/B19306_01/server.102/b14...
2008/09/19
[ "https://Stackoverflow.com/questions/106323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19387/" ]
Anyone have a good set of sqlplus configuration directives to help transform a given sql query into nicely tab separated output for pulling into a spreadsheet or further processing?
Check out the Oracle documentation: * [Formatting SQLPlus Reports](http://68.142.116.68/docs/cd/B19306_01/server.102/b14357/ch6.htm#i1081008) * [Generating HTML Reports from SQLPlus](http://68.142.116.68/docs/cd/B19306_01/server.102/b14357/ch7.htm#sthref1452) You can generate a tab in Oracle by using the tab's ASCII value 9 and the chr function: ``` select chr(9) from dual; ```
106,324
<p>With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax.</p> <p>Any place where we still have to use delegates and lambda expressions won't work?</p>
[ { "answer_id": 106348, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": false, "text": "<p>lambda is shortcut for anonymous delegate, but you will always be using delegates. the delegate specifies the methods sig...
2008/09/19
[ "https://Stackoverflow.com/questions/106324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19306/" ]
With the advent of new features like lambda expressions (inline code), does it mean we dont have to use delegates or anonymous methods anymore? In almost all the samples I have seen, it is for rewriting using the new syntax. Any place where we still have to use delegates and lambda expressions won't work?
Yes there are places where directly using anonymous delegates and lambda expressions won't work. If a method takes an untyped Delegate then the compiler doesn't know what to resolve the anonymous delegate/lambda expression to and you will get a compiler error. ``` public static void Invoke(Delegate d) { d.DynamicInvoke(); } static void Main(string[] args) { // fails Invoke(() => Console.WriteLine("Test")); // works Invoke(new Action(() => Console.WriteLine("Test"))); Console.ReadKey(); } ``` The failing line of code will get the compiler error "Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type".
106,336
<p>I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds? </p> <p>FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.</p>
[ { "answer_id": 106350, "author": "skiphoppy", "author_id": 18103, "author_profile": "https://Stackoverflow.com/users/18103", "pm_score": 2, "selected": false, "text": "<p>Just call <code>.getClass()</code> on each <code>Object</code> in a loop.</p>\n\n<p>Unfortunately, Java doesn't have ...
2008/09/19
[ "https://Stackoverflow.com/questions/106336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13491/" ]
I have a ArrayList made up of different elements imported from a db, made up of strings, numbers, doubles and ints. Is there a way to use a reflection type technique to find out what each type of data each element holds? FYI: The reason that there is so many types of data is that this is a piece of java code being written to be implemented with different DB's.
In C#: Fixed with recommendation from [Mike](https://stackoverflow.com/users/14359/mike-brown) ``` ArrayList list = ...; // List<object> list = ...; foreach (object o in list) { if (o is int) { HandleInt((int)o); } else if (o is string) { HandleString((string)o); } ... } ``` In Java: ``` ArrayList<Object> list = ...; for (Object o : list) { if (o instanceof Integer)) { handleInt((Integer o).intValue()); } else if (o instanceof String)) { handleString((String)o); } ... } ```
106,367
<p>What is the best way to add <strong>non-ASCII</strong> file names to a <strong>zip file</strong> using <strong>Java</strong>, in such a way that the files can be properly read in both <strong>Windows</strong> and <strong>Linux?</strong></p> <p>Here is one attempt, adapted from <a href="https://truezip.dev.java.net/tutorial-6.html#Example" rel="noreferrer">https://truezip.dev.java.net/tutorial-6.html#Example</a>, which works in Windows Vista but fails in Ubuntu Hardy. In Hardy the file name is shown as abc-ЖДФ.txt in file-roller.</p> <pre><code>import java.io.IOException; import java.io.PrintStream; import de.schlichtherle.io.File; import de.schlichtherle.io.FileOutputStream; public class Main { public static void main(final String[] args) throws IOException { try { PrintStream ps = new PrintStream(new FileOutputStream( "outer.zip/abc-åäö.txt")); try { ps.println("The characters åäö works here though."); } finally { ps.close(); } } finally { File.umount(); } } } </code></pre> <p>Unlike java.util.zip, truezip allows specifying zip file encoding. Here's another sample, this time explicitly specifiying the encoding. Neither IBM437, UTF-8 nor ISO-8859-1 works in Linux. IBM437 works in Windows.</p> <pre><code>import java.io.IOException; import de.schlichtherle.io.FileOutputStream; import de.schlichtherle.util.zip.ZipEntry; import de.schlichtherle.util.zip.ZipOutputStream; public class Main { public static void main(final String[] args) throws IOException { for (String encoding : new String[] { "IBM437", "UTF-8", "ISO-8859-1" }) { ZipOutputStream zipOutput = new ZipOutputStream( new FileOutputStream(encoding + "-example.zip"), encoding); ZipEntry entry = new ZipEntry("abc-åäö.txt"); zipOutput.putNextEntry(entry); zipOutput.closeEntry(); zipOutput.close(); } } } </code></pre>
[ { "answer_id": 106384, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 0, "selected": false, "text": "<p>Did it actually fail or was just a font issue? (e.g. font having different glyphs for those charcodes) I've seen simi...
2008/09/19
[ "https://Stackoverflow.com/questions/106367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19392/" ]
What is the best way to add **non-ASCII** file names to a **zip file** using **Java**, in such a way that the files can be properly read in both **Windows** and **Linux?** Here is one attempt, adapted from <https://truezip.dev.java.net/tutorial-6.html#Example>, which works in Windows Vista but fails in Ubuntu Hardy. In Hardy the file name is shown as abc-ЖДФ.txt in file-roller. ``` import java.io.IOException; import java.io.PrintStream; import de.schlichtherle.io.File; import de.schlichtherle.io.FileOutputStream; public class Main { public static void main(final String[] args) throws IOException { try { PrintStream ps = new PrintStream(new FileOutputStream( "outer.zip/abc-åäö.txt")); try { ps.println("The characters åäö works here though."); } finally { ps.close(); } } finally { File.umount(); } } } ``` Unlike java.util.zip, truezip allows specifying zip file encoding. Here's another sample, this time explicitly specifiying the encoding. Neither IBM437, UTF-8 nor ISO-8859-1 works in Linux. IBM437 works in Windows. ``` import java.io.IOException; import de.schlichtherle.io.FileOutputStream; import de.schlichtherle.util.zip.ZipEntry; import de.schlichtherle.util.zip.ZipOutputStream; public class Main { public static void main(final String[] args) throws IOException { for (String encoding : new String[] { "IBM437", "UTF-8", "ISO-8859-1" }) { ZipOutputStream zipOutput = new ZipOutputStream( new FileOutputStream(encoding + "-example.zip"), encoding); ZipEntry entry = new ZipEntry("abc-åäö.txt"); zipOutput.putNextEntry(entry); zipOutput.closeEntry(); zipOutput.close(); } } } ```
The encoding for the File-Entries in ZIP is originally specified as IBM Code Page 437. Many characters used in other languages are impossible to use that way. The [PKWARE-specification](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) refers to the problem and adds a bit. But that is a later addition (from 2007, thanks to Cheeso for clearing that up, see comments). If that bit is set, the filename-entry have to be encoded in UTF-8. This extension is described in 'APPENDIX D - Language Encoding (EFS)', that is at the end of the linked document. For Java it is a known bug, to get into trouble with non-ASCII-characters. See [bug #4244499](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4244499) and the high number of related bugs. My colleague used as workaround URL-Encoding for the filenames before storing them into the ZIP and decoding after reading them. If you control both, storing and reading, that may be a workaround. EDIT: At the bug someone suggests using the ZipOutputStream from Apache Ant as workaround. This implementation allows the specification of an encoding.
106,383
<p>Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.</p> <p>e.g.</p> <pre><code>public DerivedClass : BaseClass {} </code></pre> <p>Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?</p>
[ { "answer_id": 106392, "author": "Serafina Brocious", "author_id": 4977, "author_profile": "https://Stackoverflow.com/users/4977", "pm_score": 0, "selected": false, "text": "<p>If they're defined public in the original class, you cannot override them to be private in your derived class. ...
2008/09/19
[ "https://Stackoverflow.com/questions/106383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16866/" ]
Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance. e.g. ``` public DerivedClass : BaseClass {} ``` Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is exposed to someone who wants to use my DerivedClass?
**It's not possible, why?** In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place. Instead of using the is-a relationship, you would have to use the has-a relationship. The language designers don't allow this on purpose so that you use inheritance more properly. For example one might accidentally confuse a class Car to derive from a class Engine to get it's functionality. But an Engine is functionality that is used by the car. So you would want to use the has-a relationship. The user of the Car does not want to have access to the interface of the Engine. And the Car itself should not confuse the Engine's methods with it's own. Nor Car's future derivations. So they don't allow it to protect you from bad inheritance hierarchies. **What should you do instead?** Instead you should implement interfaces. This leaves you free to have functionality using the has-a relationship. **Other languages:** In C++ you simply specify a modifier before the base class of private, public or protected. This makes all members of the base that were public to that specified access level. It seems silly to me that you can't do the same in C#. **The restructured code:** ``` interface I { void C(); } class BaseClass { public void A() { MessageBox.Show("A"); } public void B() { MessageBox.Show("B"); } } class Derived : I { public void C() { b.A(); b.B(); } private BaseClass b; } ``` I understand the names of the above classes are a little moot :) **Other suggestions:** Others have suggested to make A() and B() public and throw exceptions. But this doesn't make a friendly class for people to use and it doesn't really make sense.
106,387
<p>I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct binary?</p> <p>This will be for Ubuntu machines.</p>
[ { "answer_id": 106399, "author": "shoover", "author_id": 18356, "author_profile": "https://Stackoverflow.com/users/18356", "pm_score": 7, "selected": true, "text": "<p>Does</p>\n\n<pre><code>uname -a\n</code></pre>\n\n<p>give you anything you can use? I don't have a 64-bit machine to te...
2008/09/19
[ "https://Stackoverflow.com/questions/106387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I am writing a bash script to deal with some installations in an automated way... I have the possibility of getting one such program in 32 or 64 bit binary... is it possible to detect the machine architecture from bash so I can select the correct binary? This will be for Ubuntu machines.
Does ``` uname -a ``` give you anything you can use? I don't have a 64-bit machine to test on. --- **Note from Mike Stone:** This works, though specifically ``` uname -m ``` Will give "x86\_64" for 64 bit, and something else for other 32 bit types (in my 32 bit VM, it's "i686").
106,400
<p>I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary?</p> <p>Thanks!</p>
[ { "answer_id": 106424, "author": "Mariano", "author_id": 2542, "author_profile": "https://Stackoverflow.com/users/2542", "pm_score": 2, "selected": false, "text": "<p>If I understand correctly, you could do:</p>\n\n<pre><code>select * from users order by max(rank) desc limit 0, 49 \nuni...
2008/09/19
[ "https://Stackoverflow.com/questions/106400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13636/" ]
I have a list of ranked users, and would like to select the top 50. I also want to make sure one particular user is in this result set, even if they aren't in the top 50. Is there a sensible way to do this in a single mysql query? Or should I just check the results for the particular user and fetch him separately, if necessary? Thanks!
If I understand correctly, you could do: ``` select * from users order by max(rank) desc limit 0, 49 union select * from users where user = x ``` This way you get 49 top users plus your particular user.
106,401
<p>The built-in <code>PHP</code> extension for <code>SOAP</code> doesn't validate everything in the incoming <code>SOAP</code> request against the <code>XML Schema</code> in the <code>WSDL</code>. It does check for the existence of basic entities, but when you have something complicated like <code>simpleType</code> restrictions the extension pretty much ignores their existence.</p> <p>What is the best way to validate the <code>SOAP</code> request against <code>XML Schema</code> contained in the <code>WSDL</code>?</p>
[ { "answer_id": 108525, "author": "user11087", "author_id": 11087, "author_profile": "https://Stackoverflow.com/users/11087", "pm_score": 2, "selected": false, "text": "<p>Typically one doesn't validate against the WSDL. If the WSDL is designed properly there should be an underlying xml ...
2008/09/19
[ "https://Stackoverflow.com/questions/106401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5726/" ]
The built-in `PHP` extension for `SOAP` doesn't validate everything in the incoming `SOAP` request against the `XML Schema` in the `WSDL`. It does check for the existence of basic entities, but when you have something complicated like `simpleType` restrictions the extension pretty much ignores their existence. What is the best way to validate the `SOAP` request against `XML Schema` contained in the `WSDL`?
Been digging around on this matter a view hours. Neither the native PHP SoapServer nore the NuSOAP Library does any Validation. PHP SoapServer simply makes a type cast. For Example if you define ``` <xsd:element name="SomeParameter" type="xsd:boolean" /> ``` and submit ``` <get:SomeParameter>dfgdfg</get:SomeParameter> ``` you'll get the php Type boolean (true) NuSOAP simply casts everthing to string although it recognizes simple types: from the nuSOAP debug log: ``` nusoap_xmlschema: processing typed element SomeParameter of type http://www.w3.org/2001/XMLSchema:boolean ``` So the best way is joelhardi solution to validate yourself or use some xml Parser like XERCES
106,425
<p>How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.</p>
[ { "answer_id": 106438, "author": "Miguel Ventura", "author_id": 19401, "author_profile": "https://Stackoverflow.com/users/19401", "pm_score": 8, "selected": true, "text": "<h3>2015 Update</h3>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_S...
2008/09/19
[ "https://Stackoverflow.com/questions/106425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/401774/" ]
How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.
### 2015 Update [Content security policy](https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy) will prevent this from working in many sites now. For example, the code below won't work on Facebook. ### 2008 answer Use a bookmarklet that creates a script tag which includes your external JS. As a sample: ``` javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})(); ```
106,437
<p>I have a stateless bean something like:</p> <pre><code>@Stateless public class MyStatelessBean implements MyStatelessLocal, MyStatelessRemote { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.SUPPORTED) public void processObjects(List&lt;Object&gt; objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.process(obj); } } @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); } } </code></pre> <p>The typically usage then is the client would call processObjects(...), which doesn't actually interact with the entity manager. It does what it needs to do and calls process(...) individually for each object to process. The duration of process(...) is relatively short, but processObjects(...) could take a very long time to run through everything. Therefore I don't want it to maintain an open transaction. I <em>do</em> need the individual process(...) operations to operate within their own transaction. This should be a new transaction for every call. Lastly I'd like to keep the option open for the client to call process(...) directly.</p> <p>I've tried a number of different transaction types: never, not supported, supported (on processObjects) and required, requires new (on process) but I get TransactionRequiredException every time merge() is called.</p> <p>I've been able to make it work by splitting up the methods into two different beans:</p> <pre><code>@Stateless @TransationAttribute(TransactionAttributeType.NOT_SUPPORTED) public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 { @EJB private MyStatelessBean2 myBean2; public void processObjects(List&lt;Object&gt; objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.myBean2.process(obj); } } } @Stateless public class MyStatelessBean2 implements MyStatelessLocal2, MyStatelessRemote2 { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); } } </code></pre> <p>but I'm still curious if it's possible to accomplish this in one class. It looks to me like the transaction manager only operates at the bean level, even when individual methods are given more specific annotations. So if I mark one method in a way to prevent the transaction from starting calling other methods within that same instance will also not create a transaction, no matter how they're marked?</p> <p>I'm using JBoss Application Server 4.2.1.GA, but non-specific answers are welcome / preferred.</p>
[ { "answer_id": 106483, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 0, "selected": false, "text": "<p>I think has to do with the <em>@TransationAttribute(TransactionAttributeType.Never)</em> on method <strong>process...
2008/09/19
[ "https://Stackoverflow.com/questions/106437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1458/" ]
I have a stateless bean something like: ``` @Stateless public class MyStatelessBean implements MyStatelessLocal, MyStatelessRemote { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.SUPPORTED) public void processObjects(List<Object> objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.process(obj); } } @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); } } ``` The typically usage then is the client would call processObjects(...), which doesn't actually interact with the entity manager. It does what it needs to do and calls process(...) individually for each object to process. The duration of process(...) is relatively short, but processObjects(...) could take a very long time to run through everything. Therefore I don't want it to maintain an open transaction. I *do* need the individual process(...) operations to operate within their own transaction. This should be a new transaction for every call. Lastly I'd like to keep the option open for the client to call process(...) directly. I've tried a number of different transaction types: never, not supported, supported (on processObjects) and required, requires new (on process) but I get TransactionRequiredException every time merge() is called. I've been able to make it work by splitting up the methods into two different beans: ``` @Stateless @TransationAttribute(TransactionAttributeType.NOT_SUPPORTED) public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 { @EJB private MyStatelessBean2 myBean2; public void processObjects(List<Object> objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.myBean2.process(obj); } } } @Stateless public class MyStatelessBean2 implements MyStatelessLocal2, MyStatelessRemote2 { @PersistenceContext(unitName="myPC") private EntityManager mgr; @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); } } ``` but I'm still curious if it's possible to accomplish this in one class. It looks to me like the transaction manager only operates at the bean level, even when individual methods are given more specific annotations. So if I mark one method in a way to prevent the transaction from starting calling other methods within that same instance will also not create a transaction, no matter how they're marked? I'm using JBoss Application Server 4.2.1.GA, but non-specific answers are welcome / preferred.
Another way to do it is actually having both methods on the same bean - and having an `@EJB` reference to itself! Something like that: ``` // supposing processObjects defined on MyStatelessRemote1 and process defined on MyStatelessLocal1 @Stateless @TransationAttribute(TransactionAttributeType.NOT_SUPPORTED) public class MyStatelessBean1 implements MyStatelessLocal1, MyStatelessRemote1 { @EJB private MyStatelessLocal1 myBean2; public void processObjects(List<Object> objs) { // this method just processes the data; no need for a transaction for(Object obj : objs) { this.myBean2.process(obj); } } @TransationAttribute(TransactionAttributeType.REQUIRES_NEW) public void process(Object obj) { // do some work with obj that must be in the scope of a transaction this.mgr.merge(obj); // ... this.mgr.merge(obj); // ... this.mgr.flush(); } } ``` This way you actually 'force' the `process()` method to be accessed via the ejb stack of proxies, therefore taking the `@TransactionAttribute` in effect - and still keeping only one class. Phew!
106,453
<p>I've been working on an embedded C/C++ project recently using the shell in Tornado 2 as a way of debugging what's going on in our kit. The only problem with this approach is that it's a complicated system and as a result, has a fair bit of output. Tornado 'helpfully' scrolls the window every time some new information arrives which means that if you spot an error, it disappears out of site too quickly to see. Each time you scroll up to look, the system adds more information, so the only way to view it is to disconnect the hardware.</p> <p>I'd love to know if anyone has a way of redirecting the output from Tornado?</p> <p>I was hoping there might be a way to log it all from a small python app so that I can apply filters to the incoming information. I've tried connecting into the Tornado process, but the window with the information isn't a standard CEditCtrl so extracting the text that way was a dead end.</p> <p>Any ideas anyone?</p> <p><strong>[Edit]</strong> I should have mentioned that we're only running Tornado 2.1.0 and upgrading to a more recent version is beyond my control.</p> <p><strong>[Edit2]</strong> The window in question in Tornado is an 'AfxFrameOrView42' according to WinID.</p>
[ { "answer_id": 106589, "author": "Benoit", "author_id": 10703, "author_profile": "https://Stackoverflow.com/users/10703", "pm_score": 1, "selected": false, "text": "<p>I am making the assumption that you are using the host shell to perform this.</p>\n\n<p>If you are running a test by lau...
2008/09/19
[ "https://Stackoverflow.com/questions/106453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ]
I've been working on an embedded C/C++ project recently using the shell in Tornado 2 as a way of debugging what's going on in our kit. The only problem with this approach is that it's a complicated system and as a result, has a fair bit of output. Tornado 'helpfully' scrolls the window every time some new information arrives which means that if you spot an error, it disappears out of site too quickly to see. Each time you scroll up to look, the system adds more information, so the only way to view it is to disconnect the hardware. I'd love to know if anyone has a way of redirecting the output from Tornado? I was hoping there might be a way to log it all from a small python app so that I can apply filters to the incoming information. I've tried connecting into the Tornado process, but the window with the information isn't a standard CEditCtrl so extracting the text that way was a dead end. Any ideas anyone? **[Edit]** I should have mentioned that we're only running Tornado 2.1.0 and upgrading to a more recent version is beyond my control. **[Edit2]** The window in question in Tornado is an 'AfxFrameOrView42' according to WinID.
here is another potential way: ``` -> saveFd = open("myfile.txt",0x102, 0777 ) -> oldFd = ioGlobalStdGet(1) -> ioGlobalStdSet(1, saveFd) -> runmytest() ... -> ioGlobalStdSet(1, oldFd) ``` this will redirect **all** stdout activity to the file you opened. You might have to play around with the file name of the open to make it write on the host (e.g. use "host:/myfile.txt" or something like this)
106,476
<p>I have a setup executable that I need to install. When I run it, it launches a msi to do the actual install and then dies immediately. The side effect of this is it will return control back to any console you call it from before the install finishes. Depending on what machine I run it on, it can take from three to ten minutes so having the calling script sleep is undesirable. I would launch the msi directly but it complains about missing components. </p> <p>I have a WSH script that uses WMI to start a process and then watch until it's pid is no longer running. Is there some way to determine the pid of the MSI the initial executable is executing, and then watch for that pid to end using WMI? Is the launching process information even associated with a process?</p>
[ { "answer_id": 106601, "author": "Jim Olsen", "author_id": 15603, "author_profile": "https://Stackoverflow.com/users/15603", "pm_score": 2, "selected": true, "text": "<p>Would doing a WMI lookup of processes that have the initial setup as the parent process do the trick? For example, if...
2008/09/19
[ "https://Stackoverflow.com/questions/106476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a setup executable that I need to install. When I run it, it launches a msi to do the actual install and then dies immediately. The side effect of this is it will return control back to any console you call it from before the install finishes. Depending on what machine I run it on, it can take from three to ten minutes so having the calling script sleep is undesirable. I would launch the msi directly but it complains about missing components. I have a WSH script that uses WMI to start a process and then watch until it's pid is no longer running. Is there some way to determine the pid of the MSI the initial executable is executing, and then watch for that pid to end using WMI? Is the launching process information even associated with a process?
Would doing a WMI lookup of processes that have the initial setup as the parent process do the trick? For example, if I launch an MSI from a command prompt with process id 4000, I can execute the following command line to find information about msiexec process: ``` c:\>wmic PROCESS WHERE ParentProcessId=4000 GET CommandLine, ProcessId CommandLine ProcessId "C:\Windows\System32\msiexec.exe" /i "C:\blahblahblah.msi" 2752 ``` That may be one way to find the information you need. Here is a demo of looking up that information in vbs: ``` Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2") Set colProcesses = objWMIService.ExecQuery("select * from Win32_Process where ParentProcessId = 4000") For Each objProcess in colProcesses Wscript.Echo "Process ID: " & objProcess.ProcessId Next ``` I hope this helps.
106,481
<p>I have this line in a javascript block in a page:</p> <pre><code>res = foo('&lt;%= @ruby_var %&gt;'); </code></pre> <p>What is the best way to handle the case where <code>@ruby_var</code> has a single-quote in it? Else it will break the JavaScript code.</p>
[ { "answer_id": 106518, "author": "Max Cantor", "author_id": 16034, "author_profile": "https://Stackoverflow.com/users/16034", "pm_score": 2, "selected": false, "text": "<pre><code>@ruby_var.gsub(/[']/, '\\\\\\\\\\'')\n</code></pre>\n\n<p>That will escape the single quote with an apostrop...
2008/09/20
[ "https://Stackoverflow.com/questions/106481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19409/" ]
I have this line in a javascript block in a page: ``` res = foo('<%= @ruby_var %>'); ``` What is the best way to handle the case where `@ruby_var` has a single-quote in it? Else it will break the JavaScript code.
I think I'd use a ruby [JSON](http://json.org) library on @ruby\_var to get proper js syntax for the string and get rid of the '', fex.: ``` res = foo(<%= @ruby_var.to_json %>) ``` (after require "json"'ing, not entirely sure how to do that in the page or if the above syntax is correct as I havn't used that templating language) (on the other hand, if JSON ever changed to be incompatible with js that'd break, but since a decent amount of code uses eval() to eval json I doubt that'd happen anytime soon)
106,508
<p>What is a smart pointer and when should I use one?</p>
[ { "answer_id": 106515, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Smart_pointer\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Smart_point...
2008/09/20
[ "https://Stackoverflow.com/questions/106508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19410/" ]
What is a smart pointer and when should I use one?
**UPDATE** This answer is rather old, and so describes what was 'good' at the time, which was smart pointers provided by the Boost library. Since C++11, the standard library has provided sufficient smart pointers types, and so you should favour the use of [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr), [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr) and [`std::weak_ptr`](http://en.cppreference.com/w/cpp/memory/weak_ptr). There was also [`std::auto_ptr`](http://en.cppreference.com/w/cpp/memory/auto_ptr). It was very much like a scoped pointer, except that it also had the "special" dangerous ability to be copied — which also unexpectedly transfers ownership. **It was deprecated in C++11 and removed in C++17**, so you shouldn't use it. ``` std::auto_ptr<MyObject> p1 (new MyObject()); std::auto_ptr<MyObject> p2 = p1; // Copy and transfer ownership. // p1 gets set to empty! p2->DoSomething(); // Works. p1->DoSomething(); // Oh oh. Hopefully raises some NULL pointer exception. ``` --- **OLD ANSWER** A smart pointer is a class that wraps a 'raw' (or 'bare') C++ pointer, to manage the lifetime of the object being pointed to. There is no single smart pointer type, but all of them try to abstract a raw pointer in a practical way. Smart pointers should be preferred over raw pointers. If you feel you need to use pointers (first consider if you *really* do), you would normally want to use a smart pointer as this can alleviate many of the problems with raw pointers, mainly forgetting to delete the object and leaking memory. With raw pointers, the programmer has to explicitly destroy the object when it is no longer useful. ``` // Need to create the object to achieve some goal MyObject* ptr = new MyObject(); ptr->DoSomething(); // Use the object in some way delete ptr; // Destroy the object. Done with it. // Wait, what if DoSomething() raises an exception...? ``` A smart pointer by comparison defines a policy as to when the object is destroyed. You still have to create the object, but you no longer have to worry about destroying it. ``` SomeSmartPtr<MyObject> ptr(new MyObject()); ptr->DoSomething(); // Use the object in some way. // Destruction of the object happens, depending // on the policy the smart pointer class uses. // Destruction would happen even if DoSomething() // raises an exception ``` The simplest policy in use involves the scope of the smart pointer wrapper object, such as implemented by [`boost::scoped_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/scoped_ptr.htm) or [`std::unique_ptr`](http://en.cppreference.com/w/cpp/memory/unique_ptr). ``` void f() { { std::unique_ptr<MyObject> ptr(new MyObject()); ptr->DoSomethingUseful(); } // ptr goes out of scope -- // the MyObject is automatically destroyed. // ptr->Oops(); // Compile error: "ptr" not defined // since it is no longer in scope. } ``` Note that `std::unique_ptr` instances cannot be copied. This prevents the pointer from being deleted multiple times (incorrectly). You can, however, pass references to it around to other functions you call. `std::unique_ptr`s are useful when you want to tie the lifetime of the object to a particular block of code, or if you embedded it as member data inside another object, the lifetime of that other object. The object exists until the containing block of code is exited, or until the containing object is itself destroyed. A more complex smart pointer policy involves reference counting the pointer. This does allow the pointer to be copied. When the last "reference" to the object is destroyed, the object is deleted. This policy is implemented by [`boost::shared_ptr`](http://www.boost.org/doc/libs/release/libs/smart_ptr/shared_ptr.htm) and [`std::shared_ptr`](http://en.cppreference.com/w/cpp/memory/shared_ptr). ``` void f() { typedef std::shared_ptr<MyObject> MyObjectPtr; // nice short alias MyObjectPtr p1; // Empty { MyObjectPtr p2(new MyObject()); // There is now one "reference" to the created object p1 = p2; // Copy the pointer. // There are now two references to the object. } // p2 is destroyed, leaving one reference to the object. } // p1 is destroyed, leaving a reference count of zero. // The object is deleted. ``` Reference counted pointers are very useful when the lifetime of your object is much more complicated, and is not tied directly to a particular section of code or to another object. There is one drawback to reference counted pointers — the possibility of creating a dangling reference: ``` // Create the smart pointer on the heap MyObjectPtr* pp = new MyObjectPtr(new MyObject()) // Hmm, we forgot to destroy the smart pointer, // because of that, the object is never destroyed! ``` Another possibility is creating circular references: ``` struct Owner { std::shared_ptr<Owner> other; }; std::shared_ptr<Owner> p1 (new Owner()); std::shared_ptr<Owner> p2 (new Owner()); p1->other = p2; // p1 references p2 p2->other = p1; // p2 references p1 // Oops, the reference count of of p1 and p2 never goes to zero! // The objects are never destroyed! ``` To work around this problem, both Boost and C++11 have defined a `weak_ptr` to define a weak (uncounted) reference to a `shared_ptr`.
106,509
<p>I have a button that I would like to disable when the form submits to prevent the user submitting multiple times.</p> <p>I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled.</p> <p>How do I disable the button when the form successfully submits not just when the user clicks?</p> <p>This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.</p>
[ { "answer_id": 106522, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<p>Disable the button at the very end of your submit handler. If the validation fails, it should return false before that.</p>\...
2008/09/20
[ "https://Stackoverflow.com/questions/106509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6600/" ]
I have a button that I would like to disable when the form submits to prevent the user submitting multiple times. I have tried naively disabling the button with javascript onclick but then if a client side validation that fails the button remains disabled. How do I disable the button when the form successfully submits not just when the user clicks? This is an ASP.NET form so I would like to hook in nicely with the asp.net ajax page lifecycle if possible.
Give this a whirl: ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Threading; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Identify button as a "disabled-when-clicked" button... WebHelpers.DisableButtonOnClick( buttonTest, "showPleaseWait" ); } protected void buttonTest_Click( object sender, EventArgs e ) { // Emulate a server-side process to demo the disabled button during // postback. Thread.Sleep( 5000 ); } } using System; using System.Web; using System.Web.UI.WebControls; using System.Text; public class WebHelpers { // // Disable button with no secondary JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl ) { DisableButtonOnClick( ButtonControl, string.Empty ); } // // Disable button with a JavaScript function call. // public static void DisableButtonOnClick( Button ButtonControl, string ClientFunction ) { StringBuilder sb = new StringBuilder( 128 ); // If the page has ASP.NET validators on it, this code ensures the // page validates before continuing. sb.Append( "if ( typeof( Page_ClientValidate ) == 'function' ) { " ); sb.Append( "if ( ! Page_ClientValidate() ) { return false; } } " ); // Disable this button. sb.Append( "this.disabled = true;" ); // If a secondary JavaScript function has been provided, and if it can be found, // call it. Note the name of the JavaScript function to call should be passed without // parens. if ( ! String.IsNullOrEmpty( ClientFunction ) ) { sb.AppendFormat( "if ( typeof( {0} ) == 'function' ) {{ {0}() }};", ClientFunction ); } // GetPostBackEventReference() obtains a reference to a client-side script function // that causes the server to post back to the page (ie this causes the server-side part // of the "click" to be performed). sb.Append( ButtonControl.Page.ClientScript.GetPostBackEventReference( ButtonControl ) + ";" ); // Add the JavaScript created a code to be executed when the button is clicked. ButtonControl.Attributes.Add( "onclick", sb.ToString() ); } } ```
106,534
<p>The default rails XML builder escapes all HTML, so something like:</p> <pre class="lang-ruby prettyprint-override"><code>atom_feed do |feed| @stories.each do |story| feed.entry story do |entry| entry.title story.title entry.content "&lt;b&gt;foo&lt;/b&gt;" end end end </code></pre> <p>will produce the text:</p> <pre class="lang-html prettyprint-override"><code>&lt;b&gt;foo&lt;/b&gt; </code></pre> <p>instead of: <strong>foo</strong></p> <p>Is there any way to instruct the XML builder to not escape the XML?</p>
[ { "answer_id": 106616, "author": "Shalmanese", "author_id": 14559, "author_profile": "https://Stackoverflow.com/users/14559", "pm_score": 4, "selected": true, "text": "<p>turns out you need to do </p>\n\n<pre><code>entry.content \"&lt;b&gt;foo&lt;/b&gt;\", :type =&gt; \"html\"\n</code></...
2008/09/20
[ "https://Stackoverflow.com/questions/106534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14559/" ]
The default rails XML builder escapes all HTML, so something like: ```ruby atom_feed do |feed| @stories.each do |story| feed.entry story do |entry| entry.title story.title entry.content "<b>foo</b>" end end end ``` will produce the text: ```html <b>foo</b> ``` instead of: **foo** Is there any way to instruct the XML builder to not escape the XML?
turns out you need to do ``` entry.content "<b>foo</b>", :type => "html" ``` althought wrapping it in a CDATA stops it working.
106,544
<p>I get the following error when trying to run the latest Cygwin version of rsync in Windows XP SP2. The error occurs for attempts at both local syncs (that is: source and destination on the local harddisk only) and remote syncs (using "-e ssh" from the openssh package). Any advice on how to fix/workaround it?</p> <pre> bash-3.2$ rsync -a dir1 dir2 rsync: Failed to dup/close: Socket operation on non-socket (108) rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/pipe.c(143) [receiver=2.6.9] rsync: read error: Connection reset by peer (104) rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/io.c(604) [sender=2.6.9] </pre>
[ { "answer_id": 106736, "author": "Niall", "author_id": 6049, "author_profile": "https://Stackoverflow.com/users/6049", "pm_score": 1, "selected": true, "text": "<p>Not really an answer to your question, but I've found <a href=\"http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp\" rel=\"n...
2008/09/20
[ "https://Stackoverflow.com/questions/106544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19417/" ]
I get the following error when trying to run the latest Cygwin version of rsync in Windows XP SP2. The error occurs for attempts at both local syncs (that is: source and destination on the local harddisk only) and remote syncs (using "-e ssh" from the openssh package). Any advice on how to fix/workaround it? ``` bash-3.2$ rsync -a dir1 dir2 rsync: Failed to dup/close: Socket operation on non-socket (108) rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/pipe.c(143) [receiver=2.6.9] rsync: read error: Connection reset by peer (104) rsync error: error in IPC code (code 14) at /home/lapo/packaging/tmp/rsync-2.6.9/io.c(604) [sender=2.6.9] ```
Not really an answer to your question, but I've found [Delta Copy](http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp) to be a much better option than messing around with Cygwin. It connects to regular rsync daemons too.
106,554
<p>I use this code in my Windows Service to be notified of USB disk drives being inserted and removed:</p> <pre><code>WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent", "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2"); query.WithinInterval = TimeSpan.FromSeconds(1); _deviceWatcher = new ManagementEventWatcher(query); _deviceWatcher.EventArrived += new EventArrivedEventHandler(OnDeviceEventArrived); _deviceWatcher.Start(); </code></pre> <p>It works on XP and Vista, but on XP I can hear the very noticeable sound of the hard drive being accessed every second. Is there another WMI query that will give me the events without the sound effect?</p>
[ { "answer_id": 106775, "author": "Andrew Queisser", "author_id": 18321, "author_profile": "https://Stackoverflow.com/users/18321", "pm_score": 2, "selected": false, "text": "<p>Not sure if this applies to your case but we've been using RegisterDeviceNotification in our C# code (which I c...
2008/09/20
[ "https://Stackoverflow.com/questions/106554", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14842/" ]
I use this code in my Windows Service to be notified of USB disk drives being inserted and removed: ``` WqlEventQuery query = new WqlEventQuery("__InstanceOperationEvent", "TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=2"); query.WithinInterval = TimeSpan.FromSeconds(1); _deviceWatcher = new ManagementEventWatcher(query); _deviceWatcher.EventArrived += new EventArrivedEventHandler(OnDeviceEventArrived); _deviceWatcher.Start(); ``` It works on XP and Vista, but on XP I can hear the very noticeable sound of the hard drive being accessed every second. Is there another WMI query that will give me the events without the sound effect?
Not sure if this applies to your case but we've been using RegisterDeviceNotification in our C# code (which I can't post here) to detect when USB devices are plugged in. There's a handful of native functions you have to import but it generally works well. Easiest to make it work in C++ first and then see what you have to move up into C#. There's some stuff on koders Code search that appears to be a whole C# device management module that might help: <http://www.koders.com/csharp/fidEF5C6B3E2F46BE9AAFC93DB75515DEFC46DB4101.aspx>
106,555
<p>I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing. </p> <p>I can do a check on the number of keys-value pairs:</p> <pre><code>if (scalar keys %cache &gt; $maxSize) { %cache = (); } </code></pre> <p>But is it possible to check the actual memory occupied by the hash?</p>
[ { "answer_id": 106565, "author": "mbac32768", "author_id": 18446, "author_profile": "https://Stackoverflow.com/users/18446", "pm_score": 4, "selected": false, "text": "<p>You're looking for <a href=\"http://search.cpan.org/perldoc?Devel::Size\" rel=\"nofollow noreferrer\">Devel::Size</a>...
2008/09/20
[ "https://Stackoverflow.com/questions/106555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5734/" ]
I have a Perl script where I maintain a very simple cache using a hash table. I would like to clear the hash once it occupies more than n bytes, to avoid Perl (32-bit) running out of memory and crashing. I can do a check on the number of keys-value pairs: ``` if (scalar keys %cache > $maxSize) { %cache = (); } ``` But is it possible to check the actual memory occupied by the hash?
[Devel::Size](http://search.cpan.org/perldoc?Devel::Size) is the answer to your question. (Note that Devel::Size will temporarily allocate a significant amount of memory when processing a large data structure, so it's not really well suited to this purpose.) However, [Cache::SizeAwareMemoryCache](http://search.cpan.org/perldoc?Cache::SizeAwareMemoryCache) and [Tie::Cache](http://search.cpan.org/perldoc?Tie::Cache) already implement what you're looking for (with somewhat different interfaces), and could save you from reinventing the wheel. [Memoize](http://search.cpan.org/perldoc?Memoize) is a module that makes it simple to cache the return value from a function. It doesn't implement a size-based cache limit, but it should be possible to use Tie::Cache as a backend for Memoize.
106,563
<p>I'd like to log the output of a command to <code>stdout</code> as well as to a log file. I've got Cygwin installed and I'm trying to use the <code>tee</code> command to accomplish this.</p> <pre><code>devenv mysolution.sln /build myproject "Release|Win32" | tee build.log </code></pre> <p>Trouble is that <code>tee</code> seems to insist on waiting for the end of file before outputting anything to either <code>stdout</code> or the log file. This takes away the point of it all, which is to have a log file for future reference, but also some <code>stdout</code> logging so I can easily see the build progress.</p> <p><code>tee</code>'s options appear to be limited to <code>--append</code>, <code>--ignore-interrupts</code>, <code>--help</code>, and <code>--version</code>. So is there another method to get to what I'm trying to do?</p>
[ { "answer_id": 106575, "author": "Sam Reynolds", "author_id": 9192, "author_profile": "https://Stackoverflow.com/users/9192", "pm_score": 2, "selected": false, "text": "<p>You can output to the file and tail -f the file.</p>\n\n<p>devenv mysolution.sln /build myproject \"Release|Win32\" ...
2008/09/20
[ "https://Stackoverflow.com/questions/106563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
I'd like to log the output of a command to `stdout` as well as to a log file. I've got Cygwin installed and I'm trying to use the `tee` command to accomplish this. ``` devenv mysolution.sln /build myproject "Release|Win32" | tee build.log ``` Trouble is that `tee` seems to insist on waiting for the end of file before outputting anything to either `stdout` or the log file. This takes away the point of it all, which is to have a log file for future reference, but also some `stdout` logging so I can easily see the build progress. `tee`'s options appear to be limited to `--append`, `--ignore-interrupts`, `--help`, and `--version`. So is there another method to get to what I'm trying to do?
> > tee seems to insist on waiting for the > end of file before outputting anything > to either stdout or the log file. > > > This should definitely not be happening - it would render tee nearly useless. Here's a simple test that I wrote that puts this to the test, and it's definitely not waiting for eof. ``` $ cat test #!/bin/sh echo "hello" sleep 5 echo "goodbye" $ ./test | tee test.log hello <pause> goodbye ```
106,622
<p>I'm trying to run the Tomcat with JBoss Embedded jpa booking example. I run the build and deploy the war. I then get the following error:</p> <pre> ERROR [catalina.core.ContainerBase.[Catalina].[localhost].[/jboss-seam-jpa]] Error configuring application listener of class com.sun.faces.config.ConfigureListener java.lang.NoClassDefFoundError: javax/el/CompositeELResolver at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357) at java.lang.Class.getConstructor0(Class.java:2671) at java.lang.Class.newInstance0(Class.java:321) at java.lang.Class.newInstance(Class.java:303) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3618) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4104 </pre> <p>I find this class exists in el-api.jar which is not in the classpath. So I add el-api.jar to the WEB-INF/lib directory. I then get the following error:</p> <pre> INFO: JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeans methods marked with these annotations will have said annotations processed. Sep 19, 2008 5:37:50 PM com.sun.faces.config.ConfigureListener installExpressionFactory SEVERE: Error Instantiating ExpressionFactory java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1332) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1181) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:164) at com.sun.faces.config.ConfigureListener.installExpressionFactory(ConfigureListener.java:1521) </pre> <p>This library appears to be in el-ri.jar or JSP 2.1 jar. Am I doing something wrong? Is there a place that explains how to run seam applications on tomcat 5.5.x? Any help is greatly appreciated!</p>
[ { "answer_id": 107003, "author": "user17163", "author_id": 17163, "author_profile": "https://Stackoverflow.com/users/17163", "pm_score": 0, "selected": false, "text": "<p>have you looked at the docs, there's also some pretty good info on the forums at www.seamframework.org and also the o...
2008/09/20
[ "https://Stackoverflow.com/questions/106622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ]
I'm trying to run the Tomcat with JBoss Embedded jpa booking example. I run the build and deploy the war. I then get the following error: ``` ERROR [catalina.core.ContainerBase.[Catalina].[localhost].[/jboss-seam-jpa]] Error configuring application listener of class com.sun.faces.config.ConfigureListener java.lang.NoClassDefFoundError: javax/el/CompositeELResolver at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357) at java.lang.Class.getConstructor0(Class.java:2671) at java.lang.Class.newInstance0(Class.java:321) at java.lang.Class.newInstance(Class.java:303) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3618) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4104 ``` I find this class exists in el-api.jar which is not in the classpath. So I add el-api.jar to the WEB-INF/lib directory. I then get the following error: ``` INFO: JSF1048: PostConstruct/PreDestroy annotations present. ManagedBeans methods marked with these annotations will have said annotations processed. Sep 19, 2008 5:37:50 PM com.sun.faces.config.ConfigureListener installExpressionFactory SEVERE: Error Instantiating ExpressionFactory java.lang.ClassNotFoundException: com.sun.el.ExpressionFactoryImpl at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1332) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1181) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:164) at com.sun.faces.config.ConfigureListener.installExpressionFactory(ConfigureListener.java:1521) ``` This library appears to be in el-ri.jar or JSP 2.1 jar. Am I doing something wrong? Is there a place that explains how to run seam applications on tomcat 5.5.x? Any help is greatly appreciated!
I got this to work. I ran ant tomcat55 under the seam/examples/jpa example. This included the el-*.jars needed. I then ran 'ant clean' and 'ant jboss-embeded' and manually copied in all of the el-*.jars from the tomcat55 make. This got past my problem above. Now I'm able to start tomcat 5.5.9 with embedded JBoss. I can run the booking example now with no problems.
106,630
<p>I start by creating a string variable with some <strong>non-ascii</strong> <em>utf-8</em> encoded data on it:</p> <pre><code>&gt;&gt;&gt; text = 'á' &gt;&gt;&gt; text '\xc3\xa1' &gt;&gt;&gt; text.decode('utf-8') u'\xe1' </code></pre> <p>Using <code>unicode()</code> on it raises errors...</p> <pre><code>&gt;&gt;&gt; unicode(text) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) </code></pre> <p>...but if I know the encoding I can use it as second parameter:</p> <pre><code>&gt;&gt;&gt; unicode(text, 'utf-8') u'\xe1' &gt;&gt;&gt; unicode(text, 'utf-8') == text.decode('utf-8') True </code></pre> <p>Now if I have a class that returns this text in the <code>__str__()</code> method:</p> <pre><code>&gt;&gt;&gt; class ReturnsEncoded(object): ... def __str__(self): ... return text ... &gt;&gt;&gt; r = ReturnsEncoded() &gt;&gt;&gt; str(r) '\xc3\xa1' </code></pre> <p><code>unicode(r)</code> seems to use <code>str()</code> on it, since it raises the same error as <code>unicode(text)</code> above:</p> <pre><code>&gt;&gt;&gt; unicode(r) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) </code></pre> <p>Until now everything is as planned!</p> <p><strong>But as no one would ever expect, <code>unicode(r, 'utf-8')</code> won't even try:</strong></p> <pre><code>&gt;&gt;&gt; unicode(r, 'utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: coercing to Unicode: need string or buffer, ReturnsEncoded found </code></pre> <p>Why? Why this inconsistent behavior? Is it a bug? is it intended? Very awkward.</p>
[ { "answer_id": 106640, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": false, "text": "<p><code>unicode</code> does not guess the encoding of your text. If your object can print itself as <code>unicode</co...
2008/09/20
[ "https://Stackoverflow.com/questions/106630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17160/" ]
I start by creating a string variable with some **non-ascii** *utf-8* encoded data on it: ``` >>> text = 'á' >>> text '\xc3\xa1' >>> text.decode('utf-8') u'\xe1' ``` Using `unicode()` on it raises errors... ``` >>> unicode(text) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) ``` ...but if I know the encoding I can use it as second parameter: ``` >>> unicode(text, 'utf-8') u'\xe1' >>> unicode(text, 'utf-8') == text.decode('utf-8') True ``` Now if I have a class that returns this text in the `__str__()` method: ``` >>> class ReturnsEncoded(object): ... def __str__(self): ... return text ... >>> r = ReturnsEncoded() >>> str(r) '\xc3\xa1' ``` `unicode(r)` seems to use `str()` on it, since it raises the same error as `unicode(text)` above: ``` >>> unicode(r) Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128) ``` Until now everything is as planned! **But as no one would ever expect, `unicode(r, 'utf-8')` won't even try:** ``` >>> unicode(r, 'utf-8') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: coercing to Unicode: need string or buffer, ReturnsEncoded found ``` Why? Why this inconsistent behavior? Is it a bug? is it intended? Very awkward.
The behaviour does seem confusing, but intensional. I reproduce here the entirety of the unicode documentation from the [Python Built-In Functions documentation](http://docs.python.org/lib/built-in-funcs.html) (for version 2.5.2, as I write this): > > **unicode([object[, encoding [, errors]]])** > > > Return the Unicode string version of object using one of the following modes: > > > If encoding and/or errors are given, unicode() will decode the > object which can either be an 8-bit string or a character buffer > using the codec for encoding. The encoding parameter is a string > giving the name of an encoding; if the encoding is not known, > LookupError is raised. Error handling is done according to > errors; this specifies the treatment of characters which are > invalid in the input encoding. If errors is 'strict' (the > default), a ValueError is raised on errors, while a value of > 'ignore' causes errors to be silently ignored, and a value of > 'replace' causes the official Unicode replacement character, > U+FFFD, to be used to replace input characters which cannot be > decoded. See also the [codecs](http://docs.python.org/lib/module-codecs.html) module. > > > If no optional parameters are given, unicode() will mimic the > behaviour of str() except that it returns Unicode strings > instead of 8-bit strings. More precisely, if object is a Unicode > string or subclass it will return that Unicode string without > any additional decoding applied. > > > For objects which provide a \_\_unicode\_\_() method, it will call > this method without arguments to create a Unicode string. For > all other objects, the 8-bit string version or representation is > requested and then converted to a Unicode string using the codec > for the default encoding in 'strict' mode. > > > New in version 2.0. Changed in version 2.2: Support for \_\_unicode\_\_() added. > > > So, when you call `unicode(r, 'utf-8')`, it requires an 8-bit string or a character buffer as the first argument, so it coerces your object using the `__str__()` method, and attempts to decode that using the `utf-8` codec. Without the `utf-8`, the `unicode()` function looks for a for a `__unicode__()` method on your object, and not finding it, calls the `__str__()` method, as you suggested, attempting to use the default codec to convert to unicode.
106,646
<p>I am looking for a CSS-based web page template where the main content <code>div</code> occupies the full height of the view port (minus header and footer heights) when its content has few lines. The footer should be at the bottom of the viewport, rather than right below content, where it's more in the middle of the viewport. Content area needs to expand vertically to be joined with the top of footer.</p> <p>If the content requires more space than the viewport, then footer can be at the bottom of the web page (instead of the bottom of view-port) as standard web design. </p> <p>A link to a specific link or sample code appreciated. Don't mention a template site and tell me to do a search there. Must work at least in IE 6 and FF. If JavaScript is required, it's OK as long as if browser doesn't support JS, it defaults to putting the footer at the bottom of the content area without breaking the layout.</p> <p>Sketch for case #1:</p> <pre><code>-------------- &lt;----- header area | | -------------| | small content| | | view-port | | | | -------------| | footer area | | -------------- &lt;----- all other cases: -------------- &lt;----- header area | | -------------| | big content | | | view-port | | | | | | | | | &lt;---- | -------------| footer area | -------------- </code></pre>
[ { "answer_id": 106689, "author": "Ross Martin", "author_id": 19433, "author_profile": "https://Stackoverflow.com/users/19433", "pm_score": 3, "selected": true, "text": "<p>Example here:\n<a href=\"http://www.rossdmartin.com/aitp/index.htm\" rel=\"nofollow noreferrer\">http://www.rossdmar...
2008/09/20
[ "https://Stackoverflow.com/questions/106646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5232/" ]
I am looking for a CSS-based web page template where the main content `div` occupies the full height of the view port (minus header and footer heights) when its content has few lines. The footer should be at the bottom of the viewport, rather than right below content, where it's more in the middle of the viewport. Content area needs to expand vertically to be joined with the top of footer. If the content requires more space than the viewport, then footer can be at the bottom of the web page (instead of the bottom of view-port) as standard web design. A link to a specific link or sample code appreciated. Don't mention a template site and tell me to do a search there. Must work at least in IE 6 and FF. If JavaScript is required, it's OK as long as if browser doesn't support JS, it defaults to putting the footer at the bottom of the content area without breaking the layout. Sketch for case #1: ``` -------------- <----- header area | | -------------| | small content| | | view-port | | | | -------------| | footer area | | -------------- <----- all other cases: -------------- <----- header area | | -------------| | big content | | | view-port | | | | | | | | | <---- | -------------| footer area | -------------- ```
Example here: <http://www.rossdmartin.com/aitp/index.htm> More in-depth resources: * <http://www.themaninblue.com/experiment/footerStickAlt/> * <http://ryanfait.com/sticky-footer/>
106,711
<p>Here's a simplified version of what I'm trying to do :</p> <ol> <li>Before any other actions are performed, present the user with a form to retrieve a string.</li> <li>Input the string, and then redirect to the default controller action (e.g. index). The string only needs to exist, no other validations are necessary.</li> <li>The string must be available (as an instance variable?) to all the actions in this controller.</li> </ol> <p>I'm very new with Rails, but this doesn't seem like it ought to be exceedingly hard, so I'm feeling kind of dumb.</p> <p>What I've tried : I have a <code>before_filter</code> redirecting to a private method that looks like</p> <pre><code>def check_string if @string return true else get_string end end </code></pre> <p>the <code>get_string</code> method looks like </p> <pre><code>def get_string if params[:string] respond_to do |format| format.html {redirect_to(accounts_url)} # authenticate.html.erb end end respond_to do |format| format.html {render :action =&gt;"get_string"} # get_string.html.erb end end </code></pre> <p>This fails because i have two render or redirect calls in the same action. I can take out that first <code>respond_to</code>, of course, but what happens is that the controller gets trapped in the <code>get_string</code> method. I can more or less see why that's happening, but I don't know how to fix it and break out. I need to be able to show one form (View), get and then do something with the input string, and then proceed as normal.</p> <p>The <code>get_string.html.erb</code> file looks like </p> <pre><code>&lt;h1&gt;Enter a string&lt;/h1&gt; &lt;% form_tag('/accounts/get_string') do %&gt; &lt;%= password_field_tag(:string, params[:string])%&gt; &lt;%= submit_tag('Ok')%&gt; &lt;% end %&gt; </code></pre> <p>I'll be thankful for any help!</p> <h2>EDIT</h2> <p>Thanks for the replies...<br> @Laurie Young : You are right, I was misunderstanding. For some reason I had it in my head that the instance of any given controller invoked by a user would persist throughout their session, and that some of the Rails magic was in tracking objects associated with each user session. I can see why that doesn't make a whole lot of sense in retrospect, and why my attempt to use an instance variable (which I'd thought would persist) won't work. Thanks to you as well :)</p>
[ { "answer_id": 106757, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 3, "selected": true, "text": "<p>Part of the problem is that you aren't setting @string. You don't really need the before_filter for this at all, and s...
2008/09/20
[ "https://Stackoverflow.com/questions/106711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17046/" ]
Here's a simplified version of what I'm trying to do : 1. Before any other actions are performed, present the user with a form to retrieve a string. 2. Input the string, and then redirect to the default controller action (e.g. index). The string only needs to exist, no other validations are necessary. 3. The string must be available (as an instance variable?) to all the actions in this controller. I'm very new with Rails, but this doesn't seem like it ought to be exceedingly hard, so I'm feeling kind of dumb. What I've tried : I have a `before_filter` redirecting to a private method that looks like ``` def check_string if @string return true else get_string end end ``` the `get_string` method looks like ``` def get_string if params[:string] respond_to do |format| format.html {redirect_to(accounts_url)} # authenticate.html.erb end end respond_to do |format| format.html {render :action =>"get_string"} # get_string.html.erb end end ``` This fails because i have two render or redirect calls in the same action. I can take out that first `respond_to`, of course, but what happens is that the controller gets trapped in the `get_string` method. I can more or less see why that's happening, but I don't know how to fix it and break out. I need to be able to show one form (View), get and then do something with the input string, and then proceed as normal. The `get_string.html.erb` file looks like ``` <h1>Enter a string</h1> <% form_tag('/accounts/get_string') do %> <%= password_field_tag(:string, params[:string])%> <%= submit_tag('Ok')%> <% end %> ``` I'll be thankful for any help! EDIT ---- Thanks for the replies... @Laurie Young : You are right, I was misunderstanding. For some reason I had it in my head that the instance of any given controller invoked by a user would persist throughout their session, and that some of the Rails magic was in tracking objects associated with each user session. I can see why that doesn't make a whole lot of sense in retrospect, and why my attempt to use an instance variable (which I'd thought would persist) won't work. Thanks to you as well :)
Part of the problem is that you aren't setting @string. You don't really need the before\_filter for this at all, and should just be able to use: ``` def get_string @string = params[:string] || session[:string] respond_to do |format| if @string format.html {redirect_to(accounts_url)} # authenticate.html.erb else format.html {render :action =>"get_string"} # get_string.html.erb end end end ``` If you want the @string variable to be available for all actions, you will need to store it in the session.
106,712
<p>I have a VB.NET Windows Forms project that at one point paints text directly to onto the form at runtime. Before I paint with the font though, I want to make sure that the font and font-size exists on the user's machine. If they don't, I'll try a few other similar fonts, eventually defaulting with Arial or something.</p> <p>What's the best way to test and validate a font on a user's computer?</p>
[ { "answer_id": 106724, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 4, "selected": true, "text": "<p>From an MSDN article titled \"How To: Enumerate Installed Fonts\", I found this code:</p>\n\n<pre>\n<code>\n\nInstalledF...
2008/09/20
[ "https://Stackoverflow.com/questions/106712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5473/" ]
I have a VB.NET Windows Forms project that at one point paints text directly to onto the form at runtime. Before I paint with the font though, I want to make sure that the font and font-size exists on the user's machine. If they don't, I'll try a few other similar fonts, eventually defaulting with Arial or something. What's the best way to test and validate a font on a user's computer?
From an MSDN article titled "How To: Enumerate Installed Fonts", I found this code: ``` InstalledFontCollection installedFontCollection = new InstalledFontCollection(); // Get the array of FontFamily objects. FontFamily[] fontFamilies = installedFontCollection.Families; ```
106,800
<p>Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example):</p> <ul> <li>Should tests be in the same project as application logic?</li> <li>Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have?</li> <li>How should I name my test classes, methods, and projects (if they go in different projects)</li> <li>Should private, protected, and internal methods be tested, or just those that are publicly accessible?</li> <li>Should unit and integration tests be separated?</li> <li>Is there a <strong>good</strong> reason not to have 100% test coverage?</li> </ul> <p>What am I not asking about that I should be?</p> <p>An online resource would be best.</p>
[ { "answer_id": 106806, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 1, "selected": false, "text": "<p>I insistently recommend you to read <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321146530\" rel=\"nofollow noref...
2008/09/20
[ "https://Stackoverflow.com/questions/106800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19421/" ]
Does anyone know of where to find unit testing guidelines and recommendations? I'd like to have something which addresses the following types of topics (for example): * Should tests be in the same project as application logic? * Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have? * How should I name my test classes, methods, and projects (if they go in different projects) * Should private, protected, and internal methods be tested, or just those that are publicly accessible? * Should unit and integration tests be separated? * Is there a **good** reason not to have 100% test coverage? What am I not asking about that I should be? An online resource would be best.
I would recommend [Kent Beck's](https://rads.stackoverflow.com/amzn/click/com/0321146530) book on TDD. Also, you need to go to [Martin Fowler's](http://martinfowler.com/articles/mocksArentStubs.html) site. He has a lot of good information about testing as well. We are pretty big on TDD so I will answer the questions in that light. > > Should tests be in the same project as application logic? > > > Typically we keep our tests in the same solution, but we break tests into seperate DLL's/Projects that mirror the DLL's/Projects they are testing, but maintain namespaces with the tests being in a sub namespace. Example: Common / Common.Tests > > Should I have test classes to mirror my logic classes or should I have only as many test classes as I feel I need to have? > > > Yes, your tests should be created before any classes are created, and by definition you should only test a single unit in isolation. Therefore you should have a test class for each class in your solution. > > How should I name my test classes, methods, and projects (if they go in different projects) > > > I like to emphasize that behavior is what is being tested so I typically name test classes after the SUT. For example if I had a User class I would name the test class like so: ``` public class UserBehavior ``` Methods should be named to describe the behavior that you expect. ``` public void ShouldBeAbleToSetUserFirstName() ``` Projects can be named however you want but usually you want it to be fairly obvious which project it is testing. See previous answer about project organization. > > Should private, protected, and internal methods be tested, or just those that are publicly accessible? > > > Again you want tests to assert expected behavior as if you were a 3rd party consumer of the objects being tested. If you test internal implementation details then your tests will be brittle. You want your test to give you the freedom to refactor without worrying about breaking existing functionality. If your test know about implementation details then you will have to change your tests if those details change. > > Should unit and integration tests be separated? > > > Yes, unit tests need to be isolated from acceptance and integration tests. Separation of concerns applies to tests as well. > > Is there a good reason not to have 100% test coverage? > > > I wouldn't get to hung up on the 100% code coverage thing. 100% code coverage tends to imply some level of quality in the tests, but that is a myth. You can have terrible tests and still get 100% coverage. I would instead rely on a good Test First mentality. If you always write a test before you write a line of code then you will ensure 100% coverage so it becomes a moot point. In general if you focus on describing the full behavioral scope of the class then you will have nothing to worry about. If you make code coverage a metric then lazy programmers will simply do just enough to meet that mark and you will still have crappy tests. Instead rely heavily on peer reviews where the tests are reviewed as well.
106,828
<p>I need to display a bunch of images on a web page using AJAX. All of them have different dimensions, so I want to adjust their size before displaying them. Is there any way to do this in JavaScript?</p> <p>Using PHP's <code>getimagesize()</code> for each image causes an unnecessary performance hit since there will be many images.</p>
[ { "answer_id": 106833, "author": "Dori", "author_id": 10936, "author_profile": "https://Stackoverflow.com/users/10936", "pm_score": 0, "selected": false, "text": "<p>Do you want to adjust the images themselves, or just the way they display? If the former, you want something on the server...
2008/09/20
[ "https://Stackoverflow.com/questions/106828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to display a bunch of images on a web page using AJAX. All of them have different dimensions, so I want to adjust their size before displaying them. Is there any way to do this in JavaScript? Using PHP's `getimagesize()` for each image causes an unnecessary performance hit since there will be many images.
I was searching a solution to get height and width of an image using JavaScript. I found many, but all those solutions only worked when the image was present in browser cache. Finally I found a solution to get the image height and width even if the image does not exist in the browser cache: ``` <script type="text/javascript"> var imgHeight; var imgWidth; function findHHandWW() { imgHeight = this.height; imgWidth = this.width; return true; } function showImage(imgPath) { var myImage = new Image(); myImage.name = imgPath; myImage.onload = findHHandWW; myImage.src = imgPath; } </script> ``` Thanks, Binod Suman <http://binodsuman.blogspot.com/2009/06/how-to-get-height-and-widht-of-image.html>
106,880
<p>I am trying to use the <code>InternalsVisibleTo</code> assembly attribute to make my internal classes in a .NET class library visible to my unit test project. For some reason, I keep getting an error message that says:</p> <blockquote> <p>'MyClassName' is inaccessible due to its protection level</p> </blockquote> <p>Both assemblies are signed and I have the correct key listed in the attribute declaration. Any ideas?</p>
[ { "answer_id": 106921, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 2, "selected": false, "text": "<p>You need to use the /out: compiler switch when compiling the friend assembly (the assembly that\ndoes not contain the Interna...
2008/09/20
[ "https://Stackoverflow.com/questions/106880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
I am trying to use the `InternalsVisibleTo` assembly attribute to make my internal classes in a .NET class library visible to my unit test project. For some reason, I keep getting an error message that says: > > 'MyClassName' is inaccessible due to its protection level > > > Both assemblies are signed and I have the correct key listed in the attribute declaration. Any ideas?
Are you absolutely sure you have the correct public key specified in the attribute? Note that you need to specify the full public key, not just the public key token. It looks something like: ``` [assembly: InternalsVisibleTo("MyFriendAssembly, PublicKey=0024000004800000940000000602000000240000525341310004000001000100F73 F4DDC11F0CA6209BC63EFCBBAC3DACB04B612E04FA07F01D919FB5A1579D20283DC12901C8B66 A08FB8A9CB6A5E81989007B3AA43CD7442BED6D21F4D33FB590A46420FB75265C889D536A9519 674440C3C2FB06C5924360243CACD4B641BE574C31A434CE845323395842FAAF106B234C2C140 6E2F553073FF557D2DB6C5")] ``` It's 320 or so hex digits. Not sure why you need to specify the full public key - possibly with just the public key token that is used in other assembly references it would be easier for someone to spoof the friend assembly's identity.
106,896
<p>I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.</p>
[ { "answer_id": 106903, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 3, "selected": false, "text": "<p>I would say to put as many classes as can be logically grouped in that file without making it too big and complex.</p...
2008/09/20
[ "https://Stackoverflow.com/questions/106896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14139/" ]
I'm used to the Java model where you can have one public class per file. Python doesn't have this restriction, and I'm wondering what's the best practice for organizing classes.
A Python file is called a "module" and it's one way to organize your software so that it makes "sense". Another is a directory, called a "package". A module is a distinct thing that may have one or two dozen closely-related classes. The trick is that a module is something you'll import, and you need that import to be perfectly sensible to people who will read, maintain and extend your software. The rule is this: **a module is the unit of reuse**. You can't easily reuse a single class. You should be able to reuse a module without any difficulties. Everything in your library (and everything you download and add) is either a module or a package of modules. For example, you're working on something that reads spreadsheets, does some calculations and loads the results into a database. What do you want your main program to look like? ``` from ssReader import Reader from theCalcs import ACalc, AnotherCalc from theDB import Loader def main( sourceFileName ): rdr= Reader( sourceFileName ) c1= ACalc( options ) c2= AnotherCalc( options ) ldr= Loader( parameters ) for myObj in rdr.readAll(): c1.thisOp( myObj ) c2.thatOp( myObj ) ldr.laod( myObj ) ``` Think of the import as the way to organize your code in concepts or chunks. Exactly how many classes are in each import doesn't matter. What matters is the overall organization that you're portraying with your `import` statements.
106,907
<p>We put all of our unit tests in their own projects. We find that we have to make certain classes public instead of internal just for the unit tests. Is there anyway to avoid having to do this. What are the memory implication by making classes public instead of sealed?</p>
[ { "answer_id": 106933, "author": "TraumaPony", "author_id": 18658, "author_profile": "https://Stackoverflow.com/users/18658", "pm_score": -1, "selected": false, "text": "<p>Classes can be both public AND sealed.</p>\n\n<p>But, don't do that.</p>\n\n<p>You can create a tool to reflect ove...
2008/09/20
[ "https://Stackoverflow.com/questions/106907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
We put all of our unit tests in their own projects. We find that we have to make certain classes public instead of internal just for the unit tests. Is there anyway to avoid having to do this. What are the memory implication by making classes public instead of sealed?
If you're using .NET, the [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx) assembly attribute allows you to create "friend" assemblies. These are specific strongly named assemblies that are allowed to access internal classes and members of the other assembly. Note, this should be used with discretion as it tightly couples the involved assemblies. A common use for InternalsVisibleTo is for unit testing projects. It's probably not a good choice for use in your actual application assemblies, for the reason stated above. **Example:** ``` [assembly: InternalsVisibleTo("NameAssemblyYouWantToPermitAccess")] namespace NameOfYourNameSpace { ```
106,912
<p>How do you draw a custom button next to the minimize, maximize and close buttons within the Titlebar of the Form?</p> <p>I know you need to use Win32 API calls and override the WndProc procedure, but I haven't been able to figure out a solution that works right.</p> <p>Does anyone know how to do this? More specifically, does anyone know a way to do this that works in Vista?</p>
[ { "answer_id": 107195, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 1, "selected": false, "text": "<p>Drawing seems to be the easy part, the following will do that:</p>\n\n<p>[Edit: Code removed, see my other ans...
2008/09/20
[ "https://Stackoverflow.com/questions/106912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
How do you draw a custom button next to the minimize, maximize and close buttons within the Titlebar of the Form? I know you need to use Win32 API calls and override the WndProc procedure, but I haven't been able to figure out a solution that works right. Does anyone know how to do this? More specifically, does anyone know a way to do this that works in Vista?
The following will work in XP, I have no Vista machine handy to test it, but I think your issues are steming from an incorrect hWnd somehow. Anyway, on with the poorly commented code. ``` // The state of our little button ButtonState _buttState = ButtonState.Normal; Rectangle _buttPosition = new Rectangle(); [DllImport("user32.dll")] private static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] private static extern int GetWindowRect(IntPtr hWnd, ref Rectangle lpRect); [DllImport("user32.dll")] private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC); protected override void WndProc(ref Message m) { int x, y; Rectangle windowRect = new Rectangle(); GetWindowRect(m.HWnd, ref windowRect); switch (m.Msg) { // WM_NCPAINT case 0x85: // WM_PAINT case 0x0A: base.WndProc(ref m); DrawButton(m.HWnd); m.Result = IntPtr.Zero; break; // WM_ACTIVATE case 0x86: base.WndProc(ref m); DrawButton(m.HWnd); break; // WM_NCMOUSEMOVE case 0xA0: // Extract the least significant 16 bits x = ((int)m.LParam << 16) >> 16; // Extract the most significant 16 bits y = (int)m.LParam >> 16; x -= windowRect.Left; y -= windowRect.Top; base.WndProc(ref m); if (!_buttPosition.Contains(new Point(x, y)) && _buttState == ButtonState.Pushed) { _buttState = ButtonState.Normal; DrawButton(m.HWnd); } break; // WM_NCLBUTTONDOWN case 0xA1: // Extract the least significant 16 bits x = ((int)m.LParam << 16) >> 16; // Extract the most significant 16 bits y = (int)m.LParam >> 16; x -= windowRect.Left; y -= windowRect.Top; if (_buttPosition.Contains(new Point(x, y))) { _buttState = ButtonState.Pushed; DrawButton(m.HWnd); } else base.WndProc(ref m); break; // WM_NCLBUTTONUP case 0xA2: // Extract the least significant 16 bits x = ((int)m.LParam << 16) >> 16; // Extract the most significant 16 bits y = (int)m.LParam >> 16; x -= windowRect.Left; y -= windowRect.Top; if (_buttPosition.Contains(new Point(x, y)) && _buttState == ButtonState.Pushed) { _buttState = ButtonState.Normal; // [[TODO]]: Fire a click event for your button // however you want to do it. DrawButton(m.HWnd); } else base.WndProc(ref m); break; // WM_NCHITTEST case 0x84: // Extract the least significant 16 bits x = ((int)m.LParam << 16) >> 16; // Extract the most significant 16 bits y = (int)m.LParam >> 16; x -= windowRect.Left; y -= windowRect.Top; if (_buttPosition.Contains(new Point(x, y))) m.Result = (IntPtr)18; // HTBORDER else base.WndProc(ref m); break; default: base.WndProc(ref m); break; } } private void DrawButton(IntPtr hwnd) { IntPtr hDC = GetWindowDC(hwnd); int x, y; using (Graphics g = Graphics.FromHdc(hDC)) { // Work out size and positioning int CaptionHeight = Bounds.Height - ClientRectangle.Height; Size ButtonSize = SystemInformation.CaptionButtonSize; x = Bounds.Width - 4 * ButtonSize.Width; y = (CaptionHeight - ButtonSize.Height) / 2; _buttPosition.Location = new Point(x, y); // Work out color Brush color; if (_buttState == ButtonState.Pushed) color = Brushes.LightGreen; else color = Brushes.Red; // Draw our "button" g.FillRectangle(color, x, y, ButtonSize.Width, ButtonSize.Height); } ReleaseDC(hwnd, hDC); } private void Form1_Load(object sender, EventArgs e) { _buttPosition.Size = SystemInformation.CaptionButtonSize; } ```