Programs & Examples On #Ora 03113

ORA-03113: end-of-file on communication channel

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

You could try this registry hack:


If it works, just keep increasing the KeepAliveTime. It is currently set for 2 minutes.

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

@Amit's answer is good because it will work in both Mustache and Handlebars.

As far as Handlebars-only solutions, I've seen a few and I like the each_with_key block helper at the best.

  • It allows you to iterate over object literals without having to restructure them first, and
  • It gives you control over what you call the key variable. With many other solutions you have to be careful about using object keys named 'key', or 'property', etc.

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

Sometimes simplicity is the key to success. Search for while (i <= 10000) {} without increasing i in your code ;)

CSS vertical-align: text-bottom;

Sometimes you can play with padding and margin top, add line-height, etc.

See fiddle.

Style and text forked from @aspirinemaga

    border:1px solid red;

Setting the correct PATH for Eclipse

I am using Windows 8.1 environment. I had the same problem while running my first java program after installing Eclipse recently. I had installed java on d drive at d:\java. But Eclipse was looking at the default installation c:\programfiles\java. I did the following:

  1. Modified my eclipse.ini file and added the following after open:

  2. While creating the java program I have to unselect default build path and then select d:\java.

After this, the program ran well and got the hello world to work.

How do I split a string in Rust?

split returns an Iterator, which you can convert into a Vec using collect: split_line.collect::<Vec<_>>(). Going through an iterator instead of returning a Vec directly has several advantages:

  • split is lazy. This means that it won't really split the line until you need it. That way it won't waste time splitting the whole string if you only need the first few values: split_line.take(2).collect::<Vec<_>>(), or even if you need only the first value that can be converted to an integer: split_line.filter_map(|x| x.parse::<i32>().ok()).next(). This last example won't waste time attempting to process the "23.0" but will stop processing immediately once it finds the "1".
  • split makes no assumption on the way you want to store the result. You can use a Vec, but you can also use anything that implements FromIterator<&str>, for example a LinkedList or a VecDeque, or any custom type that implements FromIterator<&str>.

Removing spaces from a variable input using PowerShell 4.0

You can use:

$answer.replace(' ' , '')


$answer -replace " ", ""

if you want to remove all whitespace you can use:

$answer -replace "\s", ""

Redis - Connect to Remote Server

First I'd check to verify it is listening on the IPs you expect it to be:

netstat -nlpt | grep 6379

Depending on how you start/stop you may not have actually restarted the instance when you thought you had. The netstat will tell you if it is listening where you think it is. If not, restart it and be sure it restarts. If it restarts and still is not listening where you expect, check your config file just to be sure.

After establishing it is listening where you expect it to, from a remote node which should have access try:

redis-cli -h REMOTE.HOST ping

You could also try that from the local host but use the IP you expect it to be listening on instead of a hostname or localhost. You should see it PONG in response in both cases.

If not, your firewall(s) is/are blocking you. This would be either the local IPTables or possibly a firewall in between the nodes. You could add a logging statement to your IPtables configuration to log connections over 6379 to see what is happening. Also, trying he redis ping from local and non-local to the same IP should be illustrative. If it responds locally but not remotely, I'd lean toward an intervening firewall depending on the complexity of your on-node IP Tables rules.

vagrant login as root by default

Note: Only use this method for local development, it's not secure. You can setup password and ssh config while provisioning the box. For example with debian/stretch64 box this is my provision script:

config.vm.provision "shell", inline: <<-SHELL
    echo -e "vagrant\nvagrant" | passwd root
    echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
    sed -in 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
    service ssh restart

This will set root password to vagrant and permit root login with password. If you are using private_network say with ip address then you can ssh with ssh [email protected]

You may need to change that echo and sed commands depending on the default sshd_config file.

Extract code country from phone number [libphonenumber]

Here is a solution to get the country based on an international phone number without using the Google library.

Let me explain first why it is so difficult to figure out the country. The country code of few countries is 1 digit, 2, 3 or 4 digits. That would be simple enough. But the country code 1 is not just used for US, but also for Canada and some smaller places:

1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada

Digits 2..4 decide, if it is US or Canada or ... There is no easy way to figure out the country, like the first xxx are Canada, the rest US.

For my code, I defined a class which holds information for ever digit:

