source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
133,988
I have a webapp that I am in the middle of doing some load/performance testing on, particularily on a feature where we expect a few hundred users to be accessing the same page and hitting refresh about every 10 seconds on this page. One area of improvement that we found we could make with this function was to cache the responses from the web service for some period of time, since the data is not changing. After implementing this basic caching, in some further testing I found out that I didn't consider how concurrent threads could access the Cache at the same time. I found that within the matter of ~100ms, about 50 threads were trying to fetch the object from the Cache, finding that it had expired, hitting the web service to fetch the data, and then putting the object back in the cache. The original code looked something like this: private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { final String key = "Data-" + email; SomeData[] data = (SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug("getSomeDataForEmail: using cached object"); } return data;} So, to make sure that only one thread was calling the web service when the object at key expired, I thought I needed to synchronize the Cache get/set operation, and it seemed like using the cache key would be a good candidate for an object to synchronize on (this way, calls to this method for email [email protected] would not be blocked by method calls to [email protected]). I updated the method to look like this: private SomeData[] getSomeDataByEmail(WebServiceInterface service, String email) { SomeData[] data = null; final String key = "Data-" + email; synchronized(key) { data =(SomeData[]) StaticCache.get(key); if (data == null) { data = service.getSomeDataForEmail(email); StaticCache.set(key, data, CACHE_TIME); } else { logger.debug("getSomeDataForEmail: using cached object"); } } return data;} I also added logging lines for things like "before synchronization block", "inside synchronization block", "about to leave synchronization block", and "after synchronization block", so I could determine if I was effectively synchronizing the get/set operation. However it doesn't seem like this has worked. My test logs have output like: (log output is 'threadname' 'logger name' 'message') http-80-Processor253 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor253 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor253 cache.StaticCache - get: object at key [[email protected]] has expired http-80-Processor253 cache.StaticCache - get: key [[email protected]] returning value [null] http-80-Processor263 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor263 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor263 cache.StaticCache - get: object at key [[email protected]] has expired http-80-Processor263 cache.StaticCache - get: key [[email protected]] returning value [null] http-80-Processor131 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor131 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor131 cache.StaticCache - get: object at key [[email protected]] has expired http-80-Processor131 cache.StaticCache - get: key [[email protected]] returning value [null] http-80-Processor104 jsp.view-page - getSomeDataForEmail: inside synchronization block http-80-Processor104 cache.StaticCache - get: object at key [[email protected]] has expired http-80-Processor104 cache.StaticCache - get: key [[email protected]] returning value [null] http-80-Processor252 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor283 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: about to enter synchronization block http-80-Processor2 jsp.view-page - getSomeDataForEmail: inside synchronization block I wanted to see only one thread at a time entering/exiting the synchronization block around the get/set operations. Is there an issue in synchronizing on String objects? I thought the cache-key would be a good choice as it is unique to the operation, and even though the final String key is declared within the method, I was thinking that each thread would be getting a reference to the same object and therefore would synchronization on this single object. What am I doing wrong here? Update : after looking further at the logs, it seems like methods with the same synchronization logic where the key is always the same, such as final String key = "blah";...synchronized(key) { ... do not exhibit the same concurrency problem - only one thread at a time is entering the block. Update 2 : Thanks to everyone for the help! I accepted the first answer about intern() ing Strings, which solved my initial problem - where multiple threads were entering synchronized blocks where I thought they shouldn't, because the key 's had the same value. As others have pointed out, using intern() for such a purpose and synchronizing on those Strings does indeed turn out to be a bad idea - when running JMeter tests against the webapp to simulate the expected load, I saw the used heap size grow to almost 1GB in just under 20 minutes. Currently I'm using the simple solution of just synchronizing the entire method - but I really like the code samples provided by martinprobst and MBCook, but since I have about 7 similar getData() methods in this class currently (since it needs about 7 different pieces of data from a web service), I didn't want to add almost-duplicate logic about getting and releasing locks to each method. But this is definitely very, very valuable info for future usage. I think these are ultimately the correct answers on how best to make an operation like this thread-safe, and I'd give out more votes to these answers if I could!
Without putting my brain fully into gear, from a quick scan of what you say it looks as though you need to intern() your Strings: final String firstkey = "Data-" + email;final String key = firstkey.intern(); Two Strings with the same value are otherwise not necessarily the same object. Note that this may introduce a new point of contention, since deep in the VM, intern() may have to acquire a lock. I have no idea what modern VMs look like in this area, but one hopes they are fiendishly optimised. I assume you know that StaticCache still needs to be thread-safe. But the contention there should be tiny compared with what you'd have if you were locking on the cache rather than just the key while calling getSomeDataForEmail. Response to question update : I think that's because a string literal always yields the same object. Dave Costa points out in a comment that it's even better than that: a literal always yields the canonical representation. So all String literals with the same value anywhere in the program would yield the same object. Edit Others have pointed out that synchronizing on intern strings is actually a really bad idea - partly because creating intern strings is permitted to cause them to exist in perpetuity, and partly because if more than one bit of code anywhere in your program synchronizes on intern strings, you have dependencies between those bits of code, and preventing deadlocks or other bugs may be impossible. Strategies to avoid this by storing a lock object per key string are being developed in other answers as I type. Here's an alternative - it still uses a singular lock, but we know we're going to need one of those for the cache anyway, and you were talking about 50 threads, not 5000, so that may not be fatal. I'm also assuming that the performance bottleneck here is slow blocking I/O in DoSlowThing() which will therefore hugely benefit from not being serialised. If that's not the bottleneck, then: If the CPU is busy then this approach may not be sufficient and you need another approach. If the CPU is not busy, and access to server is not a bottleneck, then this approach is overkill, and you might as well forget both this and per-key locking, put a big synchronized(StaticCache) around the whole operation, and do it the easy way. Obviously this approach needs to be soak tested for scalability before use -- I guarantee nothing. This code does NOT require that StaticCache is synchronized or otherwise thread-safe. That needs to be revisited if any other code (for example scheduled clean-up of old data) ever touches the cache. IN_PROGRESS is a dummy value - not exactly clean, but the code's simple and it saves having two hashtables. It doesn't handle InterruptedException because I don't know what your app wants to do in that case. Also, if DoSlowThing() consistently fails for a given key this code as it stands is not exactly elegant, since every thread through will retry it. Since I don't know what the failure criteria are, and whether they are liable to be temporary or permanent, I don't handle this either, I just make sure threads don't block forever. In practice you may want to put a data value in the cache which indicates 'not available', perhaps with a reason, and a timeout for when to retry. // do not attempt double-check locking here. I mean it.synchronized(StaticObject) { data = StaticCache.get(key); while (data == IN_PROGRESS) { // another thread is getting the data StaticObject.wait(); data = StaticCache.get(key); } if (data == null) { // we must get the data StaticCache.put(key, IN_PROGRESS, TIME_MAX_VALUE); }}if (data == null) { // we must get the data try { data = server.DoSlowThing(key); } finally { synchronized(StaticObject) { // WARNING: failure here is fatal, and must be allowed to terminate // the app or else waiters will be left forever. Choose a suitable // collection type in which replacing the value for a key is guaranteed. StaticCache.put(key, data, CURRENT_TIME); StaticObject.notifyAll(); } }} Every time anything is added to the cache, all threads wake up and check the cache (no matter what key they're after), so it's possible to get better performance with less contentious algorithms. However, much of that work will take place during your copious idle CPU time blocking on I/O, so it may not be a problem. This code could be commoned-up for use with multiple caches, if you define suitable abstractions for the cache and its associated lock, the data it returns, the IN_PROGRESS dummy, and the slow operation to perform. Rolling the whole thing into a method on the cache might not be a bad idea.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/133988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ] }
134,001
I need to be able to load the entire contents of a text file and load it into a variable for further processing. How can I do that? Here's what I did thanks to Roman Odaisky's answer. SetLocal EnableDelayedExpansionset content=for /F "delims=" %%i in (test.txt) do set content=!content! %%iecho %content%EndLocal
If your set command supports the /p switch, then you can pipe input that way. set /p VAR1=<test.txtset /? |find "/P" The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty. This has the added benefit of working for un-registered file types (which the accepted answer does not).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ] }
134,029
A quick Google search of this issue shows it's common, I just can't for the life of me figure out the solution in my case. I have a straight forward install of wxWidgets 2.8.8 for Windows straight from the wxWidgets website. Whenever I try to compile anything (such as the sample app described in "First Programs for wxWidgets" - http://zetcode.com/tutorials/wxwidgetstutorial/firstprograms/ ) I get: wx/setup.h: No such file or directory I've included both C:\wxWidgets-2.8.8\include and C:\wxWidgets-2.8.8\include\wx in my compiler search list. It should be simple - but it's not! :( The same thing happens if I try to use an IDE integrated with wxWidgets (such as Code::Blocks) - and this, I would have thought, would have just worked out the box... So, some help please... Why is setup.h not found?
wxWidgets is not built into useable libraries when you "install" the wxMSW installer. This is because there are so many configurable elements, which is precisely what the setup.h you refer to is for. If you just want to build it with default options as quickly as possible and move on, here is how: Start the "Visual Studio Command Prompt." You'll find this in the start menu under "Microsoft Visual Studio -> Visual Studio Tools". Change to folder: [WXWIN root]\build\msw Build default debug configuration: nmake -f makefile.vc BUILD=debug Build default release configuration: nmake -f makefile.vc BUILD=release Make sure the DLLs are in your PATH. They'll be found in [WXWIN root]\lib\vc_dll Under the DLL folder mentioned above, you will find subfolders for each build variant (The instructions above made two, debug and release.) In each variant folder you'll find a 'wx' folder containing a 'setup.h" file. You'll see that the setup.h files are actually different for each build variant. These are the folders you need to add to your project build configuration include path, one per build variant. So, for example, you'd add [WXWIN root]\lib\vc_dll\mswud to the include path for your debug build, [WXWIN root]\lib\vc_dll\mswu for your release build. It is possible to build lots of other variant combinations: static libs, monolithic single library, non-Unicode, etc. See [WXWIN root]\docs\msw\install.txt for much more extensive instructions.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
134,048
I am thinking about buying an iPod touch to make some money on developing apps for the iPhone. I like the concept of the App Store and had a quick look at it with iTunes.Looks like applications are categorized, to be iPhone OR iPod applications.Some apps which are free for the iPod seem to cost for iPhone users. What is the difference of both platforms, or why is the App Store separating them ?Does it make sense to develop for the iPhone using an iPod touch (beside phone/location related apps) ? On developer.apple.com I can sign up for selling my Applications on the AppStore for 99$.Do I have to expect any further costs ?Is it a problem to develop from outside the US (in my case Germany) ?
The iPod touch is missing: GPS Bluetooth (iPod Touch 4G has Bluetooth) Cellular network Camera (iPod Touch 4G has front and back cameras) Microphone (thanks John Topley ) (iPod Touch 4G has headset with microphone) Vibration The 1G is lacking a speaker On the plus side it weighs a bit less and is a bit smaller.. Other than that they are pretty much identical (no sarcasm here; it still has the same processor, OS, control system, and display) Personally I would get an iPhone, as you will probably end up getting one later on anyway. I have an iPod touch (bought first) and an iPhone. I never use the iPod anymore. The iPod touch is obviously cheaper than the iPhone, and there is no contract necessary. However, at least in the UK you can get a contract-free iPhone, and you should be able to do so soon on AT&T in the USA. There are no extra costs besides the $99 for application development (which is a yearly fee) We are developing from the UK. One issue to be aware of when you eventually sell your application is tax withholding - Apple will retain 30% of your revenues. There are some forms you need to fill out - I dealt with this in another thread . Here's what I wrote there: You need to fill out a W-8BEN and give it to Apple to avoid a 30% tax withholding. This requires that you have a SSN (Social Security Number). If, and only if, you do not have an SSN, you may supply an ITIN (Individual Taxpayer Identification Number) or an EIN (Employer ID Number). To get an ITIN, you need to fill out form W7 and submit that to the IRS.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20711/" ] }
134,063
Why are 'out' parameters in .NET a bad idea? I was recently asked this, but I had no real answer besides it's simply unnecessarily complicating an application. What other reasons are there?
Well, they aren't a bad idea I think. Dictionary<K, V> has a TryGetValue method which is a very good example why out parameters are sometimes a very nice thing to have. You should not overuse this feature of course, but it's not a bad idea per definition. Especially not in C# where you have to write down the out keyword in function declaration and call which makes it obvious what's going on.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
134,086
I wrote C++ for 10 years. I encountered memory problems, but they could be fixed with a reasonable amount of effort. For the last couple of years I've been writing C#. I find I still get lots of memory problems. They're difficult to diagnose and fix due to the non-determinancy, and because the C# philosophy is that you shouldn't have to worry about such things when you very definitely do. One particular problem I find is that I have to explicitly dispose and cleanup everything in code. If I don't, then the memory profilers don't really help because there is so much chaff floating about you can't find a leak within all the data they're trying to show you. I wonder if I've got the wrong idea, or if the tool I've got isn't the best. What kind of strategies and tools are useful for tackling memory leaks in .NET?
I use Scitech's MemProfiler when I suspect a memory leak. So far, I have found it to be very reliable and powerful. It has saved my bacon on at least one occasion. The GC works very well in .NET IMO, but just like any other language or platform, if you write bad code, bad things happen.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134086", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11898/" ] }
134,099
Let's say I have code like this: $dbh = new PDO("blahblah");$stmt = $dbh->prepare('SELECT * FROM users where username = :username');$stmt->execute( array(':username' => $_REQUEST['username']) ); The PDO documentation says: The parameters to prepared statements don't need to be quoted; the driver handles it for you. Is that truly all I need to do to avoid SQL injections? Is it really that easy? You can assume MySQL if it makes a difference. Also, I'm really only curious about the use of prepared statements against SQL injection. In this context, I don't care about XSS or other possible vulnerabilities.
The short answer is YES , PDO prepares are secure enough if used properly. I'm adapting this answer to talk about PDO... The long answer isn't so easy. It's based off an attack demonstrated here . The Attack So, let's start off by showing the attack... $pdo->query('SET NAMES gbk');$var = "\xbf\x27 OR 1=1 /*";$query = 'SELECT * FROM test WHERE name = ? LIMIT 1';$stmt = $pdo->prepare($query);$stmt->execute(array($var)); In certain circumstances, that will return more than 1 row. Let's dissect what's going on here: Selecting a Character Set $pdo->query('SET NAMES gbk'); For this attack to work, we need the encoding that the server's expecting on the connection both to encode ' as in ASCII i.e. 0x27 and to have some character whose final byte is an ASCII \ i.e. 0x5c . As it turns out, there are 5 such encodings supported in MySQL 5.6 by default: big5 , cp932 , gb2312 , gbk and sjis . We'll select gbk here. Now, it's very important to note the use of SET NAMES here. This sets the character set ON THE SERVER . There is another way of doing it, but we'll get there soon enough. The Payload The payload we're going to use for this injection starts with the byte sequence 0xbf27 . In gbk , that's an invalid multibyte character; in latin1 , it's the string ¿' . Note that in latin1 and gbk , 0x27 on its own is a literal ' character. We have chosen this payload because, if we called addslashes() on it, we'd insert an ASCII \ i.e. 0x5c , before the ' character. So we'd wind up with 0xbf5c27 , which in gbk is a two character sequence: 0xbf5c followed by 0x27 . Or in other words, a valid character followed by an unescaped ' . But we're not using addslashes() . So on to the next step... $stmt->execute() The important thing to realize here is that PDO by default does NOT do true prepared statements. It emulates them (for MySQL). Therefore, PDO internally builds the query string, calling mysql_real_escape_string() (the MySQL C API function) on each bound string value. The C API call to mysql_real_escape_string() differs from addslashes() in that it knows the connection character set. So it can perform the escaping properly for the character set that the server is expecting. However, up to this point, the client thinks that we're still using latin1 for the connection, because we never told it otherwise. We did tell the server we're using gbk , but the client still thinks it's latin1 . Therefore the call to mysql_real_escape_string() inserts the backslash, and we have a free hanging ' character in our "escaped" content! In fact, if we were to look at $var in the gbk character set, we'd see: 縗' OR 1=1 /* Which is exactly what the attack requires. The Query This part is just a formality, but here's the rendered query: SELECT * FROM test WHERE name = '縗' OR 1=1 /*' LIMIT 1 Congratulations, you just successfully attacked a program using PDO Prepared Statements... The Simple Fix Now, it's worth noting that you can prevent this by disabling emulated prepared statements: $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); This will usually result in a true prepared statement (i.e. the data being sent over in a separate packet from the query). However, be aware that PDO will silently fallback to emulating statements that MySQL can't prepare natively: those that it can are listed in the manual, but beware to select the appropriate server version). The Correct Fix The problem here is that we used SET NAMES instead of C API's mysql_set_charset() . Otherwise, the attack would not succeed. But the worst part is that PDO didn't expose the C API for mysql_set_charset() until 5.3.6, so in prior versions it cannot prevent this attack for every possible command!It's now exposed as a DSN parameter , which should be used instead of SET NAMES ... This is provided we are using a MySQL release since 2006. If you're using an earlier MySQL release, then a bug in mysql_real_escape_string() meant that invalid multibyte characters such as those in our payload were treated as single bytes for escaping purposes even if the client had been correctly informed of the connection encoding and so this attack would still succeed. The bug was fixed in MySQL 4.1.20 , 5.0.22 and 5.1.11 . The Saving Grace As we said at the outset, for this attack to work the database connection must be encoded using a vulnerable character set. utf8mb4 is not vulnerable and yet can support every Unicode character: so you could elect to use that instead—but it has only been available since MySQL 5.5.3. An alternative is utf8 , which is also not vulnerable and can support the whole of the Unicode Basic Multilingual Plane . Alternatively, you can enable the NO_BACKSLASH_ESCAPES SQL mode, which (amongst other things) alters the operation of mysql_real_escape_string() . With this mode enabled, 0x27 will be replaced with 0x2727 rather than 0x5c27 and thus the escaping process cannot create valid characters in any of the vulnerable encodings where they did not exist previously (i.e. 0xbf27 is still 0xbf27 etc.)—so the server will still reject the string as invalid. However, see @eggyal's answer for a different vulnerability that can arise from using this SQL mode (albeit not with PDO). Safe Examples The following examples are safe: mysql_query('SET NAMES utf8');$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1"); Because the server's expecting utf8 ... mysql_set_charset('gbk');$var = mysql_real_escape_string("\xbf\x27 OR 1=1 /*");mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1"); Because we've properly set the character set so the client and the server match. $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);$pdo->query('SET NAMES gbk');$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');$stmt->execute(array("\xbf\x27 OR 1=1 /*")); Because we've turned off emulated prepared statements. $pdo = new PDO('mysql:host=localhost;dbname=testdb;charset=gbk', $user, $password);$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');$stmt->execute(array("\xbf\x27 OR 1=1 /*")); Because we've set the character set properly. $mysqli->query('SET NAMES gbk');$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');$param = "\xbf\x27 OR 1=1 /*";$stmt->bind_param('s', $param);$stmt->execute(); Because MySQLi does true prepared statements all the time. Wrapping Up If you: Use Modern Versions of MySQL (late 5.1, all 5.5, 5.6, etc) AND PDO's DSN charset parameter (in PHP ≥ 5.3.6) OR Don't use a vulnerable character set for connection encoding (you only use utf8 / latin1 / ascii / etc) OR Enable NO_BACKSLASH_ESCAPES SQL mode You're 100% safe. Otherwise, you're vulnerable even though you're using PDO Prepared Statements... Addendum I've been slowly working on a patch to change the default to not emulate prepares for a future version of PHP. The problem that I'm running into is that a LOT of tests break when I do that. One problem is that emulated prepares will only throw syntax errors on execute, but true prepares will throw errors on prepare. So that can cause issues (and is part of the reason tests are borking).
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/134099", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ] }
134,103
On occasion, I find myself wanting to search the text of changelist descriptions in Perforce. There doesn't appear to be a way to do this in P4V. I can do it by redirecting the output of the changes command to a file... p4 changes -l > p4changes.txt ...(the -l switch tells it to dump the full text of the changelist descriptions) and then searching the file, but this is rather cumbersome. Has anyone found a better way?
When the submitted changelist pane has focus, a CTRL+F lets you do an arbitrary text search, which includes changelist descriptions. The only limitation is that it searches just those changelists that have been fetched from the server, so you may need to up the number retrieved. This is done via the "Number of changelists, jobs, branch mappings or labels to fetch at a time" setting which can be found by navigating to Edit->Preferences->Server Data.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4228/" ] }
134,158
Please, provide code examples in a language of your choice. Update :No constraints set on external storage. Example: Integers are received/sent via network. There is a sufficient space on local disk for intermediate results.
Sorting a million 32-bit integers in 2MB of RAM using Python by Guido van Rossum
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ] }
134,214
Right now, I have code that looks something like this: Private Sub ShowReport(ByVal reportName As String) Select Case reportName Case "Security" Me.ShowSecurityReport() Case "Configuration" Me.ShowConfigurationReport() Case "RoleUsers" Me.ShowRoleUsersReport() Case Else pnlMessage.Visible = True litMessage.Text = "The report name """ + reportName + """ is invalid." End SelectEnd Sub Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for: Private Sub ShowReport(ByVal reportName As String) Try Call("Show" + reportName + "Report") Catch ex As Exception 'method not found End TryEnd Sub
Type type = GetType();MethodInfo method = type.GetMethod("Show"+reportName+"Report");if (method != null){ method.Invoke(this, null);} This is C#, should be easy enough to turn it into VB. If you need to pass parameter into the method, they can be added in the 2nd argument to Invoke.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134214", "https://Stackoverflow.com", "https://Stackoverflow.com/users/681/" ] }
134,224
This code produces a FileNotFoundException, but ultimately runs without issue: void ReadXml(){ XmlSerializer serializer = new XmlSerializer(typeof(MyClass)); //...} Here is the exception: A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll Additional information: Could not load file or assembly 'MyAssembly.XmlSerializers, Version=1.4.3190.15950, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. It appears that the framework automatically generates the serialization assembly if it isn't found. I can generate it manually using sgen.exe, which alleviates the exception. How do I get visual studio to generate the XML Serialization assembly automatically? Update: The Generate Serialization Assembly: On setting doesn't appear to do anything.
This is how I managed to do it by modifying the MSBUILD script in my .CSPROJ file: First, open your .CSPROJ file as a file rather than as a project. Scroll to the bottom of the file until you find this commented out code, just before the close of the Project tag: <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.Common.targets.<Target Name="BeforeBuild"></Target><Target Name="AfterBuild"></Target>--> Now we just insert our own AfterBuild target to delete any existing XmlSerializer and SGen our own, like so: <Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)"> <!-- Delete the file because I can't figure out how to force the SGen task. --> <Delete Files="$(TargetDir)$(TargetName).XmlSerializers.dll" ContinueOnError="true" /> <SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(TargetFrameworkSDKToolsDirectory)" Platform="$(Platform)"> <Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" /> </SGen></Target> That works for me.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4066/" ] }
134,235
I want to build a site where the user can enter text and format it in Markdown. The reason I'd like a Javascript solution is because I want to display a live preview, just like on StackOverflow. My site is not targeted at developers, however, so an editor control would be ideal. I gather that on StackOverflow, the WMD editor is being used. A quick search on Google also turns up Showdown library, which I think is actually being used by WMD. Are there any other options? Are WMD/Showdown great tools already? What have been your experiences with the different options?
We've been pretty happy with WMD. There are a few niggling bugs in it, however. Nothing major, but I would love if John Fraser (the author) made the code open source so we can fix some of them. He's promised to do so but other real life projects are getting in the way. I do follow up with John every week. I'll post on the blog once the WMD source is finally available. Haven't been able to contact John Fraser in over a year now. We have open sourced both the JavaScript Markdown library http://code.google.com/p/pagedown/ and the server-side C# Markdown library http://code.google.com/p/markdownsharp/
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349/" ] }
134,237
I'm trying to use the this keyword in a static method, but the compiler won't allow me to use it. Why not?
That's an easy one. The keyword 'this' returns a reference to the current instance of the class containing it. Static methods (or any static member) do not belong to a particular instance. They exist without creating an instance of the class. There is a much more in depth explanation of what static members are and why/when to use them in the MSDN docs.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ] }
134,266
After reading the answers to the question "Calculate Code Metrics" I installed the tool SourceMonitor and calculated some metrics. But I have no idea how to interpret them. What's a "good" value for the metric "Percent Branch Statements" "Methods per Class" "Average Statements per Method" "Maximum Method or FunctionComplexity" I found no hints in the documentation, can anybody help me?
SourceMonitor is an awesome tool. "Methods Per Class" is useful to those who wish to ensure their classes follow good OO principles (too many methods indicates that a class could be taking on more than it should). "Average Statements per Method" is useful for a general feel of how big each method is. More useful to me is the info on the methods with too many statements (double click on the module for finer grain detail). Function Complexity is useful for ascertaining how nasty the code is. Truly I use this info more than anything else. This is info on how complicated the nastiest function in a module is (at least according to cyclomatic complexity). If you double click on the module / file you can find out which particular method is so bad.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ] }
134,309
I'm an IIS guy and know its as simple as just using the http://[computername]/path to webapp.. however, I can't seem to figure out how to make this possible for a JSP application I'm writing that runs under Tomcat. Is there a configuration setting I need to set somewhere?
You need to use the Port of Tomcat which is by default 8080. So you might want to access you localhost on machine A from machine B as http://A:8080/YourProject And Remember Unlike IIS , it is case sensitive.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ] }
134,331
I'm familiar with some of the basics, but what I would like to know more about is when and why error handling (including throwing exceptions) should be used in PHP, especially on a live site or web app. Is it something that can be overused and if so, what does overuse look like? Are there cases where it shouldn't be used? Also, what are some of the common security concerns in regard to error handling?
One thing to add to what was said already is that it's paramount that you record any errors in your web application into a log. This way, as Jeff "Coding Horror" Atwood suggests, you'll know when your users are experiencing trouble with your app (instead of "asking them what's wrong"). To do this, I recommend the following type of infrastructure: Create a "crash" table in your database and a set of wrapper classes for reporting errors. I'd recommend setting categories for the crashes ("blocking", "security", "PHP error/warning" (vs exception), etc). In all of your error handling code, make sure to record the error. Doing this consistently depends on how well you built the API (above step) - it should be trivial to record crashes if done right. Extra credit: sometimes, your crashes will be database-level crashes: i.e. DB server down, etc. If that's the case, your error logging infrastructure (above) will fail (you can't log the crash to the DB because the log tries to write to the DB). In that case, I would write failover logic in your Crash wrapper class to either send an email to the admin, AND/OR record the details of the crash to a plain text file All of this sounds like an overkill, but believe me, this makes a difference in whether your application is accepted as a "stable" or "flaky". That difference comes from the fact that all apps start as flaky/crashing all the time, but those developers that know about all issues with their app have a chance to actually fix it.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ] }
134,338
In Java projects in Eclipse version 3.4.1 sometimes the folder "Referenced Libraries" disappears from the "Project Explorer" view. All third party jars are shown directly in the root of the project folder. The project compiles and runs fine. It seems to be a GUI problem. How can I get this folder back?
First, bring up the "Package Explorer" view (instead of the "Project Explorer" view). Then, if the referenced .jar files still are visible in the root of the project, click on the little "down arrow" icon in the top-right corner of the Package Explorer view. In the context menu that appears, one of the items on the menu is "Show 'Referenced Libraries' Node." Click on that menu item.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/134338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ] }
134,379
Is it possible to do a SELECT statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 and returning them in that order , based on nothing more than the ID field? Both these statements return them in the same order: SELECT id FROM table WHERE id in (7,2,5,9,8) SELECT id FROM table WHERE id in (8,2,5,9,7)
I didn't think this was possible, but found a blog entry here that seems to do the type of thing you're after: SELECT id FROM table WHERE id in (7,2,5,9,8) ORDER BY FIND_IN_SET(id,"7,2,5,9,8"); will give different results to SELECT id FROM table WHERE id in (7,2,5,9,8) ORDER BY FIND_IN_SET(id,"8,2,5,9,7"); FIND_IN_SET returns the position of id in the second argument given to it, so for the first case above, id of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like id | FIND_IN_SET---|-----------7 | 12 | 25 | 3 then orders by the results of FIND_IN_SET .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21716/" ] }
134,452
What do you think is a good IDE for learning SmallTalk? I'll only be using it as a hobby, so it has to be free.
I think Squeak is the way to go. It has an entire smalltalk environment and is constantly updated. Its what I used for learning and is actually even a cool app in itself.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7415/" ] }
134,456
This SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE '%some_value%'; is slower than this SELECT * FROM SOME_TABLE WHERE SOME_FIELD = 'some_value'; but what about this? SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE 'some_value'; My testing indicates the second and third examples are exactly the same. If that's true, my question is, why ever use "=" ?
There is a clear difference when you use bind variables, which you should be using in Oracle for anything other than data warehousing or other bulk data operations. Take the case of: SELECT * FROM SOME_TABLE WHERE SOME_FIELD LIKE :b1 Oracle cannot know that the value of :b1 is '%some_value%', or 'some_value' etc. until execution time, so it will make an estimation of the cardinality of the result based on heuristics and come up with an appropriate plan that either may or may not be suitable for various values of :b, such as '%A','%', 'A' etc. Similar issues can apply with an equality predicate but the range of cardinalities that might result is much more easily estimated based on column statistics or the presence of a unique constraint, for example. So, personally I wouldn't start using LIKE as a replacement for =. The optimizer is pretty easy to fool sometimes.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ] }
134,481
What I have now (which successfully loads the plug-in) is this: Assembly myDLL = Assembly.LoadFrom("my.dll");IMyClass myPluginObject = myDLL.CreateInstance("MyCorp.IMyClass") as IMyClass; This only works for a class that has a constructor with no arguments. How do I pass in an argument to a constructor?
You cannot. Instead use Activator.CreateInstance as shown in the example below (note that the Client namespace is in one DLL and the Host in another. Both must be found in the same directory for code to work.) However, if you want to create a truly pluggable interface, I suggest you use an Initialize method that take the given parameters in your interface, instead of relying on constructors. That way you can just demand that the plugin class implement your interface, instead of "hoping" that it accepts the accepted parameters in the constructor. using System;using Host;namespace Client{ public class MyClass : IMyInterface { public int _id; public string _name; public MyClass(int id, string name) { _id = id; _name = name; } public string GetOutput() { return String.Format("{0} - {1}", _id, _name); } }}namespace Host{ public interface IMyInterface { string GetOutput(); }}using System;using System.Reflection;namespace Host{ internal class Program { private static void Main() { //These two would be read in some configuration const string dllName = "Client.dll"; const string className = "Client.MyClass"; try { Assembly pluginAssembly = Assembly.LoadFrom(dllName); Type classType = pluginAssembly.GetType(className); var plugin = (IMyInterface) Activator.CreateInstance(classType, 42, "Adams"); if (plugin == null) throw new ApplicationException("Plugin not correctly configured"); Console.WriteLine(plugin.GetOutput()); } catch (Exception e) { Console.Error.WriteLine(e.ToString()); } } }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22252/" ] }
134,492
I am able to serialize an object into a file and then restore it again as is shown in the next code snippet. I would like to serialize the object into a string and store into a database instead. Can anyone help me? LinkedList<Diff_match_patch.Patch> patches = // whatever...FileOutputStream fileStream = new FileOutputStream("foo.ser");ObjectOutputStream os = new ObjectOutputStream(fileStream);os.writeObject(patches1);os.close();FileInputStream fileInputStream = new FileInputStream("foo.ser");ObjectInputStream oInputStream = new ObjectInputStream(fileInputStream);Object one = oInputStream.readObject();LinkedList<Diff_match_patch.Patch> patches3 = (LinkedList<Diff_match_patch.Patch>) one;os.close();
Sergio: You should use BLOB . It is pretty straighforward with JDBC. The problem with the second code you posted is the encoding. You should additionally encode the bytes to make sure none of them fails. If you still want to write it down into a String you can encode the bytes using java.util.Base64 . Still you should use CLOB as data type because you don't know how long the serialized data is going to be. Here is a sample of how to use it. import java.util.*;import java.io.*;/** * Usage sample serializing SomeClass instance */public class ToStringSample { public static void main( String [] args ) throws IOException, ClassNotFoundException { String string = toString( new SomeClass() ); System.out.println(" Encoded serialized version " ); System.out.println( string ); SomeClass some = ( SomeClass ) fromString( string ); System.out.println( "\n\nReconstituted object"); System.out.println( some ); } /** Read the object from Base64 string. */ private static Object fromString( String s ) throws IOException , ClassNotFoundException { byte [] data = Base64.getDecoder().decode( s ); ObjectInputStream ois = new ObjectInputStream( new ByteArrayInputStream( data ) ); Object o = ois.readObject(); ois.close(); return o; } /** Write the object to a Base64 string. */ private static String toString( Serializable o ) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream( baos ); oos.writeObject( o ); oos.close(); return Base64.getEncoder().encodeToString(baos.toByteArray()); }}/** Test subject. A very simple class. */ class SomeClass implements Serializable { private final static long serialVersionUID = 1; // See Nick's comment below int i = Integer.MAX_VALUE; String s = "ABCDEFGHIJKLMNOP"; Double d = new Double( -1.0 ); public String toString(){ return "SomeClass instance says: Don't worry, " + "I'm healthy. Look, my data is i = " + i + ", s = " + s + ", d = " + d; }} Output: C:\samples>javac *.javaC:\samples>java ToStringSampleEncoded serialized versionrO0ABXNyAAlTb21lQ2xhc3MAAAAAAAAAAQIAA0kAAWlMAAFkdAASTGphdmEvbGFuZy9Eb3VibGU7TAABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSilr+wQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQuU4IsCAAB4cL/wAAAAAAAAdAAQQUJDREVGR0hJSktMTU5PUA==Reconstituted objectSomeClass instance says: Don't worry, I'm healthy. Look, my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0 NOTE : for Java 7 and earlier you can see the original answer here
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/134492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ] }
134,494
I wasn't aware of a difference, but a coworker says there is, although he can't back it up. What's the difference if any?
There is a difference, yes. XML that adheres to the XML standard is considered well formed, while xml that adheres to a DTD is considered valid.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134494", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ] }
134,501
Usually when I need to fork in C, I do something like this: pid_t p = fork();if(p == 0) { /* do child stuff */ }else { /* do parent stuff and pray there wasn't an error */ } It occured to me that I could ditch the extra variable and use: if(fork() == 0) { /* child */ }else { /* parent/pray */ } Improper error handling aside, (why) does this work/not work?
What you are suggesting will certainly work. However, error handling is not optional in any well-behaved application. The following implementation pattern is similarly succinct and also handles errors. Furthermore, it saves the fork() return value in the pid variable, in case you want to use it later in the parent to, say, wait for the child. switch (pid = fork()) {case -1: /* Failure */ /* ... */case 0: /* Child */ /* ... */default: /* Parent */ /* ... */}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12926/" ] }
134,517
I distribute software online, and always wonder if there is a proper way to better define version numbers. Let's assume A.B.C.D in the answers. When do you increase each of the components? Do you use any other version number tricks such as D mod 2 == 1 means it is an in house release only? Do you have beta releases with their own version numbers, or do you have beta releases per version number?
I'm starting to like the Year.Release[.Build] convention that some apps (e.g. Perforce) use. Basically it just says the year in which you release, and the sequence within that year. So 2008.1 would be the first version, and if you released another a months or three later, it would go to 2008.2. The advantage of this scheme is there is no implied "magnitude" of release, where you get into arguments about whether a feature is major enough to warrant a major version increment or not. An optional extra is to tag on the build number, but that tends to be for internal purposes only (e.g. added to the EXE/DLL so you can inspect the file and ensure the right build is there).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
134,520
Okay, this is just a crazy idea I have. Stack Overflow looks very structured and integrable into development applications. So would it be possible, even useful, to have a Stack Overflow plugin for, say, Eclipse? Which features of Stack Overflow would you like to have directly integrated into your IDE so you can use it "natively" without changing to a browser? EDIT: I'm thinking about ways of deeper integration than just using the web page inside the IDE. Like when you use a certain Java class and have a problem, answers from SO might flare up. There would probably be cases where something like this is annoying, but others may be very helpful.
Following up on Josh's answer. This VS Macro will search StackOverflow for highlighted text in the Visual Studio IDE. Just highlight and press Alt+F1 Public Sub SearchStackOverflowForSelectedText() Dim s As String = ActiveWindowSelection().Trim() If s.Length > 0 Then DTE.ItemOperations.Navigate("http://www.stackoverflow.com/search?q=" & _ Web.HttpUtility.UrlEncode(s)) End IfEnd SubPrivate Function ActiveWindowSelection() As String If DTE.ActiveWindow.ObjectKind = EnvDTE.Constants.vsWindowKindOutput Then Return OutputWindowSelection() End If If DTE.ActiveWindow.ObjectKind = "{57312C73-6202-49E9-B1E1-40EA1A6DC1F6}" Then Return HTMLEditorSelection() End If Return SelectionText(DTE.ActiveWindow.Selection)End FunctionPrivate Function HTMLEditorSelection() As String Dim hw As HTMLWindow = ActiveDocument.ActiveWindow.Object Dim tw As TextWindow = hw.CurrentTabObject Return SelectionText(tw.Selection)End FunctionPrivate Function OutputWindowSelection() As String Dim w As Window = DTE.Windows.Item(EnvDTE.Constants.vsWindowKindOutput) Dim ow As OutputWindow = w.Object Dim owp As OutputWindowPane = ow.OutputWindowPanes.Item(ow.ActivePane.Name) Return SelectionText(owp.TextDocument.Selection)End FunctionPrivate Function SelectionText(ByVal sel As EnvDTE.TextSelection) As String If sel Is Nothing Then Return "" End If If sel.Text.Length = 0 Then SelectWord(sel) End If If sel.Text.Length <= 2 Then Return "" End If Return sel.TextEnd FunctionPrivate Sub SelectWord(ByVal sel As EnvDTE.TextSelection) Dim leftPos As Integer Dim line As Integer Dim pt As EnvDTE.EditPoint = sel.ActivePoint.CreateEditPoint() sel.WordLeft(True, 1) line = sel.TextRanges.Item(1).StartPoint.Line leftPos = sel.TextRanges.Item(1).StartPoint.LineCharOffset pt.MoveToLineAndOffset(line, leftPos) sel.MoveToPoint(pt) sel.WordRight(True, 1)End Sub To install: go to Tools - Macros - IDE create a new Module with a name of your choice under "MyMacros". Or use an existing module. paste the above code into the module add a reference to the System.Web namespace (for HttpUtility) to the module close the macro IDE window go to Tools - Options - Environment - Keyboard type "google" in the Show Commands Containing textbox. The SearchGoogleForSelectedText macro should show up click in the Press Shortcut Keys textbox, then press ALT+F1 click the Assign button click OK This is all taken from Jeff Atwood's Google Search VS Macro post, just modified to search StackOverflow instead.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19734/" ] }
134,569
I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a std::string pointer? Here's what I was looking forward to doing: void Foo::Bar() { if(!QueryPerformanceTimer(&m_baz)) { throw new std::string("it's the end of the world!"); }}void Foo::Caller() { try { this->Bar(); // should throw } catch(std::string *caught) { // not quite sure the syntax is OK here... std::cout << "Got " << caught << std::endl; }}
Yes. std::exception is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be? boost has an excellent document on good style for exceptions and error handling. It's worth a read.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/134569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22187/" ] }
134,572
I am using the jQuery AutoComplete plugin in an html page where I also have an accordion menu which uses prototype. They both work perfectly separately but when I tried to implement both components in a single page I get an error that I have not been able to understand. uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIDOMViewCSS.getComputedStyle]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: file:///C:/Documents and Settings/Administrator/Desktop/website/js/jquery-1.2.6.pack.js :: anonymous :: line 11" data: no] I found out the file conflicting with jQuery is 'effects.js' which is used by the accordion menu. I tried replacing this file with a newer version but newer seems to break the accordion behavior. My guess is that the 'effects.js' file used in the accordion was modified to obtain the accordion demo output. I also tried using the overriding methods jQuery needs to avoid conflict with other libraries and that did not work. I obtained the accordion demo from stickmanlabs.com . And the jQuery AutoComplete can be obtained from jQuery site . Has any one else experienced this issue?
There are two possible solutions: There was a conflict with an older version of Scriptaculous and jQuery (Scriptaculous was attempting to extend the native Array prototype incorrectly) - first try upgrading your copy of Scriptaculous. If that does not work you will need to use noConflict() (as alluded to above). However, there's a catch. Since you're including a plugin you'll need to do the includes in a specific order, for example: <script src="jquery.js"></script><script src="jquery.autocomplete.js"></script><script> jQuery.noConflict(); jQuery(document).ready(function($){ $("#example").autocomplete(options); });</script><script src="prototype.js"></script><script src="effects.js"></script><script src="accordion.js"></script> Hope this helps to clarify the situation.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
134,575
I'm very early in the iPhone development learning process. I'm trying to get my head around various pieces. Right now I've just taken the basic NavigationController template and I'm trying to create a simple grouped table view with a couple of text fields. What I can't seem to do is to get Interface Builder to allow me to drop a UITableViewCell into a UITableView so that I can then add a text field to the Cell. Is this even possible (it would seem that its supposed to be given the fact that UITableViewCell is a draggable control)? If not, does that mean all of that is code I will need to just write myself?
You can create the cell with Interface Builder, but you have to make it a top-level object, rather than a child of the table view. Then you can return this cell in your view controller's tableView:cellForRowAtIndexPath: function. Make sure to give the cell an identifier in Interface Builder and then use the same identifier with dequeueReusableCellWithIdentifier: (see the sample code for how this works -- the idea is that cells get re-used - the OS will only allocate as many cells as fit on the screen at once. Clever way to save memory.)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13036/" ] }
134,626
I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior. Here are some trivial examples where they functionally do the same thing if either were found within another function: Lambda function >>> a = lambda x : 1 + x>>> a(5)6 Nested function >>> def b(x): return 1 + x>>> b(5)6 Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.) Does it even matter? If it doesn't then does that violate the Pythonic principle: There should be one-- and preferably only one --obvious way to do it. .
If you need to assign the lambda to a name, use a def instead. def s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable. lambda s can be used for use once, throw away functions which won't have a name. However, this use case is very rare. You rarely need to pass around unnamed function objects. The builtins map() and filter() need function objects, but list comprehensions and generator expressions are generally more readable than those functions and can cover all use cases, without the need of lambdas. For the cases you really need a small function object, you should use the operator module functions, like operator.add instead of lambda x, y: x + y If you still need some lambda not covered, you might consider writing a def , just to be more readable. If the function is more complex than the ones at operator module, a def is probably better. So, real world good lambda use cases are very rare.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/134626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ] }
134,683
This might be a stupid question but if there's a better or proper way to do this, I'd love to learn it. I have run across this a few times, including recently, where small spaces show up in the rendered version of my HTML page. Intuitively I think these should not be there because outside of text or entities the formatting of a page's HTML shouldn't matter but apparently it does. What I'm referring to is this - I have some Photoshop file from the client on how they want their site to look. They want it to look basically pixel perfect to the image in this file. One of the places in the page calls for a menu bar, where each one does the changing bit on hovering, acts like a hyperlink, etc. In the Photoshop file this is one long bar, so a cheap and easy way to do this is to just split that segment into multiple images and then place them next to each other in the file. So instinctively I lay it out like so (there's more to it but this is the gist) <a href="page1.html"> <img src="image1.png" /></a><a href="page2.html"> <img src="image2.png" /></a><a href="page3.html"> <img src="image3.png" /></a> and so forth. The problem is the images have this tiny space between them which is unacceptable since the client wants this thing pixel-perfect (and it just plain looks bad). One way to get it to render properly is to remove the carriage returns between the images <a href="page1.html"> <img src="image1.png" /></a><a href="page2.html"> <img src="image2.png" /></a><a href="page3.html"> <img src="image3.png" /></a> Which makes the images go right up against each other (the desired effect) but it makes the line incredibly long and the code more difficult to maintain (it wraps here in SO and this is a simplified version - the real one has longer filenames and JavaScript sprinkled in to do the hovering). It seems to me that this shouldn't happen but it looks like the carriage return in the HTML is being rendered as a small empty space. And this happens in all browsers, looks like. Am I right or wrong for thinking the two snippets above should render the same? And is there something I'm doing wrong? Maybe saving the file with the wrong encoding? Should I make every one of these links a perfectly positioned CSS element instead?
The whitespace (carriage return included) is usually rendered as space in all browsers. You need to put the elements one after another, but you can use a trick: <a href="page1.html"><img src="image1.png" /></a><a href="page2.html"><img src="image2.png" /></a><a href="page3.html"><img src="image3.png" /></a> This also looks a little ugly, but it's still better than one single line. You might change the formatting, but the idea is to add carriage returns inside the elements and not between them.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ] }
134,712
I would like to sort a matrix according to a particular column. There is a sort function, but it sorts all columns independently. For example, if my matrix data is: 1 3 5 7-1 4 Then the desired output (sorting by the first column) would be: -1 4 1 3 5 7 But the output of sort(data) is: -1 3 1 4 5 7 How can I sort this matrix by the first column?
I think the sortrows function is what you're looking for. >> sortrows(data,1)ans = -1 4 1 3 5 7
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9425/" ] }
134,727
What are the key differences between HTML4 and HTML5 draft ? Please keep the answers related to changed syntax and added/removed html elements.
HTML5 has several goals which differentiate it from HTML4. Consistency in Handling Malformed Documents The primary one is consistent, defined error handling . As you know, HTML purposely supports 'tag soup', or the ability to write malformed code and have it corrected into a valid document. The problem is that the rules for doing this aren't written down anywhere. When a new browser vendor wants to enter the market, they just have to test malformed documents in various browsers (especially IE) and reverse-engineer their error handling. If they don't, then many pages won't display correctly (estimates place roughly 90% of pages on the net as being at least somewhat malformed). So, HTML5 is attempting to discover and codify this error handling, so that browser developers can all standardize and greatly reduce the time and money required to display things consistently. As well, long in the future after HTML has died as a document format, historians may still want to read our documents, and having a completely defined parsing algorithm will greatly aid this. Better Web Application Features The secondary goal of HTML5 is to develop the ability of the browser to be an application platform, via HTML, CSS, and Javascript. Many elements have been added directly to the language that are currently (in HTML4) Flash or JS-based hacks, such as <canvas> , <video> , and <audio> . Useful things such as Local Storage (a js-accessible browser-built-in key-value database, for storing information beyond what cookies can hold), new input types such as date for which the browser can expose easy user interface (so that we don't have to use our js-based calendar date-pickers), and browser-supported form validation will make developing web applications much simpler for the developers, and make them much faster for the users (since many things will be supported natively, rather than hacked in via javascript). Improved Element Semantics There are many other smaller efforts taking place in HTML5, such as better-defined semantic roles for existing elements ( <strong> and <em> now actually mean something different, and even <b> and <i> have vague semantics that should work well when parsing legacy documents) and adding new elements with useful semantics - <article> , <section> , <header> , <aside> , and <nav> should replace the majority of <div> s used on a web page, making your pages a bit more semantic, but more importantly, easier to read . No more painful scanning to see just what that random </div> is closing - instead you'll have an obvious </header> , or </article> , making the structure of your document much more intuitive.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/134727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21473/" ] }
134,731
Whilst refactoring some code I came across some getter methods that returns a std::string. Something like this for example: class foo{private: std::string name_;public: std::string name() { return name_; }}; Surely the getter would be better returning a const std::string& ? The current method is returning a copy which isn't as efficient. Would returning a const reference instead cause any problems?
The only way this can cause a problem is if the caller stores the reference, rather than copy the string, and tries to use it after the object is destroyed. Like this: foo *pFoo = new foo;const std::string &myName = pFoo->getName();delete pFoo;cout << myName; // error! dangling reference However, since your existing function returns a copy, then you wouldnot break any of the existing code. Edit: Modern C++ (i. e. C++11 and up) supports Return Value Optimization , so returning things by value is no longer frowned upon. One should still be mindful of returning extremely large objects by value, but in most cases it should be ok.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ] }
134,746
What is the difference between bool and Boolean types in C#?
bool is an alias for System.Boolean just as int is an alias for System.Int32 . See a full list of aliases here: Built-In Types Table (C# Reference) .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/134746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ] }
134,791
Stateless beans in Java do not keep their state between two calls from the client. So in a nutshell we might consider them as objects with business methods. Each method takes parameters and return results. When the method is invoked some local variables are being created in execution stack. When the method returns the locals are removed from the stack and if some temporary objects were allocated they are garbage collected anyway. From my perspective that doesn’t differ from calling method of the same single instance by separate threads. So why cannot a container use one instance of a bean instead of pooling a number of them?
Pooling does several things. One, by having one bean per instance, you're guaranteed to be threads safe (Servlets, for example, are not thread safe). Two, you reduce any potential startup time that a bean might have. While Session Beans are "stateless", they only need to be stateless with regards to the client. For example, in EJB, you can inject several server resources in to a Session Bean. That state is private to the bean, but there's no reason you can't keep it from invocation to invocation. So, by pooling beans you reduce these lookups to only happening when the bean is created. Three, you can use bean pool as a means to throttle traffic. If you only have 10 Beans in a pool, you're only going to get at most 10 requests working simultaneously, the rest will be queued up.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3980/" ] }
134,796
I know I can compile individual source files, but sometimes -- say, when editing a header file used by many .cpp files -- multiple source files need to be recompiled. That's what Build is for. Default behavior of the "Build" command in VC9 (Visual C++ 2008) is to attempt to compile all files that need it. Sometimes this just results in many failed compiles. I usually just watch for errors and hit ctrl-break to stop the build manually. Is there a way to configure it such the build stops at the very first compile error (not the first failed project build) automatically?
I came up with a better macro guys. It stops immediately after the first error/s (soon as build window is updated). Visual Studio -> Tools -> Macros -> Macro IDE... (or ALT+F11) Private Sub OutputWindowEvents_OnPaneUpdated(ByVal pPane As OutputWindowPane) Handles OutputWindowEvents.PaneUpdated If Not (pPane.Name = "Build") Then Exit Sub pPane.TextDocument.Selection.SelectAll() Dim Context As String = pPane.TextDocument.Selection.Text pPane.TextDocument.Selection.EndOfDocument() Dim found As Integer = Context.IndexOf(": error ") If found > 0 Then DTE.ExecuteCommand("Build.Cancel") End IfEnd Sub Hope it works out for you guys.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ] }
134,833
I have an index.php file which has to process many different file types. How do I guess the filetype based on the REQUEST_URI ? If I request http://site/image.jpg , and all requests redirect through index.php , which looks like this <?php include('/www/site'.$_SERVER['REQUEST_URI']);?> How would I make that work correctly? Should I test based on the extension of the file requested, or is there a way to get the filetype?
If you are sure you're only ever working with images, you can check out the exif_imagetype() PHP function, which attempts to return the image MIME type. If you don't mind external dependencies, you can also check out the excellent getID3 library which can determine the MIME type of many different file types. Lastly, you can check out the mime_content_type() function - but it has been deprecated for the Fileinfo PECL extension.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ] }
134,834
This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm. Could you guys please comment on how I can make the following code more pythonic? from math import sqrt# recursively computes the factors of a numberdef factors(num): factorList = [] numroot = int(sqrt(num)) + 1 numleft = num # brute force divide the number until you find a factor for i in range(2, numroot): if num % i == 0: # if we found a factor, add it to the list and compute the remainder factorList.append(i) numleft = num / i break # if we didn't find a factor, get out of here! if numleft == num: factorList.append(num) return factorList # now recursively find the rest of the factors restFactors = factors(numleft) factorList.extend(restFactors) return factorList# grabs all of the twos in the list and puts them into 2 ^ x formdef transformFactorList(factorList): num2s = 0 # remove all twos, counting them as we go while 2 in factorList: factorList.remove(2) num2s += 1 # simply return the list with the 2's back in the right spot if num2s == 0: return factorList if num2s == 1: factorList.insert(0, 2) return factorList factorList.insert(0, '2 ^ ' + str(num2s)) return factorListprint transformFactorList(factors(#some number))
There is an excellent primer by David Goodger called "Code Like a Pythonista" here . A couple of things from that text re naming (quoting): joined_lower for functions, methods,attributes joined_lower or ALL_CAPS forconstants StudlyCaps for classes camelCase only to conform topre-existing conventions
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ] }
134,845
The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.? function myJsFunc() { alert("myJsFunc");} <a href="#" onclick="myJsFunc();">Run JavaScript Code</a> or function myJsFunc() { alert("myJsFunc");} <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>
I use javascript:void(0) . Three reasons. Encouraging the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this: function doSomething() { //Some code return false;} But then they forget to use return doSomething() in the onclick and just use doSomething() . A second reason for avoiding # is that the final return false; will not execute if the called function throws an error. Hence the developers have to also remember to handle any error appropriately in the called function. A third reason is that there are cases where the onclick event property is assigned dynamically. I prefer to be able to call a function or assign it dynamically without having to code the function specifically for one method of attachment or another. Hence my onclick (or on anything) in HTML markup look like this: onclick="someFunc.call(this)" OR onclick="someFunc.apply(this, arguments)" Using javascript:void(0) avoids all of the above headaches, and I haven't found any examples of a downside. So if you're a lone developer then you can clearly make your own choice, but if you work as a team you have to either state: Use href="#" , make sure onclick always contains return false; at the end, that any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false . OR Use href="javascript:void(0)" The second is clearly much easier to communicate.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/134845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8018/" ] }
134,847
On long Visual C++ builds, it would be really helpful to hear some sort of (optional) sounds for such build/compile results as: individual compile error file compile success/failure build success/failure batch build success/failure Does anyone know how to enable sounds for these kinds of build occurrences in Visual C++ (especially Visual C++ 2008 on Vista)?
CJM is almost right. In VC++ 9 (Visual Studio 2008) Go to Control Panel's Sounds applet (Control Panel/Hardware and Sounds/Sounds in Vista). Under the Sounds tab scroll to "Build Succeeded" under "Microsoft Visual Studio" and set a sound for this event. If you have (or had) multiple VS on this PC (I have 6.0, 2003, 2005, and 2008) there may be multiple entries with names like "Microsoft Developer" or blanks - which I assume work in the older versions. I often end-up setting the wrong ones. It seems you'll have to close VS 2008 and reopen for this to take effect. Someone mentioned this was broken/removed in VS 2005 - I noticed this as well.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10559/" ] }
134,858
I have some code I've written in PHP for consuming our simple webservice, which I'd also like to provide in Perl for users who may prefer that language. What's the simplest method of making a HTTP request to do that? In PHP I can do it in one line with file_get_contents() . Here's the entire code I want to port to Perl: /** * Makes a remote call to the our API, and returns the response * @param cmd {string} - command string ID * @param argsArray {array} - associative array of argument names and argument values * @return {array} - array of responses */function callAPI( $cmd, $argsArray=array() ){ $apikey="MY_API_KEY"; $secret="MY_SECRET"; $apiurl="https://foobar.com/api"; // timestamp this API was submitted (for security reasons) $epoch_time=time(); //--- assemble argument array into string $query = "cmd=" .$cmd; foreach ($argsArray as $argName => $argValue) { $query .= "&" . $argName . "=" . urlencode($argValue); } $query .= "&key=". $apikey . "&time=" . $epoch_time; //--- make md5 hash of the query + secret string $md5 = md5($query . $secret); $url = $apiurl . "?" . $query . "&md5=" . $md5; //--- make simple HTTP GET request, put the server response into $response $response = file_get_contents($url); //--- convert "|" (pipe) delimited string to array $responseArray = explode("|", $response); return $responseArray;}
LWP::Simple: use LWP::Simple;$contents = get("http://YOUR_URL_HERE");
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/134858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14569/" ] }
134,882
How do I easily undo a git rebase? A lengthy manual method is: checkout the commit parent to both of the branches create and checkout a temporary branch cherry-pick all commits by hand reset the faulty rebased branch to point to the temporary branch In my current situation, this works because I can easily spot commits from both branches (one was my stuff, the other was my colleague's stuff). However, my approach strikes me as suboptimal and error-prone (let's say I had just rebased with two of my own branches). Clarification: I am talking about a rebase during which multiple commits were replayed, not only one.
The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the reflog ... git reflog and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the --hard option). Suppose the old commit was HEAD@{2} in the ref log: git reset --hard HEAD@{2} In Windows, you may need to quote the reference: git reset --hard "HEAD@{2}" You can check the history of the candidate old head by just doing a git log HEAD@{2} ( Windows: git log "HEAD@{2}" ). If you've not disabled per branch reflogs you should be able to simply do git reflog branchname@{1} as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently. Per default, all reflogs are activated for non-bare repositories: [core] logAllRefUpdates = true
{ "score": 13, "source": [ "https://Stackoverflow.com/questions/134882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349/" ] }
134,887
After making it through the major parts of an introductory Lisp book, I still couldn't understand what the special operator (quote) (or equivalent ' ) function does, yet this has been all over Lisp code that I've seen. What does it do?
Short answer Bypass the default evaluation rules and do not evaluate the expression (symbol or s-exp), passing it along to the function exactly as typed. Long Answer: The Default Evaluation Rule When a regular (I'll come to that later) function is invoked, all arguments passed to it are evaluated. This means you can write this: (* (+ a 2) 3) Which in turn evaluates (+ a 2) , by evaluating a and 2. The value of the symbol a is looked up in the current variable binding set, and then replaced. Say a is currently bound to the value 3: (let ((a 3)) (* (+ a 2) 3)) We'd get (+ 3 2) , + is then invoked on 3 and 2 yielding 5. Our original form is now (* 5 3) yielding 15. Explain quote Already! Alright. As seen above, all arguments to a function are evaluated, so if you would like to pass the symbol a and not its value, you don't want to evaluate it. Lisp symbols can double both as their values, and markers where you in other languages would have used strings, such as keys to hash tables. This is where quote comes in. Say you want to plot resource allocations from a Python application, but rather do the plotting in Lisp. Have your Python app do something like this: print("'(")while allocating: if random.random() > 0.5: print(f"(allocate {random.randint(0, 20)})") else: print(f"(free {random.randint(0, 20)})") ...print(")") Giving you output looking like this (slightly prettyfied): '((allocate 3) (allocate 7) (free 14) (allocate 19) ...) Remember what I said about quote ("tick") causing the default rule not to apply? Good. What would otherwise happen is that the values of allocate and free are looked up, and we don't want that. In our Lisp, we wish to do: (dolist (entry allocation-log) (case (first entry) (allocate (plot-allocation (second entry))) (free (plot-free (second entry))))) For the data given above, the following sequence of function calls would have been made: (plot-allocation 3)(plot-allocation 7)(plot-free 14)(plot-allocation 19) But What About list ? Well, sometimes you do want to evaluate the arguments. Say you have a nifty function manipulating a number and a string and returning a list of the resulting ... things. Let's make a false start: (defun mess-with (number string) '(value-of-number (1+ number) something-with-string (length string)))Lisp> (mess-with 20 "foo")(VALUE-OF-NUMBER (1+ NUMBER) SOMETHING-WITH-STRING (LENGTH STRING)) Hey! That's not what we wanted. We want to selectively evaluate some arguments, and leave the others as symbols. Try #2! (defun mess-with (number string) (list 'value-of-number (1+ number) 'something-with-string (length string)))Lisp> (mess-with 20 "foo")(VALUE-OF-NUMBER 21 SOMETHING-WITH-STRING 3) Not Just quote , But backquote Much better! Incidently, this pattern is so common in (mostly) macros, that there is special syntax for doing just that. The backquote: (defun mess-with (number string) `(value-of-number ,(1+ number) something-with-string ,(length string))) It's like using quote , but with the option to explicitly evaluate some arguments by prefixing them with comma. The result is equivalent to using list , but if you're generating code from a macro you often only want to evaluate small parts of the code returned, so the backquote is more suited. For shorter lists, list can be more readable. Hey, You Forgot About quote ! So, where does this leave us? Oh right, what does quote actually do? It simply returns its argument(s) unevaluated! Remember what I said in the beginning about regular functions? Turns out that some operators/functions need to not evaluate their arguments. Such as IF -- you wouldn't want the else branch to be evaluated if it wasn't taken, right? So-called special operators , together with macros, work like that. Special operators are also the "axiom" of the language -- minimal set of rules -- upon which you can implement the rest of Lisp by combining them together in different ways. Back to quote , though: Lisp> (quote spiffy-symbol)SPIFFY-SYMBOLLisp> 'spiffy-symbol ; ' is just a shorthand ("reader macro"), as shown aboveSPIFFY-SYMBOL Compare to (on Steel-Bank Common Lisp): Lisp> spiffy-symboldebugger invoked on a UNBOUND-VARIABLE in thread #<THREAD "initial thread" RUNNING {A69F6A9}>: The variable SPIFFY-SYMBOL is unbound.Type HELP for debugger help, or (SB-EXT:QUIT) to exit from SBCL.restarts (invokable by number or by possibly-abbreviated name): 0: [ABORT] Exit debugger, returning to top level.(SB-INT:SIMPLE-EVAL-IN-LEXENV SPIFFY-SYMBOL #<NULL-LEXENV>)0] Because there is no spiffy-symbol in the current scope! Summing Up quote , backquote (with comma), and list are some of the tools you use to create lists, that are not only lists of values, but as you seen can be used as lightweight (no need to define a struct ) data structures! If you wish to learn more, I recommend Peter Seibel's book Practical Common Lisp for a practical approach to learning Lisp, if you're already into programming at large. Eventually on your Lisp journey, you'll start using packages too. Ron Garret's The Idiot's Guide to Common Lisp Packages will give you good explanation of those. Happy hacking!
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/134887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ] }
134,905
What is the best way to return XML from a controller's action in ASP.NET MVC? There is a nice way to return JSON, but not for XML. Do I really need to route the XML through a View, or should I do the not-best-practice way of Response.Write-ing it?
Use MVCContrib 's XmlResult Action. For reference here is their code: public class XmlResult : ActionResult{ private object objectToSerialize; /// <summary> /// Initializes a new instance of the <see cref="XmlResult"/> class. /// </summary> /// <param name="objectToSerialize">The object to serialize to XML.</param> public XmlResult(object objectToSerialize) { this.objectToSerialize = objectToSerialize; } /// <summary> /// Gets the object to be serialized to XML. /// </summary> public object ObjectToSerialize { get { return this.objectToSerialize; } } /// <summary> /// Serialises the object that was passed into the constructor to XML and writes the corresponding XML to the result stream. /// </summary> /// <param name="context">The controller context for the current request.</param> public override void ExecuteResult(ControllerContext context) { if (this.objectToSerialize != null) { context.HttpContext.Response.Clear(); var xs = new System.Xml.Serialization.XmlSerializer(this.objectToSerialize.GetType()); context.HttpContext.Response.ContentType = "text/xml"; xs.Serialize(context.HttpContext.Response.Output, this.objectToSerialize); } }}
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/134905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22299/" ] }
134,906
Is there a command or an existing script that will let me view all of a *NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as /etc/crontab , and whatever's in /etc/cron.d . It would also be nice to see the specific commands run by run-parts in /etc/crontab . Ideally, I'd like the output in a nice column form and ordered in some meaningful way. I could then merge these listings from multiple servers to view the overall "schedule of events." I was about to write such a script myself, but if someone's already gone to the trouble...
You would have to run this as root, but: for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l; done will loop over each user name listing out their crontab. The crontabs are owned by the respective users so you won't be able to see another user's crontab w/o being them or root. Edit if you want to know which user a crontab belongs to, use echo $user for user in $(cut -f1 -d: /etc/passwd); do echo $user; crontab -u $user -l; done
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/134906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ] }
134,934
How do I display a leading zero for all numbers with less than two digits? 1 → 0110 → 10100 → 100
In Python 2 (and Python 3) you can do: number = 1print("%02d" % (number,)) Basically % is like printf or sprintf (see docs ). For Python 3.+, the same behavior can also be achieved with format : number = 1print("{:02d}".format(number)) For Python 3.6+ the same behavior can be achieved with f-strings : number = 1print(f"{number:02d}")
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/134934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22306/" ] }
134,956
Is it even possible to perform address (physical, not e-mail) validation? It seems like the sheer number of address formats, even in the US alone, would make this a fairly difficult task. On the other hand it seems like a task that would be necessary for several business requirements.
Here's a free and sort of "outside the box" way to do it. Not 100% perfect, but it should reject blatantly non-existent addresses. Submit the entire address to Google's geocoding web service . This service attempts to return the exact coordinates of the location you feed it, i.e. latitude and longitude. In my experience if the address is invalid you will get a result of 602 from the service. There's definitely a possibility of false positives or false negatives, but used in conjunction with other consistency checks it could be useful. ( Yahoo's geocoding web service , on the other hand, will return the coordinates of the center of the town if the town exists but the rest of the address is bogus. Potentially useful as long as you pay close attention to the "precision" field in the result).
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/134956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ] }
134,958
How would I be able to get N results for several groups inan oracle query. For example, given the following table: |--------+------------+------------|| emp_id | name | occupation ||--------+------------+------------|| 1 | John Smith | Accountant || 2 | Jane Doe | Engineer || 3 | Jack Black | Funnyman ||--------+------------+------------| There are many more rows with more occupations. I would like to getthree employees (lets say) from each occupation. Is there a way to do this without using a subquery?
I don't have an oracle instance handy right now so I have not tested this: select *from (select emp_id, name, occupation, rank() over ( partition by occupation order by emp_id) rank from employee)where rank <= 3 Here is a link on how rank works: http://www.psoug.org/reference/rank.html
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134958", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9435/" ] }
134,962
I've been trying this a couple of different ways, but it's not working for some reason. Is it even possible?
Yes. Separate them in your declaration by semicolons.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5469/" ] }
134,969
In Ruby, is there the equivalent of the __str__() method that you can define on Python classes?
You could use to_s. http://briancarper.net/2006/09/26/ruby-to_s-vs-to_str/
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/134969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ] }
135,000
When generating XML from XmlDocument in .NET, a blank xmlns attribute appears the first time an element without an associated namespace is inserted; how can this be prevented? Example: XmlDocument xml = new XmlDocument();xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));xml.DocumentElement.AppendChild(xml.CreateElement("loner"));Console.WriteLine(xml.OuterXml); Output: <root xmlns="whatever:name-space-1.0"><loner xmlns="" /></root> Desired Output: <root xmlns="whatever:name-space-1.0"><loner /></root> Is there a solution applicable to the XmlDocument code, not something that occurs after converting the document to a string with OuterXml ? My reasoning for doing this is to see if I can match the standard XML of a particular protocol using XmlDocument-generated XML. The blank xmlns attribute may not break or confuse a parser, but it's also not present in any usage that I've seen of this protocol.
Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank xmlns attributes: pass in the root node's namespace when creating any child node you want not to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to also not have prefixes. Fixed Code: XmlDocument xml = new XmlDocument();xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0")); Console.WriteLine(xml.OuterXml); Thanks everyone to all your answers which led me in the right direction!
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ] }
135,010
I have a problem with stopping a service and starting it again and want to be notified when the process runs and let me know what the result is. Here's the scenario,I have a text file output of an "sc" command. I want to send that file but not as an attachment. Also, I want to see the initial status quickly in the subject of the email. Here's the 'servstop.txt' file contents: [SC] StartService FAILED 1058: The service cannot be started, either because it is disabled or because it has no enabled devices associated with it. I want the subject of the email to be "Alert Service Start: [SC] StartService FAILED 1058"and the body to contain the entire error message above. I will put my current method in an answer below using a program called blat to send me the result.
Thanks to Jeremy Lew's answer and a bit more playing around, I figured out how to remove blank xmlns attributes: pass in the root node's namespace when creating any child node you want not to have a prefix on. Using a namespace without a prefix at the root means that you need to use that same namespace on child elements for them to also not have prefixes. Fixed Code: XmlDocument xml = new XmlDocument();xml.AppendChild(xml.CreateElement("root", "whatever:name-space-1.0"));xml.DocumentElement.AppendChild(xml.CreateElement("loner", "whatever:name-space-1.0")); Console.WriteLine(xml.OuterXml); Thanks everyone to all your answers which led me in the right direction!
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ] }
135,020
When creating a class that has internal private methods, usually to reduce code duplication, that don't require the use of any instance fields, are there performance or memory advantages to declaring the method as static? Example: foreach (XmlElement element in xmlDoc.DocumentElement.SelectNodes("sample")){ string first = GetInnerXml(element, ".//first"); string second = GetInnerXml(element, ".//second"); string third = GetInnerXml(element, ".//third");} ... private static string GetInnerXml(XmlElement element, string nodeName){ return GetInnerXml(element, nodeName, null);}private static string GetInnerXml(XmlElement element, string nodeName, string defaultValue){ XmlNode node = element.SelectSingleNode(nodeName); return node == null ? defaultValue : node.InnerXml;} Is there any advantage to declaring the GetInnerXml() methods as static? No opinion responses please, I have an opinion.
From the FxCop rule page on this: After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/135020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6146/" ] }
135,035
In ruby the library path is provided in $: , in perl it's in @INC - how do you get the list of paths that Python searches for modules when you do an import?
I think you're looking for sys.path import sysprint (sys.path)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19784/" ] }
135,041
Why or why not?
For performance, especially when you're iterating over a large range, xrange() is usually better. However, there are still a few cases why you might prefer range() : In python 3, range() does what xrange() used to do and xrange() does not exist. If you want to write code that will run on both Python 2 and Python 3, you can't use xrange() . range() can actually be faster in some cases - eg. if iterating over the same sequence multiple times. xrange() has to reconstruct the integer object every time, but range() will have real integer objects. (It will always perform worse in terms of memory however) xrange() isn't usable in all cases where a real list is needed. For instance, it doesn't support slices, or any list methods. [Edit] There are a couple of posts mentioning how range() will be upgraded by the 2to3 tool. For the record, here's the output of running the tool on some sample usages of range() and xrange() RefactoringTool: Skipping implicit fixer: bufferRefactoringTool: Skipping implicit fixer: idiomsRefactoringTool: Skipping implicit fixer: ws_comma--- range_test.py (original)+++ range_test.py (refactored)@@ -1,7 +1,7 @@ for x in range(20):- a=range(20)+ a=list(range(20)) b=list(range(20)) c=[x for x in range(20)] d=(x for x in range(20))- e=xrange(20)+ e=range(20) As you can see, when used in a for loop or comprehension, or where already wrapped with list(), range is left unchanged.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/135041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ] }
135,057
Possible Duplicate: Running Internet Explorer 6, Internet Explorer 7, and Internet Explorer 8 on the same machine Is there a way to have Internet Explorer 8 and Internet Explorer 6 side by side without virtualizing? I used Multiple IEs which works fine with Internet Explorer 7, but since I installed Internet Explorer 8 beta 2, Internet Explorer 6 started behaving oddly (that is, more than usual).
I also use virtualisation. I've got Virtual PC 2007, which is a free download from here , on my machine and have downloaded the Internet Explorer Virual PC images from Microsoft. You can get the images here .
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135057", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13275/" ] }
135,069
This may be a matter of style, but there's a bit of a divide in our dev team and I wondered if anyone else had any ideas on the matter... Basically, we have some debug print statements which we turn off during normal development. Personally I prefer to do the following: //---- SomeSourceFile.cpp ----#define DEBUG_ENABLED (0)...SomeFunction(){ int someVariable = 5;#if(DEBUG_ENABLED) printf("Debugging: someVariable == %d", someVariable);#endif} Some of the team prefer the following though: // #define DEBUG_ENABLED...SomeFunction(){ int someVariable = 5;#ifdef DEBUG_ENABLED printf("Debugging: someVariable == %d", someVariable);#endif} ...which of those methods sounds better to you and why? My feeling is that the first is safer because there is always something defined and there's no danger it could destroy other defines elsewhere.
My initial reaction was #ifdef , of course , but I think #if actually has some significant advantages for this - here's why: First, you can use DEBUG_ENABLED in preprocessor and compiled tests. Example - Often, I want longer timeouts when debug is enabled, so using #if , I can write this DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000); ... instead of ... #ifdef DEBUG_MODE DoSomethingSlowWithTimeout(5000);#else DoSomethingSlowWithTimeout(1000);#endif Second, you're in a better position if you want to migrate from a #define to a global constant. #define s are usually frowned on by most C++ programmers. And, Third, you say you've a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that #if is the preferred choice means that code using #ifdef will compile -and run- even when DEBUG_ENABLED is false. And it's much easier to track down and remove debug output that is produced when it shouldn't be than vice-versa. Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your #define , and because the value is a single lexical token, it's the one time you don't need parentheses around it. #define DEBUG_ENABLED true instead of #define DEBUG_ENABLED (1)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135069", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ] }
135,112
I have developed in C++ many years ago, but these days I am primarily a Java software engineer. Given I own an iPhone, am ready to spring for a MacBook next month, and am generally interested in getting started with Mac OS developmentmt (using Objective C), I thought I would just put this question out there: What Next? More specifically, what books should I pick up, and are there any web resources that some folks could point me to? Some books that I am planning to purchase: Programming in Objective-C 2.0 Cocoa(R) Programming for Mac OS X (3rd Edition) Anyone familiar with these titles? Finally, I would be very interested in a summary of what I should be prepared to expect, once I embark on this journey. As someone that develops in Java using IntelliJ IDEA, what are some key differences I will notice as I move over to writing ObjectiveC code in Xcode? What's the differences between Mac OS desktop development and iPhone development? Being used to Java garbage collection, what should I know about ObjectiveC garbage collection / memory management. Any other language specific issues that anyone would like to point out? How about building UIs? Is it closer to Swing, building Visual C++ resource files that code interacts with, or is it more like some of the borland IDEs that will generate code for guis?
Having purchased both of the books in your question, I recommend Cocoa Programming for Mac OS X as a quick way to learn the language and the Cocoa framework, and is probably the fastest way to start producing real applications in Cocoa. I highly recommend it. Programming in Objective-C 2.0 is a great reference book, but if you already know C, there's no much it's going to teach you that you can't pick up from the other book. However, if you ever need to a list of all the reserved keywords in Objective-C, that's the book to go to. All of the user interface can be generated progmatically, but you'll find it much easier to use Interface Builder, which comes with XCode, to lay out the user interface. You'll end up with a lot less code. With bindings, you can even eliminate code which isn't directly related to laying out the interface. The details are in the Cocoa Programming for Mac OS X book. The one big thing I miss from Java is the collection API. In Cocoa, you just get NSSet, NSArray, and NSDictionary, and there's no analog to the Comparable interface. These classes are also immutable, but have mutable versions such as NSMutableArray. I actually haven't played with the Garbage Collection in Objective-C 2.0. In previous versions of Objective-C, memory management was handled by the retain, release, and autorelease methods. Objects were created with a retain count of 1. Retaining incremented that count, releasing decremented it, and autoreleasing objects is a little more complicated. Again, the Cocoa Programming book explains it well. Garbage collection is an option, and if it's turned on, the retain, release and autorelease methods do nothing. However, if you are writing a library or framework to be used by others, you should program it as if garbage collection is turned off. That way applications can use it whether or not they have garbage collection turned on. As for Web resources, http://cocoadevcentral.com/ is a great site with beginner tutorials. The CocoaDev Wiki at http://www.cocoadev.com/ contains detailed information on a lot of topics, and you can usually find some useful information and people on the cocoa-dev mailing list http://lists.apple.com/mailman/listinfo/cocoa-dev iPhone development is a little different, and the details are restricted by an NDA. However, if you get approved by Apple to get access to the iPhone developer center, Apple has provided some great video overviews of the differences, which point you to the documentation you need to make the jump from Mac OS X to iPhone OS X programming.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9931/" ] }
135,123
I want to add gmail-like file upload functionality for one of my projects. Can anybody help me with this? My application is built in vb.net. I would appreciate any kind of help or guidance. Thanks
Check out SWFUpload , which is essentially a javascript api to flash's absolutely superior file upload handling capabilities. Best thing out there until the browsers finally catch up. From link: Upload multiple files at once by ctrl/shift-selecting in dialog Javascript callbacks on all events Get file information before upload starts Style upload elements with XHTML and css Display information while files are uploading using HTML No page reloads necessary Works on all platforms/browsers that has Flash support. Degrades gracefully to normal HTML upload form if Flash or javascript is unavailable Control filesize before upload starts Only display chosen filetypes in dialog Queue uploads, remove/add files before starting upload Demos ----- iframe upload ----- To start, you want to have an iframe on your page. This is meant for server communication. You'll hide it later, but for now, keep it visible. Give that iframe a name attribute, like "uploader" or something. Now, in your form, set the target to the iframe's name and the action to a script you have on the server that will accept a file upload (like a normal form with a file upload). Add a link inside that form with the text "Add File". Set that link to run a javascript function which will add a new input to the form. This can be done via the DOM, but I would recommend a javascript library like jquery . Once the new file input is added to the form, set the blur event of that input to a javascript function that will submit the form and then check it periodically for output. Reading an iframe can be tricky, but it's possible. Have your file upload script output a "Done." or a filename or something when the upload is complete. Check it every second or so until there is content. Once you have content, kill your timer and replace the file input with the name of the file (or "File Uploaded") or whatever. Hide your iframe with css.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
135,129
I seem to be seeing more 'for' loops over iterators in questions & answers here than I do for_each(), transform(), and the like. Scott Meyers suggests that stl algorithms are preferred , or at least he did in 2001. Of course, using them often means moving the loop body into a function or function object. Some may feel this is an unacceptable complication, while others may feel it better breaks down the problem. So... should STL algorithms be preferred over hand-rolled loops?
It depends on: Whether high-performance is required The readability of the loop Whether the algorithm is complex If the loop isn't the bottleneck, and the algorithm is simple (like for_each), then for the current C++ standard, I'd prefer a hand-rolled loop for readability. (Locality of logic is key.) However, now that C++0x/C++11 is supported by some major compilers, I'd say use STL algorithms because they now allow lambda expressions — and thus the locality of the logic.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135129", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10077/" ] }
135,151
The .NET web system I'm working on allows the end user to input HTML formatted text in some situations. In some of those places, we want to leave all the tags, but strip off any trailing break tags (but leave any breaks inside the body of the text.) What's the best way to do this? (I can think of ways to do this, but I'm sure they're not the best.)
As @ Mitch said, // using System.Text.RegularExpressions;/// <summary>/// Regular expression built for C# on: Thu, Sep 25, 2008, 02:01:36 PM/// Using Expresso Version: 2.1.2150, http://www.ultrapico.com/// /// A description of the regular expression:/// /// Match expression but don't capture it. [\<br\s*/?\>], any number of repetitions/// \<br\s*/?\>/// </// br/// Whitespace, any number of repetitions/// /, zero or one repetitions/// >/// End of line or string/// /// /// </summary>public static Regex regex = new Regex( @"(?:\<br\s*/?\>)*$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled );regex.Replace(text, string.Empty);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ] }
135,203
I have always wondered WHaT tHE HecK?!? is the difference between JScript and JavaScript.
Just different names for what is really ECMAScript. John Resig has a good explanation . Here's the full version breakdown: IE 6-7 support JScript 5 (which is equivalent to ECMAScript 3, JavaScript 1.5) IE 8 supports JScript 6 (which is equivalent to ECMAScript 3, JavaScript 1.5 - more bug fixes over JScript 5) Firefox 1.0 supports JavaScript 1.5 (ECMAScript 3 equivalent) Firefox 1.5 supports JavaScript 1.6 (1.5 + Array Extras + E4X + misc.) Firefox 2.0 supports JavaScript 1.7 (1.6 + Generator + Iterators + let + misc.) Firefox 3.0 supports JavaScript 1.8 (1.7 + Generator Expressions + Expression Closures + misc.) The next version of Firefox will support JavaScript 1.9 (1.8 + To be determined) Opera supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc. Safari supports a language that is equivalent to ECMAScript 3 + Getters and Setters + misc.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/135203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
135,234
What is the difference between ref and out parameters in .NET? What are the situations where one can be more useful than the other? What would be a code snippet where one can be used and another can't?
They're pretty much the same - the only difference is that a variable you pass as an out parameter doesn't need to be initialized but passing it as a ref parameter it has to be set to something. int x;Foo(out x); // OKint y;Foo(ref y); // Error: y should be initialized before calling the method Ref parameters are for data that might be modified, out parameters are for data that's an additional output for the function (eg int.TryParse ) that are already using the return value for something.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/135234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1909/" ] }
135,262
I'm programming in C for RAM limited embedded microcontroller with RTOS. I regularly break my code to short functions, but every function calling require to more stack memory.Every task needs his stack, and this is one of the significant memory consumers in the project. Is there an alternative to keep the code well organized and readable, still preserve the memory?
Try to make the call stack flatter, so instead of a() calling b() which calls c() which calls d() , have a() call b() , c() , and d() itself. If a function is only referenced once, mark it inline (assuming your compiler supports this).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22249/" ] }
135,269
Can I run ASP.NET 2.0 and 3.5 code on the same website? ...or, do I need to separate them by applications, and/or servers?
.NET 3.5 is 2.0 with a few extra libraries. So the answer is yes you can run them on the same web site. In fact you cannot even set a web application to run under 3.5. It just runs under 2.0. You can check the ASP.NET tab in the properties of an IIS site to see that there isn't even an option to run your application under 3.5.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16794/" ] }
135,296
I frequently come across Windows programs that bundle in MSVCRT (or their more current equivalents) with the program executables. On a typical PC, I would find many copies of the same .DLL's. My understanding is that MSVCRT is the C runtime library, somewhat analogous to glibc/libc.so under *nix. Why do Windows programs have to bring along their C libraries with them, instead of just sharing the system-wide libc? Update: thanks to Shog9, I started to read about SxS, which has further opened up my eyes to the DLL linkage issues (DLL Hell) - Link is one useful intro to the issue...
[I'm the current maintainer of the Native SxS technology at Microsoft] New versions of MSVCRT are released with new versions of Visual Studio, and reflect changes to the C++ toolset. So that programs compiled with versions of VS released after a particular version of Windows continue can work downlevel (such as VS 2008 projects on Windows XP), the MSVCRT is redistributable, so it can be installed there. CRT installation drops the libraries into %windir%\winsxs\, which is a global system location, requiring administrator privileges to do so. Since some programs do not want to ship with an installer, or do not want the user to need administrator privileges on the machine to run their installer, they bundle the CRT directly in the same directory as the application, for private use. So on a typical machine, you'll find many programs that have opted for this solution.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22329/" ] }
135,303
In C# I could easily write the following: string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString; Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?
In Python 2.5, there is A if C else B which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case: stringValue = otherString or defaultString
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/135303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133/" ] }
135,314
What is the fastest list implementation (in java) in a scenario where the list will be created one element at a time then at a later point be read one element at a time? The reads will be done with an iterator and then the list will then be destroyed. I know that the Big O notation for get is O(1) and add is O(1) for an ArrayList, while LinkedList is O(n) for get and O(1) for add. Does the iterator behave with the same Big O notation?
It depends largely on whether you know the maximum size of each list up front. If you do, use ArrayList ; it will certainly be faster. Otherwise, you'll probably have to profile. While access to the ArrayList is O(1), creating it is not as simple, because of dynamic resizing. Another point to consider is that the space-time trade-off is not clear cut. Each Java object has quite a bit of overhead. While an ArrayList may waste some space on surplus slots, each slot is only 4 bytes (or 8 on a 64-bit JVM). Each element of a LinkedList is probably about 50 bytes (perhaps 100 in a 64-bit JVM). So you have to have quite a few wasted slots in an ArrayList before a LinkedList actually wins its presumed space advantage. Locality of reference is also a factor, and ArrayList is preferable there too. In practice, I almost always use ArrayList .
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/135314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13491/" ] }
135,330
Does anybody know if there is a built-in function in Mathematica for getting the lhs of downvalue rules (without any holding)? I know how to write the code to do it, but it seems basic enough for a built-in For example: a[1]=2;a[2]=3; BuiltInIDoNotKnowOf[a] returns {1,2}
This is like keys() in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just say a[1] = 2 and you have a hash. [1]To get the keys of a hash, I recommend adding this to your init.m or your personal utilities library: keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *) (Or the following pure function version is supposedly slightly faster: keys = DownValues[#][[All,1,1,1]]&; (* Keys of a hash/dictionary. *) ) Either way, keys[a] now returns what you want. (You can get the values of the hash with a /@ keys[a] .) If you want to allow for higher arity hashes, like a[1,2]=5; a[3,4]=6 then you can use this: SetAttributes[removeHead, {HoldAll}];removeHead[h_[args___]] := {args}keys[f_] := removeHead @@@ DownValues[f][[All,1]] Which returns {{1,2}, {3,4}} . (In that case you can get the hash values with a @@@ keys[a] .) Note that DownValues by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just do Sort@keys[f] . So I would actually recommend this version: keys = DownValues[#,Sort->False][[All,1,1,1]]&; Interestingly, there is no mention of the Sort option in the DownValues documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.) Footnotes: [1] What's really handy is that you can mix and match that with function definitions. Like: fib[0] = 1;fib[1] = 1;fib[n_] := fib[n-1] + fib[n-2] You can then add memoization by changing that last line to fib[n_] := fib[n] = fib[n-1] + fib[n-2] which says to cache the answer for all subsequent calls.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/279/" ] }
135,339
Within an n-tier app that makes use of a WCF service to interact with the database, what is the best practice way of making use of LinqToSql classes throughout the app? I've seen it done a couple of different ways but they seemed like they burned a lot of hours creating extra interfaces, message classes, and the like which reduces the benefit you get from not having to write your data access code. Is there a good way to do it currently? Are we stuck waiting for the Entity Framework?
This is like keys() in Perl and Python and other languages that have built in support for hashes (aka dictionaries). As your example illustrates, Mathematica supports hashes without any special syntax. Just say a[1] = 2 and you have a hash. [1]To get the keys of a hash, I recommend adding this to your init.m or your personal utilities library: keys[f_] := DownValues[f][[All,1,1,1]] (* Keys of a hash/dictionary. *) (Or the following pure function version is supposedly slightly faster: keys = DownValues[#][[All,1,1,1]]&; (* Keys of a hash/dictionary. *) ) Either way, keys[a] now returns what you want. (You can get the values of the hash with a /@ keys[a] .) If you want to allow for higher arity hashes, like a[1,2]=5; a[3,4]=6 then you can use this: SetAttributes[removeHead, {HoldAll}];removeHead[h_[args___]] := {args}keys[f_] := removeHead @@@ DownValues[f][[All,1]] Which returns {{1,2}, {3,4}} . (In that case you can get the hash values with a @@@ keys[a] .) Note that DownValues by default sorts the keys, which is probably not a good idea since at best it takes extra time. If you want the keys sorted you can just do Sort@keys[f] . So I would actually recommend this version: keys = DownValues[#,Sort->False][[All,1,1,1]]&; Interestingly, there is no mention of the Sort option in the DownValues documention. I found out about it from an old post from Daniel Lichtblau of Wolfram Research. (I confirmed that it still works in the current version (7.0) of Mathematica.) Footnotes: [1] What's really handy is that you can mix and match that with function definitions. Like: fib[0] = 1;fib[1] = 1;fib[n_] := fib[n-1] + fib[n-2] You can then add memoization by changing that last line to fib[n_] := fib[n] = fib[n-1] + fib[n-2] which says to cache the answer for all subsequent calls.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1860358/" ] }
135,375
I have a ListBox DataTemplate in WPF. I want one item to be tight against the left side of the ListBox and another item to be tight against the right side, but I can't figure out how to do this. So far I have a Grid with three columns, the left and right ones have content and the center is a placeholder with it's width set to "*". Where am I going wrong? Here is the code: <DataTemplate x:Key="SmallCustomerListItem"> <Grid HorizontalAlignment="Stretch"> <Grid.RowDefinitions> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition Width="*"/> <ColumnDefinition/> </Grid.ColumnDefinitions> <WrapPanel HorizontalAlignment="Stretch" Margin="0"> <!--Some content here--> <TextBlock Text="{Binding Path=LastName}" TextWrapping="Wrap" FontSize="24"/> <TextBlock Text=", " TextWrapping="Wrap" FontSize="24"/> <TextBlock Text="{Binding Path=FirstName}" TextWrapping="Wrap" FontSize="24"/> </WrapPanel> <ListBox ItemsSource="{Binding Path=PhoneNumbers}" Grid.Column="2" d:DesignWidth="100" d:DesignHeight="50" Margin="8,0" Background="Transparent" BorderBrush="Transparent" IsHitTestVisible="False" HorizontalAlignment="Stretch"/> </Grid></DataTemplate>
I also had to set: HorizontalContentAlignment="Stretch" on the containing ListBox .
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100/" ] }
135,443
There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this: MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);dynMethod.Invoke(this, new object[] { methodParams }); In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?
Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags: MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, BindingFlags.NonPublic | BindingFlags.Instance);dynMethod.Invoke(this, new object[] { methodParams }); Here's the BindingFlags enumeration documentation .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/135443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8223/" ] }
135,448
How do I check if an object has a specific property in JavaScript? Consider: x = {'key': 1};if ( x.hasOwnProperty('key') ) { //Do this} Is that the best way to do it?
2022 UPDATE Object.hasOwn() Object.hasOwn() is recommended over Object.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive. Example const object1 = { prop: 'exists'};console.log(Object.hasOwn(object1, 'prop'));// expected output: true Original answer I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to typeof this[property] or, even worse, x.key will give you completely misleading results. It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then object.hasOwnProperty is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.) If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: prop in object will give you your desired effect. Since using hasOwnProperty is probably what you want, and considering that you may want a fallback method, I present to you the following solution: var obj = { a: undefined, b: null, c: false};// a, b, c all foundfor ( var prop in obj ) { document.writeln( "Object1: " + prop );}function Class(){ this.a = undefined; this.b = null; this.c = false;}Class.prototype = { a: undefined, b: true, c: true, d: true, e: true};var obj2 = new Class();// a, b, c, d, e foundfor ( var prop in obj2 ) { document.writeln( "Object2: " + prop );}function hasOwnProperty(obj, prop) { var proto = obj.__proto__ || obj.constructor.prototype; return (prop in obj) && (!(prop in proto) || proto[prop] !== obj[prop]);}if ( Object.prototype.hasOwnProperty ) { var hasOwnProperty = function(obj, prop) { return obj.hasOwnProperty(prop); }}// a, b, c found in modern browsers// b, c found in Safari 2.0.1 and olderfor ( var prop in obj2 ) { if ( hasOwnProperty(obj2, prop) ) { document.writeln( "Object2 w/ hasOwn: " + prop ); }} The above is a working, cross-browser, solution to hasOwnProperty() , with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
{ "score": 12, "source": [ "https://Stackoverflow.com/questions/135448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4915/" ] }
135,451
I want to create a list of methods to execute. Each method has the same signature.I thought about putting delegates in a generic collection, but I keep getting this error: 'method' is a 'variable' but is used like a 'method' In theory, here is what I would like to do: List<object> methodsToExecute;int Add(int x, int y){ return x+y; }int Subtract(int x, int y){ return x-y; }delegate int BinaryOp(int x, int y);methodsToExecute.add(new BinaryOp(add));methodsToExecute.add(new BinaryOp(subtract));foreach(object method in methodsToExecute){ method(1,2);} Any ideas on how to accomplish this?Thanks!
You need to cast the object in the list to a BinaryOp , or, better, use a more specific type parameter for the list: delegate int BinaryOp(int x, int y);List<BinaryOp> methodsToExecute = new List<BinaryOp>();methodsToExecute.add(Add);methodsToExecute.add(Subtract);foreach(BinaryOp method in methodsToExecute){ method(1,2);}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8797/" ] }
135,474
For example: char * myString = malloc(sizeof(char)*STRING_BUFFER_SIZE);free(myString);free(myString); Are there any adverse side effects of doing this?
Here's the chapter and verse. If the argument [to the free function] does not match a pointer earlier returned by the calloc , malloc , or realloc function, or if the space has been deallocated by a call to free or realloc , the behavior is undefined. ( ISO 9899:1999 - Programming languages — C , Section 7.20.3.2)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/135474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2064/" ] }
135,530
I have an index on columns A, B, C, D of table T I have a query that pulls from T with A, B, C in the WHERE clause. Will the index be used or will a separate index be needed that only includes A, B, C?
David B is right that you should check the execution plan to verify the index is being used. Will the index be used or will a separate index be needed that only includes A, B, C? To answer this last part of the question, which I think is the core underlying topic (as opposed to the immediate solution), there is almost never a reason to index a subset of your indexed columns. If your index is (A, B, C, D), a WHERE against (A, B, C) will most likely result in an index seek , which is the ideal situation -- the index includes all the information the engine needs to go directly to the result set. I believe this is holds true for numeric types and for equality tests in string types, though it can break down with LIKE '%'s). On the other hand, if your WHERE only referenced D, you would most likely end up with an index scan , which would mean that the SQL engine would have to scan across all combinations of A, B, and C, and then check whether D met your criteria before deciding whether to add the row to the result set. On a particularly large table, when I found myself having to do a lot of queries against column "D", I added an additional index for D only, and saw about 90% performance improvement. Edit: I should also recommend using the Database Engine Tuning Advisor in SQL Management Studio. It will tell you if your table isn't indexed ideally for the query you want to run.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11780/" ] }
135,535
I'm a PHPer, and am not writing object-oriented code. What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP?
It doesn't help you automatically. You can write worse "OO" programs than structural programs, and vice versa. OOP is a tool which allows you to create more powerful abstractions. As with every powerful tool, you have to use it properly. As with every powerful tool, it takes time to learn how to use it properly. As with every powerful tool you will make mistakes. As with every powerful tool you will have to practice a lot. As with every powerful tool you should read a lot about it, and read what other people think. Learn from others. But, as with every powerful tool, there are people out there who misuse it. Learn to not learn bad practices from them. This is hard.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/135535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ] }
135,600
When I download my program from my website to my windows 2003 machine, it has a block on it and you have to right click on the exe, then properties, then select the button "Unblock". I would like to add detection in my installer for when the file is blocked and hence doesn't have enough permissions. But I can't eaisly reproduce getting my exe in this state where it needs to be unblocked. How can I get the unblock to appear on my exe so I can test this functionality?
This is done using NTFS File Streams. There is a stream named "Zone.Identifier" added to downloaded files. When IE7 downloads certain types of file that stream contains: [ZoneTransfer]ZoneId=3 The simplest way to set it is to create a text file with those contents in it, and use more to add it to the alternate stream. Zone.Identifier.txt: [ZoneTransfer]ZoneId=3 Command: more Zone.Identifier.txt > file.exe:Zone.Identifier Then, the way for you to check it would be to try to open the Zone.Identifier stream and look for ZoneId=3, or simply assume that if the stream exists at all that your user will receive that warning. It's also important to note that this has nothing to do with permissions. Administrators see the same warning; it's to do entirely with the source and type of file. The entire stream goes away when users uncheck the "Always ask before opening this file" box and then click Run.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ] }
135,653
I have some tables that I build as a part of my report rollup. I don't need them afterwards at all. Someone mentioned to truncate them as it would be faster.
Deleting records from a table logs every deletion and executes delete triggers for the records deleted. Truncate is a more powerful command that empties a table without logging each row. SQL Server prevents you from truncating a table with foreign keys referencing it, because of the need to check the foreign keys on each row. Truncate is normally ultra-fast, ideal for cleaning out data from a temporary table. It does preserve the structure of the table for future use. If you actually want to remove the table definitions as well as the data, simply drop the tables. See this MSDN article for more info
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
135,657
A bunch of CSS files were pulled in and now I'm trying to clean things up a bit. How can I efficiently identify unused CSS definitions in a whole project?
Chrome Developer Tools has an Audits tab which can show unused CSS selectors. Run an audit, then, under Web Page Performance see Remove unused CSS rules
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6133/" ] }
135,664
For example, how much memory is required to store a list of one million (32-bit) integers? alist = range(1000000) # or list(range(1000000)) in Python 3.0
"It depends." Python allocates space for lists in such a way as to achieve amortized constant time for appending elements to the list. In practice, what this means with the current implementation is... the list always has space allocated for a power-of-two number of elements. So range(1000000) will actually allocate a list big enough to hold 2^20 elements (~ 1.045 million). This is only the space required to store the list structure itself (which is an array of pointers to the Python objects for each element). A 32-bit system will require 4 bytes per element, a 64-bit system will use 8 bytes per element. Furthermore, you need space to store the actual elements. This varies widely. For small integers (-5 to 256 currently), no additional space is needed, but for larger numbers Python allocates a new object for each integer, which takes 10-100 bytes and tends to fragment memory. Bottom line: it's complicated and Python lists are not a good way to store large homogeneous data structures. For that, use the array module or, if you need to do vectorized math, use NumPy. PS- Tuples, unlike lists, are not designed to have elements progressively appended to them. I don't know how the allocator works, but don't even think about using it for large data structures :-)
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4279/" ] }
135,688
What is the proper way to modify environment variables like PATH in OS X? I've looked on Google a little bit and found three different files to edit: /etc/paths ~/.profile ~/.tcshrc I don't even have some of these files, and I'm pretty sure that .tcshrc is wrong, since OS X uses bash now. Where are these variables, especially PATH, defined? I'm running OS X v10.5 (Leopard).
Bruno is right on track. I've done extensive research and if you want to set variables that are available in all GUI applications, your only option is /etc/launchd.conf . Please note that environment.plist does not work for applications launched via Spotlight. This is documented by Steve Sexton here . Open a terminal prompt Type sudo vi /etc/launchd.conf (note: this file might not yet exist) Put contents like the following into the file # Set environment variables here so they are available globally to all apps# (and Terminal), including those launched via Spotlight.## After editing this file run the following command from the terminal to update# environment variables globally without needing to reboot.# NOTE: You will still need to restart the relevant application (including# Terminal) to pick up the changes!# grep -E "^setenv" /etc/launchd.conf | xargs -t -L 1 launchctl## See http://www.digitaledgesw.com/node/31# and http://stackoverflow.com/questions/135688/setting-environment-variables-in-os-x/## Note that you must hardcode the paths below, don't use environment variables.# You also need to surround multiple values in quotes, see MAVEN_OPTS example below.#setenv JAVA_VERSION 1.6setenv JAVA_HOME /System/Library/Frameworks/JavaVM.framework/Versions/1.6/Homesetenv GROOVY_HOME /Applications/Dev/groovysetenv GRAILS_HOME /Applications/Dev/grailssetenv NEXUS_HOME /Applications/Dev/nexus/nexus-webappsetenv JRUBY_HOME /Applications/Dev/jrubysetenv ANT_HOME /Applications/Dev/apache-antsetenv ANT_OPTS -Xmx512Msetenv MAVEN_OPTS "-Xmx1024M -XX:MaxPermSize=512m"setenv M2_HOME /Applications/Dev/apache-mavensetenv JMETER_HOME /Applications/Dev/jakarta-jmeter Save your changes in vi and reboot your Mac. Or use the grep / xargs command which is shown in the code comment above. Prove that your variables are working by opening a Terminal window and typing export and you should see your new variables. These will also be available in IntelliJ IDEA and other GUI applications you launch via Spotlight.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/135688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/85/" ] }
135,730
What are the different types of indexes, what are the benefits of each? I heard of covering and clustered indexes, are there more? Where would you use them?
Unique - Guarantees unique values for the column(or set of columns) included in the index Covering - Includes all of the columns that are used in a particular query (or set of queries), allowing the database to use only the index and not actually have to look at the table data to retrieve the results Clustered - This is way in which the actual data is ordered on the disk, which means if a query uses the clustered index for looking up the values, it does not have to take the additional step of looking up the actual table row for any data not included in the index.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/135730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ] }
135,755
How do you find the version of an installed Perl module? This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my .bashrc function perlmodver { perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \ " is installed.\n"' $1}
Why are you trying to get the version of the module? Do you need this from within a program, do you just need the number to pass to another operation, or are you just trying to find out what you have? I have this built into the cpan (which comes with perl) with the -D switch so you can see the version that you have installed and the current version on CPAN: $ cpan -D Text::CSV_XSText::CSV_XS------------------------------------------------------------------------- Fast 8bit clean version of Text::CSV H/HM/HMBRAND/Text-CSV_XS-0.54.tgz /usr/local/lib/perl5/site_perl/5.8.8/darwin-2level/Text/CSV_XS.pm Installed: 0.32 CPAN: 0.54 Not up to date H.Merijn Brand (HMBRAND) [email protected] If you want to see all of the out-of-date modules, use the -O (capital O) switch: $ cpan -OModule Name Local CPAN-------------------------------------------------------------------------Apache::DB 0.1300 0.1400Apache::SOAP 0.0000 0.7100Apache::Session 1.8300 1.8700Apache::SizeLimit 0.0300 0.9100Apache::XMLRPC::Lite 0.0000 0.7100... and so on If you want to see this for all modules you have installed, try the -a switch to create an autobundle.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/135755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17339/" ] }
135,759
Why can't I create a class in VB.NET that inherits System.IO.Directory ? According to Lutz Roeder, it is not declared as NotInheritable ! I want to create a utility class that adds functionality to the Directory class . For instance, I want to add a Directory.Move function. Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool.
From the Meta Data of .NET namespace System.IO{ // Summary: // Exposes static methods for creating, moving, and enumerating through directories // and subdirectories. This class cannot be inherited. [ComVisible(true)] public static class Directory You cannot inherit from a Static Class.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54420/" ] }
135,777
Seeking a method to: Take whitespace separated tokens in a String; return a suggested Word ie: Google Search can take "fonetic wrd nterpreterr" , and atop of the result page it shows "Did you mean: phonetic word interpreter" A solution in any of the C* languages or Java would be preferred. Are there any existing Open Libraries which perform such functionality? Or is there a way to Utilise a Google API to request a suggested word?
In his article How to Write a Spelling Corrector , Peter Norvig discusses how a Google-like spellchecker could be implemented. The article contains a 20-line implementation in Python, as well as links to several reimplementations in C, C++, C# and Java. Here is an excerpt: The full details of an industrial-strength spell corrector like Google's would be more confusing than enlightening, but I figured that on the plane flight home, in less than a page of code, I could write a toy spelling corrector that achieves 80 or 90% accuracy at a processing speed of at least 10 words per second. Using Norvig's code and this text as training set, i get the following results: >>> import spellch>>> [spellch.correct(w) for w in 'fonetic wrd nterpreterr'.split()]['phonetic', 'word', 'interpreters']
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4857/" ] }
135,782
A lot of my C# code follows this pattern: void foo(string param1, string param2, string param3){ try { // do something... } catch(Exception ex) { LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message)); }} Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?ORDo you have a more generic / better way of doing this?
You could use Reflection and the convention that you must pass the parameters to the LogError with the right order: private static void MyMethod(string s, int x, int y){ try { throw new NotImplementedException(); } catch (Exception ex) { LogError(MethodBase.GetCurrentMethod(), ex, s, x, y); }}private static void LogError(MethodBase method, Exception ex, params object[] values){ ParameterInfo[] parms = method.GetParameters(); object[] namevalues = new object[2 * parms.Length]; string msg = "Error in " + method.Name + "("; for (int i = 0, j = 0; i < parms.Length; i++, j += 2) { msg += "{" + j + "}={" + (j + 1) + "}, "; namevalues[j] = parms[i].Name; if (i < values.Length) namevalues[j + 1] = values[i]; } msg += "exception=" + ex.Message + ")"; Console.WriteLine(string.Format(msg, namevalues));}
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/135782", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ] }
135,789
When doing TDD , how to tell "that's enough tests for this class / feature"? I.e. when could you tell that you completed testing all edge cases?
With Test Driven Development, you’ll write a test before you write the code it tests. Once you’re written the code and the test passes, then it’s time to write another test. If you follow TDD correctly, you’ve written enough tests once you’re code does all that is required. As for edge cases, let's take an example such as validating a parameter in a method. Before you add the parameter to you code, you create tests which verify the code will handle each case correctly. Then you can add the parameter and associated logic, and ensure the tests pass. If you think up more edge cases, then more tests can be added. By taking it one step at a time, you won't have to worry about edge cases when you've finished writing your code, because you'll have already written the tests for them all. Of course, there's always human error, and you may miss something... When that situation occurs, it's time to add another test and then fix the code.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19268/" ] }
135,803
System.InvalidOperationException: DragDrop registration did not succeed. ---> System.Threading.ThreadStateException: What does this exception mean? I get it at this line trying to add a panel to a panel at runtime... splitReport.Panel1.Controls.Add(ChartPanel); Working in VS2008 C#
This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform. If you have the [STAThread] attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created): Thread.CurrentThread.SetApartmentState( ApartmentState.STA ) ( Thread and ApartmentState are members of System.Threading ) That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the [STAThread] attribute. If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
135,834
In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). What are the performance metrics of the two?
SWIG generates (rather ugly) C or C++ code. It is straightforward to use for simple functions (things that can be translated directly) and reasonably easy to use for more complex functions (such as functions with output parameters that need an extra translation step to represent in Python.) For more powerful interfacing you often need to write bits of C as part of the interface file. For anything but simple use you will need to know about CPython and how it represents objects -- not hard, but something to keep in mind. ctypes allows you to directly access C functions, structures and other data, and load arbitrary shared libraries. You do not need to write any C for this, but you do need to understand how C works. It is, you could argue, the flip side of SWIG: it doesn't generate code and it doesn't require a compiler at runtime, but for anything but simple use it does require that you understand how things like C datatypes, casting, memory management and alignment work. You also need to manually or automatically translate C structs, unions and arrays into the equivalent ctypes datastructure, including the right memory layout. It is likely that in pure execution, SWIG is faster than ctypes -- because the management around the actual work is done in C at compiletime rather than in Python at runtime. However, unless you interface a lot of different C functions but each only a few times, it's unlikely the overhead will be really noticeable. In development time, ctypes has a much lower startup cost: you don't have to learn about interface files, you don't have to generate .c files and compile them, you don't have to check out and silence warnings. You can just jump in and start using a single C function with minimal effort, then expand it to more. And you get to test and try things out directly in the Python interpreter. Wrapping lots of code is somewhat tedious, although there are attempts to make that simpler (like ctypes-configure.) SWIG, on the other hand, can be used to generate wrappers for multiple languages (barring language-specific details that need filling in, like the custom C code I mentioned above.) When wrapping lots and lots of code that SWIG can handle with little help, the code generation can also be a lot simpler to set up than the ctypes equivalents.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/135834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14028/" ] }
135,835
I am trying to load a small sample of records from a large database into a test database. How do you tell mysqldump to only give you n records out of 8 million? Thanks
As skaffman says, use the --where option: mysqldump --opt --where="1 limit 1000000" database Of course, that would give you the first million rows from every table.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
135,841
As just stated in a recent question and answer , you can't inherit from a static class. How does one enforce the rules that go along with static classes inside VB.NET? Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn't seem to be a way.
Module == static class If you just want a class that you can't inherit, use a NotInheritable class; but it won't be static/Shared. You could mark all the methods, properties, and members as Shared , but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler. If you really want the VB.Net equivalent to a C# static class, use a Module . It can't be inherited and all members, properties, and methods are static/shared.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8505/" ] }
135,845
A colleague of mine states that booleans as method arguments are not acceptable . They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example. What's easier to understand? file.writeData( data, true ); Or enum WriteMode { Append, Overwrite};file.writeData( data, Append ); Now I got it! ;-) This is definitely an example where an enumeration as second parameter makes the code much more readable. So, what's your opinion on this topic?
Boolean's represent "yes/no" choices. If you want to represent a "yes/no", then use a boolean, it should be self-explanatory. But if it's a choice between two options, neither of which is clearly yes or no, then an enum can sometimes be more readable.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/135845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2012356/" ] }
135,909
I run into this occasionally and always forget how to do it. One of those things that pop up ever so often. Also, what's the formula to convert angles expressed in radians to degrees and back again?
radians = degrees * (pi/180)degrees = radians * (180/pi) As for implementation, the main question is how precise you want to be about the value of pi. There is some related discussion here
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/135909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8683/" ] }
135,919
I haven't been able to find an adequate answer to what exactly the following error means: java.net.SocketException: Software caused connection abort: recv failed Notes: This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail. The only solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case). The URI is definitely available (as confirmed by asking the browser to do the fetch). Relevant code: BufferedReader reader;try { URL url = new URL(URI); reader = new BufferedReader(new InputStreamReader(url.openStream())));} catch( MalformedURLException e ) { throw new IOException("Expecting a well-formed URL: " + e); }//end try: Have a streamString buffer;StringBuilder result = new StringBuilder();while( null != (buffer = reader.readLine()) ) { result.append(buffer); }//end while: Got the contents.reader.close();
This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/135919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12815/" ] }
135,943
I work on relatively sensitive code that we wouldn't want falling into the wrong hands. Up until now, all the code has been keep in house so it hasn't been an issue. I am moving to working from home a day or two a week and we want to secure the code on my laptop. We have looked at a few alternatives, but Windows EFS and Bitlocker seem to be the most obvious. The laptop doesn't have TPM hardware, and I won't have access to Active Directory from home, so EFS looks to be the option. Basically, does anyone else have any alternatives, or issues with using EFS to encrypt source code?
Truecrypt : WARNING: Using TrueCrypt is not secure as it may contain unfixed security issues This page exists only to help migrate existing data encrypted by TrueCrypt. The development of TrueCrypt was ended in 5/2014 after Microsoft terminated support of Windows XP. Windows 8/7/Vista and later offer integrated support for encrypted disks and virtual disk images. Such integrated support is also available on other platforms (click here for more information). You should migrate any data encrypted by TrueCrypt to encrypted disks or virtual disk images supported on your platform...
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/135943", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ] }
136,012
I've done some research into server push with javascript and have found the general consensus to be that what I'm looking for lies in the "Comet" design pattern. Are there any good implementations of this pattern built on top of jQuery? If not, are there any good implementations of this pattern at all? And regardless of the answer to those questions, is there any documentation on this pattern from an implementation stand-point?
I wrote the plugin mentioned by Till. The plugin is an implementation of the Bayeux protocol and currently supports long-polling (local server via AJAX) and callback-polling (remote server via XSS). There is a Bayeux implementation for Python called cometd-twisted that I have heard my plugin works with, but I have not verified this. I have tested and verified it works with cometd-jetty and erlycomet which has a jQuery Comet example included. There is more info on my blog and the current code with a basic chat example can be found on its google code page . Hope this info is helpful and feel free to contact me if need any further help with the plugin.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943957/" ] }
136,026
A customer of ours has Quickbooks 2005 and is looking to have their web data (orders, customers, tax) sent as it is collected from the web in a format that can be imported into Quickbooks 2005 Pro. Does anyone have any experience with this? If so, what was your experience, and what component/method would you recommend for importing this data into Quickbooks?
I wrote the plugin mentioned by Till. The plugin is an implementation of the Bayeux protocol and currently supports long-polling (local server via AJAX) and callback-polling (remote server via XSS). There is a Bayeux implementation for Python called cometd-twisted that I have heard my plugin works with, but I have not verified this. I have tested and verified it works with cometd-jetty and erlycomet which has a jQuery Comet example included. There is more info on my blog and the current code with a basic chat example can be found on its google code page . Hope this info is helpful and feel free to contact me if need any further help with the plugin.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/136026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6158/" ] }
136,033
I despise the PHP language, and I'm quite certain that I'm not alone. But the great thing about PHP is the way that mod_php takes and hides the gory details of integrating with the apache runtime, and achieves CGI-like request isolation and decent performance. What's the shortest-distance approach to getting the same simplicity, speed and isolation as PHP's runtime environment, with Perl semantics? I feel like raw mod_perl gives me too much rope to hang myself with: cross-request globals, messy config, too many template engines to choose from. FastCGI? HTML::Mason? I'd like to do development largely in Perl, if only I had a framework that let me.
Look at Catalyst this MVC (model, view, controller) framework works stand-a-lone or with apache_perl and hides a lot of the messy bits. There is a slightly odd learning curve (quick start, slower middle, then it really clicks for advanced stuff). Catalyst allows you to use Template Toolkit to separate the design logic from the business logic, Template toolkit really is great, even if you decide not to use Catalyst then you should be using this. HTML::Mason isn't something I personally like, although if you do all the HTML yourself then you might want to review Template::Declare which is another alternative you can also use with Catalyst. For database stuff look at DBIx::Class , which yet again works with Catalyst or on it's own.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/136033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22369/" ] }