SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

How do I convert between big-endian and little-endian values in C++?

Note that, at least for Windows, htonl() is much slower than their intrinsic counterpart _byteswap_ulong(). The former is a DLL library call into ws2_32.dll, the latter is one BSWAP assembly instruction. Therefore, if you are writing some platform-dependent code, prefer using the intrinsics for speed:

#define htonl(x) _byteswap_ulong(x)

This may be especially important for .PNG image processing where all integers are saved in Big Endian with explanation "One can use htonl()..." {to slow down typical Windows programs, if you are not prepared}.

Recursively list all files in a directory including files in symlink directories

The -L option to ls will accomplish what you want. It dereferences symbolic links.

So your command would be:

ls -LR

You can also accomplish this with

find -follow

The -follow option directs find to follow symbolic links to directories.

On Mac OS X use

find -L

as -follow has been deprecated.

How to create a GUID / UUID

Necromancing.

Effectively, a Guid, or UUID as it is called in non-microsoft-circles, is just a 128-Bit cryptographic random number, with the uuid version number (1-5) being at a fixed location byte.

So when you just generate a bunch of random numbers betwween 0 and 65535 and hex-encode them, like this:

function guid()
{
    function s4()
    {
        return Math.floor(Math.random() * 65536).toString(16).padStart(4, '0')
    } // End Function s4 

    return s4() + s4() + '-' + s4() + '-' + "4" + s4().substr(1) + '-' + s4() + '-' + s4() + s4() + s4();
} // End Function guid 

you get a valid GUID, but due to the random-implementation, it's not cryptographically secure.

To generate a cryptographically secure GUID, you need to use window.crypto (or window.msCrypto for Internet Exploder).

That goes like this:

function cryptGuid()
{ 
    var array = new Uint16Array(8);
    (window.crypto || window.msCrypto).getRandomValues(array);
    var dataView = new DataView(array.buffer);
    
    var parts = [];

    for(var i = 0; i < array.length; ++i)
    {
        // 0&1,2,3,4,5-7 dataView.getUint16(0-7)
        if(i>1 && i<6) parts.push("-");
        parts.push(dataView.getUint16(i).toString(16).padStart(4, '0'));
    }

    parts[5] = "4" + parts[5].substr(1);
    // console.log(parts);
    return parts.join('').toUpperCase();// .toLowerCase();
}

cryptGuid();

Plus you have to decide, if you return the number as lower-or upper-case character string. Certain software require lowercase characters (e.g. Reporting Service), while others generate uppercase characters (SQL-Server).

How do you get total amount of RAM the computer has?

// use `/ 1048576` to get ram in MB
// and `/ (1048576 * 1024)` or `/ 1048576 / 1024` to get ram in GB
private static String getRAMsize()
{
    ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
    ManagementObjectCollection moc = mc.GetInstances();
    foreach (ManagementObject item in moc)
    {
       return Convert.ToString(Math.Round(Convert.ToDouble(item.Properties["TotalPhysicalMemory"].Value) / 1048576, 0)) + " MB";
    }

    return "RAMsize";
}

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

The mutable keyword is a way to pierce the const veil you drape over your objects. If you have a const reference or pointer to an object, you cannot modify that object in any way except when and how it is marked mutable.

With your const reference or pointer you are constrained to:

  • only read access for any visible data members
  • permission to call only methods that are marked as const.

The mutable exception makes it so you can now write or set data members that are marked mutable. That's the only externally visible difference.

Internally those const methods that are visible to you can also write to data members that are marked mutable. Essentially the const veil is pierced comprehensively. It is completely up to the API designer to ensure that mutable doesn't destroy the const concept and is only used in useful special cases. The mutable keyword helps because it clearly marks data members that are subject to these special cases.

In practice you can use const obsessively throughout your codebase (you essentially want to "infect" your codebase with the const "disease"). In this world pointers and references are const with very few exceptions, yielding code that is easier to reason about and understand. For a interesting digression look up "referential transparency".

Without the mutable keyword you will eventually be forced to use const_cast to handle the various useful special cases it allows (caching, ref counting, debug data, etc.). Unfortunately const_cast is significantly more destructive than mutable because it forces the API client to destroy the const protection of the objects (s)he is using. Additionally it causes widespread const destruction: const_casting a const pointer or reference allows unfettered write and method calling access to visible members. In contrast mutable requires the API designer to exercise fine grained control over the const exceptions, and usually these exceptions are hidden in const methods operating on private data.

(N.B. I refer to to data and method visibility a few times. I'm talking about members marked as public vs. private or protected which is a totally different type of object protection discussed here.)

Should I test private methods or only public ones?

Unit tests I believe are for testing public methods. Your public methods use your private methods, so indirectly they are also getting tested.

Position an element relative to its container

Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative on the container, then for child elements, top and left will be relative to the top-left of the container so long as the child elements have position: absolute. More information is available in the CSS 2.1 specification.

Is there a printf converter to print in binary format?

void print_bits (uintmax_t n)
{
    for (size_t i = 8 * sizeof (int); i-- != 0;)
    {
        char c;
        if ((n & (1UL << i)) != 0)
            c = '1';
        else
            c = '0';

        printf ("%c", c);

    }
}

Not a cover-absolutely-everywhere solution but if you want something quick, and easy to understand, I'm suprised no one has proposed this solution yet.

Best way to remove from NSMutableArray while iterating?

Why don't you add the objects to be removed to another NSMutableArray. When you are finished iterating, you can remove the objects that you have collected.

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

It sounds like you are almost definitely behind a proxy server.

Where this does not work for me behind my proxy:

svn checkout http://v8.googlecode.com/svn/trunk/ v8-read-only

this does:

svn --config-option servers:global:http-proxy-host=MY_PROXY_HOST --config-option servers:global:http-proxy-port=MY_PROXY_PORT checkout http://v8.googlecode.com/svn/trunk/ v8-read-only

UPDATE I forgot to quote my source :-)

