source_id
int64 1
74.7M
| question
stringlengths 0
40.2k
| response
stringlengths 0
111k
| metadata
dict |
---|---|---|---|
161,462 | I'm using org.w3c XML API to open an existing XML file. I'm removing some nodes , and I'm adding others instead. The problem is that the new nodes that are added are written one after the other, with no newline and no indentation what so ever. While it's true that the XML file is valid , it is very hard for a human to examine it. Is there anyway to add indentation , or at least a newline after each node? | I'm assuming that you're using a Transformer to do the actual writing (to a StreamResult ). In which case, do this before you call transform : transformer.setOutputProperty(OutputKeys.INDENT, "yes");transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/161462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
]
} |
161,477 | Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following: class GenericClass<T> { public event EventHandler<EventData> MyEvent; public class EventData : EventArgs { /* snip */ } // ... snip} Now, it doesn't take a rocket scientist to figure out that this can very quickly lead to a lot of typing (apologies for the horrible pun) when trying to implement a handler for that event. It'd end up being something like this: GenericClass<int> gcInt = new GenericClass<int>;gcInt.MyEvent += new EventHandler<GenericClass<int>.EventData>(gcInt_MyEvent);// ...private void gcInt_MyEvent(object sender, GenericClass<int>.EventData e){ throw new NotImplementedException();} Except, in my case, I was already using a complex type, not just an int. It'd be nice if it were possible to simplify this a little... Edit: ie. perhaps typedefing the EventHandler instead of needing to redefine it to get similar behaviour. | No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g. using CustomerList = System.Collections.Generic.List<Customer>; but that will only impact that source file. In C and C++, my experience is that typedef is usually used within .h files which are included widely - so a single typedef can be used over a whole project. That ability does not exist in C#, because there's no #include functionality in C# that would allow you to include the using directives from one file in another. Fortunately, the example you give does have a fix - implicit method group conversion. You can change your event subscription line to just: gcInt.MyEvent += gcInt_MyEvent; :) | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/161477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
]
} |
161,486 | I developing ASP.NET application using a Swedish version of Windows XP and Visual studio Professional. When ever i get an error aka. "yellow screen of death" the error message is in swedish, making it a bit hard to search for info about it. How can i change what language the error messages in ASP.NET uses? I have no language pack installed for the .net framework. I am however running an english windows xp with a swedish language interface pack on it. I also have this in my web.config: <system.web> <globalization uiCulture="en-US" /></system.web> | In web.config add: <system.web> <globalization uiCulture="en-US" /></system.web> or whatever language you prefer (note: uiCulture="en-US" not culture="en-US"). Also you should check that your app is not changing the uiCulture, for example to a user-specific uiCulture in global.asax. If the error occurs before or during processing the web.config file, this will of course make no difference. In this case, you need to change the regional settings of the account under which the ASP.NET app is running. If you are developing with VS2005 or later, you're probably running under the Cassini web server, under the identity of the current user - so just change the current user's settings. If you're using IIS, you probably want to change the regional settings of the ASPNET account - you can do this from Regional Settings in the Control Panel by checking the checkbox "Apply to current user and to the default user profile". | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20368/"
]
} |
161,510 | In Ruby, is it possible to pass by reference a parameter with value-type semantics (e.g. a Fixnum)?I'm looking for something similar to C#'s ' ref ' keyword. Example: def func(x) x += 1enda = 5func(a) #this should be something like func(ref a)puts a #should read '6' Btw. I know I could just use: a = func(a) | You can accomplish this by explicitly passing in the current binding: def func(x, bdg) eval "#{x} += 1", bdgenda = 5func(:a, binding)puts a # => 6 | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11545/"
]
} |
161,513 | How can I change the color of a DataGridView border when BorderStyle = FixedSingle? | You cannot change the border color, it is system defined. Instead you could try turning off the border setting and then placing the DataGridView inside a Panel. Where the DataGridView is set to Dock.Fill and the Panel has a Padding of 1 pixel on all edges. Then setting the background color of the Panel will show as a border around the contained DataGridView. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
161,539 | Imagine the following Ruby Module: module Foo def inst_method puts "Called Foo.inst_method" end def self.class_method puts "Called Foo.class_method" endend Obviously Foo.class_method can be called without any class instances. However, what's happening to Foo.inst_method ? Is it possible to call Foo.inst_method without previously including/extending a class? Disclaimer: The question isn't focused on solving a real problem. I'm just trying to improve my understanding of the Ruby object system. | The primary purpose of instance methods within modules is to give that functionality to classes that include it. "Mixing in" a module this way is most commonly used as a method of simulating multiple inheritance , or in other situations where inheritance is not the right paradigm (not quite a perfect "is a" relationship) but you want to share behavior. It's one more tool to keep your code DRY . A good example of this in core Ruby is noting how Array and Hash can both be traveled and sorted, etc. They each get this functionality from the Enumerable module ( each_with_index , select , reject , sort and more are all defined in the included module, not in the classes). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20467/"
]
} |
161,541 | I am starting a new distributed project. Should I use SVN or Git, and why? | SVN is one repo and lots of clients. Git is a repo with lots of client repos, each with a user. It's decentralised to a point where people can track their own edits locally without having to push things to an external server. SVN is designed to be more central where Git is based on each user having their own Git repo and those repos push changes back up into a central one. For that reason, Git gives individuals better local version control. Meanwhile you have the choice between TortoiseGit , GitExtensions (and if you host your "central" git-repository on github, their own client – GitHub for Windows ). If you're looking on getting out of SVN, you might want to evaluate Bazaar for a bit. It's one of the next generation of version control systems that have this distributed element. It isn't POSIX dependant like git so there are native Windows builds and it has some powerful open source brands backing it. But you might not even need these sorts of features yet. Have a look at the features, advantages and disadvantages of the distributed VCSes . If you need more than SVN offers, consider one. If you don't, you might want to stick with SVN's (currently) superior desktop integration. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/161541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5147/"
]
} |
161,556 | I've got a Method that gets a IDictionary as a parameter.Now I want to provide a method that retrieves the value from this dictionary, but it should be case-invariant. So my solution to this right now was to have a static function that loops through the keys and converts them toLower() like this: private static IDictionary<ILanguage, IDictionary<string, string>> ConvertKeysToLowerCase( IDictionary<ILanguage, IDictionary<string, string>> dictionaries){ IDictionary<ILanguage, IDictionary<string, string>> resultingConvertedDictionaries = new Dictionary<ILanguage, IDictionary<string, string>>(); foreach(ILanguage keyLanguage in dictionaries.Keys) { IDictionary<string, string> convertedDictionatry = new Dictionary<string, string>(); foreach(string key in dictionaries[keyLanguage].Keys) { convertedDictionatry.Add(key.ToLower(), dictionaries[keyLanguage][key]); } resultingConvertedDictionaries.Add(keyLanguage, convertedDictionatry); } return resultingConvertedDictionaries;} Now, this is ok, but still it's a pretty huge chunk of code that contradicts my idea of "clean and efficient". Do you know any alternatives to this so that the .ContainsKey() method of the dictionary doesn't differentiate between casing? | Yes - pass the Dictionary constructor StringComparer.OrdinalIgnoreCase (or another case-ignoring comparer, depending on your culture-sensitivity needs). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161556",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21699/"
]
} |
161,633 | Should methods in a Java interface be declared with or without the public access modifier? Technically it doesn't matter, of course. A class method that implements an interface is always public . But what is a better convention? Java itself is not consistent in this. See for instance Collection vs. Comparable , or Future vs. ScriptEngine . | The JLS makes this clear: It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/161633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3565/"
]
} |
161,666 | I'm trying to learn scheme via SICP. Exercise 1.3 reads as follow: Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers. Please comment on how I can improve my solution. (define (big x y) (if (> x y) x y))(define (p a b c) (cond ((> a b) (+ (square a) (square (big b c)))) (else (+ (square b) (square (big a c)))))) | Using only the concepts presented at that point of the book, I would do it: (define (square x) (* x x))(define (sum-of-squares x y) (+ (square x) (square y)))(define (min x y) (if (< x y) x y))(define (max x y) (if (> x y) x y))(define (sum-squares-2-biggest x y z) (sum-of-squares (max x y) (max z (min x y)))) | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24457/"
]
} |
161,672 | I noticed some code of a colleague today that initialized class variables in the initialization. However it was causing a warning, he says because of the order they are in. My question is why is it better to do variable initialization where it currently is and not within the curly brackets? DiagramScene::DiagramScene( int slideNo, QRectF screenRect, MainWindow* parent ) : QGraphicsScene( screenRect, parent ), myParent( parent ), slideUndoImageCurrentIndex(-1), nextGroupID(0), m_undoInProgress(false), m_deleteItemOnNextUndo(0) line(0), path(0){ /* Setup default brush for background */ scDetail->bgBrush.setStyle(Qt::SolidPattern); scDetail->bgBrush.setColor(Qt::white); setBackgroundBrush(scDetail->bgBrush);} | It is more efficient (in general). All members of a class are initialised in the constructor, whether you explicitly initialise them or not. If you do not specify an initialiser, then the default constructor of the member is run. If you assign a value in the constructor body, then the assignment operator is called again. This does not apply to scalar values, as in your example, since scalar values do not have constructors. You can't accidentally assign a value twice in the initialiser list. The compiler can check to make sure that the order in which you write the initialisers matches the order in which the members are defined in the class. The C++ standard requires that the members are initialised in the order they are declared, regardless of the order you write the initialisers. Having the compiler check this order ensures that the programmer knows which order the initialisers will be run in (again, this is more important for non-POD members than for scalars). Reference types and const members must be initialised in the initialiser list, because you can't assign to a reference or to a const member. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24459/"
]
} |
161,676 | I'm running zsh as the default shell on a Ubuntu box, and everything works fine using gnome-terminal (which as far as I know emulates xterm). When I login from a windows box via ssh and putty (which also emulates xterm) suddendly the home/end keys no longer work. I've been able to solve that adding these lines to my zshrc file... bindkey '\e[1~' beginning-of-linebindkey '\e[4~' end-of-line ...but I'm still wondering what's wrong here. Any idea? | I found it's a combination: One The ZSH developers do not think that ZSH should define the actions of the Home , End , Del , ... keys. Debian and Ubuntu fix this by defining the normal actions the average user would expect in the global /etc/zsh/zshrc file. Following the relevant code (it is the same on Debian and Ubuntu): if [[ "$TERM" != emacs ]]; then[[ -z "$terminfo[kdch1]" ]] || bindkey -M emacs "$terminfo[kdch1]" delete-char[[ -z "$terminfo[khome]" ]] || bindkey -M emacs "$terminfo[khome]" beginning-of-line[[ -z "$terminfo[kend]" ]] || bindkey -M emacs "$terminfo[kend]" end-of-line[[ -z "$terminfo[kich1]" ]] || bindkey -M emacs "$terminfo[kich1]" overwrite-mode[[ -z "$terminfo[kdch1]" ]] || bindkey -M vicmd "$terminfo[kdch1]" vi-delete-char[[ -z "$terminfo[khome]" ]] || bindkey -M vicmd "$terminfo[khome]" vi-beginning-of-line[[ -z "$terminfo[kend]" ]] || bindkey -M vicmd "$terminfo[kend]" vi-end-of-line[[ -z "$terminfo[kich1]" ]] || bindkey -M vicmd "$terminfo[kich1]" overwrite-mode[[ -z "$terminfo[cuu1]" ]] || bindkey -M viins "$terminfo[cuu1]" vi-up-line-or-history[[ -z "$terminfo[cuf1]" ]] || bindkey -M viins "$terminfo[cuf1]" vi-forward-char[[ -z "$terminfo[kcuu1]" ]] || bindkey -M viins "$terminfo[kcuu1]" vi-up-line-or-history[[ -z "$terminfo[kcud1]" ]] || bindkey -M viins "$terminfo[kcud1]" vi-down-line-or-history[[ -z "$terminfo[kcuf1]" ]] || bindkey -M viins "$terminfo[kcuf1]" vi-forward-char[[ -z "$terminfo[kcub1]" ]] || bindkey -M viins "$terminfo[kcub1]" vi-backward-char# ncurses fogyatekos[[ "$terminfo[kcuu1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcuu1]/O/[}" vi-up-line-or-history[[ "$terminfo[kcud1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcud1]/O/[}" vi-down-line-or-history[[ "$terminfo[kcuf1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcuf1]/O/[}" vi-forward-char[[ "$terminfo[kcub1]" == "^[O"* ]] && bindkey -M viins "${terminfo[kcub1]/O/[}" vi-backward-char[[ "$terminfo[khome]" == "^[O"* ]] && bindkey -M viins "${terminfo[khome]/O/[}" beginning-of-line[[ "$terminfo[kend]" == "^[O"* ]] && bindkey -M viins "${terminfo[kend]/O/[}" end-of-line[[ "$terminfo[khome]" == "^[O"* ]] && bindkey -M emacs "${terminfo[khome]/O/[}" beginning-of-line[[ "$terminfo[kend]" == "^[O"* ]] && bindkey -M emacs "${terminfo[kend]/O/[}" end-of-linefi So, if you are connecting to a Debian or Ubuntu box, you don't have to do anything. Everything should work automagically (if not, see below). But... if you are connecting to another box (e.g. FreeBSD), there might be no user friendly default zshrc . The solution is of course to add the lines from the Debian/Ubuntu zshrc to your own .zshrc . Two Putty sends xterm as terminal type to the remote host. But messes up somewhere and doesn't send the correct control codes for Home , End , ... that one would expect from an xterm . Or an xterm terminal isn't expected to send those or whatever... ( Del key does work in xterm however, if you configure it in ZSH). Also notice that your Numpad-keys act funny in Vim for example with xterm terminal. The solution is to configure Putty to send another terminal type. I've tried xterm-color and linux . xterm-color fixed the Home / End problem, but the Numpad was still funny. Setting it to linux fixed both problems. You can set terminal type in Putty under Connection -> Data. Do not be tempted to set your terminal type in your .zshrc with export TERM=linux , that is just wrong. The terminal type should be specified by your terminal app. So that if, for example, you connect from a Mac box with a Mac SSH client it can set it's own terminal type. Notice that TERM specifies your terminal type and has nothing to do with the host you are connecting to. I can set my terminal type to linux in Putty and connect to FreeBSD servers without problems. So, fix both these things and you should be fine :) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/161676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6069/"
]
} |
161,687 | You sometimes hear it said about Perl that there might be 6 different ways to approach the same problem. Good Perl developers usually have well-reasoned insights for making choices between the various possible methods of implementation. So an example Perl problem: A simple script which recursively iterates through a directory structure, looking for files which were modified recently (after a certain date, which would be variable). Save the results to a file. The question, for Perl developers: What is your best way to accomplish this? | This sounds like a job for File::Find::Rule : #!/usr/bin/perluse strict;use warnings;use autodie; # Causes built-ins like open to succeed or die. # You can 'use Fatal qw(open)' if autodie is not installed.use File::Find::Rule;use Getopt::Std;use constant SECONDS_IN_DAY => 24 * 60 * 60;our %option = ( m => 1, # -m switch: days ago modified, defaults to 1 o => undef, # -o switch: output file, defaults to STDOUT);getopts('m:o:', \%option);# If we haven't been given directories to search, default to the# current working directory.if (not @ARGV) { @ARGV = ( '.' );}print STDERR "Finding files changed in the last $option{m} day(s)\n";# Convert our time in days into a timestamp in seconds from the epoch.my $last_modified_timestamp = time() - SECONDS_IN_DAY * $option{m};# Now find all the regular files, which have been modified in the last# $option{m} days, looking in all the locations specified in# @ARGV (our remaining command line arguments).my @files = File::Find::Rule->file() ->mtime(">= $last_modified_timestamp") ->in(@ARGV);# $out_fh will store the filehandle where we send the file list.# It defaults to STDOUT.my $out_fh = \*STDOUT;if ($option{o}) { open($out_fh, '>', $option{o});}# Print our results.print {$out_fh} join("\n", @files), "\n"; | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19468/"
]
} |
161,698 | I'm using a local artifactory to proxy the request, but the build and test phases are still a bit slow. It's not the actual compile and tests that are slow, it's the "warmup" of the maven2 framework. Any ideas? | There are some possibilities to optimize some of the build tasks. For example the 'clean' task can be optimized from minutes to just milliseconds using simple trick - rename 'target' folder instead of delete. To get details how to do it refer to Speed up Maven build . | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17554/"
]
} |
161,737 | There are truckloads of counters available in perfmon for ASP.NET. What are the best (I am thinking of choosing 5-10) that will be the best to monitor in our test environment so that we can feed back to developers. I am thinking of things like request time, request queue length, active sessions etc. | For a normal (not performance/stress testing) you would be OK with the following: Request Bytes Out Total (very important especially for web (not intranet) applications) Requests Failed Requests/Sec Errors During Execution Errors Unhandled During Execution Session SQL Server Connections Total State Server Sessions Active For the performance testing you would probably want things like: % CPU Utilization (make sure you're checking for very low CPU utilisation as well as it might indicate that something is dead) Requests Queued Output Cache Hits | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3893/"
]
} |
161,738 | How can I check if a given string is a valid URL address? My knowledge of regular expressions is basic and doesn't allow me to choose from the hundreds of regular expressions I've already seen on the web. | I wrote my URL (actually IRI, internationalized) pattern to comply with RFC 3987 ( http://www.faqs.org/rfcs/rfc3987.html ). These are in PCRE syntax. For absolute IRIs (internationalized): /^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?$/i To also allow relative IRIs: /^(?:[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?|(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=@])+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?)$/i How they were compiled (in PHP): <?php/* Regex convenience functions (character class, non-capturing group) */function cc($str, $suffix = '', $negate = false) { return '[' . ($negate ? '^' : '') . $str . ']' . $suffix;}function ncg($str, $suffix = '') { return '(?:' . $str . ')' . $suffix;}/* Preserved from RFC3986 */$ALPHA = 'a-z';$DIGIT = '0-9';$HEXDIG = $DIGIT . 'a-f';$sub_delims = '!\\$&\'\\(\\)\\*\\+,;=';$gen_delims = ':\\/\\?\\#\\[\\]@';$reserved = $gen_delims . $sub_delims;$unreserved = '-' . $ALPHA . $DIGIT . '\\._~';$pct_encoded = '%' . cc($HEXDIG) . cc($HEXDIG);$dec_octet = ncg(implode('|', array( cc($DIGIT), cc('1-9') . cc($DIGIT), '1' . cc($DIGIT) . cc($DIGIT), '2' . cc('0-4') . cc($DIGIT), '25' . cc('0-5'))));$IPv4address = $dec_octet . ncg('\\.' . $dec_octet, '{3}');$h16 = cc($HEXDIG, '{1,4}');$ls32 = ncg($h16 . ':' . $h16 . '|' . $IPv4address);$IPv6address = ncg(implode('|', array( ncg($h16 . ':', '{6}') . $ls32, '::' . ncg($h16 . ':', '{5}') . $ls32, ncg($h16, '?') . '::' . ncg($h16 . ':', '{4}') . $ls32, ncg($h16 . ':' . $h16, '?') . '::' . ncg($h16 . ':', '{3}') . $ls32, ncg(ncg($h16 . ':', '{0,2}') . $h16, '?') . '::' . ncg($h16 . ':', '{2}') . $ls32, ncg(ncg($h16 . ':', '{0,3}') . $h16, '?') . '::' . $h16 . ':' . $ls32, ncg(ncg($h16 . ':', '{0,4}') . $h16, '?') . '::' . $ls32, ncg(ncg($h16 . ':', '{0,5}') . $h16, '?') . '::' . $h16, ncg(ncg($h16 . ':', '{0,6}') . $h16, '?') . '::',)));$IPvFuture = 'v' . cc($HEXDIG, '+') . cc($unreserved . $sub_delims . ':', '+');$IP_literal = '\\[' . ncg(implode('|', array($IPv6address, $IPvFuture))) . '\\]';$port = cc($DIGIT, '*');$scheme = cc($ALPHA) . ncg(cc('-' . $ALPHA . $DIGIT . '\\+\\.'), '*');/* New or changed in RFC3987 */$iprivate = '\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}';$ucschar = '\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}' . '\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}' . '\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}' . '\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}' . '\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}' . '\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}';$iunreserved = '-' . $ALPHA . $DIGIT . '\\._~' . $ucschar;$ipchar = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':@'));$ifragment = ncg($ipchar . '|' . cc('\\/\\?'), '*');$iquery = ncg($ipchar . '|' . cc($iprivate . '\\/\\?'), '*');$isegment_nz_nc = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '+');$isegment_nz = ncg($ipchar, '+');$isegment = ncg($ipchar, '*');$ipath_empty = '(?!' . $ipchar . ')';$ipath_rootless = ncg($isegment_nz) . ncg('\\/' . $isegment, '*');$ipath_noscheme = ncg($isegment_nz_nc) . ncg('\\/' . $isegment, '*');$ipath_absolute = '\\/' . ncg($ipath_rootless, '?'); // Spec says isegment-nz *( "/" isegment )$ipath_abempty = ncg('\\/' . $isegment, '*');$ipath = ncg(implode('|', array( $ipath_abempty, $ipath_absolute, $ipath_noscheme, $ipath_rootless, $ipath_empty))) . ')';$ireg_name = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '*');$ihost = ncg(implode('|', array($IP_literal, $IPv4address, $ireg_name)));$iuserinfo = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':'), '*');$iauthority = ncg($iuserinfo . '@', '?') . $ihost . ncg(':' . $port, '?');$irelative_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_noscheme . '', '' . $ipath_empty . '')));$irelative_ref = $irelative_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');$ihier_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_rootless . '', '' . $ipath_empty . '')));$absolute_IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?');$IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');$IRI_reference = ncg($IRI . '|' . $irelative_ref); Edit 7 March 2011: Because of the way PHP handles backslashes in quoted strings, these are unusable by default. You'll need to double-escape backslashes except where the backslash has a special meaning in regex. You can do that this way: $escape_backslash = '/(?<!\\)\\(?![\[\]\\\^\$\.\|\*\+\(\)QEnrtaefvdwsDWSbAZzB1-9GX]|x\{[0-9a-f]{1,4}\}|\c[A-Z]|)/';$absolute_IRI = preg_replace($escape_backslash, '\\\\', $absolute_IRI);$IRI = preg_replace($escape_backslash, '\\\\', $IRI);$IRI_reference = preg_replace($escape_backslash, '\\\\', $IRI_reference); | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/161738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1842864/"
]
} |
161,747 | I would like to allow the logged user to edit MediaWiki/Common.css without adding them to the sysop group. I understand that this will allow user to change it to harful ways but it is a closed wiki so that is not a problem. Any solution is acceptable even changing php code :) | Create a new group, add give it "editinterface" privilege. In LocalSettings.php it's done like this: $wgGroupPermissions['mynewgroup']['editinterface'] = true; Then add the user to you new group. Or if you want to give that right to all logged-in users, do it like this: $wgGroupPermissions['user']['editinterface'] = true;// user is the default group for all logged-in users For details see MediaWiki manual . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4508/"
]
} |
161,788 | Are there any downsides to passing structs by value in C, rather than passing a pointer? If the struct is large, there is obviously the performance aspect of copying lots of data, but for a smaller struct, it should basically be the same as passing several values to a function. It is maybe even more interesting when used as return values. C only has single return values from functions, but you often need several. So a simple solution is to put them in a struct and return that. Are there any reasons for or against this? Since it might not be obvious to everyone what I'm talking about here, I'll give a simple example. If you're programming in C, you'll sooner or later start writing functions that look like this: void examine_data(const char *ptr, size_t len){ ...}char *p = ...;size_t l = ...;examine_data(p, l); This isn't a problem. The only issue is that you have to agree with your coworker in which the order the parameters should be so you use the same convention in all functions. But what happens when you want to return the same kind of information? You typically get something like this: char *get_data(size_t *len);{ ... *len = ...datalen...; return ...data...;}size_t len;char *p = get_data(&len); This works fine, but is much more problematic. A return value is a return value, except that in this implementation it isn't. There is no way to tell from the above that the function get_data isn't allowed to look at what len points to. And there is nothing that makes the compiler check that a value is actually returned through that pointer. So next month, when someone else modifies the code without understanding it properly (because he didn't read the documentation?) it gets broken without anyone noticing, or it starts crashing randomly. So, the solution I propose is the simple struct struct blob { char *ptr; size_t len; } The examples can be rewritten like this: void examine_data(const struct blob data){ ... use data.tr and data.len ...}struct blob = { .ptr = ..., .len = ... };examine_data(blob);struct blob get_data(void);{ ... return (struct blob){ .ptr = ...data..., .len = ...len... };}struct blob data = get_data(); For some reason, I think that most people would instinctively make examine_data take a pointer to a struct blob, but I don't see why. It still gets a pointer and an integer, it's just much clearer that they go together. And in the get_data case it is impossible to mess up in the way I described before, since there is no input value for the length, and there must be a returned length. | For small structs (eg point, rect) passing by value is perfectly acceptable. But, apart from speed, there is one other reason why you should be careful passing/returning large structs by value: Stack space. A lot of C programming is for embedded systems, where memory is at a premium, and stack sizes may be measured in KB or even Bytes... If you're passing or returning structs by value, copies of those structs will get placed on the stack, potentially causing the situation that this site is named after... If I see an application that seems to have excessive stack usage, structs passed by value is one of the things I look for first. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/161788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24458/"
]
} |
161,790 | I have the following class in C++: class a { const int b[2]; // other stuff follows // and here's the constructor a(void);} The question is, how do I initialize b in the initialization list, given that I can't initialize it inside the body of the function of the constructor, because b is const ? This doesn't work: a::a(void) : b([2,3]){ // other initialization stuff} Edit: The case in point is when I can have different values for b for different instances, but the values are known to be constant for the lifetime of the instance. | Like the others said, ISO C++ doesn't support that. But you can workaround it. Just use std::vector instead. int* a = new int[N];// fill aclass C { const std::vector<int> v;public: C():v(a, a+N) {}}; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
]
} |
161,797 | Another question asked about determining odd/evenness in C, and the idiomatic (x & 1) approach was correctly flagged as broken for one's complement-based systems, which the C standard allows for. Do systems really exist in the 'real world' outside of computer museums? I've been coding since the 1970's and I'm pretty sure I've never met such a beast. Is anyone actually developing or testing code for such a system? And, if not, should we worry about such things or should we put them into Room 101 along with paper tape and punch cards...? | This all comes down to knowing your roots. Yes, this is technically an old technique and I would probably do what other people suggested in that question and use the modulo (%) operator to determine odd or even.But understanding what a 1s complement (or 2s complement) is always a good thing to know. Whether or not you ever use them, your CPU is dealing with those things all of the time. So it can never hurt to understand the concept. Now, modern systems make it so you generally never have to worry about things like that so it has become a topic for Programming 101 courses in a way. But you have to remember that some people actually would still use this in the "real world"... for example, contrary to popular belief there are people who still use assembly! Not many, but until CPUs can understand raw C# and Java, someone is going to still have to understand this stuff. And heck, you never know when you might find your self doing something where you actually need to perform binary math and that 1s complement could come in handy. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1737/"
]
} |
161,813 | How do I resolve merge conflicts in my Git repository? | Try: git mergetool It opens a GUI that steps you through each conflict, and you get to choose how to merge. Sometimes it requires a bit of hand editing afterwards, but usually it's enough by itself. It is much better than doing the whole thing by hand certainly. As per Josh Glover's comment : [This command]doesn't necessarily open a GUI unless you install one. Running git mergetool for me resulted in vimdiff being used. You can installone of the following tools to use it instead: meld , opendiff , kdiff3 , tkdiff , xxdiff , tortoisemerge , gvimdiff , diffuse , ecmerge , p4merge , araxis , vimdiff , emerge . Below is a sample procedure using vimdiff to resolve merge conflicts, based on this link . Run the following commands in your terminal git config merge.tool vimdiffgit config merge.conflictstyle diff3git config mergetool.prompt false This will set vimdiff as the default merge tool. Run the following command in your terminal git mergetool You will see a vimdiff display in the following format: ╔═══════╦══════╦════════╗ ║ ║ ║ ║ ║ LOCAL ║ BASE ║ REMOTE ║ ║ ║ ║ ║ ╠═══════╩══════╩════════╣ ║ ║ ║ MERGED ║ ║ ║ ╚═══════════════════════╝ These 4 views are LOCAL: this is the file from the current branch BASE: the common ancestor, how this file looked before both changes REMOTE: the file you are merging into your branch MERGED: the merge result; this is what gets saved in the merge commit and used in the future You can navigate among these views using ctrl + w . You can directly reach the MERGED view using ctrl + w followed by j . More information about vimdiff navigation is here and here . You can edit the MERGED view like this: If you want to get changes from REMOTE :diffg RE If you want to get changes from BASE :diffg BA If you want to get changes from LOCAL :diffg LO Save, Exit, Commit, and Clean up :wqa save and exit from vi git commit -m "message" git clean Remove extra files (e.g. *.orig ). Warning: It will remove all untracked files, if you won't pass any arguments. | {
"score": 13,
"source": [
"https://Stackoverflow.com/questions/161813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3713/"
]
} |
161,819 | What are the main/best Maven repositories to use that will include the majority of your open source Java package dependencies. Also in what order should these be included? Does it matter? | This is the current setup in the project we are building: MavenCentral ObjectWeb JBoss Maven2 and some snapshots (see below) <repository> <id>MavenCentral</id> <name>Maven repository</name> <url>http://repo1.maven.org/maven2</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots></repository><repository> <id>objectweb</id> <name>Objectweb repository</name> <url>http://maven.objectweb.org/maven2</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots></repository><repository> <id>jboss</id> <name>JBoss Maven2 repository</name> <url>http://repository.jboss.com/maven2/</url> <snapshots> <enabled>false</enabled> </snapshots> <releases> <enabled>true</enabled> </releases></repository><repository> <id>glassfish</id> <name>Glassfish repository</name> <url>http://download.java.net/maven/1</url> <layout>legacy</layout> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots></repository><repository> <id>apache.snapshots</id> <name>Apache Snapshot Repository</name> <url> http://people.apache.org/repo/m2-snapshot-repository </url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots></repository><repository> <id>ops4j.repository</id> <name>OPS4J Repository</name> <url>http://repository.ops4j.org/maven2</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>false</enabled> </snapshots></repository><repository> <id>Codehaus Snapshots</id> <url>http://snapshots.repository.codehaus.org/</url> <snapshots> <enabled>true</enabled> </snapshots> <releases> <enabled>false</enabled> </releases></repository> | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17719/"
]
} |
161,822 | I have several similar methods, say eg. CalculatePoint(...) and CalculateListOfPoints(...). Occasionally, they may not succeed, and need to indicate this to the caller. For CalculateListOfPoints, which returns a generic List, I could return an empty list and require the caller to check this; however Point is a value type and so I can't return null there. Ideally I would like the methods to 'look' similar; one solution could be to define them as public Point CalculatePoint(... out Boolean boSuccess);public List<Point> CalculateListOfPoints(... out Boolean boSuccess); or alternatively to return a Point? for CalculatePoint, and return null to indicate failure. That would mean having to cast back to the non-nullable type though, which seems excessive. Another route would be to return the Boolean boSuccess, have the result (Point or List) as an 'out' parameter, and call them TryToCalculatePoint or something... What is best practice? Edit: I do not want to use Exceptions for flow control! Failure is sometimes expected. | Personally, I think I'd use the same idea as TryParse() : using an out parameter to output the real value, and returning a boolean indicating whether the call was successful or not public bool CalculatePoint(... out Point result); I am not a fan of using exception for "normal" behaviors (if you expect the function not to work for some entries). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161822",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
]
} |
161,859 | I'd like to invoke bash using a string as input. Something like: sh -l -c "./foo" I'd like to do this from Java. Unfortunately, when I try to invoke the command using getRuntime().exec , I get the following error: foo": -c: line 0: unexpected EOF while looking for matching `"' foo": -c: line 1: syntax error: unexpected end of file It seems to be related to my string not being terminated with an EOF. Is there a way to insert a platform specific EOF into a Java string? Or should I be looking for another approach, like writing to a temp script before invoking "sh" ? | Use this: Runtime.getRuntime().exec(new String[] {"sh", "-l", "-c", "./foo"}); Main point: don't put the double quotes in. That's only used when writing a command-line in the shell! e.g., echo "Hello, world!" (as typed in the shell) gets translated to: Runtime.getRuntime().exec(new String[] {"echo", "Hello, world!"}); (Just forget for the moment that the shell normally has a builtin for echo , and is calling /bin/echo instead. :-)) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/161859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20426/"
]
} |
161,872 | What are some really useful but esoteric language features in Perl that you've actually been able to employ to do useful work? Guidelines: Try to limit answers to the Perl core and not CPAN Please give an example and a short description Hidden Features also found in other languages' Hidden Features: (These are all from Corion's answer ) C Duff's Device Portability and Standardness C# Quotes for whitespace delimited lists and strings Aliasable namespaces Java Static Initalizers JavaScript Functions are First Class citizens Block scope and closure Calling methods and accessors indirectly through a variable Ruby Defining methods through code PHP Pervasive online documentation Magic methods Symbolic references Python One line value swapping Ability to replace even core functions with your own functionality Other Hidden Features: Operators: The bool quasi-operator The flip-flop operator Also used for list construction The ++ and unary - operators work on strings The repetition operator The spaceship operator The || operator (and // operator) to select from a set of choices The diamond operator Special cases of the m// operator The tilde-tilde "operator" Quoting constructs: The qw operator Letters can be used as quote delimiters in q{}-like constructs Quoting mechanisms Syntax and Names: There can be a space after a sigil You can give subs numeric names with symbolic references Legal trailing commas Grouped Integer Literals hash slices Populating keys of a hash from an array Modules, Pragmas, and command-line options: use strict and use warnings Taint checking Esoteric use of -n and -p CPAN overload::constant IO::Handle module Safe compartments Attributes Variables: Autovivification The $[ variable tie Dynamic Scoping Variable swapping with a single statement Loops and flow control: Magic goto for on a single variable continue clause Desperation mode Regular expressions: The \G anchor (?{}) and '(??{})` in regexes Other features: The debugger Special code blocks such as BEGIN, CHECK, and END The DATA block New Block Operations Source Filters Signal Hooks map ( twice ) Wrapping built-in functions The eof function The dbmopen function Turning warnings into errors Other tricks, and meta-answers: cat files, decompressing gzips if needed Perl Tips See Also: Hidden features of C Hidden features of C# Hidden features of C++ Hidden features of Java Hidden features of JavaScript Hidden features of Ruby Hidden features of PHP Hidden features of Python Hidden features of Clojure | The flip-flop operator is useful for skipping the first iteration when looping through the records (usually lines) returned by a file handle, without using a flag variable: while(<$fh>){ next if 1..1; # skip first record ...} Run perldoc perlop and search for "flip-flop" for more information and examples. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21632/"
]
} |
161,879 | Quite often in ANSI C code I can see parenthesis sorrounding a single return value. Like this:- int foo(int x) { if (x) return (-1); else return (0);} Why use () around the return value in those cases? Any ideas? I can see no reason for that. | There really isn't a reason...it's just old convention. To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this: return (x+i*2); instead of int y = x+i*2;return y; The parenthesis became a habit and it stuck. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/161879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23864/"
]
} |
161,884 | For those of you that like puzzles: I had this problem recently and am sure there must be a nicer solution. Consider : an ObservableCollection of Foo objects called foos . Foo contains a string ID field I have no control over foos foos will be changing Then: I have another collection called sortLikeThis sortListThis contains strings The strings are the IDs in the order in which the foos are to be shown Plus: There may be objects in foos with an ID that is not in sortLikeThis . These need to go at the end. Likewise, there may be strings in sortLikeThis that do not appear in foos . Is there a nice way to bind to and show in wpf the Foo objects in foos in the order defined by IDs in sortLikeThis ? | There really isn't a reason...it's just old convention. To save space, programmers would often do the final math in the return line instead of on it's own line and the parens ensure are mostly there to make it easier to see that it is a single statement that is returned, like this: return (x+i*2); instead of int y = x+i*2;return y; The parenthesis became a habit and it stuck. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/161884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20508/"
]
} |
161,928 | I am trying to figure out what is the 'grafts' in the Git. For example, in one of the latest comments here , Tobu suppose to use git-filter-branch and .git/info/grafts to join two repositories. But I don't understand why I need these grafts ? It seems, that all work without last two commands. | From Git Wiki : Graft points or grafts enable two otherwise different lines of development to be joined together. It works by letting users record fake ancestry information for commits. This way you can make git pretend the set of parents a commit has is different from what was recorded when the commit was created. Reasons for Using Grafts Grafts can be useful when moving development to git, since it allows you to make cloning of the old history imported from another SCM optional. This keeps the initial clone for users who just wants to follow the latest version down while developers can have the full development history available. When Linus started using git for maintaining his kernel tree there didn't exist any tools to convert the old kernel history. Later, when the old kernel history was imported into git from the bkcvs gateway, grafts was created as a method for making it possible to tie the two different repositories together. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/161928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/70293/"
]
} |
161,942 | I don't want a discussion about when to and not to throw exceptions. I wish to resolve a simple issue. 99% of the time the argument for not throwing exceptions revolves around them being slow while the other side claims (with benchmark test) that the speed is not the issue. I've read numerous blogs, articles, and posts pertaining one side or the other. So which is it? Some links from the answers: Skeet , Mariani , Brumme . | I'm on the "not slow" side - or more precisely "not slow enough to make it worth avoiding them in normal use". I've written two short articles about this. There are criticisms of the benchmark aspect, which are mostly down to "in real life there'd be more stack to go through, so you'd blow the cache etc" - but using error codes to work your way up the stack would also blow the cache, so I don't see that as a particularly good argument. Just to make it clear - I don't support using exceptions where they're not logical. For instance, int.TryParse is entirely appropriate for converting data from a user. It's inappropriate when reading a machine-generated file, where failure means "The file isn't in the format it's meant to be, I really don't want to try to handle this as I don't know what else might be wrong." When using exceptions in "only reasonable circumstances" I've never seen an application whose performance was significantly impaired by exceptions. Basically, exceptions shouldn't happen often unless you've got significant correctness issues, and if you've got significant correctness issues then performance isn't the biggest problem you face. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/161942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23164/"
]
} |
161,960 | A query that is used to loop through 17 millions records to remove duplicates has been running now for about 16 hours and I wanted to know if the query is stopped right now if it will finalize the delete statements or if it has been deleting while running this query? Indeed, if I do stop it, does it finalize the deletes or rolls back? I have found that when I do a select count(*) from myTable That the rows that it returns (while doing this query) is about 5 less than what the starting row count was. Obviously the server resources are extremely poor, so does that mean that this process has taken 16 hours to find 5 duplicates (when there are actually thousands), and this could be running for days? This query took 6 seconds on 2000 rows of test data, and it works great on that set of data, so I figured it would take 15 hours for the complete set. Any ideas? Below is the query: --Declare the looping variableDECLARE @LoopVar char(10) DECLARE --Set private variables that will be used throughout @long DECIMAL, @lat DECIMAL, @phoneNumber char(10), @businessname varchar(64), @winner char(10) SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable) WHILE @LoopVar is not null BEGIN --initialize the private variables (essentially this is a .ctor) SELECT @long = null, @lat = null, @businessname = null, @phoneNumber = null, @winner = null -- load data from the row declared when setting @LoopVar SELECT @long = longitude, @lat = latitude, @businessname = BusinessName, @phoneNumber = Phone FROM MyTable WHERE RecordID = @LoopVar --find the winning row with that data. The winning row means SELECT top 1 @Winner = RecordID FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone ORDER BY CASE WHEN webAddress is not null THEN 1 ELSE 2 END, CASE WHEN caption1 is not null THEN 1 ELSE 2 END, CASE WHEN caption2 is not null THEN 1 ELSE 2 END, RecordID --delete any losers. DELETE FROM MyTable WHERE @long = longitude AND @lat = latitude AND @businessname = BusinessName AND @phoneNumber = Phone AND @winner != RecordID -- prep the next loop value to go ahead and perform the next duplicate query. SET @LoopVar = (SELECT MIN(RecordID) FROM MyTable WHERE @LoopVar < RecordID) END | no, sql server will not roll back the deletes it has already performed if you stop query execution. oracle requires an explicit committal of action queries or the data gets rolled back, but not mssql. with sql server it will not roll back unless you are specifically running in the context of a transaction and you rollback that transaction, or the connection closes without the transaction having been committed. but i don't see a transaction context in your above query. you could also try re-structuring your query to make the deletes a little more efficient, but essentially if the specs of your box are not up to snuff then you might be stuck waiting it out. going forward, you should create a unique index on the table to keep yourself from having to go through this again. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952/"
]
} |
161,975 | Ever since I started using .NET, I've just been creating Helper classes or Partial classes to keep code located and contained in their own little containers, etc. What I'm looking to know is the best practices for making ones code as clean and polished as it possibly could be. Obviously clean code is subjective, but I'm talking about when to use things (not how to use them) such as polymorphism, inheritance, interfaces, classes and how to design classes more appropriately (to make them more useful, not just say 'DatabaseHelper', as some considered this bad practice in the code smells wiki ). Are there any resources out there that could possibly help with this kind of decision making? Bare in mind that I haven't even started a CS or software engineering course, and that a teaching resource is fairly limited in real-life. | A real eye-opener to me was Refactoring: Improving the Design of Existing Code : With proper training a skilled system designer can take a bad design and rework it into well-designed, robust code. In this book, Martin Fowler shows you where opportunities for refactoring typically can be found, and how to go about reworking a bad design into a good one. Refactoring http://ecx.images-amazon.com/images/I/519XT0DER6L._SL160_PIlitb-dp-arrow,TopRight,21,-23_SH30_OU01_AA115_.jpg It helped me to efficiently and systematically refactor code. Also it helped me a lot in discussions with other developers, when their holy code has to be changed ... | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/161975",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20900/"
]
} |
161,984 | Is it possible to create Selenium tests using the Firefox plugin that use randomly generated values to help do regression tests? The full story: I would like to help my clients do acceptance testing by providing them with a suite of tests that use some smarts to create random (or at least pseudo-random) values for the database. One of the issues with my Selenium IDE tests at the moment is that they have predefined values - which makes some types of testing problematic. | First off, the Selenium IDE is rather limited, you should consider switching to Selenium RC, which can be driven by Java or Perl or Ruby or some other languages. Using just Selenium IDE, you can embed JavaScript expressions to derive command parameters.You should be able to type a random number into a text field, for example: type fieldName javascript{Math.floor(Math.random()*11)} Update: You can define helper functions in a file called "user-extensions.js". See the Selenium Reference . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/161984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14971/"
]
} |
162,028 | We have a large C# (.net 2.0) app which uses our own C++ COM component and a 3rd party fingerprint scanner library also accessed via COM. We ran into an issue where in production some events from the fingerprint library do not get fired into the C# app, although events from our own C++ COM component fired and were received just fine. Using MSINFO32 to compare the loaded modules on a working system to those on a failing system we determined that this was caused by STDOLE.DLL not being in the GAC and hence not loaded into the faulty process. Dragging this file into the GAC caused events to come back fine from the fingerprint COM library. So what does stdole.dll do? It's 16k in size so it can't be much... is it some sort of link to another library like STDOLE32? How come its absence causes such odd behavior? How do we distribute stdole.dll? This is an XCOPY deploy app and we don't use the GAC. Should we package it as a resource and use the System.EnterpriseServices.Internal.Publish.GacInstall to ensure it's in the GAC? | It seems that stdole.dll is a primary interop assembly . See Office 2003 Primary Interop Assemblies on MSDN. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
162,032 | I've got two arrays of the same size. I'd like to merge the two so the values of one are the key indexes of the new array, and the values of the new array are the values of the other. Right now I'm just looping through the arrays and creating the new array manually, but I have a feeling there is a much more elegant way to go about this. I don't see any array functions for this purpose, but maybe I missed something? Is there a simple way to this along these lines? $mapped_array = mapkeys($array_with_keys, $array_with_values); | See array_combine() on PHP.net. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/162032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
162,042 | Let's face it. The Singleton Pattern is highly controversial topic with hordes programmers on both sides of the fence. There are those who feel like the Singleton is nothing more then a glorified global variable, and others who swear by pattern and use it incessantly. I don't want the Singleton Controversy to lie at the heart of my question, however. Everyone can have a tug-of-war and battle it out and see who wins for all I care . What I'm trying to say is, I don't believe there is a single correct answer and I'm not intentionally trying inflame partisan bickering. I am simply interested in singleton-alternatives when I ask the question: Are their any specific alternatives to the GOF Singleton Pattern? For example, many times when I have used the singleton pattern in the past, I am simply interested in preserving the state/values of one or several variables. The state/values of variables, however, can be preserved between each instantiation of the class using static variables instead of using the singleton pattern. What other idea's do you have? EDIT: I don't really want this to be another post about "how to use the singleton correctly." Again, I'm looking for ways to avoid it. For fun, ok? I guess I'm asking a purely academic question in your best movie trailer voice, "In a parallel universe where there is no singleton, what could we do?" | Alex Miller in " Patterns I Hate " quotes the following: "When a singleton seems like the answer, I find it is often wiser to: Create an interface and a default implementation of your singleton Construct a single instance of your default implementation at the “top” of your system. This might be in a Spring config, or in code, or defined in a variety of ways depending on your system. Pass the single instance into each component that needs it (dependency injection) | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/162042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
]
} |
162,099 | I just recently got my first mac. I do lots of programming on windows but now I want to get into Mac development. What are some languages i should know or tools i should use to get started with mac development? | Cocoa(R) Programming for Mac(R) OS X (3rd Edition) by Aaron Hillegass : Fantastic book and the author has alot of credibility - Apple brought him in to train their developers on Cocoa. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2128/"
]
} |
162,112 | Just how much slower are events? I have written a streaming XML parser (that can handle open-ended and incomplete documents) and by tearing out the events and using an interface instead I got a significant speed boost. Does any one else have any war stories? (Let's not open the GC can of worms here, we all know it's broken :)) | Events firing are delegate invocations, which are a a bit slower than virtual calls (source: microsoft.com ) But dealing with interfaces for subscriber/publisher/observer/observable scenario is more painful that using events. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24064/"
]
} |
162,149 | Our company is sending out a lot of emails per day and planning to send even more in future. (thousands) Also there are mass mailouts as well in the ten thousands every now and then. Anybody has experience with hotmail, yahoo (web.de, gmx.net) and similar webmail companies blocking your emails because "too many from the same source in a period of time" have been sent to them? What can be done about it? Spreading email mailouts over a whole day/night? At what rate? (we are talking about legal emailing just to make sure...) | You want to look at the following: add a bulk-header to your outgoing email ( Precedence: bulk ) look into SPF look into SenderID look into DomainKeys or DKIM look into CAN-SPAM act setup and handle email to abuse@ build relationships with the important providers monitor the usual spam lists, work with them when you are on them Also, most providers have pages setup where they explain how they want "bulk" email to look like when you are sending it to their customers. That general includes requirements for double opt-in, etc.. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/925/"
]
} |
162,159 | Which is better to do client side or server side validation? In our situation we are using jQuery and MVC. JSON data to pass between our View and Controller. A lot of the validation I do is validating data as users enter it.For example I use the the keypress event to prevent letters in a text box, set a max number of characters and that a number is with in a range. I guess the better question would be, Are there any benefits to doing server side validation over client side? Awesome answers everyone. The website that we have is password protected and for a small user base(<50). If they are not running JavaScript we will send ninjas. But if we were designing a site for everyone one I'd agree to do validation on both sides. | As others have said, you should do both. Here's why: Client Side You want to validate input on the client side first because you can give better feedback to the average user . For example, if they enter an invalid email address and move to the next field, you can show an error message immediately. That way the user can correct every field before they submit the form. If you only validate on the server, they have to submit the form, get an error message, and try to hunt down the problem. (This pain can be eased by having the server re-render the form with the user's original input filled in, but client-side validation is still faster.) Server Side You want to validate on the server side because you can protect against the malicious user , who can easily bypass your JavaScript and submit dangerous input to the server. It is very dangerous to trust your UI. Not only can they abuse your UI, but they may not be using your UI at all, or even a browser . What if the user manually edits the URL, or runs their own Javascript, or tweaks their HTTP requests with another tool? What if they send custom HTTP requests from curl or from a script, for example? ( This is not theoretical; eg, I worked on a travel search engine that re-submitted the user's search to many partner airlines, bus companies, etc, by sending POST requests as if the user had filled each company's search form, then gathered and sorted all the results. Those companies' form JS was never executed, and it was crucial for us that they provide error messages in the returned HTML. Of course, an API would have been nice, but this was what we had to do. ) Not allowing for that is not only naive from a security standpoint, but also non-standard: a client should be allowed to send HTTP by whatever means they wish, and you should respond correctly. That includes validation. Server side validation is also important for compatibility - not all users, even if they're using a browser, will have JavaScript enabled. Addendum - December 2016 There are some validations that can't even be properly done in server-side application code, and are utterly impossible in client-side code , because they depend on the current state of the database. For example, "nobody else has registered that username", or "the blog post you're commenting on still exists", or "no existing reservation overlaps the dates you requested", or "your account balance still has enough to cover that purchase." Only the database can reliably validate data which depends on related data. Developers regularly screw this up , but PostgreSQL provides some good solutions . | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/162159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7617/"
]
} |
162,176 | fopen is failing when I try to read in a very moderately sized file in PHP . A 6 meg file makes it choke, though smaller files around 100k are just fine. i've read that it is sometimes necessary to recompile PHP with the -D_FILE_OFFSET_BITS=64 flag in order to read files over 20 gigs or something ridiculous, but shouldn't I have no problems with a 6 meg file? Eventually we'll want to read in files that are around 100 megs, and it would be nice be able to open them and then read through them line by line with fgets as I'm able to do with smaller files. What are your tricks/solutions for reading and doing operations on very large files in PHP ? Update: Here's an example of a simple codeblock that fails on my 6 meg file - PHP doesn't seem to throw an error, it just returns false. Maybe I'm doing something extremely dumb? $rawfile = "mediumfile.csv";if($file = fopen($rawfile, "r")){ fclose($file);} else { echo "fail!";} Another update: Thanks all for your help, it did turn out to be something incredibly dumb - a permissions issue. My small file inexplicably had read permissions when the larger file didn't. Doh! | Are you sure that it's fopen that's failing and not your script's timeout setting? The default is usually around 30 seconds or so, and if your file is taking longer than that to read in, it may be tripping that up. Another thing to consider may be the memory limit on your script - reading the file into an array may trip over this, so check your error log for memory warnings. If neither of the above are your problem, you might look into using fgets to read the file in line-by-line, processing as you go. $handle = fopen("/tmp/uploadfile.txt", "r") or die("Couldn't get handle");if ($handle) { while (!feof($handle)) { $buffer = fgets($handle, 4096); // Process buffer here.. } fclose($handle);} Edit PHP doesn't seem to throw an error, it just returns false. Is the path to $rawfile correct relative to where the script is running? Perhaps try setting an absolute path here for the filename. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/162176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
162,187 | When used like this: import static com.showboy.Myclass;public class Anotherclass{} what's the difference between import static com.showboy.Myclass and import com.showboy.Myclass ? | See Documentation The static import declaration is analogous to the normal import declaration. Where the normal import declaration imports classes from packages, allowing them to be used without package qualification, the static import declaration imports static members from classes, allowing them to be used without class qualification. So when should you use static import? Very sparingly! Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the static members you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing all of the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program more readable, by removing the boilerplate of repetition of class names. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/162187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10927/"
]
} |
162,192 | When adding a DLL as a reference to an ASP.Net project, VS2008 adds several files to the bin directory. If the DLL is called foo.dll, VS2008 adds foo.dll.refresh, foo.pdb and foo.xml. I know what foo.dll is :-), why does VS2008 add the other three files? What do those three files do? Can I delete them? Do they need to be added in source control? | Source Control: Ben Straub said in a comment to this post: The .dll.refresh files should be added to the source control if required, while the .xml , .pdb and of course the .dll files should not be added. John Rudy explained when to add the .refresh file: Why is this a good thing (sometimes)? Let's say you're in a team environment. Someone checks in code for foo.dll, and your build system builds a new DLL, outputting it in a file share on a server. Your refresh file points to that server copy of the DLL. Next time you build, VS will auto-magically grab the latest and greatest copy of that DLL. .xml like David Mohundro said: The xml file is there for XML comments and intellisense. Visual Studio will parse that and display the XML comments that were added when you call methods in those DLLs. .pdb like David Mohundro said: The pdb is there for debugging and symbols. If you get an exception thrown from it, you'll be able to get stacktraces, etc. You're in control of choosing whether or not the PDB is built. .refresh from a blog post about .refresh files: It tells VS where to look for updated versions of the dll with the same base name. They're text files, you can open them and see the path it's using. Their purpose is to prevent you from having to copy new versions yourself. In VS2003, the project file would contain the source location of the reference, but since VS2005 doesn't use project files for ASP.NET projects, this is the replacement for that particular functionality. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24482/"
]
} |
162,225 | I've got an XML document containing news stories, and the body element of a news story contains p tags amongst the plain text. When I use XSL to retrieve the body, e.g. <xsl:value-of select="body" /> the p tags seem to get stripped out. I'm using Visual Studio 2005's implementation of XSL. Does anyone have any ideas how to avoid this? Thanks. | Try to use <xsl:copy-of select="body"/> instead. From w3schools' documentation on same : The <xsl:copy-of> element creates a copy of the current node. Note: Namespace nodes, child nodes, and attributes of the current node are automatically copied as well! | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162225",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12277/"
]
} |
162,253 | I'm looking to start developing for the web using Java - I have some basic Java knowledge, so that's not a problem, but I'm at a loss when it comes to deciphering the various technologies for use in web applications. What options are available to me? How do they work? Are there any frameworks similar to Django/Ruby on Rails which I could use to simplify things? Any links which could help with understanding what's available would be much appreciated. | Java frameworks come in two basic flavors. One is called the "Action" Framework, the other the "Component" Framework. Action frameworks specialize on mapping HTTP requests to Java code (actions), and binding HTTP Requests to Java objects. Servlets is the most basic of the Action Frameworks, and is the basic upon all of the others are built. Struts is the most popular Action framework, but I can't in good conscience recommend it to anyone. Struts 2 and Stripes are more modern, and very similar to each other. Both are light on the configuration and easy to use out of the box, providing very good binding functionality. Component Frameworks focus on the UI and tend to promote a more event driven architecture based on high level UI components (buttons, list boxes, etc.). The frameworks tend to hide that actual HTTP request from the coder under several layers. They make developing the more advanced UIs much easier. .NET is a component framework for Windows. On Java, the popular component frameworks are JSF (a standard) and Wicket. As a rule, if you're creating a "web site". that is something more akin to presenting information (like a blog, or a community site), the Action frameworks work better. These sites tend to be simpler, get bookmarked often, require "pretty URLs" etc. This is generally easier to do with an Action framework. Component frameworks are much better for things like back office applications with lots of UI elements and complicated workflows. You'll find, particularly with tooling, that these style of apps will go together faster using a component framework. But component frameworks have more complicated request workflow, sometimes relying on hidden state, lots of POST actions, etc. Many have "horrible" URLs, and sometimes create pages that are difficult to bookmark. Both frameworks can be used for both tasks, just some are more suited to the task than others. None of these frameworks directly address persistence, but many have extension modules or idioms that work tightly with JPA/EJB3 or Hibernate. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23746/"
]
} |
162,255 | What's the best way, using SQL, to check the maximum number of connections that is allowed for an Oracle database? In the end, I would like to show the current number of sessions and the total number allowed, e.g. "Currently, 23 out of 80 connections are used". | There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e. The number of sessions the database was configured to allow SELECT name, value FROM v$parameter WHERE name = 'sessions' The number of sessions currently active SELECT COUNT(*) FROM v$session As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/162255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24495/"
]
} |
162,291 | How can I check if an application is running from a batch (well cmd) file? I need to not launch another instance if a program is already running. (I can't change the app to make it single instance only.) Also the application could be running as any user. | Another possibility I came up with, which does not require to save a file, inspired by using grep is: tasklist /fi "ImageName eq MyApp.exe" /fo csv 2>NUL | find /I "myapp.exe">NULif "%ERRORLEVEL%"=="0" echo Program is running /fi "" defines a filter of apps to find, in our case it's the *.exe name /fo csv defines the output format, csv is required because by default the name of the executable may be truncated if it is too long and thus wouldn't be matched by find later. find /I means case-insensitive matching and may be omitted See the man page of the tasklist command for the whole syntax. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/162291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1755/"
]
} |
162,303 | How can I convert a Char[] (of any length) to a List ? | First you need to understand that chars aren't bytes in .NET. To convert between chars (a textual type) and bytes (a binary type) you need to use an encoding (see System.Text.Encoding). Encoding will let you convert between string/char[] and byte[]. Once you've got a byte array, there are various ways of converting that into a List<byte> - although you may not even need to, as byte[] implements IList<byte>. See my article on Unicode for more about the text conversion side of things (and links to more articles). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1816/"
]
} |
162,304 | I've been using Remote Desktop Connection to get into a workstation. But in this environment, I cannot use the power options in Start Menu. I need an alternative way to shutdown or restart. How do I control my computer's power state through the command line? | The most common ways to use the shutdown command are: shutdown -s — Shuts down. shutdown -r — Restarts. shutdown -l — Logs off. shutdown -h — Hibernates. Note: There is a common pitfall wherein users think -h means "help" (which it does for every other command-line program... except shutdown.exe , where it means "hibernate"). They then run shutdown -h and accidentally turn off their computers. Watch out for that. shutdown -i — "Interactive mode". Instead of performing an action, it displays a GUI dialog. shutdown -a — Aborts a previous shutdown command. The commands above can be combined with these additional options: -f — Forces programs to exit. Prevents the shutdown process from getting stuck. -t <seconds> — Sets the time until shutdown. Use -t 0 to shutdown immediately. -c <message> — Adds a shutdown message. The message will end up in the Event Log. -y — Forces a "yes" answer to all shutdown queries. Note: This option is not documented in any official documentation. It was discovered by these StackOverflow users . I want to make sure some other really good answers are also mentioned along with this one. Here they are in no particular order. The -f option from JosephStyons Using rundll32 from VonC The Run box from Dean Remote shutdown from Kip | {
"score": 11,
"source": [
"https://Stackoverflow.com/questions/162304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
} |
162,309 | To pop up the UAC dialog in Vista when writing to the HKLM registry hive, we opt to not use the Win32 Registry API, as when Vista permissions are lacking, we'd need to relaunch our entire application with administrator rights. Instead, we do this trick: ShellExecute(hWnd, "runas" /* display UAC prompt on Vista */, windir + "\\Reg", "add HKLM\\Software\\Company\\KeyName /v valueName /t REG_MULTI_TZ /d ValueData", NULL, SW_HIDE); This solution works fine, besides that our application is a 32-bit one, and it runs the REG.EXE command as it would be a 32-bit app using the WOW compatibility layer! :( If REG.EXE is ran from the command line, it's properly ran in 64-bit mode. This matters, because if it's ran as a 32-bit app, the registry keys will end up in the wrong place due to registry reflection . So is there any way to launch a 64-bit app programmatically from a 32-bit app and not have it run using the WOW64 subsystem like its parent 32-bit process (i.e. a "*" suffix in the Task Manager)? | try this (from a 32bit process): > %WINDIR%\sysnative\reg.exe query ... (found that here ). | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9744/"
]
} |
162,310 | What role is Spring taking in Struts + Spring + Hibernate? | Spring provides many different "modules" and different programmers will use different parts of Spring. However, commonly in this sort of stack, you will see Spring being used as a provider of An inversion of control container for dependency injection An abstraction to Hibernate called "HibernateTemplate" Framework classes for simplifying Aspect Oriented Programming Transaction support, often "declaratively" via the IoC container and AOP. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162310",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10927/"
]
} |
162,331 | I'm developing an application targeting .NET Framework 2.0 using C# for which I need to be able to find the default application that is used for opening a particular file type. I know that, for example, if you just want to open a file using that application you can use something like: System.Diagnostics.Process.Start( "C:\...\...\myfile.html" ); to open an HTML document in the default browser, or System.Diagnostics.Process.Start( "C:\...\...\myfile.txt" ); to open a text file in the default text editor. However, what I want to be able to do is to open files that don't necessarily have a .txt extension (for example), in the default text editor, so I need to be able to find out the default application for opening .txt files, which will allow me to invoke it directly. I'm guessing there's some Win32 API that I'll need to P/Invoke in order to do this, however a quick look with both Google and MSDN didn't reveal anything of much interest; I did find a very large number of completely irrelevant pages, but nothing like I'm looking for. | All current answers are unreliable. The registry is an implementation detail and indeed such code is broken on my Windows 8.1 machine. The proper way to do this is using the Win32 API, specifically AssocQueryString : using System.Runtime.InteropServices;[DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]public static extern uint AssocQueryString( AssocF flags, AssocStr str, string pszAssoc, string pszExtra, [Out] StringBuilder pszOut, ref uint pcchOut); [Flags]public enum AssocF{ None = 0, Init_NoRemapCLSID = 0x1, Init_ByExeName = 0x2, Open_ByExeName = 0x2, Init_DefaultToStar = 0x4, Init_DefaultToFolder = 0x8, NoUserSettings = 0x10, NoTruncate = 0x20, Verify = 0x40, RemapRunDll = 0x80, NoFixUps = 0x100, IgnoreBaseClass = 0x200, Init_IgnoreUnknown = 0x400, Init_Fixed_ProgId = 0x800, Is_Protocol = 0x1000, Init_For_File = 0x2000}public enum AssocStr{ Command = 1, Executable, FriendlyDocName, FriendlyAppName, NoOpen, ShellNewValue, DDECommand, DDEIfExec, DDEApplication, DDETopic, InfoTip, QuickTip, TileInfo, ContentType, DefaultIcon, ShellExtension, DropTarget, DelegateExecute, Supported_Uri_Protocols, ProgID, AppID, AppPublisher, AppIconReference, Max} Relevant documentation: AssocQueryString ASSOCF ASSOCSTR Sample usage: static string AssocQueryString(AssocStr association, string extension){ const int S_OK = 0; const int S_FALSE = 1; uint length = 0; uint ret = AssocQueryString(AssocF.None, association, extension, null, null, ref length); if (ret != S_FALSE) { throw new InvalidOperationException("Could not determine associated string"); } var sb = new StringBuilder((int)length); // (length-1) will probably work too as the marshaller adds null termination ret = AssocQueryString(AssocF.None, association, extension, null, sb, ref length); if (ret != S_OK) { throw new InvalidOperationException("Could not determine associated string"); } return sb.ToString();} | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17786/"
]
} |
162,335 | I was browsing Scott Hanselman's Developer Interview question list , and ran across this question: What is wrong with DateTime.Parse(myString)? While I know there are inherent risks in parsing a string of unknow format or origin, are there other reasons? Is it to use DateTime.ParseExact instead? Should it be myString.ToString() first? | In addition the locale problem, DateTime.Parse() could also throw an exception which you would then have to catch. Use DateTime.TryParse() or DateTime.TryParseExact() instead. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162335",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5619/"
]
} |
162,376 | We have SOAP web services in production that are relying on SOAP Headers (containing plain client credentials) for the authentication. The WS are used in heterogeneous environments with .NET/Java/PHP/Python/C++ clients both web app or desktop app. We are considering a v2 for those WS and I am wondering what are considered as the best practices for WS SOAP authentication? (reasonably secure, yet easy to handle on a wide variety of platforms). | The easiest way to handle it across a variety of platforms is to use HTTP basic authentication and HTTPS for the transport layer. WS-Security would be good if your needs go beyond simple username/password but the support is going to vary quite a bit between platforms. HTTP authentication is supported by every decent SOAP implementation. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18858/"
]
} |
162,399 | Hi why doesn't this work in SQL Server 2005? select HALID, count(HALID) as CH from Outages.FaultsInOutageswhere CH > 3group by HALID I get invalid column name 'CH' i think having was the right way to go but still receive the error:Invalid column name 'CH'. When running: select HALID, count(HALID) as CH from Outages.FaultsInOutages group by HALID having CH > 3 | You can't use the alias in the where clause or having clause, as it isn't processed until AFTER the result set is generated, the proper syntax is SELECT HALID, COUNT(HALID) AS CHFROM Outages.FaultsInOutagesGROUP BY HALIDHAVING COUNT(HALID) > 3 This will group items on HALID, then ONLY return results that have more than 3 entries for the specific HALID | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21004/"
]
} |
162,445 | I wan't to know the real size of a web page (HTML + CSS + Javascript + Images + etc.) but from the browser side, maybe with a software, Firefox Add-On or similar? | Use firefox, and get FireBug. Then get the YSlow addon for firefox. For IE, you can get the DebugBar which comes pretty close to giving the same information. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24506/"
]
} |
162,480 | Consider: int testfunc1 (const int a){ return a;}int testfunc2 (int const a){ return a;} Are these two functions the same in every aspect or is there a difference? I'm interested in an answer for the C language, but if there is something interesting in the C++ language, I'd like to know as well. | const T and T const are identical. With pointer types it becomes more complicated: const char* is a pointer to a constant char char const* is a pointer to a constant char char* const is a constant pointer to a (mutable) char In other words, (1) and (2) are identical. The only way of making the pointer (rather than the pointee) const is to use a suffix- const . This is why many people prefer to always put const to the right side of the type (“East const” style): it makes its location relative to the type consistent and easy to remember (it also anecdotally seems to make it easier to teach to beginners). | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/162480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15955/"
]
} |
162,497 | There is a select dropdown and I want to add "No selection" item to the list which should give me 'null' when submitted.I'm using SimpleFormController derived controller. protected Map referenceData(HttpServletRequest httpServletRequest, Object o, Errors errors) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("countryList", Arrays.asList(Country.values())); return map;} And the jspx part is <form:select path="country" items="${countryList}" title="country"/> One possible solution seems to be in adding a null value to the beginning of the list and then using a custom PropertyEditor to display this 'null' as 'No selection'.Is there a better solution? @Edit: I have solved this with a custom validation annotation which checks if the selected value is "No Selection". Is there a more standard and easier solution? | One option: <form:select path="country" title="country" > <form:option value=""> </form:option> <form:options items="${countryList}" /></form:select> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
]
} |
162,537 | I just upgraded a VS 2005 project to VS 2008 and was examining the changes. I noticed one of the .Designer.cs files had changed significantly. The majority of the changes were simply replacements of System with global::System . For example, protected override System.Data.DataTable CreateInstance() became protected override global::System.Data.DataTable CreateInstance() What's going on here? | The :: operator is called a Namespace Alias Qualifier. global::System.Data.DataTable is the same as: System.Data.DataTable Visual Studio 2008 added it to the designer generated code to avoid ambigious reference issues that occasionally happened when people created classes named System...For example: class TestApp{ // Define a new class called 'System' to cause problems. public class System { } // Define a constant called 'Console' to cause more problems. const int Console = 7; const int number = 66; static void Main() { // Error Accesses TestApp.Console //Console.WriteLine(number); }} However: global::System.Console.Writeline("This works"); For further reading: http://msdn.microsoft.com/en-us/library/c3ay4x3d(VS.80).aspx | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162537",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
]
} |
162,551 | What tools do you use to find unused/dead code in large java projects? Our product has been in development for some years, and it is getting very hard to manually detect code that is no longer in use. We do however try to delete as much unused code as possible. Suggestions for general strategies/techniques (other than specific tools) are also appreciated. Edit: Note that we already use code coverage tools (Clover, IntelliJ), but these are of little help. Dead code still has unit tests, and shows up as covered. I guess an ideal tool would identify clusters of code which have very little other code depending on it, allowing for docues manual inspection. | An Eclipse plugin that works reasonably well is Unused Code Detector . It processes an entire project, or a specific file and shows various unused/dead code methods, as well as suggesting visibility changes (i.e. a public method that could be protected or private). | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/162551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7084/"
]
} |
162,571 | I've executed a JDBC query to obtain a resultset. Before iterating over it, I'd like to quickly find out how many rows were returned. How can I do this with high performance? I'm using Java 6, Oracle 11g, and the latest Oracle JDBC drivers. | You're going to have to do this as a separate query, for example: SELECT COUNT(1) FROM table_name Some JDBC drivers might tell you but this is optional behaviour and, more to the point, the driver may not know yet. This can be due to how the query is optimised eg two example execution strategies in Oracle are to get all rows as quickly as possible or to get the first row as quickly as possible. If you do two separate queries (one a count and the other the query) then you'll need to do them within the same transaction. This will work well on Oracle but can be problematic on other databases (eg SQL Server will either show you uncommitted data or block on an external uncommitted update depending on your isolation level whereas Oracle supports an isolation level that gives you a transactionally consistent view of the data without blocking on external updates). Normally though it doesn't really matter how many rows there are. Typically this sort of query is either batch processed or paged and either way you have progress information in the form of rows loaded/processed and you can detect the end of the result set (obviously). | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162571",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959/"
]
} |
162,591 | I have a subversion repository with the standard layout, i.e. trunk/ and branches/ (and tags/). When working on a bigger change, a feature branch is used, regularly synced with trunk, and later reintegrated back into trunk (using 1.5 now). Pretty standard stuff. What I am wondering is whether such a feature branch, once finished and merged should be kept around, or deleted. The subversion book occasionally seems to suggest that it is common to delete them, but I've also seen a bunch of Open Source projects which do keep the branches. I am also somewhat concerned about how deleting a branch will make it harder to keep track of which branches existed, especially when potentially duplicate names enter the scenario (say we search-refactor twice), their commit histories disappearing somewhere in the depth of the repository etc. On the other hand, branches are used quite a lot, especially with 1.5 now, and I do like the thought of not having to poke through a large list of inactive branches to find the ones I am currently working on. What are the pros and cons that I am missing? What are people doing? | If you are really worried about deleting them, lest they be forgotten, then simply create a folder under branches called 'inactive' and svn move your older, inactive branches into that folder. This might be the best of both worlds for you. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162591",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15677/"
]
} |
162,617 | When creating a new file with vim, I would like to automatically add some skeleton code. For example, when creating a new xml file, I would like to add the first line: <?xml version="1.0"?> Or when creating an html file, I would like to add: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html> <head> <title></title> </head> <body> </body></html> | I got something like this in my .vimrc: au BufNewFile *.xml 0r ~/.vim/xml.skel | let IndentStyle = "xml"au BufNewFile *.html 0r ~/.vim/html.skel | let IndentStyle = "html" And so on, whatever you'll need. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24076/"
]
} |
162,644 | Firebug is the most convenient tool I've found for editing CSS - so why isn't there a simple "save" option for CSS? I am always finding myself making tweaks in Firebug, then going back to my original .css file and replicating the tweaks. Has anyone come up with a better solution? EDIT: I'm aware the code is stored on a server (in most cases not my own), but I use it when building my own websites. Firebug's just using the .css file Firefox downloaded from the server, it knows precisely what lines in which files it's editing. I can't see why there's not an "export" or "save" option, which allows you to store the new .css file. (Which I could then replace the remote one with). I have tried looking in temporary locations, and choosing File > Save... and experimenting with the output options on Firefox, but I still haven't found a way. EDIT 2: The official discussion group has a lot of questions , but no answers. | Been wondering the same for quite some time now, just gut-wrenching when your in-the-moment-freestyle-css'ing with firebug gets blown to bits by an accidental reload or whatnot.... For my intents and purposes, I've finally found the tool.... : FireDiff . It gives you a new tab, probably some weird David Bowie reference, called "changes";which not only allows you to see/save what firebug, i. e. you, have been doing, but also optionally track changes made by the page itself....if it and/or you are so inclined. So thankful not having to re-type, or re-imagine and then re-re-type, every css rule I make... Here is a link to the developer (don't be disparaged by first appearance, mayhap just as well head straight over to the Mozilla Add-On repository . | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/162644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14966/"
]
} |
162,680 | Does attempting to develop some sort of game, even just as a hobby during leisure time provide useful (professional) experience or is it a childish waste of time? I have pursued small personal game projects on and off throughout my programming career. I've found the (often) strict performance requirements and escalating design complexity have taught me some of my most useful programming lessons. In these projects to name just a few, I very quickly came face to face with: "Everything is fast for small N". I also discovered the hard way about using basic object oriented design principles to manage complexity. In a field where many technologies and topics can be quite dry/dull, I think hobby game development is important in motivating new (and not so new) developers to brush up on essential skills while having fun at the same time. This question talks about hobby projects in general, however here I am more interested in game projects specially and how valuable they are to professional programmers. | You can learn a lot from game development. Game development requires a discipline that you can't find in other programming projects. Here are just a small set of things game development has taught me: Optimization for speed Sacrificing computational depth for speed Developing under small constraints of memory Building a system that works like an operating system but is geared toward speed. Keeping hundreds to thousands of objects in a tree, each with their own unique characteristics Some areas of game development have great academic value (like Artificial Intelligence, Procedural Algorithms, etc) It doesn't matter how much of a hack the code is, as long as the gameplay is there. Translating this to other disciplines, the objective of programming is to make the customers happy, regardless of how clever or ugly your code is. Because game programmers are forced to use less resources, they become better programmers. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5023/"
]
} |
162,681 | Given the email address: "Jim" <[email protected]> If I try to pass this to MailAddress I get the exception: The specified string is not in the form required for an e-mail address. How do I parse this address into a display name (Jim) and email address ([email protected]) in C#? EDIT: I'm looking for C# code to parse it. EDIT2: I found that the exception was being thrown by MailAddress because I had a space at the start of the email address string. | If you are looking to parse the email address manually, you want to read RFC2822 ( https://www.rfc-editor.org/rfc/rfc822.html#section-3.4 ). Section 3.4 talks about the address format. But parsing email addresses correctly is not easy and MailAddress should be able to handle most scenarios. According to the MSDN documentation for MailAddress : http://msdn.microsoft.com/en-us/library/591bk9e8.aspx It should be able to parse an address with a display name. They give "Tom Smith <[email protected]>" as an example. Maybe the quotes are the issue? If so, just strip the quotes out and use MailAddress to parse the rest. string emailAddress = "\"Jim\" <[email protected]>";MailAddress address = new MailAddress(emailAddress.Replace("\"", "")); Manually parsing RFC2822 isn't worth the trouble if you can avoid it. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4580/"
]
} |
162,718 | Using the default TWebBrowser makes things easy to embed a web browser. Unfortunately the one that comes in by default is IE<n>. I'm wondering how does one integrate a Gecko or WebKit one. Are there VCL examples somewhere? If not, how would one go about doing it? Where's the best place to find the core for Gecko and/or WebKit in an embeddable format? | TWebBrowser is IE. It is not a plugable construction for browsers. You can have other browsers integrated in your application. See http://www.adamlock.com/mozilla/ http://delphi.mozdev.org/articles/taming_the_lizard_with_delphi.html http://ftp.newbielabs.com/Delphi%20Gecko%20SDK/ Time has moved on This answer is from '08 and since then time has moved on. The links don't work anymore and there are probably better alternatives now. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8167/"
]
} |
162,727 | I've got a text file full of records where each field in each record is a fixed width. My first approach would be to parse each record simply using string.Substring(). Is there a better way? For example, the format could be described as: <Field1(8)><Field2(16)><Field3(12)> And an example file with two records could look like: SomeData0000000000123456SomeMoreDataData2 0000000000555555MoreData I just want to make sure I'm not overlooking a more elegant way than Substring(). Update: I ultimately went with a regex like Killersponge suggested: private readonly Regex reLot = new Regex(REGEX_LOT, RegexOptions.Compiled);const string REGEX_LOT = "^(?<Field1>.{6})" + "(?<Field2>.{16})" + "(?<Field3>.{12})"; I then use the following to access the fields: Match match = reLot.Match(record);string field1 = match.Groups["Field1"].Value; | Use FileHelpers . Example: [FixedLengthRecord()] public class MyData{ [FieldFixedLength(8)] public string someData; [FieldFixedLength(16)] public int SomeNumber; [FieldFixedLength(12)] [FieldTrim(TrimMode.Right)] public string someMoreData;} Then, it's as simple as this: var engine = new FileHelperEngine<MyData>(); // To Read Use: var res = engine.ReadFile("FileIn.txt"); // To Write Use: engine.WriteFile("FileOut.txt", res); | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162727",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2773/"
]
} |
162,764 | I have a database with user 'dbo' that has a login name "domain\xzy". How do I change it from "domain\xzy" to "domain\abc". | I figured it out. Within SQL Management Studio you have to right-click on the database -> Properties -> Files -> Owner field. Change this field to the login name/account that you want associated with the "dbo" username for that database. Please keep in mind that the login name/account you choose must already be setup in the sql server under Security -> Logins | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/162764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24522/"
]
} |
162,810 | I am using Log4Net with the AdoNetAppender to log messages from a simple systray application into a SQL Server 2005 database. I want to log the machine name along with the log message because this application will be running on multiple machines and I need to know on which one the message originated. But, I cannot find a way to expose this information via the log4net.Layout.PatternLayout that I am using with the appender. Is there a way to log the machine name via log4net in this manner? | You can use the pre-populated property log4net:HostName , for example: <conversionPattern value="%property{log4net:HostName}" /> This way you don't need to populate the MDC. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/162810",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2834/"
]
} |
162,873 | How do you include a file that is more than 2 directories back. I know you can use ../index.php to include a file that is 2 directories back, but how do you do it for 3 directories back?Does this make sense?I tried .../index.php but it isn't working. I have a file in /game/forum/files/index.php and it uses PHP include to include a file. Which is located in /includes/boot.inc.php ; / being the root directory. | .. selects the parent directory from the current. Of course, this can be chained: ../../index.php This would be two directories up. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/162873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
162,896 | I'm a Mac user and I've decided to learn Emacs. I've read that to reduce hand strain and improve accuracy the CTRL and CAPS LOCK keys should be swapped. How do I do this in Leopard? Also, in Terminal I have to use the ESC key to invoke meta. Is there any way to get the alt/option key to invoke meta instead? update: While the control key is much easier to hit now, the meta key is also used often enough that its position on my MacBook and Apple Keyboard also deserves attention. In fact, I find that the control key is actually easier to hit, so I've remapped my control key to act as a meta key. Does anyone have a better/more standard solution? | Swapping CTRL and CAPS LOCK Go into System Preferences Enter the Keyboard & Mouse preference pane In the Keyboard tab, click Modifier Keys... Swap the actions for Caps Lock and Control . Using ALT/OPTION as META In the menu bar, click Terminal Click Preferences... Under the Settings tab, go to the Keyboard tab Check the box labeled Use option as meta key That's it! You should be well on your way to becoming an Emacs master! | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/162896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/658/"
]
} |
162,897 | Given the following C function in a DLL: char * GetDir(char* path ); How would you P/Invoke this function into C# and marshal the char * properly..NET seems to know how to do LPCTSTR but when I can't figure out any marshaling that doesn't cause a NotSupportedException to fire when calling this function. | OregonGhost's answer is only correct if the char* returned from GetDir is either allocated in HGlobal or LocalAlloc. I can't remember which one but the CLR will assume that any string return type from a PInvoke function was allocated with one or the other. A more robust way is to type the return of GetDir to be IntPtr. Then you can use any of the Marshal.PtrToStringAnsi functions in order to get out a string type. It also gives you th flexibility of freeing the string in the manner of your choosing. [DllImport("your.dll", CharSet = CharSet.Ansi)]IntPtr GetDir(StringBuilder path); Can you give us any other hints as to the behavior of GetDir? Does it modify the input string? How is the value which is returned allocated? If you can provide that I can give a much better answer. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/162897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
]
} |
162,911 | If I can do this, how do I call Java code (methods for instance) from within JavaScript code, in Wicket. | erk. The correct answer would be ajax call backs. You can either manually code the js to hook into the wicket js, or you can setup the callbacks from wicket components in java.For example, from AjaxLazyLoadPanel: component.add( new AbstractDefaultAjaxBehavior() { @Override protected void respond(AjaxRequestTarget target) { // your code here } @Override public void renderHead(IHeaderResponse response) { super.renderHead( response ); response.renderOnDomReadyJavascript( getCallbackScript().toString() ); } } This example shows how to add call back code to any Component in Wicket. After the OnDomReady event fires in your browser, when loading a page, Wicket will cause it's js enging, to call back into your code, using Ajax, to the 'respond' method shown above, at which point you can execute Java code on the server, and potentially add components to the ajax target to be re-rendered. To do it manually, from js, you can hook into wicket's system by printing out getCallbackScript().toString() to a attribute on a wicket component, which you'll then be able to access from js. Calling this url from js manually with wicket's wicketAjaxGet from wicket-ajax.js. Check out the mailing list for lot's of conversation on this topic: http://www.nabble.com/Wicket-and-javascript-ts24336438.html#a24336438 | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162911",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23486/"
]
} |
162,936 | I'm writing a GUI in C#, Visual Studio 2008, using the Designer and WinForms. I've got a ComboBox control, and I'd like it to only allow to select from the provided options and not to accept a user-entered string. It doesn't appear to have a ReadOnly property, and disabling it hinders the readability of the control (as well as disallowing user-selection). | Set DropDownStyle to "DropDownList" | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/162936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24529/"
]
} |
162,941 | I know this is a really basic question, but I've just started with some basic C++ programming after coding a few projects with high-level languages. Basically I have three questions: Why use pointers over normal variables? When and where should I use pointers? How do you use pointers with arrays? | Why use pointers over normal variables? Short answer is: Don't. ;-) Pointers are to be used where you can't use anything else. It is either because the lack of appropriate functionality, missing data types or for pure perfomance. More below... When and where should I use pointers? Short answer here is: Where you cannot use anything else. In C you don't have any support for complex datatypes such as a string. There are also no way of passing a variable "by reference" to a function. That's where you have to use pointers. Also you can have them to point at virtually anything, linked lists, members of structs and so on. But let's not go into that here. How do you use pointers with arrays? With little effort and much confusion. ;-) If we talk about simple data types such as int and char there is little difference between an array and a pointer.These declarations are very similar (but not the same - e.g., sizeof will return different values): char* a = "Hello";char a[] = "Hello"; You can reach any element in the array like this printf("Second char is: %c", a[1]); Index 1 since the array starts with element 0. :-) Or you could equally do this printf("Second char is: %c", *(a+1)); The pointer operator (the *) is needed since we are telling printf that we want to print a character. Without the *, the character representation of the memory address itself would be printed. Now we are using the character itself instead. If we had used %s instead of %c, we would have asked printf to print the content of the memory address pointed to by 'a' plus one (in this example above), and we wouldn't have had to put the * in front: printf("Second char is: %s", (a+1)); /* WRONG */ But this would not have just printed the second character, but instead all characters in the next memory addresses, until a null character (\0) were found. And this is where things start to get dangerous. What if you accidentally try and print a variable of the type integer instead of a char pointer with the %s formatter? char* a = "Hello";int b = 120;printf("Second char is: %s", b); This would print whatever is found on memory address 120 and go on printing until a null character was found. It is wrong and illegal to perform this printf statement, but it would probably work anyway, since a pointer actually is of the type int in many environments. Imagine the problems you might cause if you were to use sprintf() instead and assign this way too long "char array" to another variable, that only got a certain limited space allocated. You would most likely end up writing over something else in the memory and cause your program to crash (if you are lucky). Oh, and if you don't assign a string value to the char array / pointer when you declare it, you MUST allocate sufficient amount of memory to it before giving it a value. Using malloc, calloc or similar. This since you only declared one element in your array / one single memory address to point at. So here's a few examples: char* x;/* Allocate 6 bytes of memory for me and point x to the first of them. */x = (char*) malloc(6);x[0] = 'H';x[1] = 'e';x[2] = 'l';x[3] = 'l';x[4] = 'o';x[5] = '\0';printf("String \"%s\" at address: %d\n", x, x);/* Delete the allocation (reservation) of the memory. *//* The char pointer x is still pointing to this address in memory though! */free(x);/* Same as malloc but here the allocated space is filled with null characters!*/x = (char *) calloc(6, sizeof(x));x[0] = 'H';x[1] = 'e';x[2] = 'l';x[3] = 'l';x[4] = 'o';x[5] = '\0';printf("String \"%s\" at address: %d\n", x, x);/* And delete the allocation again... */free(x);/* We can set the size at declaration time as well */char xx[6];xx[0] = 'H';xx[1] = 'e';xx[2] = 'l';xx[3] = 'l';xx[4] = 'o';xx[5] = '\0';printf("String \"%s\" at address: %d\n", xx, xx); Do note that you can still use the variable x after you have performed a free() of the allocated memory, but you do not know what is in there. Also do notice that the two printf() might give you different addresses, since there is no guarantee that the second allocation of memory is performed in the same space as the first one. | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/162941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
} |
162,960 | So, I've been living with my cvs repositories for some time. Though there is a thing I miss - if i rename a file that is already in repository, I need to delete the one with old name from there and add the new one. Hence, I loose all my change-history. And sometimes there's a need to rename a file in alredy existing project. From what I saw, cvs/svn can't handle something like this, or am I wrong? If not, what other source control system would you recommend, that allows the renaming of files? | Subversion can do this, but you have to do it with svn move <oldfile> <newfile> Edit: And in this decade, we do git mv <oldfile> <newfile> , or just use mv and git usually figures it out on its own. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/162960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
]
} |
163,009 | If I open a file using urllib2, like so: remotefile = urllib2.urlopen('http://example.com/somefile.zip') Is there an easy way to get the file name other then parsing the original URL? EDIT: changed openfile to urlopen... not sure how that happened. EDIT2: I ended up using: filename = url.split('/')[-1].split('#')[0].split('?')[0] Unless I'm mistaken, this should strip out all potential queries as well. | Did you mean urllib2.urlopen ? You could potentially lift the intended filename if the server was sending a Content-Disposition header by checking remotefile.info()['Content-Disposition'] , but as it is I think you'll just have to parse the url. You could use urlparse.urlsplit , but if you have any URLs like at the second example, you'll end up having to pull the file name out yourself anyway: >>> urlparse.urlsplit('http://example.com/somefile.zip')('http', 'example.com', '/somefile.zip', '', '')>>> urlparse.urlsplit('http://example.com/somedir/somefile.zip')('http', 'example.com', '/somedir/somefile.zip', '', '') Might as well just do this: >>> 'http://example.com/somefile.zip'.split('/')[-1]'somefile.zip'>>> 'http://example.com/somedir/somefile.zip'.split('/')[-1]'somefile.zip' | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/163009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6007/"
]
} |
163,022 | I'd like to do some basic profiling of my code, but found that the DateTime.Now in C# only have a resolution of about 16 ms. There must be better time keeping constructs that I haven't yet found. | Here is a sample bit of code to time an operation: Dim sw As New Stopwatch()sw.Start()//Insert Code To Timesw.Stop()Dim ms As Long = sw.ElapsedMillisecondsConsole.WriteLine("Total Seconds Elapsed: " & ms / 1000) EDIT: And the neat thing is that it can resume as well. Stopwatch sw = new Stopwatch();foreach(MyStuff stuff in _listOfMyStuff){ sw.Start(); stuff.DoCoolCalculation(); sw.Stop();}Console.WriteLine("Total calculation time: {0}", sw.Elapsed); The System.Diagnostics.Stopwatch class will use a high-resolution counter if one is available on your system. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/163022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2973/"
]
} |
163,058 | In a C++ function I need the compiler to choose a different block if it is compiling for a 64 bit architecture. I know a way to do it for MSVC++ and g++, so I'll post it as an answer. However I would like to know if there is a better way (more elegant that would work for all compilers/all 64 bits architectures). If there is not a better way, what other predefined macros should I look for in order to be compatible with other compiler/architectures? | This works for MSVC++ and g++ : #if defined(_M_X64) || defined(__amd64__) // code...#endif | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5861/"
]
} |
163,071 | The Law of Demeter indicates that you should only speak to objects that you know about directly. That is, do not perform method chaining to talk to other objects. When you do so, you are establishing improper linkages with the intermediary objects, inappropriately coupling your code to other code. That's bad. The solution would be for the class you do know about to essentially expose simple wrappers that delegate the responsibility to the object it has the relationship with. That's good. But, that seems to result in the class having low cohesion . No longer is it simply responsible for precisely what it does, but it also has the delegates that in a sense, making the code less cohesive by duplicating portions of the interface of its related object. That's bad. Does it really result in lowering cohesion? Is it the lesser of two evils? Is this one of those gray areas of development, where you can debate where the line is, or are there strong, principled ways of making a decision of where to draw the line and what criteria you can use to make that decision? | Grady Booch in "Object Oriented Analysis and Design": "The idea of cohesion also comes from structured design. Simply stated, cohesion measures the degree of connectivity among the elements of a single module (and for object-oriented design, a single class or object). The least desirable form of cohesion is coincidental cohesion, in which entirely unrelated abstractions are thrown into the same class or module. For example, consider a class comprising the abstractions of dogs and spacecraft, whose behaviors are quite unrelated. The most desirable form of cohesion is functional cohesion, in which the elements of a class or module all work together to provide some well-bounded behavior. Thus, the class Dog is functionally cohesive if its semantics embrace the behavior of a dog, the whole dog, and nothing but the dog." Subsitute Dog with Customer in the above and it might be a bit clearer. So the goal is really just to aim for functional cohesion and to move away from coincidental cohesion as much as possible. Depending on your abstractions, this may be simple or could require some refactoring. Note cohesion applies just as much to a "module" than to a single class, ie a group of classes working together. So in this case the Customer and Order classes still have decent cohesion because they have this strong relationshhip, customers create orders, orders belong to customers. Martin Fowler says he'd be more comfortable calling it the "Suggestion of Demeter" (see the article Mocks aren't stubs ): "Mockist testers do talk more about avoiding 'train wrecks' - method chains of style of getThis().getThat().getTheOther(). Avoiding method chains is also known as following the Law of Demeter. While method chains are a smell, the opposite problem of middle men objects bloated with forwarding methods is also a smell. (I've always felt I'd be more comfortable with the Law of Demeter if it were called the Suggestion of Demeter .)" That sums up nicely where I'm coming from: it is perfectly acceptable and often necessary to have a lower level of cohesion than the strict adherence to the "law" might require. Avoid coincidental cohesion and aim for functional cohesion, but don't get hung up on tweaking where needed to fit in more naturally with your design abstraction. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/163071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10737/"
]
} |
163,079 | Is there a tool to migrate an SQLite database to SQL Server (both the structure and data)? | SQLite does have a .dump option to run at the command line. Though I prefer to use the SQLite Database Browser application for managing SQLite databases. You can export the structure and contents to a .sql file that can be read by just about anything. File > Export > Database to SQL file. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7793/"
]
} |
163,092 | In Ruby you can easily set a default value for a variable x ||= "default" The above statement will set the value of x to "default" if x is nil or false Is there a similar shortcut in PHP or do I have to use the longer form: $x = (isset($x))? $x : "default"; Are there any easier ways to handle this in PHP? | As of PHP 5.3 you can use the ternary operator while omitting the middle argument: $x = $x ?: 'default'; | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163092",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/796/"
]
} |
163,104 | Is there any way for the main form to be able to intercept events firing on a subcontrol on a user control? I've got a custom user-control embedded in the main Form of my application. The control contains various subcontrols that manipulate data, which itself is displayed by other controls on the main form. What I'd like is if the main form could be somehow informed when the user changes subcontrols, so I could update the data and the corresponding display elsewhere. Right now, I am cheating. I have a delegate hooked up to the focus-leaving event of the subcontrols. This delegate changes a property of the user-control I'm not using elsewhere (in this cause, CausesValidation). I then have a delegate defined on the main form for when the CausesValidation property of the user control changes, which then directs the app to update the data and display. A problem arises because I also have a delegate set up for when focus leaves the user-control, because I need to validate the fields in the user-control before I can allow the user to do anything else. However, if the user is just switching between subcontrols, I don't want to validate, because they might not be done editing. Basically, I want the data to update when the user switches subcontrols OR leaves the user control, but not validate. When the user leaves the control, I want to update AND validate. Right now, leaving the user-control causes validation to fire twice. | The best practice would be to expose events on the UserControl that bubble the events up to the parent form. I have gone ahead and put together an example for you. Here is a description of what this example provides. UserControl1 Create a UserControl with TextBox1 Register a public event on the UserControl called ControlChanged Within the UserControl register an event handler for the TextBox1 TextChangedEvent Within the TextChangeEvent handler function I call the ControlChanged event to bubble to the parent form Form1 Drop an instance of UserControl1 on the designer Register an event handler on UserControl1 for MouseLeave and for ControlChanged Here is a screenshot illustrating that the ControlChanged event that I defined on the UserControl is available through the UX in Visual Studio on the parent Windows form. | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24529/"
]
} |
163,162 | I am trying to use the Directory.GetFiles() method to retrieve a list of files of multiple types, such as mp3 's and jpg 's. I have tried both of the following with no luck: Directory.GetFiles("C:\\path", "*.mp3|*.jpg", SearchOption.AllDirectories);Directory.GetFiles("C:\\path", "*.mp3;*.jpg", SearchOption.AllDirectories); Is there a way to do this in one call? | For .NET 4.0 and later, var files = Directory.EnumerateFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg")); For earlier versions of .NET, var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg")); edit: Please read the comments. The improvement that Paul Farry suggests, and the memory/performance issue that Christian.K points out are both very important. | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/163162",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
]
} |
163,183 | I'm encountering some peculiarities with LINQ to SQL. With a relatively simple query, I want to select some fields, but have the date fields formatted as strings, which I first achieved like this: var list = dataContext.MyLists.Single(x => x.ID == myId); var items = from i in list.MyItems select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; Later on I tried the following query, which is exactly the same, except I'm querying straight from my dataContext, rather than an element in my first query: var items = from i in dataContext.MyLists select new { i.ID, i.Sector, i.Description, CompleteDate = i.CompleteDate.HasValue ? i.CompleteDate.Value.ToShortDateString() : "", DueDate = i.DueDate.HasValue ? i.DueDate.Value.ToShortDateString() : "" }; The first one runs fine, yet the second query yields a: Could not translate expression '...' into SQL and could not treat it as a local expression. If I remove the lines that Format the date, it works fine. If I remove the .HasValue check it also works fine, until there are null values. Any ideas? Anthony | I'd do the SQL part without doing the formatting, then do the formatting on the client side: var items = list.MyItems.Select(item => new { item.ID, item.Sector, item.Description, item.CompleteDate, item.DueDate }) .AsEnumerable() // Don't do the next bit in the DB .Select(item => new { item.ID, item.Sector, item.Description, CompleteDate = FormatDate(CompleteDate), DueDate = FormatDate(DueDate) });static string FormatDate(DateTime? date){ return date.HasValue ? date.Value.ToShortDateString() : ""} | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163183",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
]
} |
163,246 | In Oracle, I can re-create a view with a single statement, as shown here: CREATE OR REPLACE VIEW MY_VIEW ASSELECT SOME_FIELDFROM SOME_TABLEWHERE SOME_CONDITIONS As the syntax implies, this will drop the old view and re-create it with whatever definition I've given. Is there an equivalent in MSSQL (SQL Server 2005 or later) that will do the same thing? | The solutions above though they will get the job done do so at the risk of dropping user permissions. I prefer to do my create or replace views or stored procedures as follows. IF NOT EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[vw_myView]')) EXEC sp_executesql N'CREATE VIEW [dbo].[vw_myView] AS SELECT ''This is a code stub which will be replaced by an Alter Statement'' as [code_stub]'GOALTER VIEW [dbo].[vw_myView]ASSELECT 'This is a code which should be replaced by the real code for your view' as [real_code]GO | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/163246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
]
} |
163,254 | On a 32-bit CPU, an integer is 4 bytes and a short integer is 2 bytes. If I am writing a C/C++ application that uses many numeric values that will always fit within the provided range of a short integer, is it more efficient to use 4 byte integers or 2 byte integers? I have heard it suggested that 4 byte integers are more efficient as this fits the bandwidth of the bus from memory to the CPU. However, if I am adding together two short integers, would the CPU package both values in a single pass in parallel (thus spanning the 4 byte bandwidth of the bus)? | Yes, you should definitely use a 32 bit integer on a 32 bit CPU, otherwise it may end up masking off the unused bits (i.e., it will always do the maths in 32 bits, then convert the answer to 16 bits) It won't do two 16 bit operations at once for you, but if you write the code yourself and you're sure it won't overflow, you can do it yourself. Edit : I should add that it also depends somewhat on your definition of "efficient". While it will be able to do 32-bit operations more quickly, you will of course use twice as much memory. If these are being used for intermediate calculations in an inner loop somewhere, then use 32-bit. If, however, you're reading this from disk, or even if you just have to pay for a cache miss, it may still work out better to use 16-bit integers. As with all optimizations, there's only one way to know: profile it . | {
"score": 5,
"source": [
"https://Stackoverflow.com/questions/163254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20133/"
]
} |
163,302 | I'm trying to have the modrewrite rules skip the directory vip . I've tried a number of things as you can see below, but to no avail. # BEGIN WordPress<IfModule mod_rewrite.c>RewriteEngine OnRewriteBase /#RewriteRule ^vip$ - [PT]RewriteRule ^vip/.$ - [PT]#RewriteCond %{REQUEST_URI} !/vip RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule . /index.php [L]</IfModule># END WordPress How do I get modrewrite to entirely ignore the /vip/ directory so that all requests pass directly to the folder? Update: As points of clarity: It's hosted on Dreamhost The folders are within a wordpress directory the /vip/ folder contains a webdav .htaccess etc (though I dont think this is important | Try putting this before any other rules. RewriteRule ^vip - [L,NC] It will match any URI beginning vip . The - means do nothing. The L means this should be last rule; ignore everything following. The NC means no-case (so "VIP" is also matched). Note that it matches anything beginning vip . The expression ^vip$ would match vip but not vip/ or vip/index.html . The $ may have been your downfall. If you really want to do it right, you might want to go with ^vip(/|$) so you don't match vip-page.html | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/163302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24557/"
]
} |
163,336 | Say for example you just queried a database and you recieved this 2D array. $results = array( array('id' => 1, 'name' => 'red' , 'spin' => 1), array('id' => 2, 'name' => 'green', 'spin' => -1), array('id' => 3, 'name' => 'blue' , 'spin' => .5)); I often find myself writing loops like this. foreach($results as $result) $names[] = $result['name']; My questions is does there exist a way to get this array $names without using a loop? Using callback functions count as using a loop. Here is a more generic example of getting every field. foreach($results as $result) foreach($result as $key => $value) $fields[$key][] = $value; | As of June 20th in PHP-5.5 there is a new function array_column For example: $records = array( array( 'id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe' ), array( 'id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith' ), array( 'id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones' ), array( 'id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Doe' ));$firstNames = array_column($records, 'first_name');print_r($firstNames); Will return Array( [0] => John [1] => Sally [2] => Jane [3] => Peter) There are even more examples in the above mentioned link. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163336",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17919/"
]
} |
163,360 | I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java String flavor and pasted it into Java code, it does not work. The following class prints false : public class RegexFoo { public static void main(String[] args) { String regex = "\\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]"; String text = "http://google.com"; System.out.println(IsMatch(text,regex));} private static boolean IsMatch(String s, String pattern) { try { Pattern patt = Pattern.compile(pattern); Matcher matcher = patt.matcher(s); return matcher.matches(); } catch (RuntimeException e) { return false; } } } Does anyone know what I am doing wrong? | Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder. String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; This works too: String regex = "\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]"; Note: String regex = "<\\b(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // matches <http://google.com>String regex = "<^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]>"; // does not match <http://google.com> | {
"score": 8,
"source": [
"https://Stackoverflow.com/questions/163360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
} |
163,365 | Let's say that for some reason you need to write a macro: MACRO(X,Y) . (Let's assume there's a good reason you can't use an inline function.) You want this macro to emulate a call to a function with no return value. Example 1: This should work as expected. if (x > y) MACRO(x, y);do_something(); Example 2: This should not result in a compiler error. if (x > y) MACRO(x, y);else MACRO(y - x, x - y); Example 3: This should not compile. do_something();MACRO(x, y)do_something(); The naïve way to write the macro is like this: #define MACRO(X,Y) \cout << "1st arg is:" << (X) << endl; \cout << "2nd arg is:" << (Y) << endl; \cout << "Sum is:" << ((X)+(Y)) << endl; This is a very bad solution which fails all three examples, and I shouldn't need to explain why. Ignore what the macro actually does, that's not the point. Now, the way I most often see macros written is to enclose them in curly braces, like this: #define MACRO(X,Y) \{ \ cout << "1st arg is:" << (X) << endl; \ cout << "2nd arg is:" << (Y) << endl; \ cout << "Sum is:" << ((X)+(Y)) << endl; \} This solves example 1, because the macro is in one statement block. But example 2 is broken because we put a semicolon after the call to the macro. This makes the compiler think the semicolon is a statement by itself, which means the else statement doesn't correspond to any if statement! And lastly, example 3 compiles OK, even though there is no semicolon, because a code block doesn't need a semicolon. Is there a way to write a macro so that it pass all three examples? Note: I am submitting my own answer as part of the accepted way of sharing a tip , but if anyone has a better solution feel free to post it here, it may get more votes than my method. :) | Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once. If it must be a macro, a while loop (already suggested) will work, or you can try the comma operator: #define MACRO(X,Y) \ ( \ (cout << "1st arg is:" << (X) << endl), \ (cout << "2nd arg is:" << (Y) << endl), \ (cout << "3rd arg is:" << ((X) + (Y)) << endl), \ (void)0 \ ) The (void)0 causes the statement to evaluate to one of void type, and the use of commas rather than semicolons allows it to be used inside a statement, rather than only as a standalone. I would still recommend an inline function for a host of reasons, the least of which being scope and the fact that MACRO(a++, b++) will increment a and b twice. | {
"score": 7,
"source": [
"https://Stackoverflow.com/questions/163365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18511/"
]
} |
163,382 | I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please? public class Test { public static void main(String args[]) { Test t = new Test(); t.testT(null); } public <T extends Test> void testT(Class<T> type) { Class<T> testType = type == null ? Test.class : type; //Error here System.out.println(testType); }} Type mismatch: cannot convert from Class<capture#1-of ? extends Test> to Class<T> By casting Test.class to Class<T> this compiles with an Unchecked cast warning and runs perfectly. | The reason is that Test.class is of the type Class<Test>. You cannot assign a reference of type Class<Test> to a variable of type Class<T> as they are not the same thing. This, however, works: Class<? extends Test> testType = type == null ? Test.class : type; The wildcard allows both Class<T> and Class<Test> references to be assigned to testType. There is a ton of information about Java generics behavior at Angelika Langer Java Generics FAQ . I'll provide an example based on some of the information there that uses the Number class heirarchy Java's core API. Consider the following method: public <T extends Number> void testNumber(final Class<T> type) This is to allow for the following statements to be successfully compile: testNumber(Integer.class);testNumber(Number.class); But the following won't compile: testNumber(String.class); Now consider these statements: Class<Number> numberClass = Number.class;Class<Integer> integerClass = numberClass; The second line fails to compile and produces this error Type mismatch: cannot convert from Class<Number> to Class<Integer> . But Integer extends Number , so why does it fail? Look at these next two statements to see why: Number anumber = new Long(0);Integer another = anumber; It is pretty easy to see why the 2nd line doesn't compile here. You can't assign an instance of Number to a variable of type Integer because there is no way to guarantee that the Number instance is of a compatible type. In this example the Number is actually a Long , which certainly can't be assigned to an Integer . In fact, the error is also a type mismatch: Type mismatch: cannot convert from Number to Integer . The rule is that an instance cannot be assigned to a variable that is a subclass of the type of the instance as there is no guarantee that is is compatible. Generics behave in a similar manner. In the generic method signature, T is just a placeholder to indicate what the method allows to the compiler. When the compiler encounters testNumber(Integer.class) it essentially replaces T with Integer . Wildcards add additional flexibility, as the following will compile: Class<? extends Number> wildcard = numberClass; Since Class<? extends Number> indicates any type that is a Number or a subclass of Number this is perfectly legal and potentially useful in many circumstances. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6414/"
]
} |
163,407 | Is there a way to use Enum values inside a JSP without using scriptlets. e.g. package com.example;public enum Direction { ASC, DESC} so in the JSP I want to do something like this <c:if test="${foo.direction ==<% com.example.Direction.ASC %>}">... | You could implement the web-friendly text for a direction within the enum as a field: <%@ page import="com.example.Direction" %>...<p>Direction is <%=foo.direction.getFriendlyName()%></p><% if (foo.direction == Direction.ASC) { %><p>That means you're going to heaven!</p><% } %> but that mixes the view and the model, although for simple uses it can be view-independent ("Ascending", "Descending", etc). Unless you don't like putting straight Java into your JSP pages, even when used for basic things like comparisons. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3332/"
]
} |
163,434 | There's a school of thought that null values should not be allowed in a relational database. That is, a table's attribute (column) should not allow null values. Coming from a software development background, I really don't understand this. It seems that if null is valid within the context of the attribute, then it should be allowed. This is very common in Java where object references are often null. Not having an extensive database experience, I wonder if I'm missing something here. | Nulls are negatively viewed from the perspective of database normalization. The idea being that if a value can be nothing, then you really should split that out into another sparse table such that you don't require rows for items which have no value. It's an effort to make sure all data is valid and valued. In some cases having a null field is useful, though, especially when you want to avoid yet another join for performance reasons (although this shouldn't be an issue if the database engine is setup properly, except in extraordinary high performance scenarios.) -Adam | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24396/"
]
} |
163,497 | Is it possible to run a ruby application as a Windows Service? I see that there is a related question which discusses running a Java Application as a Windows Service , how can you do this with a Ruby application? | Check out the following library: Win32Utils . You can create a simple service that you can start/stop/restart at your leisure. I'm currently using it to manage a Mongrel instance for a Windows hosted Rails app and it works flawlessly. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163497",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19784/"
]
} |
163,517 | Are there any good resources (books, authoritative guides, etc.) for design patterns or other best practices for software that includes financial accounting features? Specifically, where is good information about handling issues like the following: Internal representations of money quantities Internal representations of accounts, journals, and other records Reconciling inconsistencies (either automatically or via user action) Handling ends of accounting periods (daily, weekly, monthly) Designing UIs and printed financial reports that make sense to businesspeople Note: "Authoritative" or otherwise widely-accepted information is what we're looking for here. Otherwise, this will just turns into a big list of anecdotes of all the things people have tried, making the topic very subjective. | Martin Fowler's Analysis Patterns covers some of those topics. | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1175/"
]
} |
163,531 | I am creating an installer for an ASP.Net website using WiX. How do you set the ASP.Net version in IIS using WiX? | We use this: First determine the .Net framework root directory from the registry: <Property Id="FRAMEWORKROOT"> <RegistrySearch Id="FrameworkRootDir" Root="HKLM" Key="SOFTWARE\Microsoft\.NETFramework" Type="directory" Name="InstallRoot" /></Property> Then, inside the component that installs your website in IIS: <!-- Create and configure the virtual directory and application. --><Component Id='WebVirtualDirComponent' Guid='{GUID}' Permanent='no'> <iis:WebVirtualDir Id='WebVirtualDir' Alias='YourAlias' Directory='InstallDir' WebSite='DefaultWebSite' DirProperties='DirProperties'> <iis:WebApplication Id='WebApplication' Name='YourAppName' WebAppPool='AppPool'> <!-- Required to run the application under the .net 2.0 framework --> <iis:WebApplicationExtension Extension="config" CheckPath="yes" Script="yes" Executable="[FRAMEWORKROOT]v2.0.50727\aspnet_isapi.dll" Verbs="GET,HEAD,POST" /> <iis:WebApplicationExtension Extension="resx" CheckPath="yes" Script="yes" Executable="[FRAMEWORKROOT]v2.0.50727\aspnet_isapi.dll" Verbs="GET,HEAD,POST" /> <iis:WebApplicationExtension Extension="svc" CheckPath="no" Script="yes" Executable="[FRAMEWORKROOT]v2.0.50727\aspnet_isapi.dll" Verbs="GET,HEAD,POST" /> </iis:WebApplication> </iis:WebVirtualDir></Component> For an x64 installer ( THIS IS IMPORTANT )Add Win64='yes' to the registry search, because the 32 bits environment on a 64 bits machine has a different registry hive (and a different frameworkroot) <RegistrySearch Id="FrameworkRootDir" Root="HKLM" Key="SOFTWARE\Microsoft\.NETFramework" Type="directory" Name="InstallRoot" Win64='yes' /> | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1865/"
]
} |
163,538 | I am debugging with breakpoints and I realize the assert call? I thought it was only for unit tests. What does it do more than breakpoint? Since I can breakpoint, why should I use Assert? | In a debug compilation, Assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true. If you compile in Release, all Debug.Assert 's are automatically left out. | {
"score": 9,
"source": [
"https://Stackoverflow.com/questions/163538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21386/"
]
} |
163,542 | If I do the following: import subprocessfrom cStringIO import StringIOsubprocess.Popen(['grep','f'],stdout=subprocess.PIPE,stdin=StringIO('one\ntwo\nthree\nfour\nfive\nsix\n')).communicate()[0] I get: Traceback (most recent call last): File "<stdin>", line 1, in ? File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 533, in __init__ (p2cread, p2cwrite, File "/build/toolchain/mac32/python-2.4.3/lib/python2.4/subprocess.py", line 830, in _get_handles p2cread = stdin.fileno()AttributeError: 'cStringIO.StringI' object has no attribute 'fileno' Apparently a cStringIO.StringIO object doesn't quack close enough to a file duck to suit subprocess.Popen. How do I work around this? | Popen.communicate() documentation: Note that if you want to send data tothe process’s stdin, you need tocreate the Popen object withstdin=PIPE. Similarly, to get anythingother than None in the result tuple,you need to give stdout=PIPE and/orstderr=PIPE too. Replacing os.popen* pipe = os.popen(cmd, 'w', bufsize) # ==> pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin Warning Use communicate() rather thanstdin.write(), stdout.read() orstderr.read() to avoid deadlocks dueto any of the other OS pipe buffersfilling up and blocking the childprocess. So your example could be written as follows: from subprocess import Popen, PIPE, STDOUTp = Popen(['grep', 'f'], stdout=PIPE, stdin=PIPE, stderr=STDOUT) grep_stdout = p.communicate(input=b'one\ntwo\nthree\nfour\nfive\nsix\n')[0]print(grep_stdout.decode())# -> four# -> five# -> On Python 3.5+ (3.6+ for encoding ), you could use subprocess.run , to pass input as a string to an external command and get its exit status, and its output as a string back in one call: #!/usr/bin/env python3from subprocess import run, PIPEp = run(['grep', 'f'], stdout=PIPE, input='one\ntwo\nthree\nfour\nfive\nsix\n', encoding='ascii')print(p.returncode)# -> 0print(p.stdout)# -> four# -> five# -> | {
"score": 10,
"source": [
"https://Stackoverflow.com/questions/163542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
]
} |
163,550 | Is there a maximum number of characters that can be written to a file using a StreamWriter? Or is there a maximum number of characters that WriteLine() can output? I am trying to write some data to a file but all of the data does not seem to make it. This is the current state of my code: StreamWriter sw = new StreamWriter(pathToFile);foreach (GridViewRow record in gv_Records.Rows){ string recordInfo = "recordInformation"; sw.WriteLine(recordInfo);} | Are you calling StreamWriter.Close() or Flush()? | {
"score": 6,
"source": [
"https://Stackoverflow.com/questions/163550",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
]
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.