source_id
int64
1
74.7M
question
stringlengths
0
40.2k
response
stringlengths
0
111k
metadata
dict
138,159
I'm new to PHP and I'm confused seeing some examples calling a function with a @ prefix like @mysql_ping(). What is it for? Googling / searching is not much of a help since @ gets discarded and 'alias' is not good enough keyword.
@ suppresses errors, warnings and notices. You can use it for good purpose if you complement it with a custom error handler or with due check of $php_errormsg variable so you can handle errors properly. In my experience, this proper usage is not seen very much and is instead used a lot in the bad way, just to hide errors without acting on them. More info at http://www.php.net/manual/en/language.operators.errorcontrol.php
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15345/" ] }
138,162
I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly. I am on Windows XP. I tried adding 127.0.0.1 *.local to my c:\windows\system32\drivers\etc\hosts file, also tried: 127.0.0.1 .local Neither of which seem to work. I know I can set them up on different port numbers, but that is a pain since it is hard to remember which port is which. I don't want to have to setup a local DNS server or anything hard, any suggestions?
Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards. Download from the offical website http://mayakron.altervista.org/support/browse.php?path=Acrylic&name=Home Configuring Acrylic DNS Proxy To configure Acrylic DNS Proxy, install it from the above link then go to: Start Programs Acrylic DNS Proxy Config Edit Custom Hosts File (AcrylicHosts.txt) Add the folowing lines on the end of the file: 127.0.0.1 *.localhost127.0.0.1 *.local127.0.0.1 *.lc Restart the Acrylic DNS Proxy service: Start Programs Acrilic DNS Proxy Config Restart Acrylic Service You will also need to adjust your DNS setting in you network interface settings: Start Control Panel Network and Internet Network Connections Local Area Connection Properties TCP/IPv4 Set "Use the following DNS server address": Preferred DNS Server: 127.0.0.1 If you then combine this answer with jeremyasnyder's answer (using VirtualDocumentRoot ) you can then automatically setup domains/virtual hosts by simply creating a directory.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/138162", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ] }
138,177
I use several referenced tables with integer primary keys. Now I want to change ints to GUIDs leaving all references intact. What is the easiest way to do it? Thank you! Addition I do understand the process in general, so I need more detailed advices, for example, how to fill new GUID column. Using default value newid() is correct, but what for already existing rows?
Create a new column for the guidvalue in the master table. Use theuniqueidentifier data type, make itnot null with a newid() default soall existing rows will be populated. Create new uniqueidentifier columnsin the child tables. Run update statements to build the guild relationships using the exisitng int relationships to reference the entities. Drop the original int columns. In addition, leave some space in your data/index pages (specify fillfactor < 100) as guids are not sequential like int identity columns are. This means inserts can be anywhere in the data range and will cause page splits if your pages are 100% full.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ] }
138,250
If I open an image with open("image.jpg") , how can I get the RGB values of a pixel assuming I have the coordinates of the pixel? Then, how can I do the reverse of this? Starting with a blank graphic, 'write' a pixel with a certain RGB value? I would prefer if I didn't have to download any additional libraries.
It's probably best to use the Python Image Library to do this which I'm afraid is a separate download. The easiest way to do what you want is via the load() method on the Image object which returns a pixel access object which you can manipulate like an array: from PIL import Imageim = Image.open('dead_parrot.jpg') # Can be many different formats.pix = im.load()print im.size # Get the width and hight of the image for iterating overprint pix[x,y] # Get the RGBA Value of the a pixel of an imagepix[x,y] = value # Set the RGBA Value of the image (tuple)im.save('alive_parrot.png') # Save the modified pixels as .png Alternatively, look at ImageDraw which gives a much richer API for creating images.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/138250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2592/" ] }
138,273
I have recently run across these terms few times but I am quite confused how they work and when they are usualy implemented?
Well, think of it this way. If you use an array, a simple index-based data structure, and fill it up with random stuff, finding a particular entry gets to be a more and more expensive operation as you fill it with data, since you basically have to start searching from one end toward the other, until you find the one you want. If you want to get faster access to data, you typicall resort to sorting the array and using a binary search. This, however, while increasing the speed of looking up an existing value, makes inserting new values slow, as you need to move existing elements around when you need to insert an element in the middle. A hashtable, on the other hand, has an associated function that takes an entry, and reduces it to a number, a hash-key. This number is then used as an index into the array, and this is where you store the entry. A hashtable revolves around an array, which initially starts out empty. Empty does not mean zero length, the array starts out with a size, but all the elements in the array contains nothing. Each element has two properties, data, and a key that identifies the data. For instance, a list of zip-codes of the US would be a zip-code -> name type of association. The function reduces the key, but does not consider the data. So when you insert something into the hashtable, the function reduces the key to a number, which is used as an index into this (empty) array, and this is where you store the data, both the key, and the associated data. Then, later, you want to find a particular entry that you know the key for, so you run the key through the same function, get its hash-key, and goes to that particular place in the hashtable and retrieves the data there. The theory goes that the function that reduces your key to a hash-key, that number, is computationally much cheaper than the linear search. A typical hashtable does not have an infinite number of elements available for storage, so the number is typically reduced further down to an index which fits into the size of the array. One way to do this is to simply take the modulus of the index compared to the size of the array. For an array with a size of 10, index 0-9 will map directly to an index, and index 10-19 will map down to 0-9 again, and so on. Some keys will be reduced to the same index as an existing entry in the hashtable. At this point the actual keys are compared directly, with all the rules associated with comparing the data types of the key (ie. normal string comparison for instance). If there is a complete match, you either disregard the new data (it already exists) or you overwrite (you replace the old data for that key), or you add it (multi-valued hashtable). If there is no match, which means that though the hash keys was identical, the actual keys were not, you typically find a new location to store that key+data in. Collision resolution has many implementations, and the simplest one is to just go to the next empty element in the array. This simple solution has other problems though, so finding the right resolution algorithm is also a good excercise for hashtables. Hashtables can also grow, if they fill up completely (or close to), and this is usually done by creating a new array of the new size, and calculating all the indexes once more, and placing the items into the new array in their new locations. The function that reduces the key to a number does not produce a linear value, ie. "AAA" becomes 1, then "AAB" becomes 2, so the hashtable is not sorted by any typical value. There is a good wikipedia article available on the subject as well, here .
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/138273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3515/" ] }
138,279
I create a GUID (as a string) and get the hash of it. Can I consider this hash to be unique?
Not as reliably unique as the GUID itself, no. Just to expand, you are reducing your uniqueness by a factor of 4, going from 16 bytes to 4 bytes of possible combinations. As pointed out in the comments the hash size will make a difference. The 4 byte thing was an assumption, horrible at best I know, that it may be used in .NET, where the default hash size is 4 bytes (int). So you can replace what I said above with whatever byte size your hash may be.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ] }
138,280
I am currently working in a project with developers working on three sites. One of the sites is in Delhi, India while the other two are in Europe. The communication between the European offices and the office in Delhi has poor bandwidth and quite bad latency, and a CVS update from there often takes 5-10 minutes even though only a few files have changed. Is there any good CVS proxies out there, or any neat way of keeping separate CVS servers in sync? Do you have any other tips on how the performance can be improved in this scenario? Unfortunately, we will be stuck with CVS during the scope of this project, so switching to something completely different is not an option in the short-term.
Not as reliably unique as the GUID itself, no. Just to expand, you are reducing your uniqueness by a factor of 4, going from 16 bytes to 4 bytes of possible combinations. As pointed out in the comments the hash size will make a difference. The 4 byte thing was an assumption, horrible at best I know, that it may be used in .NET, where the default hash size is 4 bytes (int). So you can replace what I said above with whatever byte size your hash may be.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19220/" ] }
138,309
I have made a SVG image, or more like mini application, for viewing graphs of data. I want to include this in a HTML page, and call methods on the SVG image. Example: <object id="img" data="image.svg" width="500" height="300"/><script>document.getElementById("img").addData([1,23,4]);</script> Is it at all possible to call methods on the SVG document? If so, how do I declare the methods to expose in the SVG file, and how do I call them from the HTML document?
Solution: in svg: <script>document.method = function() {}</script> in html (using prototype to add event listeners): <script>$("img").observe("load", function() {$("img").contentDocument.method()}); You need to listen to the load event on the image. Once the image is loaded, you can use the element.contentDocument to access the document variable on the svg document. Any methods added to that, will be available.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3355/" ] }
138,311
The CSRF prevention built in to Rails is causing some problems for some automated load testing we are doing, and I want to turn it off for the duration of the process. How do I do this?
I love simple questions with clear answers. #I go in application.rbself.allow_forgery_protection = false If you want to do this for testing only you can move that into one of the environment files (obviously, you'll be touching Application then rather than self ). You could also write something like: #I still go in application.rbself.allow_forgery_protection = false unless ENV["RAILS_ENV"] == "production" See here for details. (Continuing Rails' wonderful tradition of having documentation of core features in 2 year old blog posts, which were distilled from commit logs.)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ] }
138,313
I would like to create a page where all images which reside on my website are listed with title and alternative representation. I already wrote me a little program to find and load all HTML files, but now I am stuck at how to extract src , title and alt from this HTML: <img src ="/image/fluffybunny.jpg" title ="Harvey the bunny" alt ="a cute little fluffy bunny" /> I guess this should be done with some regex, but since the order of the tags may vary, and I need all of them, I don't really know how to parse this in an elegant way (I could do it the hard char by char way, but that's painful).
EDIT : now that I know better Using regexp to solve this kind of problem is a bad idea and will likely lead in unmaintainable and unreliable code. Better use an HTML parser . Solution With regexp In that case it's better to split the process into two parts : get all the img tag extract their metadata I will assume your doc is not xHTML strict so you can't use an XML parser. E.G. with this web page source code : /* preg_match_all match the regexp in all the $html string and output everything as an array in $result. "i" option is used to make it case insensitive */preg_match_all('/<img[^>]+>/i',$html, $result); print_r($result);Array( [0] => Array ( [0] => <img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" /> [1] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" /> [2] => <img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" /> [3] => <img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" /> [4] => <img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />[...] )) Then we get all the img tag attributes with a loop : $img = array();foreach( $result as $img_tag){ preg_match_all('/(alt|title|src)=("[^"]*")/i',$img_tag, $img[$img_tag]);}print_r($img);Array( [<img src="/Content/Img/stackoverflow-logo-250.png" width="250" height="70" alt="logo link to homepage" />] => Array ( [0] => Array ( [0] => src="/Content/Img/stackoverflow-logo-250.png" [1] => alt="logo link to homepage" ) [1] => Array ( [0] => src [1] => alt ) [2] => Array ( [0] => "/Content/Img/stackoverflow-logo-250.png" [1] => "logo link to homepage" ) ) [<img class="vote-up" src="/content/img/vote-arrow-up.png" alt="vote up" title="This was helpful (click again to undo)" />] => Array ( [0] => Array ( [0] => src="/content/img/vote-arrow-up.png" [1] => alt="vote up" [2] => title="This was helpful (click again to undo)" ) [1] => Array ( [0] => src [1] => alt [2] => title ) [2] => Array ( [0] => "/content/img/vote-arrow-up.png" [1] => "vote up" [2] => "This was helpful (click again to undo)" ) ) [<img class="vote-down" src="/content/img/vote-arrow-down.png" alt="vote down" title="This was not helpful (click again to undo)" />] => Array ( [0] => Array ( [0] => src="/content/img/vote-arrow-down.png" [1] => alt="vote down" [2] => title="This was not helpful (click again to undo)" ) [1] => Array ( [0] => src [1] => alt [2] => title ) [2] => Array ( [0] => "/content/img/vote-arrow-down.png" [1] => "vote down" [2] => "This was not helpful (click again to undo)" ) ) [<img src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" height=32 width=32 alt="gravatar image" />] => Array ( [0] => Array ( [0] => src="http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" [1] => alt="gravatar image" ) [1] => Array ( [0] => src [1] => alt ) [2] => Array ( [0] => "http://www.gravatar.com/avatar/df299babc56f0a79678e567e87a09c31?s=32&d=identicon&r=PG" [1] => "gravatar image" ) ) [..] )) Regexps are CPU intensive so you may want to cache this page. If you have no cache system, you can tweak your own by using ob_start and loading / saving from a text file. How does this stuff work ? First, we use preg_ match_ all , a function that gets every string matching the pattern and ouput it in it's third parameter. The regexps : <img[^>]+> We apply it on all html web pages. It can be read as every string that starts with " <img ", contains non ">" char and ends with a > . (alt|title|src)=("[^"]*") We apply it successively on each img tag. It can be read as every string starting with "alt", "title" or "src", then a "=", then a ' " ', a bunch of stuff that are not ' " ' and ends with a ' " '. Isolate the sub-strings between () . Finally, every time you want to deal with regexps, it handy to have good tools to quickly test them. Check this online regexp tester . EDIT : answer to the first comment. It's true that I did not think about the (hopefully few) people using single quotes. Well, if you use only ', just replace all the " by '. If you mix both. First you should slap yourself :-), then try to use ("|') instead or " and [^ø] to replace [^"].
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/138313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7021/" ] }
138,321
I unpacked a zip-file delivery into a clearcase view. Now I want to add the complete file tree to the repository. The GUI only provides an "Add to source control ..." for individual files/directories. Do you know how to recursively add the whole tree? (I'm on a Windows system, but have Cygwin installed.)
I would rather go with the clearfsimport script, better equipped to import multiple times the same set of files, and automatically: add new files, make new version of existing files previously imported (but modified in the source set of files re-imported) remove files already imported but no longer present in the source set of files. make a clear log of all operations made during the import process. So if your 'zip-file delivery needs to be updated on a regularly basis, clearfsimport is the way to go, but with the following options: clearfsimport -preview -rec -nset c:\sourceDir\* m:\MyView\MyVob\MyDestinationDirectory Note the : -preview option: it will allow to check what would happen without actually doing anything. '*' used only in Windows environment, in order to import the content of a directory -nset option. From CMWiki , about that 'nset' option: By default, clearfsimport is meant to be used by the vob owner or a privileged user, but users often overlook the -nsetevent option, with which it may be used by any user. This option drives clearfsimport not to set the time stamps of elements to this of the source file object outside the vob (which requires privileged access). There is a minor non-obvious side-effect with this: once a version will have been created with a current time stamp, even the vob owner will not be able to import on top of it a version with an older (as it would be) time stamp, without this -nsetevent option. I.e. once you use this option, normal or privileged user, you are more or less bound to use it in the continuation.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/138321", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20668/" ] }
138,331
Requirements: free, preferably open-source implemented in one of the .NET managed langs Google found these: A Generic, Reusable DiffAlgorithm on codeproject An O(ND) Difference Algorithm for C# Diff/Merge/Patch Library for C#/.NET by Joshua Tauberer EDIT: No apps please, only libraries.
You can grab the COM component that uses Google's Diff/Patch/Match . It works from .NET. Update, 2010 Oct 17 : The Google Diff/Patch/Merge code has been ported to C#. The COM component still works, but if you're coming from .NET, you'll wanna use the .NET port directly.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/138331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1196/" ] }
138,334
After being troubled by an issue that I simply did not have the knowledge to debug, I've just decided that I have to learn how to use Windbg. My only problem: I have no clue where to start :-( I'm not really a WinApi-Guy, having use languages that abstract the Windows Api away from me usually. So I just wonder: What is the best souce (Book, Website) to learn Windbg for someone who knows programming but not much about the inner depths of Windows? (And yes, I do read oldnewthing every day :))
For a book, try Advanced Windows Debugging (Addison-Wesley Microsoft Technology Series) (source: knowfree.net ) Also, for a great reference sheet, see Common WinDbg Commands (Thematically Grouped) by Robert Kuster.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138334", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ] }
138,361
Or is it now the other way around? From what I've heard there are some areas in which C# proves to be faster than C++, but I've never had the guts to test it by myself. Thought any of you could explain these differences in detail or point me to the right place for information on this.
There is no strict reason why a bytecode based language like C# or Java that has a JIT cannot be as fast as C++ code. However C++ code used to be significantly faster for a long time, and also today still is in many cases. This is mainly due to the more advanced JIT optimizations being complicated to implement, and the really cool ones are only arriving just now. So C++ is faster, in many cases. But this is only part of the answer. The cases where C++ is actually faster, are highly optimized programs, where expert programmers thoroughly optimized the hell out of the code. This is not only very time consuming (and thus expensive), but also commonly leads to errors due to over-optimizations. On the other hand, code in interpreted languages gets faster in later versions of the runtime (.NET CLR or Java VM), without you doing anything. And there are a lot of useful optimizations JIT compilers can do that are simply impossible in languages with pointers. Also, some argue that garbage collection should generally be as fast or faster as manual memory management, and in many cases it is. You can generally implement and achieve all of this in C++ or C, but it's going to be much more complicated and error prone. As Donald Knuth said, "premature optimization is the root of all evil". If you really know for sure that your application will mostly consist of very performance critical arithmetic, and that it will be the bottleneck, and it's certainly going to be faster in C++, and you're sure that C++ won't conflict with your other requirements, go for C++. In any other case, concentrate on first implementing your application correctly in whatever language suits you best, then find performance bottlenecks if it runs too slow, and then think about how to optimize the code. In the worst case, you might need to call out to C code through a foreign function interface, so you'll still have the ability to write critical parts in lower level language. Keep in mind that it's relatively easy to optimize a correct program, but much harder to correct an optimized program. Giving actual percentages of speed advantages is impossible, it largely depends on your code. In many cases, the programming language implementation isn't even the bottleneck. Take the benchmarks at http://benchmarksgame.alioth.debian.org/ with a great deal of scepticism, as these largely test arithmetic code, which is most likely not similar to your code at all.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/138361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ] }
138,374
I'm attempting to do an AJAX call (via JQuery) that will initiate a fairly long process. I'd like the script to simply send a response indicating that the process has started, but JQuery won't return the response until the PHP script is done running. I've tried this with a "close" header (below), and also with output buffering; neither seems to work. Any guesses? or is this something I need to do in JQuery? <?phpecho( "We'll email you as soon as this is done." );header( "Connection: Close" );// do some stuff that will take a whilemail( '[email protected]', "okay I'm done", 'Yup, all done.' );?>
The following PHP manual page (incl. user-notes) suggests multiple instructions on how to close the TCP connection to the browser without ending the PHP script: Connection handling Docs Supposedly it requires a bit more than sending a close header. OP then confirms: yup, this did the trick: pointing to user-note #71172 (Nov 2006) copied here: Closing the users browser connection whilst keeping your php script running has been an issue since [PHP] 4.1, when the behaviour of register_shutdown_function() was modified so that it would not automatically close the users connection. sts at mail dot xubion dot hu Posted the original solution: <?phpheader("Connection: close");ob_start();phpinfo();$size = ob_get_length();header("Content-Length: $size");ob_end_flush();flush();sleep(13);error_log("do something in the background");?> Which works fine until you substitute phpinfo() for echo('text I want user to see'); in which case the headers are never sent! The solution is to explicitly turn off output buffering and clear the buffer prior to sending your header information. Example: <?phpob_end_clean();header("Connection: close");ignore_user_abort(true); // just to be safeob_start();echo('Text the user will see');$size = ob_get_length();header("Content-Length: $size");ob_end_flush(); // Strange behaviour, will not workflush(); // Unless both are called !// Do processing here sleep(30);echo('Text user will never see');?> Just spent 3 hours trying to figure this one out, hope it helps someone :) Tested in: IE 7.5730.11 Mozilla Firefox 1.81 Later on in July 2010 in a related answer Arctic Fire then linked two further user-notes that were-follow-ups to the one above: Connection Handling user-note #89177 (Feb 2009) Connection Handling user-note #93441 (Sep 2009)
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/138374", "https://Stackoverflow.com", "https://Stackoverflow.com/users/82944/" ] }
138,383
Sometimes coloring a logfile or other gives a good overview when looking for stuff and behaviors I just saw that grep have a coloring feature grep -C 99999 --color <regexp> <filename> What other methods are there?
For searching source code, I use ack . It's got a lot of options that make sense for searching code (such as automatically ignoring SCM directories).
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842/" ] }
138,419
While porting an application from SQL 2005 to SQL Server Compact Edition, I found that I need to port this command: SELECT TOP 1 Id FROM tblJob WHERE Holder_Id IS NULL But SQL Server Compact Edition doesn't support the TOP keyword. How can I port this command?
SELECT TOP(1) Id FROM tblJob WHERE Holder_Id IS NULL Need the brackets as far as I know. reference: http://technet.microsoft.com/en-us/library/bb686896.aspx addition: likewise, only for version 3.5 onwards
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15136/" ] }
138,422
I have a HTML report, which needs to be printed landscape because of the many columns. It there a way to do this, without the user having to change the document settings? And what are the options amongst browsers.
In your CSS you can set the @page property as shown below. @media print{@page {size: landscape}} The @page is part of CSS 2.1 specification however this size is not as highlighted by the answer to the question Is @Page { size:landscape} obsolete? : CSS 2.1 no longer specifies the size attribute. The current working draft for CSS3 Paged Media module does specify it (but this is not standard or accepted). As stated the size option comes from the CSS 3 Draft Specification . In theory it can be set to both a page size and orientation although in my sample the size is omitted. The support is very mixed with a bug report begin filed in firefox , most browsers do not support it. It may seem to work in IE7 but this is because IE7 will remember the users last selection of landscape or portrait in print preview (only the browser is re-started). This article does have some suggested work arounds using JavaScript or ActiveX that send keys to the users browser although it they are not ideal and rely on changing the browsers security settings. Alternately you could rotate the content rather than the page orientation. This can be done by creating a style and applying it to the body that includes these two lines but this also has draw backs creating many alignment and layout issues. <style type="text/css" media="print"> .page { -webkit-transform: rotate(-90deg); -moz-transform:rotate(-90deg); filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3); }</style> The final alternative I have found is to create a landscape version in a PDF. You can point to so when the user selects print it prints the PDF. However I could not get this to auto print work in IE7. <link media="print" rel="Alternate" href="print.pdf"> In conclusion in some browsers it is relativity easy using the @page size option however in many browsers there is no sure way and it would depend on your content and environment. This maybe why Google Documents creates a PDF when print is selected and then allows the user to open and print that.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/138422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ] }
138,449
Here's the problem: In C# I'm getting information from a legacy ACCESS database. .NET converts the content of the database (in the case of this problem a string) to Unicode before handing the content to me. How do I convert this Unicode string back to it's ASCII equivalent? Edit Unicode char 710 is indeed MODIFIER LETTER CIRCUMFLEX ACCENT. Here's the problem a bit more precise: -> (Extended) ASCII character ê (Extended ASCII 136) was inserted in the database. -> Either Access or the reading component in .NET converted this to U+02C6 U+0065 (MODIFIER LETTER CIRCUMFLEX ACCENT + LATIN SMALL LETTER E) -> I need the (Extended) ASCII character 136 back. Here's what I've tried (I see now why this did not work...): string myInput = Convert.ToString(Convert.ToChar(710));byte[] asBytes = Encoding.ASCII.GetBytes(myInput); But this does not result in 94 but a byte with value 63... Here's a new try but it still does not work: byte[] bytes = Encoding.ASCII.GetBytes("ê"); Soltution Thanks to both csgero and bzlm for pointing in the right direction I solved the problem here .
Okay, let's elaborate. Both csgero and bzlm pointed in the right direction. Because of blzm's reply I looked up the Windows-1252 page on wiki and found that it's called a codepage. The wikipedia article for Code page which stated the following: No formal standard existed for these ‘ extended character sets ’; IBM merely referred to the variants as code pages, as it had always done for variants of EBCDIC encodings. This led me to codepage 437: n ASCII-compatible code pages, the lower 128 characters maintained their standard US-ASCII values, and different pages (or sets of characters) could be made available in the upper 128 characters. DOS computers built for the North American market, for example, used code page 437 , which included accented characters needed for French, German, and a few other European languages, as well as some graphical line-drawing characters. So, codepage 437 was the codepage I was calling 'extended ASCII', it had the ê as character 136 so I looked up some other chars as well and they seem right. csgero came with the Encoding.GetEncoding() hint, I used it to create the following statement which solves my problem: byte[] bytes = Encoding.GetEncoding(437).GetBytes("ê");
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1830/" ] }
138,493
How does one handle a DateTime with a NOT NULL ? I want to do something like this: SELECT * FROM someTable WHERE thisDateTime IS NOT NULL But how?
erm it does work? I've just tested it? /****** Object: Table [dbo].[DateTest] Script Date: 09/26/2008 10:44:21 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[DateTest]( [Date1] [datetime] NULL, [Date2] [datetime] NOT NULL) ON [PRIMARY]GOInsert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')GoSELECT * FROM DateTest WHERE Date1 is not NULLGOSELECT * FROM DateTest WHERE Date2 is not NULL
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ] }
138,496
How would you go about producing reports by user selected date ranges in a rails app? What are the best date range pickers? edit in response to patrick : I am looking for a bit of both widget and active record advice but what I am really curious about is how to restfully display a date ranged list based on user selected dates.
Are we asking an interface question here (i.e. you want a widget) or an ActiveRecord question? Date Picking Widgets 1) Default Rails Solution : See date_select documentation here . 2) Use a plugin : Why write code? I personally like the CalendarDateSelect plugin, using a pair of the suckers when I need a range. 3) Adapt a Javascript widget to Rails : It is almost trivial to integrate something like the Yahoo UI library (YUI) Calendar , which is all Javascript, to Rails. From the perspective of Rails its just another way to populate the params[:start_date] and params[:end_date] . YUI Calendar has native support for ranges. Getting the data from the Widgets 1) Default Rails Solution See date_select documentation here . #an application helper method you'll find helpful#credit to http://blog.zerosum.org/2007/5/9/deconstructing-date_select# Reconstruct a date object from date_select helper form paramsdef build_date_from_params(field_name, params) Date.new(params["#{field_name.to_s}(1i)"].to_i, params["#{field_name.to_s}(2i)"].to_i, params["#{field_name.to_s}(3i)"].to_i)end#goes into view<%= date_select "report", "start_date", ... %><%= date_select "report", "end_date", ... %> #goes into controller -- add your own error handling/defaults, please!report_start_date = build_date_from_params("start_date", params[:report])report_end_date = build_date_from_params("end_date", params[:report]) 2) CalendarDateSelect : Rather similar to the above, just with sexier visible UI. 3) Adapt a Javascript widget : Typically this means that some form element will have the date input as a string. Great news for you, since Date.parse is some serious magic. The params[:some_form_element_name] will be initialized by Rails for you. #goes in controller. Please handle errors yourself -- Javascript != trusted input.report_start_date = Date.parse(params[:report_start_date]) Writing the call to ActiveRecord Easy as pie. #initialize start_date and end_date up here, by pulling from params probably @models = SomeModel.find(:all, :conditions => ['date >= ? and date <= ?', start_date, end_date]) #do something with models
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138496", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6805/" ] }
138,497
How can I iterate over each file in a directory using a for loop? And how could I tell if a certain entry is a directory or if it's just a file?
This lists all the files (and only the files) in the current directory and its subdirectories recursively: for /r %i in (*) do echo %i Also if you run that command in a batch file you need to double the % signs. for /r %%i in (*) do echo %%i (thanks @agnul)
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/138497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ] }
138,501
I have mixed data i nvarchar column (words and numbers).Which is fastest way to sort data in this column in Numeric Order. Result example: 1 2 3 ... 10 11 ... aaaa aaab b ba ba ...
Use this: ORDER BY CASE WHEN ISNUMERIC(column) = 1 THEN 0 ELSE 1 END, CASE WHEN ISNUMERIC(column) = 1 THEN CAST(column AS INT) ELSE 0 END, column This works as expected. Note : You say fastest way . This sql was fast for me to produce, but the execution plan shows a table-scan, followed by a scalar computation. This could possibly produce a temporary result containing all the values of that column with some extra temporary columns for the ISNUMERIC results. It might not be fast to execute.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ] }
138,511
I know there's some JAVA_OPTS to set to remotely debug a Java program. What are they and what do they mean ?
I have this article bookmarked on setting this up for Java 5 and below. Basically run it with : -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=1044 For Java 5 and above , run it with: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044 If you want Java to wait for you to connect before executing the application, replace suspend=n with suspend=y .
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/138511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ] }
138,521
How feasible would it be to compile Python (possibly via an intermediate C representation) into machine code? Presumably it would need to link to a Python runtime library, and any parts of the Python standard library which were Python themselves would need to be compiled (and linked in) too. Also, you would need to bundle the Python interpreter if you wanted to do dynamic evaluation of expressions, but perhaps a subset of Python that didn't allow this would still be useful. Would it provide any speed and/or memory usage advantages? Presumably the startup time of the Python interpreter would be eliminated (although shared libraries would still need loading at startup).
Try ShedSkin Python-to-C++ compiler, but it is far from perfect. Also there is Psyco - Python JIT if only speedup is needed. But IMHO this is not worth the effort. For speed-critical parts of code best solution would be to write them as C/C++ extensions.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22610/" ] }
138,555
I need to convert HTML documents into valid XML, preferably XHTML. What's the best way to do this? Does anybody know a toolkit/library/sample/...whatever that helps me to get that task done? To be a bit more clear here, my application has to do the conversion automatically at runtime. I don't look for a tool that helps me to move some pages to XHTML manually.
Convert from HTML to XML with HTML Tidy Downloadable Binaries JRoppert, For your need, i guess you might want to look at the Sources c:\temp>tidy -helptidy [option...] [file...] [option...] [file...]Utility to clean up and pretty print HTML/XHTML/XMLsee http://tidy.sourceforge.net/Options for HTML Tidy for Windows released on 14 February 2006:File manipulation----------------- -output <file>, -o write output to the specified <file> <file> -config <file> set configuration options from the specified <file> -file <file>, -f write errors to the specified <file> <file> -modify, -m modify the original input filesProcessing directives--------------------- -indent, -i indent element content -wrap <column>, -w wrap text at the specified <column>. 0 is assumed if <column> <column> is missing. When this option is omitted, the default of the configuration option "wrap" applies. -upper, -u force tags to upper case -clean, -c replace FONT, NOBR and CENTER tags by CSS -bare, -b strip out smart quotes and em dashes, etc. -numeric, -n output numeric rather than named entities -errors, -e only show errors -quiet, -q suppress nonessential output -omit omit optional end tags -xml specify the input is well formed XML -asxml, -asxhtml convert HTML to well formed XHTML -ashtml force XHTML to well formed HTML -access <level> do additional accessibility checks (<level> = 0, 1, 2, 3). 0 is assumed if <level> is missing.Character encodings------------------- -raw output values above 127 without conversion to entities -ascii use ISO-8859-1 for input, US-ASCII for output -latin0 use ISO-8859-15 for input, US-ASCII for output -latin1 use ISO-8859-1 for both input and output -iso2022 use ISO-2022 for both input and output -utf8 use UTF-8 for both input and output -mac use MacRoman for input, US-ASCII for output -win1252 use Windows-1252 for input, US-ASCII for output -ibm858 use IBM-858 (CP850+Euro) for input, US-ASCII for output -utf16le use UTF-16LE for both input and output -utf16be use UTF-16BE for both input and output -utf16 use UTF-16 for both input and output -big5 use Big5 for both input and output -shiftjis use Shift_JIS for both input and output -language <lang> set the two-letter language code <lang> (for future use)Miscellaneous------------- -version, -v show the version of Tidy -help, -h, -? list the command line options -xml-help list the command line options in XML format -help-config list all configuration options -xml-config list all configuration options in XML format -show-config list the current configuration settingsUse --blah blarg for any configuration option "blah" with argument "blarg"Input/Output default to stdin/stdout respectivelySingle letter options apart from -f may be combinedas in: tidy -f errs.txt -imu foo.htmlFor further info on HTML see http://www.w3.org/MarkUp
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6777/" ] }
138,575
I have a set of XSDs from which I generate data access classes, stored procedures and more. What I don't have is a way to generate database table from these - is there a tool that will generate the DDL statements for me? This is not the same as Create DB table from dataset table , as I do not have dataset tables, but XSDs.
Commercial Product: Altova's XML Spy . Note that there's no general solution to this. An XSD can easily describe something that does not map to a relational database. While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it won't work out well. If the XSD's have features that don't map well you'll have to (1) design a mapping of some kind and then (2) write your own application to translate the XSD's into DDL. Been there, done that. Work for hire -- no open source available.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1583/" ] }
138,576
I'm trying to use the tree command in a windows commandline to generate a text file listing the contents of a directory but when I pipe the output the unicode characters get stuffed up. Here is the command I am using: tree /f /a > output.txt The results in the console window are fine: \---Erika szobája cover.jpg Erika szobája.m3u Kátai Tamás - 01 Télvíz.ogg Kátai Tamás - 02 Zölderdõ.ogg Kátai Tamás - 03 Renoir kertje.ogg Kátai Tamás - 04 Esõben szaladtál.ogg Kátai Tamás - 05 Ázik az út.ogg Kátai Tamás - 06 Sûrû völgyek takaród.ogg Kátai Tamás - 07 Õszhozó.ogg Kátai Tamás - 08 Mécsvilág.ogg Kátai Tamás - 09 Zúzmara.ogg But the text file is no good: \---Erika szob ja cover.jpg Erika szob ja.m3u K tai Tam s - 01 T‚lv¡z.ogg K tai Tam s - 02 Z”lderdä.ogg K tai Tam s - 03 Renoir kertje.ogg K tai Tam s - 04 Esäben szaladt l.ogg K tai Tam s - 05 µzik az £t.ogg K tai Tam s - 06 S–r– v”lgyek takar¢d.ogg K tai Tam s - 07 åszhoz¢.ogg K tai Tam s - 08 M‚csvil g.ogg K tai Tam s - 09 Z£zmara.ogg How can I fix this? Ideally the text file would be exactly the same as the output in the console window. I tried Chris Jester-Young's suggestion (what happened, did you delete it Chris?) of running the command line with the /U switch, it looked like exactly what I needed but it does not appear to work. I have tried opening the file in both VS2008 and notepad and both show the same incorrect characters.
Have someone already tried this: tree /f /a |clip Open notepad, ctrl + V, save in notepad as output.txt with unicode support?
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/138576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/48281/" ] }
138,600
What is the right way of initializing a static map? Do we need a static function that will initialize it?
Using C++11: #include <map>using namespace std;map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}}; Using Boost.Assign : #include <map>#include "boost/assign.hpp"using namespace std;using namespace boost::assign;map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/138600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15163/" ] }
138,617
Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters? For example I have the following navigation-rule <navigation-rule> <navigation-case> <from-outcome>showMessage</from-outcome> <to-view-id>/showMessage.jsf</to-view-id> <redirect/> </navigation-case></navigation-rule> In my page I would like to output the following html code: <a href="/showMessage.jsf?msg=23">click to see the message</a> I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file.
This is an interesting idea. I'd be curious to know how it pans out in practice. Getting the navigation rules Navigation is handled by the NavigationHandler . Getting hold of the NavigationHandler isn't difficult, but the API does not expose the rules it uses. As I see it, you can: parse faces-config.xml on initialization and store the rules in the application context ( easy ) implement your own NavigationHandler that ignores the rules in faces-config.xml or supplements them with your own rules file and exposes its ruleset somehow ( workable, but takes a bit of work ) mock your own FacesContext and pass it to the existing navigation handler ( really difficult to make two FacesContext object coexist in same thread and extremely inefficient ) Now, you have another problem too. Where are you going to keep the mappings to look up the views? Hard-code them in the beans? Using the navigation rules Off hand, I can think of two ways you could construct parameter-containing URLs from the back-end. Both involve defining a bean of some kind. <managed-bean> <managed-bean-name>navBean</managed-bean-name> <managed-bean-class>foo.NavBean</managed-bean-class> <managed-bean-scope>application</managed-bean-scope></managed-bean> Source: package foo;import java.io.IOException;import java.io.Serializable;import java.net.URLEncoder;import javax.faces.context.ExternalContext;import javax.faces.context.FacesContext;public class NavBean implements Serializable { private String getView() { String viewId = "/showMessage.faces"; // or look this up somewhere return viewId; } /** * Regular link to page */ public String getUrlLink() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); String navUrl = context.getExternalContext().encodeActionURL( extContext.getRequestContextPath() + viewId); return navUrl; } /** * Just some value */ public String getValue() { return "" + System.currentTimeMillis(); } /** * Invoked by action */ public String invokeRedirect() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); try { String charEncoding = extContext.getRequestCharacterEncoding(); String name = URLEncoder.encode("foo", charEncoding); String value = URLEncoder.encode(getValue(), charEncoding); viewId = extContext.getRequestContextPath() + viewId + '?' + name + "=" + value; String urlLink = context.getExternalContext().encodeActionURL( viewId); extContext.redirect(urlLink); } catch (IOException e) { extContext.log(getClass().getName() + ".invokeRedirect", e); } return null; }} GET For a GET request, you can use the UIParameters to set the values and let the renderer build the parameter list. <h:outputLink value="#{navBean.urlLink}"> <f:param name="foo" value="#{navBean.value}" /> <h:outputText value="get" /></h:outputLink> POST If you want to set the URL to a view during a POST action, you can do it using a redirect in an action (invoked by a button or commandLink). <h:commandLink id="myCommandLink" action="#{navBean.invokeRedirect}"> <h:outputText value="post" /></h:commandLink> Notes Note that ExternalContext.encodeActionURL is used to encode the string. This is good practice for producing code that is portable across contexts (portlets, etcetera). You would use encodeResourceURL if you were encoding a link to an image or download file.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19331/" ] }
138,669
How can i check in JavaScript if a variable is defined in a page? Suppose I want to check if a variable named "x" is defined in a page, if I do if(x != null) , it gives me an error.
I got it to work using if (typeof(x) != "undefined")
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/138669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22628/" ] }
138,670
How unique is the php session id? I got the impression from various things that I've read that I should not rely on two users never getting the same sessionid. Isn't it a GUID?
It's not very unique as shipped. In the default configuration it's the result of a hash of various things including the result of gettimeofday (which isn't terribly unique), but if you're worried, you should configure it to draw some entropy from /dev/urandom, like so ini_set("session.entropy_file", "/dev/urandom");ini_set("session.entropy_length", "512"); search for "php_session_create_id" in the code for the actual algorithm they're using. Edited to add: There's a DFA random-number generator seeded by the pid, mixed with the time in usecs. It's not a firm uniqueness condition especially from a security perspective . Use the entropy config above. Update: As of PHP 5.4.0 session.entropy_file defaults to /dev/urandom or /dev/arandom if it is available. In PHP 5.3.0 this directive is left empty by default. PHP Manual
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22629/" ] }
138,680
is it possible to extend vim functionality via custom extension (preferably, written in Python)? What I need ideally is custom command when in command mode. E.g. ESC :do_this :do_that
vim supports scripting in python (and in perl as well, I think). You just have to make sure that the vim distribution you are using has been compiled with python support. If you are using a Linux system, you can download the source and then compile it with ./configure --enable-pythoninterp makesudo make install Inside vim, you can type :version to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise). Then, to check the usage of the python module, you can type :help python P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well. P.P.S: to create a "custom command in command mode" (if I understand correctly what you mean), you can create a function "MyFunction" in a vim script (using python or the vim scripting language) and then invoke it with :Call MyFunction() Check :help user-functions for details
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22623/" ] }
138,703
Is there any way to automatically wrap comments at the 80-column boundary as you type them? ..or failing that, any way to display a faint line at the coulmn 80 boundary to make wrapping them manually a little easier? Several other IDEs I use have one or other of those functions and it makes writing comments that wrap in sensible places much easier/quicker. [Edit] If (like me) you're using Visual C++ Express, you need to change the VisualStudio part of the key into VCExpress - had me confused for a while there!
Take a look at the question here: Hidden Features of Visual Studio (2005-2010)? It shows how to do that: "Under "HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor" Create a String called "Guides" with the value "RGB(255,0,0) 79" to have a red line at column 80 in the text editor."
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15369/" ] }
138,819
If I am iterating over each file using : @echo offFOR %%f IN (*\*.\**) DO ( echo %%f) how could I print the extension of each file? I tried assigning %%f to a temporary variable, and then using the code : echo "%t:~-3%" to print but with no success.
The FOR command has several built-in switches that allow you to modify file names. Try the following: @echo offfor %%i in (*.*) do echo "%%~xi" For further details, use help for to get a complete list of the modifiers - there are quite a few!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/138819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ] }
138,839
Currently I use .Net WebBrowser.Document.Images() to do this. It requires the Webrowser to load the document. It's messy and takes up resources. According to this question XPath is better than a regex at this. Anyone know how to do this in C#?
If your input string is valid XHTML you can treat is as xml, load it into an xmldocument, and do XPath magic :) But it's not always the case. Otherwise you can try this function, that will return all image links from HtmlSource : public List<Uri> FetchLinksFromSource(string htmlSource){ List<Uri> links = new List<Uri>(); string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>"; MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline); foreach (Match m in matchesImgSrc) { string href = m.Groups[1].Value; links.Add(new Uri(href)); } return links;} And you can use it like this : HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.example.com");request.Credentials = System.Net.CredentialCache.DefaultCredentials;HttpWebResponse response = (HttpWebResponse)request.GetResponse();if (response.StatusCode == HttpStatusCode.OK){ using(StreamReader sr = new StreamReader(response.GetResponseStream())) { List<Uri> links = FetchLinksFromSource(sr.ReadToEnd()); }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/138839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5648/" ] }
138,884
I would like to know when I should include external scripts or write them inline with the html code, in terms of performance and ease of maintenance. What is the general practice for this? Real-world-scenario - I have several html pages that need client-side form validation. For this I use a jQuery plugin that I include on all these pages. But the question is, do I: write the bits of code that configure this script inline? include all bits in one file that's share among all these html pages? include each bit in a separate external file, one for each html page? Thanks.
At the time this answer was originally posted (2008), the rule was simple: All script should be external. Both for maintenance and performance. (Why performance? Because if the code is separate, it can easier be cached by browsers.) JavaScript doesn't belong in the HTML code and if it contains special characters (such as < , > ) it even creates problems. Nowadays, web scalability has changed. Reducing the number of requests has become a valid consideration due to the latency of making multiple HTTP requests. This makes the answer more complex: in most cases, having JavaScript external is still recommended. But for certain cases, especially very small pieces of code, inlining them into the site’s HTML makes sense.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/138884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21613/" ] }
138,929
We're currently planning a new API for an application and debating the various data formats we should use for interchange. There's a fairly intense discussion going on about the relative merits of CSV , JSON and XML . Basically, the crux of the argument is whether we should support CSV at all because of the lack of recursion ( i.e. having a document which has multiple authors and multiple references would require multiple API calls to obtain all the information ). In the experiences you may have had when working with information from Web APIs and things we can do to make the lives easier for the developers working with our API . Our decision: We've decided to provide XML and JSON due to the difficulty in recursion in CSV needing multiple calls for a single logical operation. JSON doesn't have a parser in Qt and Protocol Buffers doesn't seem to have a non-alpha PHP implementation so they are out for the moment too but will probably be supported eventually.
CSV is right out. JSON is a more compact object notation than XML, so if you're looking for high volumes it has the advantage. XML has wider market penetration (I love that phrase) and is supported by all programming languages and their core frameworks. JSON is getting there (if not already there). Personally, I like the brackets. I would bet more devs are comfortable with working with xml data than with json.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5355/" ] }
138,948
I need to get UTF-8 working in my Java webapp (servlets + JSP, no framework used) to support äöå etc. for regular Finnish text and Cyrillic alphabets like ЦжФ for special cases. My setup is the following: Development environment: Windows XP Production environment: Debian Database used: MySQL 5.x Users mainly use Firefox2 but also Opera 9.x, FF3, IE7 and Google Chrome are used to access the site. How to achieve this?
Answering myself as the FAQ of this site encourages it. This works for me: Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters. To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following: Configuring Tomcat's server.xml It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters: <Connector port="8080" maxHttpHeaderSize="8192" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" connectionTimeout="20000" disableUploadTimeout="true" compression="on" compressionMinSize="128" noCompressionUserAgents="gozilla, traviata" compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript" URIEncoding="UTF-8"/> The key part being URIEncoding="UTF-8" in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded.As a result, when the user writes the following to the address bar of the browser: https://localhost:8443/ID/Users?action=search&name=*ж* the character ж is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as %D0%B6 . POST request are not affected by this. CharsetFilter Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following: package fi.foo.filters;import javax.servlet.*;import java.io.IOException;public class CharsetFilter implements Filter { private String encoding; public void init(FilterConfig config) throws ServletException { encoding = config.getInitParameter("requestEncoding"); if (encoding == null) encoding = "UTF-8"; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws IOException, ServletException { // Respect the client-specified character encoding // (see HTTP specification section 3.4.1) if (null == request.getCharacterEncoding()) { request.setCharacterEncoding(encoding); } // Set the default response content type and encoding response.setContentType("text/html; charset=UTF-8"); response.setCharacterEncoding("UTF-8"); next.doFilter(request, response); } public void destroy() { }} This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8. The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application. This filter has to be added to the web.xml or the deployment descriptor of the webapp: <!--CharsetFilter start--> <filter> <filter-name>CharsetFilter</filter-name> <filter-class>fi.foo.filters.CharsetFilter</filter-class> <init-param> <param-name>requestEncoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharsetFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> The instructions for making this filter are found at the tomcat wiki ( http://wiki.apache.org/tomcat/Tomcat/UTF-8 ) JSP page encoding In your web.xml , add the following: <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <page-encoding>UTF-8</page-encoding> </jsp-property-group></jsp-config> Alternatively, all JSP-pages of the webapp would need to have the following at the top of them: <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%> If some kind of a layout with different JSP-fragments is used, then this is needed in all of them. HTML-meta tags JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding.Then it's time to tell the browser in which encoding the html page is: This is done with the following at the top of each xhtml page produced by the webapp: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi"> <head> <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' /> ... JDBC-connection When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in context.xml or wherever the JDBC connection is defiend as follows: <Resource name="jdbc/AppDB" auth="Container" type="javax.sql.DataSource" maxActive="20" maxIdle="10" maxWait="10000" username="foo" password="bar" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/ ID_development?useEncoding=true&amp;characterEncoding=UTF-8" /> MySQL database and tables The used database must use UTF-8 encoding. This is achieved by creating the database with the following: CREATE DATABASE `ID_development` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */; Then, all of the tables need to be in UTF-8 also: CREATE TABLE `Users` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(30) collate utf8_swedish_ci default NULL PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC; The key part being CHARSET=utf8 . MySQL server configuration MySQL serveri has to be configured also. Typically this is done in Windows by modifying my.ini -file and in Linux by configuring my.cnf -file.In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8. [client] port=3306 default-character-set=utf8 [mysql] default-character-set=utf8 Mysql procedures and functions These also need to have the character set defined. For example: DELIMITER $$ DROP FUNCTION IF EXISTS `pathToNode` $$ CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8 READS SQL DATA BEGIN DECLARE path VARCHAR(255) CHARACTER SET utf8; SET path = NULL; ... RETURN path; END $$ DELIMITER ; GET requests: latin1 and UTF-8 If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly: https://localhost:8443/ID/Users?action=search&name=Petteri https://localhost:8443/ID/Users?action=search&name=ж Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly. The Cyrillic character ж is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as %D0%B6 . If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as %D0%B6 . The end result is that all users with name "Petteri" are found and also all users with the name "ж" are found. But what about äåö? HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following https://localhost:8443/ID/Users?action=search&name=*Päivi* in to the encoded version https://localhost:8443/ID/Users?action=search&name=*P%E4ivi* In latin1 the character ä is encoded as %E4 . Even though the page/request/everything is defined to use UTF-8 . The UTF-8 encoded version of ä is %C3%A4 The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8. Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8 Stuff to read A very big thank you for the writers of the following for giving the answers for my problem: http://tagunov.tripod.com/i18n/i18n.html http://wiki.apache.org/tomcat/Tomcat/UTF-8 http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/ http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html http://jeppesn.dk/utf-8.html http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html http://www.utf8-chartable.de/ Important Note mysql supports the Basic Multilingual Plane using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of VARBINARY column type or use the utf8mb4 character set (which requires MySQL 5.5.3 or later). Just be aware that using the utf8 character set in MySQL won't work 100% of the time. Tomcat with Apache One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes: Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector. <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/> Goto your apache folder i.e. /etc/httpd/conf and add AddDefaultCharset utf-8 in httpd.conf file . Note: First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/138948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15114/" ] }
138,953
When I save a file with an .htm or .html extension, which one is correct and what is different?
Neither is wrong, it's a matter of preference. Traditionally, MS software uses htm by default, and *nix prefers html . As oded pointed out below, the .htm tradition was carried over from win 3.xx, where file extensions were limited to three characters.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/138953", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21067/" ] }
138,981
Is there any way to find out if a file is a directory? I have the file name in a variable. In Perl I can do this: if(-d $var) { print "it's a directory\n" }
You can do it like so: IF EXIST %VAR%\NUL ECHO It's a directory However, this only works for directories without spaces in their names. When you add quotes round the variable to handle the spaces it will stop working. To handle directories with spaces, convert the filename to short 8.3 format as follows: FOR %%i IN (%VAR%) DO IF EXIST %%~si\NUL ECHO It's a directory The %%~si converts %%i to an 8.3 filename. To see all the other tricks you can perform with FOR variables enter HELP FOR at a command prompt. (Note - the example given above is in the format to work in a batch file. To get it work on the command line, replace the %% with % in both places.)
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/138981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ] }
138,999
I just started learning JSP technology, and came across a wall. How do you output HTML from a method in <%! ... %> JSP declaration block? This doesn't work: <%! void someOutput() { out.println("Some Output");}%>...<% someOutput(); %> Server says there's no “out”. U: I do know how to rewrite code with this method returning a string, but is there a way to do this inside <%! void () { } %> ? Though it may be non-optimal, it's still interesting.
You can't use the 'out' variable (nor any of the other "predeclared" scriptlet variables) inside directives. The JSP page gets translated by your webserver into a Java servlet. Inside tomcats, for instance, everything inside scriptlets (which start "<%"), along with all the static HTML, gets translated into one giant Java method which writes your page, line by line, to a JspWriter instance called "out". This is why you can use the "out" parameter directly in scriptlets. Directives, on the other hand (which start with "<%!") get translated as separate Java methods. As an example, a very simple page (let's call it foo.jsp): <html> <head/> <body> <%! String someOutput() { return "Some output"; } %> <% someOutput(); %> </body></html> would end up looking something like this (with a lot of the detail ignored for clarity): public final class foo_jsp{ // This is where the request comes in public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // JspWriter instance is gotten from a factory // This is why you can use 'out' directly in scriptlets JspWriter out = ...; // Snip out.write("<html>"); out.write("<head/>"); out.write("<body>"); out.write(someOutput()); // i.e. write the results of the method call out.write("</body>"); out.write("</html>"); } // Directive gets translated as separate method - note // there is no 'out' variable declared in scope private String someOutput() { return "Some output"; }}
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/138999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1764/" ] }
139,000
I hope someone might be able to help me here. I've tried to simplify my example as best I can. I have an absolutely positioned DIV, which for this example I've made fill the browser window. This div has the overflow:auto attribute to provide scroll bars when the content is too big for the DIV to display. Within the DIV I have a table to present some data, and it's width is 100%. When the content becomes too large vertically, I expect the vertical scroll bar to appear and the table to shrink horizontally slightly to accommodate the scroll bar. However in IE7 what happens is the horizontal scroll bar also appears, despite there still being enough space horizontally for all the content in the div. This is IE specific - firefox works perfectly. Full source below. Any help greatly appreciated. Tony <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Table sizing bug?</title> <style> #maxsize { position: absolute; left: 5px; right: 5px; top: 5px; bottom: 5px; border: 5px solid silver; overflow: auto; } </style></head><body> <form id="form1" runat="server"> <div id="maxsize"> <p>This will be fine until such time as the vertical size forces a vertical scroll bar. At this point I'd expect the table to re-size to now take into account of the new vertical scroll bar. Instead, IE7 keeps the table the full size and introduces a horizontal scroll bar. </p> <table width="100%" cellspacing="0" cellpadding="0" border="1"> <tbody> <tr> <td>A</td> <td>B</td> <td>C</td> <td>D</td> <td>E</td> <td>F</td> <td>G</td> <td>H</td> <td>I</td> <td>J</td> <td>K</td> <td>L</td> <td>M</td> <td>N</td> <td>O</td> <td>P</td> <td>Q</td> <td>R</td> </tr> </tbody> </table> <p>Resize the browser window vertically so this content doesn't fit any more</p> <p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p> <p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p><p>Hello</p> </div> </form></body></html> added 03/16/10... thought it might be interesting to point out that GWT's source code points to this question in a comment... http://www.google.com/codesearch/p?hl=en#MTQ26449crI/com/google/gwt/user/client/ui/ScrollPanel.java&q=%22hack%20to%20account%20for%20the%22%20scrollpanel&sa=N&cd=1&ct=rc&l=48
I had a problem with excessive horizonal bar in IE7. I've used D Carter's solution slighty changed <div style="zoom: 1; overflow: auto;"> <div id="myDiv" style="zoom: 1;"> <table style="width: 100%"... ... </table> </div></div> To work in IE browser lesser than 7 you need add: <!--[if lt IE 7]><style> #myDiv { overflow: auto; } </style><![endif]-->
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
139,010
I need to find out the file/directory name that a .lnk is pointing to using c#. What is the simplest way to do this? Thanks.
I wrote this for video browser, it works really well #region Signitures imported from http://pinvoke.net[DllImport("shfolder.dll", CharSet = CharSet.Auto)]internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);[Flags()]enum SLGP_FLAGS{ /// <summary>Retrieves the standard short (8.3 format) file name</summary> SLGP_SHORTPATH = 0x1, /// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary> SLGP_UNCPRIORITY = 0x2, /// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary> SLGP_RAWPATH = 0x4}[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]struct WIN32_FIND_DATAW{ public uint dwFileAttributes; public long ftCreationTime; public long ftLastAccessTime; public long ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; public uint dwReserved0; public uint dwReserved1; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName;}[Flags()]enum SLR_FLAGS{ /// <summary> /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set, /// the high-order word of fFlags can be set to a time-out value that specifies the /// maximum amount of time to be spent resolving the link. The function returns if the /// link cannot be resolved within the time-out duration. If the high-order word is set /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out /// duration, in milliseconds. /// </summary> SLR_NO_UI = 0x1, /// <summary>Obsolete and no longer used</summary> SLR_ANY_MATCH = 0x2, /// <summary>If the link object has changed, update its path and list of identifiers. /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine /// whether or not the link object has changed.</summary> SLR_UPDATE = 0x4, /// <summary>Do not update the link information</summary> SLR_NOUPDATE = 0x8, /// <summary>Do not execute the search heuristics</summary> SLR_NOSEARCH = 0x10, /// <summary>Do not use distributed link tracking</summary> SLR_NOTRACK = 0x20, /// <summary>Disable distributed link tracking. By default, distributed link tracking tracks /// removable media across multiple devices based on the volume name. It also uses the /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary> SLR_NOLINKINFO = 0x40, /// <summary>Call the Microsoft Windows Installer</summary> SLR_INVOKE_MSI = 0x80}/// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>[ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]interface IShellLinkW{ /// <summary>Retrieves the path and file name of a Shell link object</summary> void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags); /// <summary>Retrieves the list of item identifiers for a Shell link object</summary> void GetIDList(out IntPtr ppidl); /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary> void SetIDList(IntPtr pidl); /// <summary>Retrieves the description string for a Shell link object</summary> void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName); /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary> void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); /// <summary>Retrieves the name of the working directory for a Shell link object</summary> void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath); /// <summary>Sets the name of the working directory for a Shell link object</summary> void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary> void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath); /// <summary>Sets the command-line arguments for a Shell link object</summary> void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); /// <summary>Retrieves the hot key for a Shell link object</summary> void GetHotkey(out short pwHotkey); /// <summary>Sets a hot key for a Shell link object</summary> void SetHotkey(short wHotkey); /// <summary>Retrieves the show command for a Shell link object</summary> void GetShowCmd(out int piShowCmd); /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary> void SetShowCmd(int iShowCmd); /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary> void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon); /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary> void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon); /// <summary>Sets the relative path to the Shell link object</summary> void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved); /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary> void Resolve(IntPtr hwnd, SLR_FLAGS fFlags); /// <summary>Sets the path and file name of a Shell link object</summary> void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);}[ComImport, Guid("0000010c-0000-0000-c000-000000000046"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]public interface IPersist{ [PreserveSig] void GetClassID(out Guid pClassID);}[ComImport, Guid("0000010b-0000-0000-C000-000000000046"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]public interface IPersistFile : IPersist{ new void GetClassID(out Guid pClassID); [PreserveSig] int IsDirty(); [PreserveSig] void Load([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, uint dwMode); [PreserveSig] void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [In, MarshalAs(UnmanagedType.Bool)] bool fRemember); [PreserveSig] void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName); [PreserveSig] void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName);}const uint STGM_READ = 0;const int MAX_PATH = 260;// CLSID_ShellLink from ShlGuid.h [ ComImport(), Guid("00021401-0000-0000-C000-000000000046")]public class ShellLink{}#endregion public static string ResolveShortcut(string filename){ ShellLink link = new ShellLink(); ((IPersistFile)link).Load(filename, STGM_READ); // TODO: if I can get hold of the hwnd call resolve first. This handles moved and renamed files. // ((IShellLinkW)link).Resolve(hwnd, 0) StringBuilder sb = new StringBuilder(MAX_PATH); WIN32_FIND_DATAW data = new WIN32_FIND_DATAW(); ((IShellLinkW)link).GetPath(sb, sb.Capacity, out data, 0); return sb.ToString(); }
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ] }
139,025
I'd like my application to have a full-screen mode. What is the easiest way to do this, do I need a third party library for this or is there something in the JDK that already offers this?
Try the Full-Screen Exclusive Mode API . It was introduced in the JDK in release 1.4. Some of the features include: Full-Screen Exclusive Mode - allows you to suspend the windowing system so that drawing can be done directly to the screen. Display Mode - composed of the size (width and height of the monitor, in pixels), bit depth (number of bits per pixel), and refresh rate (how frequently the monitor updates itself). Passive vs. Active Rendering - painting while on the main event loop using the paint method is passive, whereas rendering in your own thread is active. Double Buffering and Page Flipping - Smoother drawing means better perceived performance and a much better user experience. BufferStrategy and BufferCapabilities - classes that allow you to draw to surfaces and components without having to know the number of buffers used or the technique used to display them, and help you determine the capabilities of your graphics device. There are several full-screen exclusive mode examples in the linked tutorial.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ] }
139,053
I have written an assembly I don't want other people to be able to use. My assembly is signed with a strong name key file, but how do I secure the code so that only my other assemblies signed with the same key can call the members in this assembly?
There are a few options, none very effective as they merely will make things a tiny bit difficult, but would not prevent a committed user to work around any restriction: On every one of your entry points, you can call Assembly.GetCallingAssembly() and compare the result with a list of assemblies that are allowed to call into your library, and throw an exception otherwise. You could use a tool like ilmerge to merge your assemblies into your main application, and flag all of the internals as private. Combine with an obfuscator to make the results slightly better protected. But securing an assembly is as solid as securing a computer where the attacker has physical access to it: there is very little that you can do to protect the contents once physical access is granted.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3139/" ] }
139,076
I have a Java String that contains XML, with no line feeds or indentations. I would like to turn it into a String with nicely formatted XML. How do I do this? String unformattedXml = "<tag><nested>hello</nested></tag>";String formattedXml = new [UnknownClass]().format(unformattedXml); Note: My input is a String . My output is a String . (Basic) mock result: <?xml version="1.0" encoding="UTF-8"?><root> <tag> <nested>hello</nested> </tag></root>
Transformer transformer = TransformerFactory.newInstance().newTransformer();transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");// initialize StreamResult with File object to save to fileStreamResult result = new StreamResult(new StringWriter());DOMSource source = new DOMSource(doc);transformer.transform(source, result);String xmlString = result.getWriter().toString();System.out.println(xmlString); Note: Results may vary depending on the Java version. Search for workarounds specific to your platform.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/139076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2959/" ] }
139,157
I am building a menu in HTML/CSS/JS and I need a way to prevent the text in the menu from being highlighted when double-clicked on. I need a way to pass the id's of several divs into a function and have highlighting turned off within them. So when the user accidentally (or on purpose) double clicks on the menu, the menu shows its sub-elements but its text does not highlight. There are a number of scripts out there floating around on the web, but many seem outdated. What's the best way?
In (Mozilla, Firefox, Camino, Safari, Google Chrome) you can use this: div.noSelect { -moz-user-select: none; /* mozilla browsers */ -khtml-user-select: none; /* webkit browsers */} For IE there is no CSS option, but you can capture the ondragstart event, and return false; Update Browser support for this property has expanded since 2008. div.noSelect { -webkit-user-select: none; /* Safari */ -ms-user-select: none; /* IE 10 and IE 11 */ user-select: none; /* Standard syntax */} https://www.w3schools.com/csSref/css3_pr_user-select.php
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/315650/" ] }
139,180
I have a Python module installed on my system and I'd like to be able to see what functions/classes/methods are available in it. I want to call the help function on each one. In Ruby I can do something like ClassName.methods to get a list of all the methods available on that class. Is there something similar in Python? e.g. something like: from somemodule import fooprint(foo.methods) # or whatever is the correct method to call
You can use dir(module) to see all available methods/attributes. Also check out PyDocs.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/139180", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6527/" ] }
139,199
I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I'm wondering what is wrong with taking user input and escaping any single quotes and surrounding the whole string with single quotes. Here's the code: sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'" Any single-quote the user enters is replaced with double single-quotes, which eliminates the users ability to end the string, so anything else they may type, such as semicolons, percent signs, etc., will all be part of the string and not actually executed as part of the command. We are using Microsoft SQL Server 2000, for which I believe the single-quote is the only string delimiter and the only way to escape the string delimiter, so there is no way to execute anything the user types in. I don't see any way to launch an SQL injection attack against this, but I realize that if this were as bulletproof as it seems to me someone else would have thought of it already and it would be common practice. What's wrong with this code? Is there a way to get an SQL injection attack past this sanitization technique? Sample user input that exploits this technique would be very helpful. UPDATE: I still don't know of any way to effectively launch a SQL injection attack against this code. A few people suggested that a backslash would escape one single-quote and leave the other to end the string so that the rest of the string would be executed as part of the SQL command, and I realize that this method would work to inject SQL into a MySQL database, but in SQL Server 2000 the only way (that I've been able to find) to escape a single-quote is with another single-quote; backslashes won't do it. And unless there is a way to stop the escaping of the single-quote, none of the rest of the user input will be executed because it will all be taken as one contiguous string. I understand that there are better ways to sanitize input, but I'm really more interested in learning why the method I provided above won't work. If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it.
First of all, it's just bad practice. Input validation is always necessary, but it's also always iffy. Worse yet, blacklist validation is always problematic, it's much better to explicitly and strictly define what values/formats you accept. Admittedly, this is not always possible - but to some extent it must always be done. Some research papers on the subject: http://www.imperva.com/docs/WP_SQL_Injection_Protection_LK.pdf http://www.it-docs.net/ddata/4954.pdf (Disclosure, this last one was mine ;) ) https://www.owasp.org/images/d/d4/OWASP_IL_2007_SQL_Smuggling.pdf (based on the previous paper, which is no longer available) Point is, any blacklist you do (and too-permissive whitelists) can be bypassed. The last link to my paper shows situations where even quote escaping can be bypassed. Even if these situations do not apply to you, it's still a bad idea. Moreover, unless your app is trivially small, you're going to have to deal with maintenance, and maybe a certain amount of governance: how do you ensure that its done right, everywhere all the time? The proper way to do it: Whitelist validation: type, length, format or accepted values If you want to blacklist, go right ahead. Quote escaping is good, but within context of the other mitigations. Use Command and Parameter objects, to preparse and validate Call parameterized queries only. Better yet, use Stored Procedures exclusively. Avoid using dynamic SQL, and dont use string concatenation to build queries. If using SPs, you can also limit permissions in the database to executing the needed SPs only, and not access tables directly. you can also easily verify that the entire codebase only accesses the DB through SPs...
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/139199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22392/" ] }
139,207
So many different controls to choose from! What are best practices for determining which control to use for displaying data in ASP.NET?
It's really about what you trying to achieve Gridview - Limited in design, works like an html table. More in built functionality like edit/update, page, sort. Lots of overhead. DataGrid - Old version of the Gridview. A gridview is a super datagrid. Datalist - more customisable version of the Gridview. Also has some overhead. More manual work as you have to design it yourself. ListView - the new Datalist :). Almost a hybrid of the datalist and gridview where you can use paging and build in Gridview like functionality, but have the freedom of design. One of the new controls in this family Repeater - Very light weight. No built in functionality like Headers, Footers. Has the least overhead.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/139207", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ] }
139,209
Or do you populate your form controls manually by a method? Is either considered a best practice?
It's really about what you trying to achieve Gridview - Limited in design, works like an html table. More in built functionality like edit/update, page, sort. Lots of overhead. DataGrid - Old version of the Gridview. A gridview is a super datagrid. Datalist - more customisable version of the Gridview. Also has some overhead. More manual work as you have to design it yourself. ListView - the new Datalist :). Almost a hybrid of the datalist and gridview where you can use paging and build in Gridview like functionality, but have the freedom of design. One of the new controls in this family Repeater - Very light weight. No built in functionality like Headers, Footers. Has the least overhead.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/139209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16419/" ] }
139,228
One of our developers is continually writing code and putting it into version control without testing it. The quality of our code is suffering as a result. Besides getting rid of the developer, how can I solve this problem? EDIT I have talked to him about it number of times and even given him written warning
If you systematically perform code reviews before allowing a developer to commit the code, well, your problem is mostly solved. But this doesn't seem to be your case, so this is what I recommend: Talk to the developer. Discuss the consequences for others in the team. Most developers want to be recognized by their peer, so this might be enough. Also point out it is much easier to fix bugs in the code that's fresh in your mind than weeks-old code. This part makes sense if you have some form of code owneship in place. If this doesn't work after some time, try to put in place a policy that will make commiting buggy code unpleasant for the author. One popular way is to make the person who broke the build responsible for the chores of creating the next one. If your build process is fully automated, look for another menial task to take care of instead. This approach has the added benefit of not pinpointing anyone in particular, making it more acceptable for everybody. Use disciplinary measures . Depending on the size of your team and of your company, those can take many forms. Fire the developer. There is a cost associated with keeping bad apples. When you get this far, the developer doesn't care about his fellow developers, and you've got a people problem on your hands already. If the work environment becomes poisoned, you might lose far more - productivity-wise and people-wise - than this single bad developer.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17560/" ] }
139,260
I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this: MemoryStream stream = new MemoryStream();XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1"));xmlTextWriter.Formatting = Formatting.Indented;xmlTextWriter.WriteStartDocument(); //Start doc Then I add my Norwegian text like this: xmlTextWriter.WriteCData(myNorwegianText); Then I write the file to disk like this: FileStream myFile = new FileStream(myPath, FileMode.Create);StreamWriter sw = new StreamWriter(myFile);stream.Position = 0;StreamReader sr = new StreamReader(stream);string content = sr.ReadToEnd();sw.Write(content);sw.Flush();myFile.Flush();myFile.Close(); Now the problem is that in the file on this, all the Norwegian characters look funny. I'm probably doing the above in some stupid way. Any suggestions on how to fix it?
Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work. If you still want to do the double write, for whatever reason, do one of two things. Either Make sure that the StreamReader and StreamWriter objects you use all use the same encoding as the one you used with the XmlWriter (not just the StreamWriter, like someone else suggested), or Don't use StreamReader/StreamWriter. Instead just copy the stream at the byte level using a simple byte[] and Stream.Read/Write. This is going to be, btw, a lot more efficient anyway.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5795/" ] }
139,261
For testing purposes I have to generate a file of a certain size (to test an upload limit). What is a command to create a file of a certain size on Linux?
For small files: dd if=/dev/zero of=upload_test bs=file_size count=1 Where file_size is the size of your test file in bytes. For big files: dd if=/dev/zero of=upload_test bs=1M count=size_in_megabytes
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/139261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4120/" ] }
139,288
what is an efficient way to get a certain time for the next day in Java?Let's say I want the long for tomorrow 03:30:00.Setting Calendar fields and Date formatting are obvious.Better or smarter ideas, thanks for sharing them! Okami
I take the brute force approach // make it nowCalendar dateCal = Calendar.getInstance();// make it tomorrowdateCal.add(Calendar.DAY_OF_YEAR, 1);// Now set it to the time you wantdateCal.set(Calendar.HOUR_OF_DAY, hours);dateCal.set(Calendar.MINUTE, minutes);dateCal.set(Calendar.SECOND, seconds);dateCal.set(Calendar.MILLISECOND, 0);return dateCal.getTime();
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11450/" ] }
139,325
How to set all the values in a std::map to the same value, without using a loop iterating over each value?
Using a loop is by far the simplest method. In fact, it’s a one-liner: [C++17] for (auto& [_, v] : mymap) v = value; Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use std::fill . To use them anyway (pre-C++20), we need to write adapters — in the case of std::fill , an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do not advise using it as-is. Use a library (such as Boost.Iterator ) for a more general, production-strength implementation. template <typename M>struct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> { using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>; using underlying = typename M::iterator; using typename base_type::value_type; using typename base_type::reference; value_iter(underlying i) : i(i) {} value_iter& operator++() { ++i; return *this; } value_iter operator++(int) { auto copy = *this; i++; return copy; } reference operator*() { return i->second; } bool operator ==(value_iter other) const { return i == other.i; } bool operator !=(value_iter other) const { return i != other.i; }private: underlying i;};template <typename M>auto value_begin(M& map) { return value_iter<M>(map.begin()); }template <typename M>auto value_end(M& map) { return value_iter<M>(map.end()); } With this, we can use std::fill : std::fill(value_begin(mymap), value_end(mymap), value);
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6841/" ] }
139,387
OK, I'm not looking for anti-patterns - I'm looking for things that aren't really patterns, or perhaps patterns that have been abused. My personal least favourite is the "Helper" pattern. E.g. I need to create a SQL query, so call SQLQueryHelper. This needs to process some strings, so it in turn calls StringHelper. Etc., etc. See - this isn't really a design pattern at all... [edit]Don't you people who vote this down think you should add a constructive remark?
Singleton. It's a global variable in disguise and difficult to mock/stub for unit testing. Service Locator better, Dependency injection / Inversion of Control better still. The majority of references on the wikipedia article are about why it is evil.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17641/" ] }
139,389
Is it a good idea for me to use Qt Jambi in Java as a toolkit? I see that Qt Jambi is hard to learn, and Swing is easier than Qt Jambi, but I think that Qt Jambi is more powerful.
Two years ago, I started a Java Desktop Application and used Swing as a GUI framweork. Up to that point, I had experience with C++/MFC ( shudder ) and C++/Qt ( very nice ). After trying to get along with Swing for a while (including reading lots of tutorials and even a book) I came to the following conclusion: Swing is much more difficult and clumsy than Qt for three reasons: A lot of simple stuff requires more code than it should. Some things that Qt brings for free are almost impossible to achieve in a reasonable amount of time. Swing doesn't bring a WYSIWYG GUI Editor and I could not find a free one that comes close to Qt's Designer. I then threw away the Swing GUI, switched to Qt Jambi and was really impressed by it. One weekend later I had a nice Qt GUI and lived happily ever after.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22634/" ] }
139,427
Should I stick with Sun's Java code conventions for PHP code?
For PHP, i'd suggest to follow Zends suggestions As you might know, Zend is the most widely used framework!
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4235/" ] }
139,474
I'd like to capture the output of var_dump to a string. The PHP documentation says; As with anything that outputs its result directly to the browser, the output-control functions can be used to capture the output of this function, and save it in a string (for example). What would be an example of how that might work? print_r() isn't a valid possibility, because it's not going to give me the information that I need.
Use output buffering: <?phpob_start();var_dump($someVar);$result = ob_get_clean();?>
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/139474", "https://Stackoverflow.com", "https://Stackoverflow.com/users/305/" ] }
139,479
How universally is the C99 standard supported in today's compilers? I understand that not even GCC fully supports it. Is this right? Which features of C99 are supported more than others, i.e. which can I use to be quite sure that most compilers will understand me?
If you want to write portable C code, then I'd suggest you to write in C89 (old ANSI C standard). This standard is supported by most compilers. The Intel C Compiler has very good C99 support and it produces fast binaries. (Thanks 0x69 !) MSVC supports some new features and Microsoft plan to broaden support in future versions. GCC supports some new things of C99. They created a table about the status of C99 features . Probably the most usable feature of C99 is the variable length array, and GCC supports it now. Clang (LLVM's C fronted) supports most features except floating-point pragmas. Wikipedia seems to have a nice summary of C99 support of the compilers.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ] }
139,534
I've just solved another *I-though-I-was-using-this-version-of-a-library-but-apparently-my-app-server-has-already-loaded-an-older-version-of-this-library-*issue (sigh). Does anybody know a good way to verify (or monitor) whether your application has access to all the appropriate jar-files, or loaded class-versions? Thanks in advance! [P.S. A very good reason to start using the OSGi module architecture in my view!] Update : This article helped as well! It gave me insight which classes JBoss' classloader loaded by writing it to a log file.
If you happen to be using JBoss, there is an MBean (the class loader repository iirc) where you can ask for all classloaders that have loaded a certain class. If all else fails, there's always java -verbose:class which will print the location of the jar for every class file that is being loaded.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9707/" ] }
139,592
I've got a generic dictionary Dictionary<string, T> that I would like to essentially make a Clone() of ..any suggestions.
Okay, the .NET 2.0 answers: If you don't need to clone the values, you can use the constructor overload to Dictionary which takes an existing IDictionary. (You can specify the comparer as the existing dictionary's comparer, too.) If you do need to clone the values, you can use something like this: public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue> (Dictionary<TKey, TValue> original) where TValue : ICloneable{ Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count, original.Comparer); foreach (KeyValuePair<TKey, TValue> entry in original) { ret.Add(entry.Key, (TValue) entry.Value.Clone()); } return ret;} That relies on TValue.Clone() being a suitably deep clone as well, of course.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/139592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4398/" ] }
139,593
I have the following code: info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));info.CreateNoWindow = true;info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;info.RedirectStandardOutput = true;info.UseShellExecute = false;System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);p.WaitForExit();Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at WaitForExit . Note also this code does NOT hang for smaller outputs (like 3KB). Is it possible that the internal StandardOutput in ProcessStartInfo can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?
The problem is that if you redirect StandardOutput and/or StandardError the internal buffer can become full. Whatever order you use, there can be a problem: If you wait for the process to exit before reading StandardOutput the process can block trying to write to it, so the process never ends. If you read from StandardOutput using ReadToEnd then your process can block if the process never closes StandardOutput (for example if it never terminates, or if it is blocked writing to StandardError ). The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both StandardOutput and StandardError you can do this: EDIT: See answers below for how avoid an ObjectDisposedException if the timeout occurs. using (Process process = new Process()){ process.StartInfo.FileName = filename; process.StartInfo.Arguments = arguments; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; StringBuilder output = new StringBuilder(); StringBuilder error = new StringBuilder(); using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false)) using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false)) { process.OutputDataReceived += (sender, e) => { if (e.Data == null) { outputWaitHandle.Set(); } else { output.AppendLine(e.Data); } }; process.ErrorDataReceived += (sender, e) => { if (e.Data == null) { errorWaitHandle.Set(); } else { error.AppendLine(e.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); if (process.WaitForExit(timeout) && outputWaitHandle.WaitOne(timeout) && errorWaitHandle.WaitOne(timeout)) { // Process completed. Check process.ExitCode here. } else { // Timed out. } }}
{ "score": 10, "source": [ "https://Stackoverflow.com/questions/139593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ] }
139,607
I've seen both done in some code I'm maintaining, but don't know the difference. Is there one? let me add that myCustomer is an instance of Customer
The result of both are exactly the same in your case. It will be your custom type that derives from System.Type . The only real difference here is that when you want to obtain the type from an instance of your class, you use GetType . If you don't have an instance, but you know the type name (and just need the actual System.Type to inspect or compare to), you would use typeof . Important difference EDIT: Let me add that the call to GetType gets resolved at runtime, while typeof is resolved at compile time.
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/139607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18931/" ] }
139,623
How do I cause the page to make the user jump to a new web page after X seconds. If possible I'd like to use HTML but a niggly feeling tells me it'll have to be Javascript. So far I have the following but it has no time delay <body onload="document.location='newPage.html'">
A meta refresh is ugly but will work. The following will go to the new url after 5 seconds: <meta http-equiv="refresh" content="5;url=http://example.com/"/> http://en.wikipedia.org/wiki/Meta_refresh
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ] }
139,630
What's the difference between TRUNCATE and DELETE in SQL? If your answer is platform specific, please indicate that.
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below. General Overview If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE. Various system-specific issues have to be considered, as detailed below. Statement type Delete is DML, Truncate is DDL ( What is DDL and DML? ) Commit and Rollback Variable by vendor SQL*Server Truncate can be rolled back. PostgreSQL Truncate can be rolled back. Oracle Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway. However, see Flashback below. Space reclamation Delete does not recover space, Truncate recovers space Oracle If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset. Row scope Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows. Oracle When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible. Object types Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific) Data Object Identity Oracle Delete does not affect the data object id, but truncate assigns a new data object id unless there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation. Flashback (Oracle) Flashback works across deletes, but a truncate prevents flashback to states prior to the operation. However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition Use of FLASHBACK in Oracle http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638 Privileges Variable Oracle Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant. Redo/Undo Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each. Indexes Oracle A truncate operation renders unusable indexes usable again. Delete does not. Foreign Keys A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys. Table Locking Oracle Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table. Triggers DML triggers do not fire on a truncate. Oracle DDL triggers are available. Remote Execution Oracle Truncate cannot be issued over a database link. Identity Columns SQL*Server Truncate resets the sequence for IDENTITY column types, delete does not. Result set In most implementations, a DELETE statement can return to the client the rows that were deleted. e.g. in an Oracle PL/SQL subprogram you could: DELETE FROM employees_tempWHERE employee_id = 299 RETURNING first_name, last_nameINTO emp_first_name, emp_last_name;
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/139630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6742/" ] }
139,639
I am working with Reporting Services and Sharepoint, I have an application that leverages reporting services however a client would like our application integrated into sharepoint. Currently we are tightly coupled to the ReportService.asmx webservice which exposes various methods for performing operations. Reporting Services has something called "Sharepoint Integration mode" when enabled the report server works differently and Sharepoint is used to manage the reports. Sharepoint adds a new web service called ReportService2006.asmx which is almost exactly the same. Now our application uses a web reference to the ReportService and uses various objects exposed by the service. ReportService2006 has exactly the same objects but they are obviously in a different namespace e.g I have 2 web references - 1 to each service so there is an object MyApplication.ReportService.CatalogItem and another MyApplication.ReportService2006.CatalogItem. I've tried to use dependency injection to absract the Service out of our application coupled with a factory pattern to determine which implementation of my interface to instantiate. Heres my interface. I've simplified it to include only the calls I need for this application. using System;using NetworkUserEncrypt.ReportService;namespace MyApplication.Service{ public interface IReportingService { CatalogItem CreateDataSource(string DataSource, string Parent, bool Overwrite, DataSourceDefinition Definition, Property[] Properties); void DeleteItem(string Item); DataSourceDefinition GetDataSourceContents(string DataSource); byte[] GetReportDefinition(string Report); CatalogItem[] ListChildren(string Item); }} So I have 2 implementations of this each instantiating a different web service e.g: namespace MyApp.Service.Implementation{ class ReportingServiceImpl : IReportingService { ReportingService _service = null; public ReportingServiceImpl() { ReportingService _service = new ReportingService(); } /* SNIP */ } } and namespace MyApp.Service.Implementation{ class ReportingService2006Impl : IReportingService { ReportingService2006 _service = null; public ReportingService2006Impl() { ReportingService2006 _service = new ReportingService2006(); } /* SNIP */ } } So the plan is I can inject these into my ServiceWrapper at run time. However - if you'll notice the interface is tied to the ReportService and some of the methods return objects that are from the web reference e.g. CatalogItem. Thus my project won't build because my implementation for ReportService2006 is referencing the CatalogItem from a different namespace. Any ideas? Am I going totally the wrong direction with this?
Here's a list of differences. I've highlighted Oracle-specific features, and hopefully the community can add in other vendors' specific difference also. Differences that are common to most vendors can go directly below the headings, with differences highlighted below. General Overview If you want to quickly delete all of the rows from a table, and you're really sure that you want to do it, and you do not have foreign keys against the tables, then a TRUNCATE is probably going to be faster than a DELETE. Various system-specific issues have to be considered, as detailed below. Statement type Delete is DML, Truncate is DDL ( What is DDL and DML? ) Commit and Rollback Variable by vendor SQL*Server Truncate can be rolled back. PostgreSQL Truncate can be rolled back. Oracle Because a TRUNCATE is DDL it involves two commits, one before and one after the statement execution. Truncate can therefore not be rolled back, and a failure in the truncate process will have issued a commit anyway. However, see Flashback below. Space reclamation Delete does not recover space, Truncate recovers space Oracle If you use the REUSE STORAGE clause then the data segments are not de-allocated, which can be marginally more efficient if the table is to be reloaded with data. The high water mark is reset. Row scope Delete can be used to remove all rows or only a subset of rows. Truncate removes all rows. Oracle When a table is partitioned, the individual partitions can be truncated in isolation, thus a partial removal of all the table's data is possible. Object types Delete can be applied to tables and tables inside a cluster. Truncate applies only to tables or the entire cluster. (May be Oracle specific) Data Object Identity Oracle Delete does not affect the data object id, but truncate assigns a new data object id unless there has never been an insert against the table since its creation Even a single insert that is rolled back will cause a new data object id to be assigned upon truncation. Flashback (Oracle) Flashback works across deletes, but a truncate prevents flashback to states prior to the operation. However, from 11gR2 the FLASHBACK ARCHIVE feature allows this, except in Express Edition Use of FLASHBACK in Oracle http://docs.oracle.com/cd/E11882_01/appdev.112/e41502/adfns_flashback.htm#ADFNS638 Privileges Variable Oracle Delete can be granted on a table to another user or role, but truncate cannot be without using a DROP ANY TABLE grant. Redo/Undo Delete generates a small amount of redo and a large amount of undo. Truncate generates a negligible amount of each. Indexes Oracle A truncate operation renders unusable indexes usable again. Delete does not. Foreign Keys A truncate cannot be applied when an enabled foreign key references the table. Treatment with delete depends on the configuration of the foreign keys. Table Locking Oracle Truncate requires an exclusive table lock, delete requires a shared table lock. Hence disabling table locks is a way of preventing truncate operations on a table. Triggers DML triggers do not fire on a truncate. Oracle DDL triggers are available. Remote Execution Oracle Truncate cannot be issued over a database link. Identity Columns SQL*Server Truncate resets the sequence for IDENTITY column types, delete does not. Result set In most implementations, a DELETE statement can return to the client the rows that were deleted. e.g. in an Oracle PL/SQL subprogram you could: DELETE FROM employees_tempWHERE employee_id = 299 RETURNING first_name, last_nameINTO emp_first_name, emp_last_name;
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/139639", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4950/" ] }
139,655
I have a need to convert Pixels to Points in C#. I've seen some complicated explanations about the topic, but can't seem to locate a simple formula. Let's assume a standard 96dpi, how do I calulate this conversion?
There are 72 points per inch ; if it is sufficient to assume 96 pixels per inch, the formula is rather simple: points = pixels * 72 / 96 There is a way to get the configured pixels per inch of your display in Windows using GetDeviceCaps . Microsoft has a guide called "Developing DPI-Aware Applications" , look for the section "Creating DPI-Aware Fonts". The W3C has defined the pixel measurement px as exactly 1/96th of 1in regardless of the actual resolution of your display, so the above formula should be good for all web work.
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/139655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13603/" ] }
139,670
In SQL SERVER Is it possible to store data with carriage return in a table and then retrieve it back again with carriage return. Eg: insert into table values ('test1 test2test3test4'); When I retrieve it, I get the message in a line test1 test2 test3 test4 The carriage return is treated as a single character. Is there way to get the carriage returns or its just the way its going to be stored? Thanks for the help guys!!! Edit: I should have explained this before. I get the data from the web development (asp .net) and I just insert it into the table. I might not be doing any data manipulation.. just insert. I return the data to the app development (C++) and may be some data or report viewer. I don't want to manipulate on the data.
You can store Carriage return in the database. The problem here is that you are using SQL Server Management Studio to display the results of your query. You probably have it configured to show the results in a grid. Change the configuration of SSMS to show results to text and you will see the carriage returns. Right click in the query window -> Results To -> Results To Text Run your query again.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21968/" ] }
139,723
I've been using various javascript frameworks including mootools, jquery, prototype and scriptaculous and have found them all good, but difficult to extend to more complex ideas. If I am going to knuckle down and learn one, which is the simplest to extend and use whilst staying powerful enough to use in a variety of directions?
I propose jQuery. I'll give you some of the major arguments from the presentation that my team put on yesterday for senior management to convince them of that. Reasons: Community acceptance. Look at this graph . It shows searches for "prototype", "yui" and "scriptaculous" growing from 2004 to 2008. Then out of nowhere in 2006 searches fro "jquery" shoot up to double the number of the other libraries. The community is actually converging on a single leading product, and it's jQuery. jQuery is very very succinct and readable. I conducted an experiment in which I took existing code (selected at random) written in YUI, and tried re-writing it in jQuery. It was 1/4 as long in jQuery. That makes it 4 times as easy to write, and 4 times as easy to maintain. jQuery integrates well with the rest of the web world. The use of CSS syntax as the key for selecting items is a brilliant trick which helps to meld together the highly diseparate worlds of HTML, CSS and JavaScript. Documentation: jQuery has excellent documentation, with clear specifications and working examples of every method. It has excellent books (I recommend "jQuery in Action".) The only competitor which matches it is YUI. Active user community: the Google group which is the main community discussion forum for Prototype has nearly 1000 members. The Google group for jQuery has 10 times as many members. And my personal experience is that the community tends to be helpful. Easy learning curve. jQuery is easy to learn, even for people with experience as a designer, but no experience in coding. Performance. Check out this , which is published by mootools. It compares the speed of different frameworks. jQuery is not always the VERY fastest, but it is quite good on every test. Plays well with others: jQuery's noConflict mode and the core library's small size help it to work well in environments that are already using other libraries. Designed to make JavaScript usable. Looping is a pain in JavaScript; jQuery works with set objects you almost never need to write the loop. JavaScript's greatest strength is that functions are first-class objects; jQuery makes extensive use of this feature. Plug-ins. jQuery is designed to make it easy to write plugins. And there is an enormous community of people out there writing plugins. Anything you want is probably out there. Check out things like this or this for visual examples. I hope you find this convincing!
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ] }
139,759
Is there any way to list all the files that have changed between two tags in CVS? Every time we do a release we apply a tag to all the files in that release. I want to find all the files that changed between releases. It would also work if I could find all files that had changed between two dates.
I suppose this command would help: cvs diff -N -c -r RELEASE_1_0 -r RELEASE_1_1 > diffs where RELEASE_1_0 and RELEASE_1_1 are the names of your tags. You can find a little more information on cvs diff command here plus it should be fairly simple to create a script to make report more suitbable for your needs, ex: number of files changed, created deleted etc. As far as I know the most common cvs GUI tools (wincvs and tortoise) do not provide something like this out of the box. Hope it helps ;)
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3464/" ] }
139,794
Let's say we have index.php and it is stored in /home/user/public/www and index.php calls the class Foo->bar() from the file inc/app/Foo.class.php . I'd like the bar function in the Foo class to get a hold of the path /home/user/public/www in this instance — I don't want to use a global variable, pass a variable, etc.
Wouldn't this get you the directory of the running script more easily? $dir=dirname($_SERVER["SCRIPT_FILENAME"])
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6752/" ] }
139,809
I have a Console application hosting a WCF service. I would like to be able to fire an event from a method in the WCF service and handle the event in the hosting process of the WCF service. Is this possible? How would I do this? Could I derive a custom class from ServiceHost?
You don't need to inherit from ServiceHost . There are other approaches to your problem. You can pass an instance of the service class, instead of a type to ServiceHost . Thus, you can create the instance before you start the ServiceHost , and add your own event handlers to any events it exposes. Here's some sample code: MyService svc = new MyService();svc.SomeEvent += new MyEventDelegate(this.OnSomeEvent);ServiceHost host = new ServiceHost(svc);host.Open(); There are some caveats when using this approach, as described in http://msdn.microsoft.com/en-us/library/ms585487.aspx Or you could have a well-known singleton class, that your service instances know about and explicitly call its methods when events happen.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8033/" ] }
139,844
Is there any conflict?
All new versions of Delphi can always be installed safely /next/ to older version. Each new version should be installed in its own directory. If you are going to install multiple versions, always install the oldest version first, and then work your way to the newest. We work very hard to make sure that all versions of Delphi coexist together. But again, never install one version directly on top of another.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22712/" ] }
139,867
Does anyone know of a freely available java 1.5 package that provides a list of ISO 3166-1 country codes as a enum or EnumMap? Specifically I need the "ISO 3166-1-alpha-2 code elements", i.e. the 2 character country code like "us", "uk", "de", etc. Creating one is simple enough (although tedious), but if there's a standard one already out there in apache land or the like it would save a little time.
Now an implementation of country code ( ISO 3166-1 alpha-2 / alpha-3 / numeric ) list as Java enum is available at GitHub under Apache License version 2.0. Example: CountryCode cc = CountryCode.getByCode("JP");System.out.println("Country name = " + cc.getName()); // "Japan"System.out.println("ISO 3166-1 alpha-2 code = " + cc.getAlpha2()); // "JP"System.out.println("ISO 3166-1 alpha-3 code = " + cc.getAlpha3()); // "JPN"System.out.println("ISO 3166-1 numeric code = " + cc.getNumeric()); // 392 Last Edit 2016-Jun-09 CountryCode enum was packaged into com.neovisionaries.i18n with other Java enums, LanguageCode ( ISO 639-1 ), LanguageAlpha3Code ( ISO 639-2 ), LocaleCode, ScriptCode ( ISO 15924 ) and CurrencyCode ( ISO 4217 ) and registered into the Maven Central Repository. Maven <dependency> <groupId>com.neovisionaries</groupId> <artifactId>nv-i18n</artifactId> <version>1.29</version></dependency> Gradle dependencies { compile 'com.neovisionaries:nv-i18n:1.29'} GitHub https://github.com/TakahikoKawasaki/nv-i18n Javadoc https://takahikokawasaki.github.io/nv-i18n/ OSGi Bundle-SymbolicName: com.neovisionaries.i18nExport-Package: com.neovisionaries.i18n;version="1.28.0"
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/139867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12531/" ] }
139,884
Google results on this one are a bit thin, but suggest that it is not easily possible. My specific problem is that I need to renumber the IDs in two tables that are related to each other such that table B has an "table_a_id" column in it. I can't renumber table A first because then its children in B point to the old IDs. I can't renumber table B first because then they would point to the new IDs before they were created. Now repeat for three or four tables. I don't really want to have to fiddle around with individual relationships when I could just "start transaction; disable ref integrity; sort IDs out; re-enable ref integrity; commit transaction". Mysql and MSSQL both provide this functionality IIRC so I would be surprised if Postgres didn't. Thanks!
There are two things you can do (these are complementary, not alternatives): Create your foreign key constraints as DEFERRABLE. Then, call "SET CONSTRAINTS DEFERRED;", which will cause foreign key constraints not to be checked until the end of the transaction. Note that the default if you don't specify anything is NOT DEFERRABLE (annoyingly). Call "ALTER TABLE mytable DISABLE TRIGGER ALL;", which prevents any triggers executing while you load data, then "ALTER TABLE mytable ENABLE TRIGGER ALL;" when you're done to re-enable them.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22715/" ] }
139,889
I'm setting up a number sites right now and many of them have multiple domains. The question is: do I alias the domain (with ServerAlias ) or do I Redirect the request? Obviously ServerAlias is better/easier from a readability or scripting perspective. I have heard however that Google likes it better if everything redirects to one domain. Is this true? If so, what redirect code should be used? Common vhost examples will have: ServerName example.netServerAlias www.example.net Is this wrong and should the www also be a redirect in addition to example2.net and www.example2.net? Or is Google smart enough to that all these sites (or at least the www) are the same site? UPDATE: Part of the reasoning for wanting aliases is that they are much faster. A redirect for a dialup user just because they did (or didn't) use the www adds significantly to initial page load. UPDATE and ANSWER: Thanks Paul for finding the Google link which instructs us to "help your fellow webmasters by not perpetuating the myth of duplicate content penalties". Note, however, this only applies to content ON THE SAME SITE, exemplified in the article with "www.example.com/skates.asp?color=black&brand=riedell or www.example.com/skates.asp?brand=riedell&color=black". In fact, the article explicitly says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."
Redirecting is better, then there is always one, canonical domain for your content. I hear Google penalises multiple domains hosting the same content, but I can't find a source for that at the moment (edit, here's one article , but from 2005, which is ancient history in Internet years!) (not correct, see edit below) Here's some mod-rewrite rules to redirect to a canonical domain: RewriteCond %{HTTP_HOST} !^www\.foobar\.com [NC]RewriteCond %{HTTP_HOST} !^$RewriteRule ^/(.*) http://www.foobar.com/$1 [L,R=permanent] That checks that the host isn't the canonical domain (www.foobar.com) and checks that a domain has actually been specified, before deciding to redirect the request to the canonical domain. Further Edit : Here's an article straight from the horses mouth - seems it's not as big an issue as you might think. Please read this article CAREFULLY as it distinguishes between duplicate content on the same site (as in "www.example.com/skates.asp?color=black&brand=riedell and www.example.com/skates.asp?brand=riedell&color=black") and specifically says "Don't create multiple pages, subdomains, or domains with substantially duplicate content."
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15948/" ] }
139,891
This question is not so much programming related as it is deployment related. I find myself conversing a lot with the group in my company whose job it is to maintain our production Windows servers and deploy our code on them. For legal and compliance reasons, I do not have direct visibility or any control over the servers so the only way I can tell which version(s) of .NET are installed on any of them is through directions I give to that group. So far, all of the methods I can think of to tell which version(s) are installed (check for Administrative Tools matching 1.1 or 2.0, check for the entries in the "Add/Remove Programs" list, check for the existence of the directories under c:\Windows\Microsoft.NET) are flawed (I've seen at least one machine with 2.0 but no 2.0 entries under Administrative Tools - and that method tells you nothing about 3.0+, the "Add/Remove Programs" list can get out of sync with reality, and the existence of the directories doesn't necessarily mean anything). Given that I generally need to know these things are in place in advance (discovering that "oops, this one doesn't have all the versions and service packs you need" doesn't really work well with short maintenance windows) and I have to do the checking "by proxy" since I can't get on the servers directly, what's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server? Preferably some intrinsic way to do so using what the framework installs since it will be quicker and not need some sort of utility to be loaded and also a method which will definitely fail if the frameworks are not properly installed but still have files in place (i.e., there's a directory and gacutil.exe is inded there but that version of the framework is not really "installed") EDIT: In the absence of a good foolproof intrinsic way to do this built into the Framework(s), does anyone know of a good, lightweight, no-install-required program that can find this out? I can imagine someone could easily write one but if one already exists, that would be even better.
You should open up IE on the server for which you are looking for this info, and go to this site: http://www.hanselman.com/smallestdotnet/ That's all it takes. The site has a script that looks your browser's "UserAgent" and figures out what version (if any) of the .NET Framework you have (or don't have) installed, and displays it automatically (then calculates the total size if you chose to download the .NET Framework).
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/139891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ] }
139,926
I was writing some Unit tests last week for a piece of code that generated some SQL statements. I was trying to figure out a regex to match SELECT , INSERT and UPDATE syntax so I could verify that my methods were generating valid SQL, and after 3-4 hours of searching and messing around with various regex editors I gave up. I managed to get partial matches but because a section in quotes can contain any characters it quickly expands to match the whole statement. Any help would be appreciated, I'm not very good with regular expressions but I'd like to learn more about them. By the way it's C# RegEx that I'm after. Clarification I don't want to need access to a database as this is part of a Unit test and I don't wan't to have to maintain a database to test my code. which may live longer than the project.
Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. It can be demonstrated you can't validate SQL with a regex. So, you can stop trying.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20400/" ] }
139,927
I have several projects where I need to append strings to a BSTR/CComBSTR/_bstr_t object (e.g. building a dynamic SQL statement). Is there an out-of-the-box type in the WinAPI to buffer the concatenation (like StringBuilder in .NET), or do I have to write my own? From what I know about the append methods, they perform re-allocation.
Regular expressions can match languages only a finite state automaton can parse, which is very limited, whereas SQL is a syntax. It can be demonstrated you can't validate SQL with a regex. So, you can stop trying.
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/139927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20133/" ] }
139,964
Does anyone have a method to overcome the 260 character limit of the MSBuild tool for building Visual Studio projects and solutions from the command line? I'm trying to get the build automated using CruiseControl (CruiseControl.NET isn't an option, so I'm trying to tie it into normal ant scripts) and I keep on running into problems with the length of the paths. To clarify, the problem is in the length of paths of projects referenced in the solution file, as the tool doesn't collapse paths down properly :( I've also tried using DevEnv which sometimes works and sometimes throws an exception, which isn't good for an automated build on a separate machine. So please don't suggest using this as a replacement. And to top it all, the project builds fine when using Visual Studio through the normal IDE.
It seems that it is limitation of the MSBuild. We had the same problem, and in the end, we had to get paths shortened, because did not find any other solution that worked properly.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16035/" ] }
139,988
What advice would you have for someone who wants to start in the BI (Business Intelligence) domain? I where and what I should start with: Books, Blogs, WebCasts...What I should pay attention to and what I should stay away from. Are the Microsoft technologies worth while ?
The MS technology stack is quite good and is by far the most accessible (try to get hold of a copy of Cognos Reportnet for self-learning). Where you will run into trouble (and this is the main barrier to entry for gaining a B.I. skillset) is to actually get experience working with real data. It's quite hard to come up with a realistic toy scenario for this sort of thing. This means that you have to overcome the chicken-and-egg problem that this poses. One option would be to try to get a job as a B.I. developer somewhere like a government department or other place that has trouble recruiting due to salary constraints. Clear evidence of technical skills and a demonstrated interest in the business might get your foot in the door. This will be a bit harder in a recession. However there is still an ongoing skill shortage of good B.I. people. The reason is (IMO) not the lack of technical skills (the technology isn't rocket science). Instead, I think it is the aforementioned chicken-and-egg problem and the fact that the B.I. domain involves customer intimacy to do it well. It lends itself to working in an analyst/programmer mode with direct customer contact (one of the reasons I do this type of work). If you like working in this mode it might be a good line for you to get into. Edit: Someone who's just had a job offer in this space asked whether he should take the job.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18619/" ] }
139,989
Many of my colleagues use SVN in groups of 1-5 people partly working on the specific project. Half of them are inexperienced students. In fact non of us are real software developers with year-long experience. Most of them use Eclipse and subclipse to read and write their contributions to the SVN repositories. Some of them have problems with the difference of: checking out (confused with update and merge) commiting (confused with update) updating (confused with commit and check out) merging (is the hardest. Whats a merge? Do i have to merge my code "into the SVN"?) They fear that the SVN might kill their work (they don't call it working branch) if they press the wrong button. They are committing their eclipse .project files to the repository, after adding some arbitrary library dependencies to their java projects. The other colleagues get compilation errors from these comitts and find it hard to resolve these. In general they say: I'd like to work without SVN, I don't like it. It's too complex. Is there a e-learning project like "SVN for kids"? How can I make them like version control?
In my experience, one of the main reasons why so many people are "afraid" of, or don't like, version control is because they don't understand the underlying concepts and how the system works . This is, unfortunately, also true for many experienced developers. I know people who have used CVS and Subversion for years, but they never create branches or tags, because they don't understand how they work, and therefore see them as "complicated" or "unnecessary". I think it's essential that your co-workers gain a basic understanding of the purpose of version control, the reasons for using it, and the workflow involved in doing so . Personally, I think the first two chapters of the Subversion book provide the best explanation of the involved concepts and the theory behind version control systems in general, so I recommend your co-workers to read those. I do not recommend using an IDE integration to learn using version control . Integrations and plug-ins often hide the "details" of the system from the user, which can be very confusing, especially if you don't know what things looke like "under the hood". I prefer tools like TortoiseSVN , where you perform most operations directly, and manually, without any "magic" behind the scenes. For example, a very common misconception is not understanding the difference between your working copy and the repository on the server. I have often seen that switching to a tool where you operate directly on the file system will help with this situation, because the user is forced to activeley think about what he is doing, and why. As with pretty much everything else in life, using version control is also done best by personal experience—trying and failing, and trying again. This is why I recommend creating sandbox home folders for everyone . Allow them to experiment with the various functions in the system without the fear of destroying anything in the project or losing data.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8986/" ] }
139,996
I have a Serializable object which is supposed to hold a java.awt.Image as its member. How should I go about serializing it? (Edited from a not so clear first version, sorry.)
ImageIcon implements Serializable and it can be used to wrap an Image class http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/ImageIcon.html
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/139996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ] }
140,002
I'm trying to return a dictionary from a function. I believe the function is working correctly, but I'm not sure how to utilize the returned dictionary. Here is the relevant part of my function: Function GetSomeStuff() ' ' Get a recordset... ' Dim stuff Set stuff = CreateObject("Scripting.Dictionary") rs.MoveFirst Do Until rs.EOF stuff.Add rs.Fields("FieldA").Value, rs.Fields("FieldB").Value rs.MoveNext Loop GetSomeStuff = stuffEnd Function How do I call this function and use the returned dictionary? EDIT: I've tried this: Dim someStuffsomeStuff = GetSomeStuff and Dim someStuffSet someStuff = GetSomeStuff When I try to access someStuff, I get an error: Microsoft VBScript runtime error: Object required: 'GetSomeStuff' EDIT 2: Trying this in the function: Set GetSomeStuff = stuff Results in this error: Microsoft VBScript runtime error: Wrong number of arguments or invalid property assignment.
I wasn't too sure of what was your problem, so I experimented a bit. It appears that you just missed that to assign a reference to an object, you have to use set , even for a return value: Function GetSomeStuff Dim stuff Set stuff = CreateObject("Scripting.Dictionary") stuff.Add "A", "Anaconda" stuff.Add "B", "Boa" stuff.Add "C", "Cobra" Set GetSomeStuff = stuffEnd FunctionSet d = GetSomeStuffWscript.Echo d.Item("A")Wscript.Echo d.Exists("B")items = d.ItemsFor i = 0 To UBound(items) Wscript.Echo items(i)Next
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2441/" ] }
140,030
When a Java VM crashes with an EXCEPTION_ACCESS_VIOLATION and produces an hs_err_pidXXX.log file, what does that indicate? The error itself is basically a null pointer exception. Is it always caused by a bug in the JVM, or are there other causes like malfunctioning hardware or software conflicts? Edit: there is a native component, this is an SWT application on win32.
Most of the times this is a bug in the VM.But it can be caused by any native code (e.g. JNI calls). The hs_err_pidXXX.log file should contain some information about where the problem happened. You can also check the "Heap" section inside the file. Many of the VM bugs are caused by the garbage collection (expecially in older VMs). This section should show you if the garbage was running at the time of the crash. Also this section shows, if some sections of the heap are filled (the percentage numbers). The VM is also much more likely to crash in a low memory situation than otherwise.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16399/" ] }
140,043
How do I loop into all the resources in the resourcemanager? Ie:foreach (string resource in ResourceManager) //Do something with the recource. Thanks
Use ResourceManager. GetResourceSet () for a list of all resources for a given culture. The returned ResourceSet implements IEnumerable (you can use foreach). To answer Nico's question: you can count the elements of an IEnumerable by casting it to the generic IEnumerable<object> and use the Enumerable.Count<T>() extension method, which is new in C# 3.5: using System.Linq;...var resourceSet = resourceManager.GetResourceSet(..);var count = resSet.Cast<object>().Count();
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ] }
140,049
Which family should I start to learn? (Never did any programming on microcontroller)
Today AVR and PIC are probably the most common microcontrollers among hobbyists. Both have a very wide range of device variants and both can be used to achieve similar results. For a beginner I would suggest AVR due to various reasons: AVR family (tiny, mega) is coherent and easy to understand. The architecture is powerful and modern, and is especially suitable for C compilers. AVRs can of course be programmed in assembly too. Due to its C-friendly architecture, there are quality C compilers available, both commercial and free. The ubiquitous GCC is ported to AVR and called avr-gcc . For getting started all you really need is a handful of basic components, the AVR chip itself and a breadboard . Even the programming cable between PC and AVR can be built essentially for free (a so called wiggler). However, several commercial development kits are available, most notably Atmel's own STK500 . A commercial development kit is more expensive way for getting started, but doesn't require practically any prior knowledge about electronics. Some development kits contain for example LCD displays so it's easy to get interesting stuff done. It has a rich hobbyist community . PIC is notorious for its peculiar architecture. Many love PIC for this, some hate it. AVR is more straightforward and doesn't seem to cause as much extreme and polar opinions. Both AVR and PIC are used in many serious commercial applications. However, they are not the only options of course. My personal favorite microcontroller for both hobby and commercial work is Silicon Laboratories' C8051 family, most notably C8051 F530 . There is an excellent free C compiler and assembler for the C8051 family called SDCC . Summary: There are lots of options, but please don't let that overwhelm you. Just pick one and start learning with it. Microcontrollers are, really, surprisingly easy to master once you just decide to get going!
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/140049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13913/" ] }
140,054
I need to use InstallUtil to install a C# windows service. I need to set the service logon credentials (username and password). All of this needs to be done silently. Is there are way to do something like this: installutil.exe myservice.exe /customarg1=username /customarg2=password
Bravo to my co-worker (Bruce Eddy). He found a way we can make this command-line call: installutil.exe /user=uname /password=pw myservice.exe It is done by overriding OnBeforeInstall in the installer class: namespace Test{ [RunInstaller(true)] public class TestInstaller : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller serviceProcessInstaller; public OregonDatabaseWinServiceInstaller() { serviceInstaller = new ServiceInstaller(); serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; serviceInstaller.ServiceName = "Test"; serviceInstaller.DisplayName = "Test Service"; serviceInstaller.Description = "Test"; serviceInstaller.StartType = ServiceStartMode.Automatic; Installers.Add(serviceInstaller); serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = ServiceAccount.User; Installers.Add(serviceProcessInstaller); } public string GetContextParameter(string key) { string sValue = ""; try { sValue = this.Context.Parameters[key].ToString(); } catch { sValue = ""; } return sValue; } // Override the 'OnBeforeInstall' method. protected override void OnBeforeInstall(IDictionary savedState) { base.OnBeforeInstall(savedState); string username = GetContextParameter("user").Trim(); string password = GetContextParameter("password").Trim(); if (username != "") serviceProcessInstaller.Username = username; if (password != "") serviceProcessInstaller.Password = password; } }}
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/140054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3106/" ] }
140,061
When creating a class library in C++, you can choose between dynamic ( .dll , .so ) and static ( .lib , .a ) libraries. What is the difference between them and when is it appropriate to use which?
Static libraries increase the size of the code in your binary. They're always loaded and whatever version of the code you compiled with is the version of the code that will run. Dynamic libraries are stored and versioned separately. It's possible for a version of the dynamic library to be loaded that wasn't the original one that shipped with your code if the update is considered binary compatible with the original version. Additionally dynamic libraries aren't necessarily loaded -- they're usually loaded when first called -- and can be shared among components that use the same library (multiple data loads, one code load). Dynamic libraries were considered to be the better approach most of the time, but originally they had a major flaw (google DLL hell), which has all but been eliminated by more recent Windows OSes (Windows XP in particular).
{ "score": 9, "source": [ "https://Stackoverflow.com/questions/140061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4055/" ] }
140,090
Should it be on the development servers or a Subversion server? I suppose this could be expanded to any client-server version control system.
The physical repository should be on a stable system that gets regular backups. Generally, a development server does not fit this description... it may be acceptable to put the apache server on the dev server and host the files remotely on a stable, backed-up file server (though there are a number of pitfalls with this approach) if you are unable to get additional server resources. Hosting it on the dev server may be fine if you have an aggressive backup system to protect your code... Just keep in mind that dev servers are prone to configuration changes, being blown-away, or otherwise mucked with that could take down your repo at a critical moment.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ] }
140,104
If something goes wrong in a WCF REST call, such as the requested resource is not found, how can I play with the HTTP response code (setting it to something like HTTP 404, for example) in my OperationContract method?
There is a WebOperationContext that you can access and it has a OutgoingResponse property of type OutgoingWebResponseContext which has a StatusCode property that can be set. WebOperationContext ctx = WebOperationContext.Current;ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
{ "score": 8, "source": [ "https://Stackoverflow.com/questions/140104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21784/" ] }
140,111
Linux supports sending an arbitrary Posix-Signal such as SIGINT or SIGTERM to a process using the kill -Command. While SIGINT and SIGTERM are just boring old ways to end a process in a friendly or not-so-friendly kind of way, SIGQUIT is meant to trigger a core dump. This can be used to trigger a running Java VM to print out a thread dump, including the stacktraces of all running threads -- neat! After printing the debugging info, the Java VM will continue doing whatever it was doing before; in fact the thread dump just happens in another spawned thread of maximum priority. (You can try this out yourself by using kill -3 <VM-PID> .) Note that you can also register your own signal handlers using the (unsupported!) Signal and SignalHandler classes in the sun.misc -package, so you can have all kinds of fun with it. However, I have yet to find a way to send a signal to a Windows process. Signals are created by certain user inputs: Ctrl-C triggers a SIGINT on both platforms, for instance. But there does not seem to be any utility to manually send a signal to a running, but non-interactive process on Windows. The obvious solution is to use the Cygwin kill executable, but while it can end Windows processes using the appropriate Windows API, I could not send a SIGBREAK (the Windows equivalent to SIGQUIT ) with it; in fact I think the only signal it is able to send to Windows processes is SIGTERM . So, to make a long story short and to repeat the headline: How to I send an arbitrary signal to a process in Windows?
If what you want is to explicitly/programmatically kill another program/process of any kind, within the SysInternals' pstools there is a small tool named "pskill" that behaves just like Unixen "kill" would do. If you want something else, keep reading (though I may be wrong on some of the specifics below - it's been eons since I last developed a Windows program in C using only the WinAPI and Charles Petzold's excellent books "Programming for Windows" as a guide). On Windows you don't properly have "signals", what functions WinMain and WinProc receive from the Operating System are simple messages . For instance, when you click on the "X" button of a window, Windows sends that windows' handler the message WM_CLOSE. When the window's deleted but program's still running, it sends WM_DESTROY. When it's about to get out of the main message processing loop, WinMain (not WinProc) receives WM_QUIT. Your program should respond to all these as expected - you can actually develop an "unclosable" application by not doing what it should upon receiving a WM_CLOSE. When user selects the task from Windows Task Manager and clicks "End Task", the OS will send WM_CLOSE (and another one I don't remember). If you use "End Process", though, the process is killed directly, no messages sent ever (source: The Old New Thing ) I remember there was a way to get the HWND of another process' window, once you get that another process could send that window a message thru functions PostMessage and DispatchMessage.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19256/" ] }
140,131
I am looking for a way to convert a long string (from a dump), that represents hex values into a byte array. I couldn't have phrased it better than the person that posted the same question here . But to keep it original, I'll phrase it my own way: suppose I have a string "00A0BF" that I would like interpreted as the byte[] {0x00,0xA0,0xBf} what should I do? I am a Java novice and ended up using BigInteger and watching out for leading hex zeros. But I think it is ugly and I am sure I am missing something simple.
Update (2021) - Java 17 now includes java.util.HexFormat (only took 25 years): HexFormat.of().parseHex(s) For older versions of Java: Here's a solution that I think is better than any posted so far: /* s must be an even-length string. */public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data;} Reasons why it is an improvement: Safe with leading zeros (unlike BigInteger) and with negative byte values (unlike Byte.parseByte) Doesn't convert the String into a char[] , or create StringBuilder and String objects for every single byte. No library dependencies that may not be available Feel free to add argument checking via assert or exceptions if the argument is not known to be safe.
{ "score": 11, "source": [ "https://Stackoverflow.com/questions/140131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11798/" ] }
140,149
I have a custom performance counter category. Visual Studio Server Explorer refuses to delete it, claiming it is 'not registered or a system category'. Short of doing it programmatically, how can I delete the category? Is there a registry key I can delete?
As far as I know, there is no way to safely delete them except programatically (they're intended for apps to create and remove during install) but it is trivial to do from a PowerShell command-line console. Just run this command: [Diagnostics.PerformanceCounterCategory]::Delete( "Your Category Name" ) HOWEVER: (EDIT) You can delete the registry key that's created, and that will make the category vanish. For a category called "Inventory" you can delete the whole key at HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Inventory ... and although I wouldn't be willing to bet that cleans up everything , it will make the category disappear. (If you run Process Monitor while running the Delete() method, you can see can a lot of other activity happening, and there doesn't seem to be any other changes made). It's important to note that as I said originally : when you get that error from Visual Studio, it might be that it's already deleted and you need to refresh the view in VS. In my testing, I had to restart applications in order to get them to actually get a clean list of the available categories. You can check the full list of categories from PowerShell to see if it's listed: [Diagnostics.PerformanceCounterCategory]::GetCategories() | Format-Table -auto But if you check them, then delete the registry key ... they'll still show up, until you restart PowerShell (if you start another instance, you can run the same query over there, and it will NOT show the deleted item, but re-running GetCategories in the first one will continue showing it. By the way, you can filter that list if you want to using -like for patterns, or -match for full regular expressions: [Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -like "*network*" } | Format-Table -auto[Diagnostics.PerformanceCounterCategory]::GetCategories() | Where {$_.CategoryName -match "^SQL.*Stat.*" } | Format-Table -auto
{ "score": 6, "source": [ "https://Stackoverflow.com/questions/140149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16881/" ] }
140,161
How can I find out which column and value is violating the constraint? The exception message isn't helpful at all: Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
There is a property called RowError you can check. See http://dotnetdebug.net/2006/07/16/constraintexception-a-helpful-tip/ Edited to add this link showing iteration of rows to see which had errors. http://www.devnewsgroups.net/group/microsoft.public.dotnet.framework.adonet/topic58812.aspx
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11547/" ] }
140,303
What is the cause of this exception in ASP.NET? Obviously it is a viewstate exception, but I can't reproduce the error on the page that is throwing the exception (a simple two TextBox form with a button and navigation links). FWIW, I'm not running a web farm. Exception Error Message: Unable to validate data. Error Source: System.Web Error Target Site: Byte[] GetDecodedData(Byte[], Byte[], Int32, Int32, Int32 ByRef) Post Data VIEWSTATE: /wEPDwULLTE4NTUyODcyMTFkZF96FHxDUAHIY3NOAMRJYZ+CKsnB EVENTVALIDATION: /wEWBAK+8ZzHAgKOhZRcApDF79ECAoLch4YMeQ2ayv/Gi76znHooiRyBFrWtwyg= Exception Stack Trace at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.default_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) ~ William Riley-Land
The most likely cause of this error is when a postback is stopped before all the viewstate loads (the user hits the stop or back buttons), the viewstate will fail to validate and throw the error. Other potential causes: An application pool recycling between the time the viewstate was generated and the time that the user posts it back to the server (unlikely). A web farm where the machineKeys are not synchronized (not your issue). Update: Microsoft article on the issue . In addition to the above they suggest two other potential causes: Modification of viewstate by firewalls/anti-virus software Posting from one aspx page to another.
{ "score": 5, "source": [ "https://Stackoverflow.com/questions/140303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17847/" ] }
140,406
Does anyone know of existing software or algorithms to calculate a package size for shipping multiple items? I have a bunch of items in our inventory database with length, width and height dimesions defined. Given these dimensions I need to calculate how many of the purchased items will fit into predefined box sizes.
This is a Bin Packing problem, and it's NP-hard. For small number of objects and packages, you might be able to simply use the brute force method of trying every possibility. Beyond that, you'll need to use a heuristic of some sort. The Wikipedia article has some details, along with references to papers you probably want to check out. The alternative, of course, is to start with a really simple algorithm (such as simply 'stacking' items) and calculate a reasonable upper-bound on shipping using that, then if your human packers can do better, you make a slight profit. Or discount your calculated prices slightly on the assumption that your packing is not ideal.
{ "score": 7, "source": [ "https://Stackoverflow.com/questions/140406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8754/" ] }