http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.1

How to create query parameters in Javascript?

If you are using Prototype there is Form.serialize

If you are using jQuery there is Ajax/serialize

I do not know of any independent functions to accomplish this, though, but a google search for it turned up some promising options if you aren't currently using a library. If you're not, though, you really should because they are heaven.

How do you performance test JavaScript code?

The golden rule is to NOT under ANY circumstances lock your users browser. After that, I usually look at execution time, followed by memory usage (unless you're doing something crazy, in which case it could be a higher priority).

Combine multiple results in a subquery into a single comma-separated value

In MySQL there is a group_concat function that will return what you're asking for.

SELECT TableA.ID, TableA.Name, group_concat(TableB.SomeColumn) 
as SomColumnGroup FROM TableA LEFT JOIN TableB ON 
TableB.TableA_ID = TableA.ID

What's "P=NP?", and why is it such a famous question?

To give the simplest answer I can think of:

Suppose we have a problem that takes a certain number of inputs, and has various potential solutions, which may or may not solve the problem for given inputs. A logic puzzle in a puzzle magazine would be a good example: the inputs are the conditions ("George doesn't live in the blue or green house"), and the potential solution is a list of statements ("George lives in the yellow house, grows peas, and owns the dog"). A famous example is the Traveling Salesman problem: given a list of cities, and the times to get from any city to any other, and a time limit, a potential solution would be a list of cities in the order the salesman visits them, and it would work if the sum of the travel times was less than the time limit.

Such a problem is in NP if we can efficiently check a potential solution to see if it works. For example, given a list of cities for the salesman to visit in order, we can add up the times for each trip between cities, and easily see if it's under the time limit. A problem is in P if we can efficiently find a solution if one exists.

(Efficiently, here, has a precise mathematical meaning. Practically, it means that large problems aren't unreasonably difficult to solve. When searching for a possible solution, an inefficient way would be to list all possible potential solutions, or something close to that, while an efficient way would require searching a much more limited set.)

Therefore, the P=NP problem can be expressed this way: If you can verify a solution for a problem of the sort described above efficiently, can you find a solution (or prove there is none) efficiently? The obvious answer is "Why should you be able to?", and that's pretty much where the matter stands today. Nobody has been able to prove it one way or another, and that bothers a lot of mathematicians and computer scientists. That's why anybody who can prove the solution is up for a million dollars from the Claypool Foundation.

We generally assume that P does not equal NP, that there is no general way to find solutions. If it turned out that P=NP, a lot of things would change. For example, cryptography would become impossible, and with it any sort of privacy or verifiability on the Internet. After all, we can efficiently take the encrypted text and the key and produce the original text, so if P=NP we could efficiently find the key without knowing it beforehand. Password cracking would become trivial. On the other hand, there's whole classes of planning problems and resource allocation problems that we could solve effectively.

You may have heard the description NP-complete. An NP-complete problem is one that is NP (of course), and has this interesting property: if it is in P, every NP problem is, and so P=NP. If you could find a way to efficiently solve the Traveling Salesman problem, or logic puzzles from puzzle magazines, you could efficiently solve anything in NP. An NP-complete problem is, in a way, the hardest sort of NP problem.

So, if you can find an efficient general solution technique for any NP-complete problem, or prove that no such exists, fame and fortune are yours.

What is a "callable"?

callables implement the __call__ special method so any object with such a method is callable.

How do I handle the window close event in Tkinter?

You should use destroy() to close a tkinter window.

   from Tkinter import *
   root = Tk()
   Button(root, text="Quit", command=root.destroy).pack()
   root.mainloop()

Explanation:

root.quit() The above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy() While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop()`.

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something

How do JavaScript closures work?

JavaScript functions can access their:

  1. Arguments
  2. Locals (that is, their local variables and local functions)
  3. Environment, which includes:
    • globals, including the DOM
    • anything in outer functions

If a function accesses its environment, then the function is a closure.

Note that outer functions are not required, though they do offer benefits I don't discuss here. By accessing data in its environment, a closure keeps that data alive. In the subcase of outer/inner functions, an outer function can create local data and eventually exit, and yet, if any inner function(s) survive after the outer function exits, then the inner function(s) keep the outer function's local data alive.

Example of a closure that uses the global environment:

Imagine that the Stack Overflow Vote-Up and Vote-Down button events are implemented as closures, voteUp_click and voteDown_click, that have access to external variables isVotedUp and isVotedDown, which are defined globally. (For simplicity's sake, I am referring to StackOverflow's Question Vote buttons, not the array of Answer Vote buttons.)

When the user clicks the VoteUp button, the voteUp_click function checks whether isVotedDown == true to determine whether to vote up or merely cancel a down vote. Function voteUp_click is a closure because it is accessing its environment.

var isVotedUp = false;
var isVotedDown = false;

function voteUp_click() {
  if (isVotedUp)
    return;
  else if (isVotedDown)
    SetDownVote(false);
  else
    SetUpVote(true);
}

function voteDown_click() {
  if (isVotedDown)
    return;
  else if (isVotedUp)
    SetUpVote(false);
  else
    SetDownVote(true);
}

function SetUpVote(status) {
  isVotedUp = status;
  // Do some CSS stuff to Vote-Up button
}

function SetDownVote(status) {
  isVotedDown = status;
  // Do some CSS stuff to Vote-Down button
}

All four of these functions are closures as they all access their environment.

How do I close a tkinter window?

def quit1():
     root.destroy()

Button(root, text="Quit", command=quit1).pack()
root.mainloop()

How can I find the current OS in Python?

Something along the lines:

import os
if os.name == "posix":
    print(os.system("uname -a"))
# insert other possible OSes here
# ...
else:
    print("unknown OS")

Algorithm to calculate the number of divisors of a given number

Number theory textbooks call the divisor-counting function tau. The first interesting fact is that it's multiplicative, ie. t(ab) = t(a)t(b) , when a and b have no common factor. (Proof: each pair of divisors of a and b gives a distinct divisor of ab).

Now note that for p a prime, t(p**k) = k+1 (the powers of p). Thus you can easily compute t(n) from its factorisation.

However factorising large numbers can be slow (the security of RSA crytopraphy depends on the product of two large primes being hard to factorise). That suggests this optimised algorithm

  1. Test if the number is prime (fast)
  2. If so, return 2
  3. Otherwise, factorise the number (slow if multiple large prime factors)
  4. Compute t(n) from the factorisation

filtering NSArray into a new NSArray in Objective-C

The Best and easy Way is to create this method And Pass Array And Value:

- (NSArray *) filter:(NSArray *)array where:(NSString *)key is:(id)value{
    NSMutableArray *temArr=[[NSMutableArray alloc] init];
    for(NSDictionary *dic in self)
        if([dic[key] isEqual:value])
            [temArr addObject:dic];
    return temArr;
}

Which Python memory profiler is recommended?

I found meliae to be much more functional than Heapy or PySizer. If you happen to be running a wsgi webapp, then Dozer is a nice middleware wrapper of Dowser

How to convert date to timestamp in PHP?

Here is how I'd do it:

function dateToTimestamp($date, $format, $timezone='Europe/Belgrade')
{
    //returns an array containing day start and day end timestamps
    $old_timezone=date_timezone_get();
    date_default_timezone_set($timezone);
    $date=strptime($date,$format);
    $day_start=mktime(0,0,0,++$date['tm_mon'],++$date['tm_mday'],($date['tm_year']+1900));
    $day_end=$day_start+(60*60*24);
    date_default_timezone_set($old_timezone);
    return array('day_start'=>$day_start, 'day_end'=>$day_end);
}

$timestamps=dateToTimestamp('15.02.1991.', '%d.%m.%Y.', 'Europe/London');
$day_start=$timestamps['day_start'];

This way, you let the function know what date format you are using and even specify the timezone.

Is there a function in python to split a word into a list?

text = "just trying out"

word_list = []

for i in range(0, len(text)):
    word_list.append(text[i])
    i+=1

print(word_list)

['j', 'u', 's', 't', ' ', 't', 'r', 'y', 'i', 'n', 'g', ' ', 'o', 'u', 't']

How can I uninstall an application using PowerShell?

$app = Get-WmiObject -Class Win32_Product | Where-Object { 
    $_.Name -match "Software Name" 
}

$app.Uninstall()

Edit: Rob found another way to do it with the Filter parameter:

$app = Get-WmiObject -Class Win32_Product `
                     -Filter "Name = 'Software Name'"

Best implementation for hashCode method for a collection

If I understand your question correctly, you have a custom collection class (i.e. a new class that extends from the Collection interface) and you want to implement the hashCode() method.

If your collection class extends AbstractList, then you don't have to worry about it, there is already an implementation of equals() and hashCode() that works by iterating through all the objects and adding their hashCodes() together.

   public int hashCode() {
      int hashCode = 1;
      Iterator i = iterator();
      while (i.hasNext()) {
        Object obj = i.next();
        hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
      }
  return hashCode;
   }

Now if what you want is the best way to calculate the hash code for a specific class, I normally use the ^ (bitwise exclusive or) operator to process all fields that I use in the equals method:

public int hashCode(){
   return intMember ^ (stringField != null ? stringField.hashCode() : 0);
}

Character Limit in HTML

there's a maxlength attribute

<input type="text" name="textboxname" maxlength="100" />

What is the largest TCP/IP network port number allowable for IPv4?

The largest port number is an unsigned short 2^16-1: 65535

A registered port is one assigned by the Internet Corporation for Assigned Names and Numbers (ICANN) to a certain use. Each registered port is in the range 1024–49151.

Since 21 March 2001 the registry agency is ICANN; before that time it was IANA.

Ports with numbers lower than those of the registered ports are called well known ports; port with numbers greater than those of the registered ports are called dynamic and/or private ports.

Wikipedia : Registered Ports

How to return only the Date from a SQL Server DateTime datatype

Try this:

SELECT CONVERT(VARCHAR(10),GETDATE(),111)

The above statement converts your current format to YYYY/MM/DD, please refer to this link to choose your preferable format.

Graphical DIFF programs for linux

Diffuse is also very good. It even lets you easily adjust how lines are matched up, by defining match-points.

py2exe - generate single executable file

try c_x freeze it can create a good standalone

How do I remove objects from an array in Java?

Make a List out of the array with Arrays.asList(), and call remove() on all the appropriate elements. Then call toArray() on the 'List' to make back into an array again.

Not terribly performant, but if you encapsulate it properly, you can always do something quicker later on.

How do I remove the passphrase for the SSH key without having to create a new key?

On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.

php.ini & SMTP= - how do you pass username & password

After working all day on this, I finally found a solution. Here's how I send from Windows XP with WAMP.

  1. Use Google's SMTP server. You probably need an account.
  2. Download and install Fake Sendmail. I just downloaded it, unzipped it and put it in the WAMP folder.
  3. Create a test PHP file. See below.
<?php
    $message = "test message body";
    $result = mail('[email protected]', 'message subject', $message);
    echo "result: $result";
?>
  1. Update your php.ini file and your sendmail.ini file (sendmail.ini is in the sendmail folder).
  2. Check the error.log file in the sendmail folder that you just created if it doesn't work.

Reference:

is the + operator less performant than StringBuffer.append()

Like already some users have noted: This is irrelevant for small strings.

And new JavaScript engines in Firefox, Safari or Google Chrome optimize so

"<a href='" + url + "'>click here</a>";

is as fast as

["<a href='", url, "'>click here</a>"].join("");

What does %~d0 mean in a Windows batch file?

From Filename parsing in batch file and more idioms - Real's How-to:

The path (without drive) where the script is : ~p0

The drive where the script is : ~d0

Using Python's ftplib to get a directory listing, portably

The reliable/standardized way to parse FTP directory listing is by using MLSD command, which by now should be supported by all recent/decent FTP servers.

import ftplib
f = ftplib.FTP()
f.connect("localhost")
f.login()
ls = []
f.retrlines('MLSD', ls.append)
for entry in ls:
    print entry

The code above will print:

modify=20110723201710;perm=el;size=4096;type=dir;unique=807g4e5a5; tests
modify=20111206092323;perm=el;size=4096;type=dir;unique=807g1008e0; .xchat2
modify=20111022125631;perm=el;size=4096;type=dir;unique=807g10001a; .gconfd
modify=20110808185618;perm=el;size=4096;type=dir;unique=807g160f9a; .skychart
...

Starting from python 3.3, ftplib will provide a specific method to do this:

Is there any way to do HTTP PUT in python

You can use the requests library, it simplifies things a lot in comparison to taking the urllib2 approach. First install it from pip:

pip install requests

More on installing requests.

Then setup the put request:

import requests
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}

# Create your header as required
headers = {"content-type": "application/json", "Authorization": "<auth-key>" }

r = requests.put(url, data=json.dumps(payload), headers=headers)

See the quickstart for requests library. I think this is a lot simpler than urllib2 but does require this additional package to be installed and imported.

Why shouldn't I use "Hungarian Notation"?

Tacking on cryptic characters at the beginning of each variable name is unnecessary and shows that the variable name by itself isn't descriptive enough. Most languages require the variable type at declaration anyway, so that information is already available.

There's also the situation where, during maintenance, a variable type needs to change. Example: if a variable declared as "uint_16 u16foo" needs to become a 64-bit unsigned, one of two things will happen:

  1. You'll go through and change each variable name (making sure not to hose any unrelated variables with the same name), or
  2. Just change the type and not change the name, which will only cause confusion.

Given a DateTime object, how do I get an ISO 8601 date in string format?

The "s" standard format specifier represents a custom date and time format string that is defined by the DateTimeFormatInfo.SortableDateTimePattern property. The pattern reflects a defined standard (ISO 8601), and the property is read-only. Therefore, it is always the same, regardless of the culture used or the format provider supplied. The custom format string is "yyyy'-'MM'-'dd'T'HH':'mm':'ss".

When this standard format specifier is used, the formatting or parsing operation always uses the invariant culture.

– from MSDN

Is a Python dictionary an example of a hash table?

Yes. Internally it is implemented as open hashing based on a primitive polynomial over Z/2 (source).

count (non-blank) lines-of-code in bash

If you want to use something other than a shell script, try CLOC:

cloc counts blank lines, comment lines, and physical lines of source code in many programming languages. It is written entirely in Perl with no dependencies outside the standard distribution of Perl v5.6 and higher (code from some external modules is embedded within cloc) and so is quite portable.

How do I create a readable diff of two spreadsheets using git diff?

I got the problem like you so I decide to write small tool to help me out. Please check ExcelDiff_Tools. It comes with several key points:

  • Support xls, xlsx, xlsm.
  • With formula cell. It will compare both formula and value.
  • I try to make UI look like standard diff text viewer with : modified, deleted, added, unchanged status. Please take a look with image below for example: enter image description here

How to horizontally center an element

Use:

<style>
  #outer{
    text-align: center;
    width: 100%;
  }
  #inner{
    text-align: center;
  }
