I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python?...
488Votes10Comments

Undoing a git rebase

Does anybody know how to easily undo a git rebase? The only way that comes to mind is to go at it manually: git checkout the commit parent to both of the branches then create a temp branch from there cherry-pick all commits by hand replace the branch in which I rebased by the manually-created branch In my current situation this is gonna work because I can easily spot commits from both branches...
I've used the following script to see if a file exists: #!/bin/bash FILE=$1 if [ -f $FILE ]; then echo "File $FILE exists." else echo "File $FILE does not exist." fi What's the correct syntax to use if I only want to check if the file does not exist? #!/bin/bash FILE=$1 if [ $FILE does not exist ]; then echo "File $FILE does not exist." fi...
Are there clear rules on when to use each of these when making classes and interfaces and dealing with inheritance?...
I was writing a simple script in the school computer, and committing the changes to Git (in a repo that was in my pendrive, cloned from my computer at home). After several commits I realized I was committing stuff as the root user. Is there any way to change the author of these commits to my name?...
How do I write a switch statement in Ruby?...
How can I convert a String to an int in Java? My String contains only numbers and I want to return the number it represents. For example, given the string "1234" the result should be the number 1234....
What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried: filename = "/my/directory/filename.txt" dir = os.path.dirname(filename) try: os.stat(dir) except: os.mkdir(dir) f = file(filename) Somehow, I missed os.path.exists (thanks kanja, Blair, and Douglas). This is what I have...
Is there a way to empty an array and if so possibly with .remove()? For instance, A = [1,2,3,4]; How can I empty that?...
I have a Git repository which contains a number of subdirectories. Now I have found that one of the subdirectories is unrelated to the other and should be detached to a separate repository. How can I do this while keeping the history of the files within the subdirectory? I guess I could make a clone and remove the unwanted parts of each clone, but I suppose this would give me the complete tree when...
If I create a global variable in one function, how can I use that variable in another function? Do I need to store the global variable in a local variable of the function which needs its access?...
My initial commit contained some log files. I've added *log to my .gitignore, and now I want to remove the log files from my repository. git rm mylogfile.log will remove a file from the repository, but will also remove it from the local file system. How can I remove this file from the repo without deleting my local copy of the file?...
I have an Android Activity, with two elements: EditText ListView When my Activity starts, the EditText immediately has input focus (flashing cursor). I don't want any control to have input focus at startup. I tried: EditText.setSelected(false); No luck. How can I convince the EditText to not select itself when the Activity starts?...
What do atomic and nonatomic mean in property declarations? @property(nonatomic, retain) UITextField *userName; @property(atomic, retain) UITextField *userName; @property(retain) UITextField *userName; What is the operational difference between these three?...
How do I convert a string to a byte[] in .NET (C#)? Also, why should encoding be taken into consideration? Can't I simply get what bytes the string has been stored in? Why is there a dependency on character encodings?...
How do you disable autocomplete in the major browsers for a specific input (or form field)?...
I would like to select the <li> element that is a parent (which immediately precedes the anchor tag, if that helps…) according to some attribute of the anchor tag. i.e. my CSS would be something like this: li < a.active { property: value; } Obviously there are ways of doing this with JavaScript but I'm hoping that there is some sort of workaround that exists native to CSS 2. The...
I can't find the good old "Add existing frameworks" option. How do I do this? We're talking about Xcode 4 DP2 (in the context of iPhone development, as far as it matters...)....
I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this: /Date(1224043200000)/ From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker...
I'm not that into dynamic programming languages, but I've written my fair share of JavaScript code. I never really got my head around this prototype-based programming, does any one know how this works? var obj = new Object(); // not a functional object obj.prototype.test = function() { alert('Hello?'); }; // this is wrong! function MyObject() {} // a first class functional object MyObject.prototype.test...
How can one parse HTML/XML and extract information from it? This is a General Reference question for the php tag...
The command git add [--all|-A] appears to be identical to git add .. Is this correct? If not, how do they differ?...
How can I change a class of an HTML element in response to an onClick event using JavaScript?...
I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary. I can sort on the keys, but how can I sort based on the values? Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list...
How can a column with a default value be added to an existing table in SQL Server 2000 / SQL Server 2005?...
How can I check the existence of an element in jQuery? The current code that I have is this: if ($(selector).length>0) { // Do something } Is there is a more elegant way to approach this? Perhaps a plugin or a function?...
Someone posted in a comment to another question about the meaning of the explicit keyword in C++. So, what does it mean?...
I've been playing around with the Android SDK, and I am a little unclear on saving an application's state. So given this minor re-tooling of the 'Hello, Android' example: package com.android.hello; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloAndroid extends Activity { /** Called when the activity is first created. */ @Override ...
495Votes11Comments

.prop() vs .attr()

So jQuery 1.6 has the new function prop(). $(selector).click(function(){ //instead of: this.getAttribute('style'); //do i use: $(this).prop('style'); //or: $(this).attr('style'); }) or in this case do they do the same thing? And if I do have to switch to using prop(), all the old attr() calls will break if i switch to 1.6? UPDATE See this fiddle: http://jsfiddle.net/maniator/JpUF2/ The...
Are there any good resources to get started with Node.JS? Any good tutorials, blogs or books? Of course, I have visited its official website http://nodejs.org/, but I didn't think the documentation they have is a good starting point....
I have an already initialized git repo that I added a .gitignore file to, how can I refresh the file index so the files I want ignored get ignored?...
I have two Python dictionaries, and I want to write a single expression that returns these two dictionaries, merged. The update() method would be what I need, if it returned its result instead of modifying a dict in-place. >>> x = {'a':1, 'b': 2} >>> y = {'b':10, 'c': 11} >>> z = x.update(y) >>> print z None >>> x {'a': 1, 'b': 10, 'c': 11} How can I...
How should pip be installed on Windows? Summary of the answers: Depending on your Python version and whether you want to use it inside a virtual environment or not: Starting from Python versions 2.7.9 and 3.4.0, pip is already included in the regular install, see matth's answer below. Check if the path to the Scripts directory inside your Python installation directory is contained in your system's...
Suppose a1, b1, c1, and d1 point to heap memory and my numerical code has the following core loop. const int n=100000; for(int j=0;j<n;j++){ a1[j] += b1[j]; c1[j] += d1[j]; } This loop is executed 10,000 times via another outer for loop. To speed it up, I changed the code to: for(int j=0;j<n;j++){ a1[j] += b1[j]; } for(int j=0;j<n;j++){ c1[j] += d1[j]; } Compiled on...
I know references are syntactic sugar, so code is easier to read and write. But what are the differences? Summary from answers and links below: A pointer can be re-assigned any number of times while a reference can not be re-seated after binding. Pointers can point nowhere (NULL), whereas reference always refer to an object. You can't take the address of a reference like you can with pointers. There's...
I have recently stumbled upon the game 2048. You merge similar tiles by moving them in any of the four directions to make "bigger" tiles. After each move, a new tile appears at random empty position with value of either 2 or 4. The game terminates when all the boxes are filled and there are no moves that can merge tiles, or you create a tile with a value of 2048. One, I need to follow a well-defined...
I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery? I can get all of them like this: $("form :radio") How do I know which one is selected?...
Is it possible, using CSS only, to make the background of an element semi-transparent but have the content (text & images) of the element opaque? I'd like to accomplish this without having the text and the background as two separate elements. When trying: <p style="position:absolute;background-color:green;filter:alpha(opacity=60);opacity:.6;"> <span style="color:white;filter:alpha(opacity=100);opacity:1;">Hello...
337Votes24Comments

Add table row in jQuery

What is the best method in jQuery to add an additional row to a table as the last row? Update Is this acceptable: $('#myTable').append('<tr><td>my data</td><td>more data</td></tr>'); Are there limitations to what you can add to a table like this (such as inputs, selects, number of rows)?...
I would like to grep for a string, but also show the preceding five lines and the following five lines as well as the matched line. I'm scanning for errors in a logfile, and want to see the context. Is it possible?...
I am hoping to make this question and the answers to it the definitive guide to dealing with daylight saving time, in particular for dealing with the actual change overs. If you have anything to add, please do Many systems are dependent on keeping accurate time, the problem is with changes to time due to daylight savings - moving the clock forward or backwards. For instance, one has business rules...
Is there a (unix) shell script to format JSON in human-readable form? Basically, I want it to transform the following: { "foo": "lorem", "bar": "ipsum" } ... into something like this: { "foo": "lorem", "bar": "ipsum" }...
I started some work on a new feature and after coding for a bit, I decided this feature should be on its own branch. How do I move the existing uncommitted changes to a new branch and reset my current one? I want to reset my current branch while preserving existing work on the new feature....
This was bugging me over the weekend: What is a good way to solve those Where's Waldo? ['Wally' outside of North America] puzzles, using Mathematica (image-processing and other functionality)? Here is what I have so far, a function which reduces the visual complexity a little bit by dimming some of the non-red colors: whereIsWaldo[url_] := Module[{waldo, waldo2, waldoMask}, waldo = Import[url]; ...
Is there a way to make the following return true? string title = "ASTRINGTOTEST"; title.Contains("string"); There doesn't seem to be an overload that allows me to set the case sensitivity.. Currently I UPPERCASE them both, but that's just silly. UPDATE The sillyness I refer to is the i18n issues that come with up- and down casing. UPDATE This question is ancient and since then I have realized...
What I am looking for: A way to style one HALF of a character. (In this case, half the letter being transparent) What I have currently searched for and tried (With no luck): Methods for styling half of a character/letter Styling part of a character with CSS or JavaScript Apply CSS to 50% of a character Below is an example of what I am trying to obtain. Does a CSS or JavaScript solution exists...
I need to match all of these opening tags: <p> <a href="foo"> But not these: <br /> <hr class="foo" /> I came up with this and wanted to make sure I've got it right. I am only capturing the a-z. <([a-z]+) *[^/]*?> I believe it says: Find a less-than, then Find (and capture) a-z one or more times, then Find zero or more spaces, then Find any character zero or...
There have been several questions already posted with specific questions about dependency injection, such as when to use it and what frameworks are there for it. However, What is dependency injection and when/why should or shouldn't it be used?...
What does the if __name__ == "__main__": do? # Threading example import time, thread def myfunction(string, sleeptime, lock, *args): while 1: lock.acquire() time.sleep(sleeptime) lock.release() time.sleep(sleeptime) if __name__ == "__main__": lock = thread.allocate_lock() thread.start_new_thread(myfunction, ("Thread #: 1", 2, lock)) thread.start_new_thread(myfunction,...
148Votes14Comments

Appending to array

How do I append to an array in JavaScript?...
Should be trivial, and it might even be in the help, but I can't figure out how to navigate it. How do I indent multiple lines quickly in vi?...
How do I get the website URL? Not the URL as taken from a link. On the loading page, I want to get the full, current URL of the current web page and store its value in a variable....
273Votes18Comments

Cast int to enum in C#

How can an int be cast to an enum in C#?...
336Votes9Comments

Encode URL in JavaScript?

How do you safely encode a URL using JavaScript such that it can be put into a GET string? var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; var myOtherUrl = "http://example.com/index.html?url=" + myUrl; I assume that you need to encode the myUrl variable on that second line?...
How can I view the change history of an individual file in Git, complete with what has changed? I have got as far as: git log -- [filename] which shows me the commit history of the file, but how do I get at the content of each of the changes? I'm trying to make the transition from MS SourceSafe and that used to be a simple right-click → show history....
Say I'm in a Git repository. I delete a file and commit that change. I continue working and make some more commits. Then, I find I need to restore that file. I know I can checkout a file using git checkout HEAD^ foo.bar, but I don't really know when that file was deleted. What would be the quickest way to find the commit that deleted a given filename? What would be the easiest way to get that file...
I have a UILabel with space for two lines of text. Sometimes, when the text is too short, this text is displayed in the vertical center of the label. How do I vertically align the text to always be at the top of the UILabel?...
Eclipse issues warnings when a serialVersionUID is missing. The serializable class Foo does not declare a static final serialVersionUID field of type long What is serialVersionUID and why is it important? Please show an example where missing serialVersionUID will cause a problem....
I am doing some numerical optimization on a scientific application. One thing I noticed is that GCC will optimize the call pow(a,2) by compiling it into a*a, but the call pow(a,6) is not optimized and will actually call the library function pow, which greatly slows down the performance. (In contrast, Intel C++ Compiler, executable icc, will eliminate the library call for pow(a,6).) What I am curious...
What is the best way to copy text to the clipboard? (multi-browser) I have tried: function copyToClipboard(text) { if (window.clipboardData) { // Internet Explorer window.clipboardData.setData("Text", text); } else { unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);...
I have a function foo which makes an Ajax request. How can I return the response from foo? I tried to return the value from the success callback as well as assigning the response to a local variable inside the function and return that one, but none of those ways actually return the response. function foo() { var result; $.ajax({ url: '...', success: function(response) { ...
447Votes23Comments

datetime vs timestamp?

What would you recommend using between a datetime and a timestamp field, and why? (using mysql). I'm working with php on the server side....
I am using Eclipse Android plugins to build a project, but I am getting this error in the console window: [2010-02-03 10:31:14 - androidVNC]Error generating final archive: Debug certificate expired on 1/30/10 2:35 PM! How do I fix it?...
How do I capitalize the first character of a string, but not change the case of any of the other letters? For example: this is a test -> This is a test the Eiffel Tower -> The Eiffel Tower /index.html -> /index.html...
I generated two matrices of 1000 x 1000: First Matrix: O and #. Second Matrix: O and B. Using the following code, the first matrix took 8.52 seconds to complete: Random r = new Random(); for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { if(r.nextInt(4) == 0) { System.out.print("O"); } else { System.out.print("#"); } } ...
I've always been one to simply use: List<String> names = new ArrayList<String>(); I use the interface as the type name for portability, so that when I ask questions such as these I can rework my code. When should LinkedList be used over ArrayList and vice-versa?...
I would like to know how to delete a commit. By "delete", I mean it is as if I didn't make that commit, and when I do a push in the future, my changes will not push to the remote branch. I read git help, and I think the command I should use is git reset --hard HEAD. Is this correct?...
I am trying to generate a random integer with Java, but random in a specific range. For example, my range is 5-10, meaning that 5 is the smallest possible value the random number can take, and 10 is the biggest. Any other number in between these numbers is possible to be a value, too. In Java, there is a method random() in the Math class, which returns a double value between 0.0 and 1.0. In the class...
In SQL Server, it's possible to insert into a table using a SELECT statement: INSERT INTO Table (col, col2, col3) SELECT col, col2, col3 FROM other_table WHERE sql = 'cool' Is it also possible to update via a SELECT? I have a temporary table containing the values, and would like to update another table using those values. Perhaps something like this: UPDATE Table SET col1, col2 SELECT col1,...
Optimizing SQLite is tricky. Bulk-insert performance of a C application can vary from 85 inserts-per-second to over 96 000 inserts-per-second! Background: We are using SQLite as part of a desktop application. We have large amounts of configuration data stored in XML files that are parsed and loaded into an SQLite database for further processing when the application is initialized. SQLite is ideal...
How can an email address be validated in JavaScript?...
I have made some changes to a file which has been committed a few times as part of a group of files, but now want to reset/revert the changes on it back to a previous version. I have done a git log along with a git diff to find the revision I need, but just have no idea how to get the file back to its former state in the past....
What's the best way of checking if an object property in JavaScript is undefined?...
I have a layout similar to this: <div id="..."><img src="..."></div> and would like to use a jQuery selector to select the child img inside the div on click. To get the div, I've got this selector: $(this) How can I get the child img using a selector?...
786Votes30Comments

Split a string in C++?

What's the most elegant way to split a string in C++? The string can be assumed to be composed of words separated by whitespace. (Note that I'm not interested in C string functions or that kind of character manipulation/access. Also, please give precedence to elegance over efficiency in your answer.) The best solution I have right now is: #include <iostream> #include <sstream> #include...
I just had an interview, and I was asked to create a memory leak with Java. Needless to say I felt pretty dumb having no clue on how to even start creating one. What would an example be?...
What's the cleanest, most effective way to validate decimal numbers in JavaScript? Bonus points for: Clarity. Solution should be clean and simple. Cross-platform. Test cases: 01. IsNumeric('-1') => true 02. IsNumeric('-1.5') => true 03. IsNumeric('0') => true 04. IsNumeric('0.42') => true 05. IsNumeric('.42') => true 06. IsNumeric('99,999') => false 07. IsNumeric('0x89f')...
300Votes13Comments

Create ArrayList from array

I have an array that is initialized like: Element[] array = {new Element(1), new Element(2), new Element(3)}; I would like to convert this array into an object of the ArrayList class. ArrayList<Element> arraylist = ???;...
I have a repo (origin) on a USB key that I cloned on my hard drive (local). I moved "origin" to a NAS and successfully tested cloning it from here. I would like to know if I can change the URI of "origin" in the settings of "local" so it will now pull from the NAS, and not from the USB key. For now, I can see two solutions: push everything to the usb-orign, and copy it to the NAS again (implies...
Possible Duplicate: How do I iterate over each Entry in a Collection Map? What's the best way to iterate over the items in a HashMap?...
I created a local branch which I want to 'push' upstream. There is a similar question here on Stack Overflow on how to track a newly created remote branch. However, my workflow is slightly different. First I want to create a local branch, and I will only push it upstream when I'm satisfied and want to share my branch. How would I do that? (my google searches did not seem to come up with anything). How...
What command can be used to check if a directory does or does not exist, within a shell script?...
I tried looking for a an answer to this, but couldn't find any which address this specific need. Which is weird. I want to be able to do the following: create a local branch based on some other (remote or local) branch (via git branch or git checkout -b) push the local branch to remote repo (publish), but make it trackable so git pull and git push will work immediately. How do I do that? EDIT:...
550Votes20Comments

Undo a Git merge?

Within my master branch, I did a git merge some-other-branch locally, but never pushed the changes to origin master. I didn't mean to merge, so I'd like to undo it. When doing a git status after my merge, I was getting this message: # On branch master # Your branch is ahead of 'origin/master' by 4 commits. Based upon some instructions I found, I tried running git revert HEAD -m 1 but now I'm...
I've been wondering whether there is a good "git export" solution that creates a copy of a tree without the .git repository directory. There are at least three methods I know of: git clone followed by removing the .git repository directory. git checkout-index alludes to this functionality but starts with "Just read the desired tree into the index..." which I'm not entirely sure how to do. git-export...
I have an EditText and a Button in my layout. After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard. I assume that there's a simple, one- or two-liner to make this happen. Where can I find an example of it?...
I am the developer of some family tree software (written in C++ and Qt). I had no problems until one of my customers mailed me a bug report. The problem is that the customer has two children with their own daughter, and, as a result, he can't use my software because of errors. Those errors are the result of my various assertions and invariants about the family graph being processed (for example, after...
In Swing, the password field has a getPassword() (returns char[]) method instead of the usual getText() (returns String) method. Similarly, I have come across a suggestion not to use String to handle passwords. Why does String pose a threat to security when it comes to passwords? It feels inconvenient to use char[]....
How can I make two decorators in Python that would do the following? @makebold @makeitalic def say(): return "Hello" which should return <b><i>Hello</i></b> I'm not trying to make HTML this way in a real application, just trying to understand how decorators and decorator chaining works....
How can I call an external command (as if I'd typed it at the Unix shell or Windows command prompt) from within a Python script?...
I would like to upload a file asynchronously with jQuery. This is my HTML: <span>File</span> <input type="file" id="file" name="file" size="10"/> <input id="uploadbutton" type="button" value="Upload"/> And here my JavaScript code: $(document).ready(function () { $("#uploadbutton").click(function () { var filename = $("#file").val(); $.ajax({ ...
When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well: 1. event.preventDefault() $('a').click(function (e) { // custom handling here e.preventDefault(); }); 2. return false $('a').click(function () { // custom handling here return false; }); Is...
What is the difference between using call and apply to invoke a function? var func = function(){ alert('hello!'); }; func.apply(); vs func.call(); Are there performance differences between the two methods? When is it best to use call over apply and vice versa?...
I'd like to move the last several commits I've made to master to a new branch and take master back to before those commits were made. Unfortunately, my Git-fu isn't strong enough yet, any help? I.e. How can I go from this master A - B - C - D - E to this? newbranch C - D - E / master A - B...
What is the most concise and efficient way to find out if a JavaScript array contains an obj? This is the only way I know to do it: function contains(a, obj) { for (var i = 0; i < a.length; i++) { if (a[i] === obj) { return true; } } return false; } Is there a better and more concise way to accomplish this? This is very closely related to Stack Overflow...
I am new to this kind of stuff, but lately I've been hearing a lot about how good Node.js is. Considering how much I love working with jQuery and JavaScript in general, I can't help but wonder how to decide when to use Node.js. The web application I have in mind is something like Bitly - takes some content, archives it. From all the homework I have been doing in the last few days, I obtained the...
Possible Duplicate: Nullable type is not a nullable type? Why GetType returns System.Int32 instead of Nullable<Int32>? I expected ((int?) 1).GetType() to return typeof(int?), but it turns out that it returns typeof(int): bool a = ((int?)1).GetType() == typeof(int?); // a is false bool b = ((int?)1).GetType() == typeof(int); // b is true Still, code such as ((int?) 1).HasValue compiles...
I've been using Git for a while now and have recently downloaded an update only to find this warning message come up when I try to push. warning: push.default is unset; its implicit value is changing in Git 2.0 from 'matching' to 'simple'. To squelch this message and maintain the current behavior after the default changes, use: git config --global push.default matching To squelch this message...
I'm trying to create globally-unique identifiers in JavaScript. I'm not sure what routines are available on all browsers, how "random" and seeded the built-in random number generator is, etc.. The GUID / UUID should be at least 32 characters and should stay in the ASCII range to avoid trouble when passing them around....
What exactly is RESTful programming?...
If you have java.io.InputStream object, how should you process that object and produce a String? Suppose I have an InputStream that contains text data, and I want to convert this to a String (for example, so I can write the contents of the stream to a log file). What is the easiest way to take the InputStream and convert it to a String? public String convertStreamToString(InputStream is) { ...
What are the differences between AngularJS module's Service, Provider and Factory?...
404Votes22Comments

Enumerate an enum?

How can you enumerate an enum in C#? E.g., the following does not compile: public enum Suit { Spades, Hearts, Clubs, Diamonds } public void EnumerateAllSuitsDemoMethod() { foreach (Suit suit in Suit) { DoSomething(suit); } } It gives the compile time error: 'Suit' is a 'type' but is used like a 'variable' It fails on the Suit keyword, the 2nd one....
If not, is it possible to simulate one concisely using other language constructs?...
How do I discard changes in my working copy that are not in the index?...
What are the differences between a HashMap and a Hashtable in Java? Which is more efficient for non-threaded applications?...
How can I loop through all the objects in an array using JavaScript? I thought of something like this (where objects is my array of objects): forEach(instance in objects) But this does not seem to be correct....
How can I horizontally center a div within a div using CSS (if it's even possible)? The outer div has 100% width: <div id="outer" style="width:100%"> <div id="inner">Foo foo</div> </div>...
How can I add an empty directory (that contains no files) to a Git repository?...
In an HTML table, the cellpadding and cellspacing can be set like this: <table cellspacing="1" cellpadding="1"> How can the same be accomplished using CSS?...
I know it's possible to match for a word and then reverse the matches using other tools (e.g. grep -v). However, I'd like to know if it's possible to match lines that don't contain a specific word (e.g. hede) using a regular expression? Input: hoho hihi haha hede # grep "Regex for do not contain hede" Input Output: hoho hihi haha...
How do I check whether a file exists, using Python, without using a try statement?...
Over the years I have slowly developed a regular expression that validates MOST email addresses correctly, assuming they don't use an IP address as the server part. I use it in several PHP programs, and it works most of the time. However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized...
I know how to make a new branch that tracks remote branches, but how do I make an existing branch track a remote branch? I know I can just edit the .git/config file, but it seems there should be an easier way....
People talk about URLs, URIs and URNs as if they're different things, but they look the same to the naked eye. What's the difference between them?...
How can I get a timestamp in JavaScript? Something similar to Unix's timestamp, that is, a single number that represents the current time and date. Either as a number or a string....
I was looking at the new APIs introduced in Android 4.2. While looking at the UserManager class I came across the following method: public boolean isUserAGoat () Used to determine whether the user making this call is subject to teleportations. Returns whether the user making this call is a goat. How and when should this be used?...
What is this? This is a collection of questions that come up every now and then about syntax in PHP. This is also a Community Wiki, so everyone is invited to participate in maintaining this list. Why is this? It used to be hard to find questions about operators and other syntax tokens.¹ The main idea is to have links to existing questions on Stack Overflow, so it's easier for us to reference them,...
I have an array of integers, which I'm using the .push() method to add to. Is there a simple way to remove a specific element from an array? The equivalent of something like array.remove(int); I have to use core JavaScript - no frameworks are allowed....
How do I remove a Git submodule? By the way, is there a reason I can't simply do git submodule rm whatever ?...
I have a 2.67 GHz Celeron processor, and 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all the instructions in setting up the IDE, SDKs, JDKs and such and have had some success in starting the emulator quickly, but that is very rare. How can I, if...
Chrome supports the placeholder attribute on input[type=text] elements (others probably do too). But the following CSS doesn't do diddly squat to the placeholder's value: input[placeholder], [placeholder], *[placeholder] { color: red !important; } <input type="text" placeholder="Value"> Value will still remain grey instead of red. Is there a way to change the color of the...
943Votes30Comments

Avoiding != null statements

The idiom I use the most when programming in Java is to test if object != null before I use it. This is to avoid a NullPointerException. I find the code very ugly, and it becomes unreadable. Is there a good alternative to this? I want to address the necessity to test every object if you want to access a field or method of this object. For example: if (someobject != null) { someobject.doCalc(); } In...
How do I get the path of the directory in which a Bash script is located FROM that Bash script? For instance, let's say I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so: $ ./application...
I'd like to do something like this to tick a checkbox using jQuery: $(".myCheckBox").checked(true); or $(".myCheckBox").selected(true); Does such a thing exist?...
Say I create an object as followed: var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; What is the best way to remove the property regex to end up with this new myJSONObject: var myJSONObject = {"ircEvent": "PRIVMSG", "method": "newURI"};...
Is there something similar to @import in CSS in JavaScript that allows you to include a JavaScript file inside another JavaScript file?...
497Votes10Comments

Java += operator

Until today I thought that for example: i += j; is just a shortcut for: i = i + j; But what if we try this: int i = 5; long j = 8; Then i = i + j; will not compile but i += j; will compile fine. Does it mean that in fact i += j; is a shortcut for something like this i = (type of i) (i + j)?...
I need to check the checked property of a checkbox and perform an action based on the checked property using jQuery. For example, if the age checkbox is checked, then I need to show a textbox to enter age, else hide the textbox. But the following code returns false by default: if($('#isAgeSelected').attr('checked')) { $("#txtAge").show(); } else { $("#txtAge").hide(); } How do I successfully...
How do I force an overwrite of local files on a Git pull? The scenario is following: A team member is modifying the templates for a website we are working on They are adding some images to the images directory (but forgets to add them under source control) They are sending the images by mail, later, to me I'm adding the images under the source control and pushing them to Github together with other...
What is the difference between INNER JOIN and OUTER JOIN? How do LEFT JOIN, RIGHT JOIN, and FULL JOIN fit in?...
when i imported some projects from Github have some errors in console like this : WARNING: unable to write jarlist cache file any help would be appreciated ....
11Votes1Comments

Exceptions in Yesod

I had made a daemon that used a very primitive form of ipc (telnet and send a String that had certain words in a certain order). I snapped out of it and am now using JSON to pass messages to a Yesod server. However, there were some things I really liked about my design, and I'm not sure what my choices are now. Here's what I was doing: buildManager :: Phase -> IO () buildManager phase = do let...
Why does Google prepend while(1); to their (private) JSON responses? For example, here's a response while turning a calendar on and off in Google Calendar: while(1);[['u',[['smsSentFlag','false'],['hideInvitations','false'], ['remindOnRespondedEventsOnly','true'], ['hideInvitations_remindOnRespondedEventsOnly','false_true'], ['Calendar ID stripped for privacy','false'],['smsVerifiedFlag','true']]]] I...
I have a Flash project, and it has many source files. I have a fairly heavily-used class, call it Jenine. I recently (and, perhaps, callously) relocated Jenine from one namespace to another. I thought we were ready - I thought it was time. The new Jenine was better in every way - she had lost some code bloat, she had decoupled herself from a few vestigial class relationships, and she had finally come...
751Votes12Comments

Checkout remote Git branch

I am trying to checkout a remote branch: Somebody pushed a branch called test with git push origin test to a shared repository. I can see the branch with git branch -r. But how can I get this branch? git checkout test does nothing git checkout origin/test does something, but git branch says * (no branch). I am on no branch? How do I share branches via a public repository?...
I have a master and a development branch, both pushed to GitHub. I've cloned, pulled, and fetched, but I remain unable to get anything other than the master branch back. I'm sure I'm missing something obvious, but I have read the manual and I'm getting no joy at all....
What is the most efficient way to clone a JavaScript object? I've seen obj = eval(uneval(o)); being used, but that's currently Firefox-only. In Mootools 1.2, I've done things like obj = JSON.decode(JSON.encode(o)); but question the efficiency. I've also seen recursive copying functions with various flaws. I'm surprised no canonical solution exists....
1211Votes24Comments

PUT vs POST in REST

According to the HTTP/1.1 Spec: The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line In other words, POST is used to create. The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already...
The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.? function myJsFunc() { alert("myJsFunc"); } <a href="#" onclick="myJsFunc();">Run JavaScript Code</a> or function myJsFunc() { alert("myJsFunc"); } <a href="javascript:void(0)"...
What are metaclasses? What do you use them for?...
What is the maximum length of a URL in different browsers? Does it differ between browsers? Does the HTTP protocol dictate it?...
For anchors that act like buttons (for example, Questions, Tags, Users, etc. at the top of the Stack Overflow page) or tabs, is there a CSS standard way to disable the highlighting effect if the user accidentally selects the text? I realize this could be done with JavaScript, and a little googling yielded the Mozilla-only -moz-user-select option. Is there a standard-compliant way to accomplish...
I always thought Java was pass-by-reference; however I've seen a couple of blog posts (for example, this blog) that claim it's not. I do not think I understand the distinction they are making. What is the explanation?...
Yesterday I was pairing the socks from the clean laundry and figured out the way I was doing it is not very efficient. I was doing a naive search — picking one sock and "iterating" the pile in order to find its pair. This requires iterating over n/2 * n/4 = n2/8 socks on average. As a computer scientist I was thinking what I could do? Sorting (according to size/color/...) of course came to...
Can I use comments inside a JSON file? If so, how?...
How do I revert from my current state to a snapshot made on a certain commit? If I do git log, I get the following output: $ git log commit a867b4af366350be2e7c21b8de9cc6504678a61b` Author: Me <[email protected]> Date: Thu Nov 4 18:59:41 2010 -0400 blah blah blah... commit 25eee4caef46ae64aa08e8ab3f988bc917ee1ce4 Author: Me <[email protected]> Date: Thu Nov 4 05:13:39 2010 -0400 more blah blah...
1015Votes16Comments

Fix merge conflicts in Git?

Is there a good way to explain how to resolve merge conflicts in Git?...
In C#, what is the difference between String and string? (note the case) Example: string s = "Hello world!"; String S = "Hello world!"; What are the guidelines for the use of each? And what are the differences?...
Is there a plugin-less way of retrieving query string values via jQuery (or without)? If so, how? If not, is there a plugin which can do so?...
If user input is inserted without modification into an SQL query, then the application becomes vulnerable to SQL injection, like in the following example: $unsafe_variable = $_POST['user_input']; mysql_query("INSERT INTO `table` (`column`) VALUES ('$unsafe_variable')"); That's because the user can input something like value'); DROP TABLE table;--, and the query becomes: INSERT INTO `table` (`column`)...
What is the difference between the px, dip, dp and sp units in Android?...
How do you delete untracked local files from your current branch?...
How come certain random strings produce various colors when entered as background colors in HTML? For example: <body bgcolor="chucknorris"> test </body> ...produces a document with a red background across all browsers and platforms. Interestingly, while chucknorri produces a red background as well, chucknorr produces a yellow background. What's going on here?...
What is a plain English explanation of Big O notation? I'd prefer as little formal definition as possible and simple mathematics....
I'm using JSLint to go through JavaScript, and it's returning many suggestions to replace == (two equals signs) with === (three equals signs) when doing things like comparing idSele_UNVEHtype.value.length == 0 inside of an if statement. Is there a performance benefit to replacing == with ===? Any performance improvement would be welcomed as many comparison operators exist. If no type conversion...
I've recently started maintaining someone else's JavaScript code. I'm fixing bugs, adding features and also trying to tidy up the code and make it more consistent. The previous developer uses two ways of declaring functions and I can't work out if there is a reason behind it or not. The two ways are: var functionOne = function() { // Some code }; function functionTwo() { // Some code } What...
Form-based authentication for websites We believe that Stack Overflow should not just be a resource for very specific technical questions, but also for general guidelines on how to solve variations on common problems. "Form based authentication for websites" should be a fine topic for such an experiment. It should include topics such as: How to log in How to remain logged in How to store passwords Using...
I am looking for a library that implements a general purpose range coder or arithmetic coder that supports alphabets with a lot of symbols (millions). I am especially looking for libraries written in Haskell but C is also okay. Performance is not so important as I want to use the library as a prototyping tool for a later implementation by myself. Thanks for the help!...
Possible Duplicate: [Branch from a previous commit using git] Link to a more recent/less clear question: (Branch from a previous commit using git) I have the git branch called: jzbranch and an old commit id: a9c146a09505837ec03b How do I create a new branch justin from the information listed above...
What does class << self do in Ruby?...
I do not want to rename a remote branch, as described in Rename master branch for both local and remote Git repositories. Instead, I want to use the simplest way to rename a local branch, which is not pushed to a remote branch....
We have an employee whose last name is Null. Our employee lookup application is killed when that last name is used as the search term (which happens to be quite often now). The error received (thanks Fiddler!) is: <soapenv:Fault> <faultcode>soapenv:Server.userException</faultcode> <faultstring>coldfusion.xml.rpc.CFCInvocationException: [coldfusion.runtime.MissingArgumentException...
How can I check if one string contains another substring in JavaScript? Usually I would expect a String.contains() method, but there doesn't seem to be one....
If I run the following program, which parses two date strings referencing times one second apart and compares them: public static void main(String[] args) throws ParseException { SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String str3 = "1927-12-31 23:54:07"; String str4 = "1927-12-31 23:54:08"; Date sDt3 = sf.parse(str3); Date sDt4 = sf.parse(str4);...
In jQuery, it is possible to toggle the visibility of an element, using the functions .hide(), .show() or .toggle(). Using jQuery, how would you test if an element is visible or hidden?...
I mistakenly added files using the command git add file I have not yet run git commit. Is there a way to undo this or remove these files from the commit?...
Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error: Problem at line 1 character 1: Missing "use strict" statement. Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string...
What is the use of the yield keyword in Python? What does it do? For example, I'm trying to understand this code1: def node._get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild and distance - max_dist < self._median: yield self._leftchild if self._rightchild and distance + max_dist >= self._median: yield self._rightchild And this is the caller: result,...
How can I redirect the user from one page to another using jQuery?...
Programming language books explain that value types are created on the stack, and reference types are created on the heap, without explaining what these two things are. I haven't read a clear explanation of this. I understand what a stack is, but where and what are they (physically in a real computer's memory)? To what extent are they controlled by the OS or language runtime? What is their scope? What...
This question attempts to collect the few pearls among the dozens of bad C++ books that are published every year. Unlike many other programming languages, which are often picked up on the go from tutorials found on the Internet, few are able to quickly pick up C++ without studying a well-written C++ book. It is way too big and complex for doing this. In fact, it is so big and complex, that there are...
After reading Hidden Features and Dark Corners of C++/STL on comp.lang.c++.moderated, I was completely surprised that the following snippet compiled and worked in both Visual Studio 2008 and G++ 4.4. Here's the code: #include <stdio.h> int main() { int x = 10; while (x --> 0) // x goes to 0 { printf("%d ", x); } } I'd assume this is C, since it works in GCC as well....
Like the old Albert Einstein said: If you can't explain it to a six-year-old, you really don't understand it yourself. Well, I tried to explain JavaScript closures to a 27-year-old friend and completely failed. How would you explain it to someone with a knowledge of the concepts which make up closures (for example, functions, variables and the like), but does not understand closures themselves? I...
What are the differences between git pull and git fetch?...
I want to delete a branch both locally and on my remote project fork on GitHub. Successfully Deleted Local Branch $ git branch -D bugfix Deleted branch bugfix (was 2a14ef7). Note: The uppercase -D option is a shortcut for --delete --force. If you want to delete a local branch that must be fully merged in its upstream branch, use -d which is a shortcut for --delete. Failed Attempts to Delete Remote...
I've been messing around with JSON for some time, just pushing it out as text and it hasn't hurt anybody (that I know of), but I'd like to start doing things properly. I have seen so many purported "standards" for the JSON content type: application/json application/x-javascript text/javascript text/x-javascript text/x-json But which is correct, or best? I gather that there are security and browser...
I wrote the wrong thing in a commit message. How can I change the message? The commit has not been pushed yet....
I committed a directory containing .class files instead of a directory containing .java files to Git. How can I undo this commit?...
Here is a piece of C++ code that seems very peculiar. For some strange reason, sorting the data miraculously makes the code almost six times faster. #include <algorithm> #include <ctime> #include <iostream> int main() { // Generate data const unsigned arraySize = 32768; int data[arraySize]; for (unsigned c = 0; c < arraySize; ++c) data[c] = std::rand()...