source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
153,046
Ok, this probably has a really simple answer, but I've never tried to do it before: How do you launch a web page from within an app? You know, "click here to go to our FAQ", and when they do it launches their default web browser and goes to your page. I'm working in C/C++ in Windows, but if there's a broader, more portable way to do it I'd like to know that, too.
#include <windows.h>void main(){ ShellExecute(NULL, "open", "http://yourwebpage.com", NULL, NULL, SW_SHOWNORMAL);}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17693/" ] }
153,048
I'm new to mock objects, but I understand that I need to have my classes implement interfaces in order to mock them. The problem I'm having is that in my data access layer, I want to have static methods, but I can't put a static method in an interface. What's the best way around this? Should I just use instance methods (which seems wrong) or is there another solution?
I would use a method object pattern. Have a static instance of this, and call it in the static method. It should be possible to subclass for testing, depending on your mocking framework. i.e. in your class with the static method have: private static final MethodObject methodObject = new MethodObject();public static void doSomething(){ methodObject.doSomething();} and your method object can be a very simple, easily-tested: public class MethodObject { public void doSomething() { // do your thang }}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4219/" ] }
153,054
I need to change the app name based on what configuration I'm using in Visual Studio. For example, if I'm in Debug configuration, I want the app name to show as 'App_Debug' in the Application field in the Elmah_Error table. Does anyone have any experience with this? Or is there another way to do it?
This can now be done purely in markup. Just add an applicationName attribute to the errorLog element in the <elmah> section of the web.config file. Example: <errorLog type="Elmah.SqlErrorLog, Elmah" connectionStringName="connectionString" applicationName="myApp" /> I've tested this and it works both when logging an exception and when viewing the log via Elmah.axd . In the case of the OP, one would imagine it can be set programatically too but I didn't test that. For me and I imagine for most scenarios the markup approach is sufficient.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ] }
153,065
I am trying to adapt an existing code to a 64 bit machine. The main problem is that in one function, the previous coder uses a void* argument that is converted into suitable type in the function itself. A short example: void function(MESSAGE_ID id, void* param){ if(id == FOO) { int real_param = (int)param; // ... }} Of course, on a 64 bit machine, I get the error: error: cast from 'void*' to 'int' loses precision I would like to correct this so that it still works on a 32 bit machine and as cleanly as possible. Any idea ?
Use intptr_t and uintptr_t . To ensure it is defined in a portable way, you can use code like this: #if defined(__BORLANDC__) typedef unsigned char uint8_t; typedef __int64 int64_t; typedef unsigned long uintptr_t;#elif defined(_MSC_VER) typedef unsigned char uint8_t; typedef __int64 int64_t;#else #include <stdint.h>#endif Just place that in some .h file and include wherever you need it. Alternatively, you can download Microsoft’s version of the stdint.h file from here or use a portable one from here .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7136/" ] }
153,074
Do you have any sugestions of tools to ease the task of understanding C/C++ code? We just inherited a large piece of software written by others and we need to quickly get up to speed on it. Any advice on tools that might simplify this task?
SourceInsight and Understand for C++ are the best tools you can get for c/c++ code analysis including flow charts.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21943/" ] }
153,087
I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers? After a quick google, I found only the WMI solution and a suggestion to PInvoke GetSecurityInfo
No need to P/Invoke. System.IO.File.GetAccessControl will return a FileSecurity object, which has a GetOwner method. Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API: const string FILE = @"C:\test.txt";var fs = File.GetAccessControl(FILE);var sid = fs.GetOwner(typeof(SecurityIdentifier));Console.WriteLine(sid); // SIDvar ntAccount = sid.Translate(typeof(NTAccount));Console.WriteLine(ntAccount); // DOMAIN\username Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership. var ntAccount = new NTAccount("DOMAIN", "username");fs.SetOwner(ntAccount);try { File.SetAccessControl(FILE, fs);} catch (InvalidOperationException ex) { Console.WriteLine("You cannot assign ownership to that user." + "Either you don't have TakeOwnership permissions, or it is not your user account." ); throw;}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5363/" ] }
153,148
What files do I need to put the header comment in for adding GPL to a C# project? Does form generated code require it? Does just need to be in every *.cs file? Is there a resource or in-depth list of language-specific steps required to add GPL to any kind of project?
The canonical answer is in the GPL Howto : Whichever license you plan to use, the process involves adding two elements to each source file of your program: a copyright notice (such as “Copyright 1999 Terry Jones”), and a statement of copying permission, saying that the program is distributed under the terms of the GNU General Public License (or the Lesser GPL). The recommended header for applying the GPL is: Copyright 200X My Name This file is part of Foobar. Foobar is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Foobar is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Foobar. If not, see http://www.gnu.org/licenses/ . Yes, it SHOULD be added to every file , since you cannot legally depend upon the assumption that every recipient receives your work as a whole. And, no, it doesn't have to be the complete license text.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ] }
153,152
I am working on an iGoogle-like application. Content from other applications (on other domains) is shown using iframes. How do I resize the iframes to fit the height of the iframes' content? I've tried to decipher the javascript Google uses but it's obfuscated, and searching the web has been fruitless so far. Update: Please note that content is loaded from other domains, so the same-origin policy applies.
We had this type of problem, but slightly in reverse to your situation - we were providing the iframed content to sites on other domains, so the same origin policy was also an issue. After many hours spent trawling google, we eventually found a (somewhat..) workable solution, which you may be able to adapt to your needs. There is a way around the same origin policy, but it requires changes on both the iframed content and the framing page, so if you haven't the ability to request changes on both sides, this method won't be very useful to you, i'm afraid. There's a browser quirk which allows us to skirt the same origin policy - javascript can communicate either with pages on its own domain, or with pages it has iframed, but never pages in which it is framed, e.g. if you have: www.foo.com/home.html, which iframes |-> www.bar.net/framed.html, which iframes |-> www.foo.com/helper.html then home.html can communicate with framed.html (iframed) and helper.html (same domain). Communication options for each page: +-------------------------+-----------+-------------+-------------+ | | home.html | framed.html | helper.html | +-------------------------+-----------+-------------+-------------+ | www.foo.com/home.html | N/A | YES | YES | | www.bar.net/framed.html | NO | N/A | YES | | www.foo.com/helper.html | YES | YES | N/A | +-------------------------+-----------+-------------+-------------+ framed.html can send messages to helper.html (iframed) but not home.html (child can't communicate cross-domain with parent). The key here is that helper.html can receive messages from framed.html , and can also communicate with home.html . So essentially, when framed.html loads, it works out its own height, tells helper.html , which passes the message on to home.html , which can then resize the iframe in which framed.html sits. The simplest way we found to pass messages from framed.html to helper.html was through a URL argument. To do this, framed.html has an iframe with src='' specified. When its onload fires, it evaluates its own height, and sets the src of the iframe at this point to helper.html?height=N There's an explanation here of how facebook handle it, which may be slightly clearer than mine above! Code In www.foo.com/home.html , the following javascript code is required (this can be loaded from a .js file on any domain, incidentally..): <script> // Resize iframe to full height function resizeIframe(height) { // "+60" is a general rule of thumb to allow for differences in // IE & and FF height reporting, can be adjusted as required.. document.getElementById('frame_name_here').height = parseInt(height)+60; }</script><iframe id='frame_name_here' src='http://www.bar.net/framed.html'></iframe> In www.bar.net/framed.html : <body onload="iframeResizePipe()"><iframe id="helpframe" src='' height='0' width='0' frameborder='0'></iframe><script type="text/javascript"> function iframeResizePipe() { // What's the page height? var height = document.body.scrollHeight; // Going to 'pipe' the data to the parent through the helpframe.. var pipe = document.getElementById('helpframe'); // Cachebuster a precaution here to stop browser caching interfering pipe.src = 'http://www.foo.com/helper.html?height='+height+'&cacheb='+Math.random(); }</script> Contents of www.foo.com/helper.html : <html> <!-- This page is on the same domain as the parent, so cancommunicate with it to order the iframe window resizingto fit the content --> <body onload="parentIframeResize()"> <script> // Tell the parent iframe what height the iframe needs to be function parentIframeResize() { var height = getParam('height'); // This works as our parent's parent is on our domain.. parent.parent.resizeIframe(height); } // Helper function, parse param from request string function getParam( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&]"+name+"=([^&#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return results[1]; } </script> </body> </html>
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/153152", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3842/" ] }
153,156
How to count distinct values in a node in XSLT? Example: I want to count the number of existing countries in Country nodes, in this case, it would be 3. <Artists_by_Countries> <Artist_by_Country> <Location_ID>62</Location_ID> <Artist_ID>212</Artist_ID> <Country>Argentina</Country> </Artist_by_Country> <Artist_by_Country> <Location_ID>4</Location_ID> <Artist_ID>108</Artist_ID> <Country>Australia</Country> </Artist_by_Country> <Artist_by_Country> <Location_ID>4</Location_ID> <Artist_ID>111</Artist_ID> <Country>Australia</Country> </Artist_by_Country> <Artist_by_Country> <Location_ID>12</Location_ID> <Artist_ID>78</Artist_ID> <Country>Germany</Country> </Artist_by_Country></Artists_by_Countries>
If you have a large document, you probably want to use the "Muenchian Method", which is usually used for grouping, to identify the distinct nodes. Declare a key that indexes the things you want to count by the values that are distinct: <xsl:key name="artists-by-country" match="Artist_by_Country" use="Country" /> Then you can get the <Artist_by_Country> elements that have distinct countries using: /Artists_by_Countries /Artist_by_Country [generate-id(.) = generate-id(key('artists-by-country', Country)[1])] and you can count them by wrapping that in a call to the count() function. Of course in XSLT 2.0, it's as simple as count(distinct-values(/Artists_by_Countries/Artist_by_Country/Country))
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ] }
153,220
I'm a bit surprised I haven't found a good open source library for performing common network tasks. There are a few very good commercial libraries, but they're too expensive to use on an open source project. Anyone know of any?
SSH.NET Library - https://github.com/sshnet/SSH.NET Inspired by Sharp.SSH, this library is complete rewrite using .NET 4.0, without any third party dependencies and utilizes parallelism as much as possible to allow best performance. It's been a solid C# implementation of client side SSH.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
153,223
I do TDD, and I've been fairly loose in organizing my unit tests. I tend to start with a file representing the next story or chunk of functionality and write all the unit-tests to make that work. Of course, if I'm introducing a new class, I usually make a separate unit-test module or file for that class, but I don't organize the tests themselves into any higher level structure. The result is I write code fast and I believe my actual program is reasonably well structured, but the unit tests themselves are "messy". Especially, their structure tends to recapitulate the phylogeny of the development process. Sometimes I see myself as trading laziness in the code for laziness in the tests. How big a problem is this? Who here continually refactors and reorganizes their unit tests to try to improve their overall structure? Any tips for this? What should the overall structure of tests look like. (Note, that I'm not so much asking the "how many assertions per function" question asked here : How many unit tests should I write per function/method? I'm talking about the bigger picture.)
Divide your tests in 2 sets: functional tests units tests Functional tests are per-user story. Unit tests are per-class. The former check that you actually support the story, the latter exercise and document your functionality. There is one directory (package) for functional tests. Unit tests should be closely bound with functionality they exercise (so they're scattered). You move them around and refactor them as you move & refactor your code around.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8482/" ] }
153,234
The thing I've found about TDD is that its takes time to get your tests set up and being naturally lazy I always want to write as little code as possible. The first thing I seem do is test my constructor has set all the properties but is this overkill? My question is to what level of granularity do you write you unit tests at? ..and is there a case of testing too much?
I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don't typically make a kind of mistake (like setting the wrong variables in a constructor), I don't test for it. I do tend to make sense of test errors, so I'm extra careful when I have logic with complicated conditionals. When coding on a team, I modify my strategy to carefully test code that we, collectively, tend to get wrong. Different people will have different testing strategies based on this philosophy, but that seems reasonable to me given the immature state of understanding of how tests can best fit into the inner loop of coding. Ten or twenty years from now we'll likely have a more universal theory of which tests to write, which tests not to write, and how to tell the difference. In the meantime, experimentation seems in order.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/153234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1116/" ] }
153,286
I went to school for programming years ago and when I got out I found a job in system administration and that is the direction my career took. I'd like to get back into development of some sort and have been 'playing' with C# and ASP.NET, but I've been hearing lots of buzz for other 'new' languages (by new I mean that they are new to me) like Ruby and F#. I guess I'm wondering if I'm wasting my time with learning largely MS languages instead of being more of a generalist. Having not been apart of the development community for a long time (if ever I was) has me floundering with trends and I'd like not to be left behind the times. Any thoughts to if it's better to follow the "latest" languages or stick with what is more tried and true technologies?
You should learn at least 1 compiled language (like C# or Java) and 1 Script Language (Python, Ruby, etc). This is usually enough to help most developers succeed at what they do, regardless of the age of the language. As for new vs old, I'd stick with C# for now as it's pretty popular. Learning a new language wouldn't be too bad though.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153286", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2623/" ] }
153,376
We have similar code to the following in one of our projects. Can anyone explain (in simple English) why the fixed statement is needed here? class TestClass{ int iMyVariable; static void Main() { TestClass oTestClass = new TestClass(); unsafe { fixed (int* p = &oTestClasst.iMyVariable) { *p = 9; } } }}
It fixes the pointer in memory. Garbage collected languages have the freedom to move objects around memory for efficiency. This is all transparent to the programmer because they don't really use pointers in "normal" CLR code. However, when you do require pointers, then you need to fix it in memory if you want to work with them.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23790/" ] }
153,381
I have to concatenate a bunch of Strings in Javascript and am searching for the fastest way to do so. Let's assume that the Javascript has to create a large XML-"file" that, naturally, consists of many small Strings. So I came up with: var sbuffer = []; for (var idx=0; idx<10000; idx=idx+1) { sbuffer.push(‘<xmltag>Data comes here... bla... </xmltag>’); } // Now we "send" it to the browser... alert(sbuffer.join(”)); Do not pay any attention to the loop or the other "sophisticated" code which builds the example. My question is: For an unknown number of Strings, do you have a faster algorithm / method / idea to concatenate many small Strings to a huge one?
Changing the line: sbuffer.push(‘Data comes here... bla... ’); to sbuffer[sbuffer.length] = ‘Data comes here... bla... ’; will give you 5-50% speed gain (depending on browser, in IE - gain will be highest) Regards.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13209/" ] }
153,388
I'm really sick of this problem. Google searches always seem to suggest "delete all bpls for the package", "delete all dcus". Sometimes this just-does-not-work. Hopefully I can get some other ideas here. I have a package written in-house, which had been installed without issue a few months ago. Having made a few changes to the source, I figured it was time to recompile/reinstall the package. Now I get two errors, the first if I choose "install" is Access violation at address 02422108 in module 'dcc100.dll'. Read of address 00000000. ...or if I try to build/compile the package, I get [Pascal Fatal Error] F2084 Internal Error: LA33 This is one of those Delphi problems that seems to occur time and time again for many of us. Would be great if we could collate a response something along the lines of "any one or combination of these steps might fix it, but if you do all these steps it will fix it...." At the moment, I've removed all references to the bpl/dcp files for this package, but still getting the same error... Using BDS2006 (Delphi) Update 01-Oct-2008: I managed to solve this - see my post below. As I can't accept my own answer, I'm not entirely sure what to do here. Obviously these types of issues occur frequently for some people, so I'll leave it open for a while to get other suggestions. Then I guess if someone collates all the info into a super-post, I can accept the answer
I managed to solve this, following the below procedure Create a new package One by one, add the components to the package, compile & install, until it failed. Investigate the unit causing the failure. As it turns out, the unit in question had a class constant array, eg TMyClass = class(TComponent)private const ErrStrs: array[TErrEnum] of string = ('', //erOK 'Invalid user name or password', //erInvUserPass 'Trial Period has Expired'); //erTrialExpprotected ...public ...end; So it appears that Delphi does not like class constants (or perhaps class constant arrays) in package components Update: and yes, this has been reported to codegear
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11820/" ] }
153,420
I'm starting a project using a Restful architecture implemented in Java (using the new JAX-RS standard) We are planning to develop the GUI with a Flex application. I have already found some problems with this implementation using the HTTPService component (the response error codes, headers access...). Any of you guys have some experience in a similar project. Is it feasible?
The problem here is that a lot of the web discussions around this issue are a year or more old. I'm working through this same research right now, and this is what I've learned today. This IBM Developer Works article from August 2008 by Jorge Rasillo and Mike Burr shows how to do a Flex front-end / RESTful back-end app (examples in PHP and Groovy). Nice article. Anyway, here's the take away: Their PHP/Groovy code uses and expects PUT and DELETE. But the Flex code has to use POST, but sets the HTTP header X-Method-Override to DELETE (you can do the same for PUT I presume). Note that this is not the Proxy method discussed above. // Flex doesn't know how to generate an HTTP DELETE.// Fortunately, sMash/Zero will interpret an HTTP POST with// an X-Method-Override: DELETE header as a DELETE.deleteTodoHS.headers['X-Method-Override'] = 'DELETE'; What's happening here? the IBM web server intercepts and interprets the "POST with DELETE" as a DELETE. So, I dug further and found this post and discussion with Don Box (one of the original SOAP guys). Apparently this is a fairly standard behavior since some browsers, etc. do not support PUT and DELETE, and is a work-around that has been around a while. Here's a snippet, but there's much more discussion. "If I were building a GData client, I honestly wonder why I'd bother using DELETE and PUT methods at all given that X-HTTP-Method-Override is going to work in more cases/deployments." My take away from this is that if your web side supports this X-Method-Override header, then you can use this approach. The Don Box comments make me think it's fairly well supported, but I've not confirmed that yet. Another issue arises around being able to read the HTTP response headers. Again, from a blog post in 2007 by Nathan de Vries , we see this discussed. He followed up that blog post and discussion with his own comment: "The only change on the web front is that newer versions of the Flash Player (certainly those supplied with the Flex 3 beta) now support the responseHeaders property on instances of HTTPStatusEvent." I'm hoping that means it is a non-issue now.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2937/" ] }
153,451
I am trying to use WebClient to download a file from web using a WinForms application. However, I really only want to download HTML file. Any other type I will want to ignore. I checked the WebResponse.ContentType , but its value is always null . Anyone have any idea what could be the cause?
Given your update, you can do this by changing the .Method in GetWebRequest: using System;using System.Net;static class Program{ static void Main() { using (MyClient client = new MyClient()) { client.HeadOnly = true; string uri = "http://www.google.com"; byte[] body = client.DownloadData(uri); // note should be 0-length string type = client.ResponseHeaders["content-type"]; client.HeadOnly = false; // check 'tis not binary... we'll use text/, but could // check for text/html if (type.StartsWith(@"text/")) { string text = client.DownloadString(uri); Console.WriteLine(text); } } }}class MyClient : WebClient{ public bool HeadOnly { get; set; } protected override WebRequest GetWebRequest(Uri address) { WebRequest req = base.GetWebRequest(address); if (HeadOnly && req.Method == "GET") { req.Method = "HEAD"; } return req; }} Alternatively, you can check the header when overriding GetWebRespons(), perhaps throwing an exception if it isn't what you wanted: protected override WebResponse GetWebResponse(WebRequest request){ WebResponse resp = base.GetWebResponse(request); string type = resp.Headers["content-type"]; // do something with type return resp;}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
153,507
How do I calculate the position of an accelerating body (e.g. a car) after a certain time (e.g. 1 second)? For a moving body that it not accelerating, it is a linear relationship, so I presume for an accelerating body it involves a square somewhere. Any ideas?
The equation is: s = ut + (1/2)a t^2 where s is position, u is velocity at t=0, t is time and a is a constant acceleration. For example, if a car starts off stationary, and accelerates for two seconds with an acceleration of 3m/s^2, it moves (1/2) * 3 * 2^2 = 6m This equation comes from integrating analytically the equations stating that velocity is the rate-of-change of position, and acceleration is the rate-of-change of velocity. Usually in a game-programming situation, one would use a slightly different formulation: at every frame, the variables for velocity and position are integrated not analytically, but numerically: s = s + u * dt;u = u + a * dt; where dt is the length of a frame (measured using a timer: 1/60th second or so). This method has the advantage that the acceleration can vary in time. Edit A couple of people have noted that the Euler method of numerical integration (as shown here), though the simplest to demonstrate with, has fairly poor accuracy. See Velocity Verlet (often used in games), and 4th order Runge Kutta (a 'standard' method for scientific applications) for improved algorithms.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11911/" ] }
153,524
What is the ideal code to logging ratio? I'm not used to writing logs as most of the applications I've developed have not had much logging. Recently though I've changed job, and I've noticed that you can't see the application code for the calls to log4net. I appreciate that this is useful but surely having too many debug statements is just as bad as not having any at all? There are logging statements that tell you when every method starts and finishes and what they are returning. and when pretty much anything is done. Would it not be easier to have some addon that used reflection to add the logging statements in at compile time so they didn't get in the way as you were trying to look at the code? Also in these days of powerful IDEs and remote debugging is that much logging really nescisary?
Since log4net does a great job at not clogging up the resources, I tend to be a little verbose on logging because when you have to change to debug mode, the more info you have, the better. Here's what I typically log: DEBUG Level Any parameters passed into themethod Any row counts from result sets I retrieve Any datarows that may contain suspicious data when being passed down to the method Any "generated" file paths, connection strings, or other values that could get mungled up when being "pieced together" by the environment. INFO Level The start and end of the method The start and end of any major loops The start of any major case/switch statements ERROR Level Handled exceptions Invalid login attempts (if security is an issue) Bad data that I have intercepted forreporting FATAL Level Unhandled exceptions. Also having a lot of logging details prevents me from asking the user what they were doing when they got the error message. I can easily piece it together.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ] }
153,527
I have a page that contains a form. This page is served with content type text/html;charset=utf-8. I need to submit this form to server using ISO-8859-1 character encoding. Is this possible with Internet Explorer? Setting accept-charset attribute to form element, like this, works for Firefox, Opera etc. but not for IE. <form accept-charset="ISO-8859-1"> ...</form> Edit: This form is created by server A and will be submitted to server B. I have no control over server B. If I set server A to serve content with charset ISO-8859-1 everything works, but I am looking a way to make this work without changes to server A's encoding. I have another question about setting the encoding in server A.
There is a simple hack to this: Insert a hidden input field in the form with an entity which only occur in the character set the server your posting (or doing a GET) to accepts. Example: If the form is located on a server serving ISO-8859-1 and the form will post to a server expecting UTF-8 insert something like this in the form: <input name="iehack" type="hidden" value="&#9760;" /> IE will then "detect" that the form contains a UTF-8 character and use UTF-8 when you POST or GET. Strange, but it does work.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431/" ] }
153,572
I'm looking for a tool that will be able to build a parser (in C#) if I give it a BNF grammar (eg. http://savage.net.au/SQL/sql-2003-2.bnf ) Does such a generator exist?
Normally BNF grammars are too ambiguous. ANTLR will be probably good for what you are looking for.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ] }
153,573
Take the following C# class: c1 { event EventHandler someEvent;} If there are a lot of subscriptions to c1 's someEvent event and I want to clear them all, what is the best way to achieve this? Also consider that subscriptions to this event could be/are lambdas/anonymous delegates. Currently my solution is to add a ResetSubscriptions() method to c1 that sets someEvent to null. I don't know if this has any unseen consequences.
From within the class, you can set the (hidden) variable to null. A null reference is the canonical way of representing an empty invocation list, effectively. From outside the class, you can't do this - events basically expose "subscribe" and "unsubscribe" and that's it. It's worth being aware of what field-like events are actually doing - they're creating a variable and an event at the same time. Within the class, you end up referencing the variable. From outside, you reference the event. See my article on events and delegates for more information.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/153573", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5289/" ] }
153,584
How do I iterate over a timespan after days, hours, weeks or months? Something like: for date in foo(from_date, to_date, delta=HOURS): print date Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.
Use dateutil and its rrule implementation, like so: from dateutil import rrulefrom datetime import datetime, timedeltanow = datetime.now()hundredDaysLater = now + timedelta(days=100)for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater): print dt Output is 2008-09-30 23:29:542008-10-30 23:29:542008-11-30 23:29:542008-12-30 23:29:54 Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want. This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/153584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473/" ] }
153,598
I have a simple query: SELECT u_name AS user_name FROM users WHERE user_name = "john"; I get Unknown Column 'user_name' in where clause . Can I not refer to 'user_name' in other parts of the statement even after select 'u_name as user_name' ?
SQL is evaluated backwards, from right to left. So the where clause is parsed and evaluate prior to the select clause. Because of this the aliasing of u_name to user_name has not yet occurred.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
153,616
I'm working on a loosely coupled cluster for some data processing. The network code and processing code is in place, but we are evaluating different methodologies in our approach. Right now, as we should be, we are I/O bound on performance issues, and we're trying to decrease that bottleneck. Obviously, faster switches like Infiniband would be awesome, but we can't afford the luxury of just throwing out what we have and getting new equipment. My question posed is this. All traditional and serious HPC applications done on clusters is typically implemented with message passing versus sending over sockets directly. What are the performance benefits to this? Should we see a speedup if we switched from sockets?
MPI MIGHT use sockets. But there are also MPI implementation to be used with SAN (System area network) that use direct distributed shared memory. That of course if you have the hardware for that. So MPI allows you to use such resources in the future. On that case you can gain massive performance improvements (on my experience with clusters back at university time, you can reach gains of a few orders of magnitude). So if you are writting code that can be ported to higher end clusters, using MPI is a very good idea. Even discarding performance issues, using MPI can save you a lot of time, that you can use to improve performance of other parts of your system or simply save your sanity.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ] }
153,630
Unfortunately, I need to do this. I'm using ELMAH for my error log. Before I route to my error.aspx view, I have to grab the default ELMAH error log so I can log the exception. You used to be able to use Elmah.ErrorLog.Default However, this is now marked as obsolete. The compiler directs me to use the method Elmah.ErrorLog.GetDefault(HttpContext context) MVC's context is of type HttpContextBase, which enables us to mock it (YAY!). How can we deal with MVC-unaware libraries that require the old style HttpContext?
Try System.Web.HttpContext.Current . It should do the trick. Gets HTTP-specific information about an individual HTTP request. MSDN
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/153630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
153,633
Is there an elegant way to have performant, natural sorting in a MySQL database? For example if I have this data set: Final Fantasy Final Fantasy 4 Final Fantasy 10 Final Fantasy 12 Final Fantasy 12: Chains of Promathia Final Fantasy Adventure Final Fantasy Origins Final Fantasy Tactics Any other elegant solution than to split up the games' names into their components Title : "Final Fantasy" Number : "12" Subtitle : "Chains of Promathia" to make sure that they come out in the right order? (10 after 4, not before 2). Doing so is a pain in the a** because every now and then there's another game that breaks that mechanism of parsing the game title (e.g. "Warhammer 40,000", "James Bond 007")
Here is a quick solution: SELECT alphanumeric, integerFROM sorting_testORDER BY LENGTH(alphanumeric), alphanumeric
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ] }
153,644
Since arrays and hashes can only contain scalars in Perl, why do you have to use the $ to tell the interpreter that the value is a scalar when accessing array or hash elements? In other words, assuming you have an array @myarray and a hash %myhash , why do you need to do: $x = $myarray[1];$y = $myhash{'foo'}; instead of just doing : $x = myarray[1];$y = myhash{'foo'}; Why are the above ambiguous? Wouldn't it be illegal Perl code if it was anything but a $ in that place? For example, aren't all of the following illegal in Perl? @var[0];@var{'key'};%var[0];%var{'key'};
Slices aren't illegal: @slice = @myarray[1, 2, 5];@slice = @myhash{qw/foo bar baz/}; And I suspect that's part of the reason why you need to specify if you want to get a single value out of the hash/array or not.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ] }
153,706
It seems to me that phpMyAdmin imports tables by default with collation latin1_swedish_ci, how i change this?
In your Mysql configuration change the default-character-set operative under the [mysqld] tab. For example: [mysqld]default-character-set=utf8 Don't forget to restart your Mysql server afterwards for the changes to take effect.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ] }
153,712
So how does someone create a music visualizer? I've looked on Google but I haven't really found anything that talks about the actual programming; mostly just links to plug-ins or visualizing applications. I use iTunes but I realize that I need Xcode to program for that (I'm currently deployed in Iraq and can't download that large of a file). So right now I'm just interested in learning "the theory" behind it, like processing the frequencies and whatever else is required.
As a visualizer plays a song file, it reads the audio data in very short time slices (usually less than 20 milliseconds). The visualizer does a Fourier transform on each slice, extracting the frequency components, and updates the visual display using the frequency information. How the visual display is updated in response to the frequency info is up to the programmer. Generally, the graphics methods have to be extremely fast and lightweight in order to update the visuals in time with the music (and not bog down the PC). In the early days (and still), visualizers often modified the color palette in Windows directly to achieve some pretty cool effects. One characteristic of frequency-component-based visualizers is that they don't often seem to respond to the "beats" of music (like percussion hits, for example) very well. More interesting and responsive visualizers can be written that combine the frequency-domain information with an awareness of "spikes" in the audio that often correspond to percussion hits.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18676/" ] }
153,716
Is there any way to verify in Java code that an e-mail address is valid. By valid, I don't just mean that it's in the correct format ([email protected]), but that's it's a real active e-mail address. I'm almost certain that there's no 100% reliable way to do this, because such a technique would be the stuff of spammer's dreams. But perhaps there's some technique that gives some useful indication about whether an address is 'real' or not.
Here is what I have around. To check that the address is a valid format, here is a regex that verifies that it's nearly rfc2822 (it doesn't catch some weird corner cases). I found it on the 'net last year. private static final Pattern rfc2822 = Pattern.compile( "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$");if (!rfc2822.matcher(email).matches()) { throw new Exception("Invalid address");} That will take care of simple syntax (for the most part). The other check I know of will let you check if the domain has an MX record. It looks like this: Hashtable<String, String> env = new Hashtable<String, String>();env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");DirContext ictx = new InitialDirContext(env);Attributes attrs = ictx.getAttributes(domainName, new String[] {"MX"});Attribute attr = attrs.get("MX");if (attr == null) // No MX recordelse // If attr.size() > 0, there is an MX record This, I also found on the 'net. It came from this link . If these both pass, you have a good chance at having a valid address. As for if the address it's self (not just the domain), it's not full, etc... you really can't check that. Note that the second check is time intensive . It can take anywhere from milliseconds to >30 seconds (if the DNS does not respond and times out). It's not something to try and run real-time for large numbers of people. Hope this helps. EDIT I'd like to point out that, at least instead of the regex, there are better ways to check basic validity. Don and Michael point out that Apache Commons has something, and I recently found out you can use .validate() on InternetAddress to have Java check that the address is really RFC-8222, which is certainly more accurate than my regex.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ] }
153,721
What alternatives are there to GAE, given that I already have a good bit of code working that I would like to keep. In other words, I'm digging python. However, my use case is more of a low number of requests, higher CPU usage type use case, and I'm worried that I may not be able to stay with App Engine forever. I have heard a lot of people talking about Amazon Web Services and other sorts of cloud providers, but I am having a hard time seeing where most of these other offerings provide the range of services (data querying, user authentication, automatic scaling) that App Engine provides. What are my options here?
I don't think there is another alternative (with regards to code portability) to GAE right now since GAE is in a class of its own. Sure GAE is cloud computing, but I see GAE as a subset of cloud computing. Amazon's EC2 is also cloud computing (as well as Joyent Accelerators, Slicehost Slices), but obviously they are two different beasts as well. So right now you're in a situation that requires rethinking your architecture depending on your needs. The immediate benefits of GAE is that its essentially maintenance free as it relates to infrastructure (scalable web server and database administration). GAE is more tailored to those developers that only want to focus on their applications and not the underlying system.In a way you can consider that developer friendly. Now it should also be said that these other cloud computing solutions also try to allow you to only worry about your application as much as you like by providing VM images/templates. Ultimately your needs will dictate the approach you should take. Now with all this in mind we can also construct hybrid solutions and workarounds that might fulfill our needs as well. For example, GAE doesn't seem directly suited to this specific app needs you describe. In other words, GAE offers relatively high number of requests, low number of cpu cycles (not sure if paid version will be any different). However, one way to tackle this challenge is by building a customized solution involving GAE as the front end and Amazon AWS (EC2, S3, and SQS) as the backend. Some will say you might as well build your entire stack on AWS, but that may involve rewriting lots of existing code as well. Furthermore, as a workaround a previous stackoverflow post describes a method of simulating background tasks in GAE. Furthermore, you can look into HTTP Map/Reduce to distribute workload as well.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/96/" ] }
153,724
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations. I also would like only significant digits to be displayed - i.e. there should not be any trailing zeroes. I know one method of doing this is to use the String.format method: String.format("%.5g%n", 0.912385); returns: 0.91239 which is great, however it always displays numbers with 5 decimal places even if they are not significant: String.format("%.5g%n", 0.912300); returns: 0.91230 Another method is to use the DecimalFormatter : DecimalFormat df = new DecimalFormat("#.#####");df.format(0.912385); returns: 0.91238 However as you can see this uses half-even rounding. That is it will round down if the previous digit is even. What I'd like is this: 0.912385 -> 0.912390.912300 -> 0.9123 What is the best way to achieve this in Java?
Use setRoundingMode , set the RoundingMode explicitly to handle your issue with the half-even round, then use the format pattern for your required output. Example: DecimalFormat df = new DecimalFormat("#.####");df.setRoundingMode(RoundingMode.CEILING);for (Number n : Arrays.asList(12, 123.12345, 0.23, 0.1, 2341234.212431324)) { Double d = n.doubleValue(); System.out.println(df.format(d));} gives the output: 12123.12350.230.12341234.2125 EDIT : The original answer does not address the accuracy of the double values. That is fine if you don't care much whether it rounds up or down. But if you want accurate rounding, then you need to take the expected accuracy of the values into account. Floating point values have a binary representation internally. That means that a value like 2.7735 does not actually have that exact value internally. It can be slightly larger or slightly smaller. If the internal value is slightly smaller, then it will not round up to 2.7740. To remedy that situation, you need to be aware of the accuracy of the values that you are working with, and add or subtract that value before rounding. For example, when you know that your values are accurate up to 6 digits, then to round half-way values up, add that accuracy to the value: Double d = n.doubleValue() + 1e-6; To round down, subtract the accuracy.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/153724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12149/" ] }
153,735
I think there are a lot of people out there unaware of RFC's (Request for Comments). I know what they are at a logical level, but can anybody give a good description for a new developer? Also, sharing some resources on how to use and read them would be nice.
The term comes from the days of ARPANET, the predecessor to the internet, where the researchers would basically just throw ideas out there to, well, make a request for comments from the other researchers on the project. They could be about pretty much anything and were not very formal at the time. If you go read them, it’s pretty comical how informal they were. Now, there are more standards about what goes in RFC's and you can't get an RFC published until you have met strict guidelines and have done extensive research. They are pretty much reserved for well researched network standards that have been approved by the IETF.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14065/" ] }
153,748
I've tried this: string newScript = textBox1.Text;HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0];HtmlElement scriptEl = browserCtrl.Document.CreateElement("script");lblStatus.Text = scriptEl.GetType().ToString();scriptEl.SetAttribute("type", "text/javascript");head.AppendChild(scriptEl);scriptEl.InnerHtml = "function sayHello() { alert('hello') }"; scriptEl.InnerHtml and scriptEl.InnerText both give errors: System.NotSupportedException: Property is not supported on this type of HtmlElement. at System.Windows.Forms.HtmlElement.set_InnerHtml(String value) at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31 at System.Windows.Forms.Control.OnClick(EventArgs e) at System.Windows.Forms.Button.OnClick(EventArgs e) at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent) at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks) at System.Windows.Forms.Control.WndProc(Message& m) at System.Windows.Forms.ButtonBase.WndProc(Message& m) at System.Windows.Forms.Button.WndProc(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) Is there an easy way to inject a script into the dom?
For some reason Richard's solution didn't work on my end (insertAdjacentText failed with an exception). This however seems to work: HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;element.text = "function sayHello() { alert('hello') }";head.AppendChild(scriptEl);webBrowser1.Document.InvokeScript("sayHello"); This answer explains how to get the IHTMLScriptElement interface into your project.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/153748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432/" ] }
153,759
How do I use the jQuery Datepicker with a textbox input: $("#my_txtbox").datepicker({ // options}); that doesn't allow the user to input random text in the textbox.I want the Datepicker to pop up when the textbox gains focus or the user clicks on it, but I want the textbox to ignore any user input using the keyboard (copy & paste, or any other). I want to fill the textbox exclusively from the Datepicker calendar. Is this possible? jQuery 1.2.6 Datepicker 1.5.2
You should be able to use the readonly attribute on the text input, and jQuery will still be able to edit its contents. <input type='text' id='foo' readonly='true'>
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/153759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024/" ] }
153,812
In SVN, trunk is the recommended place for the main development and I use this convention for all of my projects. However, this means that trunk is sometimes unstable, or even broken . This happens for instance when I commit something by mistake When the trunk simply has to be broken because of the way SVN works. Canonical example is file renames - you must commit any file renames first and do any further modifications later; however, file rename may require code refactoring to reflect namespace or class name change so you basically need to commit a single logic operation in two steps. And the build is broken between steps 1 and 2. I can imagine there would be tools to prevent commiting something by mistake (TeamCity and delayed commits, for instance) but can you really overcome the second problem? If not, wouldn't it be better to do the "wild development" on some branch like /branch/dev and only merge to trunk when the build is reasonably solid?
Your trunk should ALWAYS compile, if you need to make breaking changes you should use a branch and merge the changes back later. Read this chapter of the SVN book: http://svnbook.red-bean.com/nightly/en/svn.branchmerge.html
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21728/" ] }
153,815
I am coming from the SQL server world where we had uniqueidentifier. Is there an equivalent in oracle? This column will be frequently queried so performance is the key. I am generating the GUID in .Net and will be passing it to Oracle. For a couple reasons it cannot be generated by oracle so I cannot use sequence.
CREATE table test (testguid RAW(16) default SYS_GUID() ) This blog studied the relative performance.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1514/" ] }
153,861
What do the brackets do in a sql statement? For example, in the statement: insert into table1 ([columnname1], columnname2) values (val1, val2) Also, what does it do if the table name is in brackets?
The [] marks the delimitation of a identifier, so if you have a column whose name contains spaces like Order Qty you need to enclose it with [] like: select [Order qty] from [Client sales] They are also to escape reserved keywords used as identifiers
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ] }
153,877
I have read the documentation on this and I think I understand. An AutoResetEvent resets when the code passes through event.WaitOne() , but a ManualResetEvent does not. Is this correct?
Yes. It's like the difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset) manually. The AutoResetEvent is a tollbooth, allowing one car to go by and automatically closing before the next one can get through.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/153877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1455/" ] }
153,890
I'm trying to find a good way to print leading 0 , such as 01001 for a ZIP Code . While the number would be stored as 1001 , what is a good way to do it? I thought of using either case statements or if to figure out how many digits the number is and then convert it to an char array with extra 0 's for printing, but I can't help but think there may be a way to do this with the printf format syntax that is eluding me.
printf("%05d", zipCode); The 0 indicates what you are padding with and the 5 shows the width of the integer number. Example 1: If you use "%02d" (useful for dates) this would only pad zeros for numbers in the ones column. E.g., 06 instead of 6 . Example 2: "%03d" would pad 2 zeros for one number in the ones column and pad 1 zero for a number in the tens column. E.g., number 7 padded to 007 and number 17 padded to 017 .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/153890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ] }
153,909
I call my JavaScript function. Why do I sometimes get the error 'myFunction is not defined' when it is defined? For example. I'll occasionally get 'copyArray is not defined' even in this example: function copyArray( pa ) { var la = []; for (var i=0; i < pa.length; i++) la.push( pa[i] ); return la;}Function.prototype.bind = function( po ) { var __method = this; var __args = []; // Sometimes errors -- in practice I inline the function as a workaround. __args = copyArray( arguments ); return function() { /* bind logic omitted for brevity */ }} As you can see, copyArray is defined right there , so this can't be about the order in which script files load. I've been getting this in situations that are harder to work around, where the calling function is located in another file that should be loaded after the called function. But this was the simplest case I could present, and appears to be the same problem. It doesn't happen 100% of the time, so I do suspect some kind of load-timing-related problem. But I have no idea what. @Hojou: That's part of the problem. The function in which I'm now getting this error is itself my addLoadEvent, which is basically a standard version of the common library function. @James: I understand that, and there is no syntax error in the function. When that is the case, the syntax error is reported as well. In this case, I am getting only the 'not defined' error. @David: The script in this case resides in an external file that is referenced using the normal <script src="file.js"></script> method in the page's head section. @Douglas: Interesting idea, but if this were the case, how could we ever call a user-defined function with confidence? In any event, I tried this and it didn't work. @sk: This technique has been tested across browsers and is basically copied from the Prototype library.
I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it. What happened in my case was that I had a former SCRIPT block, before the block that defined the function with problem, stated in the following way: <SCRIPT src="mycode.js"/> (That is, without the closing tag.) I had to redeclare this block in the following way. <SCRIPT src="mycode.js"></SCRIPT> And then what followed worked fine... weird huh?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4525/" ] }
153,912
I'm looking for a good way to visualize ASP.NET session state data stored in SQL server, preferably without creating a throwaway .aspx page. Is there a good way to get a list of the keys (and serialized data, if possible) directly from SQL server? Ideally, I'd like to run some T-SQL commands directly against the database to get a list of session keys that have been stored for a given session ID. It would be nice to see the serialized data for each key as well.
I had this function not being recognized as defined in latest Firefox for Linux, though Chromium was dealing fine with it. What happened in my case was that I had a former SCRIPT block, before the block that defined the function with problem, stated in the following way: <SCRIPT src="mycode.js"/> (That is, without the closing tag.) I had to redeclare this block in the following way. <SCRIPT src="mycode.js"></SCRIPT> And then what followed worked fine... weird huh?
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23632/" ] }
153,928
We currently are using both Visual Source Safe and Team Foundation Server at work (VSS for old projects, TFS for current or new projects). We have always used Labels in source control for each build. In VSS if you chose to see a file history you could include labels. In TFS I cannot find an option to include the lables in the history window. Since one of the most common questions that I get asked by support or management is 'What version did we fix/add/remove/change xxxx?', I have always relied on our build labels showing up in the history. Can I get Labels to show up in a file history?
In the 2008 version of TFS, you don't see labels in the standard history of files and folders. If you really want to know why - see Brian Harry's blog post " Why TFS Labels are not like VSS Labels ". To find labels in Visual Studio, go to File, Source Control, Label, Find Label... From that you can see what versions of files were included in that label. The team have definitely heard that this is not ideal, and the next version of TFS (Team Foundation Server 2010, codenamed "Rosario") will include improvements to the History view to make labels easier to find - see http://go.microsoft.com/?linkid=7807943 for the spec of improvements to the History view in TFS 2010. BTW - I actually moved to changeset based build numbering with TFS which makes labelling less necessary. See http://www.woodwardweb.com/vsts/changeset_based.html for more details. Hope that helps, Martin.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5882/" ] }
153,934
I'm trying to modify the class of an element if an ajax call based on that element is successful <script type='text/javascript'>$("#a.toggle").click(function(e){ $.ajax({ url: '/changeItem.php', dataType: 'json', type: 'POST', success: function(data,text){ if(data.error=='') { if($(this).hasClass('class1')) { $(this).removeClass('class1'); $(this).addClass('class2'); } else if($(this).hasClass('class2')) { $(this).removeClass('class2'); $(this).addClass('class1'); } } else(alert(data.error)); } }); return false;});</script><a class="toggle class1" title='toggle-this'>Item</a> My understanding of the problem is that in the success function this references the ajax object parameters, NOT the calling dom element like it does within other places of the click function. So, how do I reference the calling dom element and check / add / remove classes?
You can just store it in a variable. Example: $("#a.toggle").click(function(e){ var target = $(this); $.ajax({ url: '/changeItem.php', dataType: 'json', type: 'POST', success: function(data,text) { if(data.error=='') { if(target.hasClass('class1')) { target .removeClass('class1') .addClass('class2'); } else if(target.hasClass('class2')) { target .removeClass('class2') .addClass('class1'); } } else(alert(data.error)); } }); return false;});
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/153934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ] }
153,944
Is SQL case sensitive? I've used MySQL and SQL Server which both seem to be case insensitive. Is this always the case? Does the standard define case-sensitivity?
The SQL keywords are case insensitive ( SELECT , FROM , WHERE , etc), but they are often written in all caps. However, in some setups, table and column names are case sensitive. MySQL has a configuration option to enable/disable it. Usually case sensitive table and column names are the default on Linux MySQL and case insensitive used to be the default on Windows, but now the installer asked about this during setup. For SQL Server it is a function of the database's collation setting. Here is the MySQL page about name case-sensitivity Here is the article in MSDN about collations for SQL Server
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/153944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/415/" ] }
153,983
For some reason the Windows command prompt is "special" in that you have to go to a properties dialog to resize it horizontally rather than just dragging the corner of the window like every other app. Unsurprisingly this feature made it into P-P-P-Powershell as well -- is there any way around this via command prompt replacement or Windows hackery?
2019 Update: Microsoft has released the terminal app on Github & the Windows Store , and it has tabs, panels, acrylic transparency, and other features. 2016 Update: Windows 10's default conhost UI has more features, including free resize, transparency, etc (this includes cmd & powershell) I now use ConEmu (walkthrough here ) which has many features including tabs & split panes. Other options include Cmder (which comes with additional tools built in), and ConsoleZ (a fork of Console2). Console appears to no longer be updated
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/153983", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ] }
153,988
I need to copy some records from our SQLServer 2005 test server to our live server. It's a flat lookup table, so no foreign keys or other referential integrity to worry about. I could key-in the records again on the live server, but this is tiresome. I could export the test server records and table data in its entirety into an SQL script and run that, but I don't want to overwrite the records present on the live system, only add to them. How can I select just the records I want and get them transferred or otherwise into the live server? We don't have Sharepoint, which I understand would allow me to copy them directly between the two instances.
If your production SQL server and test SQL server can talk, you could just do in with a SQL insert statement. first run the following on your test server: Execute sp_addlinkedserver PRODUCTION_SERVER_NAME Then just create the insert statement: INSERT INTO [PRODUCTION_SERVER_NAME].DATABASE_NAME.dbo.TABLE_NAME (Names_of_Columns_to_be_inserted)SELECT Names_of_Columns_to_be_insertedFROM TABLE_NAME
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/153988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7703/" ] }
154,004
I have a link that I dynamically create which looks something like the following: <a onclick="Edit('value from a text column here')" href="javascript:void(null);">Edit</a> with the Edit function then taking the passed in value and putting it into a Yahoo Rich Text Editor. This works well except for when there is a single quote in the text being passed. The obvious problem being that the link then looks something like: <a onclick="Edit('I'm a jelly donut')" href="javascript:void(null);">Edit</a> Any suggestions on what I can do? I'd rather not stray too far from the structure I am currently using because it is something of a standard (and maybe the standard sucks, but that's another question altogether). Note: I am using ASP as my server side language.
Convert quote charaters to their HTML equivalents, &quot; etc. before you insert them into the HTML. There's a long list of HTML/XML character codes on wikipedia. There may well be a function to do this for you, depending on how you're dynamically generating the code: PHP has htmlspecialchars , and though I'm not familiar with ASP etc, I'm sure there are similar routines.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22777/" ] }
154,031
Pattern pattern = Pattern.compile("^[a-z]+$");String string = "abc-def";assertTrue( pattern.matcher(string).matches() ); // obviously fails Is it possible to have the character class match a "-" ?
Don't put the minus sign between characters. "[a-z-]"
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11858/" ] }
154,059
Is there a string.Empty in JavaScript, or is it just a case of checking for "" ?
Empty string, undefined, null, ... To check for a truthy value : if (strValue) { // strValue was non-empty string, true, 42, Infinity, [], ...} To check for a falsy value : if (!strValue) { // strValue was empty string, false, 0, null, undefined, ...} Empty string (only!) To check for exactly an empty string, compare for strict equality against "" using the === operator : if (strValue === "") { // strValue was empty string} To check for not an empty string strictly, use the !== operator : if (strValue !== "") { // strValue was not an empty string}
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/154059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ] }
154,075
I have a Virtual Machine in Virtual PC 2007. To start it from the desktop, I have the following command in a batch file: "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc "MY-PC" -launch But that leaves a dos prompt on the host machine until the virtual machine shuts down, and I exit out of the Virtual PC console. That's annoying. So I changed my command to use the START command, instead: start "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch But it chokes on the parameters passed into Virtual PC. START /? indicates that parameters do indeed go in that location. Has anyone used START to launch a program with multiple command-line arguments?
START has a peculiarity involving double quotes around the first parameter. If the first parameter has double quotes it uses that as the optional TITLE for the new window. I believe what you want is: start "" "c:\program files\Microsoft Virtual PC\Virtual PC.exe" -pc MY-PC -launch In other words, give it an empty title before the name of the program to fake it out.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/154075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ] }
154,097
I've switched computers a few times recently, and somewhere along the way I lost my .emacs. I'm trying to build it up again, but while I'm at it, I thought I'd pick up other good configurations that other people use. So, if you use Emacs, what's in your .emacs? Mine is pretty barren right now, containing only: Global font-lock-mode! (global-font-lock-mode 1) My personal preferences with respect to indentation, tabs, and spaces. Use cperl-mode instead of perl-mode. A shortcut for compilation. What do you think is useful?
Use the ultimate dotfiles site . Add your '.emacs' here. Read the '.emacs' of others.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3508/" ] }
154,109
When using the ObsoleteAtribute in .Net it gives you compiler warnings telling you that the object/method/property is obsolete and somthing else should be used. I'm currently working on a project that requires a lot of refactoring an ex-employees code. I want to write a custom attribute that I can use to mark methods or properties that will generate compiler warnings that give messages that I write. Something like this [MyAttribute("This code sux and should be looked at")]public void DoEverything(){} <MyAttribute("This code sux and should be looked at")>Public Sub DoEverything()End Sub I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.
This is worth a try. You can't extend Obsolete, because it's final, but maybe you can create your own attribute, and mark that class as obsolete like this: [Obsolete("Should be refactored")]public class MustRefactor: System.Attribute{} Then when you mark your methods with the "MustRefactor" attribute, the compile warnings will show. It generates a compile time warning, but the error message looks funny, you should see it for yourself and choose. This is very close to what you wanted to achieve. UPDATE:With this code It generates a warning (not very nice, but I don't think there's something better). public class User{ private String userName; [TooManyArgs] // Will show warning: Try removing some arguments public User(String userName) { this.userName = userName; } public String UserName { get { return userName; } } [MustRefactor] // will show warning: Refactor is needed Here public override string ToString() { return "User: " + userName; }}[Obsolete("Refactor is needed Here")]public class MustRefactor : System.Attribute{}[Obsolete("Try removing some arguments")]public class TooManyArgs : System.Attribute{}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ] }
154,112
Without running this code, identify which Foo method will be called: class A{ public void Foo( int n ) { Console.WriteLine( "A::Foo" ); }}class B : A{ /* note that A::Foo and B::Foo are not related at all */ public void Foo( double n ) { Console.WriteLine( "B::Foo" ); }}static void Main( string[] args ){ B b = new B(); /* which Foo is chosen? */ b.Foo( 5 );} Which method? And why? No cheating by running the code. I found this puzzle on the web; I like it and I think I'm going to use it as an interview question...Opinions? EDIT: I wouldn't judge a candidate on getting this wrong, I'd use it as a way to open a fuller discussion about the C# and CLR itself, so I can get a good understanding of the candidates abilities. Source: http://netpl.blogspot.com/2008/06/c-puzzle-no8-beginner.html
I really wouldn't use this as an interview question. I know the answer and the reasoning behind it, but something like this should come up so rarely that it shouldn't be a problem. Knowing the answer really doesn't show much about a candidate's ability to code. Note that you'll get the same behaviour even if A.Foo is virtual and B overrides it. If you like C# puzzles and oddities, I've got a few too (including this one) .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ] }
154,119
This was an interview question. Given Visual Studio 2008 and an icon saved as a .PNG file, they required the image as an embedded resource and to be used as the icon within the title bar of a form. I'm looking for what would have been the model answer to this question, Both (working!) code and any Visual Studio tricks. (Model answer is one that should get me the job if I meet it next time around.) Specifically I don't know how to load the image once it is an embedded resource nor how to get it as the icon for the title bar. As a part solution, ignoring the embedded bit, I copied the resource to the ouput directory and tried the following:- public partial class Form1 : Form{ public Form1() { InitializeComponent(); this.Icon = new Icon("Resources\\IconImage.png"); }} This failed with the error "Argument 'picture' must be a picture that can be used as a Icon." I presuming that the .PNG file actually needed to be a .ICO, but I couldn't see how to make the conversion. Is this presumption correct or is there a different issue?
Fire up VS, start new Windows Application. Open the properties sheet, add the .png file as a resource (in this example: glider.png ). From hereon, you can access the resource as a Bitmap file as WindowsFormsApplication10.Properties.Resources.glider Code for using it as an application icon: public Form1() { InitializeComponent(); Bitmap bmp = WindowsFormsApplication10.Properties.Resources.glider; this.Icon = Icon.FromHandle(bmp.GetHicon()); }
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22284/" ] }
154,136
In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless do while loop. Here are examples. #define FOO(X) do { f(X); g(X); } while (0)#define FOO(X) if (1) { f(X); g(X); } else I can't see what the do while is doing. Why not just write this without it? #define FOO(X) f(X); g(X)
The do ... while and if ... else are there to make it so that asemicolon after your macro always means the same thing. Let's say youhad something like your second macro. #define BAR(X) f(x); g(x) Now if you were to use BAR(X); in an if ... else statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise. if (corge) BAR(corge);else gralt(); The above code would expand into if (corge) f(corge); g(corge);else gralt(); which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect. if (corge) {f(corge); g(corge);};else gralt(); There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression. #define BAR(X) f(X), g(X) The above version of bar BAR expands the above code into what follows, which is syntactically correct. if (corge) f(corge), g(corge);else gralt(); This doesn't work if instead of f(X) you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like do ... while to cause the macro to be a single statement that takes a semicolon without confusion. #define BAR(X) do { \ int i = f(X); \ if (i > 4) g(i); \} while (0) You don't have to use do ... while , you could cook up something with if ... else as well, although when if ... else expands inside of an if ... else it leads to a " dangling else ", which could make an existing dangling else problem even harder to find, as in the following code. if (corge) if (1) { f(corge); g(corge); } else;else gralt(); The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare BAR as an actual function, not a macro. In summary, the do ... while is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/154136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11138/" ] }
154,159
Looking for good techniques to justify "great than normal" machine for developers. The company I work for buys the same underpowered $500 dollar systems for everyone, and looking for ways to prove ROI or arguments to use. Sorry, I didn't say this in the initial question, the stack is VS 2008, SQL 2005/2008. As duties dictate we are SQL admins as well as Web/Winform/WebService Developers. So its very typical to have 2 VS sessions and at least one SQL session open at the same time.
Figure out how long you spend in the edit -> build -> debug cycle, then total that up over the course of a year. Then guesstimate (with some justifiable inflation) what a good computer would do to that number. Multiply the time improvement by your hourly rate, and present it as a business case.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
154,163
I need to detect whether my application is running within a virtualized OS instance or not. I've found an article with some useful information on the topic. The same article appears in multiple places, I'm unsure of the original source. VMware implements a particular invalid x86 instruction to return information about itself, while VirtualPC uses a magic number and I/O port with an IN instruction. This is workable, but appears to be undocumented behavior in both cases. I suppose a future release of VMWare or VirtualPC might change the mechanism. Is there a better way? Is there a supported mechanism for either product? Similarly, is there a way to detect Xen or VirtualBox ? I'm not concerned about cases where the platform is deliberately trying to hide itself. For example, honeypots use virtualization but sometimes obscure the mechanisms that malware would use to detect it. I don't care that my app would think it is not virtualized in these honeypots, I'm just looking for a "best effort" solution. The application is mostly Java, though I'm expecting to use native code plus JNI for this particular function. Windows XP/Vista support is most important, though the mechanisms described in the referenced article are generic features of x86 and don't rely on any particular OS facility.
Have you heard about blue pill, red pill? . It's a technique used to see if you are running inside a virtual machine or not. The origin of the term stems from the matrix movie where Neo is offered a blue or a red pill (to stay inside the matrix = blue, or to enter the 'real' world = red). The following is some code that will detect whether you are running inside 'the matrix' or not: (code borrowed from this site which also contains some nice information about the topic at hand): int swallow_redpill () { unsigned char m[2+4], rpill[] = "\x0f\x01\x0d\x00\x00\x00\x00\xc3"; *((unsigned*)&rpill[3]) = (unsigned)m; ((void(*)())&rpill)(); return (m[5]>0xd0) ? 1 : 0; } The function will return 1 when you are running inside a virutal machine, and 0 otherwise.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4761/" ] }
154,185
I have heard this concept used frequently, but I don't have a really good grasp of what it is.
Converting an object in memory into a format that can be written to disk, or sent over the wire, etc. Wikipedia's description .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
154,204
Is there any way to change the default tab size in a .NET RichTextBox?It currently seems to be set to the equivalent of 8 spaces which is kinda large for my taste. Edit: To clarify, I want to set the global default of "\t" displays as 4 spaces for the control. From what I can understand, the SelectionTabs property requires you to select all the text first and then the the tab widths via the array. I will do this if I have to, but I would rather just change the global default once, if possible, sot that I don't have to do that every time.
You can set it by setting the SelectionTabs property. private void Form1_Load(object sender, EventArgs e){ richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };} UPDATE: The sequence matters.... If you set the tabs prior to the control's text being initialized, then you don't have to select the text prior to setting the tabs. For example, in the above code, this will keep the text with the original 8 spaces tab stops: richTextBox1.Text = "\t1\t2\t3\t4";richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 }; But this will use the new ones: richTextBox1.SelectionTabs = new int[] { 100, 200, 300, 400 };richTextBox1.Text = "\t1\t2\t3\t4";
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ] }
154,206
I am trying to use a DynamicResource in Storyboard contained within a ControlTemplate. But, when I try to do this, I get a 'Cannot freeze this Storyboard timeline tree for use across threads' error. What is going on here?
No, you can't use a DynamicResource in a Storyboard that is contained within a Style or ControlTemplate. In fact, you can't use a data binding expression either. The story here is that everything within a Style or ControlTemplate must be safe for use across threads and the timing system actually tries to freeze the Style or ControlTemplate to make them thread-safe. However, if a DynamicResource or data binding expression is present, it is unable to freeze them. For more info see: MSDN Link . Check out the 'Animate in a Style' and the 'Animate in a ControlTemplate' sections (this documentation page is rather long). And for a workaround (at least for my scenario) see: WPF Forum Post . Hope this helps someone. I've lost more than enough hair on it. Cory
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22294/" ] }
154,256
Possible Duplicate: C#: How to enumerate an enum? The subject says all. I want to use that to add the values of an enum in a combobox. Thanks vIceBerg
string[] names = Enum.GetNames (typeof(MyEnum)); Then just populate the dropdown withe the array
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ] }
154,270
It's been a while since I've programmed a GUI program, so this may end up being super simple, but I can't find the solution anywhere online. Basically my problem is that when I maximize my program, all the things inside of the window (buttons, textboxes, etc.) stay in the same position in the window, which results in a large blank area near the bottom and right side. Is there a way of making the the elements in the program to stretch to scale?
You want to check and properly set the Anchor and Dock properties on each control in the Form. The Anchor property on a control tells which sides of the form (top, bottom, left, right) the control is 'anchored' to. When the form is resized, the distance between the control and its anchors will stay the same. This lets you make a control stay in the bottom right corner for example. The Dock property instructs the control to fill the entire parent form or to fill one side of it (again top, bottom, left or right).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23875/" ] }
154,299
I am debugging a VB6 executable. The executable loads dlls and files from it's current directory, when running. When run in debugger, the current directory seems to be VB6's dir. How do I set working directory for VB6?
It doesn't seems to be a "out of the box" solution for this thing. Taken from The Old Joel On Software Forums Anyways.. to put this topic to rest.. the following was my VB6 solution: I define 2 symbols in my VB project "MPDEBUG" and "MPRELEASE" and call the following function as the first operation in my apps entry point function. Public Sub ChangeDirToApp()#If MPDEBUG = 0 And MPRELEASE = 1 Then ' assume that in final release builds the current dir will be the location ' of where the .exe was installed; paths are relative to the install dir ChDrive App.path ChDir App.path#Else ' in all debug/IDE related builds, we need to switch to the "bin" dir ChDrive App.path ChDir App.path & BackSlash(App.path) & "..\bin"#End IfEnd Sub
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ] }
154,307
I just saw this behaviour and I'm a bit surprised by it... If I add 3 or 4 elements to a Dictionary, and then do a "For Each" to get all the keys, they appear in the same order I added them. The reason this surprises me is that a Dictionary is supposed to be a HashTable internally, so I expected things to come out in ANY order (ordered by the hash of the key, right?) What am I missing here?Is this a behaviour I can count on? EDIT: OK, I thought already of many of the reasons why this might happen (like the separate list to entries, whether this is a coincidence, etc).My question is, does anyone know how this really works?
If you use .NET Reflector on the 3.5 class libraries you can see that the implementation of Dictionary actually stores the items in an array (which is resized as needed), and hashes indexes into that array. When getting the keys, it completely ignores the hashtable and iterates over the array of items. For this reason, you will see the behavior you have described since new items are added at the end of the array. It looks like if you do the following: add 1add 2add 3add 4remove 2add 5 you will get back 1 5 3 4 because it reuses empty slots. It is important to note, like many others have, you cannot count on this behavior in future (or past) releases. If you want your dictionary to be sorted then there is a SortedDictionary class for this purpose.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3314/" ] }
154,309
One of our programs is sometimes getting an OutOfMemory error on one user's machine, but of course not when I'm testing it. I just ran it with JProfiler (on a 10 day evaluation license because I've never used it before), and filtering on our code prefix, the biggest chunk both in total size and number of instances is 8000+ instances of a particular simple class. I clicked the "Garbage Collect" button on JProfiler, and most instances of other classes of ours went away, but not these particular ones. I ran the test again, still in the same instance, and it created 4000+ more instances of the class, but when I clicked "Garbage Collect", those went away leaving the 8000+ original ones. These instances do get stuck into various Collections at various stages. I assume that the fact that they're not garbage collected must mean that something is holding onto a reference to one of the collections so that's holding onto a reference to the objects. Any suggestions how I can figure out what is holding onto the reference? I'm looking for suggestions of what to look for in the code, as well as ways to find this out in JProfiler if there are.
Dump the heap and inspect it. I'm sure there's more than one way to do this, but here is a simple one. This description is for MS Windows, but similar steps can be taken on other operating systems. Install the JDK if you don't already have it. It comes with a bunch of neat tools. Start the application. Open task manager and find the process id (PID) for java.exe (or whatever executable you are using). If the PID's aren't shown by default, use View > Select Columns... to add them. Dump the heap using jmap . Start the jhat server on the file you generated and open your browser to http://localhost:7000 (the default port is 7000). Now you can browse the type you're interested in and information like the number of instances, what has references to them, etcetera. Here is an example: C:\dump>jmap -dump:format=b,file=heap.bin 3552C:\dump>jhat heap.binReading from heap.bin...Dump file created Tue Sep 30 19:46:23 BST 2008Snapshot read, resolving...Resolving 35484 objects...Chasing references, expect 7 dots.......Eliminating duplicate references.......Snapshot resolved.Started HTTP server on port 7000Server is ready. To interpret this, it is useful to understand some of the array type nomenclature Java uses - like knowing that class [Ljava.lang.Object; really means an object of type Object[] .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3333/" ] }
154,314
I've found a couple of references ( for example ) that suggest using final as much as possible and I'm wondering how important that is. This is mainly in the the context of method parameters and local variables, not final methods or classes. For constants, it makes obvious sense. On one hand, the compiler can make some optimizations and it makes the programmer's intent clearer. On the other hand, it adds verbosity and the optimizations may be trivial. Is it something I should make an effort to remember?
Obsess over: Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.) Final static fields - Although I use enums now for many of the cases where I used to use static final fields. Consider but use judiciously: Final classes - Framework/API design is the only case where I consider it. Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation. Ignore unless feeling anal: Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class. Edit: note that one use case where final local variables are actually very useful as mentioned by @adam-gent is when value gets assigned to the var in the if / else branches.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/154314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23669/" ] }
154,332
I'm using mysqldump to replicate a database between accounts on a particular machine. Everything works just great, except when we get to our defined views. Because the dump includes a line like the following ... /*!50013 DEFINER=`user_a`@`localhost` SQL SECURITY DEFINER */ ... when loading the dump into mysql on user_b we receive an error: ERROR 1227 (42000) at line 657: Access denied; you need the SUPER privilege for this operation Needless to say, I don't have SUPER privilege on this mysql instance. Is there a way to convince mysqldump to dump the views in a user-agnostic way? I can't find anything in the manual on this point. Do I have to actually parse the dumpfile to replace the usernames? Or am I missing something?
same problem. I solved it that way: mysqldump -uuser1 -ppassword1 database1 > backup.sqlsed '/^\/\*\!50013 DEFINER/d' backup.sql > backup_without_50013.sqlmysql -u user2 -ppassword2 -D database2 < backup_without_50013.sql The interesting thing is the sed command which, here, removes all lines beginning with /*!50013. Heidy
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21632/" ] }
154,365
I need to find occurrences of ~ 25 000 words within a text. What is the most suitable algorithm/library for this purpose? target language is C++
build a hashtable with the words, and scan throuhgt the text, for each word lookup in the wordtable and stuff the needed info (increment count, add to a position list, whatever).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/127878/" ] }
154,369
I need to store the summer time (daylight saving time) change-over rules for different world regions in a database. I already have a way of storing regions and sub-regions (so the whole "half of Australia"/Arizona/Navaho problem is taken care of), but I'm wondering what the most efficient schema would be to accomplish this. The two options as I see them: Have a table which contains unique one row for each year and region giving the start and end times for summer time as well as the specific offset Have a table which stores a formula and effective date range for each region (effective range required for regions like Israel) The advantage to the first is flexibility, since literally anything is possible. Unfortunately, it also requires (a) more space, and correspondingly (b) a lot of work to get the data input. The second is nice because one row could correspond to one region for decades, but it also requires some sort of language parser and interpreter in the application layer. Since this database will be used by several different applications written in languages without powerful text processing capabilities, I would rather avoid that route. I would love to just use zoneinfo or something like that, but unfortunately that's not an option in this case. Likewise, I cannot normalize the dates, timezone and summer time info must be in the database to satisfy certain use cases. Does anybody have any experience doing something similar? Likewise, does anyone have any brilliant options that I may have missed?
You're pretty much doomed to the first option. You can pre-generate dates as far ahead as you wish for countries that have "rules" regarding time changes, but some areas do not have any rule and the changes are enacted either by dictatorial fiat or by legislative vote annually (Brazil did so until this year). This is why all OS vendors roll out timezone file changes once or twice a year -- they have to, because they cannot generate a 100% accurate file programatically.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9815/" ] }
154,372
How do I get a list of all the tables defined for the database when using active record?
Call ActiveRecord::ConnectionAdapters::SchemaStatements#tables . This method is undocumented in the MySQL adapter, but is documented in the PostgreSQL adapter. SQLite/SQLite3 also has the method implemented, but undocumented. >> ActiveRecord::Base.connection.tables=> ["accounts", "assets", ...] See activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb:21 , as well as the implementations here: activerecord/lib/active_record/connection_adapters/mysql_adapter.rb:412 activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb:615 activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb:176
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/154372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3547/" ] }
154,430
I need to store encrypted data (few small strings) between application runs. I do not want the user to provide a passphrase every time (s)he launches the application. I.e. after all it goes down to storing securely the encryption key(s). I was looking into RSACryptoServiceProvider and using PersistentKeyInCsp, but I'm not sure how it works. Is the key container persistent between application runs or machine restarts? If yes, is it user specific, or machine specific. I.e. if I store my encrypted data in user's roaming profile, can I decrypt the data if the user logs on a different machine? If the above does not work, what are my options (I need to deal with roaming profiles).
The Data Protection API (DPAPI) does exactly what you want. It provides symmetric encryption of arbitrary data, using the credentials of the machine or (better) the user, as the encryption key. You don't have to worry about managing the keys; Windows takes care of that for you. If the user changes his password, Windows will re-encrypt the data using the user's new password. DPAPI is exposed in .NET with the System.Security.Cryptography.ProtectedData class: byte[] plaintextBytes = GetDataToProtect();byte[] encodedBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.CurrentUser); The second parameter of the Protect method is an optional entropy byte array, which can be used as an additional application-specific "secret". To decrypt, use the ProtectedData.Unprotect call: byte[] encodedBytes = GetDataToUnprotect();byte[] plaintextBytes = ProtectedData.Unprotect(encodedBytes, null, DataProtectionScope.CurrentUser); DPAPI works correctly with roaming profiles (as described here ), though you'll need to store the encrypted data in a place (network share, IsolatedStorage with IsolatedStorageScope.Roaming , etc.) that your various machines can access. See the ProtectedData class in MSDN for more information. There's a DPAPI white paper here , with more information than you'd ever want.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8220/" ] }
154,434
How do you get spreadsheet data in Excel to recalculate itself from within VBA, without the kluge of just changing a cell value?
The following lines will do the trick: ActiveSheet.EnableCalculation = False ActiveSheet.EnableCalculation = True Edit: The .Calculate() method will not work for all functions. I tested it on a sheet with add-in array functions. The production sheet I'm using is complex enough that I don't want to test the .CalculateFull() method, but it may work.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13295/" ] }
154,441
I need to test some HTTP interaction with a client I'd rather not modify. What I need to test is the behavior of the server when the client's requests include a certain, static header. I'm thinking the easiest way to run this test is to set up an HTTP proxy that inserts the header on every request. What would be the simplest way to set this up?
I do something like this in my development environment by configuring Apache on port 80 as a proxy for my application server on port 8080, with the following Apache config: NameVirtualHost *<VirtualHost *> <Proxy http://127.0.0.1:8080/*> Allow from all </Proxy> <LocationMatch "/myapp"> ProxyPass http://127.0.0.1:8080/myapp ProxyPassReverse http://127.0.0.1:8080/myapp Header add myheader "myvalue" RequestHeader set myheader "myvalue" </LocationMatch></VirtualHost> See LocationMatch and RequestHeader documentation. This adds the header myheader: myvalue to requests going to the application server.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154441", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3518/" ] }
154,443
Can I run the python interpreter without generating the compiled .pyc files?
From "What’s New in Python 2.6 - Interpreter Changes" : Python can now be prevented fromwriting .pyc or .pyo files bysupplying the -B switch to the Pythoninterpreter, or by setting the PYTHONDONTWRITEBYTECODE environmentvariable before running theinterpreter. This setting is availableto Python programs as the sys.dont_write_bytecode variable, andPython code can change the value tomodify the interpreter’s behaviour. So run your program as python -B prog.py . Update 2010-11-27: Python 3.2 addresses the issue of cluttering source folders with .pyc files by introducing a special __pycache__ subfolder, see What's New in Python 3.2 - PYC Repository Directories . NOTE: The default behavior is to generate the bytecode and is done for "performance" reasons (for more information see here for python2 and see here for python3 ). The generation of bytecode .pyc files is a form of caching (i.e. greatly improves average performance). Configuring python with PYTHONDONTWRITEBYTECODE=1 can be bad for python performance (for python2 see https://www.python.org/dev/peps/pep-0304/ and for python3 see https://www.python.org/dev/peps/pep-3147/ ). If you are interested in the performance impact please see here https://github.com/python/cpython .
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/154443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1476/" ] }
154,469
A feature of C++ is the ability to create unnamed (anonymous) namespaces, like so: namespace { int cannotAccessOutsideThisFile() { ... }} // namespace You would think that such a feature would be useless -- since you can't specify the name of the namespace, it's impossible to access anything within it from outside. But these unnamed namespaces are accessible within the file they're created in, as if you had an implicit using-clause to them. My question is, why or when would this be preferable to using static functions? Or are they essentially two ways of doing the exact same thing?
The C++ Standard reads in section 7.3.1.1 Unnamed namespaces, paragraph 2: The use of the static keyword isdeprecated when declaring objects in anamespace scope, the unnamed-namespaceprovides a superior alternative. Static only applies to names of objects, functions, and anonymous unions, not to type declarations. Edit: The decision to deprecate this use of the static keyword (affecting visibility of a variable declaration in a translation unit) has been reversed ( ref ). In this case using a static or an unnamed namespace are back to being essentially two ways of doing the exact same thing. For more discussion please see this SO question. Unnamed namespace 's still have the advantage of allowing you to define translation-unit-local types. Please see this SO question for more details. Credit goes to Mike Percy for bringing this to my attention.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/154469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ] }
154,483
I would like to do some condition formatting of strings. I know that you can do some conditional formatting of integers and floats as follows: Int32 i = 0;i.ToString("$#,##0.00;($#,##0.00);Zero"); The above code would result in one of three formats if the variable is positive, negative, or zero. I would like to know if there is any way to use sections on string arguments. For a concrete, but contrived example, I would be looking to replace the "if" check in the following code: string MyFormatString(List<String> items, List<String> values){ string itemList = String.Join(", " items.ToArray()); string valueList = String.Join(", " values.ToArray()); string formatString; if (items.Count > 0) //this could easily be: //if (!String.IsNullOrEmpty(itemList)) { formatString = "Items: {0}; Values: {1}"; } else { formatString = "Values: {1}"; } return String.Format(formatString, itemList, valueList);}
Well, you can simplify it a bit with the conditional operator: string formatString = items.Count > 0 ? "Items: {0}; Values: {1}" : "Values: {1}";return string.Format(formatString, itemList, valueList); Or even include it in the same statement: return string.Format(items.Count > 0 ? "Items: {0}; Values: {1}" : "Values: {1}", itemList, valueList); Is that what you're after? I don't think you can have a single format string which sometimes includes bits and sometimes it doesn't.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ] }
154,485
The title pretty much says it all. I want to create a SqlConnection and then check that connection without opening a database, cause at that point I don't know yet where will I connect to. Is it possible to do that? The SqlConnection class has a 'Open' member which tries to open the database you'd set in the Database property, and if you didn't set one, SqlServer tries with the master db. The thing is the user I'm trying to connect with (MACHINE\ASPNET) has access to some databases (which I don't know yet) and not the master db. Regards,Seba
Connect to temp db. Everybody has accecss to tempdb so you will be able to authenticate yourself for access. Later when you know the actual database , you can change this property to connect to the db you want.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23893/" ] }
154,489
I've been trying this a few different ways, but I'm reaching the conclusion that it can't be done. It's a language feature I've enjoyed from other languages in the past. Is it just something I should just write off?
No, static indexers aren't supported in C#. Unlike other answers, however, I see how there could easily be point in having them. Consider: Encoding x = Encoding[28591]; // Equivalent to Encoding.GetEncoding(28591)Encoding y = Encoding["Foo"]; // Equivalent to Encoding.GetEncoding("Foo") It would be relatively rarely used, I suspect, but I think it's odd that it's prohibited - it gives asymmetry for no particular reason as far as I can see.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
154,504
Timsort is an adaptive, stable, natural mergesort. It has supernatural performance on many kinds of partially ordered arrays (less than lg(N!) comparisons needed, and as few as N-1), yet as fast as Python's previous highly tuned samplesort hybrid on random arrays. Have you seen timsort used outside of CPython? Does it make sense?
Yes, it makes quite a bit of sense to use timsort outside of CPython, in specific, or Python, in general. There is currently an effort underway to replace Java's "modified merge sort" with timsort, and the initial results are quite positive.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20310/" ] }
154,533
What is the best way to bind WPF properties to ApplicationSettings in C#? Is there an automatic way like in a Windows Forms Application? Similar to this question , how (and is it possible to) do you do the same thing in WPF?
You can directly bind to the static object created by Visual Studio. In your windows declaration add: xmlns:p="clr-namespace:UserSettings.Properties" where UserSettings is the application namespace. Then you can add a binding to the correct setting: <TextBlock Height="{Binding Source={x:Static p:Settings.Default}, Path=Height, Mode=TwoWay}" ....... /> Now you can save the settings, per example when you close your application: protected override void OnClosing(System.ComponentModel.CancelEventArgs e){ Properties.Settings.Default.Save(); base.OnClosing(e); }
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/154533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3798/" ] }
154,535
I have used Photoshop CS2's "Save for Web" feature to create a table of images for my site layout. This HTML appears fine in a web browser, however when imported into Visual Studio and viewed in the site designer, the metrics are wrong and there are horizontal gaps between images (table cells). The output from Photoshop does not refer to any stylesheets. The table attributes set border, cellpadding and cellspacing to 0. Here is how it looks in the Designer: And here is how it looks in the browser: Is Visual Studio picky about layout of tables and images? Is this a bug in Visual Studio 2005?
You can directly bind to the static object created by Visual Studio. In your windows declaration add: xmlns:p="clr-namespace:UserSettings.Properties" where UserSettings is the application namespace. Then you can add a binding to the correct setting: <TextBlock Height="{Binding Source={x:Static p:Settings.Default}, Path=Height, Mode=TwoWay}" ....... /> Now you can save the settings, per example when you close your application: protected override void OnClosing(System.ComponentModel.CancelEventArgs e){ Properties.Settings.Default.Save(); base.OnClosing(e); }
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/154535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/414107/" ] }
154,536
Does anyone know of any good C++ code that does this?
I faced the encoding half of this problem the other day. Unhappy with the available options, and after taking a look at this C sample code , i decided to roll my own C++ url-encode function: #include <cctype>#include <iomanip>#include <sstream>#include <string>using namespace std;string url_encode(const string &value) { ostringstream escaped; escaped.fill('0'); escaped << hex; for (string::const_iterator i = value.begin(), n = value.end(); i != n; ++i) { string::value_type c = (*i); // Keep alphanumeric and other accepted characters intact if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { escaped << c; continue; } // Any other characters are percent-encoded escaped << uppercase; escaped << '%' << setw(2) << int((unsigned char) c); escaped << nouppercase; } return escaped.str();} The implementation of the decode function is left as an exercise to the reader. :P
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033811/" ] }
154,543
If you create a panel on a form and set it to Dock=Top and drop another panel and set its Dock=Fill, it may fill the entire form, ignoring the first panel. Changing the tab order does nothing.
Docking layout depends on the order of sibling controls. Controls are docked "button up", so the last control in the collection is docked first . A docked control only take the layout of previously docked siblings into account. Hence the control with Dock=Fill should be first (top) in the sibling order, if you want it to take the other docked controls into account. If it is not the first control, earlier controls will overlap it. This can be confusing because the sibling-order is not necessarily the same as the visual order, and the sibling order is not always apparent from the design view. The Document outline window (View -> Other Windows -> Document outline) gives a useful tree-view over the control hierarchy and order, and allows you to change the sibling order of controls. You can also change sibling order directly in the designer by context menu -> Bring to front / Send to back, which moves the control to be first or last of the siblings. These menu labels may be somewhat confusing since the actual effect depends on the layout model. With fixed positioned controls, the 2D position is independent of the sibling order, but when controls are overlapping, the control earliest in the order will be "on top", hiding part of siblings later in the order. In this context Bring to front / Send to back makes sense. Inside flow- or table-layout panels, the creation order determines the visual order of the controls. There is no overlapping controls. So bring to front/send to back really means make first or last in the order of controls. With docked layout, the bring to front / send to back may be even more confusing since it determines in which order the docking is calculated, so "bring to front" on a fill-docked control will place the control in the middle of the parent, taking all edge-docked controls into account.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/154543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2277/" ] }
154,551
Let's say that a class has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented. To increment this field, which approach should be used, and why? lock(this.locker) this.counter++; , Interlocked.Increment(ref this.counter); , Change the access modifier of counter to public volatile . Now that I've discovered volatile , I've been removing many lock statements and the use of Interlocked . But is there a reason not to do this?
Worst (won't actually work) Change the access modifier of counter to public volatile As other people have mentioned, this on its own isn't actually safe at all. The point of volatile is that multiple threads running on multiple CPUs can and will cache data and re-order instructions. If it is not volatile , and CPU A increments a value, then CPU B may not actually see that incremented value until some time later, which may cause problems. If it is volatile , this just ensures the two CPUs see the same data at the same time. It doesn't stop them at all from interleaving their reads and write operations which is the problem you are trying to avoid. Second Best: lock(this.locker) this.counter++ ; This is safe to do (provided you remember to lock everywhere else that you access this.counter ). It prevents any other threads from executing any other code which is guarded by locker .Using locks also, prevents the multi-CPU reordering problems as above, which is great. The problem is, locking is slow, and if you re-use the locker in some other place which is not really related then you can end up blocking your other threads for no reason. Best Interlocked.Increment(ref this.counter); This is safe, as it effectively does the read, increment, and write in 'one hit' which can't be interrupted. Because of this, it won't affect any other code, and you don't need to remember to lock elsewhere either. It's also very fast (as MSDN says, on modern CPUs, this is often literally a single CPU instruction). I'm not entirely sure however if it gets around other CPUs reordering things, or if you also need to combine volatile with the increment. InterlockedNotes: INTERLOCKED METHODS ARE CONCURRENTLY SAFE ON ANY NUMBER OF COREs OR CPUs. Interlocked methods apply a full fence around instructions they execute, so reordering does not happen. Interlocked methods do not need or even do not support access to a volatile field , as volatile is placed a half fence around operations on given field and interlocked is using the full fence. Footnote: What volatile is actually good for. As volatile doesn't prevent these kinds of multithreading issues, what's it for? A good example is saying you have two threads, one which always writes to a variable (say queueLength ), and one which always reads from that same variable. If queueLength is not volatile, thread A may write five times, but thread B may see those writes as being delayed (or even potentially in the wrong order). A solution would be to lock, but you could also use volatile in this situation. This would ensure that thread B will always see the most up-to-date thing that thread A has written. Note however that this logic only works if you have writers who never read, and readers who never write, and if the thing you're writing is an atomic value. As soon as you do a single read-modify-write, you need to go to Interlocked operations or use a Lock.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/154551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ] }
154,577
In terms of Java, when someone asks: what is polymorphism? Would overloading or overriding be an acceptable answer? I think there is a bit more to it than that. IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding? I think overloading is not the right answer for sure.
The clearest way to express polymorphism is via an abstract base class (or interface) public abstract class Human{ ... public abstract void goPee();} This class is abstract because the goPee() method is not definable for Humans. It is only definable for the subclasses Male and Female. Also, Human is an abstract concept — You cannot create a human that is neither Male nor Female. It’s got to be one or the other. So we defer the implementation by using the abstract class. public class Male extends Human{... @Override public void goPee(){ System.out.println("Stand Up"); }} and public class Female extends Human{... @Override public void goPee(){ System.out.println("Sit Down"); }} Now we can tell an entire room full of Humans to go pee. public static void main(String[] args){ ArrayList<Human> group = new ArrayList<Human>(); group.add(new Male()); group.add(new Female()); // ... add more... // tell the class to take a pee break for (Human person : group) person.goPee();} Running this would yield: Stand UpSit Down...
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/154577", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
154,625
I've noticed that sometimes wrapper scripts will use ${1:+"$@"} for the parameters rather than just "$@" . For example, http://svn.macosforge.org/repository/macports/trunk/dports/editors/vim-app/files/gvim.sh uses exec "$binary" $opts ${1:+"$@"} Can anyone break ${1:+"$@"} down into English and explain why it would be an advantage over plain "$@" ?
'Hysterical Raisins', aka Historical Reasons. The explanation from JesperE (or the Bash man page on shell parameter expansion ) is accurate for what it does: If $1 exists and is not an empty string, then substitute the quoted list of arguments. Once upon 20 or so years ago, some broken minor variants of the Bourne Shell substituted an empty string "" for "$@" if there were no arguments, instead of the correct, current behaviour of substituting nothing. Whether any such systems are still in use is open to debate. [Hmm: that expansion would not work correctly for: command '' arg2 arg3 ... In this context, the correct notation is: ${1+"$@"} This works correctly whether $1 is an empty argument or not. So, someone remembered the notation incorrectly, accidentally introducing a bug.]
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
154,630
Other than -Wall , what other warnings have people found useful? Options to Request or Suppress Warnings
I routinely use: gcc -m64 -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith -Wcast-qual \ -Wstrict-prototypes -Wmissing-prototypes This set catches a lot for people unused to it (people whose code I get to compile with those flags for the first time); it seldom gives me a problem (though -Wcast-qual is occasionally a nuisance).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9831/" ] }
154,636
At the moment we use HSQLDB as an embedded database, but we search for a database with less memory footprint as the data volume grows. Derby / JavaDB is not an option at the moment because it stores properties globally in the system properties. So we thought of h2 . While we used HSQLDB we created a Server-object, set the parameters and started it. This is described here (and given as example in the class org.hsqldb.test.TestBase). The question is: Can this be done analogous with the h2 database, too? Do you have any code samples for that? Scanning the h2-page, I did not find an example.
From the download, I see that the file tutorial.html has this import org.h2.tools.Server;...// start the TCP ServerServer server = Server.createTcpServer(args).start();...// stop the TCP Serverserver.stop();
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13209/" ] }
154,672
I asked a question about Lua perfromance, and on of the responses asked: Have you studied general tips for keeping Lua performance high? i.e. know table creation and rather reuse a table than create a new one, use of 'local print=print' and such to avoid global accesses. This is a slightly different question from Lua Patterns,Tips and Tricks because I'd like answers that specifically impact performance and (if possible) an explanation of why performance is impacted. One tip per answer would be ideal.
In response to some of the other answers and comments: It is true that as a programmer you should generally avoid premature optimization. But . This is not so true for scripting languages where the compiler does not optimize much -- or at all. So, whenever you write something in Lua, and that is executed very often, is run in a time-critical environment or could run for a while, it is a good thing to know things to avoid (and avoid them). This is a collection of what I found out over time. Some of it I found out over the net, but being of a suspicious nature when the interwebs are concerned I tested all of it myself. Also, I have read the Lua performance paper at Lua.org. Some reference: Lua Performance Tips Lua-users.org Optimisation Tips Avoid globals This is one of the most common hints, but stating it once more can't hurt. Globals are stored in a hashtable by their name. Accessing them means you have to access a table index. While Lua has a pretty good hashtable implementation, it's still a lot slower than accessing a local variable. If you have to use globals, assign their value to a local variable, this is faster at the 2nd variable access. do x = gFoo + gFoo;enddo -- this actually performs better. local lFoo = gFoo; x = lFoo + lFoo;end (Not that simple testing may yield different results. eg. local x; for i=1, 1000 do x=i; end here the for loop header takes actually more time than the loop body, thus profiling results could be distorted.) Avoid string creation Lua hashes all strings on creation, this makes comparison and using them in tables very fast and reduces memory use since all strings are stored internally only once. But it makes string creation more expensive. A popular option to avoid excessive string creation is using tables. For example, if you have to assemble a long string, create a table, put the individual strings in there and then use table.concat to join it once -- do NOT do something like thislocal ret = "";for i=1, C do ret = ret..foo();end If foo() would return only the character A , this loop would create a series of strings like "" , "A" , "AA" , "AAA" , etc. Each string would be hashed and reside in memory until the application finishes -- see the problem here? -- this is a lot fasterlocal ret = {};for i=1, C do ret[#ret+1] = foo();endret = table.concat(ret); This method does not create strings at all during the loop, the string is created in the function foo and only references are copied into the table. Afterwards, concat creates a second string "AAAAAA..." (depending on how large C is). Note that you could use i instead of #ret+1 but often you don't have such a useful loop and you won't have an iterator variable you can use. Another trick I found somewhere on lua-users.org is to use gsub if you have to parse a string some_string:gsub(".", function(m) return "A";end); This looks odd at first, the benefit is that gsub creates a string "at once" in C which is only hashed after it is passed back to lua when gsub returns. This avoids table creation, but possibly has more function overhead (not if you call foo() anyway, but if foo() is actually an expression) Avoid function overhead Use language constructs instead of functions where possible function ipairs When iterating a table, the function overhead from ipairs does not justify it's use. To iterate a table, instead use for k=1, #tbl do local v = tbl[k]; It does exactly the same without the function call overhead (pairs actually returns another function which is then called for every element in the table while #tbl is only evaluated once). It's a lot faster, even if you need the value. And if you don't... Note for Lua 5.2 : In 5.2 you can actually define a __ipairs field in the metatable, which does make ipairs useful in some cases. However, Lua 5.2 also makes the __len field work for tables, so you might still prefer the above code to ipairs as then the __len metamethod is only called once, while for ipairs you would get an additional function call per iteration. functions table.insert , table.remove Simple uses of table.insert and table.remove can be replaced by using the # operator instead. Basically this is for simple push and pop operations. Here are some examples: table.insert(foo, bar);-- does the same asfoo[#foo+1] = bar;local x = table.remove(foo);-- does the same aslocal x = foo[#foo];foo[#foo] = nil; For shifts (eg. table.remove(foo, 1) ), and if ending up with a sparse table is not desirable, it is of course still better to use the table functions. Use tables for SQL-IN alike compares You might - or might not - have decisions in your code like the following if a == "C" or a == "D" or a == "E" or a == "F" then ...end Now this is a perfectly valid case, however (from my own testing) starting with 4 comparisons and excluding table generation, this is actually faster: local compares = { C = true, D = true, E = true, F = true };if compares[a] then ...end And since hash tables have constant look up time, the performance gain increases with every additional comparison. On the other hand if "most of the time" one or two comparisons match, you might be better off with the Boolean way or a combination. Avoid frequent table creation This is discussed thoroughly in Lua Performance Tips . Basically the problem is that Lua allocates your table on demand and doing it this way will actually take more time than cleaning it's content and filling it again. However, this is a bit of a problem, since Lua itself does not provide a method for removing all elements from a table, and pairs() is not the performance beast itself. I have not done any performance testing on this problem myself yet. If you can, define a C function that clears a table, this should be a good solution for table reuse. Avoid doing the same over and over This is the biggest problem, I think. While a compiler in a non-interpreted language can easily optimize away a lot of redundancies, Lua will not. Memoize Using tables this can be done quite easily in Lua. For single-argument functions you can even replace them with a table and __index metamethod. Even though this destroys transparancy, performance is better on cached values due to one less function call. Here is an implementation of memoization for a single argument using a metatable. (Important: This variant does not support a nil value argument, but is pretty damn fast for existing values.) function tmemoize(func) return setmetatable({}, { __index = function(self, k) local v = func(k); self[k] = v return v; end });end-- usage (does not support nil values!)local mf = tmemoize(myfunc);local v = mf[x]; You could actually modify this pattern for multiple input values Partial application The idea is similar to memoization, which is to "cache" results. But here instead of caching the results of the function, you would cache intermediate values by putting their calculation in a constructor function that defines the calculation function in it's block. In reality I would just call it clever use of closures. -- Normal functionfunction foo(a, b, x) return cheaper_expression(expensive_expression(a,b), x);end-- foo(a,b,x1);-- foo(a,b,x2);-- ...-- Partial applicationfunction foo(a, b) local C = expensive_expression(a,b); return function(x) return cheaper_expression(C, x); endend-- local f = foo(a,b);-- f(x1);-- f(x2);-- ... This way it is possible to easily create flexible functions that cache some of their work without too much impact on program flow. An extreme variant of this would be Currying , but that is actually more a way to mimic functional programming than anything else. Here is a more extensive ("real world") example with some code omissions, otherwise it would easily take up the whole page here (namely get_color_values actually does a lot of value checking and recognizes accepts mixed values) function LinearColorBlender(col_from, col_to) local cfr, cfg, cfb, cfa = get_color_values(col_from); local ctr, ctg, ctb, cta = get_color_values(col_to); local cdr, cdg, cdb, cda = ctr-cfr, ctg-cfg, ctb-cfb, cta-cfa; if not cfr or not ctr then error("One of given arguments is not a color."); end return function(pos) if type(pos) ~= "number" then error("arg1 (pos) must be in range 0..1"); end if pos < 0 then pos = 0; end; if pos > 1 then pos = 1; end; return cfr + cdr*pos, cfg + cdg*pos, cfb + cdb*pos, cfa + cda*pos; endend-- Call local blender = LinearColorBlender({1,1,1,1},{0,0,0,1});object:SetColor(blender(0.1));object:SetColor(blender(0.3));object:SetColor(blender(0.7)); You can see that once the blender was created, the function only has to sanity-check a single value instead of up to eight. I even extracted the difference calculation, though it probably does not improve a lot, I hope it shows what this pattern tries to achieve.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/154672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ] }
154,698
In java, I could do this with the 'final' keyword. I don't see 'final' in C#. Is there a substitute?
You're looking for the sealed keyword. It does exactly what the final keyword in Java does. Attempts to inherit will result in a compilation error.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ] }
154,702
We are using the MVC framework (release 5) and the CrystalReportViewer control to show our reports. I cannot get any of the buttons at the top of the report viewer control to work. If I'm working with the report 'HoursSummary'. If I hover over any of the buttons on the report viewer in IE the displayed link at the bottom of the pages is '../HoursSummary'. This creates a url of ' http://localhost/HoursSummary '. There is no 'HoursSummary' controller so I keep receiving 404 errors. I believe I want to redirect to ' http://localhost/reports/HoursSummary ' since I do have a reports controller. If this is the correct method does anyone know which property I should set on the CrystalReportViewer control to make that happen? Is there an easier method to handle this situation?
You're looking for the sealed keyword. It does exactly what the final keyword in Java does. Attempts to inherit will result in a compilation error.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7561/" ] }
154,707
I want to store a large number of sound files in a database, but I don't know if it is a good practice. I would like to know the pros and cons of doing it in this way. I also thought on the possibility to have "links" to those files, but maybe this will carry more problems than solutions. Any experience in this direction will be welcome :) Note: The database will be MySQL.
Every system I know of that stores large numbers of big files stores them externally to the database. You store all of the queryable data for the file (title, artist, length, etc) in the database, along with a partial path to the file. When it's time to retrieve the file, you extract the file's path, prepend some file root (or URL) to it, and return that. So, you'd have a "location" column, with a partial path in it, like "a/b/c/1000", which you then map to:" http://myserver/files/a/b/c/1000.mp3 " Make sure that you have an easy way to point the media database at a different server/directory, in case you need that for data recovery. Also, you might need a routine that re-syncs the database with the contents of the file archive. Also, if you're going to have thousands of media files, don't store them all in one giant directory - that's a performance bottleneck on some file systems. Instead,break them up into multiple balanced sub-trees.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/154707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19689/" ] }
154,718
My web application sends email fairly often, and it sends 3 kinds of emails: initiated by user, in response to an event in the system, and in automatic response to an email received by the application. I would like to make sure that the third type of email does not get stuck in an endless loop of auto-responders talking to each other. Currently, I use the header: Precedence: junk but Yahoo! mail is treating these messages as spam. This is obviously not ideal, because we would like SOMEBODY to read our auto-response and make a decision on it, just not an out-of-office reply. What is the best way to send an email without triggering either junk filters or auto-responders? Precedence: junk?Precedence: bulk?Precedence: list?X-Priority: 2?
RFC 2076 discourages the use of the precedence header. as you have noted, many clients will just filter that off (especially the precedence: junk variety). it may be better to use a null path to avoid auto responder wars: Return-Path: <> Ultimately you could use priority to try to get around this, but this seems like going against the spirit of the header. i'd suggest just using the return-path header for this, and avoiding precedence. in some cases you may have to write in some way to drop auto-responders in your application (to avoid getting into a responder war), but i can't remember a situation in which this happened using an appropriate return-path. (most auto responder wars i recall having to deal with were the result of very badly formed emails) Note: the Return-Path header is, in short, the destination for notifications (bounces, delay delivery, etc...), and is described in RFC 2821 -- because it's required by SMTP. It's also one method to drop bad mail (as theoretically all good mail will set an appropriate return-path).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3140/" ] }
154,724
The use of weak references is something that I've never seen an implementation of so I'm trying to figure out what the use case for them is and how the implementation would work. When have you needed to use a WeakHashMap or WeakReference and how was it used?
One problem with strong references is caching, particular with very large structures like images. Suppose you have an application which has to work with user-supplied images, like the web site design tool I work on. Naturally you want to cache these images, because loading them from disk is very expensive and you want to avoid the possibility of having two copies of the (potentially gigantic) image in memory at once. Because an image cache is supposed to prevent us from reloading images when we don't absolutely need to, you will quickly realize that the cache should always contain a reference to any image which is already in memory. With ordinary strong references, though, that reference itself will force the image to remain in memory, which requires you to somehow determine when the image is no longer needed in memory and remove it from the cache, so that it becomes eligible for garbage collection. You are forced to duplicate the behavior of the garbage collector and manually determine whether or not an object should be in memory. Understanding Weak References , Ethan Nicholas
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/154724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12662/" ] }
154,762
I need to create XML in Perl. From what I read, XML::LibXML is great for parsing and using XML that comes from somewhere else. Does anyone have any suggestions for an XML Writer? Is XML::Writer still maintained? Does anyone like/use it? In addition to feature-completeness, I am interested an easy-to-use syntax, so please describe the syntax and any other reasons why you like that module in your answer. Please respond with one suggestion per answer, and if someone has already answered with your favorite, please vote that answer up. Hopefully it will be easy to see what is most popular. Thanks!
XML::Writer is still maintained (at least, as of February of this year), and it's indeed one of the favorite Perl XML writers out there. As for describing the syntax, one is better to look at the module's documentation (the link is already in the question). To wit: use XML::Writer;my $writer = new XML::Writer(); # will write to stdout$writer->startTag("greeting", "class" => "simple");$writer->characters("Hello, world!");$writer->endTag("greeting");$writer->end();# produces <greeting class='simple'>Hello world!</greeting>
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/154762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4257/" ] }
154,845
I have a DataRow and I am getting one of the elements which is a Amount with a dollar sign. I am calling a toString on it. Is there another method I can call on it to remove the dollar sign if present. So something like: dr.ToString.Substring(1, dr.ToString.Length); But more conditionally in case the dollar sign ever made an appearance again. I am trying to do this with explicitly defining another string.
Convert.ToString(dr(columnName)).Replace("$", String.Empty) --If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
154,846
I'm looking for a way to create an online form that will update an Access database that has just a few tables. Does anyone know of a simple solution for this?
Convert.ToString(dr(columnName)).Replace("$", String.Empty) --If you are working with a data table, then you have to unbox the value (by default its Object) to a string, so you are already creating a string, and then another with the replacement. There is really no other way to get around it, but you will only see performance differences when dealing with tens of thousands of operations.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/154846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6958/" ] }