</style>

Simplest way to have a configuration file in a Windows Forms C# application

You want to use an App.Config.

When you add a new item to a project there is something called Applications Configuration file. Add that.

Then you add keys in the configuration/appsettings section

Like:

<configuration>
 <appSettings>
  <add key="MyKey" value="false"/>

Access the members by doing

System.Configuration.ConfigurationSettings.AppSettings["MyKey"];

This works in .NET 2 and above.

Determine the number of rows in a range

Function ListRowCount(ByVal FirstCellName as String) as Long
    With thisworkbook.Names(FirstCellName).RefersToRange
        If isempty(.Offset(1,0).value) Then 
            ListRowCount = 1
        Else
            ListRowCount = .End(xlDown).row - .row + 1
        End If
    End With
End Function

But if you are damn sure there's nothing around the list, then just thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Remove the following hot fixes and updates

  • Update KB972221
  • Hotfix KB973674
  • Hotfix KB971091

Restart the PC and try to uninstall now. This worked for me without problems.

Class method differences in Python: bound, unbound and static

>>> class Class(object):
...     def __init__(self):
...         self.i = 0
...     def instance_method(self):
...         self.i += 1
...         print self.i
...     c = 0
...     @classmethod
...     def class_method(cls):
...         cls.c += 1
...         print cls.c
...     @staticmethod
...     def static_method(s):
...         s += 1
...         print s
... 
>>> a = Class()
>>> a.class_method()
1
>>> Class.class_method()    # The class shares this value across instances
2
>>> a.instance_method()
1
>>> Class.instance_method() # The class cannot use an instance method
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method instance_method() must be called with Class instance as first argument (got nothing instead)
>>> Class.instance_method(a)
2
>>> b = 0
>>> a.static_method(b)
1
>>> a.static_method(a.c) # Static method does not have direct access to 
>>>                      # class or instance properties.
3
>>> Class.c        # a.c above was passed by value and not by reference.
2
>>> a.c
2
>>> a.c = 5        # The connection between the instance
>>> Class.c        # and its class is weak as seen here.
2
>>> Class.class_method()
3
>>> a.c
5

