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
72,240
<p>How can I call a BizTalk Orchestration dynamically knowing the Orchestration name? </p> <p>The call Orchestration shapes need to know the name and parameters of Orchestrations at design time. I've tried using 'call' XLang keyword but it also required Orchestration name as Design Time like in expression shape, we can write as </p> <pre><code>call BizTalkApplication1.Orchestration1(param1,param2); </code></pre> <p>I'm looking for some way to specify calling orchestration name, coming from the incoming message or from SSO config store.</p> <p>EDIT: I'musing BizTalk 2006 R1 (ESB Guidance is for R2 and I didn't get how it could solve my problem) </p>
[ { "answer_id": 72353, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Look at ESB Guidance (www.codeplex.com/esb) This package provides the functionality you are looking for</p>\n" }, { ...
2008/09/16
[ "https://Stackoverflow.com/questions/72240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7722/" ]
How can I call a BizTalk Orchestration dynamically knowing the Orchestration name? The call Orchestration shapes need to know the name and parameters of Orchestrations at design time. I've tried using 'call' XLang keyword but it also required Orchestration name as Design Time like in expression shape, we can write as ``` call BizTalkApplication1.Orchestration1(param1,param2); ``` I'm looking for some way to specify calling orchestration name, coming from the incoming message or from SSO config store. EDIT: I'musing BizTalk 2006 R1 (ESB Guidance is for R2 and I didn't get how it could solve my problem)
The way I've accomplished something similar in the past is by using direct binding ports in the orchestrations and letting the MsgBox do the dirty work for me. Basically, it goes something like this: 1. Make the callable orchestrations use a direct-bound port attached to your activating receive shape. 2. Set up a filter expression on your activating receive shape with a custom context-based property and set it equal to a value that uniquely identifies the orchestration (such as the orchestration name or whatever) 3. In the calling orchestration, create the message you'll want to use to fire the new orchestration. In that message, set your custom context property to the value that matches the filter used in the specific orchestration you want to fire. 4. Send the message through a direct-bound send port so that it gets sent to the MsgBox directly and the Pub/Sub mechanisms in BizTalk will take care of the rest. One thing to watch out in step 4: To have this work correctly, you will need to create a new Correlation Set type that includes your custom context property, and then make sure that the direct-bound send port "follows" the correlation set on the send. Otherwise, the custom property will only be written (and not promoted) to the msg context and the routing will fail. Hope this helps!
72,242
<p>The page <em><a href="http://www.codinghorror.com/blog/archives/001167.html" rel="noreferrer">Protecting Your Cookies: HttpOnly</a></em> explains why making HttpOnly cookies is a good idea.</p> <p>How do I set this property in Ruby on Rails?</p>
[ { "answer_id": 72287, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 3, "selected": false, "text": "<p>Just set :http_only to true as described in the <a href=\"http://dev.rubyonrails.org/changeset/7525\" rel=\"noreferrer\"...
2008/09/16
[ "https://Stackoverflow.com/questions/72242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
The page *[Protecting Your Cookies: HttpOnly](http://www.codinghorror.com/blog/archives/001167.html)* explains why making HttpOnly cookies is a good idea. How do I set this property in Ruby on Rails?
Set the 'http\_only' option in the hash used to set a cookie e.g. ``` cookies["user_name"] = { :value => "david", :httponly => true } ``` or, in Rails 2: e.g. ``` cookies["user_name"] = { :value => "david", :http_only => true } ```
72,264
<p>I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE. </p> <p>What are the steps to create such an executable?</p>
[ { "answer_id": 72296, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 5, "selected": true, "text": "<p>Single Assembly Deployment of Managed and Unmanaged Code\nSunday, February 4, 2007</p>\n\n<p>.NET developers love XCOPY deploy...
2008/09/16
[ "https://Stackoverflow.com/questions/72264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12113/" ]
I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE. What are the steps to create such an executable?
Single Assembly Deployment of Managed and Unmanaged Code Sunday, February 4, 2007 .NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that component. So when I recently had to develop a managed code component and had to augment it with some unmanaged code from a C DLL (thx to Marcus Heege for helping me with this!), I thought about how to make it easier to deploy the two DLLs. If this were just two assemblies I could have used ILmerge to pack them up in just one file. But this doesn´t work for mixed code components with managed as well as unmanaged DLLs. So here´s what I came up with for a solution: I include whatever DLLs I want to deploy with my component´s main assembly as embedded resources. Then I set up a class constructor to extract those DLLs like below. The class ctor is called just once within each AppDomain so it´s a neglible overhead, I think. ``` namespace MyLib { public class MyClass { static MyClass() { ResourceExtractor.ExtractResourceToFile("MyLib.ManagedService.dll", "managedservice.dll"); ResourceExtractor.ExtractResourceToFile("MyLib.UnmanagedService.dll", "unmanagedservice.dll"); } ... ``` In this example I included two DLLs as resources, one being an unmanaged code DLL, and one being a managed code DLL (just for demonstration purposes), to show, how this technique works for both kinds of code. The code to extract the DLLs into files of their own is simple: ``` public static class ResourceExtractor { public static void ExtractResourceToFile(string resourceName, string filename) { if (!System.IO.File.Exists(filename)) using (System.IO.Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) using (System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create)) { byte[] b = new byte[s.Length]; s.Read(b, 0, b.Length); fs.Write(b, 0, b.Length); } } } ``` Working with a managed code assembly like this is the same as usual - almost. You reference it (here: ManagedService.dll) in your component´s main project (here: MyLib), but set the Copy Local property to false. Additionally you link in the assembly as an Existing Item and set the Build Action to Embedded Resource. For the unmanaged code (here: UnmanagedService.dll) you just link in the DLL as an Existing Item and set the Build Action to Embedded Resource. To access its functions use the DllImport attribute as usual, e.g. ``` [DllImport("unmanagedservice.dll")] public extern static int Add(int a, int b); ``` That´s it! As soon as you create the first instance of the class with the static ctor the embedded DLLs get extracted into files of their own and are ready to use as if you deployed them as separate files. As long as you have write permissions for the execution directory this should work fine for you. At least for prototypical code I think this way of single assembly deployment is quite convenient. Enjoy! <http://weblogs.asp.net/ralfw/archive/2007/02/04/single-assembly-deployment-of-managed-and-unmanaged-code.aspx>
72,281
<p>Receiving the following error when attempting to run a CLR stored proc. Any help is much appreciated.</p> <pre><code>Msg 10314, Level 16, State 11, Line 1 An error occurred in the Microsoft .NET Framework while trying to load assembly id 65752. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error: System.IO.FileLoadException: Could not load file or assembly 'orders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A) System.IO.FileLoadException: at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark&amp; stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark&amp; stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark&amp; stackMark, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark&amp; stackMark, Boolean forIntrospection) at System.Reflection.Assembly.Load(String assemblyString) </code></pre>
[ { "answer_id": 72445, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 0, "selected": false, "text": "<p>Does your assembly do file I/O? If so, you must grant the assembly permission to do this. In SSMS:</p>\n\n<ol>\n<li...
2008/09/16
[ "https://Stackoverflow.com/questions/72281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3400/" ]
Receiving the following error when attempting to run a CLR stored proc. Any help is much appreciated. ``` Msg 10314, Level 16, State 11, Line 1 An error occurred in the Microsoft .NET Framework while trying to load assembly id 65752. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error: System.IO.FileLoadException: Could not load file or assembly 'orders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A) System.IO.FileLoadException: at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) at System.Reflection.Assembly.Load(String assemblyString) ```
Ran the SQL commands below and the issue appears to be resolved. ``` USE database_name GO EXEC sp_changedbowner 'sa' ALTER DATABASE database_name SET TRUSTWORTHY ON ```
72,358
<p>I am using Tomcat as a server and Internet Explorer 6 as a browser. A web page in our app has about 75 images. We are using SSL. It seems to be very slow at loading all the content. How can I configure Tomcat so that IE caches the images?</p>
[ { "answer_id": 72413, "author": "Gabor", "author_id": 10485, "author_profile": "https://Stackoverflow.com/users/10485", "pm_score": -1, "selected": false, "text": "<p>Content served over a HTTPS connection <strong>never gets cached</strong> in the browser. You cannot do much about it. </...
2008/09/16
[ "https://Stackoverflow.com/questions/72358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ]
I am using Tomcat as a server and Internet Explorer 6 as a browser. A web page in our app has about 75 images. We are using SSL. It seems to be very slow at loading all the content. How can I configure Tomcat so that IE caches the images?
If you are serving a page over https then you'll need to serve all the included static or dynamic resources over https (either from the same domain, or another domain, also over https) to avoid a security warning in the browser. Content delivered over a secure channel will not be written to disk by default by most browsers and so lives in the browsers memory cache, which is much smaller than the on disk cache. This cache also disappears when the application quits. Having said all of that there are things you can do to improve the cachability for SSL assets inside a single browser setting. For starters, ensure that all you assets have reasonable Expires and Cache-Control headers. If tomcat is sitting behind apache then use mod\_expires to add them. This will avoid the browser having to check if the image has changed between pages ``` <Location /images> FileEtag none ExpiresActive on ExpiresDefault "access plus 1 month" </Location> ``` Secondly, and this is specific to MSIE and Apache, most apache ssl configs include these lines ``` SetEnvIf User-Agent ".*MSIE.*" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 ``` Which disables keepalive for ALL MSIE agents. IMHO this is far too conservative, the last MSIE browsers to have issues using SSL were 5.x and unpatched versions of 6.0 pre SP2, both of which are very uncommon now. The following is more lenient and will not disable keepalives when using MSIE and SSL ``` BrowserMatch "MSIE [1-4]" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0 BrowserMatch "MSIE [5-9]" ssl-unclean-shutdown ```
72,360
<p>here is what a I'm doing: </p> <pre><code>object ReturnMatch(System.Type type) { foreach(object obj in myObjects) { if (obj == type) { return obj; } } } </code></pre> <p>However, if obj is a subclass of <code>type</code>, it will not match. But I would like the function to return the same way as if I was using the operator <code>is</code>.</p> <p>I tried the following, but it won't compile:</p> <pre><code>if (obj is type) // won't compile in C# 2.0 </code></pre> <p>The best solution I came up with was:</p> <pre><code>if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type)) </code></pre> <p>Isn't there a way to use operator <code>is</code> to make the code cleaner?</p>
[ { "answer_id": 72384, "author": "Thunder3", "author_id": 2832, "author_profile": "https://Stackoverflow.com/users/2832", "pm_score": 2, "selected": false, "text": "<p>Perhaps </p>\n\n<pre><code>type.IsAssignableFrom(obj.GetType())\n</code></pre>\n" }, { "answer_id": 72407, "a...
2008/09/16
[ "https://Stackoverflow.com/questions/72360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10833/" ]
here is what a I'm doing: ``` object ReturnMatch(System.Type type) { foreach(object obj in myObjects) { if (obj == type) { return obj; } } } ``` However, if obj is a subclass of `type`, it will not match. But I would like the function to return the same way as if I was using the operator `is`. I tried the following, but it won't compile: ``` if (obj is type) // won't compile in C# 2.0 ``` The best solution I came up with was: ``` if (obj.GetType().Equals(type) || obj.GetType().IsSubclassOf(type)) ``` Isn't there a way to use operator `is` to make the code cleaner?
I've used the IsAssignableFrom method when faced with this problem. ``` Type theTypeWeWant; // From argument or whatever foreach (object o in myCollection) { if (theTypeWeWant.IsAssignableFrom(o.GetType)) return o; } ``` Another approach that may or may not work with your problem is to use a generic method: ``` private T FindObjectOfType<T>() where T: class { foreach(object o in myCollection) { if (o is T) return (T) o; } return null; } ``` (Code written from memory and is not tested)
72,381
<p>I'm trying to use the following code but it's returning the wrong day of month.</p> <pre><code>Calendar cal = Calendar.getInstance(); cal.setTime(sampleDay.getTime()); cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1); cal.set(Calendar.DAY_OF_MONTH, 0); return cal.getTime(); </code></pre>
[ { "answer_id": 72411, "author": "Stephen Wrighton", "author_id": 7516, "author_profile": "https://Stackoverflow.com/users/7516", "pm_score": 2, "selected": false, "text": "<p>I would create a date object for the first day of the NEXT month, and then just subtract a single day from the da...
2008/09/16
[ "https://Stackoverflow.com/questions/72381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
I'm trying to use the following code but it's returning the wrong day of month. ``` Calendar cal = Calendar.getInstance(); cal.setTime(sampleDay.getTime()); cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1); cal.set(Calendar.DAY_OF_MONTH, 0); return cal.getTime(); ```
Get the number of days for this month: ``` Calendar cal = Calendar.getInstance(); cal.setTime(sampleDay.getTime()); int noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH); ``` Set the Calendar to the last day of this month: ``` Calendar cal = Calendar.getInstance(); cal.setTime(sampleDay.getTime()); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); ```
72,393
<p>A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:</p> <pre><code>result = re.match(&quot;a_regex_of_pure_awesomeness&quot;, &quot;a string containing the awesomeness&quot;) # result is None` </code></pre> <p>After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change:</p> <pre><code>regex = &quot;.*(a_regex_of_pure_awesomeness)&quot; </code></pre> <p>into</p> <pre><code>regex = &quot;a_regex_of_pure_awesomeness&quot; </code></pre> <p>Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.</p>
[ { "answer_id": 72449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Are you using the <code>re.match()</code> or <code>re.search()</code> method? My understanding is that <code>re.match()</cod...
2008/09/16
[ "https://Stackoverflow.com/questions/72393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed: ``` result = re.match("a_regex_of_pure_awesomeness", "a string containing the awesomeness") # result is None` ``` After much head scratching I found out the issue, it automatically expects your pattern to be at the start of the string. I have found a fix but I would like to know how to change: ``` regex = ".*(a_regex_of_pure_awesomeness)" ``` into ``` regex = "a_regex_of_pure_awesomeness" ``` Okay, it's a standard URL regex but I wanted to avoid any potential confusion about what I wanted to get rid of and possibly pretend to be funny.
In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string. [Python regex docs](http://docs.python.org/lib/module-re.html) [Matching vs searching](http://docs.python.org/lib/matching-searching.html)
72,410
<p>How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu").</p> <p>I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions.</p> <p>One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies.</p> <p>I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much.</p> <hr> <p>I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know).</p> <p>Google will help me with translating the text, but not storing/presenting it.</p> <p>Has anyone worked on a multi-language project that relied on their own code for presentation?</p> <hr> <p>Any thoughts on serving up content in the following ways, and which is best?</p> <ul> <li><a href="http://www.website.com/text/view.asp?id=12345&amp;lang=fr" rel="nofollow noreferrer">http://www.website.com/text/view.asp?id=12345&amp;lang=fr</a></li> <li><a href="http://www.website.com/text/12345/bonjour_mes_amis.htm" rel="nofollow noreferrer">http://www.website.com/text/12345/bonjour_mes_amis.htm</a></li> <li><a href="http://fr.website.com/text/12345" rel="nofollow noreferrer">http://fr.website.com/text/12345</a></li> </ul> <p>(these are not real URLs, i was just showing examples)</p>
[ { "answer_id": 72451, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 1, "selected": false, "text": "<p>If you are using .Net, I would recommend going with one or more resource files (.resx). There is plenty of documen...
2008/09/16
[ "https://Stackoverflow.com/questions/72410", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11461/" ]
How should I store (and present) the text on a website intended for worldwide use, with several languages? The content is mostly in the form of 500+ word articles, although I will need to translate tiny snippets of text on each page too (such as "print this article" or "back to menu"). I know there are several CMS packages that handle multiple languages, but I have to integrate with our existing ASP systems too, so I am ignoring such solutions. One concern I have is that Google should be able to find the pages, even for foreign users. I am less concerned about issues with processing dates and currencies. I worry that, left to my own devices, I will invent a way of doing this which work, but eventually lead to disaster! I want to know what professional solutions you have actually used on real projects, not untried ideas! Thanks very much. --- I looked at RESX files, but felt they were unsuitable for all but the most trivial translation solutions (I will elaborate if anyone wants to know). Google will help me with translating the text, but not storing/presenting it. Has anyone worked on a multi-language project that relied on their own code for presentation? --- Any thoughts on serving up content in the following ways, and which is best? * <http://www.website.com/text/view.asp?id=12345&lang=fr> * <http://www.website.com/text/12345/bonjour_mes_amis.htm> * <http://fr.website.com/text/12345> (these are not real URLs, i was just showing examples)
Firstly put all code for all languages under one domain - it will help your google-rank. We have a fully multi-lingual system, with localisations stored in a database but cached with the web application. Wherever we want a localisation to appear we use: ``` <%$ Resources: LanguageProvider, Path/To/Localisation %> ``` Then in our web.config: ``` <globalization resourceProviderFactoryType="FactoryClassName, AssemblyName"/> ``` `FactoryClassName` then implements `ResourceProviderFactory` to provide the actual dynamic functionality. Localisations are stored in the DB with a string key "Path/To/Localisation" It is important to cache the localised values - you don't want to have lots of DB lookups on each page, and we cache thousands of localised strings with no performance issues. Use the user's current browser localisation to choose what language to serve up.
72,422
<p>Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.</p> <pre><code>&gt;&gt;&gt; class MyTest(unittest.TestCase): def setUp(self): self.i = 1 def testA(self): self.i = 3 self.assertEqual(self.i, 3) def testB(self): self.assertEqual(self.i, 3) &gt;&gt;&gt; unittest.main() .F ====================================================================== FAIL: testB (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "&lt;pyshell#61&gt;", line 8, in testB AssertionError: 1 != 3 ---------------------------------------------------------------------- Ran 2 tests in 0.016s </code></pre>
[ { "answer_id": 72498, "author": "mmaibaum", "author_id": 12213, "author_profile": "https://Stackoverflow.com/users/12213", "pm_score": 0, "selected": false, "text": "<p>If I recall correctly in that test framework the setUp method is run before each test</p>\n" }, { "answer_id": ...
2008/09/16
[ "https://Stackoverflow.com/questions/72422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9510/" ]
Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test. ``` >>> class MyTest(unittest.TestCase): def setUp(self): self.i = 1 def testA(self): self.i = 3 self.assertEqual(self.i, 3) def testB(self): self.assertEqual(self.i, 3) >>> unittest.main() .F ====================================================================== FAIL: testB (__main__.MyTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "<pyshell#61>", line 8, in testB AssertionError: 1 != 3 ---------------------------------------------------------------------- Ran 2 tests in 0.016s ```
Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance. Additionally, as others have pointed out, setUp is called before each test.
72,442
<p>I have a nullable property, and I want to return a null value. How do I do that in VB.NET ?</p> <p>Currently I use this solution, but I think there might be a better way.</p> <pre><code> Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer) Get If Current.Request.QueryString("rid") &lt;&gt; "" Then Return CInt(Current.Request.QueryString("rid")) Else Return (New Nullable(Of Integer)).Value End If End Get End Property </code></pre>
[ { "answer_id": 72465, "author": "Jon", "author_id": 12261, "author_profile": "https://Stackoverflow.com/users/12261", "pm_score": 4, "selected": true, "text": "<p>Are you looking for the keyword \"Nothing\"?</p>\n" }, { "answer_id": 72542, "author": "Luca Molteni", "autho...
2008/09/16
[ "https://Stackoverflow.com/questions/72442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6776/" ]
I have a nullable property, and I want to return a null value. How do I do that in VB.NET ? Currently I use this solution, but I think there might be a better way. ``` Public Shared ReadOnly Property rubrique_id() As Nullable(Of Integer) Get If Current.Request.QueryString("rid") <> "" Then Return CInt(Current.Request.QueryString("rid")) Else Return (New Nullable(Of Integer)).Value End If End Get End Property ```
Are you looking for the keyword "Nothing"?
72,458
<p><strong>Problem</strong></p> <p>I need to redirect some short convenience URLs to longer actual URLs. The site in question uses a set of subdomains to identify a set of development or live versions.</p> <p>I would like the URL to which certain requests are redirected to include the HTTP_HOST such that I don't have to create a custom .htaccess file for each host.</p> <p><strong>Host-specific Example (snipped from .htaccess file)</strong></p> <pre><code>Redirect /terms http://support.dev01.example.com/articles/terms/ </code></pre> <p>This example works fine for the development version running at dev01.example.com. If I use the same line in the main .htaccess file for the development version running under dev02.example.com I'd end up being redirected to the wrong place.</p> <p><strong>Ideal rule (not sure of the correct syntax)</strong></p> <pre><code>Redirect /terms http://support.{HTTP_HOST}/articles/terms/ </code></pre> <p>This rule does not work and merely serves as an example of what I'd like to achieve. I could then use the exact same rule under many different hosts and get the correct result.</p> <p><strong>Answers?</strong></p> <ul> <li>Can this be done with mod_alias or does it require the more complex mod_rewrite?</li> <li>How can this be achieved using mod_alias or mod_rewrite? I'd prefer a mod_alias solution if possible.</li> </ul> <p><strong>Clarifications</strong></p> <p>I'm not staying on the same server. I'd like:</p> <ul> <li>http://<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li> <li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>example.com</strong>/articles/terms/</li> <li>http://<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li> <li><a href="https://secure" rel="nofollow noreferrer">https://secure</a>.<strong>dev.example.com</strong>/terms/ -> <a href="http://support" rel="nofollow noreferrer">http://support</a>.<strong>dev.example.com</strong>/articles/terms/</li> </ul> <p>I'd like to be able to use the same rule in the .htaccess file on both example.com and dev.example.com. In this situation I'd need to be able to refer to the HTTP_HOST as a variable rather than specifying it literally in the URL to which requests are redirected.</p> <p>I'll investigate the HTTP_HOST parameter as suggested but was hoping for a working example.</p>
[ { "answer_id": 72530, "author": "Nicholas", "author_id": 8054, "author_profile": "https://Stackoverflow.com/users/8054", "pm_score": -1, "selected": false, "text": "<p>According to this cheatsheet ( <a href=\"http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/png/\" rel=\"nofo...
2008/09/16
[ "https://Stackoverflow.com/questions/72458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5343/" ]
**Problem** I need to redirect some short convenience URLs to longer actual URLs. The site in question uses a set of subdomains to identify a set of development or live versions. I would like the URL to which certain requests are redirected to include the HTTP\_HOST such that I don't have to create a custom .htaccess file for each host. **Host-specific Example (snipped from .htaccess file)** ``` Redirect /terms http://support.dev01.example.com/articles/terms/ ``` This example works fine for the development version running at dev01.example.com. If I use the same line in the main .htaccess file for the development version running under dev02.example.com I'd end up being redirected to the wrong place. **Ideal rule (not sure of the correct syntax)** ``` Redirect /terms http://support.{HTTP_HOST}/articles/terms/ ``` This rule does not work and merely serves as an example of what I'd like to achieve. I could then use the exact same rule under many different hosts and get the correct result. **Answers?** * Can this be done with mod\_alias or does it require the more complex mod\_rewrite? * How can this be achieved using mod\_alias or mod\_rewrite? I'd prefer a mod\_alias solution if possible. **Clarifications** I'm not staying on the same server. I'd like: * http://**example.com**/terms/ -> <http://support>.**example.com**/articles/terms/ * <https://secure>.**example.com**/terms/ -> <http://support>.**example.com**/articles/terms/ * http://**dev.example.com**/terms/ -> <http://support>.**dev.example.com**/articles/terms/ * <https://secure>.**dev.example.com**/terms/ -> <http://support>.**dev.example.com**/articles/terms/ I'd like to be able to use the same rule in the .htaccess file on both example.com and dev.example.com. In this situation I'd need to be able to refer to the HTTP\_HOST as a variable rather than specifying it literally in the URL to which requests are redirected. I'll investigate the HTTP\_HOST parameter as suggested but was hoping for a working example.
It's strange that nobody has done the actual **working** answer (lol): ``` RewriteCond %{HTTP_HOST} support\.(([^\.]+))\.example\.com RewriteRule ^/terms http://support.%1/article/terms [NC,QSA,R] ``` --- To help you doing the job faster, my favorite tool to check for regexp: <http://www.quanetic.com/Regex> (don't forget to choose ereg(POSIX) instead of preg(PCRE)!) You use this tool when you want to check the URL and see if they're valid or not.
72,479
<p>Can anyone tell me what exactly does this Java code do?</p> <pre><code>SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] bytes = new byte[20]; synchronized (random) { random.nextBytes(bytes); } return Base64.encode(bytes); </code></pre> <hr> <p>Step by step explanation will be useful so that I can recreate this code in VB. Thanks</p>
[ { "answer_id": 72520, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>This creates a random number generator (SecureRandom). It then creates a byte array (byte[] bytes), length 20 bytes, and pop...
2008/09/16
[ "https://Stackoverflow.com/questions/72479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12178/" ]
Can anyone tell me what exactly does this Java code do? ``` SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); byte[] bytes = new byte[20]; synchronized (random) { random.nextBytes(bytes); } return Base64.encode(bytes); ``` --- Step by step explanation will be useful so that I can recreate this code in VB. Thanks
Using code snippets you can get to something like this ``` Dim randomNumGen As RandomNumberGenerator = RNGCryptoServiceProvider.Create() Dim randomBytes(20) As Byte randomNumGen.GetBytes(randomBytes) return Convert.ToBase64String(randomBytes) ```
72,515
<p>I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?</p> <p>I would like to be able to use a RichTextBox to allow better formatting of the input value. Can this be done without creating a custom editor class?</p>
[ { "answer_id": 72538, "author": "GEOCHET", "author_id": 5640, "author_profile": "https://Stackoverflow.com/users/5640", "pm_score": 0, "selected": false, "text": "<p>I think what you are looking for is Custom Type Descriptors.\nYou could read up a bit and get started here: <a href=\"http...
2008/09/16
[ "https://Stackoverflow.com/questions/72515", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2533/" ]
I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property? I would like to be able to use a RichTextBox to allow better formatting of the input value. Can this be done without creating a custom editor class?
To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box. What is nice is that you can reuse the existing implementations. So to add the ability to multiline edit a string you just do this... ``` [Editor(typeof(MultilineStringEditor), typeof(UITypeEditor))] public override string Text { get { return _string; } set { _string = value; } } ``` Another nice one they provide for you is the ability to edit an array of strings... ``` [Editor("System.Windows.Forms.Design.StringArrayEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(UITypeEditor))] public string[] Lines { get { return _lines; } set { _lines = value; } } ```
72,552
<p>What does the <code>volatile</code> keyword do? In C++ what problem does it solve?</p> <p>In my case, I have never knowingly needed it.</p>
[ { "answer_id": 72576, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 7, "selected": false, "text": "<p><code>volatile</code> is needed when developing embedded systems or device drivers, where you need to read or write a memor...
2008/09/16
[ "https://Stackoverflow.com/questions/72552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2167252/" ]
What does the `volatile` keyword do? In C++ what problem does it solve? In my case, I have never knowingly needed it.
`volatile` is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this: ``` void waitForSemaphore() { volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/ while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED); } ``` Without `volatile`, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.
72,556
<p>I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid.</p> <p>Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.</p>
[ { "answer_id": 72576, "author": "ChrisN", "author_id": 3853, "author_profile": "https://Stackoverflow.com/users/3853", "pm_score": 7, "selected": false, "text": "<p><code>volatile</code> is needed when developing embedded systems or device drivers, where you need to read or write a memor...
2008/09/16
[ "https://Stackoverflow.com/questions/72556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12333/" ]
I am playing with Microsoft's TreeView control and I am trying to force a data update of some sorts while editing a node's label, similar to UpdateData for a grid. Basically, in my editor, I have a Save button and this TreeView control: what I want is when I am editing a node's label in the TreeView, if I click on the Save button I want to be able to commit the node's label I was editing.
`volatile` is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to. I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this: ``` void waitForSemaphore() { volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/ while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED); } ``` Without `volatile`, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.
72,564
<p>I'm kind of interested in getting some feedback about this technique I picked up from somewhere.</p> <p>I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this.</p> <p>Basically the technique involves returning true for success, and <em>something</em> which <em>equates</em> to false for failure. Here's an example to show what I mean:</p> <pre><code>define ('DUPLICATE_USERNAME', false); define ('DATABASE_ERROR', 0); define ('INSUFFICIENT_DETAILS', 0.0); define ('OK', true); function createUser($username) { // create the user and return the appropriate constant from the above } </code></pre> <p>The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code:</p> <pre><code>if (createUser('fred')) { // yay, it worked! } else { // aww, it didn't work. } </code></pre> <p>If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with ===</p> <pre><code>$status = createUser('fred'); if ($status) { // yay, it worked! } else if ($status === DUPLICATE_USERNAME) { // tell the user about it and get them to try again. } else { // aww, it didn't work. log it and show a generic error message? whatever. } </code></pre> <p>The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false.</p> <p>The downside is that you can only have <code>7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null.</code> If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an <code>enum</code> where they all equate to false is <code>"ick"</code>.</p> <hr> <p>So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing? </p>
[ { "answer_id": 72589, "author": "Chris Broadfoot", "author_id": 3947, "author_profile": "https://Stackoverflow.com/users/3947", "pm_score": 2, "selected": false, "text": "<p>As long as it's documented and contracted, and not too WTFy, then there shouldn't be a problem.</p>\n\n<p>Then aga...
2008/09/16
[ "https://Stackoverflow.com/questions/72564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
I'm kind of interested in getting some feedback about this technique I picked up from somewhere. I use this when a function can either succeed or fail, but you'd like to get more information about why it failed. A standard way to do this same thing would be with exception handling, but I often find it a bit over the top for this sort of thing, plus PHP4 does not offer this. Basically the technique involves returning true for success, and *something* which *equates* to false for failure. Here's an example to show what I mean: ``` define ('DUPLICATE_USERNAME', false); define ('DATABASE_ERROR', 0); define ('INSUFFICIENT_DETAILS', 0.0); define ('OK', true); function createUser($username) { // create the user and return the appropriate constant from the above } ``` The beauty of this is that in your calling code, if you don't care WHY the user creation failed, you can write simple and readable code: ``` if (createUser('fred')) { // yay, it worked! } else { // aww, it didn't work. } ``` If you particularly want to check why it didn't work (for logging, display to the user, or do whatever), use identity comparison with === ``` $status = createUser('fred'); if ($status) { // yay, it worked! } else if ($status === DUPLICATE_USERNAME) { // tell the user about it and get them to try again. } else { // aww, it didn't work. log it and show a generic error message? whatever. } ``` The way I see it, the benefits of this are that it is a normal expectation that a successful execution of a function like that would return true, and failure return false. The downside is that you can only have `7 "error" return values: false, 0, 0.0, "0", null, "", and (object) null.` If you forget to use identity checking you could get your program flow all wrong. Someone else has told me that using constants like an `enum` where they all equate to false is `"ick"`. --- So, to restate the question: how acceptable is a practise like this? Would you recommend a different way to achieve the same thing?
I agree with the others who have stated that this is a little on the WTFy side. If it's clearly documented functionality, then it's less of an issue, but I think it'd be safer to take an alternate route of returning 0 for success and integers for error codes. If you don't like that idea or the idea of a global last error variable, consider redefining your function as: ``` function createUser($username, &$error) ``` Then you can use: ``` if (createUser('fred', $error)) { echo 'success'; } else { echo $error; } ``` Inside createUser, just populate $error with any error you encounter and it'll be accessible outside of the function scope due to the reference.
72,568
<p>What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API? </p>
[ { "answer_id": 73349, "author": "Aaron", "author_id": 11176, "author_profile": "https://Stackoverflow.com/users/11176", "pm_score": 2, "selected": false, "text": "<p>If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double...
2008/09/16
[ "https://Stackoverflow.com/questions/72568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What's the best and/or fastest method of doing multijoin queries in Django using the ORM and QuerySet API?
If you are trying to join across tables linked by ForeignKeys or ManyToManyField relationships then you can use the double underscore syntax. For example if you have the following models: ``` class Foo(models.Model): name = models.CharField(max_length=255) class FizzBuzz(models.Model): bleh = models.CharField(max_length=255) class Bar(models.Model): foo = models.ForeignKey(Foo) fizzbuzz = models.ForeignKey(FizzBuzz) ``` You can do something like: ``` Fizzbuzz.objects.filter(bar__foo__name = "Adrian") ```
72,626
<p>I save stuff in an <a href="http://msdn.microsoft.com/en-us/library/3ak841sy.aspx" rel="nofollow noreferrer">Isolated Storage</a> file (using class IsolatedStorageFile). It works well, and I can retrieve the saved values when calling the saving and retrieving methods in my <a href="http://en.wikipedia.org/wiki/Data_access_layer" rel="nofollow noreferrer">DAL</a> layer from my GUI layer. However, when I try to retrieve the same settings from another assembly in the same project, it gives me a FileNotFoundException. What do I do wrong? This is the general concept:</p> <pre><code> public void Save(int number) { IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly(); IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage); StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine(number); writer.Close(); } public int Retrieve() { IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly(); IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.Open, storage); StreamReader reader = new StreamReader(fileStream); int number; try { string line = reader.ReadLine(); number = int.Parse(line); } finally { reader.Close(); } return number; } </code></pre> <p>I've tried using all the GetMachineStoreFor* scopes.</p> <p>EDIT: Since I need several assemblies to access the files, it doesn't seem possible to do with isolated storage, unless it's a <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a> application.</p>
[ { "answer_id": 72736, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 3, "selected": true, "text": "<p>When you instantiated the IsolatedStorageFile, did you scope it to IsolatedStorageScope.Machine?</p>\n\n<p>Ok now that you ...
2008/09/16
[ "https://Stackoverflow.com/questions/72626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3397/" ]
I save stuff in an [Isolated Storage](http://msdn.microsoft.com/en-us/library/3ak841sy.aspx) file (using class IsolatedStorageFile). It works well, and I can retrieve the saved values when calling the saving and retrieving methods in my [DAL](http://en.wikipedia.org/wiki/Data_access_layer) layer from my GUI layer. However, when I try to retrieve the same settings from another assembly in the same project, it gives me a FileNotFoundException. What do I do wrong? This is the general concept: ``` public void Save(int number) { IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly(); IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.OpenOrCreate, storage); StreamWriter writer = new StreamWriter(fileStream); writer.WriteLine(number); writer.Close(); } public int Retrieve() { IsolatedStorageFile storage = IsolatedStorageFile.GetMachineStoreForAssembly(); IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(filename, FileMode.Open, storage); StreamReader reader = new StreamReader(fileStream); int number; try { string line = reader.ReadLine(); number = int.Parse(line); } finally { reader.Close(); } return number; } ``` I've tried using all the GetMachineStoreFor\* scopes. EDIT: Since I need several assemblies to access the files, it doesn't seem possible to do with isolated storage, unless it's a [ClickOnce](http://en.wikipedia.org/wiki/ClickOnce) application.
When you instantiated the IsolatedStorageFile, did you scope it to IsolatedStorageScope.Machine? Ok now that you have illustrated your code style and I have gone back to retesting the behaviour of the methods, here is the explanation: * GetMachineStoreForAssembly() - scoped to the machine and the assembly identity. Different assemblies in the same application would have their own isolated storage. * GetMachineStoreForDomain() - a misnomer in my opinion. scoped to the machine and the domain identity *on top of* the assembly identity. There should have been an option for just AppDomain alone. * GetMachineStoreForApplication() - this is the one you are looking for. I have tested it and different assemblies can pick up the values written in another assembly. The only catch is, the *application identity* must be verifiable. When running locally, it cannot be properly determined and it will end up with exception "Unable to determine application identity of the caller". It can be verified by deploying the application via Click Once. Only then can this method apply and achieve its desired effect of shared isolated storage.
72,639
<p>I am importing data from MS Excel spreadsheets into a php/mySQL application. Several different parties are supplying the spreadsheets and they are in formats ranging from Excel 4.0 to Excel 2007. The trouble is finding a technique to read ALL versions.</p> <p>More info: </p> <pre><code> - I am currently using php-ExcelReader. - A script in a language other than php that can convert Excel to CSV would be an acceptable solution. </code></pre>
[ { "answer_id": 72669, "author": "Erratic", "author_id": 2246765, "author_profile": "https://Stackoverflow.com/users/2246765", "pm_score": 2, "selected": false, "text": "<p>Depending on the nature of your data and the parties that upload the excel files, you might want to consider having ...
2008/09/16
[ "https://Stackoverflow.com/questions/72639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12231/" ]
I am importing data from MS Excel spreadsheets into a php/mySQL application. Several different parties are supplying the spreadsheets and they are in formats ranging from Excel 4.0 to Excel 2007. The trouble is finding a technique to read ALL versions. More info: ``` - I am currently using php-ExcelReader. - A script in a language other than php that can convert Excel to CSV would be an acceptable solution. ```
Depending on the nature of your data and the parties that upload the excel files, you might want to consider having them save the data in .csv format. It will be much easier to parse on your end. Assuming that isn't an option a quick google search turned up <http://sourceforge.net/projects/phpexcelreader/> which might suit your needs.
72,671
<p>I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command.</p> <p>However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this?</p> <p>E.g. batch file</p> <pre><code>start "c:\path with spaces\app.exe" param1 "param with spaces" </code></pre>
[ { "answer_id": 72726, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": -1, "selected": false, "text": "<p>Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to han...
2008/09/16
[ "https://Stackoverflow.com/questions/72671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need to create a batch file which starts multiple console applications in a Windows .cmd file. This can be done using the start command. However, the command has a path in it. I also need to pass paramaters which have spaces as well. How to do this? E.g. batch file ``` start "c:\path with spaces\app.exe" param1 "param with spaces" ```
Actually, his example won't work (although at first I thought that it would, too). Based on the help for the Start command, the first parameter is the name of the newly created Command Prompt window, and the second and third should be the path to the application and its parameters, respectively. If you add another "" before path to the app, it should work (at least it did for me). Use something like this: ``` start "" "c:\path with spaces\app.exe" param1 "param with spaces" ``` You can change the first argument to be whatever you want the title of the new command prompt to be. If it's a Windows app that is created, then the command prompt won't be displayed, and the title won't matter.
72,672
<p>Has anyone written an 'UnFormat' routine for Delphi?</p> <p>What I'm imagining is the <em>inverse</em> of <em>SysUtils.Format</em> and looks something like this </p> <p>UnFormat('a number %n and another %n',[float1, float2]); </p> <p>So you could unpack a string into a series of variables using format strings.</p> <p>I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.</p>
[ { "answer_id": 72713, "author": "PatrickvL", "author_id": 12170, "author_profile": "https://Stackoverflow.com/users/12170", "pm_score": 5, "selected": true, "text": "<p>This is called scanf in C, I've made a Delphi look-a-like for this :</p>\n\n<pre><code>function ScanFormat(const Input,...
2008/09/16
[ "https://Stackoverflow.com/questions/72672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12376/" ]
Has anyone written an 'UnFormat' routine for Delphi? What I'm imagining is the *inverse* of *SysUtils.Format* and looks something like this UnFormat('a number %n and another %n',[float1, float2]); So you could unpack a string into a series of variables using format strings. I've looked at the 'Format' routine in SysUtils, but I've never used assembly so it is meaningless to me.
This is called scanf in C, I've made a Delphi look-a-like for this : ``` function ScanFormat(const Input, Format: string; Args: array of Pointer): Integer; var InputOffset: Integer; FormatOffset: Integer; InputChar: Char; FormatChar: Char; function _GetInputChar: Char; begin if InputOffset <= Length(Input) then begin Result := Input[InputOffset]; Inc(InputOffset); end else Result := #0; end; function _PeekFormatChar: Char; begin if FormatOffset <= Length(Format) then Result := Format[FormatOffset] else Result := #0; end; function _GetFormatChar: Char; begin Result := _PeekFormatChar; if Result <> #0 then Inc(FormatOffset); end; function _ScanInputString(const Arg: Pointer = nil): string; var EndChar: Char; begin Result := ''; EndChar := _PeekFormatChar; InputChar := _GetInputChar; while (InputChar > ' ') and (InputChar <> EndChar) do begin Result := Result + InputChar; InputChar := _GetInputChar; end; if InputChar <> #0 then Dec(InputOffset); if Assigned(Arg) then PString(Arg)^ := Result; end; function _ScanInputInteger(const Arg: Pointer): Boolean; var Value: string; begin Value := _ScanInputString; Result := TryStrToInt(Value, {out} PInteger(Arg)^); end; procedure _Raise; begin raise EConvertError.CreateFmt('Unknown ScanFormat character : "%s"!', [FormatChar]); end; begin Result := 0; InputOffset := 1; FormatOffset := 1; FormatChar := _GetFormatChar; while FormatChar <> #0 do begin if FormatChar <> '%' then begin InputChar := _GetInputChar; if (InputChar = #0) or (FormatChar <> InputChar) then Exit; end else begin FormatChar := _GetFormatChar; case FormatChar of '%': if _GetInputChar <> '%' then Exit; 's': begin _ScanInputString(Args[Result]); Inc(Result); end; 'd', 'u': begin if not _ScanInputInteger(Args[Result]) then Exit; Inc(Result); end; else _Raise; end; end; FormatChar := _GetFormatChar; end; end; ```
72,682
<p>Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes.</p> <p>Now you have a method, and you want to return a value. You <em>also</em> want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this:</p> <pre><code>class FunctionResult&lt;T&gt; { public T payload; public int result; } </code></pre> <p>And then declare your functions like this:</p> <pre><code>FunctionResult&lt;string&gt; MyFunction() { FunctionResult&lt;string&gt; result; //... return result; } </code></pre> <p>One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it?</p>
[ { "answer_id": 72729, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 1, "selected": false, "text": "<p>How about the \"Can't decide whether this is an error or not\" pattern. Seems like if you really had an exception but want...
2008/09/16
[ "https://Stackoverflow.com/questions/72682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
Let me start by saying that I do not advocate this approach, but I saw it recently and I was wondering if there was a name for it I could use to point the guilty party to. So here goes. Now you have a method, and you want to return a value. You *also* want to return an error code. Of course, exceptions are a much better choice, but for whatever reason you want an error code instead. Remember, I'm playing devil's advocate here. So you create a generic class, like this: ``` class FunctionResult<T> { public T payload; public int result; } ``` And then declare your functions like this: ``` FunctionResult<string> MyFunction() { FunctionResult<string> result; //... return result; } ``` One variation on this pattern is to use an enum for the error code instead of a string. Now, back to my question: is there a name for this, and if so what is it?
I'd agree that this isn't specifically an antipattern. It might be a smell depending upon the usage. There are reasons why one would actually not want to use exceptions (e.g. the errors being returned are not 'exceptional', for starters). There are instances where you want to have a service return a common model for its results, including both errors and good values. This might be wrapped by a low level service interaction that translates the result into an exception or other error structure, but at the level of the service, it lets the service return a result and a status code without having to define some exception structure that might have to be translated across a remote boundary. This code may not necessarily be an error either: consider an HTTP response, which consists of a lot of different data, including a status code, along with the body of the response.
72,696
<p>I have some code like this:</p> <pre><code>If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then DoSomething() End If </code></pre> <p>I don't care about the case. Should I use <code>OrdinalIgnoreCase</code>, <code>InvariantCultureIgnoreCase</code>, or <code>CurrentCultureIgnoreCase</code>?</p>
[ { "answer_id": 72718, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>It depends on what you want, though I'd shy away from invariantculture unless you're <em>very</em> sure you'll never...
2008/09/16
[ "https://Stackoverflow.com/questions/72696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
I have some code like this: ``` If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then DoSomething() End If ``` I don't care about the case. Should I use `OrdinalIgnoreCase`, `InvariantCultureIgnoreCase`, or `CurrentCultureIgnoreCase`?
**[Newer .Net Docs now has a table to help you decide which is best to use in your situation.](https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call)** From MSDN's "[New Recommendations for Using Strings in Microsoft .NET 2.0](https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms973919(v=msdn.10))" > > Summary: Code owners previously using the `InvariantCulture` for string comparison, casing, and sorting should strongly consider using a new set of `String` overloads in Microsoft .NET 2.0. *Specifically, data that is designed to be culture-agnostic and linguistically irrelevant* should begin specifying overloads using either the `StringComparison.Ordinal` or `StringComparison.OrdinalIgnoreCase` members of the new `StringComparison` enumeration. These enforce a byte-by-byte comparison similar to `strcmp` that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance. > > >
72,699
<p>For example which is better:</p> <pre><code>select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id </code></pre> <p>or</p> <pre><code>select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id </code></pre> <p>better as in less work for the database, faster results.</p> <p><strong>Note:</strong> Sybase, and there's an index on both tables of <code>country+id</code>.</p>
[ { "answer_id": 72738, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 0, "selected": false, "text": "<p>I'd lean towards only including your constant in the code once. There might be a performance advantage one way or t...
2008/09/16
[ "https://Stackoverflow.com/questions/72699", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12386/" ]
For example which is better: ``` select * from t1, t2 where t1.country='US' and t2.country=t1.country and t1.id=t2.id ``` or ``` select * from t1, t2 where t1.country'US' and t2.country='US' and t1.id=t2.id ``` better as in less work for the database, faster results. **Note:** Sybase, and there's an index on both tables of `country+id`.
I had a situation similar to this and this was the solution I resorted to: Select \* FROM t1 INNER JOIN t2 ON t1.id = t2.id AND t1.country = t2.country AND t1.country = 'US' I noticed that my query ran faster in this scenario. I made the assumption that joining on the constant saved the engine time because the WHERE clause will execute at the end. Joining and then filtering by 'US' means you still pulled all the other countries from your table and then had to filter out the ones you wanted. This method pulls less records in the end, because it will only find US records.
72,723
<p>I have a svn repository, R, that depends on a library, l, in another repository.</p> <p>The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R.</p> <p>I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'.</p> <p>If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.</p>
[ { "answer_id": 72925, "author": "jtimberman", "author_id": 7672, "author_profile": "https://Stackoverflow.com/users/7672", "pm_score": 2, "selected": false, "text": "<p>I suggest using a script wrapper for svn co. </p>\n\n<pre><code>#!/bin/sh\nsvn co path://server/R svn-R\ngit clone path...
2008/09/16
[ "https://Stackoverflow.com/questions/72723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a svn repository, R, that depends on a library, l, in another repository. The goal is that when someone checks out R, they also check out l. We want l to still be in its own repository so that l can be updated without dependence on R. I don't know much about external svn links, but I believe that when depending on a svn-based library one can link to it externally, 'ext'. If l is in a git repository, can I do something similar? I'd like to preserve the goal stated above.
I suggest using a script wrapper for svn co. ``` #!/bin/sh svn co path://server/R svn-R git clone path://server/l git-l ``` Or similar.
72,768
<p>I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this?</p>
[ { "answer_id": 72801, "author": "senfo", "author_id": 10792, "author_profile": "https://Stackoverflow.com/users/10792", "pm_score": 11, "selected": true, "text": "<p>The credit/debit card number is referred to as a <strong>PAN</strong>, or <em>Primary Account Number</em>. The first six ...
2008/09/16
[ "https://Stackoverflow.com/questions/72768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12382/" ]
I'm trying to figure out how to detect the type of credit card based purely on its number. Does anyone know of a definitive, reliable way to find this?
The credit/debit card number is referred to as a **PAN**, or *Primary Account Number*. The first six digits of the PAN are taken from the **IIN**, or *Issuer Identification Number*, belonging to the issuing bank (IINs were previously known as BIN — Bank Identification Numbers — so you may see references to that terminology in some documents). These six digits are subject to an international standard, [ISO/IEC 7812](http://en.wikipedia.org/wiki/ISO/IEC_7812), and can be used to determine the type of card from the number. Unfortunately the actual ISO/IEC 7812 database is not publicly available, however, there are unofficial lists, both commercial and free, including [on Wikipedia](http://en.wikipedia.org/wiki/Bank_card_number). Anyway, to detect the type from the number, you can use a regular expression like the ones below: [Credit for original expressions](http://www.regular-expressions.info/creditcard.html) **Visa:** `^4[0-9]{6,}$` Visa card numbers start with a 4. **MasterCard:** `^5[1-5][0-9]{5,}|222[1-9][0-9]{3,}|22[3-9][0-9]{4,}|2[3-6][0-9]{5,}|27[01][0-9]{4,}|2720[0-9]{3,}$` Before 2016, MasterCard numbers start with the numbers 51 through 55, **but this will only detect MasterCard credit cards**; there are other cards issued using the MasterCard system that do not fall into this IIN range. In 2016, they will add numbers in the range (222100-272099). **American Express:** `^3[47][0-9]{5,}$` American Express card numbers start with 34 or 37. **Diners Club:** `^3(?:0[0-5]|[68][0-9])[0-9]{4,}$` Diners Club card numbers begin with 300 through 305, 36 or 38. There are Diners Club cards that begin with 5 and have 16 digits. These are a joint venture between Diners Club and MasterCard and should be processed like a MasterCard. **Discover:** `^6(?:011|5[0-9]{2})[0-9]{3,}$` Discover card numbers begin with 6011 or 65. **JCB:** `^(?:2131|1800|35[0-9]{3})[0-9]{3,}$` JCB cards begin with 2131, 1800 or 35. Unfortunately, there are a number of card types processed with the MasterCard system that do not live in MasterCard’s IIN range (numbers starting 51...55); the most important case is that of Maestro cards, many of which have been issued from other banks’ IIN ranges and so are located all over the number space. As a result, **it may be best to assume that any card that is not of some other type you accept must be a MasterCard**. **Important**: card numbers do vary in length; for instance, Visa has in the past issued cards with 13 digit PANs and cards with 16 digit PANs. Visa’s documentation currently indicates that it may issue or may have issued numbers with between 12 and 19 digits. **Therefore, you should not check the length of the card number, other than to verify that it has at least 7 digits** (for a complete IIN plus one check digit, which should match the value predicted by [the Luhn algorithm](http://en.wikipedia.org/wiki/Luhn_algorithm)). One further hint: **before processing a cardholder PAN, strip any whitespace and punctuation characters from the input**. Why? Because it’s typically *much* easier to enter the digits in groups, similar to how they’re displayed on the front of an actual credit card, i.e. ``` 4444 4444 4444 4444 ``` is much easier to enter correctly than ``` 4444444444444444 ``` There’s really no benefit in chastising the user because they’ve entered characters you don't expect here. **This also implies making sure that your entry fields have room for *at least* 24 characters, otherwise users who enter spaces will run out of room.** I’d recommend that you make the field wide enough to display 32 characters and allow up to 64; that gives plenty of headroom for expansion. Here's an image that gives a little more insight: **UPDATE (2016):** Mastercard is to implement new BIN ranges starting [Ach Payment](http://achpayment.net/). ![Credit Card Verification](https://i.stack.imgur.com/Cu7PG.jpg)
72,769
<p>Problem (simplified to make things clearer):</p> <ul> 1. there is one statically-linked static.lib that has a function that increments: <pre><code> extern int CallCount = 0; int TheFunction() { void *p = &CallCount; printf("Function called"); return CallCount++; } </code></pre> 2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method: <pre><code> int Managed::CallLibFunc() { return TheFunction(); } </code></pre> 3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper: <pre><code> static void Main(string[] args) { Managed c1 = new Managed(); int val1 = c1.CallLibFunc(); // value is zero AppDomain ad = AppDomain.CreateDomain("NewDomain"); Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed; int val2 = c.CallLibFunc(); // value is one } </code></pre> </ul> <p>Question:</p> <p>Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed?</p> <p>Thank you very much everyone!</p>
[ { "answer_id": 73075, "author": "gnobal", "author_id": 7748, "author_profile": "https://Stackoverflow.com/users/7748", "pm_score": 3, "selected": true, "text": "<p>My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the A...
2008/09/16
[ "https://Stackoverflow.com/questions/72769", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2341/" ]
Problem (simplified to make things clearer): 1. there is one statically-linked static.lib that has a function that increments: ``` extern int CallCount = 0; int TheFunction() { void *p = &CallCount printf("Function called"); return CallCount++; } ``` 2. static.lib is linked into a managed C++/CLI managed.dll that wraps TheFunction method: ``` int Managed::CallLibFunc() { return TheFunction(); } ``` 3. Test app has a reference to managed.dll and creates multiple domains that call C++/CLI wrapper: ``` static void Main(string[] args) { Managed c1 = new Managed(); int val1 = c1.CallLibFunc(); // value is zero AppDomain ad = AppDomain.CreateDomain("NewDomain"); Managed c = ad.CreateInstanceAndUnwrap(a.FullName, typeof(Managed).FullName) as Managed; int val2 = c.CallLibFunc(); // value is one } ``` Question: Based on what I have read in Essential .NET Vol1 The CLR by Don Box, I would expect val2 to be zero since a brand new copy of managed.dll/static.lib is loaded when CreateInstanceAndUnwrap is called. Am I misunderstanding what is happening? The static library does not seem to be respecting the appdomain boundaries since it's unmanaged code. Is there a way to get around this issue other than by creating a brand new process for instantiating Managed? Thank you very much everyone!
My hunch was that, as you suspected, unmanaged DLLs are loaded in the context of the process and not in the context of the AppDomain, so any static data in unmanaged code is shared among AppDomains. [This link](http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/98cbabe0-33d6-4775-a3a7-04e71b7498dd/) shows someone with the same problem you have, still not 100% verification of this, but probably this is the case. [This link](http://lambert.geek.nz/2007/05/29/unmanaged-appdomain-callback/) is about creating a callback from unmanaged code into an AppDomain using a thunking trick. I'm not sure this can help you but maybe you'll find this useful to create some kind of a workaround.
72,789
<p>I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config?</p>
[ { "answer_id": 72848, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "<p>This will get you halfway there: <a href=\"http://www.codeproject.com/KB/dotnet/embedmultipleiconsdotnet.aspx\" rel=\"nofollo...
2008/09/16
[ "https://Stackoverflow.com/questions/72789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12117/" ]
I'd like to use a different icon for the demo version of my game, and I'm building the demo with a different build config than I do for the full verison, using a preprocessor define to lockout some content, use different graphics, etc. Is there a way that I can make Visual Studio use a different icon for the app Icon in the demo config but continue to use the regular icon for the full version's config?
According to [this page](http://msdn.microsoft.com/en-us/library/aa381033(VS.85).aspx) you may use preprocessor directives in your \*.rc file. You should write something like this ``` #ifdef _DEMO_VERSION_ IDR_MAINFRAME ICON "demo.ico" #else IDR_MAINFRAME ICON "full.ico" #endif ```
72,831
<p>Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?</p>
[ { "answer_id": 72862, "author": "ageektrapped", "author_id": 631, "author_profile": "https://Stackoverflow.com/users/631", "pm_score": 9, "selected": true, "text": "<p><code>TextInfo.ToTitleCase()</code> capitalizes the first character in each token of a string.<br />\nIf there is no nee...
2008/09/16
[ "https://Stackoverflow.com/questions/72831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9938/" ]
Is there an easy way to capitalize the first letter of a string and lower the rest of it? Is there a built in method or do I need to make my own?
`TextInfo.ToTitleCase()` capitalizes the first character in each token of a string. If there is no need to maintain Acronym Uppercasing, then you should include `ToLower()`. ``` string s = "JOHN DOE"; s = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s.ToLower()); // Produces "John Doe" ``` If CurrentCulture is unavailable, use: ``` string s = "JOHN DOE"; s = new System.Globalization.CultureInfo("en-US", false).TextInfo.ToTitleCase(s.ToLower()); ``` See the [MSDN Link](http://msdn2.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx) for a detailed description.
72,832
<p>When you use Visual Studio's code analysic (FxCop), and want to suppress a message there are 3 options.</p> <ol> <li>Suppress a violation in code.</li> <li>Suppress a violation in a GlobalSupression.cs file.</li> <li>Disable the violation check in the project file (via Project -> Properties -> Code Analysic).</li> </ol> <p>The later is very hard to review when checking in to Source Control, and it is hard to get an overview of all disabled violations. So we would like to use option 2.</p> <p>The problem with option 1 and 2 is that you get one suppression line for each violation. E.g like: </p> <pre><code>[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace2")] [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace1")] </code></pre> <p>We would love to do something like this ing GlobalSuppressions.cs:</p> <pre><code>[assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes")] </code></pre> <p>But is this possible?</p>
[ { "answer_id": 73369, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 4, "selected": true, "text": "<p>Suppressing multiple violations with a single <strong>SuppressMessage</strong> attribute is officially not supported. Appare...
2008/09/16
[ "https://Stackoverflow.com/questions/72832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
When you use Visual Studio's code analysic (FxCop), and want to suppress a message there are 3 options. 1. Suppress a violation in code. 2. Suppress a violation in a GlobalSupression.cs file. 3. Disable the violation check in the project file (via Project -> Properties -> Code Analysic). The later is very hard to review when checking in to Source Control, and it is hard to get an overview of all disabled violations. So we would like to use option 2. The problem with option 1 and 2 is that you get one suppression line for each violation. E.g like: ``` [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace2")] [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Company.Project.Namespace1")] ``` We would love to do something like this ing GlobalSuppressions.cs: ``` [assembly: SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes")] ``` But is this possible?
Suppressing multiple violations with a single **SuppressMessage** attribute is officially not supported. Apparently, this is by design. I agree, it might be annoying at times, but I can't say I disagree with the decision, since the attribute is their way to force you to say, "Yes, I know what I am doing", which should be evaluated in a case-by-case basis.
72,852
<p>Imagine this directory structure:</p> <pre><code>app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py </code></pre> <p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it? </p> <p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p> <p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way? </p> <hr> <p>Edit: all my <code>__init__.py</code>'s are currently empty </p> <p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p> <p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> (thanks John B)</p>
[ { "answer_id": 73149, "author": "John B", "author_id": 9597, "author_profile": "https://Stackoverflow.com/users/9597", "pm_score": 10, "selected": true, "text": "<p>Everyone seems to want to tell you what you should be doing rather than just answering the question.</p>\n\n<p>The problem ...
2008/09/16
[ "https://Stackoverflow.com/questions/72852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3497/" ]
Imagine this directory structure: ``` app/ __init__.py sub1/ __init__.py mod1.py sub2/ __init__.py mod2.py ``` I'm coding `mod1`, and I need to import something from `mod2`. How should I do it? I tried `from ..sub2 import mod2` but I'm getting an "Attempted relative import in non-package". I googled around but found only "`sys.path` manipulation" hacks. Isn't there a clean way? --- Edit: all my `__init__.py`'s are currently empty Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (`sub1`, `subX`, etc.). Edit3: The behaviour I'm looking for is the same as described in [PEP 366](http://www.python.org/dev/peps/pep-0366/) (thanks John B)
Everyone seems to want to tell you what you should be doing rather than just answering the question. The problem is that you're running the module as '\_\_main\_\_' by passing the mod1.py as an argument to the interpreter. From [PEP 328](http://www.python.org/dev/peps/pep-0328/): > > Relative imports use a module's \_\_name\_\_ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '\_\_main\_\_') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system. > > > In Python 2.6, they're adding the ability to reference modules relative to the main module. [PEP 366](http://python.org/dev/peps/pep-0366/) describes the change. **Update**: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.
72,899
<p>How do I sort a list of dictionaries by a specific key's value? Given:</p> <pre><code>[{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}] </code></pre> <p>When sorted by <code>name</code>, it should become:</p> <pre><code>[{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}] </code></pre>
[ { "answer_id": 72950, "author": "Matej", "author_id": 11457, "author_profile": "https://Stackoverflow.com/users/11457", "pm_score": 5, "selected": false, "text": "<p>You have to implement your own comparison function that will compare the dictionaries by values of name keys. See <a href=...
2008/09/16
[ "https://Stackoverflow.com/questions/72899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12398/" ]
How do I sort a list of dictionaries by a specific key's value? Given: ``` [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}] ``` When sorted by `name`, it should become: ``` [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}] ```
The [`sorted()`](https://docs.python.org/library/functions.html#sorted) function takes a `key=` parameter ``` newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) ``` Alternatively, you can use [`operator.itemgetter`](https://docs.python.org/library/operator.html#operator.itemgetter) instead of defining the function yourself ``` from operator import itemgetter newlist = sorted(list_to_be_sorted, key=itemgetter('name')) ``` For completeness, add `reverse=True` to sort in descending order ``` newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True) ```
72,913
<p>If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?</p>
[ { "answer_id": 72963, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 1, "selected": false, "text": "<p>A Lambda expression can contain complex statements, so you can do the following:</p>\n\n<pre><code>Func&lt;IEnumer...
2008/09/16
[ "https://Stackoverflow.com/questions/72913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
If I have an IEnumerator variable is it possible to have a lambda function that takes it, advances it with MoveNext() and returns the Current value every single time its called?
``` e => e.MoveNext() ? e.Current : null ``` This will advance the enumerator and return the current value, and return null when the enumeration is complete.
72,921
<p>I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem.</p> <p>I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. <a href="https://stackoverflow.com/users/4465/levik">Internet Duct Tape's Greasemonkey tools, like Comment Ninja</a>, are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth.</p> <p>I just want to be able to select a bunch of text on the comments page and click a bookmarklet (<a href="https://stackoverflow.com/users/8119/jacob">http://bookmarklets.com</a>) in Firefox that pops up a window listing all the IP addresses found in the selection.</p> <p><strong>Update:</strong></p> <p>I kind of combined a the answers from <a href="https://stackoverflow.com/users/4465/levik">levik</a> and <a href="https://stackoverflow.com/users/8119/jacob">Jacob</a> to come up with this:</p> <pre><code>javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("&lt;br&gt;");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses) </code></pre> <p>The difference is that instead of an <em>alert</em> message, as in levik's answer, I open a new window similar to Jacob's answer. The <em>alert</em> doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a <em><br></em> for the join instead of levik's <em>\n</em>. </p> <p>Thanks for all the help, guys.</p>
[ { "answer_id": 72981, "author": "Dr. Bob", "author_id": 12182, "author_profile": "https://Stackoverflow.com/users/12182", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://javascript.about.com/library/blip.htm\" rel=\"nofollow noreferrer\">Here</a> is a good article on obtai...
2008/09/16
[ "https://Stackoverflow.com/questions/72921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12419/" ]
I am just starting to learn javascript, so I don't have the skills to figure out what I assume is a trivial problem. I'm working with a Wordpress blog that serves as a FAQ for our community and I am trying to pull together some tools to make managing the comments easier. [Internet Duct Tape's Greasemonkey tools, like Comment Ninja](https://stackoverflow.com/users/4465/levik), are helpful for most of it, but I want to be able to get a list of all the IP addresses that we're getting comments from in order to track trends and so forth. I just want to be able to select a bunch of text on the comments page and click a bookmarklet ([http://bookmarklets.com](https://stackoverflow.com/users/8119/jacob)) in Firefox that pops up a window listing all the IP addresses found in the selection. **Update:** I kind of combined a the answers from [levik](https://stackoverflow.com/users/4465/levik) and [Jacob](https://stackoverflow.com/users/8119/jacob) to come up with this: ``` javascript:ipAddresses=document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g).join("<br>");newWindow=window.open('', 'IP Addresses in Selection', 'innerWidth=200,innerHeight=300,scrollbars');newWindow.document.write(ipAddresses) ``` The difference is that instead of an *alert* message, as in levik's answer, I open a new window similar to Jacob's answer. The *alert* doesn't provide scroll bars which can be a problem for pages with many IP addresses. However, I needed the list to be vertical, unlike Jacob's solution, so I used the hint from levik's to make a for the join instead of levik's *\n*. Thanks for all the help, guys.
In Firefox, you could do something like this: ``` javascript:alert( document.getSelection().match(/\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g) .join("\n")) ``` How this works: * Gets the selection text from the browser ("document.getSelection()" in FF, in IE it would be "document.selection.createRange().text") * Applies a regular expression to march the IP addresses (as suggested by Muerr) - this results in an array of strings. * Joins this array into one string separated by return characters * Alerts that string The way you get the selection is a little different on IE, but the principle is the same. To get it to be cross-browser, you'd need to check which method is available. You could also do more complicated output (like create a floating DIV and insert all the IPs into it).
72,936
<pre> kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al ls: cannot access post-commit: No such file or directory ls: cannot access update: No such file or directory ls: cannot access post-update: No such file or directory ls: cannot access commit-msg: No such file or directory ls: cannot access pre-rebase: No such file or directory ls: cannot access post-receive: No such file or directory ls: cannot access pre-applypatch: No such file or directory ls: cannot access pre-commit: No such file or directory total 8 drwxrwxr-x 2 kt kt 4096 2008-09-09 18:10 . drwxrwxr-x 4 kt kt 4096 2008-09-09 18:10 .. -????????? ? ? ? ? ? commit-msg -????????? ? ? ? ? ? post-commit -????????? ? ? ? ? ? post-receive -????????? ? ? ? ? ? post-update -????????? ? ? ? ? ? pre-applypatch -????????? ? ? ? ? ? pre-commit -????????? ? ? ? ? ? pre-rebase -????????? ? ? ? ? ? update </pre>
[ { "answer_id": 72988, "author": "raldi", "author_id": 7598, "author_profile": "https://Stackoverflow.com/users/7598", "pm_score": 4, "selected": true, "text": "<p>First off, here's your question, nicely formatted (surround it in &lt; pre > tags to get this):</p>\n\n<pre>kt@rails-ubuntu:~...
2008/09/16
[ "https://Stackoverflow.com/questions/72936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12417/" ]
``` kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al ls: cannot access post-commit: No such file or directory ls: cannot access update: No such file or directory ls: cannot access post-update: No such file or directory ls: cannot access commit-msg: No such file or directory ls: cannot access pre-rebase: No such file or directory ls: cannot access post-receive: No such file or directory ls: cannot access pre-applypatch: No such file or directory ls: cannot access pre-commit: No such file or directory total 8 drwxrwxr-x 2 kt kt 4096 2008-09-09 18:10 . drwxrwxr-x 4 kt kt 4096 2008-09-09 18:10 .. -????????? ? ? ? ? ? commit-msg -????????? ? ? ? ? ? post-commit -????????? ? ? ? ? ? post-receive -????????? ? ? ? ? ? post-update -????????? ? ? ? ? ? pre-applypatch -????????? ? ? ? ? ? pre-commit -????????? ? ? ? ? ? pre-rebase -????????? ? ? ? ? ? update ```
First off, here's your question, nicely formatted (surround it in < pre > tags to get this): ``` kt@rails-ubuntu:~/rails/ledger/releases/20080820144914/.git/hooks$ ls -al ls: cannot access post-commit: No such file or directory ls: cannot access update: No such file or directory ls: cannot access post-update: No such file or directory [snip] ``` Anyway, you need to boot up in single-user mode and run fsck. If you can't reboot right now, just move the directory to /tmp and forget about it.
72,943
<p>Is it possible to launch a new window in JavaScript using the window.Open function, then set the focus to that tab?</p> <p>Here's what I'm doing today: <code></p> <pre> var winRef = window.open(outUrl,wName,'left='+ wX +',top=' + wY + ',height=' + wH + ',width=' + wW + args); try { // Not all window types support the focus() property. winRef.focus(); } catch (exception) { } </pre> <p></code></p> <p>The window opens, but the new tab doesn't receive focus.</p>
[ { "answer_id": 72971, "author": "jtimberman", "author_id": 7672, "author_profile": "https://Stackoverflow.com/users/7672", "pm_score": 1, "selected": false, "text": "<p>As a user, I never want applications (or tabs) to take focus unless I specifically requested it. I have gone to great l...
2008/09/16
[ "https://Stackoverflow.com/questions/72943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/733/" ]
Is it possible to launch a new window in JavaScript using the window.Open function, then set the focus to that tab? Here's what I'm doing today: ``` var winRef = window.open(outUrl,wName,'left='+ wX +',top=' + wY + ',height=' + wH + ',width=' + wW + args); try { // Not all window types support the focus() property. winRef.focus(); } catch (exception) { } ``` The window opens, but the new tab doesn't receive focus.
Jay, You are seeing designed behavior. To limit opportunities for malicious behavior, scripts running in tabbed windows cannot affect other tabs. For more information, please see Tabbed Browsing for Developers at <http://msdn.microsoft.com/en-us/library/ms537636.aspx> : "The ability to open multiple documents within the same browser window has certain practical and security implications [...] Active tabs (tabs with focus) cannot be affected by scripts that run in inactive or background tabs." BR.
72,945
<p>Using Django's built in models, how would one create a triple-join between three models.</p> <p>For example:</p> <ul> <li>Users, Roles, and Events are the models.</li> <li>Users have many Roles, and Roles many Users. (ManyToMany)</li> <li>Events have many Users, and Users many Events. (ManyToMany)</li> <li>But for any given Event, any User may have only one Role.</li> </ul> <p>How can this be represented in the model?</p>
[ { "answer_id": 73153, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 2, "selected": false, "text": "<p>I'd recommend just creating an entirely separate model for this.</p>\n\n<pre><code>class Assignment(Model):\n u...
2008/09/16
[ "https://Stackoverflow.com/questions/72945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8507/" ]
Using Django's built in models, how would one create a triple-join between three models. For example: * Users, Roles, and Events are the models. * Users have many Roles, and Roles many Users. (ManyToMany) * Events have many Users, and Users many Events. (ManyToMany) * But for any given Event, any User may have only one Role. How can this be represented in the model?
**zacherates** writes: > > I'd model Role as an association class between Users and Roles (...) > > > I'd also reccomed this solution, but you can also make use of some syntactical sugar provided by Django: [ManyToMany relation with extra fields](http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships). Example: ``` class User(models.Model): name = models.CharField(max_length=128) class Event(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(User, through='Role') def __unicode__(self): return self.name class Role(models.Model): person = models.ForeignKey(User) group = models.ForeignKey(Event) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) ```
72,994
<p>I want to simulate a 'Web 2.0' Lightbox style UI technique in a <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window. </p> <p>The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible? </p> <p>I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful. If it is not possible, what would be another way to do it?</p> <p>See: <a href="http://www.useit.com/alertbox/application-design.html" rel="noreferrer">http://www.useit.com/alertbox/application-design.html</a> (under the Lightbox section for a screenshot to illustrate what I mean.)</p>
[ { "answer_id": 73062, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>The forms themselves have the property <code>Opacity</code> that would be perfect, but I don't think most of the ind...
2008/09/16
[ "https://Stackoverflow.com/questions/72994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6199/" ]
I want to simulate a 'Web 2.0' Lightbox style UI technique in a [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) application. That is, to draw attention to some foreground control by 'dimming' all other content in the client area of a window. The obvious solution is to create a control that is simply a partially transparent rectangle that can be docked to the client area of a window and brought to the front of the Z-Order. It needs to act like a dirty pain of glass through which the other controls can still be seen (and therefore continue to paint themselves). Is this possible? I've had a good hunt round and tried a few techniques myself but thus far have been unsuccessful. If it is not possible, what would be another way to do it? See: <http://www.useit.com/alertbox/application-design.html> (under the Lightbox section for a screenshot to illustrate what I mean.)
Can you do this in .NET/C#? Yes you certainly can but it takes a little bit of effort. I would recommend the following approach. Create a top level Form that has no border or titlebar area and then give make sure it draws no client area background by setting the TransparencyKey and BackColor to the same value. So you now have a window that draws nothing... ``` public class DarkenArea : Form { public DarkenArea() { FormBorderStyle = FormBorderStyle.None; SizeGripStyle = SizeGripStyle.Hide; StartPosition = FormStartPosition.Manual; MaximizeBox = false; MinimizeBox = false; ShowInTaskbar = false; BackColor = Color.Magenta; TransparencyKey = Color.Magenta; Opacity = 0.5f; } } ``` Create and position this DarkenArea window over the client area of your form. Then you need to be able to show the window without it taking the focus and so you will need to platform invoke in the following way to show without it becoming active... ``` public void ShowWithoutActivate() { // Show the window without activating it (i.e. do not take focus) PlatformInvoke.ShowWindow(this.Handle, (short)SW_SHOWNOACTIVATE); } ``` You need to make it actually draw something but exclude drawing in the area of the control you want to remain highlighted. So override the OnPaint handler and draw in black/blue or whatever you want but excluding the area you want to remain bright... ``` protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // Do your painting here be exclude the area you want to be brighter } ``` Last you need to override the WndProc to prevent the mouse interacting with the window if the user tries something crazy like clicking on the darkened area. Something like this... ``` protected override void WndProc(ref Message m) { if (m.Msg == (int)WM_NCHITTEST) m.Result = (IntPtr)HTTRANSPARENT; else base.WndProc(ref m); } ``` That should be enough to get the desired effect. When you are ready to reverse the effect you dispose of the DarkenArea instance and carry on.
72,996
<p>I am creating an installer in IzPack. It is quite large, and I have broken up my XML files appropriately using &lt;xinclude&gt; and &lt;xfragment&gt; tags. Unfortunately, IzPack does not combine them together when you build your installer. This requires you to package the files with the installer, which just won't work. </p> <p>I was about to start writing a tool in Java to load the XML files and combine them, but I don't want to go reinventing the wheel. </p> <p>Do the Java XML libraries provide native handling of xinclude? A google didn't seem to turn up much. </p> <p>Not a big deal if I have to write this myself, just wanted to check with you guys. Thanks.</p> <p>Format of XML for example purposes: File1.xml</p> <pre><code>&lt;?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?&gt; &lt;installation version="1.0"&gt; &lt;packs&gt; &lt;pack name="Transaction Service" id="Transaction Service" required="no" &gt; &lt;xinclude href="example/File2.xml" /&gt; &lt;/pack&gt; &lt;/packs&gt; </code></pre> <p>File2.xml</p> <pre><code>&lt;xfragment&gt; &lt;file src="..." /&gt; &lt;/xfragment&gt; </code></pre> <p>File2 does not need the standard XML header. The xml file is parsed at build time, because the resources it specifies are included in the installer. What isn't included is the actual XML information (order to write the files, where to put them etc.)</p> <p>What I am looking to have produced:</p> <pre><code>&lt;?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?&gt; &lt;installation version="1.0"&gt; &lt;packs&gt; &lt;pack name="Transaction Service" id="Transaction Service" required="no" &gt; &lt;file src="..." /&gt; &lt;/pack&gt; &lt;/packs&gt; </code></pre> <p>Thanks, I am going to start whipping it together in Java now, but hopefully someone has a simple answer. </p> <p>Tim Reynolds</p>
[ { "answer_id": 73306, "author": "Paul de Vrieze", "author_id": 4100, "author_profile": "https://Stackoverflow.com/users/4100", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if java supports automatic xinclude. But you will have to use namespaces to make it work. So don't use...
2008/09/16
[ "https://Stackoverflow.com/questions/72996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am creating an installer in IzPack. It is quite large, and I have broken up my XML files appropriately using <xinclude> and <xfragment> tags. Unfortunately, IzPack does not combine them together when you build your installer. This requires you to package the files with the installer, which just won't work. I was about to start writing a tool in Java to load the XML files and combine them, but I don't want to go reinventing the wheel. Do the Java XML libraries provide native handling of xinclude? A google didn't seem to turn up much. Not a big deal if I have to write this myself, just wanted to check with you guys. Thanks. Format of XML for example purposes: File1.xml ``` <?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?> <installation version="1.0"> <packs> <pack name="Transaction Service" id="Transaction Service" required="no" > <xinclude href="example/File2.xml" /> </pack> </packs> ``` File2.xml ``` <xfragment> <file src="..." /> </xfragment> ``` File2 does not need the standard XML header. The xml file is parsed at build time, because the resources it specifies are included in the installer. What isn't included is the actual XML information (order to write the files, where to put them etc.) What I am looking to have produced: ``` <?xml version="1.0" encoding="iso-8859-1" standalone="yes" ?> <installation version="1.0"> <packs> <pack name="Transaction Service" id="Transaction Service" required="no" > <file src="..." /> </pack> </packs> ``` Thanks, I am going to start whipping it together in Java now, but hopefully someone has a simple answer. Tim Reynolds
If you can't get xinclude to work and you're using Ant, I'd recommend [XMLTask](http://www.oopsconsultancy.com/software/xmltask), which is a plugin task for Ant. It'll do lots of clever stuff, including the one thing you're interested in - constructing a XML file out of fragments. e.g. ``` <xmltask source="templatefile.xml" dest="finalfile.xml"> <insert path="/packs/pack[1]" position="under" file="pack1.xml"/> </xmltask> ``` (warning- the above is done from memory so please consult the documentation!). Note that in the above, the file *pack1.xm*l doesn't have to have a root node.
73,000
<p>I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds <strong>all</strong> IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they <em>see</em> dialog on top of IE but it looks like it has hanged since it is not refreshe). </p> <p>So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. </p> <p>Here's the code:</p> <pre><code> PassDialog dialog = new PassDialog(parent); /* do some non gui related initialization */ dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setAlwaysOnTop(true); dialog.setVisible(true); </code></pre> <p>Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: </p> <pre><code>parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet); </code></pre>
[ { "answer_id": 73214, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 0, "selected": false, "text": "<p>You might try launching a modal from JavaScript using the JavaScript integration (see <a href=\"http://www.raditha.com/java...
2008/09/16
[ "https://Stackoverflow.com/questions/73000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7918/" ]
I have to write an applet that brings up a password dialog. The problem is that dialog is set to be always on top but when user clicks on IE window dialog gets hidden behind IE window nevertheless. And since dialog is modal and holds **all** IE threads IE pane does not refresh and dialog window is still painted on top of IE (but not refreshed). This behaviour confuses users (they *see* dialog on top of IE but it looks like it has hanged since it is not refreshe). So I need a way to keep that dialog on top of everything. But any other solution to this problem would be nice. Here's the code: ``` PassDialog dialog = new PassDialog(parent); /* do some non gui related initialization */ dialog.pack(); dialog.setLocationRelativeTo(null); dialog.setAlwaysOnTop(true); dialog.setVisible(true); ``` Resolution: As @shemnon noted I should make a window instead of (null, Frame, Applet) parent of modal dialog. So good way to initlialize parent was: ``` parent = javax.swing.SwingUtilities.getWindowAncestor(theApplet); ```
What argument are you using for the parent? You may have better luck if you use the parent of the Applet. ``` javax.swing.SwingUtilities.getWindowAncestor(theApplet) ``` Using the getWindowAncestor will skip the applet parents (getRoot(component) will return applets). In at least some versions of Java there was a Frame that was equivalent to the IE window. YMMV.
73,024
<p>This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why <code>delegate(0)</code> accomplishes this, in the kind of simple terms I can understand.</p> <pre><code>xmpp.OnLogin += delegate(object o) { xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); }; </code></pre>
[ { "answer_id": 73040, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 0, "selected": false, "text": "<p>That is creating an anonymous function. This feature was introduced in C# 2.0</p>\n" }, { "answer_id": 73...
2008/09/16
[ "https://Stackoverflow.com/questions/73024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7574/" ]
This is from an example accompanying the agsXMPP .Net assembly. I've read up on delegates, but am not sure how that fits in with this line of code (which waits for the logon to occur, and then sends a message. I guess what I'm looking for is an understanding of why `delegate(0)` accomplishes this, in the kind of simple terms I can understand. ``` xmpp.OnLogin += delegate(object o) { xmpp.Send(new Message(new Jid(JID_RECEIVER), MessageType.chat, "Hello, how are you?")); }; ```
The `delegate(object o){..}` tells the compiler to package up whatever is inside the brackets as an object to be executed later, in this case when `OnLogin` is fired. Without the `delegate()` statement, the compiler would think you are tying to execute an action in the middle of an assignemnt statement and give you errors.
73,029
<p>I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project.</p> <p>That's why I need to serve servlets and html (login.html) under the same context to make authentication work. I don't want to secure the hole application since different context should need different roles. The jetty javadoc states that a ContextHandlerCollection can handle different handlers for one context but I don't get it to work. My sample ignoring the authentication stuff will not work, why?</p> <pre><code>ContextHandlerCollection contexts = new ContextHandlerCollection(); // serve html Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS); ctxADocs.setResourceBase("d:\\tmp\\ctxA"); ServletHolder ctxADocHolder= new ServletHolder(); ctxADocHolder.setInitParameter("dirAllowed", "false"); ctxADocHolder.setServlet(new DefaultServlet()); ctxADocs.addServlet(ctxADocHolder, "/"); // serve a sample servlet Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS); ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda"); ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/"); contexts.setHandlers(new Handler[]{ctxA, ctxADocs}); // end of snippet </code></pre> <p>Any helpful thought is welcome!</p> <p>Thanks.</p> <p>Okami</p>
[ { "answer_id": 91072, "author": "Eduard Wirch", "author_id": 17428, "author_profile": "https://Stackoverflow.com/users/17428", "pm_score": 1, "selected": false, "text": "<p>Use the web application descriptor:</p>\n\n<p>Paste this in to your web.xml:</p>\n\n<pre><code>&lt;login-config&gt;...
2008/09/16
[ "https://Stackoverflow.com/questions/73029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11450/" ]
I try to use the Forms-Based authentication within an embedded Jetty 6.1.7 project. That's why I need to serve servlets and html (login.html) under the same context to make authentication work. I don't want to secure the hole application since different context should need different roles. The jetty javadoc states that a ContextHandlerCollection can handle different handlers for one context but I don't get it to work. My sample ignoring the authentication stuff will not work, why? ``` ContextHandlerCollection contexts = new ContextHandlerCollection(); // serve html Context ctxADocs= new Context(contexts,"/ctxA",Context.SESSIONS); ctxADocs.setResourceBase("d:\\tmp\\ctxA"); ServletHolder ctxADocHolder= new ServletHolder(); ctxADocHolder.setInitParameter("dirAllowed", "false"); ctxADocHolder.setServlet(new DefaultServlet()); ctxADocs.addServlet(ctxADocHolder, "/"); // serve a sample servlet Context ctxA = new Context(contexts,"/ctxA",Context.SESSIONS); ctxA.addServlet(new ServletHolder(new SessionDump()), "/sda"); ctxA.addServlet(new ServletHolder(new DefaultServlet()), "/"); contexts.setHandlers(new Handler[]{ctxA, ctxADocs}); // end of snippet ``` Any helpful thought is welcome! Thanks. Okami
Finally I got it right, solution is to use latest jetty 6.1.12 rc2. I didn't check out what they changed - I'm just happy that it works now.
73,032
<p>I'd really like to handle this without monkey-patching but I haven't been able to find another option yet.</p> <p>I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example:</p> <pre><code>ordered_list = [[1, 2], [1, 1], [2, 1]] </code></pre> <p>Any suggestions?</p> <p>Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like:</p> <pre><code>ordered_list = [[1, "b"], [1, "a"], [2, "a"]] </code></pre>
[ { "answer_id": 73090, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 6, "selected": true, "text": "<p>How about:</p>\n\n<pre>\n<code>\nordered_list = [[1, \"b\"], [1, \"a\"], [2, \"a\"]]\nordered_list.sort! do |a,b|\n ...
2008/09/16
[ "https://Stackoverflow.com/questions/73032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3230/" ]
I'd really like to handle this without monkey-patching but I haven't been able to find another option yet. I have an array (in Ruby) that I need to sort by multiple conditions. I know how to use the sort method and I've used the trick on sorting using an array of options to sort by multiple conditions. However, in this case I need the first condition to sort ascending and the second to sort descending. For example: ``` ordered_list = [[1, 2], [1, 1], [2, 1]] ``` Any suggestions? Edit: Just realized I should mention that I can't easily compare the first and second values (I'm actually working with object attributes here). So for a simple example it's more like: ``` ordered_list = [[1, "b"], [1, "a"], [2, "a"]] ```
How about: ``` ordered_list = [[1, "b"], [1, "a"], [2, "a"]] ordered_list.sort! do |a,b| [a[0],b[1]] <=> [b[0], a[1]] end ```
73,037
<p>This is a 3 part question regarding embedded RegEx into SQL statements. </p> <ol> <li><p>How do you embed a RegEx expression into an Oracle PL/SQL select statement that will parse out the “DELINQUENT” string in the text string shown below?</p></li> <li><p>What is the performance impact if used within a mission critical business transaction?</p></li> <li><p>Since embedding regex into SQL was introduced in Oracle 10g and SQL Server 2005, is it considered a recommended practice?</p></li> </ol> <hr> <p>Dear Larry :</p> <p>Thank you for using ABC's alert service.</p> <p>ABC has detected a change in the status of one of your products in the state of KS. Please review the information below to determine if this status change was intended.</p> <p>ENTITY NAME: Oracle Systems, LLC</p> <p>PREVIOUS STATUS: --</p> <p>CURRENT STATUS: DELINQUENT</p> <p>As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC so that we can discontinue our services.</p> <p>Kind regards,</p> <p>Service Team 1 ABC</p> <p>--PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.--</p> <p>Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information maintained by the responsible government agency or other sources of data upon which these alerts are based.</p>
[ { "answer_id": 73084, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 0, "selected": false, "text": "<p>Why not just use INSTR (for Oracle) or CHARINDEX (for SQL Server) combined with SUBSTRING? Seems a bit more straightfo...
2008/09/16
[ "https://Stackoverflow.com/questions/73037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048/" ]
This is a 3 part question regarding embedded RegEx into SQL statements. 1. How do you embed a RegEx expression into an Oracle PL/SQL select statement that will parse out the “DELINQUENT” string in the text string shown below? 2. What is the performance impact if used within a mission critical business transaction? 3. Since embedding regex into SQL was introduced in Oracle 10g and SQL Server 2005, is it considered a recommended practice? --- Dear Larry : Thank you for using ABC's alert service. ABC has detected a change in the status of one of your products in the state of KS. Please review the information below to determine if this status change was intended. ENTITY NAME: Oracle Systems, LLC PREVIOUS STATUS: -- CURRENT STATUS: DELINQUENT As a reminder, you may contact your the ABC Team for assistance in correcting any delinquencies or, if needed, reinstating the service. Alternatively, if the system does not intend to continue to engage this state, please notify ABC so that we can discontinue our services. Kind regards, Service Team 1 ABC --PLEASE DO NOT REPLY TO THIS EMAIL. IT IS NOT A MONITORED EMAIL ACCOUNT.-- Notice: ABC Corporation cannot independently verify the timeliness, accuracy, or completeness of the public information maintained by the responsible government agency or other sources of data upon which these alerts are based.
Why would you need regular expressions here? INSTR and SUBSTR will do the job perfectly. But if you convinced you need Regex'es you can use: [REGEXP\_INSTR](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions129.htm#i1239887) [REGEXP\_REPLACE](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions130.htm#i1305521) [REGEXP\_SUBSTR](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions131.htm#i1239858) (only available in Oracle 10g and up) ``` SELECT emp_id, text FROM employee_comment WHERE REGEXP_LIKE(text,'...-....'); ```
73,039
<p>In my web application there is a process that queries data from all over the web, filters it, and saves it to the database. As you can imagine this process takes some time. My current solution is to increase the page timeout and give an AJAX progress bar to the user while it loads. This is a problem for two reasons - 1) it still takes to long and the user must wait 2) it sometimes still times out.</p> <p>I've dabbled in threading the process and have read I should async post it to a web service ("Fire and forget").</p> <p>Some references I've read:<br> - <a href="http://msdn.microsoft.com/en-us/library/ms978607.aspx#diforwc-ap02_plag_howtomultithread" rel="nofollow noreferrer">MSDN</a><br> - <a href="http://aspalliance.com/329" rel="nofollow noreferrer">Fire and Forget</a></p> <p>So my question is - what is the best method?</p> <p>UPDATE: After the user inputs their data I would like to redirect them to the results page that incrementally updates as the process is running in the background.</p>
[ { "answer_id": 73082, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 1, "selected": false, "text": "<p>I ran into this exact problem at my last job. The best way I found was to fire off an asychronous process, and notif...
2008/09/16
[ "https://Stackoverflow.com/questions/73039", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12442/" ]
In my web application there is a process that queries data from all over the web, filters it, and saves it to the database. As you can imagine this process takes some time. My current solution is to increase the page timeout and give an AJAX progress bar to the user while it loads. This is a problem for two reasons - 1) it still takes to long and the user must wait 2) it sometimes still times out. I've dabbled in threading the process and have read I should async post it to a web service ("Fire and forget"). Some references I've read: - [MSDN](http://msdn.microsoft.com/en-us/library/ms978607.aspx#diforwc-ap02_plag_howtomultithread) - [Fire and Forget](http://aspalliance.com/329) So my question is - what is the best method? UPDATE: After the user inputs their data I would like to redirect them to the results page that incrementally updates as the process is running in the background.
To avoid excessive architecture astronomy, I often [use a hidden iframe to call the long running process and stream back progress information](http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/). Coupled with something like [jsProgressBarHandler](http://www.bram.us/demo/projects/jsprogressbarhandler/), you can pretty easily create great out-of-band progress indication for longer tasks where a generic progress animation doesn't cut it. In your specific situation, you may want to use one LongRunningProcess.aspx call per task, to avoid those page timeouts. For example, call LongRunningProcess.aspx?taskID=1 to kick it off and then at the end of that task, emit a ``` document.location = "LongRunningProcess.aspx?taskID=2". ``` Ad nauseum.
73,051
<p>I need to run a stored procedure from a C# application.</p> <p>I use the following code to do so:</p> <pre><code>Process sqlcmdCall = new Process(); sqlcmdCall.StartInfo.FileName = "sqlcmd.exe"; sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\"" sqlcmdCall.Start(); sqlcmdCall.WaitForExit(); </code></pre> <p>From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).</p> <p>How can I customize these return codes?</p> <p>H.</p>
[ { "answer_id": 73108, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the comm...
2008/09/16
[ "https://Stackoverflow.com/questions/73051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12525/" ]
I need to run a stored procedure from a C# application. I use the following code to do so: ``` Process sqlcmdCall = new Process(); sqlcmdCall.StartInfo.FileName = "sqlcmd.exe"; sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\"" sqlcmdCall.Start(); sqlcmdCall.WaitForExit(); ``` From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...). How can I customize these return codes? H.
If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line. Look at `SqlConnection` and `SqlCommand` in the `System.Data.SqlClient` namespace. Once you are calling the stored procedure via `SqlCommand` you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.
73,063
<p>In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window.</p> <p>Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them?</p>
[ { "answer_id": 73120, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>If you can search for the word exactly, you can use a pair of keyboard shortcuts to do it quickly.</p>\n\n<p>Tools -> O...
2008/09/16
[ "https://Stackoverflow.com/questions/73063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12113/" ]
In Visual Studio 2005-2015 it is possible to find all lines containing certain references and display them in a "Find Results" window. Now that these result lines are displayed, is there any keyboard shortcut that would allow adding debug breakpoints to all of them?
***This answer does not work for Visual Studio 2015 or later. A more recent answer can be found [here](https://stackoverflow.com/questions/38061627/how-do-i-add-debug-breakpoints-to-lines-displayed-in-a-find-results-window-in?rq=1).*** You can do this fairly easily with a Visual Studio macro. Within Visual Studio, hit Alt-F11 to open the Macro IDE and add a new module by right-clicking on MyMacros and selecting Add|Add Module... Paste the following in the source editor: ``` Imports System Imports System.IO Imports System.Text.RegularExpressions Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports System.Diagnostics Public Module CustomMacros Sub BreakpointFindResults() Dim findResultsWindow As Window = DTE.Windows.Item(Constants.vsWindowKindFindResults1) Dim selection As TextSelection selection = findResultsWindow.Selection selection.SelectAll() Dim findResultsReader As New StringReader(selection.Text) Dim findResult As String = findResultsReader.ReadLine() Dim findResultRegex As New Regex("(?<Path>.*?)\((?<LineNumber>\d+)\):") While Not findResult Is Nothing Dim findResultMatch As Match = findResultRegex.Match(findResult) If findResultMatch.Success Then Dim path As String = findResultMatch.Groups.Item("Path").Value Dim lineNumber As Integer = Integer.Parse(findResultMatch.Groups.Item("LineNumber").Value) Try DTE.Debugger.Breakpoints.Add("", path, lineNumber) Catch ex As Exception ' breakpoints can't be added everywhere End Try End If findResult = findResultsReader.ReadLine() End While End Sub End Module ``` This example uses the results in the "Find Results 1" window; you might want to create an individual shortcut for each result window. You can create a keyboard shortcut by going to Tools|Options... and selecting **Keyboard** under the **Environment** section in the navigation on the left. Select your macro and assign any shortcut you like. You can also add your macro to a menu or toolbar by going to Tools|Customize... and selecting the **Macros** section in the navigation on the left. Once you locate your macro in the list, you can drag it to any menu or toolbar, where it its text or icon can be customized to whatever you want.
73,110
<p>For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit.</p> <p>This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?)</p> <hr/> <p>Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction.</p> <hr/> <p>@nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils.</p> <hr/> <p>@André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.</p>
[ { "answer_id": 73173, "author": "André Chalella", "author_id": 4850, "author_profile": "https://Stackoverflow.com/users/4850", "pm_score": 3, "selected": false, "text": "<p>I also made some experiments, and found that the vertical bar will always show if you enable it, and the horizontal...
2008/09/16
[ "https://Stackoverflow.com/questions/73110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1042/" ]
For a System.Windows.Forms.TextBox with Multiline=True, I'd like to only show the scrollbars when the text doesn't fit. This is a readonly textbox used only for display. It's a TextBox so that users can copy the text out. Is there anything built-in to support auto show of scrollbars? If not, should I be using a different control? Or do I need to hook TextChanged and manually check for overflow (if so, how to tell if the text fits?) --- Not having any luck with various combinations of WordWrap and Scrollbars settings. I'd like to have no scrollbars initially and have each appear dynamically only if the text doesn't fit in the given direction. --- @nobugz, thanks, that works when WordWrap is disabled. I'd prefer not to disable wordwrap, but it's the lesser of two evils. --- @André Neves, good point, and I would go that way if it was user-editable. I agree that consistency is the cardinal rule for UI intuitiveness.
Add a new class to your project and paste the code shown below. Compile. Drop the new control from the top of the toolbox onto your form. It's not quite perfect but ought to work for you. ``` using System; using System.Drawing; using System.Windows.Forms; public class MyTextBox : TextBox { private bool mScrollbars; public MyTextBox() { this.Multiline = true; this.ReadOnly = true; } private void checkForScrollbars() { bool scroll = false; int cnt = this.Lines.Length; if (cnt > 1) { int pos0 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(0)).Y; if (pos0 >= 32768) pos0 -= 65536; int pos1 = this.GetPositionFromCharIndex(this.GetFirstCharIndexFromLine(1)).Y; if (pos1 >= 32768) pos1 -= 65536; int h = pos1 - pos0; scroll = cnt * h > (this.ClientSize.Height - 6); // 6 = padding } if (scroll != mScrollbars) { mScrollbars = scroll; this.ScrollBars = scroll ? ScrollBars.Vertical : ScrollBars.None; } } protected override void OnTextChanged(EventArgs e) { checkForScrollbars(); base.OnTextChanged(e); } protected override void OnClientSizeChanged(EventArgs e) { checkForScrollbars(); base.OnClientSizeChanged(e); } } ```
73,117
<p>I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)</p> <pre> Basics: Player has a time machine. On each iteration of using the time machine, a parallel state is created, co-existing with a previous state. One of the states must complete all the objectives of the level before ending the stage. In addition, all the stages must be able to end the stage normally, without causing a state paradox (wherein they should have been able to finish the stage normally but, due to the interactions of another state, were not). </pre> <p>So, that sort of explains how the game works. You should play it a bit to really understand what my problem is. <br /></p> <p>I'm thinking a good way to solve this would be to use linked lists to store each state, which will probably either be a hash map, based on time, or a linked list that iterates based on time. I'm still unsure.<br /></p> <p>ACTUAL QUESTION:</p> <p>Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads?</p> <p>EDIT (To clarify more):<br /> OS -- Windows (since this is a hobby project, may do this in Linux later)<br /> Graphics -- 2D Language -- C++ (must be C++ -- this is practice for a course next semester)</p> <p>Q-Unanswered: SDL : OpenGL : Direct X <br /> Q-Answered: Avoid Parallel Processing <br /> Q-Answered: Use STL to implement time-step actions.<br /></p> <pre> So far from what people have said, I should: 1. Use STL to store actions. 2. Iterate through actions based on time-step. 3. Forget parallel processing -- period. (But I'd still like some pointers as to how it could be used and in what cases it should be used, since this is for practice). </pre> <p>Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?)</p>
[ { "answer_id": 73152, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 1, "selected": false, "text": "<p>I have played this game before. I don't necessarily think parallel processing is the way to go. You have shared objects ...
2008/09/16
[ "https://Stackoverflow.com/questions/73117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6128/" ]
I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself) ``` Basics: Player has a time machine. On each iteration of using the time machine, a parallel state is created, co-existing with a previous state. One of the states must complete all the objectives of the level before ending the stage. In addition, all the stages must be able to end the stage normally, without causing a state paradox (wherein they should have been able to finish the stage normally but, due to the interactions of another state, were not). ``` So, that sort of explains how the game works. You should play it a bit to really understand what my problem is. I'm thinking a good way to solve this would be to use linked lists to store each state, which will probably either be a hash map, based on time, or a linked list that iterates based on time. I'm still unsure. ACTUAL QUESTION: Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads? EDIT (To clarify more): OS -- Windows (since this is a hobby project, may do this in Linux later) Graphics -- 2D Language -- C++ (must be C++ -- this is practice for a course next semester) Q-Unanswered: SDL : OpenGL : Direct X Q-Answered: Avoid Parallel Processing Q-Answered: Use STL to implement time-step actions. ``` So far from what people have said, I should: 1. Use STL to store actions. 2. Iterate through actions based on time-step. 3. Forget parallel processing -- period. (But I'd still like some pointers as to how it could be used and in what cases it should be used, since this is for practice). ``` Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?)
What you should do is first to read and understand the "fixed time-step" game loop (Here's a good explanation: <http://www.gaffer.org/game-physics/fix-your-timestep>). Then what you do is to keep a list of list of pairs of frame counter and action. STL example: ```c++ std::list<std::list<std::pair<unsigned long, Action> > > state; ``` Or maybe a vector of lists of pairs. To create the state, for every action (player interaction) you store the frame number and what action is performed, most likely you'd get the best results if action simply was "key <X> pressed" or "key <X> released": ```c++ state.back().push_back(std::make_pair(currentFrame, VK_LEFT | KEY_PRESSED)); ``` To play back the previous states, you'd have to reset the frame counter every time the player activates the time machine and then iterate through the state list for each previous state and see if any matches the current frame. If there is, perform the action for that state. To optimize you could keep a list of iterators to where you are in each previous state-list. Here's some *pseudo-code* for that: ```c++ typedef std::list<std::pair<unsigned long, Action> > StateList; std::list<StateList::iterator> stateIteratorList; // foreach(it in stateIteratorList) { if(it->first == currentFrame) { performAction(it->second); ++it; } } ``` I hope you get the idea... Separate threads would simply complicate the matter greatly, this way you get the same result every time, which you cannot guarantee by using separate threads (can't really see how that would be implemented) or a non-fixed time-step game loop. When it comes to graphics API, I'd go with SDL as it's probably the easiest thing to get you started. You can always use OpenGL from SDL later on if you want to go 3D.
73,123
<p>Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?</p> <p>For example:</p> <pre><code>http://mywebsite.com/132483 </code></pre> <p>would be sent to:</p> <pre><code>http://mywebsite.com/scriptname.php?no=132483 </code></pre> <p>but</p> <pre><code>http://mywebsite.com/132483a or http://mywebsite.com/asdf </code></pre> <p>would be handled as a 404 error.</p> <p>I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.</p>
[ { "answer_id": 73141, "author": "Frank Wiles", "author_id": 12568, "author_profile": "https://Stackoverflow.com/users/12568", "pm_score": 0, "selected": false, "text": "<p>Yes it's possible with mod_rewrite. There are tons of good mod_rewrite tutorials online a quick Google search shoul...
2008/09/16
[ "https://Stackoverflow.com/questions/73123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12513/" ]
Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404? For example: ``` http://mywebsite.com/132483 ``` would be sent to: ``` http://mywebsite.com/scriptname.php?no=132483 ``` but ``` http://mywebsite.com/132483a or http://mywebsite.com/asdf ``` would be handled as a 404 error. I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.
``` <IfModule mod_rewrite.c> RewriteEngine on RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L] </IfModule> ``` To preserve the clean URL ``` http://mywebsite.com/132483 ``` while serving scriptname.php use only [L]. Using [R=301] will redirect you to your scriptname.php?no=xxx You may find this useful <http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/>
73,128
<p>We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates the FileSystemWatcher: </p> <pre><code>if (this.fileWatcher == null) { this.fileWatcher = new FileSystemWatcher(); } this.fileWatcher.BeginInit(); this.fileWatcher.IncludeSubdirectories = true; this.fileWatcher.Path = project.Directory; this.fileWatcher.EnableRaisingEvents = true; this.fileWatcher.NotifyFilter = NotifyFilters.Attributes; this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args) { FileWatcherFileChanged(args); }; this.fileWatcher.EndInit(); </code></pre> <p>The way this is being used is to update the state image of a TreeNode object (adjusted slightly to remove business specific information):</p> <pre><code>private void FileWatcherFileChanged(FileSystemEventArgs args) { if (this.TreeView != null) { if (this.TreeView.InvokeRequired) { FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged); this.TreeView.Invoke(d, new object[] { args }); } else { switch (args.ChangeType) { case WatcherChangeTypes.Changed: if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0) { this.StateImageKey = GetStateImageKey(); } else { projectItemTreeNode.StateImageKey = GetStateImageKey(); } break; } } } } </code></pre> <p>Is there something we're missing or is this an anomoly from .NET3.5 SP1?</p>
[ { "answer_id": 73192, "author": "Jonathan Rupp", "author_id": 12502, "author_profile": "https://Stackoverflow.com/users/12502", "pm_score": 4, "selected": true, "text": "<p>Just a thought... Any chance there's a deadlock issue here?</p>\n\n<p>You're calling TreeView.Invoke, which is a bl...
2008/09/16
[ "https://Stackoverflow.com/questions/73128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1559/" ]
We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates the FileSystemWatcher: ``` if (this.fileWatcher == null) { this.fileWatcher = new FileSystemWatcher(); } this.fileWatcher.BeginInit(); this.fileWatcher.IncludeSubdirectories = true; this.fileWatcher.Path = project.Directory; this.fileWatcher.EnableRaisingEvents = true; this.fileWatcher.NotifyFilter = NotifyFilters.Attributes; this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args) { FileWatcherFileChanged(args); }; this.fileWatcher.EndInit(); ``` The way this is being used is to update the state image of a TreeNode object (adjusted slightly to remove business specific information): ``` private void FileWatcherFileChanged(FileSystemEventArgs args) { if (this.TreeView != null) { if (this.TreeView.InvokeRequired) { FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged); this.TreeView.Invoke(d, new object[] { args }); } else { switch (args.ChangeType) { case WatcherChangeTypes.Changed: if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0) { this.StateImageKey = GetStateImageKey(); } else { projectItemTreeNode.StateImageKey = GetStateImageKey(); } break; } } } } ``` Is there something we're missing or is this an anomoly from .NET3.5 SP1?
Just a thought... Any chance there's a deadlock issue here? You're calling TreeView.Invoke, which is a blocking call. If a filesystem change happens just as you're clicking whatever button causes the FileSystemWatcher.Dispose() call, your FileWatcherFileChanged method will get called on a background thread and call TreeView.Invoke, which will block until your form thread can process the Invoke request. However, your form thread would be calling FileSystemWatcher.Dispose(), which probably doesn't return until all pending change requests are processed. Try changing the .Invoke to .BeginInvoke and see if that helps. That may help point you in the right direction. Of course, it could also be a .NET 3.5SP1 issue. I'm just speculating here based on the code you provided.
73,134
<p>I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array <code>new</code> thus:</p> <pre class="lang-cpp prettyprint-override"><code>STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize]; </code></pre> <p>Later on however the memory is freed using a <code>delete</code> call:</p> <pre class="lang-cpp prettyprint-override"><code>delete pStruct; </code></pre> <p>Will this mix of array <code>new[]</code> and non-array <code>delete</code> cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use <code>malloc</code> and <code>free</code> instead?</p>
[ { "answer_id": 73157, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 0, "selected": false, "text": "<p>Yes that may, since your allocating with new[] but deallocating with delelte, yes malloc/free is safer here, but in c+...
2008/09/16
[ "https://Stackoverflow.com/questions/73134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
I have been working on some legacy C++ code that uses variable length structures (TAPI), where the structure size will depend on variable length strings. The structures are allocated by casting array `new` thus: ```cpp STRUCT* pStruct = (STRUCT*)new BYTE[sizeof(STRUCT) + nPaddingSize]; ``` Later on however the memory is freed using a `delete` call: ```cpp delete pStruct; ``` Will this mix of array `new[]` and non-array `delete` cause a memory leak or would it depend on the compiler? Would I be better off changing this code to use `malloc` and `free` instead?
Technically I believe it could cause a problem with mismatched allocators, though in practice I don't know of any compiler that would not do the right thing with this example. More importantly if `STRUCT` where to have (or ever be given) a destructor then it would invoke the destructor without having invoked the corresponding constructor. Of course, if you know where pStruct came from why not just cast it on delete to match the allocation: ``` delete [] (BYTE*) pStruct; ```
73,162
<p>Is there an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with?</p>
[ { "answer_id": 73203, "author": "Abe Heidebrecht", "author_id": 9268, "author_profile": "https://Stackoverflow.com/users/9268", "pm_score": 2, "selected": false, "text": "<p>The FlashWindowEx Win32 API is the call used to do this. The documentation for it is at:\n<a href=\"http://msdn.mi...
2008/09/16
[ "https://Stackoverflow.com/questions/73162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6896/" ]
Is there an API call in .NET or a native DLL that I can use to create similar behaviour as Windows Live Messenger when a response comes from someone I chat with?
FlashWindowEx is the way to go. See [here for MSDN documentation](http://msdn.microsoft.com/en-us/library/ms679347%28VS.85%29.aspx) ``` [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool FlashWindowEx(ref FLASHWINFO pwfi); [StructLayout(LayoutKind.Sequential)] public struct FLASHWINFO { public UInt32 cbSize; public IntPtr hwnd; public UInt32 dwFlags; public UInt32 uCount; public UInt32 dwTimeout; } public const UInt32 FLASHW_ALL = 3; ``` Calling the Function: ``` FLASHWINFO fInfo = new FLASHWINFO(); fInfo.cbSize = Convert.ToUInt32(Marshal.SizeOf(fInfo)); fInfo.hwnd = hWnd; fInfo.dwFlags = FLASHW_ALL; fInfo.uCount = UInt32.MaxValue; fInfo.dwTimeout = 0; FlashWindowEx(ref fInfo); ``` This was shamelessly plugged from [Pinvoke.net](http://pinvoke.net/default.aspx/user32/FlashWindowEx.html)
73,198
<p>When using Linq to SQL and stored procedures, the class generated to describe the proc's result set uses char properties to represent char(1) columns in the SQL proc. I'd rather these be strings - is there any easy way to make this happen?</p>
[ { "answer_id": 73237, "author": "Glenn Slaven", "author_id": 2975, "author_profile": "https://Stackoverflow.com/users/2975", "pm_score": -1, "selected": false, "text": "<p>Not sure why you'd want to do that. The underlying data type can't store more than one char, by representing it as ...
2008/09/16
[ "https://Stackoverflow.com/questions/73198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12260/" ]
When using Linq to SQL and stored procedures, the class generated to describe the proc's result set uses char properties to represent char(1) columns in the SQL proc. I'd rather these be strings - is there any easy way to make this happen?
You could modify the {database}.designer.cs file. I don't have one handy to check, but I believe it's fairly straight forward --- you'll just have to plow through a lot of code, and remember to re-apply the change if you ever regenerate it. Alternately, you could create your own class and handle it in the select. For example, given the LINQ generated class: ``` class MyTable { int MyNum {get; set;} int YourNum {get; set;} char OneChar {get; set;} } ``` you could easily create: ``` class MyFixedTable { int MyNum {get; set;} int YourNum {get; set;} string OneChar {get; set;} public MyFixedTable(MyTable t) { this,MyNum = t.MyNum; this.YourNum = t.YourNum; this.OneChar = new string(t.OneChar, 1); } } ``` Then instead of writing: ``` var q = from t in db.MyTable select t; ``` write ``` var q = from t in db.MyTable select new MyFixTable(t); ```
73,227
<p>I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.</p>
[ { "answer_id": 73249, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>Well, the really oversimplified version is that a lambda is just shorthand for an anonymous function. A delegate c...
2008/09/16
[ "https://Stackoverflow.com/questions/73227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1538/" ]
I get asked this question a lot and I thought I'd solicit some input on how to best describe the difference.
They are actually two very different things. "Delegate" is actually the name for a variable that holds a reference to a method or a lambda, and a lambda is a method without a permanent name. Lambdas are very much like other methods, except for a couple subtle differences. 1. A normal method is defined in a ["statement"](http://en.wikipedia.org/wiki/Statement_(programming)) and tied to a permanent name, whereas a lambda is defined "on the fly" in an ["expression"](http://en.wikipedia.org/wiki/Expression_(programming)) and has no permanent name. 2. Some lambdas can be used with .NET expression trees, whereas methods cannot. A delegate is defined like this: ``` delegate Int32 BinaryIntOp(Int32 x, Int32 y); ``` A variable of type BinaryIntOp can have either a method or a labmda assigned to it, as long as the signature is the same: two Int32 arguments, and an Int32 return. A lambda might be defined like this: ``` BinaryIntOp sumOfSquares = (a, b) => a*a + b*b; ``` Another thing to note is that although the generic Func and Action types are often considered "lambda types", they are just like any other delegates. The nice thing about them is that they essentially define a name for any type of delegate you might need (up to 4 parameters, though you can certainly add more of your own). So if you are using a wide variety of delegate types, but none more than once, you can avoid cluttering your code with delegate declarations by using Func and Action. Here is an illustration of how Func and Action are "not just for lambdas": ``` Int32 DiffOfSquares(Int32 x, Int32 y) { return x*x - y*y; } Func<Int32, Int32, Int32> funcPtr = DiffOfSquares; ``` Another useful thing to know is that delegate types (not methods themselves) with the same signature but different names will not be implicitly casted to each other. This includes the Func and Action delegates. However if the signature is identical, you can explicitly cast between them. Going the extra mile.... In C# functions are flexible, with the use of lambdas and delegates. But C# does not have "first-class functions". You can use a function's name assigned to a delegate variable to essentially create an object representing that function. But it's really a compiler trick. If you start a statement by writing the function name followed by a dot (i.e. try to do member access on the function itself) you'll find there are no members there to reference. Not even the ones from Object. This prevents the programmer from doing useful (and potentially dangerous of course) things such as adding extension methods that can be called on any function. The best you can do is extend the Delegate class itself, which is surely also useful, but not quite as much. Update: Also see [Karg's answer](https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#73448) illustrating the difference between anonymous delegates vs. methods & lambdas. Update 2: [James Hart](https://stackoverflow.com/questions/73227/what-is-the-difference-between-lambdas-and-delegates-in-the-net-framework#74414) makes an important, though very technical, note that lambdas and delegates are not .NET entities (i.e. the CLR has no concept of a delegate or lambda), but rather they are framework and language constructs.
73,286
<p>I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?</p>
[ { "answer_id": 73363, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 3, "selected": false, "text": "<p>You can't do this.</p>\n\n<p>If you want to output to the debugger's output window, call OutputDebugString.</p>\n\n<p...
2008/09/16
[ "https://Stackoverflow.com/questions/73286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1265473/" ]
I created a C++ console app and just want to capture the cout/cerr statements in the Output Window within the Visual Studio 2005 IDE. I'm sure this is just a setting that I'm missing. Can anyone point me in the right direction?
I've finally implemented this, so I want to share it with you: ``` #include <vector> #include <iostream> #include <windows.h> #include <boost/iostreams/stream.hpp> #include <boost/iostreams/tee.hpp> using namespace std; namespace io = boost::iostreams; struct DebugSink { typedef char char_type; typedef io::sink_tag category; std::vector<char> _vec; std::streamsize write(const char *s, std::streamsize n) { _vec.assign(s, s+n); _vec.push_back(0); // we must null-terminate for WINAPI OutputDebugStringA(&_vec[0]); return n; } }; int main() { typedef io::tee_device<DebugSink, std::streambuf> TeeDevice; TeeDevice device(DebugSink(), *cout.rdbuf()); io::stream_buffer<TeeDevice> buf(device); cout.rdbuf(&buf); cout << "hello world!\n"; cout.flush(); // you may need to flush in some circumstances } ``` **BONUS TIP:** If you write: ``` X:\full\file\name.txt(10) : message ``` to the output window and then double-click on it, then Visual Studio will jump to the given file, line 10, and display the 'message' in status bar. It's *very* useful.
73,308
<p>I am trying to implement a request to an unreliable server. The request is a nice to have, but not 100% required for my perl script to successfully complete. The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed. Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever. What is the best way to enforce an absolute timeout on a request? </p> <p>FYI, this is not an DNS problem. The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time. For testing purposes, we've essentially put a while(1) {} line in the servers response handler. </p> <p>Currently, the code looks like so:</p> <pre><code>my $ua = LWP::UserAgent-&gt;new; ua-&gt;timeout(5); $ua-&gt;cookie_jar({}); my $req = HTTP::Request-&gt;new(POST =&gt; "http://$host:$port/auth/login"); $req-&gt;content_type('application/x-www-form-urlencoded'); $req-&gt;content("login[user]=$username&amp;login[password]=$password"); # This line never returns $res = $ua-&gt;request($req); </code></pre> <p>I've tried using signals to trigger a timeout, but that does not seem to work. </p> <pre><code>eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm(1); $res = $ua-&gt;request($req); alarm(0); }; # This never runs print "here\n"; </code></pre> <p>The final answer I'm going to use was proposed by someone offline, but I'll mention it here. For some reason, SigAction works while $SIG(ALRM) does not. Still not sure why, but this has been tested to work. Here are two working versions:</p> <pre><code># Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request sub ua_request_with_timeout { my $ua = $_[0]; my $req = $_[1]; # Get whatever timeout is set for LWP and use that to # enforce a maximum timeout per request in case of server # deadlock. (This has happened.) use Sys::SigAction qw( timeout_call ); our $res = undef; if( timeout_call( 5, sub {$res = $ua-&gt;request($req);}) ) { return HTTP::Response-&gt;new( 408 ); #408 is the HTTP timeout } else { return $res; } } sub ua_request_with_timeout2 { print "ua_request_with_timeout\n"; my $ua = $_[0]; my $req = $_[1]; # Get whatever timeout is set for LWP and use that to # enforce a maximum timeout per request in case of server # deadlock. (This has happened.) my $timeout_for_client = $ua-&gt;timeout() - 2; our $socket_has_timedout = 0; use POSIX; sigaction SIGALRM, new POSIX::SigAction( sub { $socket_has_timedout = 1; die "alarm timeout"; } ) or die "Error setting SIGALRM handler: $!\n"; my $res = undef; eval { alarm ($timeout_for_client); $res = $ua-&gt;request($req); alarm(0); }; if ( $socket_has_timedout ) { return HTTP::Response-&gt;new( 408 ); #408 is the HTTP timeout } else { return $res; } } </code></pre>
[ { "answer_id": 73351, "author": "Alex Fort", "author_id": 12624, "author_profile": "https://Stackoverflow.com/users/12624", "pm_score": 0, "selected": false, "text": "<p>From what I understand, the timeout property doesn't take into account DNS timeouts. It's possible that you could make...
2008/09/16
[ "https://Stackoverflow.com/questions/73308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12628/" ]
I am trying to implement a request to an unreliable server. The request is a nice to have, but not 100% required for my perl script to successfully complete. The problem is that the server will occasionally deadlock (we're trying to figure out why) and the request will never succeed. Since the server thinks it is live, it keeps the socket connection open thus LWP::UserAgent's timeout value does us no good what-so-ever. What is the best way to enforce an absolute timeout on a request? FYI, this is not an DNS problem. The deadlock has something to do with a massive number of updates hitting our Postgres database at the same time. For testing purposes, we've essentially put a while(1) {} line in the servers response handler. Currently, the code looks like so: ``` my $ua = LWP::UserAgent->new; ua->timeout(5); $ua->cookie_jar({}); my $req = HTTP::Request->new(POST => "http://$host:$port/auth/login"); $req->content_type('application/x-www-form-urlencoded'); $req->content("login[user]=$username&login[password]=$password"); # This line never returns $res = $ua->request($req); ``` I've tried using signals to trigger a timeout, but that does not seem to work. ``` eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm(1); $res = $ua->request($req); alarm(0); }; # This never runs print "here\n"; ``` The final answer I'm going to use was proposed by someone offline, but I'll mention it here. For some reason, SigAction works while $SIG(ALRM) does not. Still not sure why, but this has been tested to work. Here are two working versions: ``` # Takes a LWP::UserAgent, and a HTTP::Request, returns a HTTP::Request sub ua_request_with_timeout { my $ua = $_[0]; my $req = $_[1]; # Get whatever timeout is set for LWP and use that to # enforce a maximum timeout per request in case of server # deadlock. (This has happened.) use Sys::SigAction qw( timeout_call ); our $res = undef; if( timeout_call( 5, sub {$res = $ua->request($req);}) ) { return HTTP::Response->new( 408 ); #408 is the HTTP timeout } else { return $res; } } sub ua_request_with_timeout2 { print "ua_request_with_timeout\n"; my $ua = $_[0]; my $req = $_[1]; # Get whatever timeout is set for LWP and use that to # enforce a maximum timeout per request in case of server # deadlock. (This has happened.) my $timeout_for_client = $ua->timeout() - 2; our $socket_has_timedout = 0; use POSIX; sigaction SIGALRM, new POSIX::SigAction( sub { $socket_has_timedout = 1; die "alarm timeout"; } ) or die "Error setting SIGALRM handler: $!\n"; my $res = undef; eval { alarm ($timeout_for_client); $res = $ua->request($req); alarm(0); }; if ( $socket_has_timedout ) { return HTTP::Response->new( 408 ); #408 is the HTTP timeout } else { return $res; } } ```
You might try [LWPx::ParanoidAgent](http://search.cpan.org/%7Ebradfitz/LWPx-ParanoidAgent-1.02/lib/LWPx/ParanoidAgent.pm), a subclass of LWP::UserAgent which is more cautious about how it interacts with remote webservers. Among other things, it allows you to specify a global timeout. It was developed by Brad Fitzpatrick as part of the LiveJournal project.
73,320
<p>How do I set the column which has the header sort glyph, and its direction, in a .NET 2.0 WinForms ListView?</p> <h2>Bump</h2> <p>The listview is .net is not a managed control, it is a very thin wrapper around the Win32 ListView common control. It's not even a very good wrapper - it doesn't expose all the features of the real listview.</p> <p>The Win32 listview common control supports drawing itself with themes. One of the themed elements is the header sort arrow. Windows Explorer's listview common control knows how to draw one of its columns with that theme element.</p> <ul> <li>does the Win32 listview support specifying which column has what sort order? </li> <li>does the Win32 header control that the listview internally uses support specifying which column has what sort order? </li> <li>does the win32 header control support custom drawing, so I can draw the header sort glyph myself?</li> <li>does the win32 listview control support custom header drawing, so I can draw the header sort glyph myself?</li> <li>does the .NET ListView control support custom header drawing, so I can draw the header sort glyph myself?</li> </ul>
[ { "answer_id": 73331, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 1, "selected": false, "text": "<p>I use unicode arrow characters in the title of the column and make the header a linkbutton.</p>\n" }, { "a...
2008/09/16
[ "https://Stackoverflow.com/questions/73320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
How do I set the column which has the header sort glyph, and its direction, in a .NET 2.0 WinForms ListView? Bump ---- The listview is .net is not a managed control, it is a very thin wrapper around the Win32 ListView common control. It's not even a very good wrapper - it doesn't expose all the features of the real listview. The Win32 listview common control supports drawing itself with themes. One of the themed elements is the header sort arrow. Windows Explorer's listview common control knows how to draw one of its columns with that theme element. * does the Win32 listview support specifying which column has what sort order? * does the Win32 header control that the listview internally uses support specifying which column has what sort order? * does the win32 header control support custom drawing, so I can draw the header sort glyph myself? * does the win32 listview control support custom header drawing, so I can draw the header sort glyph myself? * does the .NET ListView control support custom header drawing, so I can draw the header sort glyph myself?
In case someone needs a quick solution (it draws up/down arrow at the beginning of column header text): **ListViewExtensions.cs:** ``` public static class ListViewExtensions { public static void DrawSortArrow(this ListView listView, SortOrder sortOrder, int colIndex) { string upArrow = "▲ "; string downArrow = "▼ "; foreach (ColumnHeader ch in listView.Columns) { if (ch.Text.Contains(upArrow)) ch.Text = ch.Text.Replace(upArrow, string.Empty); else if (ch.Text.Contains(downArrow)) ch.Text = ch.Text.Replace(downArrow, string.Empty); } if (sortOrder == SortOrder.Ascending) listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, downArrow); else listView.Columns[colIndex].Text = listView.Columns[colIndex].Text.Insert(0, upArrow); } } ``` **Usage:** ``` private void lstOffers_ColumnClick(object sender, ColumnClickEventArgs e) { lstOffers.DrawSortArrow(SortOrder.Descending, e.Column); } ```
73,380
<p>I'm running some c# .net pages with various gridviews. If I ever leave any of them alone in a web browser for an extended period of time (usually overnight), I get the following error when I click any element on the page.</p> <p>I'm not really sure where to start dealing with the problem. I don't mind resetting the page if it's viewstate has expired, but throwing an error is unacceptable!</p> <pre><code> Error: The state information is invalid for this page and might be corrupted. Target: Void ThrowError(System.Exception, System.String, System.String, Boolean) Data: System.Collections.ListDictionaryInternal Inner: System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 66.35.180.246 Port: 1799 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0 ViewState: (**Very long Gibberish Omitted!**) Offending URL: (**Omitted**) Source: System.Web Message: The state information is invalid for this page and might be corrupted. Stack trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) </code></pre>
[ { "answer_id": 73402, "author": "MrHinsh - Martin Hinshelwood", "author_id": 11799, "author_profile": "https://Stackoverflow.com/users/11799", "pm_score": 1, "selected": false, "text": "<p>You can remove this error completely by saving your view state to a database and only cleaning with...
2008/09/16
[ "https://Stackoverflow.com/questions/73380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12382/" ]
I'm running some c# .net pages with various gridviews. If I ever leave any of them alone in a web browser for an extended period of time (usually overnight), I get the following error when I click any element on the page. I'm not really sure where to start dealing with the problem. I don't mind resetting the page if it's viewstate has expired, but throwing an error is unacceptable! ``` Error: The state information is invalid for this page and might be corrupted. Target: Void ThrowError(System.Exception, System.String, System.String, Boolean) Data: System.Collections.ListDictionaryInternal Inner: System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 66.35.180.246 Port: 1799 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9) Gecko/2008052906 Firefox/3.0 ViewState: (**Very long Gibberish Omitted!**) Offending URL: (**Omitted**) Source: System.Web Message: The state information is invalid for this page and might be corrupted. Stack trace: at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ClientScriptManager.EnsureEventValidationFieldLoaded() at System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) at System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) at System.Web.UI.WebControls.DropDownList.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.WebControls.DropDownList.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) ```
That is odd as the ViewState is stored as a string in the webpage itself. So I do not see how an extended period of time would cause that error. Perhaps one or more objects on the page have been garbage collected or the application reset, so the viewstate is referencing old controls instead of the controls created when the application restarted. Whatever the case, I feel your pain, these errors are never pleasant to debug, and I have no easy answer as to how to find the problem other than perhaps studying [how ViewState works](http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx)
73,385
<p>Is there an easy way to convert a string from csv format into a string[] or list? </p> <p>I can guarantee that there are no commas in the data.</p>
[ { "answer_id": 73390, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 0, "selected": false, "text": "<pre><code>CsvString.split(',');\n</code></pre>\n" }, { "answer_id": 73394, "author": "Timothy Carter", ...
2008/09/16
[ "https://Stackoverflow.com/questions/73385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12653/" ]
Is there an easy way to convert a string from csv format into a string[] or list? I can guarantee that there are no commas in the data.
``` string[] splitString = origString.Split(','); ``` *(Following comment not added by original answerer)* **Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.**
73,447
<p>What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()?</p>
[ { "answer_id": 73503, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 4, "selected": true, "text": "<p>How about this:</p>\n\n<pre><code>master.sys.fn_varbintohexstr(@binvalue)\n</code></pre>\n" }, { "answer_id": ...
2008/09/16
[ "https://Stackoverflow.com/questions/73447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366182/" ]
What's the most efficient way to convert the output of this function from a varbinary() to a a varchar()?
How about this: ``` master.sys.fn_varbintohexstr(@binvalue) ```
73,456
<p>I have a weird problem with a dropdownbox selectedIndex always being set to 0 upon postback. I'm not accidentally rebinding it in my code. In fact I've placed a breakpoint at the very first line of the page_load event and the value is already set to zero. The dropdown is in the master page of my project, I don't know if that makes a difference. I'm not referencing the control in my content holder. </p> <p>If I set my autoPostBack = 'true' the page works fine. I don't have to change any code and the selectedIndex is maintained. I have also tried setting enableViewState on and off and it doesn't make a difference. At this point I'm grasping at straws to figure out what's going on. I've never had this problem before.</p> <p>Here is the code in my page_load event.</p> <pre><code> If CartEstablished Then txtCustNum.Visible = False btnCustSearch.Visible = False lblCustNum.Visible = True ddlSalesType.Visible = False lblSalesType.Visible = True ddlTerms.Visible = False lblTerms.Visible = True lblTerms.Text = TermsDescription Else txtCustNum.Visible = True btnCustSearch.Visible = True lblCustNum.Visible = False lblSalesType.Visible = False ddlSalesType.Visible = True lblTerms.Visible = False ddlTerms.Visible = True End If If Page.IsPostBack Then GetUIValues() Else LoadTermCodes() End If </code></pre> <p>The LoadTermCodes is where I bind the dropdownlist that is causing me problems.</p>
[ { "answer_id": 73501, "author": "Gilligan", "author_id": 12356, "author_profile": "https://Stackoverflow.com/users/12356", "pm_score": 1, "selected": false, "text": "<p>Are you sure you are doing a postback and not a refresh? It is hard to help you without more context into the problem o...
2008/09/16
[ "https://Stackoverflow.com/questions/73456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288/" ]
I have a weird problem with a dropdownbox selectedIndex always being set to 0 upon postback. I'm not accidentally rebinding it in my code. In fact I've placed a breakpoint at the very first line of the page\_load event and the value is already set to zero. The dropdown is in the master page of my project, I don't know if that makes a difference. I'm not referencing the control in my content holder. If I set my autoPostBack = 'true' the page works fine. I don't have to change any code and the selectedIndex is maintained. I have also tried setting enableViewState on and off and it doesn't make a difference. At this point I'm grasping at straws to figure out what's going on. I've never had this problem before. Here is the code in my page\_load event. ``` If CartEstablished Then txtCustNum.Visible = False btnCustSearch.Visible = False lblCustNum.Visible = True ddlSalesType.Visible = False lblSalesType.Visible = True ddlTerms.Visible = False lblTerms.Visible = True lblTerms.Text = TermsDescription Else txtCustNum.Visible = True btnCustSearch.Visible = True lblCustNum.Visible = False lblSalesType.Visible = False ddlSalesType.Visible = True lblTerms.Visible = False ddlTerms.Visible = True End If If Page.IsPostBack Then GetUIValues() Else LoadTermCodes() End If ``` The LoadTermCodes is where I bind the dropdownlist that is causing me problems.
Are you sure you are doing a postback and not a refresh? It is hard to help you without more context into the problem or a chunk of the code.
73,467
<p>I've got a custom handler applied to a class (using the Policy Injection Application Block in entlib 4) and I would like to know whether the input method is a property when Invoke is called. Following is what my handler looks like.</p> <pre><code>[ConfigurationElementType(typeof(MyCustomHandlerData))] public class MyCustomHandler : ICallHandler { public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (input.MethodBase.IsPublic &amp;&amp; (input.MethodBase.Name.Contains("get_") || input.MethodBase.Name.Contains("set_"))) { Console.WriteLine("MyCustomHandler Invoke called with input of {0}", input.MethodBase.Name); } return getNext().Invoke(input, getNext); } public int Order { get; set; } } </code></pre> <p>As you can see from my code sample, the best way I've thought of so far is by parsing the method name. Isn't there a better way to do this?</p>
[ { "answer_id": 73747, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 0, "selected": false, "text": "<p>You could check the IsSpecialName property; it will be true for property getters and setters. However, it will als...
2008/09/16
[ "https://Stackoverflow.com/questions/73467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6542/" ]
I've got a custom handler applied to a class (using the Policy Injection Application Block in entlib 4) and I would like to know whether the input method is a property when Invoke is called. Following is what my handler looks like. ``` [ConfigurationElementType(typeof(MyCustomHandlerData))] public class MyCustomHandler : ICallHandler { public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { if (input.MethodBase.IsPublic && (input.MethodBase.Name.Contains("get_") || input.MethodBase.Name.Contains("set_"))) { Console.WriteLine("MyCustomHandler Invoke called with input of {0}", input.MethodBase.Name); } return getNext().Invoke(input, getNext); } public int Order { get; set; } } ``` As you can see from my code sample, the best way I've thought of so far is by parsing the method name. Isn't there a better way to do this?
You can also check IsSpecialName is true. this will be true in a property (amongst other things) At the il level the methods are exposed as follows (using Environment.ExitCode as example): ``` .method public hidebysig specialname static int32 get_ExitCode() cil managed .method public hidebysig specialname static void set_ExitCode(int32 'value') cil managed ``` If you wanted to get fancy you could verify after extracting the name that said property exists but to be honest ``` if (m.IsSpecialName && (m.Attributes & MethodAttributes.HideBySig) != 0)) ``` as well as starts with get\_ or set\_ then you should be good even for people using nasty names (faking the hidebysig is easy enough, faking the IsSpecialName would be very tricky) Nothing is guaranteed though. Someone could emit a class with a set\_Foo method that looked just like a real set method but actually wasn't a set on a read only property. Unless you check whether the property CanRead/CanWrite as well. This strikes me as madness for you though you aren't expecting deliberate circumvention. A simple utility/extension method on MethodInfo which did this logic wouldn't be too hard and including IsSpecialName would almost certainly cover all your needs.
73,468
<p>I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do.</p> <p><strong>Is there a way of doing a non-blocking pthread_join? Some sort of timed join would be good too.</strong></p> <p>something like this:</p> <pre> foreach thread do nb_pthread_join(); if still running pthread_cancel(); </pre> <p>I can think more cases where a a non-bloking join would be useful.</p> <p>As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.</p>
[ { "answer_id": 73481, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 0, "selected": false, "text": "<p>You could push a byte into a pipe opened as non-blocking to signal to the other thread when its done, then use a non-block...
2008/09/16
[ "https://Stackoverflow.com/questions/73468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12661/" ]
I'm coding the shutdown of a multithreaded server.If everything goes as it should all the threads exit by their own, but there's a small chance that a thread gets stuck.In this case it would be convenient to have a non-blocking join so I could do. **Is there a way of doing a non-blocking pthread\_join? Some sort of timed join would be good too.** something like this: ``` foreach thread do nb_pthread_join(); if still running pthread_cancel(); ``` I can think more cases where a a non-bloking join would be useful. As it seems there is no such a function so I have already coded a workaround, but it's not as simple as I would like.
As others have pointed out there is not a non-blocking pthread\_join available in the standard pthread libraries. However, given your stated problem (trying to guarantee that all of your threads have exited on program shutdown) such a function is not needed. You can simply do this: ``` int killed_threads = 0; for(i = 0; i < num_threads; i++) { int return = pthread_cancel(threads[i]); if(return != ESRCH) killed_threads++; } if(killed_threads) printf("%d threads did not shutdown properly\n", killed_threads) else printf("All threads exited successfully"); ``` There is nothing wrong with calling pthread\_cancel on all of your threads (terminated or not) so calling that for all of your threads will not block and will guarantee thread exit (clean or not). That should qualify as a 'simple' workaround.
73,471
<p>I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?</p>
[ { "answer_id": 73636, "author": "Clinton Pierce", "author_id": 8173, "author_profile": "https://Stackoverflow.com/users/8173", "pm_score": 0, "selected": false, "text": "<p>You want to use the DataGridView RowPostPaint method. Let the framework draw the row, and afterwards go back and c...
2008/09/16
[ "https://Stackoverflow.com/questions/73471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ]
I have an editable DataGridView with SelectionMode set to FullRowSelect (so the whole row is highlighted when the user clicks on any cell). However I would like the cell that currently has focus to be highlighted with a different back color (so the user can clearly see what cell they are about to edit). How can I do this (I do not want to change the SelectionMode)?
I figured out a better way of doing this, using the CellFormatting event: ``` Private Sub uxContacts_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles uxContacts.CellFormatting If uxContacts.CurrentCell IsNot Nothing Then If e.RowIndex = uxContacts.CurrentCell.RowIndex And e.ColumnIndex = uxContacts.CurrentCell.ColumnIndex Then e.CellStyle.SelectionBackColor = Color.SteelBlue Else e.CellStyle.SelectionBackColor = uxContacts.DefaultCellStyle.SelectionBackColor End If End If End Sub ```
73,474
<p>I am having a frequent problems with my web hosting (its shared)</p> <p>I am not able to delete or change permission for a particular directory. The response is,</p> <pre><code>Cannot delete. Directory may not be empty </code></pre> <p>I checked the permissions and it looks OK. There are 100's of files in this folder which I don't want. </p> <p>I contacted my support and they solved it saying it was permission issue. But it reappeared. Any suggestions?</p> <p>The server is Linux.</p>
[ { "answer_id": 73529, "author": "Ram Prasad", "author_id": 6361, "author_profile": "https://Stackoverflow.com/users/6361", "pm_score": 0, "selected": false, "text": "<p>This could also be because your FTP client might not be showing the hidden files (like cache, or any hiddn files that y...
2008/09/16
[ "https://Stackoverflow.com/questions/73474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12178/" ]
I am having a frequent problems with my web hosting (its shared) I am not able to delete or change permission for a particular directory. The response is, ``` Cannot delete. Directory may not be empty ``` I checked the permissions and it looks OK. There are 100's of files in this folder which I don't want. I contacted my support and they solved it saying it was permission issue. But it reappeared. Any suggestions? The server is Linux.
You can't **rmdir** a directory with files in it. You must first **rm** all files and subdirectories. Many times, the easiest solution is: ``` $ rm -rf old_directory ``` It's entirely possible that some of the files or subdirectories have permission limitations that might prevent them from being removed. Occasionally, this can be solved with: ``` $ chmod -R +w old_directory ``` But I suspect that's what your support people did earlier.
73,476
<p>We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?</p>
[ { "answer_id": 73483, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 3, "selected": true, "text": "<p>No, it isn't true, you can encode XML to any Writer in Java using something similar to:</p>\n\n<pre><code>char[] ch;\n...
2008/09/16
[ "https://Stackoverflow.com/questions/73476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9254/" ]
We use SAX to parse XML because it does not require the entire XML document to be read into memory in order to parse a single value. I read many articles that insisted SAX can only be used to parse/decode XML and not create it. Is this true?
No, it isn't true, you can encode XML to any Writer in Java using something similar to: ``` char[] ch; AttributesImpl atts = new AttributesImpl(); Writer writer = new StringWriter(); StreamResult streamResult = new StreamResult(writer); SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); // SAX2.0 ContentHandler TransformerHandler transformerHandler = tf.newTransformerHandler(); Transformer serializer = transformerHandler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "nodes.dtd"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); transformerHandler.setResult(streamResult); transformerHandler.startDocument(); atts.clear(); // atts.addAttribute("", "", "xmlns", "CDATA", "http://www.example.com/nodes"); // atts.addAttribute("", "", "xmlns:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance"); // atts.addAttribute("", "", "xsi:schemaLocation", "CDATA", "/nodes.xsd"); transformerHandler.startElement("", "", "node_list", atts); // displayName element if (displayName != null) { transformerHandler.startElement("", "", "display_name", null); ch = displayName.toCharArray(); transformerHandler.characters(ch, 0, ch.length); transformerHandler.endElement("", "", "display_name"); } // nodes element transformerHandler.startElement("", "", "nodes", null); atts.clear(); atts.addAttribute("", "", "node_type", "CDATA", "sometype"); transformerHandler.startElement("", "", "node", atts); ch = node.getValue().toCharArray(); transformerHandler.startElement("", "", "value", null); transformerHandler.characters(ch, 0, ch.length); transformerHandler.endElement("", "", "value"); transformerHandler.endElement("", "", "node"); transformerHandler.endElement("", "", "nodes"); transformerHandler.endElement("", "", "node_list"); transformerHandler.endDocument(); String xml = writer.toString(); ```
73,484
<p>Basically I would like to find a way to ddo something like:</p> <pre><code>&lt;asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="&lt;%# MyProperty %&gt;"&gt;&lt;/asp:Label&gt; </code></pre> <p>I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution. (MyProperty is a string property) cheers</p>
[ { "answer_id": 73507, "author": "Akselsson", "author_id": 8862, "author_profile": "https://Stackoverflow.com/users/8862", "pm_score": 0, "selected": false, "text": "<p>Call lID.Databind() from code-behind</p>\n" }, { "answer_id": 73513, "author": "John Sheehan", "author_i...
2008/09/16
[ "https://Stackoverflow.com/questions/73484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1613872/" ]
Basically I would like to find a way to ddo something like: ``` <asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label> ``` I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution. (MyProperty is a string property) cheers
Code expressions are an option as well. These can be used inside of quotes in ASP tags, unlike standard <%= %> tags. The general syntax is: ``` <%$ resources: ResourceKey %> ``` There is a built-in expression for appSettings: ``` <%$ appSettings: AppSettingsKey %> ``` More info on this here: <http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx>
73,491
<p>I'm trying to use maven2 to build an axis2 project. My project is configured as a parent project with AAR, WAR, and EAR modules. When I run the parent project's package goal, the console shows a successful build and all of the files are created. However the AAR file generated by AAR project is not included in the generated WAR project. The AAR project is listed as a dependency of WAR project. When I explicitly run the WAR's package goal, the AAR file is then included in the WAR file.</p> <p>Why would the parent's package goal not include the necessary dependency while running the child's package goal does?</p> <p>I'm using the maven-war-plugin v2.1-alpha-2 in my war project.</p> <p>Parent POM:</p> <pre><code>&lt;parent&gt; &lt;groupId&gt;companyId&lt;/groupId&gt; &lt;artifactId&gt;build&lt;/artifactId&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.nationwide.nf&lt;/groupId&gt; &lt;artifactId&gt;parent&lt;/artifactId&gt; &lt;packaging&gt;pom&lt;/packaging&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;modules&gt; &lt;module&gt;ws-war&lt;/module&gt; &lt;module&gt;ws-aar&lt;/module&gt; &lt;module&gt;ws-ear&lt;/module&gt; &lt;/modules&gt; </code></pre> <p>AAR POM:</p> <pre><code>&lt;parent&gt; &lt;artifactId&gt;parent&lt;/artifactId&gt; &lt;groupId&gt;companyId&lt;/groupId&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;companyId&lt;/groupId&gt; &lt;artifactId&gt;ws-aar&lt;/artifactId&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;description/&gt; &lt;packaging&gt;aar&lt;/packaging&gt; &lt;dependencies&gt;...&lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;source&gt;1.5&lt;/source&gt; &lt;target&gt;1.5&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2-wsdl2code-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;configuration&gt;...&lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;goals&gt; &lt;goal&gt;wsdl2code&lt;/goal&gt; &lt;/goals&gt; &lt;id&gt;axis2-gen-sources&lt;/id&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.axis2&lt;/groupId&gt; &lt;artifactId&gt;axis2-aar-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;extensions&gt;true&lt;/extensions&gt; &lt;configuration&gt;...&lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>WAR POM:</p> <pre><code>&lt;parent&gt; &lt;artifactId&gt;parent&lt;/artifactId&gt; &lt;groupId&gt;companyId&lt;/groupId&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;companyId&lt;/groupId&gt; &lt;artifactId&gt;ws-war&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;description/&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;companyId&lt;/groupId&gt; &lt;artifactId&gt;ws-aar&lt;/artifactId&gt; &lt;type&gt;aar&lt;/type&gt; &lt;version&gt;1.0.0-SNAPSHOT&lt;/version&gt; &lt;/dependency&gt; . . . &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1-alpha-2&lt;/version&gt; &lt;configuration&gt; &lt;warName&gt;appName&lt;/warName&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p>Thanks, Joe</p>
[ { "answer_id": 89868, "author": "user11087", "author_id": 11087, "author_profile": "https://Stackoverflow.com/users/11087", "pm_score": 0, "selected": false, "text": "<p>Have you tried using the \"type\" element in your dependencies? For example:</p>\n\n<pre><code>&lt;dependency&gt;\n ...
2008/09/16
[ "https://Stackoverflow.com/questions/73491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5313/" ]
I'm trying to use maven2 to build an axis2 project. My project is configured as a parent project with AAR, WAR, and EAR modules. When I run the parent project's package goal, the console shows a successful build and all of the files are created. However the AAR file generated by AAR project is not included in the generated WAR project. The AAR project is listed as a dependency of WAR project. When I explicitly run the WAR's package goal, the AAR file is then included in the WAR file. Why would the parent's package goal not include the necessary dependency while running the child's package goal does? I'm using the maven-war-plugin v2.1-alpha-2 in my war project. Parent POM: ``` <parent> <groupId>companyId</groupId> <artifactId>build</artifactId> <version>1.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>com.nationwide.nf</groupId> <artifactId>parent</artifactId> <packaging>pom</packaging> <version>1.0.0-SNAPSHOT</version> <modules> <module>ws-war</module> <module>ws-aar</module> <module>ws-ear</module> </modules> ``` AAR POM: ``` <parent> <artifactId>parent</artifactId> <groupId>companyId</groupId> <version>1.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>companyId</groupId> <artifactId>ws-aar</artifactId> <version>1.0.0-SNAPSHOT</version> <description/> <packaging>aar</packaging> <dependencies>...</dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> <plugin> <groupId>org.apache.axis2</groupId> <artifactId>axis2-wsdl2code-maven-plugin</artifactId> <version>1.4</version> <configuration>...</configuration> <executions> <execution> <goals> <goal>wsdl2code</goal> </goals> <id>axis2-gen-sources</id> </execution> </executions> </plugin> <plugin> <groupId>org.apache.axis2</groupId> <artifactId>axis2-aar-maven-plugin</artifactId> <version>1.4</version> <extensions>true</extensions> <configuration>...</configuration> </plugin> </plugins> </build> ``` WAR POM: ``` <parent> <artifactId>parent</artifactId> <groupId>companyId</groupId> <version>1.0.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <groupId>companyId</groupId> <artifactId>ws-war</artifactId> <packaging>war</packaging> <version>1.0.0-SNAPSHOT</version> <description/> <dependencies> <dependency> <groupId>companyId</groupId> <artifactId>ws-aar</artifactId> <type>aar</type> <version>1.0.0-SNAPSHOT</version> </dependency> . . . </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.1-alpha-2</version> <configuration> <warName>appName</warName> </configuration> </plugin> </plugins> </build> ``` Thanks, Joe
I was able to get my maven build working correctly by adding the following plugin to the ws-war pom file: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <phase>process-classes</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <outputDirectory> ${project.build.directory}/${project.build.finalName}/WEB-INF/services </outputDirectory> <includeArtifactIds> ws-aar </includeArtifactIds> </configuration> </execution> </executions> </plugin> ```
73,518
<p>In Windows XP:</p> <p>How do you direct traffic to/from a particular site to a specific NIC?</p> <p>For Instance: How do I say, all connections to stackoverflow.com should use my wireless connection, while all other sites will use my ethernet?</p>
[ { "answer_id": 73545, "author": "Danimal", "author_id": 2757, "author_profile": "https://Stackoverflow.com/users/2757", "pm_score": 1, "selected": false, "text": "<p>you should be able to do it using the route command. Route add (ip address) (netmask) (gateway) metric 1</p>\n" }, { ...
2008/09/16
[ "https://Stackoverflow.com/questions/73518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2744/" ]
In Windows XP: How do you direct traffic to/from a particular site to a specific NIC? For Instance: How do I say, all connections to stackoverflow.com should use my wireless connection, while all other sites will use my ethernet?
I'm not sure if there's an easier way, but one way would be to add a route to the IP(s) of stackoverflow.com that explicitly specifies your wireless connection, using a lower metric (cost) than your default route. Running nslookup www.stackoverflow.com shows only one IP: 67.199.15.132, so the syntax would be: ``` route -p add 67.199.15.132 [your wireless gateway] metric [lower metric than default route] IF [wireless interface] ``` See the route command for more info.
73,524
<p>I have a list of addresses from a Database for which I'd like to put markers on a Yahoo Map. The <a href="http://developer.yahoo.com/maps/ajax/V3.8/index.html#YMap" rel="nofollow noreferrer"><code>addMarker()</code> method</a> on YMap takes a YGeoPoint, which requires a latitude and longitude. However, Yahoo Maps must know how to convert from addresses because <code>drawZoomAndCenter(LocationType,ZoomLevel)</code> can take an address. I could convert by using <code>drawZoomAndCenter()</code> then <code>getCenterLatLon()</code> but is there a better way, which doesn't require a draw?</p>
[ { "answer_id": 73625, "author": "Paul Reiners", "author_id": 7648, "author_profile": "https://Stackoverflow.com/users/7648", "pm_score": -1, "selected": false, "text": "<p>If you're working with U.S. addresses, you can use <a href=\"http://geocoder.us/\" rel=\"nofollow noreferrer\">geoco...
2008/09/16
[ "https://Stackoverflow.com/questions/73524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5346/" ]
I have a list of addresses from a Database for which I'd like to put markers on a Yahoo Map. The [`addMarker()` method](http://developer.yahoo.com/maps/ajax/V3.8/index.html#YMap) on YMap takes a YGeoPoint, which requires a latitude and longitude. However, Yahoo Maps must know how to convert from addresses because `drawZoomAndCenter(LocationType,ZoomLevel)` can take an address. I could convert by using `drawZoomAndCenter()` then `getCenterLatLon()` but is there a better way, which doesn't require a draw?
You can ask the map object to do the geoCoding, and catch the callback: ``` <script type="text/javascript"> var map = new YMap(document.getElementById('map')); map.drawZoomAndCenter("Algeria", 17); map.geoCodeAddress("Cambridge, UK"); YEvent.Capture(map, EventsList.onEndGeoCode, function(geoCode) { if (geoCode.success) map.addOverlay(new YMarker(geoCode.GeoPoint)); }); </script> ``` One thing to beware of -- in this example the `drawAndZoom` call will itself make a geoCoding request, so you'll get the callback from that too. You might want to filter that out, or set the map's centre based on a GeoPoint.
73,542
<p>I have an List and I'd like to wrap it into an IQueryable.</p> <p>Is this possible?</p>
[ { "answer_id": 73563, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 8, "selected": true, "text": "<pre><code>List&lt;int&gt; list = new List&lt;int&gt;() { 1, 2, 3, 4, };\nIQueryable&lt;int&gt; query = list.AsQu...
2008/09/16
[ "https://Stackoverflow.com/questions/73542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11835/" ]
I have an List and I'd like to wrap it into an IQueryable. Is this possible?
``` List<int> list = new List<int>() { 1, 2, 3, 4, }; IQueryable<int> query = list.AsQueryable(); ``` If you don't see the `AsQueryable()` method, add a using statement for `System.Linq`.
73,544
<p>Anyone know of a good, hopefully free FTP class for use in .NET that can actually work behind an HTTP proxy or FTP gateway? The FtpWebRequest stuff in .NET is horrible at best, and I really don't want to roll my own here.</p>
[ { "answer_id": 73566, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>System.Net.WebClient can handle ftp urls, and it's a bit easier to work with. You can set credentials and proxy in...
2008/09/16
[ "https://Stackoverflow.com/questions/73544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91911/" ]
Anyone know of a good, hopefully free FTP class for use in .NET that can actually work behind an HTTP proxy or FTP gateway? The FtpWebRequest stuff in .NET is horrible at best, and I really don't want to roll my own here.
Our [Rebex FTP](http://www.rebex.net/ftp.net/) works with proxies just fine. Following code shows how to connect to the FTP using HTTP proxy (code is taken from [FTP tutorial page](http://www.rebex.net/ftp.net/tutorial-ftp.aspx#proxy)). ``` // initialize FTP client Ftp client = new Ftp(); // setup proxy details client.Proxy.ProxyType = FtpProxyType.HttpConnect; client.Proxy.Host = proxyHostname; client.Proxy.Port = proxyPort; // add proxy username and password when needed client.Proxy.UserName = proxyUsername; client.Proxy.Password = proxyPassword; // connect, login client.Connect(hostname, port); client.Login(username, password); // do some work // ... // disconnect client.Disconnect(); ``` You can download the trial at [www.rebex.net/ftp.net/download.aspx](http://www.rebex.net/ftp.net/download.aspx)
73,580
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail">How do you send email from a Java app using Gmail?</a> </p> </blockquote> <p>How do I send an SMTP Message from Java?</p>
[ { "answer_id": 73596, "author": "Mason", "author_id": 8973, "author_profile": "https://Stackoverflow.com/users/8973", "pm_score": 2, "selected": false, "text": "<p>See the <a href=\"http://www.oracle.com/technetwork/java/javamail/index.html\" rel=\"nofollow noreferrer\">JavaMail API</a> ...
2008/09/16
[ "https://Stackoverflow.com/questions/73580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
> > **Possible Duplicate:** > > [How do you send email from a Java app using Gmail?](https://stackoverflow.com/questions/46663/how-do-you-send-email-from-a-java-app-using-gmail) > > > How do I send an SMTP Message from Java?
Here's an example for Gmail smtp: ``` import java.io.*; import java.net.InetAddress; import java.util.Properties; import java.util.Date; import javax.mail.*; import javax.mail.internet.*; import com.sun.mail.smtp.*; public class Distribution { public static void main(String args[]) throws Exception { Properties props = System.getProperties(); props.put("mail.smtps.host","smtp.gmail.com"); props.put("mail.smtps.auth","true"); Session session = Session.getInstance(props, null); Message msg = new MimeMessage(session); msg.setFrom(new InternetAddress("mail@tovare.com"));; msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("tov.are.jacobsen@iss.no", false)); msg.setSubject("Heisann "+System.currentTimeMillis()); msg.setText("Med vennlig hilsennTov Are Jacobsen"); msg.setHeader("X-Mailer", "Tov Are's program"); msg.setSentDate(new Date()); SMTPTransport t = (SMTPTransport)session.getTransport("smtps"); t.connect("smtp.gmail.com", "admin@tovare.com", "<insert password here>"); t.sendMessage(msg, msg.getAllRecipients()); System.out.println("Response: " + t.getLastServerResponse()); t.close(); } } ``` Now, do it this way only if you would like to keep your project dependencies to a minimum, otherwise i can warmly recommend using classes from apache <http://commons.apache.org/email/> Regards Tov Are Jacobsen
73,628
<p>If you have a JSF <code>&lt;h:commandLink&gt;</code> (which uses the <code>onclick</code> event of an <code>&lt;a&gt;</code> to submit the current form), how do you execute JavaScript (such as asking for delete confirmation) prior to the action being performed?</p>
[ { "answer_id": 73644, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 4, "selected": true, "text": "<pre><code>&lt;h:commandLink id=\"myCommandLink\" action=\"#{myPageCode.doDelete}\"&gt;\n &lt;h:outputText value=\"#{m...
2008/09/16
[ "https://Stackoverflow.com/questions/73628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9254/" ]
If you have a JSF `<h:commandLink>` (which uses the `onclick` event of an `<a>` to submit the current form), how do you execute JavaScript (such as asking for delete confirmation) prior to the action being performed?
``` <h:commandLink id="myCommandLink" action="#{myPageCode.doDelete}"> <h:outputText value="#{msgs.deleteText}" /> </h:commandLink> <script type="text/javascript"> if (document.getElementById) { var commandLink = document.getElementById('<c:out value="${myPageCode.myCommandLinkClientId}" />'); if (commandLink && commandLink.onclick) { var commandLinkOnclick = commandLink.onclick; commandLink.onclick = function() { var result = confirm('Do you really want to <c:out value="${msgs.deleteText}" />?'); if (result) { return commandLinkOnclick(); } return false; } } } </script> ``` Other Javascript actions (like validating form input etc) could be performed by replacing the call to `confirm()` with a call to another function.
73,629
<p>I have a string that is like below.</p> <pre><code>,liger, unicorn, snipe </code></pre> <p>in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#?</p> <p>Thanks.</p> <hr> <p><em>There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.</em></p>
[ { "answer_id": 73650, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 0, "selected": false, "text": "<pre><code>if (s.StartsWith(\",\")) {\n s = s.Substring(1, s.Length - 1);\n}\n</code></pre>\n" }, { "answer_id": ...
2008/09/16
[ "https://Stackoverflow.com/questions/73629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I have a string that is like below. ``` ,liger, unicorn, snipe ``` in other languages I'm familiar with I can just do a string.trim(",") but how can I do that in c#? Thanks. --- *There's been a lot of back and forth about the StartTrim function. As several have pointed out, the StartTrim doesn't affect the primary variable. However, given the construction of the data vs the question, I'm torn as to which answer to accept. True the question only wants the first character trimmed off not the last (if anny), however, there would never be a "," at the end of the data. So, with that said, I'm going to accept the first answer that that said to use StartTrim assigned to a new variable.*
``` string sample = ",liger, unicorn, snipe"; sample = sample.TrimStart(','); // to remove just the first comma ``` Or perhaps: ``` sample = sample.Trim().TrimStart(','); // to remove any whitespace and then the first comma ```
73,651
<p>I'm failing at finding the commands I need to send to authenticate to a SMTP server using NTLM. </p> <p>I think it goes something like:</p> <pre><code>AUTH NTLM &lt;bae64encode something&gt; 334 &lt;bae64encode something&gt; 235 </code></pre>
[ { "answer_id": 82401, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 1, "selected": false, "text": "<p>Look for information about <strong>Apache</strong> and Siteminder as Apache is responsible for the HTTP transport stu...
2008/09/16
[ "https://Stackoverflow.com/questions/73651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4580/" ]
I'm failing at finding the commands I need to send to authenticate to a SMTP server using NTLM. I think it goes something like: ``` AUTH NTLM <bae64encode something> 334 <bae64encode something> 235 ```
SVN with Siteminder has been implemented and is working now. Since there is not much of information out there on this, I would like to post the overview of steps followed: 1. Cookie based authentcation was disabled on Siteminder end 2. HTTP AUTH was enabled (in Siteminder) and all webdav methods were added to policy server to be handled by SiteMinder 3. Authentication was disabled on apache end (HTTP Auth) for SVN
73,663
<p>How do I exit a script early, like the <code>die()</code> command in PHP?</p>
[ { "answer_id": 73673, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 12, "selected": true, "text": "<pre><code>import sys\nsys.exit()\n</code></pre>\n<p>details from the <a href=\"https://docs.python.org/2/library/sys.html#sys.ex...
2008/09/16
[ "https://Stackoverflow.com/questions/73663", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
How do I exit a script early, like the `die()` command in PHP?
``` import sys sys.exit() ``` details from the [`sys` module documentation](https://docs.python.org/2/library/sys.html#sys.exit): > > `sys.**exit**([*arg*])` > > > Exit from Python. This is implemented by raising the > [`SystemExit`](https://docs.python.org/2/library/exceptions.html#SystemExit "SystemExit") exception, so cleanup actions specified by finally clauses > of [`try`](https://docs.python.org/2/reference/compound_stmts.html#try "try") statements are honored, and it is possible to intercept the > exit attempt at an outer level. > > > The optional argument *arg* can be an integer giving the exit status > (defaulting to zero), or another type of object. If it is an integer, > zero is considered “successful termination” and any nonzero value is > considered “abnormal termination” by shells and the like. Most systems > require it to be in the range 0-127, and produce undefined results > otherwise. Some systems have a convention for assigning specific > meanings to specific exit codes, but these are generally > underdeveloped; Unix programs generally use 2 for command line syntax > errors and 1 for all other kind of errors. If another type of object > is passed, None is equivalent to passing zero, and any other object is > printed to [`stderr`](https://docs.python.org/2/library/sys.html#sys.stderr "sys.stderr") and results in an exit code of 1. In particular, > `sys.exit("some error message")` is a quick way to exit a program when > an error occurs. > > > Since [`exit()`](https://docs.python.org/2/library/constants.html#exit "exit") ultimately “only” raises an exception, it will only exit > the process when called from the main thread, and the exception is not > intercepted. > > > Note that this is the 'nice' way to exit. @[glyphtwistedmatrix](https://stackoverflow.com/questions/73663/terminating-a-python-script#76374) below points out that if you want a 'hard exit', you can use `os._exit(*errorcode*)`, though it's likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesn't let the interpreter do any cleanup before the process dies. On the other hand, it *does* kill the entire process, including all running threads, while `sys.exit()` (as it says in the docs) only exits if called from the main thread, with no other threads running.
73,667
<p>How can I start an interactive console for Perl, similar to the <code>irb</code> command for Ruby or <code>python</code> for Python?</p>
[ { "answer_id": 73685, "author": "Brian Phillips", "author_id": 7230, "author_profile": "https://Stackoverflow.com/users/7230", "pm_score": 3, "selected": false, "text": "<p><code>perl -d</code> is your friend:</p>\n\n<pre><code>% perl -de 0</code></pre>\n" }, { "answer_id": 73689...
2008/09/16
[ "https://Stackoverflow.com/questions/73667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5475/" ]
How can I start an interactive console for Perl, similar to the `irb` command for Ruby or `python` for Python?
You can use the perl debugger on a trivial program, like so: ``` perl -de1 ``` Alternatively there's [*Alexis Sukrieh*'s Perl Console](http://search.cpan.org/~sukria/perlconsole-0.4/perlconsole) application, but I haven't used it.
73,686
<pre><code>#include &lt;iostream&gt; using namespace std; int main() { double u = 0; double w = -u; cout &lt;&lt; w &lt;&lt; endl; return 0; } </code></pre> <p>Why does this great piece of code output <code>-0</code> and not <code>0</code>, as one would expect?</p>
[ { "answer_id": 73711, "author": "foxxtrot", "author_id": 10369, "author_profile": "https://Stackoverflow.com/users/10369", "pm_score": 5, "selected": true, "text": "<p>The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to b...
2008/09/16
[ "https://Stackoverflow.com/questions/73686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6922/" ]
``` #include <iostream> using namespace std; int main() { double u = 0; double w = -u; cout << w << endl; return 0; } ``` Why does this great piece of code output `-0` and not `0`, as one would expect?
The IEEE 754 standard for floating-point numbers has the sign bit separate from the mantissa, which allows for zero to be negative. [Wikipedia](http://en.wikipedia.org/wiki/IEEE_754) should be able to help explain this.
73,713
<p>The following will cause infinite recursion on the == operator overload method</p> <pre><code> Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (foo1 == null) return foo2 == null; return foo1.Equals(foo2); } </code></pre> <p>How do I check for nulls?</p>
[ { "answer_id": 73729, "author": "Andrew Jones", "author_id": 12767, "author_profile": "https://Stackoverflow.com/users/12767", "pm_score": 4, "selected": false, "text": "<p>Cast to object in the overload method:</p>\n\n<pre><code>public static bool operator ==(Foo foo1, Foo foo2) {\n ...
2008/09/16
[ "https://Stackoverflow.com/questions/73713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12767/" ]
The following will cause infinite recursion on the == operator overload method ``` Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (foo1 == null) return foo2 == null; return foo1.Equals(foo2); } ``` How do I check for nulls?
Use `ReferenceEquals`: ``` Foo foo1 = null; Foo foo2 = new Foo(); Assert.IsFalse(foo1 == foo2); public static bool operator ==(Foo foo1, Foo foo2) { if (object.ReferenceEquals(null, foo1)) return object.ReferenceEquals(null, foo2); return foo1.Equals(foo2); } ```
73,748
<p>I have a dropdownlist with the autopostback set to true. I want the user to confirm if they really want to change the value, which on post back fires a server side event (selectedindexchanged).</p> <p>I have tried adding an onchange attribute "return confirm('Please click OK to change. Otherwise click CANCEL?';") but it will not postback regardless of the confirm result and the value in the list does not revert back if cancel selected. </p> <p>When I remove the onchange attribute from the DropdownList tag, the page does postback. It does not when the onchange attribute is added. Do I still need to wire the event handler (I'm on C# .Net 2.0 ).</p> <p>Any leads will be helpful.</p> <p>Thanks!</p>
[ { "answer_id": 73860, "author": "Brian Liang", "author_id": 5853, "author_profile": "https://Stackoverflow.com/users/5853", "pm_score": 0, "selected": false, "text": "<p>Make sure your event is wired:</p>\n\n<pre><code>dropDown.SelectedIndexChanged += new EventHandler(dropDown_SelectedIn...
2008/09/16
[ "https://Stackoverflow.com/questions/73748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262613/" ]
I have a dropdownlist with the autopostback set to true. I want the user to confirm if they really want to change the value, which on post back fires a server side event (selectedindexchanged). I have tried adding an onchange attribute "return confirm('Please click OK to change. Otherwise click CANCEL?';") but it will not postback regardless of the confirm result and the value in the list does not revert back if cancel selected. When I remove the onchange attribute from the DropdownList tag, the page does postback. It does not when the onchange attribute is added. Do I still need to wire the event handler (I'm on C# .Net 2.0 ). Any leads will be helpful. Thanks!
Have you tried to set the onChange event to a javascript function and then inside the function display the javascript alert and utilize the \_\_doPostback function if it passes? i.e. ``` drpControl.Attributes("onChange") = "DisplayConfirmation();" function DisplayConfirmation() { if (confirm('Are you sure you want to do this?')) { __doPostback('drpControl',''); } } ```
73,781
<p>If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process?</p> <p>Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice?</p> <p>I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP.</p> <p>As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to <code>popen('/usr/bin/sendmail', 'w')</code> is a little closer to the metal than I'd like.</p> <p>If the answer is 'go write a library,' so be it ;-)</p>
[ { "answer_id": 73807, "author": "tovare", "author_id": 12677, "author_profile": "https://Stackoverflow.com/users/12677", "pm_score": 2, "selected": false, "text": "<p>It's quite common to just use the sendmail command from Python using os.popen</p>\n\n<p>Personally, for scripts i didn't ...
2008/09/16
[ "https://Stackoverflow.com/questions/73781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12779/" ]
If I want to send mail not via SMTP, but rather via sendmail, is there a library for python that encapsulates this process? Better yet, is there a good library that abstracts the whole 'sendmail -versus- smtp' choice? I'll be running this script on a bunch of unix hosts, only some of which are listening on localhost:25; a few of these are part of embedded systems and can't be set up to accept SMTP. As part of Good Practice, I'd really like to have the library take care of header injection vulnerabilities itself -- so just dumping a string to `popen('/usr/bin/sendmail', 'w')` is a little closer to the metal than I'd like. If the answer is 'go write a library,' so be it ;-)
Header injection isn't a factor in how you send the mail, it's a factor in how you construct the mail. Check the [email](https://docs.python.org/2/library/email.html) package, construct the mail with that, serialise it, and send it to `/usr/sbin/sendmail` using the [subprocess](https://docs.python.org/2/library/subprocess.html) module: ``` import sys from email.mime.text import MIMEText from subprocess import Popen, PIPE msg = MIMEText("Here is the body of my message") msg["From"] = "me@example.com" msg["To"] = "you@example.com" msg["Subject"] = "This is the subject." p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE) # Both Python 2.X and 3.X p.communicate(msg.as_bytes() if sys.version_info >= (3,0) else msg.as_string()) # Python 2.X p.communicate(msg.as_string()) # Python 3.X p.communicate(msg.as_bytes()) ```
73,785
<p>I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells. The cells may contain text, numbers or be blank. I am not very familiar / comfortable working with the concept of 'Range'. Therefore, any sample codes would be greatly appreciated. (I did try to google it, but the code snippets I found didn't quite do what I needed)</p> <p>Thank you.</p>
[ { "answer_id": 73891, "author": "Martin08", "author_id": 8203, "author_profile": "https://Stackoverflow.com/users/8203", "pm_score": 0, "selected": false, "text": "<p>In Excel VBA, this function will give you the content of any cell in any worksheet.</p>\n\n<pre><code>Function getCellCon...
2008/09/16
[ "https://Stackoverflow.com/questions/73785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5899/" ]
I need to simply go through all the cells in a Excel Spreadsheet and check the values in the cells. The cells may contain text, numbers or be blank. I am not very familiar / comfortable working with the concept of 'Range'. Therefore, any sample codes would be greatly appreciated. (I did try to google it, but the code snippets I found didn't quite do what I needed) Thank you.
``` Sub CheckValues1() Dim rwIndex As Integer Dim colIndex As Integer For rwIndex = 1 To 10 For colIndex = 1 To 5 If Cells(rwIndex, colIndex).Value <> 0 Then _ Cells(rwIndex, colIndex).Value = 0 Next colIndex Next rwIndex End Sub ``` Found this snippet on <http://www.java2s.com/Code/VBA-Excel-Access-Word/Excel/Checksvaluesinarange10rowsby5columns.htm> It seems to be quite useful as a function to illustrate the means to check values in cells in an ordered fashion. Just imagine it as being a 2d Array of sorts and apply the same logic to loop through cells.
73,797
<p>How do I tell Subversion (svn) to treat a file as a binary file?</p>
[ { "answer_id": 73820, "author": "Jan Krüger", "author_id": 12471, "author_profile": "https://Stackoverflow.com/users/12471", "pm_score": 3, "selected": false, "text": "<p>For example:</p>\n\n<pre><code>svn propset svn:mime-type image/png foo.png\n</code></pre>\n" }, { "answer_id"...
2008/09/16
[ "https://Stackoverflow.com/questions/73797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5222/" ]
How do I tell Subversion (svn) to treat a file as a binary file?
It is possible to manually identify a file located within a repository as *binary* by using: ``` svn propset svn:mime-type application/octet-stream <filename> ``` This is generally not necessary, as Subversion will attempt to determine whether a file is binary when the file is first added. If Subversion is incorrectly tagging a certain type as "text" when it should be treated as binary, it is possible to configure Subversion's [auto-props feature](http://svnbook.red-bean.com/nightly/en/svn.advanced.props.html#svn.advanced.props.auto) to automatically tag that file with a non-text MIME type. Regardless of the properties configured on the file, Subversion still stores the file in a binary format within the repository. If Subversion identifies the MIME type as a "text" type, it enables certain features which are not available on binary files, such as *svn diff* and *svn blame*. It also allows for automatic line ending conversion, which is configurable on a client-by-client basis. For more information, see [How does Subversion handle binary files?](http://subversion.apache.org/faq.html#binary-files)
73,833
<p>I want to search for files containing DOS line endings with grep on Linux. Something like this:</p> <pre class="lang-sh prettyprint-override"><code>grep -IUr --color '\r\n' . </code></pre> <p>The above seems to match for literal <code>rn</code> which is not what is desired.</p> <p>The output of this will be piped through xargs into todos to convert crlf to lf like this</p> <pre><code>grep -IUrl --color '^M' . | xargs -ifile fromdos 'file' </code></pre>
[ { "answer_id": 73886, "author": "pjz", "author_id": 8002, "author_profile": "https://Stackoverflow.com/users/8002", "pm_score": 7, "selected": false, "text": "<p>Use <kbd>Ctrl</kbd>+<kbd>V</kbd>, <kbd>Ctrl</kbd>+<kbd>M</kbd> to enter a literal Carriage Return character into your grep str...
2008/09/16
[ "https://Stackoverflow.com/questions/73833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245/" ]
I want to search for files containing DOS line endings with grep on Linux. Something like this: ```sh grep -IUr --color '\r\n' . ``` The above seems to match for literal `rn` which is not what is desired. The output of this will be piped through xargs into todos to convert crlf to lf like this ``` grep -IUrl --color '^M' . | xargs -ifile fromdos 'file' ```
grep probably isn't the tool you want for this. It will print a line for every matching line in every file. Unless you want to, say, run todos 10 times on a 10 line file, grep isn't the best way to go about it. Using find to run file on every file in the tree then grepping through that for "CRLF" will get you one line of output for each file which has dos style line endings: ``` find . -not -type d -exec file "{}" ";" | grep CRLF ``` will get you something like: ``` ./1/dos1.txt: ASCII text, with CRLF line terminators ./2/dos2.txt: ASCII text, with CRLF line terminators ./dos.txt: ASCII text, with CRLF line terminators ```
73,885
<p>How can I construct my ajaxSend call, this seems like the place to put it, to preview what is being passed back to the broker? also, can I stop the ajax call in ajaxSend?..so I can perfect my url string before dealing with errors from the broker?</p> <p>This is the complete URL that, when passed to the broker, will return the JSON code I need:</p> <pre><code>http://myServer/cgi-bin/broker?service=myService&amp;program=myProgram&amp;section=mySection&amp;start=09/08/08&amp;end=09/26/08 </code></pre> <p>This is my $.post call (not sure it is creating the above url string)</p> <pre><code>$(function() { $("#submit").bind("click", function() { $.post({ url: "http://csewebprod/cgi-bin/broker" , datatype: "json", data: { 'service' : myService, 'program' : myProgram, 'section' : mySection, 'start' : '09/08/08', 'end' : '09/26/08' }, error: function(request){ $("#updateHTML").removeClass("hide") ; $("#updateHTML").html(request.statusText); }, success: function(request) { $("#updateHTML").removeClass("hide") ; $("#updateHTML").html(request) ; } }); // End post method }); // End bind method }); // End eventlistener </code></pre> <p>Thanks</p>
[ { "answer_id": 73916, "author": "moswald", "author_id": 8368, "author_profile": "https://Stackoverflow.com/users/8368", "pm_score": 3, "selected": true, "text": "<p>As far as I know, the only way to do that is to enter something (anything) on that line, then delete it. Or hit space and ...
2008/09/16
[ "https://Stackoverflow.com/questions/73885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
How can I construct my ajaxSend call, this seems like the place to put it, to preview what is being passed back to the broker? also, can I stop the ajax call in ajaxSend?..so I can perfect my url string before dealing with errors from the broker? This is the complete URL that, when passed to the broker, will return the JSON code I need: ``` http://myServer/cgi-bin/broker?service=myService&program=myProgram&section=mySection&start=09/08/08&end=09/26/08 ``` This is my $.post call (not sure it is creating the above url string) ``` $(function() { $("#submit").bind("click", function() { $.post({ url: "http://csewebprod/cgi-bin/broker" , datatype: "json", data: { 'service' : myService, 'program' : myProgram, 'section' : mySection, 'start' : '09/08/08', 'end' : '09/26/08' }, error: function(request){ $("#updateHTML").removeClass("hide") ; $("#updateHTML").html(request.statusText); }, success: function(request) { $("#updateHTML").removeClass("hide") ; $("#updateHTML").html(request) ; } }); // End post method }); // End bind method }); // End eventlistener ``` Thanks
As far as I know, the only way to do that is to enter something (anything) on that line, then delete it. Or hit space and you'll never see it there until you return to that line. Once VS determines that you've edited a line of text, it won't automatically modify it for you (at least, not in that way that you've described).
73,892
<p>How can I <strong>pre pend</strong> (insert at beginning of file) a file to all files of a type in folder and sub-folders using <code>Powershell</code>?</p> <p>I need to add a standard header file to all <code>.cs</code> and was trying to use <code>Powershell</code> to do so, but while I was able to append it in a few lines of code I was stuck when trying to <strong>pre-pend</strong> it.</p>
[ { "answer_id": 74035, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 1, "selected": false, "text": "<p>Have no idea, but if you have the code to append just do it the other way round. Something like</p>\n\n<ol>\n<li>rename exis...
2008/09/16
[ "https://Stackoverflow.com/questions/73892", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11673/" ]
How can I **pre pend** (insert at beginning of file) a file to all files of a type in folder and sub-folders using `Powershell`? I need to add a standard header file to all `.cs` and was trying to use `Powershell` to do so, but while I was able to append it in a few lines of code I was stuck when trying to **pre-pend** it.
Here is a very simple example to show you one of the ways it could be done. ``` $Content = "This is your content`n" Get-ChildItem *.cs | foreach-object { $FileContents = Get-Content -Path $_ Set-Content -Path $_ -Value ($Content + $FileContents) } ```
73,930
<p>What do I need to add to my <code>.spec</code> file to create the desktop shortcut and assign an icon to the shortcut during install of my <code>.rpm</code>? If a script is required, an example would be very helpful.</p>
[ { "answer_id": 74003, "author": "akdom", "author_id": 145, "author_profile": "https://Stackoverflow.com/users/145", "pm_score": 3, "selected": false, "text": "<p>You use a .desktop file for icons under linux. Where to put the icon depends on what distribution and what desktop environmen...
2008/09/16
[ "https://Stackoverflow.com/questions/73930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What do I need to add to my `.spec` file to create the desktop shortcut and assign an icon to the shortcut during install of my `.rpm`? If a script is required, an example would be very helpful.
You use a .desktop file for icons under linux. Where to put the icon depends on what distribution and what desktop environment you are using. Since I'm currently running Gnome on Fedora 9, I will answer it in those terms. An example foo.desktop file would be: ``` [Desktop Entry] Encoding=UTF-8 GenericName=Generic Piece Of Software Name=FooBar Exec=/usr/bin/foo.sh Icon=foo.png Terminal=false Type=Application Categories=Qt;Gnome;Applications; ``` The .desktop file should under Fedora 9 Gnome be located in /usr/share/applications/ , you can run a locate on .desktop to figure out where you should put in on your distro. Gnome will generally look in the KDE icon directory to see if there are other icons there also.... > > Encoding, Name and Exec should speak for themselves. > > > * Generic name == Brief Description of application. > * Icon == The image to display for the icon > * Terminal == Is this a terminal application, should I start it as one? > * Type == Type of program this is, can be used in placing the icon in a menu. > * Categories == This information is what is mainly used to place the icon in a given menu if an XML file to specify such is not present. The setup for menus is handled a little differently by everyone. > > > There are more attributes you can set, but they aren't strictly necessary. The image file used sits somewhere in the bowels of the /usr/share/icons/ directory. You can parse through that to find all the wonders of how such things work, but the basics are that you pick the directory for the icon type (in my case gnome) and place the image within the appropriate directory (there is a scalable directory for .svg images, and specific sizes such as 48x48 for raster images. Under Gnome all images are generally .png).
73,947
<p>I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc. </p> <p>What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually.</p> <p>Thanks to StackOverflow responses I have now found some more info from Adobe - <a href="http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html" rel="noreferrer">http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html</a> and <a href="https://github.com/mikechambers/as3corelib" rel="noreferrer">https://github.com/mikechambers/as3corelib</a> - which I think I can use for the encryption. Not sure this will get me around CheatEngine though.</p> <p>I need to know the best solutions for both AS2 and AS3, if they are different.</p> <p>The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster)</p>
[ { "answer_id": 74043, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 5, "selected": false, "text": "<p>You may be asking the wrong question. You seem focused on the methods people are using to game their way up the hig...
2008/09/16
[ "https://Stackoverflow.com/questions/73947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911/" ]
I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc. What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually. Thanks to StackOverflow responses I have now found some more info from Adobe - <http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html> and <https://github.com/mikechambers/as3corelib> - which I think I can use for the encryption. Not sure this will get me around CheatEngine though. I need to know the best solutions for both AS2 and AS3, if they are different. The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster)
This is a classic problem with Internet games and contests. Your Flash code works with users to decide a score for a game. But users aren't trusted, and the Flash code runs on the user's computer. You're SOL. There is nothing you can do to prevent an attacker from forging high scores: * Flash is even easier to reverse engineer than you might think it is, since the bytecodes are well documented and describe a high-level language (Actionscript) --- when you publish a Flash game, you're publishing your source code, whether you know it or not. * Attackers control the runtime memory of the Flash interpreter, so that anyone who knows how to use a programmable debugger can alter any variable (including the current score) at any time, or alter the program itself. The simplest possible attack against your system is to run the HTTP traffic for the game through a proxy, catch the high-score save, and replay it with a higher score. You can try to block this attack by binding each high score save to a single instance of the game, for instance by sending an encrypted token to the client at game startup, which might look like: ``` hex-encoding( AES(secret-key-stored-only-on-server, timestamp, user-id, random-number)) ``` (You could also use a session cookie to the same effect). The game code echoes this token back to the server with the high-score save. But an attacker can still just launch the game again, get a token, and then immediately paste that token into a replayed high-score save. So next you feed not only a token or session cookie, but also a high-score-encrypting session key. This will be a 128 bit AES key, itself encrypted with a key hardcoded into the Flash game: ``` hex-encoding( AES(key-hardcoded-in-flash-game, random-128-bit-key)) ``` Now before the game posts the high score, it decrypts the high-score-encrypting-session key, which it can do because you hardcoded the high-score-encrypting-session-key-decrypting-key into the Flash binary. You encrypt the high score with this decrypted key, along with the SHA1 hash of the high score: ``` hex-encoding( AES(random-128-bit-key-from-above, high-score, SHA1(high-score))) ``` The PHP code on the server checks the token to make sure the request came from a valid game instance, then decrypts the encrypted high score, checking to make sure the high-score matches the SHA1 of the high-score (if you skip this step, decryption will simply produce random, likely very high, high scores). So now the attacker decompiles your Flash code and quickly finds the AES code, which sticks out like a sore thumb, although even if it didn't it'd be tracked down in 15 minutes with a memory search and a tracer ("I know my score for this game is 666, so let's find 666 in memory, then catch any operation that touches that value --- oh look, the high score encryption code!"). With the session key, the attacker doesn't even have to run the Flash code; she grabs a game launch token and a session key and can send back an arbitrary high score. You're now at the point where most developers just give up --- give or take a couple months of messing with attackers by: * Scrambling the AES keys with XOR operations * Replacing key byte arrays with functions that calculate the key * Scattering fake key encryptions and high score postings throughout the binary. This is all mostly a waste of time. It goes without saying, SSL isn't going to help you either; SSL can't protect you when one of the two SSL endpoints is evil. Here are some things that can actually reduce high score fraud: * Require a login to play the game, have the login produce a session cookie, and don't allow multiple outstanding game launches on the same session, or multiple concurrent sessions for the same user. * Reject high scores from game sessions that last less than the shortest real games ever played (for a more sophisticated approach, try "quarantining" high scores for game sessions that last less than 2 standard deviations below the mean game duration). Make sure you're tracking game durations serverside. * Reject or quarantine high scores from logins that have only played the game once or twice, so that attackers have to produce a "paper trail" of reasonable looking game play for each login they create. * "Heartbeat" scores during game play, so that your server sees the score growth over the lifetime of one game play. Reject high scores that don't follow reasonable score curves (for instance, jumping from 0 to 999999). * "Snapshot" game state during game play (for instance, amount of ammunition, position in the level, etc), which you can later reconcile against recorded interim scores. You don't even have to have a way to detect anomalies in this data to start with; you just have to collect it, and then you can go back and analyze it if things look fishy. * Disable the account of any user who fails one of your security checks (for instance, by ever submitting an encrypted high score that fails validation). Remember though that you're only deterring high score fraud here. There's *nothing* you can do to prevent if. If there's money on the line in your game, someone is going to defeat any system you come up with. The objective isn't to *stop* this attack; it's to make the attack more expensive than just getting really good at the game and beating it.
73,958
<p>In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block.</p> <p>The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware?</p> <p>Thanks</p>
[ { "answer_id": 74039, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It should be something like: <code>ifconfig eth0 192.168.0.42 up</code></p>\n\n<p>Replace eth0 by the network interface of y...
2008/09/16
[ "https://Stackoverflow.com/questions/73958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In a shellscript, I'd like to set the IP of my box, run a command, then move to the next IP. The IPs are an entire C block. The question is how do I set the IP of the box without editing a file? What command sets the IP on Slackware? Thanks
As mentioned in other answers, you can use either the ifconfig command or the ip command. ip is a much more robust command, and I prefer to use it. A full script which loops through a full class C subnet adding the IP, doing stuff, then removing it follows. Note that it doesn't use .0 or .255, which are the network and broadcast addresses of the subnet. Also, when using the ip command to add or remove an address, it's good to include the mask width, as well (the /24 at the end of the address). ``` #!/bin/bash SUBNET=192.168.135. ETH=eth0 for i in {1..254} do ip addr add ${SUBNET}${i}/24 dev ${ETH} # do whatever you want here ip addr del ${SUBNET}${i}/24 dev ${ETH} done ```
73,960
<p>In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content. </p> <p>This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :(</p> <p>Is there any workaround for this problem? How can I use CSS to set different widths for dropbox and the dropdownlist?</p>
[ { "answer_id": 74062, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You can add a style directly to the select element:</p>\n\n<p><code>&lt;select name=\"foo\" style=\"width: 200px\"&gt;</code...
2008/09/16
[ "https://Stackoverflow.com/questions/73960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/747/" ]
In IE, the dropdown-list takes the same width as the dropbox (I hope I am making sense) whereas in Firefox the dropdown-list's width varies according to the content. This basically means that I have to make sure that the dropbox is wide enough to display the longest selection possible. This makes my page look very ugly :( Is there any workaround for this problem? How can I use CSS to set different widths for dropbox and the dropdownlist?
Here's another [jQuery](http://jquery.com) based example. In contrary to all the other answers posted here, it takes all keyboard and mouse events into account, especially clicks: ``` if (!$.support.leadingWhitespace) { // if IE6/7/8 $('select.wide') .bind('focus mouseover', function() { $(this).addClass('expand').removeClass('clicked'); }) .bind('click', function() { $(this).toggleClass('clicked'); }) .bind('mouseout', function() { if (!$(this).hasClass('clicked')) { $(this).removeClass('expand'); }}) .bind('blur', function() { $(this).removeClass('expand clicked'); }); } ``` Use it in combination with this piece of CSS: ``` select { width: 150px; /* Or whatever width you want. */ } select.expand { width: auto; } ``` All you need to do is to add the class `wide` to the dropdown element(s) in question. ``` <select class="wide"> ... </select> ``` [Here is a jsfiddle example](http://jsfiddle.net/HnV9Q/). Hope this helps.
73,964
<p>I would like to turn the HTML generated by my CFM page into a PDF, and have the user prompted with the standard "Save As" prompt when navigating to my page.</p>
[ { "answer_id": 73982, "author": "Frank Wiles", "author_id": 12568, "author_profile": "https://Stackoverflow.com/users/12568", "pm_score": 1, "selected": false, "text": "<p>I'm not that familiar with ColdFusion, but what you need to do is set the Content-Type of the page when the user req...
2008/09/16
[ "https://Stackoverflow.com/questions/73964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2232/" ]
I would like to turn the HTML generated by my CFM page into a PDF, and have the user prompted with the standard "Save As" prompt when navigating to my page.
You should use the cfdocument tag (with format="PDF") to generate the PDF by placing it around the page you are generating. You'll want to specify a filename attribute, otherwise the document will just stream right to your browser. After you have saved the content as a PDF, use cfheader and cfcontent in combination to output the PDF as an attachment ("Save As") and add the file to the response stream. I also added deletefile="Yes" on the cfcontent tag to keep the file system clean of the files. ``` <cfdocument format="PDF" filename="file.pdf" overwrite="Yes"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Hello World</title> </head> <body> Hello World </body> </html> </cfdocument> <cfheader name="Content-Disposition" value="attachment;filename=file.pdf"> <cfcontent type="application/octet-stream" file="#expandPath('.')#\file.pdf" deletefile="Yes"> ``` As an aside: I'm just using file.pdf for the filename in the example below, but you might want to use some random or session generated string for the filename to avoid problems resulting from race conditions.
73,971
<p>In JavaScript, what is the best way to determine if a date provided falls within a valid range?</p> <p>An example of this might be checking to see if the user input <code>requestedDate</code> is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.</p>
[ { "answer_id": 74024, "author": "Jesper Blad Jensen", "author_id": 11559, "author_profile": "https://Stackoverflow.com/users/11559", "pm_score": 3, "selected": false, "text": "<p>So if i understand currenctly, you need to look if one date is bigger than the other.</p>\n\n<pre><code>funct...
2008/09/16
[ "https://Stackoverflow.com/questions/73971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
In JavaScript, what is the best way to determine if a date provided falls within a valid range? An example of this might be checking to see if the user input `requestedDate` is part of the next valid work week. Note that this is not just checking to see if one date is larger than another as a valid date would be equal to or greater than the lower end of the range while less than or equal to the upper end of the range.
This is actually a problem that I have seen come up before a lot in my works and the following bit of code is my answer to the problem. ``` // checkDateRange - Checks to ensure that the values entered are dates and // are of a valid range. By this, the dates must be no more than the // built-in number of days appart. function checkDateRange(start, end) { // Parse the entries var startDate = Date.parse(start); var endDate = Date.parse(end); // Make sure they are valid if (isNaN(startDate)) { alert("The start date provided is not valid, please enter a valid date."); return false; } if (isNaN(endDate)) { alert("The end date provided is not valid, please enter a valid date."); return false; } // Check the date range, 86400000 is the number of milliseconds in one day var difference = (endDate - startDate) / (86400000 * 7); if (difference < 0) { alert("The start date must come before the end date."); return false; } if (difference <= 1) { alert("The range must be at least seven days apart."); return false; } return true; } ``` Now a couple things to note about this code, the `Date.parse` function should work for most input types, but has been known to have issues with some formats such as "YYYY MM DD" so you should test that before using it. However, I seem to recall that most browsers will interpret the date string given to Date.parse based upon the computers region settings. Also, the multiplier for 86400000 should be whatever the range of days you are looking for is. So if you are looking for dates that are at least one week apart then it should be seven.
74,010
<p>I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this?</p>
[ { "answer_id": 74105, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>An explicit cursor is one you declare, like:</p>\n\n<pre><code>CURSOR my_cursor IS\n SELECT table_name FROM USER_TABLE...
2008/09/16
[ "https://Stackoverflow.com/questions/74010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this?
An implicit cursor is one created "automatically" for you by Oracle when you execute a query. It is simpler to code, but suffers from * inefficiency (the ANSI standard specifies that it must fetch twice to check if there is more than one record) * vulnerability to data errors (if you ever get two rows, it raises a TOO\_MANY\_ROWS exception) Example ``` SELECT col INTO var FROM table WHERE something; ``` An explicit cursor is one you create yourself. It takes more code, but gives more control - for example, you can just open-fetch-close if you only want the first record and don't care if there are others. Example ``` DECLARE CURSOR cur IS SELECT col FROM table WHERE something; BEGIN OPEN cur; FETCH cur INTO var; CLOSE cur; END; ```
74,019
<p>How can I specify the filename when dumping data into the response stream?</p> <p>Right now I'm doing the following:</p> <pre><code>byte[] data= GetFoo(); Response.Clear(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.BinaryWrite(data); Response.End(); </code></pre> <p>With the code above, I get "foo.aspx.pdf" as the filename to save. I seem to remember being able to add a header to the response to specify the filename to save.</p>
[ { "answer_id": 74044, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 4, "selected": false, "text": "<pre><code>Response.AppendHeader(\"Content-Disposition\", \"attachment; filename=foo.pdf\");\n</code></pre>\n" }, { "...
2008/09/16
[ "https://Stackoverflow.com/questions/74019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1672/" ]
How can I specify the filename when dumping data into the response stream? Right now I'm doing the following: ``` byte[] data= GetFoo(); Response.Clear(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.BinaryWrite(data); Response.End(); ``` With the code above, I get "foo.aspx.pdf" as the filename to save. I seem to remember being able to add a header to the response to specify the filename to save.
Add a content-disposition to the header: ``` Response.AddHeader("content-disposition", @"attachment;filename=""MyFile.pdf"""); ```
74,032
<p>I'm looking for real world best practices, how other people might have implemented solutions with complex domains.</p>
[ { "answer_id": 74070, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 2, "selected": false, "text": "<p>This is what <a href=\"http://msdn.microsoft.com/en-us/library/system.collections.iequalitycomparer.aspx\" rel=\"n...
2008/09/16
[ "https://Stackoverflow.com/questions/74032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5802/" ]
I'm looking for real world best practices, how other people might have implemented solutions with complex domains.
Any time you consider using an `IEqualityComparer<T>`, pause to think if the class could be made to implement `IEquatable<T>` instead. If a `Product` should always be compared by ID, just define it to be equated as such so you can use the default comparer. That said, there are still a few of reasons you might want a custom comparer: 1. If there are multiple ways instances of a class could be considered equal. The best example of this is a string, for which the framework provides six different comparers in [`StringComparer`](http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx). 2. If the class is defined in such a way that you can't define it as `IEquatable<T>`. This would include classes defined by others and classes generated by the compiler (specifically anonymous types, which use a property-wise comparison by default). If you do decide you need a comparer, you can certainly use a generalized comparer (see DMenT's answer), but if you need to reuse that logic you should encapsulate it in a dedicated class. You could even declare it by inheriting from the generic base: ``` class ProductByIdComparer : GenericEqualityComparer<ShopByProduct> { public ProductByIdComparer() : base((x, y) => x.ProductId == y.ProductId, z => z.ProductId) { } } ``` As far as use, you should take advantage of comparers when possible. For example, rather than calling `ToLower()` on every string used as a dictionary key (logic for which will be strewn across your app), you should declare the dictionary to use a case-insensitive `StringComparer`. The same goes for the LINQ operators that accept a comparer. But again, always consider if the equatable behavior that should be intrinsic to the class rather than defined externally.
74,057
<p>Is there a way to use sql-server like analytic functions in Hibernate?</p> <p>Something like </p> <pre><code>select foo from Foo foo where f.x = max(f.x) over (partition by f.y) </code></pre>
[ { "answer_id": 75287, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 3, "selected": false, "text": "<p>You are after a native SQL query.</p>\n\n<p>If you are using JPA the syntax is:</p>\n\n<pre><code>Query q = em.cre...
2008/09/16
[ "https://Stackoverflow.com/questions/74057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12905/" ]
Is there a way to use sql-server like analytic functions in Hibernate? Something like ``` select foo from Foo foo where f.x = max(f.x) over (partition by f.y) ```
You are after a native SQL query. If you are using JPA the syntax is: ``` Query q = em.createNativeQuery("select foo.* from Foo foo " + "where f.x = max(f.x) over " + "(partition by f.y)", Foo.class); ``` If you need to return multiple types, take a look at the [SQLResultSetMapping](http://java.sun.com/javaee/5/docs/api/javax/persistence/SqlResultSetMapping.html) annotation. If you're using the the Hibernate API directly: ``` Query q = session.createSQLQuery("select {foo.*} from Foo foo " + "where f.x = max(f.x) over "+ "(partition by f.y)"); q.addEntity("foo", Foo.class); ``` See [10.4.4. Queries in native SQL](http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html#objectstate-querying-nativesql) in the Hibernate documentation for more details. In both APIs you can pass in parameters as normal using setParameter.
74,083
<p>When using Business Objects' CrystalReportViewer control, how can you detect and manually print the report the user has currently drilled into? You can print this automatically using the Print() method of the CrystalReportViewer, but I want to be able to do a manual printing of this report.</p> <p>It is possible to print the main ReportSource of the CrystalReportViewer, but I need to know what report the user has drilled into and then do a manual printing of that particular drill down. Any ideas?</p>
[ { "answer_id": 75287, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 3, "selected": false, "text": "<p>You are after a native SQL query.</p>\n\n<p>If you are using JPA the syntax is:</p>\n\n<pre><code>Query q = em.cre...
2008/09/16
[ "https://Stackoverflow.com/questions/74083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When using Business Objects' CrystalReportViewer control, how can you detect and manually print the report the user has currently drilled into? You can print this automatically using the Print() method of the CrystalReportViewer, but I want to be able to do a manual printing of this report. It is possible to print the main ReportSource of the CrystalReportViewer, but I need to know what report the user has drilled into and then do a manual printing of that particular drill down. Any ideas?
You are after a native SQL query. If you are using JPA the syntax is: ``` Query q = em.createNativeQuery("select foo.* from Foo foo " + "where f.x = max(f.x) over " + "(partition by f.y)", Foo.class); ``` If you need to return multiple types, take a look at the [SQLResultSetMapping](http://java.sun.com/javaee/5/docs/api/javax/persistence/SqlResultSetMapping.html) annotation. If you're using the the Hibernate API directly: ``` Query q = session.createSQLQuery("select {foo.*} from Foo foo " + "where f.x = max(f.x) over "+ "(partition by f.y)"); q.addEntity("foo", Foo.class); ``` See [10.4.4. Queries in native SQL](http://www.hibernate.org/hib_docs/v3/reference/en/html/objectstate.html#objectstate-querying-nativesql) in the Hibernate documentation for more details. In both APIs you can pass in parameters as normal using setParameter.