public class DigitInfo {
  public char Digit;
  public Country? Country;
  public DigitInfo?[]? Digits;

A first array holds the DigitInfos for the first digit in the number. The second digit is used as an index into DigitInfo.Digits. One travels down that Digits chain, until Digits is empty. If Country is defined (i.e. not null) that value gets returned, otherwise any Country defined earlier gets returned:

country code 1: byPhone[1].Country is US  
country code 1236: byPhone[1].Digits[2].Digits[3].Digits[6].Country is Canada  
country code 1235: byPhone[1].Digits[2].Digits[3].Digits[5].Country is null. Since   
                   byPhone[1].Country is US, also 1235 is US, because no other   
                   country was found in the later digits

Here is the method which returns the country based on the phone number:

/// <summary>
/// Returns the Country based on an international dialing code.
/// </summary>
public static Country? GetCountry(ReadOnlySpan<char> phoneNumber) {
  if (phoneNumber.Length==0) return null;

  var isFirstDigit = true;
  DigitInfo? digitInfo = null;
  Country? country = null;
  foreach (var digitChar in phoneNumber) {
    var digitIndex = digitChar - '0';
    if (isFirstDigit) {
      isFirstDigit = false;
      digitInfo = ByPhone[digitIndex];
    } else {
      if (digitInfo!.Digits is null) return country;

      digitInfo = digitInfo.Digits[digitIndex];
    if (digitInfo is null) return country;

    country = digitInfo.Country??country;
  return country;

The rest of the code (digitInfos for every country of the world, test code, ...) is too big to be posted here, but it can be found on Github:

The code is part of a WPF TextBox and the library contains also other controls for email addresses, etc. A more detailed description is on CodeProject: International Phone Number Validation Explained in Detail

Java: get greatest common divisor

If you are using Java 1.5 or later then this is an iterative binary GCD algorithm which uses Integer.numberOfTrailingZeros() to reduce the number of checks and iterations required.

public class Utils {
    public static final int gcd( int a, int b ){
        // Deal with the degenerate case where values are Integer.MIN_VALUE
        // since -Integer.MIN_VALUE = Integer.MAX_VALUE+1
        if ( a == Integer.MIN_VALUE )
            if ( b == Integer.MIN_VALUE )
                throw new IllegalArgumentException( "gcd() is greater than Integer.MAX_VALUE" );
            return 1 << Integer.numberOfTrailingZeros( Math.abs(b) );
        if ( b == Integer.MIN_VALUE )
            return 1 << Integer.numberOfTrailingZeros( Math.abs(a) );

        a = Math.abs(a);
        b = Math.abs(b);
        if ( a == 0 ) return b;
        if ( b == 0 ) return a;
        int factorsOfTwoInA = Integer.numberOfTrailingZeros(a),
            factorsOfTwoInB = Integer.numberOfTrailingZeros(b),
            commonFactorsOfTwo = Math.min(factorsOfTwoInA,factorsOfTwoInB);
        a >>= factorsOfTwoInA;
        b >>= factorsOfTwoInB;
        while(a != b){
            if ( a > b ) {
                a = (a - b);
                a >>= Integer.numberOfTrailingZeros( a );
            } else {
                b = (b - a);
                b >>= Integer.numberOfTrailingZeros( b );
        return a << commonFactorsOfTwo;

Unit test:

import java.math.BigInteger;
import org.junit.Test;
import static org.junit.Assert.*;

public class UtilsTest {
    public void gcdUpToOneThousand(){
        for ( int x = -1000; x <= 1000; ++x )
            for ( int y = -1000; y <= 1000; ++y )
                int gcd = Utils.gcd(x, y);
                int expected = BigInteger.valueOf(x).gcd(BigInteger.valueOf(y)).intValue();
                assertEquals( expected, gcd );

    public void gcdMinValue(){
        for ( int x = 0; x < Integer.SIZE-1; x++ ){
            int gcd = Utils.gcd(Integer.MIN_VALUE,1<<x);
            int expected = BigInteger.valueOf(Integer.MIN_VALUE).gcd(BigInteger.valueOf(1<<x)).intValue();
            assertEquals( expected, gcd );

Abstract Class:-Real Time Example

A good example of real time found from here:-

A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.

A business example:

I have a persistance engine that will work against any data sourcer (XML, ASCII (delimited and fixed-length), various JDBC sources (Oracle, SQL, ODBC, etc.) I created a base, abstract class to provide common functionality in this persistance, but instantiate the appropriate "Port" (subclass) when persisting my objects. (This makes development of new "Ports" much easier, since most of the work is done in the superclasses; especially the various JDBC ones; since I not only do persistance but other things [like table generation], I have to provide the various differences for each database.) The best business examples of Interfaces are the Collections. I can work with a java.util.List without caring how it is implemented; having the List as an abstract class does not make sense because there are fundamental differences in how anArrayList works as opposed to a LinkedList. Likewise, Map and Set. And if I am just working with a group of objects and don't care if it's a List, Map, or Set, I can just use the Collection interface.

Convert byte[] to char[]

You must know the source encoding.

string someText = "The quick brown fox jumps over the lazy dog.";
byte[] bytes = Encoding.Unicode.GetBytes(someText);
char[] chars = Encoding.Unicode.GetChars(bytes);

Overwriting my local branch with remote branch

What I do when I mess up my local branch is I just rename my broken branch, and check out/branch the upstream branch again:

git branch -m branch branch-old
git fetch remote
git checkout -b branch remote/branch

Then if you're sure you don't want anything from your old branch, remove it:

git branch -D branch-old

But usually I leave the old branch around locally, just in case I had something in there.

How to disable spring security for particular url

When using permitAll it means every authenticated user, however you disabled anonymous access so that won't work.

What you want is to ignore certain URLs for this override the configure method that takes WebSecurity object and ignore the pattern.

public void configure(WebSecurity web) throws Exception {

And remove that line from the HttpSecurity part. This will tell Spring Security to ignore this URL and don't apply any filters to them.

how to set ASPNETCORE_ENVIRONMENT to be considered for publishing an core application?

This variable can be saved in json. For example envsettings.json with content as below

   // Possible string values reported below. When empty it use ENV variable value or 
     // Visual Studio setting.
     // - Production
     // - Staging
     // - Test
     // - Development


Later modify your program.cs as below

  public class Program
    public static IConfiguration Configuration { get; set; }
    public static void Main(string[] args)
        var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var environmentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();

        var builder = new ConfigurationBuilder()

        Configuration = builder.Build();
          var webHostBuilder = new WebHostBuilder()

        // If none is set it use Operative System hosting enviroment
        if (!string.IsNullOrWhiteSpace(environmentValue))

        var host = webHostBuilder.Build();


This way it will always be included in publish and you can change to required value according to environment where website is hosted. This method can also be used in console app as the changes are in Program.cs

Android - Share on Facebook, Twitter, Mail, ecc

sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"your subject" );
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "your text");
startActivity(Intent.createChooser(sharingIntent, ""));

How to make a UILabel clickable?

Swift 5

Similar to @liorco, but need to replace @objc with @IBAction.

class DetailViewController: UIViewController {

    @IBOutlet weak var tripDetails: UILabel!

    override func viewDidLoad() {

        let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
        tripDetails.isUserInteractionEnabled = true

    @IBAction func tapFunction(sender: UITapGestureRecognizer) {
        print("tap working")

This is working on Xcode 10.2.

Format numbers in JavaScript similar to C#

Firstly, converting an integer into string in JS is really simple:

// Start off with a number
var number = 42;
// Convert into a string by appending an empty (or whatever you like as a string) to it
var string = 42+'';
// No extra conversion is needed, even though you could actually do
var alsoString = number.toString();

If you have a number as a string and want it to be turned to an integer, you have to use the parseInt(string) for integers and parseFloat(string) for floats. Both of these functions then return the desired integer/float. Example:

// Start off with a float as a string
var stringFloat = '3.14';
// And an int as a string
var stringInt = '42';

// typeof stringInt  would give you 'string'

// Get the real float from the string
var realFloat = parseFloat(someFloat);
// Same for the int
var realInt = parseInt(stringInt);

// but typeof realInt  will now give you 'number'

What exactly are you trying to append etc, remains unclear to me from your question.

Twitter Bootstrap date picker

The most popular bootstrap date picker is currently: (thanks to @dentarg for digging it up)

A simple instantiation only requires:


<input class="datepicker">



See a simple example here or the full docs here

iOS 7 - Failing to instantiate default view controller

Projects created in Xcode 11 and above, simply changing the Main Interface file from the project settings won't be enough.

You have to manually edit the Info.plist file and set the storyboard name for the UISceneStoryboardFile as well.

How to remove unique key from mysql table

ALTER TABLE mytable DROP INDEX key_Name;

How can I change IIS Express port for a site

.Net Core

For those who got here looking for this configuration in .Net core this resides in the lauchSettings.json. Just edit the port in the property "applicationUrl".

The file should look something like this:

  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:53950/", //Here
      "sslPort": 0
  "profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "index.html",
      "environmentVariables": {
        "Hosting:Environment": "Development"

Or you can use the GUI by double clicking in the "Properties" of your project.

Note: I had to reopen VS to make it work.

How to send FormData objects with Ajax-requests in jQuery?

I do it like this and it's work for me, I hope this will help :)

   <div id="data">
            <input type="file" name="userfile" id="userfile" size="20" />
            <br /><br />
            <input type="button" id="upload" value="upload" />

                    console.log('upload button clicked!')
                    var fd = new FormData();    
                    fd.append( 'userfile', $('#userfile')[0].files[0]);

                      url: 'upload/do_upload',
                      data: fd,
                      processData: false,
                      contentType: false,
                      type: 'POST',
                      success: function(data){
                        console.log('upload success!')


Random String Generator Returning Same String

As long as you are using Asp.Net 2.0 or greater, you can also use the library call- System.Web.Security.Membership.GeneratePassword, however it will include special characters.

To get 4 random characters with minimum of 0 special characters-

Membership.GeneratePassword(4, 0)

An error occurred while updating the entries. See the inner exception for details

Click "View Detail..." a window will open where you can expand the "Inner Exception" my guess is that when you try to delete the record there is a reference constraint violation. The inner exception will give you more information on that so you can modify your code to remove any references prior to deleting the record.

enter image description here

I get conflicting provisioning settings error when I try to archive to submit an iOS app

In my case I had to login to Apple Developer Website and reset the list of devices.

It appears they now require you to do it every year when the subscription is renewed, before being able to add new devices and generate certificates.

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Running npm command within Visual Studio Code

VSCode User Setup is a new installer which installs VSCode and its dependencies in directories which don't require system-level / administrator permissions to modify. This is because New VSCode runs with user privileges. Your Nodejs installation added npm's path as System variable which VSCode cannot read.

Adding NPM path to Path variable in the User variable, you will be able to run NPM from the integrated command line.

Python requests library how to pass Authorization header with single token

You can also set headers for the entire session:

TOKEN = 'abcd0123'
HEADERS = {'Authorization': 'token {}'.format(TOKEN)}

with requests.Session() as s:

    resp = s.get('')

A full list of all the new/popular databases and their uses?

Martin Fowler did an interesting blog post last year about non-relational databases starting to gain traction. He mentions:

  • Drizzle (a "bare bones" relational database)
  • CouchDB (a document-oriented database)
  • GemStone (an object-oriented database)

There is also Google's BigTable which is described as "a sparse, distributed multi-dimensional sorted map".

I have been working with GemStone for a number of years now and the productivity gains is amazing - having the database store your objects directly removes the need to constantly marshall back and forth between tables and objects.

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

Just go to the project Properties->Project Facets

  1. Uncheck the dynamic module, click apply.

  2. Maven->update the project.

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I think I got this from not explicitly deleting some tables from the edmx before renaming and re-adding them. Instead, I just renamed the tables and then did an Update Model from Database, thinking it would see them gone, and delete them from model. I then did another Update Model from Database and added the renamed tables.

The site was working with the new tables, but I had the error. Eventually, I noticed the original tables were still in the model. I deleted them from the model (click them in edmx screen, delete key), and then the error went away.

Read and write to binary files in C?

I really struggled to find a way to read a binary file into a byte array in C++ that would output the same hex values I see in a hex editor. After much trial and error, this seems to be the fastest way to do so without extra casts. By default it loads the entire file into memory, but only prints the first 1000 bytes.

string Filename = "BinaryFile.bin";
FILE* pFile;
pFile = fopen(Filename.c_str(), "rb");
fseek(pFile, 0L, SEEK_END);
size_t size = ftell(pFile);
fseek(pFile, 0L, SEEK_SET);
uint8_t* ByteArray;
ByteArray = new uint8_t[size];
if (pFile != NULL)
    int counter = 0;
    do {
        ByteArray[counter] = fgetc(pFile);
    } while (counter <= size);
for (size_t i = 0; i < 800; i++) {
    printf("%02X ", ByteArray[i]);

Get only the date in timestamp in mysql

$date= new DateTime($row['your_date']) ;  
echo $date->format('Y-m-d');

JOptionPane YES/No Options Confirm Dialog Box Issue

Try this,

int dialogButton = JOptionPane.YES_NO_OPTION;
int dialogResult = JOptionPane.showConfirmDialog(this, "Your Message", "Title on Box", dialogButton);
if(dialogResult == 0) {
  System.out.println("Yes option");
} else {
  System.out.println("No Option");

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:


$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");


$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.


I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

| word   | num_bytes | num_characters |
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |

Be careful if you're dealing with multi-byte characters.

file_get_contents behind a proxy?

Use stream_context_set_default function. It is much easier to use as you can directly use file_get_contents or similar functions without passing any additional parameters

This blog post explains how to use it. Here is the code from that page.

// Edit the four values below
$PROXY_HOST = ""; // Proxy server address
$PROXY_PORT = "1234";    // Proxy server port
$PROXY_USER = "LOGIN";    // Username
$PROXY_PASS = "PASSWORD";   // Password
// Username and Password are required only if your proxy server needs basic authentication

$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
  'http' => array(
   'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
   'request_fulluri' => true,
   'header' => "Proxy-Authorization: Basic $auth"
   // Remove the 'header' option if proxy authentication is not required

$url = "";

print_r( get_headers($url) );

echo file_get_contents($url);

Getting an Embedded YouTube Video to Auto Play and Loop

Had same experience, however what did the magic for me is not to change embed to v.

So the code will look like this...

<iframe width="560" height="315" src="" frameborder="0" allowfullscreen></iframe>

Hope it helps...

How to set base url for rest in spring boot?

server.servlet.context-path=/api would be the solution I guess. I had the same issue and this got me solved. I used server.context-path. However, that seemed to be deprecated and I found that server.servlet.context-path solves the issue now. Another workaround I found was adding a base tag to my front end (H5) pages. I hope this helps someone out there.


Find Java classes implementing an interface

If you were asking from the perspective of working this out with a running program then you need to look to the java.lang.* package. If you get a Class object, you can use the isAssignableFrom method to check if it is an interface of another Class.

There isn't a simple built in way of searching for these, tools like Eclipse build an index of this information.

If you don't have a specific list of Class objects to test you can look to the ClassLoader object, use the getPackages() method and build your own package hierarchy iterator.

Just a warning though that these methods and classes can be quite slow.

Bootstrap: align input with button

Not directly related, unless you have similar code but I just noticed a strange behaviour to form-inline, bootstrap 3.3.7

I did not use row and cells for this as it is a desktop project, if the opening tag was below table (in this case):

<table class="form-inline"> 

Form elements would stack.

Switch and it properly lined up.

<table class="form-inline">

Safari 10.0.2 and latest Chrome did not make any differences. Maybe my layout was wrong but it is not very forgiving.

Showing empty view when ListView is empty

When you extend FragmentActivity or Activity and not ListActivity, you'll want to take a look at:


Java: recommended solution for deep cloning/copying an instance

I'd recommend the DIY way which, combined with a good hashCode() and equals() method should be easy to proof in a unit test.

No value accessor for form control

In my case, I used Angular forms with contenteditable elements like div and had similar problems before.

I wrote ng-contenteditable module to resolve this problem.

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

For a very specific reason Type Nullable<int> put your cursor on Nullable and hit F12 - The Metadata provides the reason (Note the struct constraint):

public struct Nullable<T> where T : struct

Could not load file or assembly for Oracle.DataAccess in .NET

The solution is quite simple, it is all a matter of how you define things on the server / workstation in relation to your visual studio project.

First check the version of the Oracle library that you are using, in your case Next go to the Windows GAC located in your windows home->assembly folder.

Scroll down to the Oracle dll, it is normally called Oracle.DataAccess or Oracle.Web. Find the right version of it and note down if it says x86 or AMD64.

In visual studio ensure that your target platform is the same as the dll in the GAC, so if it says x86 in the GAC folder ensure that the target platform is x64 and other x64. You can set this in Visual Studio project properties, under build/platform target.

Also ensure that your reference, under references in your project points to this exact same version on your development computer.

With this everything should work fine.

What I normally do is to check the server first as it is often easier in an enterprise environment to change the version of your local dependencies, then to ask a server administrator to do an installation of a different dll.

CSS: create white glow around image

You can use CSS3 to create an effect like that, but then you're only going to see it in modern browsers that support box shadow, unless you use a polyfill like CSS3PIE. So, for example, you could do something like this:

Getting files by creation date in .NET

@jing: "The DirectoryInfo solution is much faster then this (especially for network path)"

I cant confirm this. It seems as if Directory.GetFiles triggers a filesystem or network cache. The first request takes a while, but the following requests are much faster, even if new files were added. In my test I did a Directory.getfiles and a info.GetFiles with the same patterns and both run equally

GetFiles  done 437834 in00:00:20.4812480
process files  done 437834 in00:00:00.9300573
GetFiles by Dirinfo(2)  done 437834 in00:00:20.7412646

Get next element in foreach loop

You could probably use while loop instead of foreach:

while ($current = current($array) )
    $next = next($array);
    if (false !== $next && $next == $current)
        //do something with $current

Html.DropdownListFor selected value not being set

Add the Controller Section

  ViewBag.Orders= new SelectList(db.Orders, "Id", "business", paramid);

Add the Html Section

   @Html.DropDownList("Orders", null)

A simple method

Pyinstaller setting icons don't change

I know this is old and whatnot (and not exactly sure if it's a question), but after searching, I had success with this command for --onefile:

pyinstaller.exe --onefile --windowed --icon=app.ico

Google led me to this page while I was searching for an answer on how to set an icon for my .exe, so maybe it will help someone else.

The information here was found at this site:

How to break out from a ruby block?

use the keyword break instead of return

Java Object Null Check for method

public static double calculateInventoryTotal(Book[] arrayBooks) {

    final AtomicReference<BigDecimal> total = new AtomicReference<>(BigDecimal.ZERO);
    Optional.ofNullable(arrayBooks).map(Arrays::asList).ifPresent(books -> books.forEach(book -> total.accumulateAndGet(book.getPrice(), BigDecimal::add)));
    return total.get().doubleValue();


How to add months to a date in JavaScript?

Corrected as of 25.06.2019:

var newDate = new Date(date.setMonth(date.getMonth()+8));

Old From here:

var jan312009 = new Date(2009, 0, 31);
var eightMonthsFromJan312009  = jan312009.setMonth(jan312009.getMonth()+8);

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

Just convert numbers from int64 (from numpy) to int.

For example, if variable x is a int64:


If is array of int64:

map(int, x)

HTTP redirect: 301 (permanent) vs. 302 (temporary)

Status 301 means that the resource (page) is moved permanently to a new location. The client/browser should not attempt to request the original location but use the new location from now on.

Status 302 means that the resource is temporarily located somewhere else, and the client/browser should continue requesting the original url.

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
        document.getElementById('<%= savebtn.ClientID %>').click();

web-api POST body object always null

If the any of values of the request's JSON object are not the same type as expected by the service then the [FromBody] argument will be null.

For example, if the age property in the json had a float value:


but the API service expects it to be an int


then student will be null. (No error messages will be sent in the response unless no null reference check).

How is the java memory pool divided?

The Heap is divided into young and old generations as follows :

Young Generation: It is a place where an object lived for a short period and it is divided into two spaces:

  • Eden Space: When object created using new keyword memory allocated on this space.
  • Survivor Space (S0 and S1): This is the pool which contains objects which have survived after minor java garbage collection from Eden space.

Old Generation: This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from the Young Generation.

  • Tenured Space: This memory pool contains objects which survived after multiple garbage collection means an object which survived after garbage collection from Survivor space.

enter image description here


Let's imagine our application has just started.

So at this point all three of these spaces are empty (Eden, S0, S1).

Whenever a new object is created it is placed in the Eden space.

When the Eden space gets full then the garbage collection process (minor GC) will take place on the Eden space and any surviving objects are moved into S0.

Our application then continues running add new objects are created in the Eden space the next time that the garbage collection process runs it looks at everything in the Eden space and in S0 and any objects that survive get moved into S1.

PS: Based on the configuration that how much time object should survive in Survivor space, the object may also move back and forth to S0 and S1 and then reaching the threshold objects will be moved to old generation heap space.

What does $(function() {} ); do?

I think you may be confusing Javascript with jQuery methods. Vanilla or plain Javascript is something like:

function example() {

A function of that nature can be called at any time, anywhere.

jQuery (a library built on Javascript) has built in functions that generally required the DOM to be fully rendered before being called. The syntax for when this is completed is:

$(document).ready(function() {

So a jQuery function, which is prefixed with the $ or the word jQuery generally is called from within that method.

$(document).ready(function() {        
    // Assign all list items on the page to be the  color red.  
    //      This does not work until AFTER the entire DOM is "ready", hence the $(document).ready()
    $('li').css('color', 'red');   

The pseudo-code for that block is:

When the document object model $(document) is ready .ready(), call the following function function() { }. In that function, check for all <li>'s on the page $('li') and using the jQuery method .CSS() to set the CSS property "color" to the value "red" .css('color', 'red');

How to apply a CSS class on hover to dynamically generated submit buttons?

Add the below code

input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;

If you need only for these button then you can add id name

#paginate input[type="submit"]:hover {
    border: 1px solid #999;
    color: #000;


Link to add to Google calendar

Here's an example link you can use to see the format:,+link+here:+,+301+Park+Ave+,+New+York,+NY+10022&sf=true&output=xml

Note the key query parameters:


Here's another example (taken from

<a href="
&dates=[start-custom format='Ymd\\THi00\\Z']/[end-custom format='Ymd\\THi00\\Z']
target="_blank" rel="nofollow">Add to my calendar</a>

Here's a form which will help you construct such a link if you want (mentioned in earlier answers): Edit: This link no longer gives you a form you can use

Messages Using Command prompt in Windows 7

Open Notepad and write this

@echo off
set /p n=User:
set /p m=Message:
net send %n% %m%
Goto A

and then save as "Messenger.bat" and close the Notepad
Step 1:

when you open that saved notepad file it will open as a file Messenger command prompt with this details.


after "User" write the ip of the computer you want to contact and then press enter.

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

Other possible solution:

tv.setText(Integer.toString(a1));  // where a1 - int value

Custom exception type

Use the throw statement.

JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".

If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.

Excel VBA For Each Worksheet Loop

Try to slightly modify your code:

Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call resizingColumns(ws)
End Sub

Sub resizingColumns(ws As Worksheet)
    With ws
        .Range("A:A").ColumnWidth = 20.14
        .Range("B:B").ColumnWidth = 9.71
        .Range("C:C").ColumnWidth = 35.86
        .Range("D:D").ColumnWidth = 30.57
        .Range("E:E").ColumnWidth = 23.57
        .Range("F:F").ColumnWidth = 21.43
        .Range("G:G").ColumnWidth = 18.43
        .Range("H:H").ColumnWidth = 23.86
        .Range("i:I").ColumnWidth = 27.43
        .Range("J:J").ColumnWidth = 36.71
        .Range("K:K").ColumnWidth = 30.29
        .Range("L:L").ColumnWidth = 31.14
        .Range("M:M").ColumnWidth = 31
        .Range("N:N").ColumnWidth = 41.14
        .Range("O:O").ColumnWidth = 33.86
    End With
End Sub

Note, resizingColumns routine takes parametr - worksheet to which Ranges belongs.

Basically, when you're using Range("O:O") - code operats with range from ActiveSheet, that's why you should use With ws statement and then .Range("O:O").

And there is no need to use global variables (unless you are using them somewhere else)

how to add or embed CKEditor in php page

Easy steps to Integrate ckeditor with php pages

step 1 : download the file

step 2 : paste file on root directory of the site or you can paste it where the files are (i did this one )

step 3 : extract the file

step 4 : open the desired php page you want to integrate with here page1.php

step 5 : add some javascript first below, this is to call elements of ckeditor and styling and css without this you will only a blank textarea

<script type="text/javascript" src="ckeditor/ckeditor.js"></script>

And if you are using in other sites, then use relative links for that here is one below

<script type="text/javascript" src="somedirectory/ckeditor/ckeditor.js"></script>

step 6 : now!, you need to call the work code of ckeditor on your page page1.php below is how you call it


// Make sure you are using a correct path here.
include_once 'ckeditor/ckeditor.php';

$ckeditor = new CKEditor();
$ckeditor->basePath = '/ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = '/ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = '/ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = '/ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = '/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';


step 7 : what ever you name you want, you can name to it ckeditor by changing the step 6 code last line


step 8 : Open-up the page1.php, see it, use it, share it and Enjoy because we all love Open Source.


What's the bad magic number error?

You will need to run this command in every path you have in your environment.

>>> import sys
>>> sys.path
['', '/usr/lib/', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/dist-packages', '/source_code/src/python', '/usr/lib/python3/dist-packages']

Then run the command in every directory here

find /usr/lib/python3.6/ -name "*.pyc" -delete
find /usr/local/lib/python3.6/dist-packages -name "*.pyc" -delete
# etc...

How to convert a string of numbers to an array of numbers?

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.


  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids =; // [1, 3, 4, 7]
    var arr = ["1", 5, "7", 11];
    var ints=; // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000,;
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    > f(Number)
    > 3964 // still the same
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    > f(parseFloat)
    > 3737 // all ok
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

Deep copy, shallow copy, clone

The term "clone" is ambiguous (though the Java class library includes a Cloneable interface) and can refer to a deep copy or a shallow copy. Deep/shallow copies are not specifically tied to Java but are a general concept relating to making a copy of an object, and refers to how members of an object are also copied.

As an example, let's say you have a person class:

class Person {
    String name;
    List<String> emailAddresses

How do you clone objects of this class? If you are performing a shallow copy, you might copy name and put a reference to emailAddresses in the new object. But if you modified the contents of the emailAddresses list, you would be modifying the list in both copies (since that's how object references work).

A deep copy would mean that you recursively copy every member, so you would need to create a new List for the new Person, and then copy the contents from the old to the new object.

Although the above example is trivial, the differences between deep and shallow copies are significant and have a major impact on any application, especially if you are trying to devise a generic clone method in advance, without knowing how someone might use it later. There are times when you need deep or shallow semantics, or some hybrid where you deep copy some members but not others.

What are some examples of commonly used practices for naming git branches?

Note, as illustrated in the commit e703d7 or commit b6c2a0d (March 2014), now part of Git 2.0, you will find another naming convention (that you can apply to branches).

"When you need to use space, use dash" is a strange way to say that you must not use a space.
Because it is more common for the command line descriptions to use dashed-multi-words, you do not even want to use spaces in these places.

A branch name cannot have space (see "Which characters are illegal within a branch name?" and git check-ref-format man page).

So for every branch name that would be represented by a multi-word expression, using a '-' (dash) as a separator is a good idea.

Program to find largest and second largest number in array

If you ever need to find the largest or smallest element in an array, try with bubble sort. Bubble Sort works on simple concept of shifting the biggest element at the end in every pass it does (in case of increasing order). Since you need the first and second largest element in an array, 2 passes of bubble sort will do the trick. The last element will be the largest and the second last element will be second largest. I'm providing you with the link that'll help you understand the bubble sort concept.

Hope it helps!!!

How can I make robocopy silent in the command line except for progress?

There's no need to redirect to a file and delete it later. Try:

Robocopy src dest > null 

OR operator in switch-case?

What are the backgrounds for a switch-case to not accept this operator?

Because case requires constant expression as its value. And since an || expression is not a compile time constant, it is not allowed.

From JLS Section 14.11:

Switch label should have following syntax:

case ConstantExpression :
case EnumConstantName :
default :

Under the hood:

The reason behind allowing just constant expression with cases can be understood from the JVM Spec Section 3.10 - Compiling Switches:

Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.

So, for the cases label to be used by tableswitch as a index into the table of target offsets, the value of the case should be known at compile time. That is only possible if the case value is a constant expression. And || expression will be evaluated at runtime, and the value will only be available at that time.

From the same JVM section, the following switch-case:

switch (i) {
    case 0:  return  0;
    case 1:  return  1;
    case 2:  return  2;
    default: return -1;

is compiled to:

0   iload_1             // Push local variable 1 (argument i)
1   tableswitch 0 to 2: // Valid indices are 0 through 2  (NOTICE This instruction?)
      0: 28             // If i is 0, continue at 28
      1: 30             // If i is 1, continue at 30
      2: 32             // If i is 2, continue at 32
      default:34        // Otherwise, continue at 34
28  iconst_0            // i was 0; push int constant 0...
29  ireturn             // ...and return it
30  iconst_1            // i was 1; push int constant 1...
31  ireturn             // ...and return it
32  iconst_2            // i was 2; push int constant 2...
33  ireturn             // ...and return it
34  iconst_m1           // otherwise push int constant -1...
35  ireturn             // ...and return it

So, if the case value is not a constant expressions, compiler won't be able to index it into the table of instruction pointers, using tableswitch instruction.

Using CSS to affect div style inside iframe

Yes. Take a look at this other thread for details: How to apply CSS to iframe?

var cssLink = document.createElement("link");
cssLink.href = "style.css";  
cssLink.rel = "stylesheet";  
cssLink.type = "text/css";  

Search of table names

Adding on to @[RichardTheKiwi]'s answer.

Whenever I search for a list of tables, in general I want to select from all of them or delete them. Below is a script that generates those scripts for you.

The generated select script also adds a tableName column so you know what table you're looking at:

select 'select ''' + name + ''' as TableName, * from ' + name as SelectTable,
'delete from ' + name as DeleteTable
from sys.tables
where name like '%xxxx%'
and is_ms_shipped = 0; 

Python Progress Bar

This progress bar shows points of each 2 percent complete and numbers for each 10 percent complete.

import sys

def ProgressBar (num, total, nextPercent, nextPoint):
    num = float (num)
    total = float (total) - 1
    if not nextPoint:
        nextPoint = 0.0
    if not nextPercent:
        nextPoint += 2.0
        sys.stdout.write ("[0%")
        nextPercent = 10
    elif num == total:
        sys.stdout.write ("100%]\n")
        nextPercent += 10
    elif not nextPoint:
        nextPoint = 0.0
    elif num / total * 100 >= nextPercent:
        sys.stdout.write (str(int (nextPercent)) + "%")
        nextPercent += 10
    elif num / total * 100 >= nextPoint:
        sys.stdout.write (":")
        nextPoint += 2
    return (nextPercent, nextPoint)

nextPercent, nextPoint = 0, 0
total = 1000

for num in range (total):
    nextPercent, nextPoint = ProgressBar (num, total, nextPercent, nextPoint)



How do I read the source code of shell commands?

    cd ~ && apt-get source coreutils && ls -d coreutils*     

You should be able to use a command like this on ubuntu to gather the source for a package, you can omit sudo assuming your downloading to a location you own.

WSDL/SOAP Test With soapui

I faced the same exception while trying to test my web-services deployed to WSO2 ESB.

WSO2 generated both wsdl and wsdl2. I tried to pass a wsdl2 URL and got the above exception. Quick googling showed me, that one of differences between wsdl1.1 and wsdl2.0 is replacing 'definitions' element with 'description'. Also, I found out, that SoapUI does not support wsdl2.

Therefore, for me the solution was to use wsdl1 url instead of wsdl2.

How to upload a file in Django?

Extending on Henry's example:

import tempfile
import shutil

FILE_UPLOAD_DIR = '/home/imran/uploads'

def handle_uploaded_file(source):
    fd, filepath = tempfile.mkstemp(, dir=FILE_UPLOAD_DIR)
    with open(filepath, 'wb') as dest:
        shutil.copyfileobj(source, dest)
    return filepath

You can call this handle_uploaded_file function from your view with the uploaded file object. This will save the file with a unique name (prefixed with filename of the original uploaded file) in filesystem and return the full path of saved file. You can save the path in database, and do something with the file later.

Label axes on Seaborn Barplot

One can avoid the AttributeError brought about by set_axis_labels() method by using the matplotlib.pyplot.xlabel and matplotlib.pyplot.ylabel.

matplotlib.pyplot.xlabel sets the x-axis label while the matplotlib.pyplot.ylabel sets the y-axis label of the current axis.

Solution code:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
fig = sns.barplot(x = 'val', y = 'cat', data = fake, color = 'black')
plt.title("Colors vs Values") # You can comment this line out if you don't need title

Output figure:

enter image description here

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"

How to set css style to button?

You could just style the input element in your css file. That is then independent of ASP.NET.

<form action="">
    Name: <input type="text" class="input" />
    Password: <input type="password" class="input" />
    <input type="submit" value="Submit" class="button" />
.input {
    border: 1px solid #006;
    background: #ffc;
.button {
    border: 1px solid #006;
    background: #9cf;

With the CssClass you can assign the "input" class to it.

When use ResponseEntity<T> and @RestController for Spring RESTful applications

ResponseEntity is meant to represent the entire HTTP response. You can control anything that goes into it: status code, headers, and body.

@ResponseBody is a marker for the HTTP response body and @ResponseStatus declares the status code of the HTTP response.

@ResponseStatus isn't very flexible. It marks the entire method so you have to be sure that your handler method will always behave the same way. And you still can't set the headers. You'd need the HttpServletResponse or a HttpHeaders parameter.

Basically, ResponseEntity lets you do more.

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).


Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b =
 val c =
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 


This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre =
   while (iter.hasNext)
     val cur =;
     res .::= (pre, cur)
     pre = cur;
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur =;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:

  • F1 (Help),
  • F3 (Search),
  • F5 (Refresh),
  • F6 (focus address bar),
  • F7 (caret browsing mode),
  • F11 (full screen mode), and
  • F12 (used by several add-ons, including Firebug)

The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.

Error 0x80005000 and DirectoryServices

On IIS hosted sites, try recycling the app pool. It fixed my issue. Thanks

Git refusing to merge unrelated histories on rebase

I tried git pull --allow-unrelated-histories didn't work, but what solves this issue for me was:

  1. I copied all the files on my desktop repository to another folder and then deleted the folder.

  2. Then I clone the repo again because it is a new project.

  3. When I copied my files again and push it worked like charm.

Is there any way to wait for AJAX response and halt execution?

New, using jquery's promise implementation:

function functABC(){

  // returns a promise that can be used later. 

  return $.ajax({
    url: 'myPage.php',
    data: {id: id}

functABC().then( response => 

Nice read e.g. here.

This is not "synchronous" really, but I think it achieves what the OP intends.

Old, (jquery's async option has since been deprecated):

All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

async: false 

like described here

Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

Finding the median of an unsorted array

I have already upvoted the @dasblinkenlight answer since the Median of Medians algorithm in fact solves this problem in O(n) time. I only want to add that this problem could be solved in O(n) time by using heaps also. Building a heap could be done in O(n) time by using the bottom-up. Take a look to the following article for a detailed explanation Heap sort

Supposing that your array has N elements, you have to build two heaps: A MaxHeap that contains the first N/2 elements (or (N/2)+1 if N is odd) and a MinHeap that contains the remaining elements. If N is odd then your median is the maximum element of MaxHeap (O(1) by getting the max). If N is even, then your median is (MaxHeap.max()+MinHeap.min())/2 this takes O(1) also. Thus, the real cost of the whole operation is the heaps building operation which is O(n).

BTW this MaxHeap/MinHeap algorithm works also when you don't know the number of the array elements beforehand (if you have to resolve the same problem for a stream of integers for e.g). You can see more details about how to resolve this problem in the following article Median Of integer streams

Get push notification while App in foreground iOS

If your application is in foreground state, it means you are currently using the same app. So there is no need to show notification on the top generally.

But still if you want to show notification in that case you have to create your custom Alert View or Custom View like Toast or something else to show to the user that you have got a notification.

You can also show a badge on the top if you have such kind of feature in your app.

Parse JSON String into a Particular Object Prototype in JavaScript

Do you want to add JSON serialization/deserialization functionality, right? Then look at this:

You want to achieve this:


toJson() is a normal method.
fromJson() is a static method.


var Book = function (title, author, isbn, price, stock){
    this.title = title; = author;
    this.isbn = isbn;
    this.price = price;
    this.stock = stock;

    this.toJson = function (){
        return ("{" +
            "\"title\":\"" + this.title + "\"," +
            "\"author\":\"" + + "\"," +
            "\"isbn\":\"" + this.isbn + "\"," +
            "\"price\":" + this.price + "," +
            "\"stock\":" + this.stock +

Book.fromJson = function (json){
    var obj = JSON.parse (json);
    return new Book (obj.title,, obj.isbn, obj.price, obj.stock);


var book = new Book ("t", "a", "i", 10, 10);
var json = book.toJson ();
alert (json); //prints: {"title":"t","author":"a","isbn":"i","price":10,"stock":10}

var book = Book.fromJson (json);
alert (book.title); //prints: t

Note: If you want you can change all property definitions like this.title,, etc by var title, var author, etc. and add getters to them to accomplish the UML definition.

exporting multiple modules in react.js

When you

import App from './App.jsx';

That means it will import whatever you export default. You can rename App class inside App.jsx to whatever you want as long as you export default it will work but you can only have one export default.

So you only need to export default App and you don't need to export the rest.

If you still want to export the rest of the components, you will need named export.

What are abstract classes and abstract methods?

An abstract method is a method signature declaration with no body. For instance:

public abstract class Shape {
    . . .

    public abstract double getArea();
    public abstract double getPerimeter();

The methods getArea() and getPerimeter() are abstract. Because the Shape class has an abstract method, it must be declared abstract as well. A class may also be declared abstract without any abstract methods. When a class is abstract, an instance of it cannot be created; one can only create instances of (concrete) subclasses. A concrete class is a class that is not declared abstract (and therefore has no abstract methods and implements all inherited abstract methods). For instance:

public class Circle extends Shape {
    public double radius;
    . . .

    public double getArea() {
        return Math.PI * radius * radius;

    public double getPerimeter() {
        return 2.0 * Math.PI * radius;

There are many reasons to do this. One would be to write a method that would be the same for all shapes but that depends on shape-specific behavior that is unknown at the Shape level. For instance, one could write the method:

public abstract class Shape {
    . . .

    public void printArea(PrintStream out) {
        out.println("The area is " + getArea());

Admittedly, this is a contrived example, but it shows the basic idea: define concrete behavior in terms of unspecified behavior.

Another reason for having an abstract class is so you can partially implement an interface. All methods declared in an interface are inherited as abstract methods by any class that implements the interface. Sometimes you want to provide a partial implementation of an interface in a class and leave the details to subclasses; the partial implementation must be declared abstract.

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

I do the "in clause" query with spring jdbc like this:

String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";

List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template = 
    new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

List<Long> list = template.queryForList(sql, paramMap, Long.class);

The system cannot find the file specified in java

When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.

I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].

How do HashTables deal with collisions?

here's a very simple hash table implementation in java. in only implements put() and get(), but you can easily add whatever you like. it relies on java's hashCode() method that is implemented by all objects. you could easily create your own interface,

interface Hashable {
  int getHash();

and force it to be implemented by the keys if you like.

public class Hashtable<K, V> {
    private static class Entry<K,V> {
        private final K key;
        private final V val;

        Entry(K key, V val) {
            this.key = key;
            this.val = val;

    private static int BUCKET_COUNT = 13;

    private List<Entry>[] buckets = new List[BUCKET_COUNT];

    public Hashtable() {
        for (int i = 0, l = buckets.length; i < l; i++) {
            buckets[i] = new ArrayList<Entry<K,V>>();

    public V get(K key) {
        int b = key.hashCode() % BUCKET_COUNT;
        List<Entry> entries = buckets[b];
        for (Entry e: entries) {
            if (e.key.equals(key)) {
                return e.val;
        return null;

    public void put(K key, V val) {
        int b = key.hashCode() % BUCKET_COUNT;
        List<Entry> entries = buckets[b];
        entries.add(new Entry<K,V>(key, val));

How do I set adaptive multiline UILabel text?

Programmatically in Swift 5 with Xcode 10.2

Building on top of @La masse's solution, but using autolayout to support rotation

Set anchors for the view's position (left, top, centerY, centerX, etc). You can also set the width anchor or set the frame.width dynamically with the UIScreen extension provided (to support rotation)

label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.translatesAutoresizingMaskIntoConstraints = false
label.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 20).isActive = true
label.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: -20).isActive = true
label.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 20).isActive = true
// label.frame.size = CGSize(width: UIScreen.absoluteWidth() - 40.0, height: 0)

If setting frame.width dynamically using UIScreen:

    class func absoluteWidth() -> CGFloat {
        var width: CGFloat
        if UIScreen.main.bounds.width > UIScreen.main.bounds.height {
            width = self.main.bounds.height // Landscape
        } else {
            width = self.main.bounds.width // Portrait
        return width

How to combine paths in Java?

The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.

Delete a row from a table by id

Something quick and dirty:

<script type='text/javascript'>
function del_tr(remtr)  
        remtr = remtr.parentNode;

function del_id(id)  

if you place

<a href='' onclick='del_tr(this);return false;'>x</a>

anywhere within the row you want to delete, than its even working without any ids

How do I revert my changes to a git submodule?

This works with our libraries running GIT v1.7.1, where we have a DEV package repo and LIVE package repo. The repositories themselves are nothing but a shell to package the assets for a project. all submodules.

The LIVE is never updated intentionally, however cache files or accidents can occur, leaving the repo dirty. New submodules added to the DEV must be initialized within LIVE as well.

Package Repository in DEV

Here we want to pull all upstream changes that we are not yet aware of, then we will update our package repository.

# Recursively reset to the last HEAD
git submodule foreach --recursive git reset --hard

# Recursively cleanup all files and directories
git submodule foreach --recursive git clean -fd

# Recursively pull the upstream master
git submodule foreach --recursive git pull origin master

# Add / Commit / Push all updates to the package repo
git add .
git commit -m "Updates submodules"
git push   

Package Repository in LIVE

Here we want to pull the changes that are committed to the DEV repository, but not unknown upstream changes.

# Pull changes
git pull

# Pull status (this is required for the submodule update to work)
git status

# Initialize / Update 
git submodule update --init --recursive

How to solve PHP error 'Notice: Array to string conversion in...'

You are using <input name='C[]' in your HTML. This creates an array in PHP when the form is sent.

You are using echo $_POST['C']; to echo that array - this will not work, but instead emit that notice and the word "Array".

Depending on what you did with the rest of the code, you should probably use echo $_POST['C'][0];

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

You don't need to learn JPA. You can use my easy-criteria for JPA2 ( Here is the example

CriteriaComposer<Pet> petCriteria CriteriaComposer.from(Pet.class).
where(Pet_.type, EQUAL, "Cat").join(Pet_.owner).where(,EQUAL, "foo");

List<Pet> result = CriteriaProcessor.findAllEntiry(petCriteria);


List<Tuple> result =  CriteriaProcessor.findAllTuple(petCriteria);

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

I was facing with the same issue and tried everything restarting, packages get, repair everything, But none of these solution worked. The only thing which worked was to set the encoding of the packages file giving error to UTF-8.

PS: I faced this on Android studio

Hope this would help someone.

Bootstrap: how do I change the width of the container?

You are tying one had behind your back saying that you won't use the LESS files. I built my first Twitter Bootstrap theme using 2.0, and I did everything in CSS -- creating an override.css file. It took days to get things to work correctly.

Now we have 3.0. Let me assure you that it takes less time to learn LESS, which is pretty straight forward if you're comfortable with CSS, than doing all of those crazy CSS overrides. Making changes like the one you want is a piece of cake.

In Bootstrap 3.0, the container class controls the width, and all of the contained styles adjust to fill the container. The container width variables are at the bottom of the variables.less file.

// Container sizes
// --------------------------------------------------

// Small screen / tablet
@container-tablet:            ((720px + @grid-gutter-width));

// Medium screen / desktop
@container-desktop:           ((940px + @grid-gutter-width));

// Large screen / wide desktop
@container-lg-desktop:        ((1020px + @grid-gutter-width));

Some sites either don't have enough content to fill the 1020 display or you want a narrower frame for aesthetic reasons. Because BS uses a 12-column grid I use a multiple like 960.

How to change the MySQL root account password on CentOS7?

I used the advice of Kevin Jones above with the following --skip-networking change for slightly better security:

sudo systemctl set-environment MYSQLD_OPTS="--skip-grant-tables --skip-networking"

[user@machine ~]$ mysql -u root

Then when attempting to reset the password I received an error, but googling elsewhere suggested I could simply forge ahead. The following worked:

mysql> select user(), current_user();
| user() | current_user()                    |
| root@  | skip-grants user@skip-grants host |
1 row in set (0.00 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'sup3rPw#'
ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement
Query OK, 0 rows affected (0.02 sec)

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'sup3rPw#'
Query OK, 0 rows affected (0.08 sec)

mysql> exit
[user@machine ~]$ systemctl stop mysqld
[user@machine ~]$ sudo systemctl unset-environment MYSQLD_OPTS
[user@machine ~]$ systemctl start mysqld

At that point I was able to log in.

Display date/time in user's locale format and time offset

Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.

Then the various toLocale…String methods will provide localized output.


// This would come from the server._x000D_
// Also, this whole block could probably be made into an mktime function._x000D_
// All very bare here for quick grasping._x000D_
d = new Date();_x000D_
console.log(d);                        // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)_x000D_
console.log(d.toLocaleString());       // -> Sat Feb 28 23:45:26 2004_x000D_
console.log(d.toLocaleDateString());   // -> 02/28/2004_x000D_
console.log(d.toLocaleTimeString());   // -> 23:45:26

Some references:

Code formatting shortcuts in Android Studio for Operation Systems

You can use the following shortcut for code formatting: Ctrl+Alt+L

Sum up a column from a specific row down

If you don't mind using OFFSET(), which is a volatile function that recalculates everytime a cell is changed, then this is a good solution that is both dynamic and reusable:

=OFFSET($COL:$COL, ROW(), 1, 1048576 - ROW(), 1)

where $COL is the letter of the column you are going to operate upon, and ROW() is the row function that dynamically selects the same row as the cell containing this formula. You could also replace the ROW() function with a static number ($ROW).

=OFFSET($COL:$COL, $ROW, 1, 1048576 - $ROW, 1)

You could further clean up the formula by defining a named constant for the 1048576 as 'maxRows'. This can be done in the 'Define Name' menu of the Formulas tab.

=OFFSET($COL:$COL, $ROW, 1, maxRows - $ROW, 1)

A quick example: to Sum from C6 to the end of column C, you could do:

=SUM(OFFSET(C:C, 6, 1, maxRows - 6, 1))

or =SUM(OFFSET(C:C, ROW(), 1, maxRows - ROW(),1))

How to convert FileInputStream to InputStream?

If you wrap one stream into another, you don't close intermediate streams, and very important: You don't close them before finishing using the outer streams. Because you would close the outer stream too.

Shortcut for creating single item list in C#

You can also do

new List<string>() { "string here" };

How to clear an EditText on click?

For me the easiest way... Create an public EditText, for Example "myEditText1"

public EditText myEditText1;

Then, connect it with the EditText which should get cleared

myEditText1 = (EditText) findViewById(;

After that, create an void which reacts to an click to the EditText an let it clear the Text inside it when its Focused, for Example

        void textGone(){
            if (myEditText1.isFocused()){


Hope i could help you, Have a nice Day everyone

Check if element is visible in DOM

Here's the code I wrote to find the only visible among a few similar elements, and return the value of its "class" attribute without jQuery:

  // Build a NodeList:
  var nl = document.querySelectorAll('.myCssSelector');

  // convert it to array:
  var myArray = [];for(var i = nl.length; i--; myArray.unshift(nl[i]));

  // now find the visible (= with offsetWidth more than 0) item:
  for (i =0; i < myArray.length; i++){
    var curEl = myArray[i];
    if (curEl.offsetWidth !== 0){
      return curEl.getAttribute("class");

Bash: If/Else statement in one line

You can make full use of the && and || operators like this:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0

For excluding grep itself, you could also do something like:

ps aux | grep some_proces | grep -vw grep > /tmp/test.txt && echo 1 || echo 0

HTML entity for the middle dot

That's a bullet: •


m2e lifecycle-mapping not found

Suprisingly these 3 steps helped me:

mvn clean
mvn package
mvn spring-boot:run

Xcode: failed to get the task for process

I had this issue when trying to debug an App on a device I hadn't used before. Developer profile was correctly set. The device was part of our teams account but wasn't included in my profile.

Simply had to open Organizer -> Select the Device -> Add to Member Center

Setting the zoom level for a MKMapView

Here, I put my answer and its working for swift 4.2.

MKMapView center and zoom in

concatenate two strings

You need to use the string concatenation operator +

String both = name + "-" + dest;

What are the safe characters for making URLs?

From the context you describe, I suspect that what you're actually trying to make is something called an 'SEO slug'. The best general known practice for those is:

  1. Convert to lower-case
  2. Convert entire sequences of characters other than a-z and 0-9 to one hyphen (-) (not underscores)
  3. Remove 'stop words' from the URL, i.e. not-meaningfully-indexable words like 'a', 'an', and 'the'; Google 'stop words' for extensive lists

So, as an example, an article titled "The Usage of !@%$* to Represent Swearing In Comics" would get a slug of "usage-represent-swearing-comics".

HTML Script tag: type or language (or omit both)?

The language attribute has been deprecated for a long time, and should not be used.

When W3C was working on HTML5, they discovered all browsers have "text/javascript" as the default script type, so they standardized it to be the default value. Hence, you don't need type either.

For pages in XHTML 1.0 or HTML 4.01 omitting type is considered invalid. Try validating the following:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" xml:lang="en" lang="en">
<script src=""></script>

You will be informed of the following error:

Line 4, Column 41: required attribute "type" not specified

So if you're a fan of standards, use it. It should have no practical effect, but, when in doubt, may as well go by the spec.

Return JSON for ResponseEntity<String>

This is a String, not a json structure(key, value), try:

return new ResponseEntity("{"vale" : "This is a String"}", HttpStatus.OK);

Interface naming in Java

Is this a broader naming convention in any real sense? I'm more on the C++ side, and not really up on Java and descendants. How many language communities use the I convention?

If you have a language-independent shop standard naming convention here, use it. If not, go with the language naming convention.

Using setImageDrawable dynamically to set image in an ImageView


API 23 Android 6.0

c++ array - expression must have a constant value

C++ doesn't allow non-constant values for the size of an array. That's just the way it was designed.

C99 allows the size of an array to be a variable, but I'm not sure it is allowed for two dimensions. Some C++ compilers (gcc) will allow this as an extension, but you may need to turn on a compiler option to allow it.

And I almost missed it - you need to declare a variable name, not just the array dimensions.

jQuery AJAX form using mail() PHP script sends email, but POST data from HTML form is undefined

You code should be:

   <section id="right">
      <label for="form_msg">Message</label>
      <textarea name="form_msg" id="#msg_text"></textarea>
      <input id="submit" class="button" name="submit" type="submit" value="Send">


var data = {
    name: $("#form_name").val(),
    email: $("#form_email").val(),
    message: $("#msg_text").val()
    type: "POST",
    url: "email.php",
    data: data,
    success: function(){

The PHP:

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['text'];

//send email
    mail("[email protected]","My Subject:",$email,$message);

What's the fastest way of checking if a point is inside a polygon in python

You can consider shapely:

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

point = Point(0.5, 0.5)
polygon = Polygon([(0, 0), (0, 1), (1, 1), (1, 0)])

From the methods you've mentioned I've only used the second, path.contains_points, and it works fine. In any case depending on the precision you need for your test I would suggest creating a numpy bool grid with all nodes inside the polygon to be True (False if not). If you are going to make a test for a lot of points this might be faster (although notice this relies you are making a test within a "pixel" tolerance):

from matplotlib import path
import matplotlib.pyplot as plt
import numpy as np

first = -3
size  = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)])  # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags

xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]

, the results is this:

point inside polygon within pixel tolerance

jQuery post() with serialize and extra data

An alternative solution, in case you are needing to do this on an ajax file upload:

var data = new FormData( $('#form')[0] ).append( 'name' , value );

OR even simpler.


    var data = new FormData( this ).append('name', value );

    // ... your ajax code here ...

    return false;


How to workaround 'FB is not defined'?

I had FB never being defined. Turned out that I was prototyping functions into the Object class called "merge" and another called "toArray". Both of these screwed up Facebook, no error messages but it wouldn't load.

I changed the names of my prototypes, it works now. Hey, if Facebook is going to prototype Object, shouldn't I be allowed to prototype it?

List supported SSL/TLS versions for a specific OpenSSL build

It's clumsy, but you can get this from the usage messages for s_client or s_server, which are #ifed at compile time to match the supported protocol versions. Use something like

 openssl s_client -help 2>&1 | awk '/-ssl[0-9]|-tls[0-9]/{print $1}' 
 # in older releases any unknown -option will work; in 1.1.0 must be exactly -help

How to pass parameter to function using in addEventListener?

If the this value you want is the just the object that you bound the event handler to, then addEventListener() already does that for you. When you do this:

productLineSelect.addEventListener('change', getSelection, false);

the getSelection function will already be called with this set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

function getSelection(event) {
    // this will be set to the object that the event handler was bound to
    // event is all the detailed information about the event

If the desired this value is some other value than the object you bound the event handler to, you can just do this:

var self = this;
productLineSelect.addEventListener('change',function() {

By way of explanation:

  1. You save away the value of this into a local variable in your other event handler.
  2. You then create an anonymous function to pass addEventListener.
  3. In that anonymous function, you call your actual function and pass it the saved value of this.

What is the difference between React Native and React?

Simple React Js is for web React Native is for cross-platform mobile apps!

How to save image in database using C#

Since you are using SQL, would recommend against using adhoc ('writing statements in strings'), especially given that you are loading an image.

ADO.NET can do all of the hard work of mapping, escaping etc for you.

Either create a Stored Procedure, or use SqlParameter to do the binding.

As the other posters say, use VARBINARY(MAX) as your storage type - IMAGE is being depracated.

How to clear exisiting dropdownlist items when its content changes?

You should clear out your listbbox prior to binding:

  ' now set datasource and bind

CSS background image alt attribute

As mentioned in other answers, there is no (supported) alt attribute for a div tag only for the img tag.

The real question is why you need to add the alt attribute to all background images for the site? Based on this answer, it will help you determine which route to take in your approach.

Visual/Textual: If you are simply attempting to add a textual fall back for the user if the image fails to load, simply use the title attribute. Most browsers will provide a visual tool tip(message box) when a user hovers over the image, and if the image is not loaded for whatever reason, it behaves the same as an alt attribute presenting text when image fails. This technique still allows for the site to speed up load times by keeping images set to backgrounds.

Screen Readers: The middle of the road option, this varies because technically keeping your images as backgrounds and using the title attribute approach should work as hinted above, "Audio user agents may speak the title information in a similar context." However this is not guaranteed to work in all cases, including some readers may ignore it all together. If you end up opting for this approach, you can also try adding in aria-labels to help ensure screen readers pick these up.

SEO/Search Engines: Here is the big one, if you were like me, you added your background images, all was good. Then months later the customer(or maybe yourself) realized that you are missing out on some prime SEO gold by not having alt's for your images. Keep in mind, the title attribute does not have any weight on search engines, from my research and as mentioned in an article here: So if you are aiming for SEO, then you will need to have an img tag with the alt attribute. One possible approach is to just load very small actual images on the site with alt attributes, this way you get all the SEO and don't have to readjust the existing CSS in place. However this may lead to additional load time depending on the size and google does indeed look at the images path when indexing. In short if you are going this route, just accept what has to be done and include the actual images instead of using backgrounds.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

-xms is the start memory (at the VM start), -xmx is the maximum memory for the VM

  • eclipse.ini : the memory for the VM running eclipse
  • jre setting : the memory for java programs run from eclipse
  • : the memory for your tomcat server

Comparing date part only without comparing time in JavaScript

After reading this question quite same time after it is posted I have decided to post another solution, as I didn't find it that quite satisfactory, at least to my needs:

I have used something like this:

var currentDate= new Date().setHours(0,0,0,0);

var startDay = new Date(currentDate - 86400000 * 2);
var finalDay = new Date(currentDate + 86400000 * 2);

In that way I could have used the dates in the format I wanted for processing afterwards. But this was only for my need, but I have decided to post it anyway, maybe it will help someone

jQuery 1.9 .live() is not a function

.live was removed in 1.9, please see the upgrade guide:

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

Some good answers, but the problem with all solutions I have tried is that the images doesn´t fade into each other. Instead the first one fades completely out and than the next one fades in.

After a few hours of testing a found this sollution. Thx to

  1. In the HTML code change from .slide to .fade on the .carousel element
  2. Add this in the css:

    .carousel.fade { opacity: 1; } .carousel.fade .item { transition: opacity ease-out .7s; left: 0; opacity: 0; /* hide all slides */ top: 0; position: absolute; width: 100%; display: block; } .carousel.fade .item:first-child { top: auto; opacity: 1; /* show first slide */ position: relative; } .carousel.fade { opacity: 1; }

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

I have faced the same issue using Google Chrome browser. Same website was opening normally using the incognito mode and different browsers. At first, I cleared cached files and cookies over the past 24 hours, but this didn't help.

I realized that my first visit to the website was during the past 10 days. So, I cleared cached files and cookies over the past 4 weeks and that resolved the problem.
Note: I didn't clear my browsing history data

SQL - How to find the highest number in a column?

Depends on what SQL implementation you are using. Both MySQL and SQLite, for example, have ways to get last insert id. In fact, if you're using PHP, there's even a nifty function for exactly that mysql_insert_id().

You should probably look to use this MySQL feature instead of looking at all the rows just to get the biggest insert ID. If your table gets big, that could become very inefficient.

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

Hibernate error - QuerySyntaxException: users is not mapped [from users]

with org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users], you are trying to select from the users table. But you are annotating your class with @Table( name = "Users" ). So either use users, or Users.

CSS "and" and "or"

Just in case if any one is stuck like me. After going though the post and some hit and trial this worked for me.


How do I run a program with a different working directory from current, from Linux shell?

I always think UNIX tools should be written as filters, read input from stdin and write output to stdout. If possible you could change your helloworld binary to write the contents of the text file to stdout rather than a specific file. That way you can use the shell to write your file anywhere.

$ cd ~/b

$ ~/a/helloworld > ~/c/helloworld.txt

Matrix Multiplication in pure Python?

The shape of your matrix C is wrong; it's the transpose of what you actually want it to be. (But I agree with ulmangt: the Right Thing is almost certainly to use numpy, really.)

How to remove multiple indexes from a list at the same time?

another option (in place, any combination of indices):

_marker = object()

for i in indices:
    my_list[i] = _marker  # marked for deletion

obj[:] = [v for v in my_list if v is not _marker]

What are the differences between Visual Studio Code and Visual Studio?

Out of the box, Visual Studio can compile, run and debug programs.

Out of the box, Visual Studio Code can do practically nothing but open and edit text files. It can be extended to compile, run, and debug, but you will need to install other software. It's a PITA.

If you're looking for a Notepad replacement, Visual Studio Code is your man.

If you want to develop and debug code without fiddling for days with settings and installing stuff, then Visual Studio is your man.

In Javascript/jQuery what does (e) mean?

e doesn't have any special meaning. It's just a convention to use e as function parameter name when the parameter is event.

It can be

$(this).click(function(loremipsumdolorsitamet) {
    // does something

as well.

What __init__ and self do in Python?

Class objects support two kinds of operations: attribute references and instantiation

Attribute references use the standard syntax used for all attribute references in Python: Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment. __doc__ is also a valid attribute, returning the docstring belonging to the class: "A simple example class".

Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class. For example:

x = MyClass()

The instantiation operation (“calling” a class object) creates an empty object. Many classes like to create objects with instances customized to a specific initial state. Therefore a class may define a special method named __init__(), like this:

def __init__(self): = []

When a class defines an __init__() method, class instantiation automatically invokes __init__() for the newly-created class instance. So in this example, a new, initialized instance can be obtained by:

x = MyClass()

Of course, the __init__() method may have arguments for greater flexibility. In that case, arguments given to the class instantiation operator are passed on to __init__(). For example,

class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart

x = Complex(3.0, -4.5)
x.r, x.i

Taken from official documentation which helped me the most in the end.

Here is my example

class Bill():
    def __init__(self,apples,figs,dates):
        self.apples = apples
        self.figs = figs
        self.dates = dates
        self.bill = apples + figs + dates
        print ("Buy",self.apples,"apples", self.figs,"figs 
                Total fruitty bill is",self.bill," pieces of fruit :)")

When you create instance of class Bill:

purchase = Bill(5,6,7)

You get:

> Buy 5 apples 6 figs and 7 dates. Total fruitty bill is 18  pieces of
> fruit :)

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    cache: false,
                    success:function (msg) {}

$(form).ajaxSubmit is not a function

Try ajaxsubmit library. It does ajax submition as well as validation via ajax.

Also configuration is very flexible to support any kind of UI.

Live demo available with js, css and html examples.

Given an RGB value, how do I create a tint (or shade)?

Some definitions

  • A shade is produced by "darkening" a hue or "adding black"
  • A tint is produced by "ligthening" a hue or "adding white"

Creating a tint or a shade

Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:

  • RGB:

    • To shade:

      newR = currentR * (1 - shade_factor)
      newG = currentG * (1 - shade_factor)
      newB = currentB * (1 - shade_factor)
    • To tint:

      newR = currentR + (255 - currentR) * tint_factor
      newG = currentG + (255 - currentG) * tint_factor
      newB = currentB + (255 - currentB) * tint_factor
    • More generally, the color resulting in layering a color RGB(currentR,currentG,currentB) with a color RGBA(aR,aG,aB,alpha) is:

      newR = currentR + (aR - currentR) * alpha
      newG = currentG + (aG - currentG) * alpha
      newB = currentB + (aB - currentB) * alpha

    where (aR,aG,aB) = black = (0,0,0) for shading, and (aR,aG,aB) = white = (255,255,255) for tinting

  • HSV or HSB:

    • To shade: lower the Value / Brightness or increase the Saturation
    • To tint: lower the Saturation or increase the Value / Brightness
  • HSL:
    • To shade: lower the Lightness
    • To tint: increase the Lightness

There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB and want to use the HSV model to shade for example, you can just convert to HSV, do the shading and convert back to RGB. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :

Comparing the models

  • RGB has the advantage of being really simple to implement, but:
    • you can only shade or tint your color relatively
    • you have no idea if your color is already tinted or shaded
  • HSV or HSB is kind of complex because you need to play with two parameters to get what you want (Saturation & Value / Brightness)
  • HSL is the best from my point of view:
    • supported by CSS3 (for webapp)
    • simple and accurate:
      • 50% means an unaltered Hue
      • >50% means the Hue is lighter (tint)
      • <50% means the Hue is darker (shade)
    • given a color you can determine if it is already tinted or shaded
    • you can tint or shade a color relatively or absolutely (by just replacing the Lightness part)

How to detect if JavaScript is disabled?

For those who just want to track if js was enabled, how about using an ajax routine to store the state? For example, I log all visitors/visits in a set of tables. The JSenabled field can be set to a default of FALSE, and the ajax routine would set it to TRUE, if JS is enabled.

Hexadecimal To Decimal in Shell Script

In dash and other shells, you can use

printf "%d\n" (your hexadecimal number)

to convert a hexadecimal number to decimal. This is not bash, or ksh, specific.

PostgreSQL: ERROR: operator does not exist: integer = character varying

I think it is telling you exactly what is wrong. You cannot compare an integer with a varchar. PostgreSQL is strict and does not do any magic typecasting for you. I'm guessing SQLServer does typecasting automagically (which is a bad thing).

If you want to compare these two different beasts, you will have to cast one to the other using the casting syntax ::.

Something along these lines:

create view view1
select table1.col1,table2.col1,table3.col3
from table1 
inner join
inner join 
table1.col4::varchar = table2.col5
/* Here col4 of table1 is of "integer" type and col5 of table2 is of type "varchar" */
/* ERROR: operator does not exist: integer = character varying */

Notice the varchar typecasting on the table1.col4.

Also note that typecasting might possibly render your index on that column unusable and has a performance penalty, which is pretty bad. An even better solution would be to see if you can permanently change one of the two column types to match the other one. Literately change your database design.

Or you could create a index on the casted values by using a custom, immutable function which casts the values on the column. But this too may prove suboptimal (but better than live casting).

form serialize javascript (no framework)

Here is pure JavaScript approach:

var form = document.querySelector('form');
var data = new FormData(form);

  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
  };"POST", "<YOUR-URL>", true);

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

You can also create a public method on the page then call that from the code-in-front.

e.g. if using C#:

public string ProcessMyDataItem(object myValue)
  if (myValue == null)
     return "0 value";

  return myValue.ToString();

Then the label in the code-in-front will be something like:

<asp:Label ID="Label18" Text='<%# ProcessMyDataItem(Eval("item")) %>' runat="server"></asp:Label>

Sorry, haven't tested this code so can't guarantee I got the syntax of "<%# ProcessMyDataItem(Eval("item")) %>" entirely correct.

Is it possible to get a history of queries made in postgres

If The question is the see the history of queries executed in the Command line. Answer is

As per Postgresql 9.3, Try \? in your command line, you will find all possible commands, in that search for history,

  \s [FILE]              display history or save it to file

in your command line, try \s. This will list the history of queries, you have executed in the current session. you can also save to the file, as shown below.

hms=# \s /tmp/save_queries.sql
Wrote history to file ".//tmp/save_queries.sql".

How do I get monitor resolution in Python?

I created a PyPI module for this reason:

pip install screeninfo

The code:

from screeninfo import get_monitors
for m in get_monitors():



It supports multi monitor environments. Its goal is to be cross platform; for now it supports Cygwin and X11 but pull requests are totally welcome.

No more data to read from socket error

I seemed to fix my instance by removing the parameter placeholder for a parameterized query.

For some reason, using these placeholders were working fine, and then they stopped working and I got the error/bug.

As a workaround, I substituted literals for my placeholders and it started working.

Remove this

    SOME_VAR = :1

Use this

    SOME_VAR = 'Value'

HTML text-overflow ellipsis detection

This sample show tooltip on cell table with text truncated. Is dynamic based on table width:

$.expr[':'].truncated = function (obj) {
    var element = $(obj);

    return (element[0].scrollHeight > (element.innerHeight() + 1)) || (element[0].scrollWidth > (element.innerWidth() + 1));

$(document).ready(function () {
    $("td").mouseenter(function () {
        var cella = $(this);
        var isTruncated = cella.filter(":truncated").length > 0;
        if (isTruncated) 
            cella.attr("title", cella.text());
            cella.attr("title", null);


It works on all version of jQuery

Java code To convert byte to Hexadecimal

The Best solution is this badass one-liner:

String hex=DatatypeConverter.printHexBinary(byte[] b);

as mentioned here

Vagrant error : Failed to mount folders in Linux guest

Your log complains about not finding exportfs: sudo: /usr/bin/exportfs: command not found

The exportfs makes local directories available for NFS clients to mount.

A fast way to delete all rows of a datatable at once

Why dont you just do it in SQL?


Split value from one field to two

In case someone needs to run over a table and split a field:

  1. First we use the function mention above:
CREATE DEFINER=`root`@`localhost` FUNCTION `fn_split_str`($str VARCHAR(800), $delimiter VARCHAR(12), $position INT) RETURNS varchar(800) CHARSET utf8
                SUBSTRING_INDEX($str, $delimiter, $position),
                    SUBSTRING_INDEX($str, $delimiter, $position -1)
                ) + 1
    $delimiter, '');
  1. Second, we run in a while loop on the string until there isn't any results (I've added $id for JOIN clause):
CREATE DEFINER=`root`@`localhost` FUNCTION `fn_split_str_to_rows`($id INT, $str VARCHAR(800), $delimiter VARCHAR(12), $empty_table BIT) RETURNS int(11)

    DECLARE position INT;
    DECLARE val VARCHAR(800);
    SET position = 1;
    IF $empty_table THEN
        DROP TEMPORARY TABLE IF EXISTS tmp_rows;    
    END IF;
    SET val = fn_split_str($str, ',', position);
    CREATE TEMPORARY TABLE IF NOT EXISTS tmp_rows AS (SELECT $id as id, val as val where 1 = 2);
    WHILE (val IS NOT NULL and val != '') DO               
        INSERT INTO tmp_rows
        SELECT $id, val;
        SET position = position + 1;
        SET val = fn_split_str($str, ',', position);
    RETURN position - 1;
  1. Finally we can use it like that:
SELECT  SUM(fn_split_str_to_rows(ID, FieldToSplit, ',', 0))
FROM    MyTable;

SELECT * FROM tmp_rows;

You can use the id to join to other table.

In case you are only splitting one value you can use it like that

SELECT  fn_split_str_to_rows(null, 'AAA,BBB,CCC,DDD,EEE,FFF,GGG', ',', 1);
SELECT * FROM tmp_rows;

We don't need to empty the temporary table, the function will take care of that.

How can I create directory tree in C++/Linux?

You said "C++" but everyone here seems to be thinking "Bash shell."

Check out the source code to gnu mkdir; then you can see how to implement the shell commands in C++.

Print commit message of a given commit in git

git show is more a plumbing command than git log, and has the same formatting options:

git show -s --format=%B SHA1

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

How to change navbar/container width? Bootstrap 3

If you are dealing with more dynamic screen resolution/sizes, instead of hardcoding the size in pixels you can change the width to a percentage of the media width as such

@media (min-width: 1200px) {
        max-width: 70%;

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()


#random dataframe
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

CSS: how to add white space before element's content?

You can use the unicode of a non breaking space :

p:before { content: "\00a0 "; }

See JSfiddle demo

[style improved by @Jason Sperske]

Create html documentation for C# code

This page might interest you:

You can generate the XML documentation file using either the command-line compiler or through the Visual Studio interface. If you are compiling with the command-line compiler, use options /doc or /doc+. That will generate an XML file by the same name and in the same path as the assembly. To specify a different file name, use /doc:file.

If you are using the Visual Studio interface, there's a setting that controls whether the XML documentation file is generated. To set it, double-click My Project in Solution Explorer to open the Project Designer. Navigate to the Compile tab. Find "Generate XML documentation file" at the bottom of the window, and make sure it is checked. By default this setting is on. It generates an XML file using the same name and path as the assembly.

Convert NSDate to NSString

It's swift format :

func dateFormatterWithCalendar(calndarIdentifier: Calendar.Identifier, dateFormat: String) -> DateFormatter {

    let formatter = DateFormatter()
    formatter.calendar = Calendar(identifier: calndarIdentifier)
    formatter.dateFormat = dateFormat

    return formatter

let date = Date()
let fotmatter = dateFormatterWithCalendar(calndarIdentifier: .gregorian, dateFormat: "yyyy")
let dateString = fotmatter.string(from: date)
print(dateString) //2018

What is the difference between signed and unsigned variables?

Signed variables can be 0, positive or negative.

Unsigned variables can be 0 or positive.

Unsigned variables are used sometimes because more bits can be used to represent the actual value. Giving you a larger range. Also you can ensure that a negative value won't be passed to your function for example.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

Building further on Aydin's and Todd's answers, here is an extension method that also lets you get the name from a resource file

using AppResources;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Resources;

public static class EnumExtensions
    public static string GetDisplayName(this Enum enumValue)
        var enumMember= enumValue.GetType()

        DisplayAttribute displayAttrib = null;
        if (enumMember.Any()) {
            displayAttrib = enumMember 

        string name = null;
        Type resource = null;

        if (displayAttrib != null)
            name = displayAttrib.Name;
            resource = displayAttrib.ResourceType;

        return String.IsNullOrEmpty(name) ? enumValue.ToString()
            : resource == null ?  name
            : new ResourceManager(resource).GetString(name);

and use it like

public enum Season 
    [Display(ResourceType = typeof(Resource), Name = Season_Summer")]

Pass Multiple Parameters to jQuery ajax call

    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',      
    data: "jewellerId=" + filter+ "&locale=" +  locale,  
    success: AjaxSucceeded,
    error: AjaxFailed

How to draw circle in html page?

border-radius:50% if you want the circle to adjust to whatever dimensions the container gets (e.g. if the text is variable length)

Don't forget the -moz- and -webkit- prefixes! (prefixing no longer needed)

  border-radius: 50%;
  display: inline-block;
  background: lightgreen;

  padding: 50px;

  width: 100px;
  height: 100px;
<div class='a'></div>
<div class='b'></div>

how to check if input field is empty

Use trim and val.

var value=$.trim($("#spa").val());

 //do some stuffs. 

val() : return the value of the input.

trim(): will trim the white spaces.

How do I get the opposite (negation) of a Boolean in Python?

The not operator (logical negation)

Probably the best way is using the operator not:

>>> value = True
>>> not value

>>> value = False
>>> not value

So instead of your code:

if bool == True:
    return False
    return True

You could use:

return not bool

The logical negation as function

There are also two functions in the operator module operator.not_ and it's alias operator.__not__ in case you need it as function instead of as operator:

>>> import operator
>>> operator.not_(False)
>>> operator.not_(True)

These can be useful if you want to use a function that requires a predicate-function or a callback.

For example map or filter:

>>> lst = [True, False, True, False]
>>> list(map(operator.not_, lst))
[False, True, False, True]

>>> lst = [True, False, True, False]
>>> list(filter(operator.not_, lst))
[False, False]

Of course the same could also be achieved with an equivalent lambda function:

>>> my_not_function = lambda item: not item

>>> list(map(my_not_function, lst))
[False, True, False, True]

Do not use the bitwise invert operator ~ on booleans

One might be tempted to use the bitwise invert operator ~ or the equivalent operator function operator.inv (or one of the other 3 aliases there). But because bool is a subclass of int the result could be unexpected because it doesn't return the "inverse boolean", it returns the "inverse integer":

>>> ~True
>>> ~False

That's because True is equivalent to 1 and False to 0 and bitwise inversion operates on the bitwise representation of the integers 1 and 0.

So these cannot be used to "negate" a bool.

Negation with NumPy arrays (and subclasses)

If you're dealing with NumPy arrays (or subclasses like pandas.Series or pandas.DataFrame) containing booleans you can actually use the bitwise inverse operator (~) to negate all booleans in an array:

>>> import numpy as np
>>> arr = np.array([True, False, True, False])
>>> ~arr
array([False,  True, False,  True])

Or the equivalent NumPy function:

>>> np.bitwise_not(arr)
array([False,  True, False,  True])

You cannot use the not operator or the operator.not function on NumPy arrays because these require that these return a single bool (not an array of booleans), however NumPy also contains a logical not function that works element-wise:

>>> np.logical_not(arr)
array([False,  True, False,  True])

That can also be applied to non-boolean arrays:

>>> arr = np.array([0, 1, 2, 0])
>>> np.logical_not(arr)
array([ True, False, False,  True])

Customizing your own classes

not works by calling bool on the value and negate the result. In the simplest case the truth value will just call __bool__ on the object.

So by implementing __bool__ (or __nonzero__ in Python 2) you can customize the truth value and thus the result of not:

class Test(object):
    def __init__(self, value):
        self._value = value

    def __bool__(self):
        print('__bool__ called on {!r}'.format(self))
        return bool(self._value)

    __nonzero__ = __bool__  # Python 2 compatibility

    def __repr__(self):
        return '{self.__class__.__name__}({self._value!r})'.format(self=self)

I added a print statement so you can verify that it really calls the method:

>>> a = Test(10)
>>> not a
__bool__ called on Test(10)

Likewise you could implement the __invert__ method to implement the behavior when ~ is applied:

class Test(object):
    def __init__(self, value):
        self._value = value

    def __invert__(self):
        print('__invert__ called on {!r}'.format(self))
        return not self._value

    def __repr__(self):
        return '{self.__class__.__name__}({self._value!r})'.format(self=self)

Again with a print call to see that it is actually called:

>>> a = Test(True)
>>> ~a
__invert__ called on Test(True)

>>> a = Test(False)
>>> ~a
__invert__ called on Test(False)

However implementing __invert__ like that could be confusing because it's behavior is different from "normal" Python behavior. If you ever do that clearly document it and make sure that it has a pretty good (and common) use-case.

HTML Table width in percentage, table rows separated equally

you can try this, I would do it with CSS, but i think you want it with tables without CSS.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "">
   <body leftmargin=0 rightmargin=0>
      <table cellpadding="0" cellspacing="0" width="100%" border="1" height="350px"> 
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>
            <td width="25%">&nbsp;</td>

Python strftime - date without leading 0?

Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it's not listed in the Python documentation I found

Facebook API: Get fans of / people who like a page

Facebook's FQL documentation here tells you how to do it. Run the example SELECT name, fan_count FROM page WHERE page_id = 19292868552 and replace the page_id number with your page's id number and it will return the page name and the fan count.

JavaScript hashmap equivalent

Problem description

JavaScript has no built-in general map type (sometimes called associative array or dictionary) which allows to access arbitrary values by arbitrary keys. JavaScript's fundamental data structure is the object, a special type of map which only accepts strings as keys and has special semantics like prototypical inheritance, getters and setters and some further voodoo.

When using objects as maps, you have to remember that the key will be converted to a string value via toString(), which results in mapping 5 and '5' to the same value and all objects which don't overwrite the toString() method to the value indexed by '[object Object]'. You might also involuntarily access its inherited properties if you don't check hasOwnProperty().

JavaScript's built-in array type does not help one bit: JavaScript arrays are not associative arrays, but just objects with a few more special properties. If you want to know why they can't be used as maps, look here.

Eugene's Solution

Eugene Lazutkin already described the basic idea of using a custom hash function to generate unique strings which can be used to look up the associated values as properties of a dictionary object. This will most likely be the fastest solution, because objects are internally implemented as hash tables.

  • Note: Hash tables (sometimes called hash maps) are a particular implementation of the map concept using a backing array and lookup via numeric hash values. The runtime environment might use other structures (such as search trees or skip lists) to implement JavaScript objects, but as objects are the fundamental data structure, they should be sufficiently optimised.

In order to get a unique hash value for arbitrary objects, one possibility is to use a global counter and cache the hash value in the object itself (for example, in a property named __hash).

A hash function which does this is and works for both primitive values and objects is:

function hash(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :

hash.current = 0;

This function can be used as described by Eugene. For convenience, we will further wrap it in a Map class.

My Map implementation

The following implementation will additionally store the key-value-pairs in a doubly linked list in order to allow fast iteration over both keys and values. To supply your own hash function, you can overwrite the instance's hash() method after creation.

// Linking the key-value-pairs is optional.
// If no argument is provided, linkItems === undefined, i.e. !== false
// --> linking will be enabled
function Map(linkItems) {
    this.current = undefined;
    this.size = 0;

    if(linkItems === false)

Map.noop = function() {
    return this;

Map.illegal = function() {
    throw new Error("illegal operation for maps without linking");

// Map initialisation from an existing object
// doesn't add inherited properties if not explicitly instructed to:
// omitting foreignKeys means foreignKeys === undefined, i.e. == false
// --> inherited properties won't be added
Map.from = function(obj, foreignKeys) {
    var map = new Map;

    for(var prop in obj) {
        if(foreignKeys || obj.hasOwnProperty(prop))
            map.put(prop, obj[prop]);

    return map;

Map.prototype.disableLinking = function() { = Map.noop;
    this.unlink = Map.noop;
    this.disableLinking = Map.noop; = Map.illegal;
    this.key = Map.illegal;
    this.value = Map.illegal;
    this.removeAll = Map.illegal;

    return this;

// Overwrite in Map instance if necessary
Map.prototype.hash = function(value) {
    return (typeof value) + ' ' + (value instanceof Object ?
        (value.__hash || (value.__hash = ++arguments.callee.current)) :

Map.prototype.hash.current = 0;

// --- Mapping functions

Map.prototype.get = function(key) {
    var item = this[this.hash(key)];
    return item === undefined ? undefined : item.value;

Map.prototype.put = function(key, value) {
    var hash = this.hash(key);

    if(this[hash] === undefined) {
        var item = { key : key, value : value };
        this[hash] = item;;
    else this[hash].value = value;

    return this;

Map.prototype.remove = function(key) {
    var hash = this.hash(key);
    var item = this[hash];

    if(item !== undefined) {

        delete this[hash];

    return this;

// Only works if linked
Map.prototype.removeAll = function() {

    return this;

// --- Linked list helper functions = function(item) {
    if(this.size == 0) {
        item.prev = item; = item;
        this.current = item;
    else {
        item.prev = this.current.prev; = item; = this.current;
        this.current.prev = item;

Map.prototype.unlink = function(item) {
    if(this.size == 0)
        this.current = undefined;
    else { =; = item.prev;
        if(item === this.current)
            this.current =;

// --- Iterator functions - only work if map is linked = function() {
    this.current =;

Map.prototype.key = function() {
    return this.current.key;

Map.prototype.value = function() {
    return this.current.value;


The following script,

var map = new Map;

map.put('spam', 'eggs').
    put('foo', 'bar').
    put('foo', 'baz').
    put({}, 'an object').
    put({}, 'another object').
    put(5, 'five').
    put(5, 'five again').
    put('5', 'another five');

for(var i = 0; i++ < map.size;
    document.writeln(map.hash(map.key()) + ' : ' + map.value());

generates this output:

string spam : eggs
string foo : baz
object 1 : an object
object 2 : another object
number 5 : five again
string 5 : another five

Further considerations

PEZ suggested to overwrite the toString() method, presumably with our hash function. This is not feasible, because it doesn't work for primitive values (changing toString() for primitives is a very bad idea). If we want toString() to return meaningful values for arbitrary objects, we would have to modify Object.prototype, which some people (myself not included) consider verboten.

The current version of my Map implementation as well as other JavaScript goodies can be obtained from here.

When and why to 'return false' in JavaScript?

When you want to trigger javascript code from an anchor tag, the onclick handler should be used rather than the javascript: pseudo-protocol. The javascript code that runs within the onclick handler must return true or false (or an expression than evalues to true or false) back to the tag itself - if it returns true, then the HREF of the anchor will be followed like a normal link. If it returns false, then the HREF will be ignored. This is why "return false;" is often included at the end of the code within an onclick handler.

Changing image sizes proportionally using CSS?

If you don't want to stretch the image, fit it into div container without overflow and center it by adjusting it's margin if needed.

  1. The image will not get cropped
  2. The aspect ratio will also remain the same.


<div id="app">
    <div id="container">
      <img src="#" alt="something">
    <div id="container">
      <img src="#" alt="something">
    <div id="container">
      <img src="#" alt="something">


div#container {
    height: 200px;
    width: 200px;
    border: 1px solid black;
    margin: 4px;
img {
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;

What Content-Type value should I send for my XML sitemap?

both are fine.

text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.

Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.

SQL Server : fetching records between two dates?

The unambiguous way to write this is (i.e. increase the 2nd date by 1 and make it <)

select * 
from xxx 
where dates >= '20121026'
  and dates <  '20121028'

If you're using SQL Server 2008 or above, you can safety CAST as DATE while retaining SARGability, e.g.

select * 
from xxx 
where CAST(dates as DATE) between '20121026' and '20121027'

This explicitly tells SQL Server that you are only interested in the DATE portion of the dates column for comparison against the BETWEEN range.

addEventListener not working in IE8

I've opted for a quick Polyfill based on the above answers:

//# Polyfill
window.addEventListener = window.addEventListener || function (e, f) { window.attachEvent('on' + e, f); };

//# Standard usage
window.addEventListener("message", function(){ /*...*/ }, false);

Of course, like the answers above this doesn't ensure that window.attachEvent exists, which may or may not be an issue.

Installing a dependency with Bower from URL and specify version

If you use bower.json file to specify your dependencies:

     "dependencies": {
         "photo-swipe": "[email protected]:dimsemenov/PhotoSwipe.git#v3.0.x",

#bower 1.4 (tested with that version) can read repositorios with uri format

         "photo-swipe": "git://",


Just remember bower also searches for released versions and tags so you can point to almost everything, and can interprate basic query patterns like previous example. that will fetch latest minor update of version 3.0 (tested from bower 1.3.5)

Update, as the question description also mention using only a URL and no mention of a github repository.

Another example is to execute this command using the desired url, like:

bower install gmap3MarkerWithLabel= -S

that command downloads your js library puts in {your destination path}/gmap3MarkerWithLabel/index.js and automatically creates an entry in your bower.json file called gmap3MarkerWithLabel: "..." After that, you can only execute bower update gmap3MarkerWithLabel if needed.

Funny thing if you do the process backwars (add manually the entry in bower.json, an then bower install entryName) it doesn't work, you get a

bower ENOTFOUND Package gmapV3MarkerWithLabel not found

How do I check/uncheck all checkboxes with a button using jQuery?

$(function () {
    $('input#check_all').change(function () {
        $("input[name='input_ids[]']").prop('checked', $(this).prop("checked"));

SQL Order By Count

SELECT * FROM table 
group by `Group`

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

Position Relative vs Absolute?

Position Relative:

If you specify position:relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.

Position Absolute:

When you specify position:absolute, the element is removed from the document and placed exactly where you tell it to go.

Here is a good tutorial with the sample usage of both position with respective to absolute and relative positioning.

Dropping Unique constraint from MySQL table

  1. First delete table

  2. go to SQL

Use this code:

CREATE  TABLE service( --tablename 
  `serviceid` int(11) NOT NULL,--columns
  `customerid` varchar(20) DEFAULT NULL,--columns
  `dos` varchar(30) NOT NULL,--columns
  `productname` varchar(150) NOT NULL,--columns
  `modelnumber` bigint(12) NOT NULL,--columns
  `serialnumber` bigint(20) NOT NULL,--columns
  `serviceby` varchar(20) DEFAULT NULL--columns
INSERT INTO `service` (`serviceid`, `customerid`, `dos`, `productname`, `modelnumber`, `serialnumber`, `serviceby`) VALUES
(1, '1', '12/10/2018', 'mouse', 1234555, 234234324, '9999'),
(2, '09', '12/10/2018', 'vhbgj', 79746385, 18923984, '9999'),
(3, '23', '12/10/2018', 'mouse', 123455534, 11111123, '9999'),
(4, '23', '12/10/2018', 'mouse', 12345, 84848, '9999'),
(5, '546456', '12/10/2018', 'ughg', 772882, 457283, '9999'),
(6, '23', '12/10/2018', 'keyboard', 7878787878, 22222, '1'),
(7, '23', '12/10/2018', 'java', 11, 98908, '9999'),
(8, '128', '12/10/2018', 'mouse', 9912280626, 111111, '9999'),
(9, '23', '15/10/2018', 'hg', 29829354, 4564564646, '9999'),
(10, '12', '15/10/2018', '2', 5256, 888888, '9999');
--before droping table
ALTER TABLE `service`
  ADD PRIMARY KEY (`serviceid`),
  ADD  unique`modelnumber` (`modelnumber`),
  ADD  unique`serialnumber` (`serialnumber`),
  ADD unique`modelnumber_2` (`modelnumber`);
--after droping table
ALTER TABLE `service`
  ADD PRIMARY KEY (`serviceid`),
  ADD  modelnumber` (`modelnumber`),
  ADD  serialnumber` (`serialnumber`),
  ADD modelnumber_2` (`modelnumber`);

What's the difference between jquery.js and jquery.min.js?

In easy language, both versions are absolutely the same. Only difference is:

  • min.js is for websites (online)

  • .js is for developers, guys who needs to read, learn about or/and understand jquery codes, for ie plugin development (offline, local work).