Pointer vs. Reference

You should pass a pointer if you are going to modify the value of the variable. Even though technically passing a reference or a pointer are the same, passing a pointer in your use case is more readable as it "advertises" the fact that the value will be changed by the function.

How to implement WiX installer upgrade?

One important thing I missed from the tutorials for a while (stolen from http://www.tramontana.co.hu/wix/lesson4.php) which resulted in the "Another version of this product is already installed" errors:

*Small updates mean small changes to one or a few files where the change doesn't warrant changing the product version (major.minor.build). You don't have to change the Product GUID, either. Note that you always have to change the Package GUID when you create a new .msi file that is different from the previous ones in any respect. The Installer keeps track of your installed programs and finds them when the user wants to change or remove the installation using these GUIDs. Using the same GUID for different packages will confuse the Installer.

Minor upgrades denote changes where the product version will already change. Modify the Version attribute of the Product tag. The product will remain the same, so you don't need to change the Product GUID but, of course, get a new Package GUID.

Major upgrades denote significant changes like going from one full version to another. Change everything: Version attribute, Product and Package GUIDs.

Can I return the 'id' field after a LINQ insert?

Try this:

MyContext Context = new MyContext(); 
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;

How to recursively download a folder via FTP on Linux

wget -r ftp://url

Work perfectly for Redhat and Ubuntu

Inner join vs Where

In PostgreSQL, there's definitely no difference - they both equate to the same query plan. I'm 99% sure that's also the case for Oracle.

When a 'blur' event occurs, how can I find out which element focus went *to*?

I do not like using timeout when coding javascript so I would do it the opposite way of Michiel Borkent. (Did not try the code behind but you should get the idea).

<input id="myInput" onblur="blured = this.id;"></input>
<span onfocus = "sortOfCallback(this.id)" id="mySpan">Hello World</span>

In the head something like that

<head>
    <script type="text/javascript">
        function sortOfCallback(id){
            bluredElement = document.getElementById(blured);
            // Do whatever you want on the blured element with the id of the focus element


        }

    </script>
</head>

Accessing Object Memory Address

I know this is an old question but if you're still programming, in python 3 these days... I have actually found that if it is a string, then there is a really easy way to do this:

>>> spam.upper
<built-in method upper of str object at 0x1042e4830>
>>> spam.upper()
'YO I NEED HELP!'
>>> id(spam)
4365109296

string conversion does not affect location in memory either:

>>> spam = {437 : 'passphrase'}
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'
>>> str(spam)
"{437: 'passphrase'}"
>>> object.__repr__(spam)
'<dict object at 0x1043313f0>'

Fetch the row which has the Max value for a column

select   UserId,max(Date) over (partition by UserId) value from users;

Is there a way to comment out markup in an .ASPX page?

Bonus answer: The keyboard shortcut in Visual Studio for commenting out anything is Ctrl-KC . This works in a number of places, including C#, VB, Javascript, and aspx pages; it also works for SQL in SQL Management Studio.

You can either select the text to be commented out, or you can position your text inside a chunk to be commented out; for example, put your cursor inside the opening tag of a GridView, press Ctrl-KC, and the whole thing is commented out.

How to detect if JavaScript is disabled?

I'd suggest you go the other way around by writing unobtrusive JavaScript.

Make the features of your project work for users with JavaScript disabled, and when you're done, implement your JavaScript UI-enhancements.

https://en.wikipedia.org/wiki/Unobtrusive_JavaScript

What does the explicit keyword mean?

Cpp Reference is always helpful!!! Details about explicit specifier can be found here. You may need to look at implicit conversions and copy-initialization too.

Quick look

The explicit specifier specifies that a constructor or conversion function (since C++11) doesn't allow implicit conversions or copy-initialization.

Example as follows:

struct A
{
    A(int) { }      // converting constructor
    A(int, int) { } // converting constructor (C++11)
    operator bool() const { return true; }
};

struct B
{
    explicit B(int) { }
    explicit B(int, int) { }
    explicit operator bool() const { return true; }
};

int main()
{
    A a1 = 1;      // OK: copy-initialization selects A::A(int)
    A a2(2);       // OK: direct-initialization selects A::A(int)
    A a3 {4, 5};   // OK: direct-list-initialization selects A::A(int, int)
    A a4 = {4, 5}; // OK: copy-list-initialization selects A::A(int, int)
    A a5 = (A)1;   // OK: explicit cast performs static_cast
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

//  B b1 = 1;      // error: copy-initialization does not consider B::B(int)
    B b2(2);       // OK: direct-initialization selects B::B(int)
    B b3 {4, 5};   // OK: direct-list-initialization selects B::B(int, int)
//  B b4 = {4, 5}; // error: copy-list-initialization does not consider B::B(int,int)
    B b5 = (B)1;   // OK: explicit cast performs static_cast
    if (b5) cout << "true" << endl; // OK: B::operator bool()
//  bool nb1 = b2; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b2); // OK: static_cast performs direct-initialization
}

What are the rules for calling the superclass constructor?

Nobody mentioned the sequence of constructor calls when a class derives from multiple classes. The sequence is as mentioned while deriving the classes.

How do I create a WPF Rounded Corner container?

You don't need a custom control, just put your container in a border element:

<Border BorderBrush="#FF000000" BorderThickness="1" CornerRadius="8">
   <Grid/>
</Border>

You can replace the <Grid/> with any of the layout containers...

How do I set the proxy to be used by the JVM

The following shows how to set in Java a proxy with proxy user and proxy password from the command line, which is a very common case. You should not save passwords and hosts in the code, as a rule in the first place.

Passing the system properties in command line with -D and setting them in the code with System.setProperty("name", "value") is equivalent.

But note this

Example that works:

C:\temp>java -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps.proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit com.andreas.JavaNetHttpConnection

But the following does not work:

C:\temp>java com.andreas.JavaNetHttpConnection -Dhttps.proxyHost=host -Dhttps.proxyPort=port -Dhttps=proxyUser=user -Dhttps.proxyPassword="password" -Djavax.net.ssl.trustStore=c:/cacerts -Djavax.net.ssl.trustStorePassword=changeit

The only difference is the position of the system properties! (before and after the class)

If you have special characters in password, you are allowed to put it in quotes "@MyPass123%", like in the above example.

If you access an HTTPS service, you have to use https.proxyHost, https.proxyPort etc.

If you access an HTTP service, you have to use http.proxyHost, http.proxyPort etc.

Directory-tree listing in Python

I wrote a long version, with all the options I might need: http://sam.nipl.net/code/python/find.py

I guess it will fit here too:

#!/usr/bin/env python

import os
import sys

def ls(dir, hidden=False, relative=True):
    nodes = []
    for nm in os.listdir(dir):
        if not hidden and nm.startswith('.'):
            continue
        if not relative:
            nm = os.path.join(dir, nm)
        nodes.append(nm)
    nodes.sort()
    return nodes

def find(root, files=True, dirs=False, hidden=False, relative=True, topdown=True):
    root = os.path.join(root, '')  # add slash if not there
    for parent, ldirs, lfiles in os.walk(root, topdown=topdown):
        if relative:
            parent = parent[len(root):]
        if dirs and parent:
            yield os.path.join(parent, '')
        if not hidden:
            lfiles   = [nm for nm in lfiles if not nm.startswith('.')]
            ldirs[:] = [nm for nm in ldirs  if not nm.startswith('.')]  # in place
        if files:
            lfiles.sort()
            for nm in lfiles:
                nm = os.path.join(parent, nm)
                yield nm

def test(root):
    print "* directory listing, with hidden files:"
    print ls(root, hidden=True)
    print
    print "* recursive listing, with dirs, but no hidden files:"
    for f in find(root, dirs=True):
        print f
    print

if __name__ == "__main__":
    test(*sys.argv[1:])

Dark color scheme for Eclipse

I played with customizing the colors. I went with the yellow text/blue background I've liked from Turbo Pascal. The problem I ran into was it let you set the colors of the editors but then the other views like Package Explorer or Navigator stayed with the default black-on-white colors. I'm sure you could do it programatically but there are waaaay to many settings for my patience.

What's the difference between "Layers" and "Tiers"?

  1. In plain english, the Tier refers to "each in a series of rows or levels of a structure placed one above the other" whereas the Layer refers to "a sheet, quantity, or thickness of material, typically one of several, covering a surface or body".

  2. Tier is a physical unit, where the code / process runs. E.g.: client, application server, database server;

    Layer is a logical unit, how to organize the code. E.g.: presentation (view), controller, models, repository, data access.

  3. Tiers represent the physical separation of the presentation, business, services, and data functionality of your design across separate computers and systems.

    Layers are the logical groupings of the software components that make up the application or service. They help to differentiate between the different kinds of tasks performed by the components, making it easier to create a design that supports reusability of components. Each logical layer contains a number of discrete component types grouped into sublayers, with each sublayer performing a specific type of task.

The two-tier pattern represents a client and a server.

In this scenario, the client and server may exist on the same machine, or may be located on two different machines. Figure below, illustrates a common Web application scenario where the client interacts with a Web server located in the client tier. This tier contains the presentation layer logic and any required business layer logic. The Web application communicates with a separate machine that hosts the database tier, which contains the data layer logic.

Layers vs Tiers

Advantages of Layers and Tiers:

  • Layering helps you to maximize maintainability of the code, optimize the way that the application works when deployed in different ways, and provide a clear delineation between locations where certain technology or design decisions must be made.

  • Placing your layers on separate physical tiers can help performance by distributing the load across multiple servers. It can also help with security by segregating more sensitive components and layers onto different networks or on the Internet versus an intranet.

A 1-Tier application could be a 3-Layer application.

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE `tableName` CHANGE  `columnName` DECIMAL(16,1) NOT NULL;

I uses This for the alterration

JavaScript Chart Library

We just bought a license of TechOctave Charts Suite for our new startup. I highly recommend them. Licensing is simple. Charts look great! It was easy to get started and has a powerful API for when we need it. I was shocked by how clean and extensible the code is. Really happy with our choice.

How do I sort a VARCHAR column in SQL server that contains numbers?

This query is helpful for you. In this query, a column has data type varchar is arranged by good order.For example- In this column data are:- G1,G34,G10,G3. So, after running this query, you see the results: - G1,G10,G3,G34.

SELECT *,
       (CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum
FROM table_name 
ORDER BY IsNum, LEN(column_name), column_name;

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

The best way to do this is by a simple check and assess. I usually do something like this:

#ifndef _DEPRECATION_DISABLE   /* One time only */
#define _DEPRECATION_DISABLE   /* Disable deprecation true */
#if (_MSC_VER >= 1400)         /* Check version */
#pragma warning(disable: 4996) /* Disable deprecation */
#endif /* #if defined(NMEA_WIN) && (_MSC_VER >= 1400) */
#endif /* #ifndef _DEPRECATION_DISABLE */

All that is really required is the following:

#pragma warning(disable: 4996)

Hasn't failed me yet; Hope this helps

Determine the number of lines within a text file

If by easy you mean a lines of code that are easy to decipher but per chance inefficient?

string[] lines = System.IO.File.RealAllLines($filename);
int cnt = lines.Count();

That's probably the quickest way to know how many lines.

You could also do (depending on if you are buffering it in)

#for large files
while (...reads into buffer){
string[] lines = Regex.Split(buffer,System.Enviorment.NewLine);
}

There are other numerous ways but one of the above is probably what you'll go with.

Virtual member call in a constructor

Because until the constructor has completed executing, the object is not fully instantiated. Any members referenced by the virtual function may not be initialised. In C++, when you are in a constructor, this only refers to the static type of the constructor you are in, and not the actual dynamic type of the object that is being created. This means that the virtual function call might not even go where you expect it to.

Highlight a word with jQuery

Is it possible to get this above example:

jQuery.fn.highlight = function (str, className)
{
    var regex = new RegExp(str, "g");

    return this.each(function ()
    {
        this.innerHTML = this.innerHTML.replace(
            regex,
            "<span class=\"" + className + "\">" + str + "</span>"
        );
    });
};

not to replace text inside html-tags like , this otherwise breakes the page.

ssl_error_rx_record_too_long and Apache SSL

You might also try fixing the hosts file.

Keep the vhost file with the fully qualified domain and add the hostname in the hosts file /etc/hosts (debian)

ip.ip.ip.ip name name.domain.com

After restarting apache2, the error should be gone.

Why isn't sizeof for a struct equal to the sum of sizeof of each member?

Among the other well-explained answers about memory alignment and structure padding/packing, there is something which I have discovered in the question itself by reading it carefully.

"Why isn't sizeof for a struct equal to the sum of sizeof of each member?"

"Why does the sizeof operator return a size larger for a structure than the total sizes of the structure's members"?

Both questions suggest something what is plain wrong. At least in a generic, non-example focused view, which is the case here.

The result of the sizeof operand applied to a structure object can be equal to the sum of sizeof applied to each member separately. It doesn't have to be larger/different.

If there is no reason for padding, no memory will be padded.


One most implementations, if the structure contains only members of the same type:

struct foo {
   int a;   
   int b;
   int c;     
} bar;

Assuming sizeof(int) == 4, the size of the structure bar will be equal to the sum of the sizes of all members together, sizeof(bar) == 12. No padding done here.

Same goes for example here:

struct foo {
   short int a;   
   short int b;
   int c;     
} bar;

Assuming sizeof(short int) == 2 and sizeof(int) == 4. The sum of allocated bytes for a and b is equal to the allocated bytes for c, the largest member and with that everything is perfectly aligned. Thus, sizeof(bar) == 8.

This is also object of the second most popular question regarding structure padding, here:

Can't connect to MySQL server on 'localhost' (10061)

Edit your 'my-default.ini' file (by default it comes with commented properties)as below ie.

basedir=D:/D_Drive/mysql-5.6.20-win32
datadir=D:/D_Drive/mysql-5.6.20-win32/data
port=8888

There is very good article present that dictates commands to create user, browse tables etc ie.

http://www.ntu.edu.sg/home/ehchua/programming/sql/MySQL_HowTo.html#zz-3.1

How can you program if you're blind?

I'm blind and from some months I'm using VINUX (a linux distro based on Ubuntu) with SODBEANS (a version of netbeans with a plug-in named SAPPY that add a TTS support). This solution works quite well but sometimes I prefer to launch Win XP and NVDA for launching many pages on FireFox because Vinux doesn't work very well when you try to open more than 3 windows of FireFox...

Best C/C++ Network Library

Aggregated List of Libraries

How to force the browser to reload cached CSS and JavaScript files

Changing the filename will work. But that's not usually the simplest solution.

An HTTP cache-control header of 'no-cache' doesn't always work, as you've noticed. The HTTP 1.1 spec allows wiggle-room for user-agents to decide whether or not to request a new copy. (It's non-intuitive if you just look at the names of the directives. Go read the actual HTTP 1.1 spec for cache... it makes a little more sense in context.)

In a nutshell, if you want iron-tight cache-control use

Cache-Control: no-cache, no-store, must-revalidate

in your response headers.

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

Here's another path you can use. I'm not sure if this is part of the standard distribution or if the file is automatically created on first use of the IDLE.

C:\Python25\Lib\idlelib\idle.pyw

Open multiple Eclipse workspaces on the Mac

This seems to be the supported native method in OS X:

cd /Applications/eclipse/

open -n Eclipse.app

Be sure to specify the ".app" version (directory); in OS X Mountain Lion erroneously using the symbolic link such as open -n eclipse, might get one GateKeeper stopping access:

"eclipse" can't be opened because it is from an unidentified developer.

Your security preferences allow installation of only apps from the Mac App Store and identified developers.

Even removing the extended attribute com.apple.quarantine does not fix that. Instead, simply using the ".app" version will rely on your previous consent, or prompt you once:

"Eclipse" is an application downloaded from the Internet. Are you sure you want to open it?

Calculate text width with JavaScript

Without jQuery:

String.prototype.width = function (fontSize) {
    var el,
        f = fontSize + " px arial" || '12px arial';
    el = document.createElement('div');
    el.style.position = 'absolute';
    el.style.float = "left";
    el.style.whiteSpace = 'nowrap';
    el.style.visibility = 'hidden';
    el.style.font = f;
    el.innerHTML = this;
    el = document.body.appendChild(el);
    w = el.offsetWidth;
    el.parentNode.removeChild(el);
    return w;
}

// Usage
"MyString".width(12);

How do I ignore ampersands in a SQL script running from SQL Plus?

This may work for you:

set define off

Otherwise the ampersand needs to be at the end of a string,

'StackOverflow &' || ' you'

EDIT: I was click-happy when saving... This was referenced from a blog.

Use of 'const' for function parameters

the thing to remember with const is that it is much easier to make things const from the start, than it is to try and put them in later.

Use const when you want something to be unchanged - its an added hint that describes what your function does and what to expect. I've seen many an C API that could do with some of them, especially ones that accept c-strings!

I'd be more inclined to omit the const keyword in the cpp file than the header, but as I tend to cut+paste them, they'd be kept in both places. I have no idea why the compiler allows that, I guess its a compiler thing. Best practice is definitely to put your const keyword in both files.

How do I get a decimal value when using the division operator in Python?

Add the following function in your code with its callback.

# Starting of the function
def divide(number_one, number_two, decimal_place = 4):
    quotient = number_one/number_two
    remainder = number_one % number_two
    if remainder != 0:
        quotient_str = str(quotient)
        for loop in range(0, decimal_place):
            if loop == 0:
                quotient_str += "."
            surplus_quotient = (remainder * 10) / number_two
            quotient_str += str(surplus_quotient)
            remainder = (remainder * 10) % number_two
            if remainder == 0:
                break
        return float(quotient_str)
    else:
        return quotient
#Ending of the function

# Calling back the above function
# Structure : divide(<divident>, <divisor>, <decimal place(optional)>)
divide(1, 7, 10) # Output : 0.1428571428
# OR
divide(1, 7) # Output : 0.1428

This function works on the basis of "Euclid Division Algorithm". This function is very useful if you don't want to import any external header files in your project.

Syntex : divide([divident], [divisor], [decimal place(optional))

Code : divide(1, 7, 10) OR divide(1, 7)

Comment below for any queries.

Can anyone recommend a simple Java web-app framework?

Try this: http://skingston.com/SKWeb

It could do with some more features and improvements, but it is simple and it works.

Visual Studio: How to break on handled exceptions?

There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.

java get file size efficiently

The benchmark given by GHad measures lots of other stuff (such as reflection, instantiating objects, etc.) besides getting the length. If we try to get rid of these things then for one call I get the following times in microseconds:

   file sum___19.0, per Iteration___19.0
    raf sum___16.0, per Iteration___16.0
channel sum__273.0, per Iteration__273.0

For 100 runs and 10000 iterations I get:

   file sum__1767629.0, per Iteration__1.7676290000000001
    raf sum___881284.0, per Iteration__0.8812840000000001
channel sum___414286.0, per Iteration__0.414286

I did run the following modified code giving as an argument the name of a 100MB file.

import java.io.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;

public class FileSizeBench {

  private static File file;
  private static FileChannel channel;
  private static RandomAccessFile raf;

  public static void main(String[] args) throws Exception {
    int runs = 1;
    int iterations = 1;

    file = new File(args[0]);
    channel = new FileInputStream(args[0]).getChannel();
    raf = new RandomAccessFile(args[0], "r");

    HashMap<String, Double> times = new HashMap<String, Double>();
    times.put("file", 0.0);
    times.put("channel", 0.0);
    times.put("raf", 0.0);

    long start;
    for (int i = 0; i < runs; ++i) {
      long l = file.length();

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != file.length()) throw new Exception();
      times.put("file", times.get("file") + System.nanoTime() - start);

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != channel.size()) throw new Exception();
      times.put("channel", times.get("channel") + System.nanoTime() - start);

      start = System.nanoTime();
      for (int j = 0; j < iterations; ++j)
        if (l != raf.length()) throw new Exception();
      times.put("raf", times.get("raf") + System.nanoTime() - start);
    }
    for (Map.Entry<String, Double> entry : times.entrySet()) {
        System.out.println(
            entry.getKey() + " sum: " + 1e-3 * entry.getValue() +
            ", per Iteration: " + (1e-3 * entry.getValue() / runs / iterations));
    }
  }
}

C compiler for Windows?

You could always just use gcc via cygwin.

What is the difference between vmalloc and kmalloc?

One of other differences is kmalloc will return logical address (else you specify GPF_HIGHMEM). Logical addresses are placed in "low memory" (in the first gigabyte of physical memory) and are mapped directly to physical addresses (use __pa macro to convert it). This property implies kmalloced memory is continuous memory.

In other hand, Vmalloc is able to return virtual addresses from "high memory". These addresses cannot be converted in physical addresses in a direct fashion (you have to use virt_to_page function).

How do I kill a process using Vb.NET or C#?

Something like this will work:

foreach ( Process process in Process.GetProcessesByName( "winword" ) )
{
    process.Kill();
    process.WaitForExit();
}

How do I ignore a directory with SVN?

...and if you want to ignore more than one directory (say build/ temp/ and *.tmp files), you could either do it in two steps (ignoring the first and edit ignore properties (see other answers here) or one could write something like

svn propset svn:ignore "build
temp
*.tmp" .

on the command line.

How can I add an empty directory to a Git repository?

The solution of Jamie Flournoy works great. Here is a bit enhanced version to keep the .htaccess :

# Ignore everything in this directory
*
# Except this file
!.gitignore
!.htaccess

With this solution you are able to commit a empty folder, for example /log, /tmp or /cache and the folder will stay empty.

Indirectly referenced from required .class file

This issue happen because of few jars are getting references from other jar and reference jar is missing .

Example : Spring framework

Description Resource    Path    Location    Type
The project was not built since its build path is incomplete. Cannot find the class file for org.springframework.beans.factory.annotation.Autowire. Fix the build path then try building this project   SpringBatch     Unknown Java Problem

In this case "org.springframework.beans.factory.annotation.Autowire" is missing.

Spring-bean.jar is missing

Once you add dependency in your class path issue will resolve.

How do I get the title of the current active window using c#?

If you were talking about WPF then use:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

Storing C++ template function definitions in a .CPP file

There is nothing wrong with the example you have given. But i must say i believe it's not efficient to store function definitions in a cpp file. I only understand the need to separate the function's declaration and definition.

When used together with explicit class instantiation, the Boost Concept Check Library (BCCL) can help you generate template function code in cpp files.

Best PHP IDE for Mac? (Preferably free!)

Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.

UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.