Programs & Examples On #Cs3

How to customize the configuration file of the official PostgreSQL Docker image?

A fairly low-tech solution to this problem seems to be to declare the service (I'm using swarm on AWS and a yaml file) with your database files mounted to a persisted volume (here AWS EFS as denoted by the cloudstor:aws driver specification).

  version: '3.3'
  services:
    database:
      image: postgres:latest
      volumes:
        - postgresql:/var/lib/postgresql
        - postgresql_data:/var/lib/postgresql/data
    volumes:
       postgresql:
         driver: "cloudstor:aws" 
       postgresql_data:
         driver: "cloudstor:aws"
  1. The db comes up as initialized with the image default settings.
  2. You edit the conf settings inside the container, e.g if you want to increase the maximum number of concurrent connections that requires a restart
  3. stop the running container (or scale the service down to zero and then back to one)
  4. the swarm spawns a new container, which this time around picks up your persisted configuration settings and merrily applies them.

A pleasant side-effect of persisting your configuration is that it also persists your databases (or was it the other way around) ;-)

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

MySQL CONCAT returns NULL if any field contain NULL

you can use if statement like below

select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices

how to save canvas as png image?

var canvasId = chart.id + '-canvas';
var canvasDownloadId = chart.id + '-download-canvas';
var canvasHtml = Ext.String.format('<canvas id="{0}" width="{1}" height="{2}"></canvas><a id="{3}"/>',
canvasId,
chart.getWidth(),
chart.getHeight(),
canvasDownloadId);
var canvasElement = reportBuilder.add({ html: canvasHtml });

var canvas = document.getElementById(canvasId);

var canvasDownload = document.getElementById(canvasDownloadId);
canvasDownload.href = chart.getImage().data;
canvasDownload.download = 'chart';

canvasDownload.click();

How to Load RSA Private Key From File

Two things. First, you must base64 decode the mykey.pem file yourself. Second, the openssl private key format is specified in PKCS#1 as the RSAPrivateKey ASN.1 structure. It is not compatible with java's PKCS8EncodedKeySpec, which is based on the SubjectPublicKeyInfo ASN.1 structure. If you are willing to use the bouncycastle library you can use a few classes in the bouncycastle provider and bouncycastle PKIX libraries to make quick work of this.

import java.io.BufferedReader;
import java.io.FileReader;
import java.security.KeyPair;
import java.security.Security;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;

// ...   

String keyPath = "mykey.pem";
BufferedReader br = new BufferedReader(new FileReader(keyPath));
Security.addProvider(new BouncyCastleProvider());
PEMParser pp = new PEMParser(br);
PEMKeyPair pemKeyPair = (PEMKeyPair) pp.readObject();
KeyPair kp = new JcaPEMKeyConverter().getKeyPair(pemKeyPair);
pp.close();
samlResponse.sign(Signature.getInstance("SHA1withRSA").toString(), kp.getPrivate(), certs);

PNG transparency issue in IE8

I use a CSS fix rather than JS to workaround my round cornered layer with transparent PNG inside

Try

.ie .whateverDivWrappingTheImage img {
background: #ffaabb; /* this should be the background color matching your design actually */
filter: chroma(#ffaabb); /* and this should match whatever value you put in background-color */
}

This may require more work on ie9 or later.

Interfaces with static fields in java for sharing 'constants'

According to JVM specification, fields and methods in a Interface can have only Public, Static, Final and Abstract. Ref from Inside Java VM

By default, all the methods in interface is abstract even tough you didn't mention it explicitly.

Interfaces are meant to give only specification. It can not contain any implementations. So To avoid implementing classes to change the specification, it is made final. Since Interface cannot be instantiated, they are made static to access the field using interface name.

How do I run a file on localhost?

Ok, thanks for the more specific info, ppl may remove their downvotes now...

What you are proposing is a very common thing to do! You want to run your web application locally without uploading it to your host yet. That's totally fine and that's what your Apache is there for. Your Apache is a web server meaning its main purpose is to serve HTML, PHP, ASP, etc. files. Some like PHP; it first sends to the interpreter and then sends the rendered file to the browser. All in all: it's just serving pages to your browser (the client).

Your web server has a root directory which is wwwroot (IIS) or htdocs (apache, xampp) or something else like public_html, www or html, etc. It depends on your OS and web server.

Now if you type http://localhost into your browser, your browser will be directed to this webroot and the server will serve any index.html, index.php, etc. it can find there (in a customizable order).

If you have a project called "mytutorial" you can enter http://localhost/mytutorial and the server will show you the index-file of your tutorial, etc. If you look at the absolute path of this tutorial folder then it's just a subfolder of your webroot, which is itself located somewhere on your harddrive, but that doesn't matter for your localhost.

So the relative path is

http://localhost/mytutorial

while the absolute path may be

c:/webservices/apache/www

or

c:/xampp/htdocs

If you're working with Dreamweaver you can simplify the testing process by setting up your local server as a testing server in your project settings. Try it! It's easy. Once it's done, you can just press the browser icon with any of your files and it will open on localhost.

Working with Enums in android

Android's preferred approach is int constants enforced with @IntDef:

public static final int GENDER_MALE = 1;
public static final int GENDER_FEMALE = 2;

@Retention(RetentionPolicy.SOURCE)
@IntDef ({GENDER_MALE, GENDER_FEMALE})
public @interface Gender{}

// Example usage...
void exampleFunc(@Gender int gender) {
  switch(gender) {
  case GENDER_MALE:

     break;
  case GENDER_FEMALE:
     // TODO
     break;
  }
}

Docs: https://developer.android.com/studio/write/annotations.html#enum-annotations

How to generate List<String> from SQL query?

I think this is what you're looking for.

List<String> columnData = new List<String>();

using(SqlConnection connection = new SqlConnection("conn_string"))
{
    connection.Open();
    string query = "SELECT Column1 FROM Table1";
    using(SqlCommand command = new SqlCommand(query, connection))
    {
        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                columnData.Add(reader.GetString(0));
            }         
        }
    }
}

Not tested, but this should work fine.

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

<!DOCTYPE html>
<html lang="en">
<head>
<style>
#container { width: 100%; border: 1px solid black; display: block; text-align: justify; }
object, span { display: inline-block; }
span { width: 100%; }
</style>
</head>

  <div id="container">
    <object>
      <div>
      alpha
      </div>
    </object>
    <object>
      <div>
      beta
      </div>
    </object>
    <object>
      <div>
      charlie
      </div>
    </object>
    <object>
      <div>
      delta
      </div>
    </object>
    <object>
      <div>
      epsilon
      </div>
    </object>
    <object>
      <div>
      foxtrot
      </div>
    </object>
    <span></span>
  </div>
</html>

Html.fromHtml deprecated in Android N

Compare of the flags of fromHtml().

<p style="color: blue;">This is a paragraph with a style</p>

<h4>Heading H4</h4>

<ul>
   <li style="color: yellow;">
      <font color=\'#FF8000\'>li orange element</font>
   </li>
   <li>li #2 element</li>
</ul>

<blockquote>This is a blockquote</blockquote>

Text after blockquote
Text before div

<div>This is a div</div>

Text after div

FROM_HTML FLAGS

C# - insert values from file into two arrays

var Text = File.ReadAllLines("Path"); foreach (var i in Text) {    var SplitText = i.Split().Where(x=> x.Lenght>1).ToList();    //@Array1 add SplitText[0]    //@Array2 add SpliteText[1]   }  

how to permit an array with strong parameters

If you want to permit an array of hashes(or an array of objects from the perspective of JSON)

params.permit(:foo, array: [:key1, :key2])

2 points to notice here:

  1. array should be the last argument of the permit method.
  2. you should specify keys of the hash in the array, otherwise you will get an error Unpermitted parameter: array, which is very difficult to debug in this case.

Convert timestamp in milliseconds to string formatted time in Java

It is possible to use apache commons (commons-lang3) and its DurationFormatUtils class.

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.1</version>
</dependency>

For example:

String formattedDuration = DurationFormatUtils.formatDurationHMS(12313152);
// formattedDuration value is "3:25:13.152"
String otherFormattedDuration = DurationFormatUtils.formatDuration(12313152, DurationFormatUtils.ISO_EXTENDED_FORMAT_PATTERN);
// otherFormattedDuration value is "P0000Y0M0DT3H25M13.152S"

Hope it can help ...

Border around each cell in a range

The following can be called with any range as parameter:

Option Explicit

Sub SetRangeBorder(poRng As Range)
    If Not poRng Is Nothing Then
        poRng.Borders(xlDiagonalDown).LineStyle = xlNone
        poRng.Borders(xlDiagonalUp).LineStyle = xlNone
        poRng.Borders(xlEdgeLeft).LineStyle = xlContinuous
        poRng.Borders(xlEdgeTop).LineStyle = xlContinuous
        poRng.Borders(xlEdgeBottom).LineStyle = xlContinuous
        poRng.Borders(xlEdgeRight).LineStyle = xlContinuous
        poRng.Borders(xlInsideVertical).LineStyle = xlContinuous
        poRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
    End If
End Sub

Examples:

Call SetRangeBorder(Range("C11"))
Call SetRangeBorder(Range("A" & result))
Call SetRangeBorder(DT.Cells(I, 6))
Call SetRangeBorder(Range("A3:I" & endRow))

phpmyadmin "no data received to import" error, how to fix?

Check permissions for you upload directory. You can find its path inside /etc/phpmyadmin/apache.conf file.

In my case (Ubuntu 14.04) it was:

php_admin_value upload_tmp_dir /var/lib/phpmyadmin/tmp

So I checked permissions for /var/lib/phpmyadmin/tmp and it turns out that the directory wasn't writable for my Apache user (which is by default www-data). It could be the case especially if you changed your apache user like I do.

How to remove focus border (outline) around text/input boxes? (Chrome)

input:focus {
    outline:none;
}

This will do. Orange outline won't show up anymore.

Create intermediate folders if one doesn't exist

You have to actually call some method to create the directories. Just creating a file object will not create the corresponding file or directory on the file system.

You can use File#mkdirs() method to create the directory: -

theFile.mkdirs();

Difference between File#mkdir() and File#mkdirs() is that, the later will create any intermediate directory if it does not exist.

Javascript reduce() on Object

1:

[{value:5}, {value:10}].reduce((previousValue, currentValue) => { return {value: previousValue.value + currentValue.value}})

>> Object {value: 15}

2:

[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })

>> 15

3:

[{value:5}, {value:10}].reduce(function (previousValue, currentValue) {
      return {value: previousValue.value + currentValue.value};
})

>> Object {value: 15}

Difference between .dll and .exe?

The major exact difference between DLL and EXE that DLL hasn't got an entry point and EXE does. If you are familiar with c++ you can see that build EXE has main() entry function and DLL doesn't :)

How to convert password into md5 in jquery?

Get the field value through the id and send with ajax

var field = $("#field").val();
$.ajax({
    type: "POST",
    url: "db.php",
    data: {variable_name:field},
    async:false,
    dataType:"json",
    success: function(response) {
       alert(response);
    }
 });

At db.php file get the variable name

$variable_name = $_GET['variable_name'];
mysql_query("SELECT password FROM table_name WHERE password='".md5($variable_name)."'");

How to correctly represent a whitespace character

Using regular expressions, you can represent any whitespace character with the metacharacter "\s"

MSDN Reference

What is the difference between varchar and nvarchar?

It depends on how Oracle was installed. During the installation process, the NLS_CHARACTERSET option is set. You may be able to find it with the query SELECT value$ FROM sys.props$ WHERE name = 'NLS_CHARACTERSET'.

If your NLS_CHARACTERSET is a Unicode encoding like UTF8, great. Using VARCHAR and NVARCHAR are pretty much identical. Stop reading now, just go for it. Otherwise, or if you have no control over the Oracle character set, read on.

VARCHAR — Data is stored in the NLS_CHARACTERSET encoding. If there are other database instances on the same server, you may be restricted by them; and vice versa, since you have to share the setting. Such a field can store any data that can be encoded using that character set, and nothing else. So for example if the character set is MS-1252, you can only store characters like English letters, a handful of accented letters, and a few others (like € and —). Your application would be useful only to a few locales, unable to operate anywhere else in the world. For this reason, it is considered A Bad Idea.

NVARCHAR — Data is stored in a Unicode encoding. Every language is supported. A Good Idea.

What about storage space? VARCHAR is generally efficient, since the character set / encoding was custom-designed for a specific locale. NVARCHAR fields store either in UTF-8 or UTF-16 encoding, base on the NLS setting ironically enough. UTF-8 is very efficient for "Western" languages, while still supporting Asian languages. UTF-16 is very efficient for Asian languages, while still supporting "Western" languages. If concerned about storage space, pick an NLS setting to cause Oracle to use UTF-8 or UTF-16 as appropriate.

What about processing speed? Most new coding platforms use Unicode natively (Java, .NET, even C++ std::wstring from years ago!) so if the database field is VARCHAR it forces Oracle to convert between character sets on every read or write, not so good. Using NVARCHAR avoids the conversion.

Bottom line: Use NVARCHAR! It avoids limitations and dependencies, is fine for storage space, and usually best for performance too.

Insert variable values in the middle of a string

You can use string.Format:

string template = "Hi We have these flights for you: {0}. Which one do you want";
string data = "A, B, C, D";
string message = string.Format(template, data);

You should load template from your resource file and data is your runtime values.

Be careful if you're translating to multiple languages, though: in some cases, you'll need different tokens (the {0}) in different languages.

Reducing the gap between a bullet and text in a list item

I've tried these and other solutions offered, which don't actually work, but I seem to have found a way to do this, and that is to remove the bullet and use the :before pseudo-element to put a Unicode bullet in its place. Then you can adjust the the space between the list item and bullet. You have to use Unicode to insert an entity into the content property of :before or :after - HTML entities don't work.

There's some sizing and positioning code needed too, because the Unicode bullet by default displays the size of a pinhead. So the bullet has to be enlarged and absolutely positioned to get it into place. Note the use of ems for the bullet's sizing and positioning so that the bullet's relationship to the list item stays constant when your change the font size of the list item. The comments in the code explain how it all works. If you want to use a different entity, you can find a list of the Unicode entities here:

http://www.evotech.net/blog/2007/04/named-html-entities-in-numeric-order/

Use a value from the far right column (octal) from the table on this page - you just need the \ and number. You should be able to trash everying except the content property from the :before rule when using the other entities as they seem to display at a useable size. Email me: charles at stylinwithcss dot com with any thoughts/comments. I tested it Firefox, Chrome and Safari and it works nicely.

    body {
      font-family:"Trebuchet MS", sans-serif;
      }
    li  {
      font-size:14px;        /* set font size of list item and bullet here */
      list-style-type:none; /* removes default bullet */
      position:relative;      /* positioning context for bullet */
      }
      li:before  {
        content:"\2219";    /* escaped unicode character */
        font-size:2.5em;    /* the default unicode bullet size is very small */
        line-height:0;        /* kills huge line height on resized bullet */
        position:absolute;  /* position bullet relative to list item */
        top:.23em;           /* vertical align bullet position relative to list item */
        left:-.5em;            /* position the bullet L- R relative to list item */
       }

Regex date format validation on Java

Construct a SimpleDateFormat with the mask, and then call: SimpleDateFormat.parse(String s, ParsePosition p)

remove empty lines from text file with PowerShell

Not specifically using -replace, but you get the same effect parsing the content using -notmatch and regex.

(get-content 'c:\FileWithEmptyLines.txt') -notmatch '^\s*$' > c:\FileWithNoEmptyLines.txt

C++ compile error: has initializer but incomplete type

You need this include:

#include <sstream>

One line if-condition-assignment

Another way num1 = (20*boolVar)+(num1*(not boolVar))

The entity cannot be constructed in a LINQ to Entities query

You can use this and it should be working --> You must use toList before making the new list using select:

db.Products
    .where(x=>x.CategoryID == categoryID).ToList()
    .select(x=>new Product { Name = p.Name}).ToList(); 

How to create a temporary directory and get the path / file name in Python

Use the mkdtemp() function from the tempfile module:

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)

How do I declare an array with a custom class?

You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.

Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.

Here is the working code:

#include <iostream> 
#include <string>  // <-- you need this if you want to use string type

using namespace std; 

class name { 
  public: 
    string first; 
    string last; 

  name(string a, string b){ 
    first = a; 
    last = b; 

  }

  name ()  // <-- this is your explicit parameterless constructor
  {}

}; 

int main (int argc, const char * argv[]) 
{ 

  const int howManyNames = 3; 

  name someName[howManyNames]; 

  return 0; 
}

(BTW, you need to include to make the code compilable.)

An alternative way is to initialize your instances explicitly on declaration

  name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };

How to load up CSS files using Javascript?

use:

document.getElementById("of head/body tag")
        .innerHTML += '<link rel="stylesheet" type="text/css" href="style.css">';

ignoring any 'bin' directory on a git project

As a notice;

If you think about .gitignore does not work in a way (so added foo/* folder in it but git status still showing that folder content(s) as modified or something like this), then you can use this command;

git checkout -- foo/*

How can I write these variables into one line of code in C#?

Use $ before " " it will allow to write variables between these brackets

 Console.WriteLine($"{mon}.{da}.{yer}");

The pro way :

  Console.WriteLine($"{DateTime.Today.Month}.{DateTime.Today.Day}.{DateTime.Today.Year}");
  Console.WriteLine($"month{DateTime.Today.Month} day{DateTime.Today.Day} year{DateTime.Today.Year}");

5.24.2016

month5 day24 year2016

Change drive in git bash for windows

How I do it in Windows 10

Go to your folder directory you want to open in git bash like so

enter image description here

After you have reached the folder simply type git bash in the top navigation area like so and hit enter.

enter image description here

A git bash for the destined folder will open for you.

enter image description here

Hope that helps.

UTF-8 all the way through

In addition to setting default_charset in php.ini, you can send the correct charset using header() from within your code, before any output:

header('Content-Type: text/html; charset=utf-8');

Working with Unicode in PHP is easy as long as you realize that most of the string functions don't work with Unicode, and some might mangle strings completely. PHP considers "characters" to be 1 byte long. Sometimes this is okay (for example, explode() only looks for a byte sequence and uses it as a separator -- so it doesn't matter what actual characters you look for). But other times, when the function is actually designed to work on characters, PHP has no idea that your text has multi-byte characters that are found with Unicode.

A good library to check into is phputf8. This rewrites all of the "bad" functions so you can safely work on UTF8 strings. There are extensions like the mbstring extension that try to do this for you, too, but I prefer using the library because it's more portable (but I write mass-market products, so that's important for me). But phputf8 can use mbstring behind the scenes, anyway, to increase performance.

Java 8 forEach with index

It works with params if you capture an array with one element, that holds the current index.

int[] idx = { 0 };
params.forEach(e -> query.bind(idx[0]++, e));

The above code assumes, that the method forEach iterates through the elements in encounter order. The interface Iterable specifies this behaviour for all classes unless otherwise documented. Apparently it works for all implementations of Iterable from the standard library, and changing this behaviour in the future would break backward-compatibility.

If you are working with Streams instead of Collections/Iterables, you should use forEachOrdered, because forEach can be executed concurrently and the elements can occur in different order. The following code works for both sequential and parallel streams:

int[] idx = { 0 };
params.stream().forEachOrdered(e -> query.bind(idx[0]++, e));

Sending and receiving data over a network using TcpClient

I've developed a dotnet library that might come in useful. I have fixed the problem of never getting all of the data if it exceeds the buffer, which many posts have discounted. Still some problems with the solution but works descently well https://github.com/NicholasLKSharp/DotNet-TCP-Communication

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

Use a default form value to avoid the error.

Instead of using the accepted answer of applying detectChanges() in ngAfterViewInit() (which also solved the error in my case), I decided instead to save a default value for a dynamically required form field, so that when the form is later updated, it's validity is not changed if the user decides to change an option on the form that would trigger the new required fields (and cause the submit button to be disabled).

This saved a tiny bit of code in my component, and in my case the error was avoided altogether.

Laravel migration default value

Might be a little too late to the party, but hope this helps someone with similar issue.

The reason why your default value doesnt't work is because the migration file sets up the default value in your database (MySQL or PostgreSQL or whatever), and not in your Laravel application.

Let me illustrate with an example.

This line means Laravel is generating a new Book instance, as specified in your model. The new Book object will have properties according to the table associated with the model. Up until this point, nothing is written on the database.

$book = new Book();

Now the following lines are setting up the values of each property of the Book object. Same still, nothing is written on the database yet.

$book->author = 'Test'
$book->title = 'Test'

This line is the one writing to the database. After passing on the object to the database, then the empty fields will be filled by the database (may be default value, may be null, or whatever you specify on your migration file).

$book->save();

And thus, the default value will not pop up before you save it to the database.

But, that is not enough. If you try to access $book->price, it will still be null (or 0, i'm not sure). Saving it is only adding the defaults to the record in the database, and it won't affect the Object you are carrying around.

So, to get the instance with filled-in default values, you have to re-fetch the instance. You may use the

Book::find($book->id);

Or, a more sophisticated way by refreshing the instance

$book->refresh();

And then, the next time you try to access the object, it will be filled with the default values.

Difference between static, auto, global and local variable in the context of c and c++

static is a heavily overloaded word in C and C++. static variables in the context of a function are variables that hold their values between calls. They exist for the duration of the program.

local variables persist only for the lifetime of a function or whatever their enclosing scope is. For example:

void foo()
{
    int i, j, k;
    //initialize, do stuff
} //i, j, k fall out of scope, no longer exist

Sometimes this scoping is used on purpose with { } blocks:

{ 
   int i, j, k;
   //...
} //i, j, k now out of scope

global variables exist for the duration of the program.

auto is now different in C and C++. auto in C was a (superfluous) way of specifying a local variable. In C++11, auto is now used to automatically derive the type of a value/expression.

Getting distance between two points based on latitude/longitude

There are multiple ways to calculate the distance based on the coordinates i.e latitude and longitude

Install and import

from geopy import distance
from math import sin, cos, sqrt, atan2, radians
from sklearn.neighbors import DistanceMetric
import osrm
import numpy as np

Define coordinates

lat1, lon1, lat2, lon2, R = 20.9467,72.9520, 21.1702, 72.8311, 6373.0
coordinates_from = [lat1, lon1]
coordinates_to = [lat2, lon2]

Using haversine

dlon = radians(lon2) - radians(lon1)
dlat = radians(lat2) - radians(lat1)
    
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * atan2(sqrt(a), sqrt(1 - a))
    
distance_haversine_formula = R * c
print('distance using haversine formula: ', distance_haversine_formula)

Using haversine with sklearn

dist = DistanceMetric.get_metric('haversine')
    
X = [[radians(lat1), radians(lon1)], [radians(lat2), radians(lon2)]]
distance_sklearn = R * dist.pairwise(X)
print('distance using sklearn: ', np.array(distance_sklearn).item(1))

Using OSRM

osrm_client = osrm.Client(host='http://router.project-osrm.org')
coordinates_osrm = [[lon1, lat1], [lon2, lat2]] # note that order is lon, lat
    
osrm_response = osrm_client.route(coordinates=coordinates_osrm, overview=osrm.overview.full)
dist_osrm = osrm_response.get('routes')[0].get('distance')/1000 # in km
print('distance using OSRM: ', dist_osrm)

Using geopy

distance_geopy = distance.distance(coordinates_from, coordinates_to).km
print('distance using geopy: ', distance_geopy)
    
distance_geopy_great_circle = distance.great_circle(coordinates_from, coordinates_to).km 
print('distance using geopy great circle: ', distance_geopy_great_circle)

Output

distance using haversine formula:  26.07547017310917
distance using sklearn:  27.847882224769783
distance using OSRM:  33.091699999999996
distance using geopy:  27.7528030550408
distance using geopy great circle:  27.839182219511834

How to implement common bash idioms in Python?

Any shell has several sets of features.

  • The Essential Linux/Unix commands. All of these are available through the subprocess library. This isn't always the best first choice for doing all external commands. Look also at shutil for some commands that are separate Linux commands, but you could probably implement directly in your Python scripts. Another huge batch of Linux commands are in the os library; you can do these more simply in Python.

    And -- bonus! -- more quickly. Each separate Linux command in the shell (with a few exceptions) forks a subprocess. By using Python shutil and os modules, you don't fork a subprocess.

  • The shell environment features. This includes stuff that sets a command's environment (current directory and environment variables and what-not). You can easily manage this from Python directly.

  • The shell programming features. This is all the process status code checking, the various logic commands (if, while, for, etc.) the test command and all of it's relatives. The function definition stuff. This is all much, much easier in Python. This is one of the huge victories in getting rid of bash and doing it in Python.

  • Interaction features. This includes command history and what-not. You don't need this for writing shell scripts. This is only for human interaction, and not for script-writing.

  • The shell file management features. This includes redirection and pipelines. This is trickier. Much of this can be done with subprocess. But some things that are easy in the shell are unpleasant in Python. Specifically stuff like (a | b; c ) | something >result. This runs two processes in parallel (with output of a as input to b), followed by a third process. The output from that sequence is run in parallel with something and the output is collected into a file named result. That's just complex to express in any other language.

Specific programs (awk, sed, grep, etc.) can often be rewritten as Python modules. Don't go overboard. Replace what you need and evolve your "grep" module. Don't start out writing a Python module that replaces "grep".

The best thing is that you can do this in steps.

  1. Replace AWK and PERL with Python. Leave everything else alone.
  2. Look at replacing GREP with Python. This can be a bit more complex, but your version of GREP can be tailored to your processing needs.
  3. Look at replacing FIND with Python loops that use os.walk. This is a big win because you don't spawn as many processes.
  4. Look at replacing common shell logic (loops, decisions, etc.) with Python scripts.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Merge two array of objects based on a key

This solution is applicable even when you have different size of array being merged. Also, even if the keys on which match is happening has a different name.

const arr1 = [
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" },
  { id: "abdc4053", date: "2017-01-22" }
];
const arr2 = [
  { nameId: "abdc4051", name: "ab" },
  { nameId: "abdc4052", name: "abc" }
];

Now to merge these use a Map as follows:

const map = new Map();
arr1.forEach(item => map.set(item.id, item));
arr2.forEach(item => map.set(item.nameId, {...map.get(item.nameId), ...item}));
const mergedArr = Array.from(map.values());

This should result in:

[
  {
    "id": "abdc4051",
    "date": "2017-01-24",
    "nameId": "abdc4051",
    "name": "ab"
  },
  {
    "id": "abdc4052",
    "date": "2017-01-22",
    "nameId": "abdc4052",
    "name": "abc"
  },
  {
    "id": "abdc4053",
    "date": "2017-01-22"
  }
]

how to set windows service username and password through commandline

In PowerShell, the "sc" command is an alias for the Set-Content cmdlet. You can workaround this using the following syntax:

sc.exe config Service obj= user password= pass

Specyfying the .exe extension, PowerShell bypasses the alias lookup.

HTH

OnClickListener in Android Studio

This worked for me:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_newarea);

    btnSave = (Button)findViewById(R.id.btnSave);

    OnClickListener btnListener = new OnClickListener() {
        @Override
        public void onClick(android.view.View view) {
            finish();
        }
    };
    btnSave.setOnClickListener(btnListener);

}

CSS Layout - Dynamic width DIV

This will do what you want. Fixed sides with 50px-width, and the content fills the remaining area.

<div style="width:100%;">
    <div style="width: 50px; float: left;">Left Side</div>
    <div style="width: 50px; float: right;">Right Side</div>
    <div style="margin-left: 50px; margin-right: 50px;">Content Goes Here</div>
</div>

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

I had the same error, but it was caused by the package manager process port being already used (port 8081).

To fix, I just ran the react-native by specifying a different port, see below.

react-native run-ios --port 8090

Authentication issue when debugging in VS2013 - iis express

Open up the applicationHost.config file located in the C:\Users[userid]\Documents\IISExpress\config folder. Inside this file change the overrideModeDefault of anonymousAthentication and windowsAuthentication to "Allow"

 <sectionGroup name="security">
                <section name="access" overrideModeDefault="Deny" />
                <section name="applicationDependencies" overrideModeDefault="Deny" />
                <sectionGroup name="authentication">
                    <section name="anonymousAuthentication" overrideModeDefault="Allow" />
                    <section name="basicAuthentication" overrideModeDefault="Deny" />
                    <section name="clientCertificateMappingAuthentication" overrideModeDefault="Deny" />
                    <section name="digestAuthentication" overrideModeDefault="Deny" />
                    <section name="iisClientCertificateMappingAuthentication" overrideModeDefault="Deny" />
                    <section name="windowsAuthentication" overrideModeDefault="Allow" />
                </sectionGroup>

Next change lockItem to be "false" for AnonymousAuthenticationModule and WindowsAuthenticationModule

  <system.webServer>
            <modules>
                <!--
                <add name="HttpCacheModule" lockItem="true" />
-->
                <add name="DynamicCompressionModule" lockItem="true" />
                <add name="StaticCompressionModule" lockItem="true" />
                <add name="DefaultDocumentModule" lockItem="true" />
                <add name="DirectoryListingModule" lockItem="true" />
                <add name="IsapiFilterModule" lockItem="true" />
                <add name="ProtocolSupportModule" lockItem="true" />
                <add name="HttpRedirectionModule" lockItem="true" />
                <add name="ServerSideIncludeModule" lockItem="true" />
                <add name="StaticFileModule" lockItem="true" />
                <add name="AnonymousAuthenticationModule" lockItem="false" />
                <add name="CertificateMappingAuthenticationModule" lockItem="true" />
                <add name="UrlAuthorizationModule" lockItem="true" />
                <add name="BasicAuthenticationModule" lockItem="true" />
                <add name="WindowsAuthenticationModule" lockItem="false" />

Making these changes will allow the existing web config settings to override what is in the applicationHost file for IIS Express.

C++ error 'Undefined reference to Class::Function()'

This part has problems:

Card* cardArray;
void Deck() {
    cardArray = new Card[NUM_TOTAL_CARDS];
    int cardCount = 0;
    for (int i = 0; i > NUM_SUITS; i++) {  //Error
        for (int j = 0; j > NUM_RANKS; j++) { //Error
            cardArray[cardCount] = Card(Card::Rank(i), Card::Suit(j) );
            cardCount++;
         }
    }
 }
  1. cardArray is a dynamic array, but not a member of Card class. It is strange if you would like to initialize a dynamic array which is not member of the class
  2. void Deck() is not constructor of class Deck since you missed the scope resolution operator. You may be confused with defining the constructor and the function with name Deck and return type void.
  3. in your loops, you should use < not > otherwise, loop will never be executed.

onclick go full screen

Short personal bookmarklet version

javascript: document.body.webkitRequestFullScreen(); 

go fullscreen ? You can drag this link to your bookmark bar to create the bookmarklet, but you have to edit its URL afterwards: Delete everything before javascript, including the single slash: http://delete_me/javascript:[…]

This works for me in Google Chrome. You have to test whether it works in your environment and otherwise use a different wording of the function call, e.g. javascript:document.body.requestFullScreen(); – see the other answers for the possible variants.

Based on the answers by @Zuul and @default – thanks!

How to get a substring between two strings in PHP?

function getInnerSubstring($string,$delim){
    // "foo a foo" becomes: array(""," a ","")
    $string = explode($delim, $string, 3); // also, we only need 2 items at most
    // we check whether the 2nd is set and return it, otherwise we return an empty string
    return isset($string[1]) ? $string[1] : '';
}

Example of use:

var_dump(getInnerSubstring('foo Hello world foo','foo'));
// prints: string(13) " Hello world "

If you want to remove surrounding whitespace, use trim. Example:

var_dump(trim(getInnerSubstring('foo Hello world foo','foo')));
// prints: string(11) "Hello world"

How to check if an integer is within a range?

I'm not able to comment (not enough reputation) so I'll amend Luis Rosety's answer here:

function between($n, $a, $b) {
    return ($n-$a)*($n-$b) <= 0;
}

This function works also in cases where n == a or n == b.

Proof: Let n belong to range [a,b], where [a,b] is a subset of real numbers.

Now a <= n <= b. Then n-a >= 0 and n-b <= 0. That means that (n-a)*(n-b) <= 0.

Case b <= n <= a works similarly.

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

Parse JSON String to JSON Object in C#.NET

use new JavaScriptSerializer().Deserialize<object>(jsonString)

You need System.Web.Extensions dll and import the following namespace.

Namespace: System.Web.Script.Serialization

for more info MSDN

SQL Statement with multiple SETs and WHEREs

No, you would need to create a seperate query for each update.

How to embed a SWF file in an HTML page?

This one will work, I am sure!

<embed src="application.swf" quality="high" pluginspage="http://www.macromedia.com/go/getfashplayer" type="application/x-shockwave-flash" width="690" height="430">

How do I print the full value of a long string in gdb?

As long as your program's in a sane state, you can also call (void)puts(your_string) to print it to stdout. Same principle applies to all functions available to the debugger, actually.

Saving an Excel sheet in a current directory with VBA

Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:

workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"

Only works if your file structure contains one instance of the text used to replace. YMMV.

How to convert an int value to string in Go?

You can use fmt.Sprintf or strconv.FormatFloat

For example

package main

import (
    "fmt"
)

func main() {
    val := 14.7
    s := fmt.Sprintf("%f", val)
    fmt.Println(s)
}

Printing one character at a time from a string, using the while loop

I'm quite sure, that the internet is full of python while-loops, but one example:

i=0

while i < len(text):
    print text[i]
    i += 1

How to convert rdd object to dataframe in spark

Method 1: (Scala)

val sqlContext = new org.apache.spark.sql.SQLContext(sc)
import sqlContext.implicits._
val df_2 = sc.parallelize(Seq((1L, 3.0, "a"), (2L, -1.0, "b"), (3L, 0.0, "c"))).toDF("x", "y", "z")

Method 2: (Scala)

case class temp(val1: String,val3 : Double) 

val rdd = sc.parallelize(Seq(
  Row("foo",  0.5), Row("bar",  0.0)
))
val rows = rdd.map({case Row(val1:String,val3:Double) => temp(val1,val3)}).toDF()
rows.show()

Method 1: (Python)

from pyspark.sql import Row
l = [('Alice',2)]
Person = Row('name','age')
rdd = sc.parallelize(l)
person = rdd.map(lambda r:Person(*r))
df2 = sqlContext.createDataFrame(person)
df2.show()

Method 2: (Python)

from pyspark.sql.types import * 
l = [('Alice',2)]
rdd = sc.parallelize(l)
schema =  StructType([StructField ("name" , StringType(), True) , 
StructField("age" , IntegerType(), True)]) 
df3 = sqlContext.createDataFrame(rdd, schema) 
df3.show()

Extracted the value from the row object and then applied the case class to convert rdd to DF

val temp1 = attrib1.map{case Row ( key: Int ) => s"$key" }
val temp2 = attrib2.map{case Row ( key: Int) => s"$key" }

case class RLT (id: String, attrib_1 : String, attrib_2 : String)
import hiveContext.implicits._

val df = result.map{ s => RLT(s(0),s(1),s(2)) }.toDF

Pointer-to-pointer dynamic two-dimensional array

What you describe for the second method only gives you a 1D array:

int *board = new int[10];

This just allocates an array with 10 elements. Perhaps you meant something like this:

int **board = new int*[4];
for (int i = 0; i < 4; i++) {
  board[i] = new int[10];
}

In this case, we allocate 4 int*s and then make each of those point to a dynamically allocated array of 10 ints.

So now we're comparing that with int* board[4];. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*s, as the array will be destroyed at the end of its scope.

The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:

for (int i = 0; i < 4; i++) {
  delete[] board[i];
}
delete[] board;

I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4> or perhaps a std::vector<std::vector<int>> which you initialise to the appropriate size.

ERROR 1064 (42000) in MySQL

I had this error because of using mysql/mariadb reserved words:

INSERT INTO tablename (precision) VALUE (2)

should be

INSERT INTO tablename (`precision`) VALUE (2)

LaTeX Optional Arguments

All of the above show hard it can be to make a nice, flexible (or forbid an overloaded) function in LaTeX!!! (that TeX code looks like greek to me)

well, just to add my recent (albeit not as flexible) development, here's what I've recently used in my thesis doc, with

\usepackage{ifthen}  % provides conditonals...

Start the command, with the "optional" command set blank by default:

\newcommand {\figHoriz} [4] []  {

I then have the macro set a temporary variable, \temp{}, differently depending on whether or not the optional argument is blank. This could be extended to any passed argument.

\ifthenelse { \equal {#1} {} }  %if short caption not specified, use long caption (no slant)
    { \def\temp {\caption[#4]{\textsl{#4}}} }   % if #1 == blank
    { \def\temp {\caption[#1]{\textsl{#4}}} }   % else (not blank)

Then I run the macro using the \temp{} variable for the two cases. (Here it just sets the short-caption to equal the long caption if it wasn't specified by the user).

\begin{figure}[!]
    \begin{center}
        \includegraphics[width=350 pt]{#3}
        \temp   %see above for caption etc.
        \label{#2}
    \end{center}
\end{figure}
}

In this case I only check for the single, "optional" argument that \newcommand{} provides. If you were to set it up for, say, 3 "optional" args, you'd still have to send the 3 blank args... eg.

\MyCommand {first arg} {} {} {}

which is pretty silly, I know, but that's about as far as I'm going to go with LaTeX - it's just not that sensical once I start looking at TeX code... I do like Mr. Robertson's xparse method though, perhaps I'll try it...

How to sort a list of objects based on an attribute of the objects?

from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)

What is the most effective way for float and double comparison?

As others have pointed out, using a fixed-exponent epsilon (such as 0.0000001) will be useless for values away from the epsilon value. For example, if your two values are 10000.000977 and 10000, then there are NO 32-bit floating-point values between these two numbers -- 10000 and 10000.000977 are as close as you can possibly get without being bit-for-bit identical. Here, an epsilon of less than 0.0009 is meaningless; you might as well use the straight equality operator.

Likewise, as the two values approach epsilon in size, the relative error grows to 100%.

Thus, trying to mix a fixed point number such as 0.00001 with floating-point values (where the exponent is arbitrary) is a pointless exercise. This will only ever work if you can be assured that the operand values lie within a narrow domain (that is, close to some specific exponent), and if you properly select an epsilon value for that specific test. If you pull a number out of the air ("Hey! 0.00001 is small, so that must be good!"), you're doomed to numerical errors. I've spent plenty of time debugging bad numerical code where some poor schmuck tosses in random epsilon values to make yet another test case work.

If you do numerical programming of any kind and believe you need to reach for fixed-point epsilons, READ BRUCE'S ARTICLE ON COMPARING FLOATING-POINT NUMBERS.

Comparing Floating Point Numbers

How to create a scrollable Div Tag Vertically?

This code creates a nice vertical scrollbar for me in Firefox and Chrome:

_x000D_
_x000D_
#answerform {
  position: absolute;
  border: 5px solid gray;
  padding: 5px;
  background: white;
  width: 300px;
  height: 400px;
  overflow-y: scroll;
}
_x000D_
<div id='answerform'>
  badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br> mushroom
  <br><br>mushroom<br><br> a badger<br><br>badger<br><br>badger<br><br>badger<br><br>badger<br><br>
</div>
_x000D_
_x000D_
_x000D_

Here is a JS fiddle demo proving the above works.

How to add rows dynamically into table layout

You are doing it right; every time you need to add a row, simply so new TableRow(), etc. It might be easier for you to inflate the new row from XML though.

How can I add to a List's first position?

Use List.Insert(0, ...). But are you sure a LinkedList isn't a better fit? Each time you insert an item into an array at a position other than the array end, all existing items will have to be copied to make space for the new one.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

You are trying to set the timezone for date_time which already has a timezone. Use replace and astimezone functions.

local_tz = pytz.timezone('Asia/Kolkata')

current_time = datetime.now().replace(tzinfo=pytz.utc).astimezone(local_tz)

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

Adding Lombok plugin to IntelliJ project

You need to Enable Annotation Processing on IntelliJ IDEA

> Settings > Build, Execution, Deployment > Compiler > Annotation Processors

enter image description here

How do I set an ASP.NET Label text from code behind on page load?

protected void Page_Load(object sender, EventArgs e)
{
    myLabel.Text = "My text";
}

this is the base of ASP.Net, thinking in controls, not html flow.

Consider following a course, or reading a beginner book... and first, forget what you did in php :)

Ubuntu: Using curl to download an image

For those who don't have nor want to install wget, curl -O (capital "o", not a zero) will do the same thing as wget. E.g. my old netbook doesn't have wget, and is a 2.68 MB install that I don't need.

curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Easiest way to change font and font size

You can also create a varible and then assign it for a text. It is cool because you can assign it two or more texts.

To assign a variable do that

public partial class Sayfa1 : Form

   Font Normal = new Font("Segoe UI", 9, FontStyle.Bold);

    public Sayfa1()

This varible is not assigned to any text yet.To do it write the name of the text(Look proporties -> (Name)) then write ".Font" then call the name of your font variable.

lupusToolStripMenuItem.Font = Normal;

Now you have a text assigned to a Normal font. I hope I could be helpful.

How do I paste multi-line bash codes into terminal and run it all at once?

Another possibility:

bash << EOF
echo "Hello"
echo "World"
EOF

Round up value to nearest whole number in SQL UPDATE

For MS SQL CEILING(your number) will round it up. FLOOR(your number) will round it down

Escaping a forward slash in a regular expression

If you are using C#, you do not need to escape it.

Is it possible to select the last n items with nth-child?

This will select the last two iems of a list:

_x000D_
_x000D_
li:nth-last-child(-n+2) {color:red;}
_x000D_
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>
_x000D_
_x000D_
_x000D_

Testing for empty or nil-value string

variable = id if variable.to_s.empty?

Creating an empty bitmap and drawing though canvas in Android

This is probably simpler than you're thinking:

int w = WIDTH_PX, h = HEIGHT_PX;

Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);

// ready to draw on that bitmap through that canvas

Here's a series of tutorials I've found on the topic: Drawing with Canvas Series

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

How to set a text box for inputing password in winforms?

I know the perfect answer:

  1. double click on The password TextBox.
  2. write your textbox name like textbox2.
  3. write PasswordChar = '*';.
  4. I prefer going to windows character map and find a perfect hide like ?.

    example:TextBox2.PasswordChar = '?';
    

How to convert image into byte array and byte array to base64 String in android?

Try this simple solution to convert file to base64 string

String base64String = imageFileToByte(file);

public String imageFileToByte(File file){

    Bitmap bm = BitmapFactory.decodeFile(file.getAbsolutePath());
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
    byte[] b = baos.toByteArray();
    return Base64.encodeToString(b, Base64.DEFAULT);
}

How do multiple clients connect simultaneously to one port, say 80, on a server?

Important:

I'm sorry to say that the response from "Borealid" is imprecise and somewhat incorrect - firstly there is no relation to statefulness or statelessness to answer this question, and most importantly the definition of the tuple for a socket is incorrect.

First remember below two rules:

  1. Primary key of a socket: A socket is identified by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT, PROTOCOL} not by {SRC-IP, SRC-PORT, DEST-IP, DEST-PORT} - Protocol is an important part of a socket's definition.

  2. OS Process & Socket mapping: A process can be associated with (can open/can listen to) multiple sockets which might be obvious to many readers.

Example 1: Two clients connecting to same server port means: socket1 {SRC-A, 100, DEST-X,80, TCP} and socket2{SRC-B, 100, DEST-X,80, TCP}. This means host A connects to server X's port 80 and another host B also connects to same server X to the same port 80. Now, how the server handles these two sockets depends on if the server is single threaded or multiple threaded (I'll explain this later). What is important is that one server can listen to multiple sockets simultaneously.

To answer the original question of the post:

Irrespective of stateful or stateless protocols, two clients can connect to same server port because for each client we can assign a different socket (as client IP will definitely differ). Same client can also have two sockets connecting to same server port - since such sockets differ by SRC-PORT. With all fairness, "Borealid" essentially mentioned the same correct answer but the reference to state-less/full was kind of unnecessary/confusing.

To answer the second part of the question on how a server knows which socket to answer. First understand that for a single server process that is listening to same port, there could be more than one sockets (may be from same client or from different clients). Now as long as a server knows which request is associated with which socket, it can always respond to appropriate client using the same socket. Thus a server never needs to open another port in its own node than the original one on which client initially tried to connect. If any server allocates different server-ports after a socket is bound, then in my opinion the server is wasting its resource and it must be needing the client to connect again to the new port assigned.

A bit more for completeness:

Example 2: It's a very interesting question: "can two different processes on a server listen to the same port". If you do not consider protocol as one of parameter defining socket then the answer is no. This is so because we can say that in such case, a single client trying to connect to a server-port will not have any mechanism to mention which of the two listening processes the client intends to connect to. This is the same theme asserted by rule (2). However this is WRONG answer because 'protocol' is also a part of the socket definition. Thus two processes in same node can listen to same port only if they are using different protocol. For example two unrelated clients (say one is using TCP and another is using UDP) can connect and communicate to the same server node and to the same port but they must be served by two different server-processes.

Server Types - single & multiple:

When a server's processes listening to a port that means multiple sockets can simultaneously connect and communicate with the same server-process. If a server uses only a single child-process to serve all the sockets then the server is called single-process/threaded and if the server uses many sub-processes to serve each socket by one sub-process then the server is called multi-process/threaded server. Note that irrespective of the server's type a server can/should always uses the same initial socket to respond back (no need to allocate another server-port).

Suggested Books and rest of the two volumes if you can.

A Note on Parent/Child Process (in response to query/comment of 'Ioan Alexandru Cucu')

Wherever I mentioned any concept in relation to two processes say A and B, consider that they are not related by parent child relationship. OS's (especially UNIX) by design allow a child process to inherit all File-descriptors (FD) from parents. Thus all the sockets (in UNIX like OS are also part of FD) that a process A listening to, can be listened by many more processes A1, A2, .. as long as they are related by parent-child relation to A. But an independent process B (i.e. having no parent-child relation to A) cannot listen to same socket. In addition, also note that this rule of disallowing two independent processes to listen to same socket lies on an OS (or its network libraries) and by far it's obeyed by most OS's. However, one can create own OS which can very well violate this restrictions.

There is already an object named in the database

Delete rows from dbo_MigrationHistory table or delete the table and run

update-database -verbose

It will run all the migrations in your project one by one

How can I get my webapp's base URL in ASP.NET MVC?

Assuming you have a Request object available, you can use:

string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));

If it's not available, you can get to it via the context:

var request = HttpContext.Current.Request

Adding a JAR to an Eclipse Java library

In Eclipse Ganymede (3.4.0):

  1. Select the library and click "Edit" (left side of the window)
  2. Click "User Libraries"
  3. Select the library again and click "Add JARs"

Best way to change font colour halfway through paragraph?

wrap a <span> around those words and style with the appropriate color

now is the time for <span style='color:orange'>all good men</span> to come to the

set date in input type date

to me the shortest way to solve this problem is to use moment.js and solve this problem in just 2 lines.

var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);

how to apply click event listener to image in android

Try this example.

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

<GridView
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="100dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/grid"
    android:background="#fff7ff"
    />

    </LinearLayout>

grid_single.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5dp" >

    <ImageView
        android:id="@+id/grid_image"
        android:layout_width="60dp"
        android:layout_height="60dp"

        >
    </ImageView>

    <TextView
        android:id="@+id/grid_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp"
        android:textSize="9sp"
        android:textColor="#3a0fff">
    </TextView>

</LinearLayout>

CustomGrid.java:

package com.example.lalit.gridtest;

import android.content.Context;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.BaseAdapter;
        import android.widget.ImageView;
        import android.widget.TextView;

public class CustomGrid extends BaseAdapter {
    private Context mContext;
    private final String[] web;
    private final int[] Imageid;

    public CustomGrid(Context c, String[] web, int[] Imageid) {
        mContext = c;
        this.Imageid = Imageid;
        this.web = web;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return web.length;
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        View grid;
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {

            grid = new View(mContext);
            grid = inflater.inflate(R.layout.grid_single, null);
            TextView textView = (TextView) grid.findViewById(R.id.grid_text);
            ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
            textView.setText(web[position]);
            imageView.setImageResource(Imageid[position]);
        } else {
            grid = (View) convertView;
        }

        return grid;
    }
}

MainActivity.java:

package com.example.lalit.gridtest;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
    GridView grid;
    String[] web = {
            "Mom",
            "Mahendra",
            "Narayan",
            "Bhai",
            "Deepak",
            "Sanjay",
            "Navdeep",
            "Lovesh",


    };
    int[] imageId = {
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher,
            R.drawable.ic_launcher

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final CustomGrid adapter = new CustomGrid(MainActivity.this, web, imageId);
        grid = (GridView) findViewById(R.id.grid);
        grid.setAdapter(adapter);
        grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id){

                if (web[position].toString().equals("Mom")) {
                    try {
                        String uri ="te:"+ "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }
                }


                    if (web[position].toString().equals("Mahendra")) {
                        try {
                            String uri = "tel:" + "**********";

                            Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                            startActivity(callIntent);
                        } catch (Exception e) {
                            Toast.makeText(getApplicationContext(), "Your call has failed...",
                                    Toast.LENGTH_LONG).show();
                            e.printStackTrace();

                        }
                    }


                      if(web[position].toString().equals("Narayan")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


             }
                if(web[position].toString().equals("Bhai")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                if(web[position].toString().equals("Deepak")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }


                if(web[position].toString().equals("Sanjay")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Navdeep")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }
                if(web[position].toString().equals("Lovesh")){

                    try {
                        String uri = "tel:" + "**********";

                        Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
                        startActivity(callIntent);
                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Your call has failed...",
                                Toast.LENGTH_LONG).show();
                        e.printStackTrace();

                    }


                }

                }



        });

    }

    }

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lalit.gridtest" >
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

you can do update the User path as inside _JAVA_OPTIONS : -Xmx512M Path : C:\Program Files (x86)\Java\jdk1.8.0_231\bin;C:\Program Files(x86)\Java\jdk1.8.0_231\jre\bin for now it is working / /

EnterKey to press button in VBA Userform

Use the TextBox's Exit event handler:

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    Logincode_Click  
End Sub

Simple proof that GUID is not unique

But do you have to be sure you have a duplicate, or do you only care if there can be a duplicate. To be sure that you have two people with the same birthday, you need 366 people (not counting leap year). For there to be a greater than 50% chance of having two people with the same birthday you only need 23 people. That's the birthday problem.

If you have 32 bits, you only need 77,163 values to have a greater than 50% chance of a duplicate. Try it out:

Random baseRandom = new Random(0);

int DuplicateIntegerTest(int interations)
{
    Random r = new Random(baseRandom.Next());
    int[] ints = new int[interations];
    for (int i = 0; i < ints.Length; i++)
    {
        ints[i] = r.Next();
    }
    Array.Sort(ints);
    for (int i = 1; i < ints.Length; i++)
    {
        if (ints[i] == ints[i - 1])
            return 1;
    }
    return 0;
}

void DoTest()
{
    baseRandom = new Random(0);
    int count = 0;
    int duplicates = 0;
    for (int i = 0; i < 1000; i++)
    {
        count++;
        duplicates += DuplicateIntegerTest(77163);
    }
    Console.WriteLine("{0} iterations had {1} with duplicates", count, duplicates);
}

1000 iterations had 737 with duplicates

Now 128 bits is a lot, so you are still talking a large number of items still giving you a low chance of collision. You would need the following number of records for the given odds using an approximation:

  • 0.8 billion billion for a 1/1000 chance of a collision occurring
  • 21.7 billion billion for 50% chance of a collision occurring
  • 39.6 billion billion for 90% chance of a collision occurring

There are about 1E14 emails sent per year so it would be about 400,000 years at this level before you would have a 90% chance of having two with the same GUID, but that is a lot different than saying you need to run a computer 83 billion times the age of the universe or that the sun would go cold before finding a duplicate.

Creating a procedure in mySql with parameters

I figured it out now. Here's the correct answer

CREATE PROCEDURE checkUser 
(
   brugernavn1 varchar(64),
   password varchar(64)
) 
BEGIN 
   SELECT COUNT(*) FROM bruger 
   WHERE bruger.brugernavn=brugernavn1 
   AND bruger.pass=password; 
END; 

@ points to a global var in mysql. The above syntax is correct.

Remove the last three characters from a string

myString = myString.Remove(myString.Length - 3, 3);

Wait until an HTML5 video loads

In response to the final part of your question, which is still unanswered... When you write $('#video').duration, you're asking for the duration property of the jQuery collection object, which doesn't exist. The native DOM video element does have the duration. You can get that in a few ways.

Here's one:

// get the native element directly
document.getElementById('video').duration

Here's another:

// get it out of the jQuery object
$('#video').get(0).duration

And another:

// use the event object
v.bind('loadeddata', function(e) {
  console.log(e.target.duration);
});

How can I add new dimensions to a Numpy array?

Alternatively to

image = image[..., np.newaxis]

in @dbliss' answer, you can also use numpy.expand_dims like

image = np.expand_dims(image, <your desired dimension>)

For example (taken from the link above):

x = np.array([1, 2])

print(x.shape)  # prints (2,)

Then

y = np.expand_dims(x, axis=0)

yields

array([[1, 2]])

and

y.shape

gives

(1, 2)

unary operator expected in shell script when comparing null value with string

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

How to break out of the IF statement

You can use a goto to drop past some code. In the example, if thing1 is true then the check for things2 is bypassed.

if (something) {
    do_stuff();
    if (thing1) { 
        do_thing1();
        goto SkipToEnd;
    }
    if (thing2) {
        do_thing2();
    }
SkipToEnd:
    do_thing3();
}

Checkbox angular material checked by default

If you are using Reactive form you can set it to default like this:

In the form model, set the value to false. So if it's checked its value will be true else false

let form = this.formBuilder.group({
    is_known: [false]
})

//In HTML

 <mat-checkbox matInput formControlName="is_known">Known</mat-checkbox>

How can I disable ARC for a single file in a project?

Just use the -fno-objc-arc flag in Build Phases>Compile Sources

Windows Scheduled task succeeds but returns result 0x1

Windows Task scheduler (Windows server 2008r2)

Same error for me (last run result: 0x1)

Tabs

  1. Action: remove quotes/double-quotes in

program/script

and

start in

even if there is spaces in the path name...

  1. General:

Run with highest privileges

and

configure for your OS...

Now it work!

last run result: The operation completed successfully

How to convert image to byte array

Code:

using System.IO;

byte[] img = File.ReadAllBytes(openFileDialog1.FileName);

How do I use StringUtils in Java?

StringUtils is a utility class from Apache commons-lang (many libraries have it but this is the most common library). You need to download the jar and add it to your applications classpath.

Getting the index of the returned max or min item using max()/min() on a list

list=[1.1412, 4.3453, 5.8709, 0.1314]
list.index(min(list))

Will give you first index of minimum.

Space between border and content? / Border distance from content?

Just wrap another div around it, which has the border and the padding you want.

How to get a cross-origin resource sharing (CORS) post request working

Took me some time to find the solution.

In case your server response correctly and the request is the problem, you should add withCredentials: true to the xhrFields in the request:

$.ajax({
    url: url,
    type: method,
    // This is the important part
    xhrFields: {
        withCredentials: true
    },
    // This is the important part
    data: data,
    success: function (response) {
        // handle the response
    },
    error: function (xhr, status) {
        // handle errors
    }
});

Note: jQuery >= 1.5.1 is required

Rotation of 3D vector?

I made a fairly complete library of 3D mathematics for Python{2,3}. It still does not use Cython, but relies heavily on the efficiency of numpy. You can find it here with pip:

python[3] -m pip install math3d

Or have a look at my gitweb http://git.automatics.dyndns.dk/?p=pymath3d.git and now also on github: https://github.com/mortlind/pymath3d .

Once installed, in python you may create the orientation object which can rotate vectors, or be part of transform objects. E.g. the following code snippet composes an orientation that represents a rotation of 1 rad around the axis [1,2,3], applies it to the vector [4,5,6], and prints the result:

import math3d as m3d
r = m3d.Orientation.new_axis_angle([1,2,3], 1)
v = m3d.Vector(4,5,6)
print(r * v)

The output would be

<Vector: (2.53727, 6.15234, 5.71935)>

This is more efficient, by a factor of approximately four, as far as I can time it, than the oneliner using scipy posted by B. M. above. However, it requires installation of my math3d package.

int to unsigned int conversion

You can convert an int to an unsigned int. The conversion is valid and well-defined.

Since the value is negative, UINT_MAX + 1 is added to it so that the value is a valid unsigned quantity. (Technically, 2N is added to it, where N is the number of bits used to represent the unsigned type.)

In this case, since int on your platform has a width of 32 bits, 62 is subtracted from 232, yielding 4,294,967,234.

How to destroy JWT Tokens on logout?

On Logout from the Client Side, the easiest way is to remove the token from the storage of browser.

But, What if you want to destroy the token on the Node server -

The problem with JWT package is that it doesn't provide any method or way to destroy the token.

So in order to destroy the token on the serverside you may use jwt-redis package instead of JWT

This library (jwt-redis) completely repeats the entire functionality of the library jsonwebtoken, with one important addition. Jwt-redis allows you to store the token label in redis to verify validity. The absence of a token label in redis makes the token not valid. To destroy the token in jwt-redis, there is a destroy method

it works in this way :

1) Install jwt-redis from npm

2) To Create -

var redis = require('redis');
var JWTR =  require('jwt-redis').default;
var redisClient = redis.createClient();
var jwtr = new JWTR(redisClient);

jwtr.sign(payload, secret)
    .then((token)=>{
            // your code
    })
    .catch((error)=>{
            // error handling
    });

3) To verify -

jwtr.verify(token, secret);

4) To Destroy -

jwtr.destroy(token)

Note : you can provide expiresIn during signin of token in the same as it is provided in JWT.

How do I set the icon for my application in visual studio 2008?

The important thing is that the icon you want to be displayed as the application icon ( in the title bar and in the task bar ) must be the FIRST icon in the resource script file

The file is in the res folder and is named (applicationName).rc

/////////////////////////////////////////////////////////////////////////////
//
// Icon
//

// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
(icon ID )          ICON                    "res\\filename.ico"

What is the difference between a "line feed" and a "carriage return"?

A line feed means moving one line forward. The code is \n.
A carriage return means moving the cursor to the beginning of the line. The code is \r.

Windows editors often still use the combination of both as \r\n in text files. Unix uses mostly only the \n.

The separation comes from typewriter times, when you turned the wheel to move the paper to change the line and moved the carriage to restart typing on the beginning of a line. This was two steps.

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

matplotlib does not show my drawings although I call pyplot.show()

For me the problem happens if I simply create an empty matplotlibrc file under ~/.matplotlib on macOS. Adding "backend: macosx" in it fixes the problem.

I think it is a bug: if backend is not specified in my matplotlibrc it should take the default value.

Is there a way to automatically build the package.json file for Node.js projects

Command line:

npm init

will create package.json file

To install , update and uninstall packages under dependencies into package.json file:

Command line :

npm install <pkg>@* --save 

will automatically add the latest version for the package under dependencies into package.json file

EX:

npm install node-markdown@* --save

Command line:

npm install <pkg> --save

also will automatically add the latest version for the package under dependencies into package.json file

if you need specific version for a package use this Command line:

npm install <pkg>@<version> --save

will automatically add specific version of package under dependencies into package.json file

EX:

npm install [email protected] --save

if you need specific range of version for a package use this Command line:

npm install <pkg>@<version range>

will automatically add the latest version for the package between range of version under dependencies into package.json file

EX:

npm install koa-views@">1.0.0 <1.2.0" --save

For more details about how to write version for package npm Doc

Command line:

npm update --save

will update packages into package.json file and will automatically add updated version for all packages under dependencies into package.json file

Command line:

npm uninstall <pkg> --save

will automatically remove package from dependencies into package.json file and remove package from node_module folder

Get first element of Series without knowing the index

Use iloc to access by position (rather than label):

In [11]: df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['A', 'B'])

In [12]: df
Out[12]: 
   A  B
a  1  2
b  3  4

In [13]: df.iloc[0]  # first row in a DataFrame
Out[13]: 
A    1
B    2
Name: a, dtype: int64

In [14]: df['A'].iloc[0]  # first item in a Series (Column)
Out[14]: 1

Jenkins could not run git

I had similar problem, the solution for Windows looks the same (my Jenkins is installed on a Windows machine):

Global settings:

Go to Manage jenkins -> Configure System -> Git installations add there the git exe path (for example: C:\Program Files\Git\bin\git.exe), or you can use environment variable.

For Jenkins version 2.121.3, Go to Manage jenkins -> Global tool configuration -> Git installations -> Path to Git executable: C:\Program Files\Git\bin\git.exe

Jenkins job side:

Go to Source code Management -> select git, add your repository, choose connection to repository (http/ssh) and add credentials and it should work.

jQuery Set Select Index

select 3rd option

$('#selectBox').val($('#selectBox option').eq(2).val());

Example on jsfiddle

Java Reflection: How to get the name of a variable?

update @Marcel Jackwerth's answer for general.

and only working with class attribute, not working with method variable.

    /**
     * get variable name as string
     * only work with class attributes
     * not work with method variable
     *
     * @param headClass variable name space
     * @param vars      object variable
     * @throws IllegalAccessException
     */
    public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
        List<Object> fooList = Arrays.asList(vars);
        for (Field field : headClass.getClass().getFields()) {
            if (fooList.contains(field.get(headClass))) {
                System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
            }
        }
    }

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

In your comment on @Kenneth's answer you're saying that ReadAsStringAsync() is returning empty string.

That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.

What you can do is this:

public static string GetRequestBody()
{
    var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream);
    bodyStream.BaseStream.Seek(0, SeekOrigin.Begin);
    var bodyText = bodyStream.ReadToEnd();
    return bodyText;
}

Converting HTML to plain text in PHP for e-mail

If you want to convert the HTML special characters and not just remove them as well as strip things down and prepare for plain text this was the solution that worked for me...

function htmlToPlainText($str){
    $str = str_replace('&nbsp;', ' ', $str);
    $str = html_entity_decode($str, ENT_QUOTES | ENT_COMPAT , 'UTF-8');
    $str = html_entity_decode($str, ENT_HTML5, 'UTF-8');
    $str = html_entity_decode($str);
    $str = htmlspecialchars_decode($str);
    $str = strip_tags($str);

    return $str;
}

$string = '<p>this is (&nbsp;) a test</p>
<div>Yes this is! &amp; does it get "processed"? </div>'

htmlToPlainText($string);
// "this is ( ) a test. Yes this is! & does it get processed?"`

html_entity_decode w/ ENT_QUOTES | ENT_XML1 converts things like &#39; htmlspecialchars_decode converts things like &amp; html_entity_decode converts things like '&lt; and strip_tags removes any HTML tags left over.

Load a WPF BitmapImage from a System.Drawing.Bitmap

I came to this question because I was trying to do the same, but in my case the Bitmap is from a resource/file. I found the best solution is as described in the following link:

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx

// Create the image element.
Image simpleImage = new Image();    
simpleImage.Width = 200;
simpleImage.Margin = new Thickness(5);

// Create source.
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
bi.UriSource = new Uri(@"/sampleImages/cherries_larger.jpg",UriKind.RelativeOrAbsolute);
bi.EndInit();
// Set the image source.
simpleImage.Source = bi;

How to read pdf file and write it to outputStream

import java.io.*;


public class FileRead {


    public static void main(String[] args) throws IOException {


        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c = is.read(buf, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);
            oos.flush();
        }

        oos.close();
        System.out.println("stop");
        is.close();

    }

}

The easiest way so far. Hope this helps.

Take a screenshot via a Python script on Linux

bit late but nevermind easy one is

import autopy
import time
time.sleep(2)
b = autopy.bitmap.capture_screen()
b.save("C:/Users/mak/Desktop/m.png")

Refresh/reload the content in Div using jquery/ajax

You need to add the source from where you're loading the data.

For Example:

$("#step1Content").load("yourpage.html");

Hope It will help you.

how to convert JSONArray to List of Object using camel-jackson

private static String readAll(Reader rd) throws IOException {
    StringBuilder sb = new StringBuilder();
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

 String jsonText = readAll(inputofyourjsonstream);
 JSONObject json = new JSONObject(jsonText);
 JSONArray arr = json.getJSONArray("Compemployes");

Your arr would looks like: [ { "id":1001, "name":"jhon" }, { "id":1002, "name":"jhon" } ] You can use:

arr.getJSONObject(index)

to get the objects inside of the array.

Java Class that implements Map and keeps insertion order?

If an immutable map fits your needs then there is a library by google called guava (see also guava questions)

Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.

ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Adding a dictionary to another

Create an Extension Method most likely you will want to use this more than once and this prevents duplicate code.

Implementation:

 public static void AddRange<T, S>(this Dictionary<T, S> source, Dictionary<T, S> collection)
 {
        if (collection == null)
        {
            throw new ArgumentNullException("Collection is null");
        }

        foreach (var item in collection)
        {
            if(!source.ContainsKey(item.Key)){ 
               source.Add(item.Key, item.Value);
            }
            else
            {
               // handle duplicate key issue here
            }  
        } 
 }

Usage:

Dictionary<string,string> animals = new Dictionary<string,string>();
Dictionary<string,string> newanimals = new Dictionary<string,string>();

animals.AddRange(newanimals);

Rails: How can I rename a database column in a Ruby on Rails migration?

Just generate migration using command

rails g migration rename_hased_password

After that edit the migration add following line in change method

rename_column :table, :hased_password, :hashed_password

This should do the trick.

Converting File to MultiPartFile

Solution without Mocking class, Java9+ and Spring only.

FileItem fileItem = new DiskFileItemFactory().createItem("file",
    Files.probeContentType(file.toPath()), false, file.getName());

try (InputStream in = new FileInputStream(file); OutputStream out = fileItem.getOutputStream()) {
    in.transferTo(out);
} catch (Exception e) {
    throw new IllegalArgumentException("Invalid file: " + e, e);
}

CommonsMultipartFile multipartFile = new CommonsMultipartFile(fileItem);

Text that shows an underline on hover

You just need to specify text-decoration: underline; with pseudo-class :hover.

HTML

<span class="underline-on-hover">Hello world</span>

CSS

.underline-on-hover:hover {
    text-decoration: underline;
}

I have whipped up a working Code Pen Demo.

POST: sending a post request in a url itself

You can use postman.

Where select Post as method. and In Request Body send JSON Object.

Select 50 items from list at random to write to file

Say your list has 100 elements and you want to pick 50 of them in a random way. Here are the steps to follow:

  1. Import the libraries
  2. Create the seed for random number generator, I have put it at 2
  3. Prepare a list of numbers from which to pick up in a random way
  4. Make the random choices from the numbers list

Code:

from random import seed
from random import choice

seed(2)
numbers = [i for i in range(100)]

print(numbers)

for _ in range(50):
    selection = choice(numbers)
    print(selection)

Adding local .aar files to Gradle build using "flatDirs" is not working

I got this working on Android Studio 2.1. I have a module called "Native_Ads" which is shared across multiple projects.

First, I created a directory in my Native_ads module with the name 'aars' and then put the aar file in there.

Directory structure:

libs/
aars/    <-- newly created
src/
build.gradle
etc

Then, the other changes:

Top level Gradle file:

allprojects {
    repositories {
        jcenter()
        // For module with aar file in it
        flatDir {
            dirs project(':Native_Ads').file('aars')
        }
    }
}

App module's build.gradle file: - no changes

Settings.gradle file (to include the module):

include ':app'
include 'Native_Ads'
project(':Native_Ads').projectDir = new File(rootProject.projectDir, '../path/to/Native_Ads')

Gradle file for the Native_Ads module:

repositories {
    jcenter()
    flatDir {
        dirs 'aars'
    }
}
dependencies {
    compile(name:'aar_file_name_without_aar_extension', ext:'aar')
}

That's it. Clean and build.

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],
       .....

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

PUT compile 'de.hdodenhof:circleimageview:2.0.0' IN Gradle Dependencies and put this code in nav_header_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/lib/org.mainsoft.navigationdrawer"

    android:gravity="bottom"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:layout_width="match_parent"
    android:layout_height="160dp"
    android:background="@drawable/background_material_red"
    android:orientation="vertical">

<de.hdodenhof.circleimageview.CircleImageView

    android:id="@+id/profile_image"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:src="@drawable/profile"
    app:border_color="#FF000000"
    android:layout_marginLeft="24dp"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginStart="24dp" />

</LinearLayout>

Div Size Automatically size of content

If you are coming here, there is high chance width: min-content or width: max-content can fix your problem. This can force an element to use the smallest or largest space the browser could choose…

This is the modern solution. Here is a small tutorial for that.

There is also fit-content, which often works like min-content, but is more flexible. (But also has worse browser support.)

This is a quite new feature and some browsers do not support it yet, but browser support is growing. See the current browser status here.

Detect If Browser Tab Has Focus

I would do it this way (Reference http://www.w3.org/TR/page-visibility/):

    window.onload = function() {

        // check the visiblility of the page
        var hidden, visibilityState, visibilityChange;

        if (typeof document.hidden !== "undefined") {
            hidden = "hidden", visibilityChange = "visibilitychange", visibilityState = "visibilityState";
        }
        else if (typeof document.mozHidden !== "undefined") {
            hidden = "mozHidden", visibilityChange = "mozvisibilitychange", visibilityState = "mozVisibilityState";
        }
        else if (typeof document.msHidden !== "undefined") {
            hidden = "msHidden", visibilityChange = "msvisibilitychange", visibilityState = "msVisibilityState";
        }
        else if (typeof document.webkitHidden !== "undefined") {
            hidden = "webkitHidden", visibilityChange = "webkitvisibilitychange", visibilityState = "webkitVisibilityState";
        }


        if (typeof document.addEventListener === "undefined" || typeof hidden === "undefined") {
            // not supported
        }
        else {
            document.addEventListener(visibilityChange, function() {
                console.log("hidden: " + document[hidden]);
                console.log(document[visibilityState]);

                switch (document[visibilityState]) {
                case "visible":
                    // visible
                    break;
                case "hidden":
                    // hidden
                    break;
                }
            }, false);
        }

        if (document[visibilityState] === "visible") {
            // visible
        }

    };  

Notification not showing in Oreo

This is bug in firebase api version 11.8.0, So if you reduce API version you will not face this issue.

Unable to run Java code with Intellij IDEA

I had the similar issue and solved it by doing the below step.

  1. Go to "Run" menu and "Edit configuration"
  2. Click on add(+) icon and select Application from the list.
  3. In configuration name your Main class: name of your main class.
  4. Working Directory : It should point till the src folder of your project. C:\Users\name\Work\ProjectName\src

    This is where I had issue and after correcting this, I could see the run option for that class.

How can I show a hidden div when a select option is selected?

Try handling the change event of the select and using this.value to determine whether it's 'Yes' or not.

jsFiddle

JS

document.getElementById('test').addEventListener('change', function () {
    var style = this.value == 1 ? 'block' : 'none';
    document.getElementById('hidden_div').style.display = style;
});

HTML

<select id="test" name="form_select">
   <option value="0">No</option>
   <option value ="1">Yes</option>
</select>

<div id="hidden_div" style="display: none;">Hello hidden content</div>

Deleting a pointer in C++

Pointers are similar to normal variables in that you don't need to delete them. They are removed from memory at the end of a functions execution and/or the end of the program.

You can however use pointers to allocate a 'block' of memory, for example like this:

int *some_integers = new int[20000]

This will allocate memory space for 20000 integers. Useful, because the Stack has a limited size and you might want to mess about with a big load of 'ints' without a stack overflow error.

Whenever you call new, you should then 'delete' at the end of your program, because otherwise you will get a memory leak, and some allocated memory space will never be returned for other programs to use. To do this:

delete [] some_integers;

Hope that helps.

How to create a file with a given size in Linux?

you could do:

[dsm@localhost:~]$ perl -e 'print "\0" x 100' > filename.ext

Where you replace 100 with the number of bytes you want written.

Correct way to write line to file?

The python docs recommend this way:

with open('file_to_write', 'w') as f:
    f.write('file contents\n')

So this is the way I usually do it :)

Statement from docs.python.org:

It is good practice to use the 'with' keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks.

Is an HTTPS query string secure?

Yes. The entire text of an HTTPS session is secured by SSL. That includes the query and the headers. In that respect, a POST and a GET would be exactly the same.

As to the security of your method, there's no real way to say without proper inspection.

How to install pandas from pip on windows cmd?

Please Ensure you are using a virtualEnv this is how :

virtualenv -p python3 envname

source env/bin/activate
pip install pandas

on windows you have to add scripts exe in the CLASSPATH in order to use pip command

C:\Python34\Scripts\pip3.exe

i suggest you to use MINGW he can gives you a better environment to work with python

Error in plot.new() : figure margins too large in R

RStudio Plots canvas is limiting the plot width and heights. However if you make your plot from Rmarkdown code chunk, it works without canvas field limitation because plotting area set according to the paper size.

For instance:

    ```{r}
#inside of code chunk in Rmarkdown
        grid <- par(mfrow=c(4, 5))
        plot(faithful, main="Faithful eruptions")
        plot(large.islands, main="Islands", ylab="Area")
        ...
        par(grid)
    ```

jQuery: how to trigger anchor link's click event

Even though this post is caput, I think it's an excellent demonstration of some walls that one can run into with jQuery, i.e. thinking click() actually clicks on an element, rather than just sending a click event bubbling up through the DOM. Let's say you actually need to simulate a click event (i.e. for testing purposes, etc.) If that's the case, provided that you're using a modern browser you can just use HTMLElement.prototype.click (see here for method details as well as a link to the W3 spec). This should work on almost all browsers, especially if you're dealing with links, and you can fall back to window.open pretty easily if you need to:

var clickLink = function(linkEl) {
  if (HTMLElement.prototype.click) {
    // You'll want to create a new element so you don't alter the page element's
    // attributes, unless of course the target attr is already _blank
    // or you don't need to alter anything
    var linkElCopy = $.extend(true, Object.create(linkEl), linkEl);
    $(linkElCopy).attr('target', '_blank');
    linkElCopy.click();
  } else {
    // As Daniel Doezema had said
    window.open($(linkEl).attr('href'));
  }
};

Change the image source on rollover using jQuery

I've made something like the following code :)

It works only, when you have a second file named with _hover, for example, facebook.png and facebook_hover.png

$('#social').find('a').hover(function() {
    var target = $(this).find('img').attr('src');
    //console.log(target);
    var newTarg = target.replace('.png', '_hover.png');
    $(this).find('img').attr("src", newTarg);
}, function() {
    var target = $(this).find('img').attr('src');
    var newTarg = target.replace('_hover.png', '.png');
    $(this).find('img').attr("src", newTarg);
});

Difference between DOM parentNode and parentElement

parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.

As an example:

document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false

Since the <html> element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)

boundingRectWithSize for NSAttributedString returning wrong size

I have had the same problem with not getting an accurate size using these techniques and I've changed my approach to make it work.

I have a long attributed string which I've been trying to fit into a scroll view so that it shows properly without being truncated. What I did to make the text work reliably was to not set the height at all as a constraint and instead allowed the intrinsic size to take over. Now the text is displayed correctly without being truncated and I do not have to calculate the height.

I suppose if I did need to get the height reliably I would create a view which is hidden and these constraints and get the height of the frame once the constraints are applied.

How to downgrade tensorflow, multiple versions possible?

If you are using python3 on windows then you might do this as well

pip3 install tensorflow==1.4

you may select any version from "(from versions: 1.2.0rc2, 1.2.0, 1.2.1, 1.3.0rc0, 1.3.0rc1, 1.3.0rc2, 1.3.0, 1.4.0rc0, 1.4.0rc1, 1.4.0, 1.5.0rc0, 1.5.0rc1, 1.5.0, 1.5.1, 1.6.0rc0, 1.6.0rc1, 1.6.0, 1.7.0rc0, 1.7.0rc1, 1.7.0)"

I did this when I wanted to downgrade from 1.7 to 1.4

Making sure at least one checkbox is checked

I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them. Let's begin with giving the checkboxes a class so we can round them up very nicely. I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.

HTML

    <input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
    <input type="checkbox" class="checkbox" value=ck2 /> ck2<br />

JavaScript

function atLeastOneCheckboxIsChecked(){
    const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
    return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}

When called, the function will return false if no checkbox has been checked and true if one or both is.

It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true. the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.

What is the list of supported languages/locales on Android?

First we need to plan how the application will render differently in different locals. Here it shows example, where the text string and images have to go.

de-rDE German / Germany res/values-de/ res/drawable-de-rDE/ 
fr-rFR French / France res/values-fr/ res/drawable-fr-rFR/ 
fr-rCA French / Canada res/values-fr/ res/drawable-fr-rCA/ 
en-rCA English / Canada (res/values/) res/drawable-en-rCA/ 
ja-rJP Japanese / Japan res/values-ja/ res/drawable-ja-rJP/ 
en-rUS English / United States (res/values/) res/drawable-en-rUS/ 

For more info you can see the page Localization

adding .css file to ejs

You can use this

     var fs = require('fs');
     var myCss = {
         style : fs.readFileSync('./style.css','utf8');
     };

     app.get('/', function(req, res){
       res.render('index.ejs', {
       title: 'My Site',
       myCss: myCss
      });
     });

put this on template

   <%- myCss.style %>

just build style.css

  <style>
    body { 
     background-color: #D8D8D8;
     color: #444;
   }
  </style>

I try this for some custom css. It works for me

Python OpenCV2 (cv2) wrapper to get image size?

import cv2
img=cv2.imread('my_test.jpg')
img_info = img.shape
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])

Ouput :- enter image description here

My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg

Convert list to dictionary using linq and not worrying about duplicates

Starting from Carra's solution you can also write it as:

foreach(var person in personList.Where(el => !myDictionary.ContainsKey(el.FirstAndLastName)))
{
    myDictionary.Add(person.FirstAndLastName, person);
}

How can I lookup a Java enum from its String value?

You can define your Enum as following code :

public enum Verbosity 
{
   BRIEF, NORMAL, FULL, ACTION_NOT_VALID;
   private int value;

   public int getValue()
   {
     return this.value;
   } 

   public static final Verbosity getVerbosityByValue(int value)
   {
     for(Verbosity verbosity : Verbosity.values())
     {
        if(verbosity.getValue() == value)
            return verbosity ;
     }

     return ACTION_NOT_VALID;
   }

   @Override
   public String toString()
   {
      return ((Integer)this.getValue()).toString();
   }
};

See following link for more clarification

Does VBA contain a comment block syntax?

Although there isn't a syntax, you can still get close by using the built-in block comment buttons:

If you're not viewing the Edit toolbar already, right-click on the toolbar and enable the Edit toolbar:

enter image description here

Then, select a block of code and hit the "Comment Block" button; or if it's already commented out, use the "Uncomment Block" button:

enter image description here

Fast and easy!

SQLite Reset Primary Key Field

As an alternate option, if you have the Sqlite Database Browser and are more inclined to a GUI solution, you can edit the sqlite_sequence table where field name is the name of your table. Double click the cell for the field seq and change the value to 0 in the dialogue box that pops up.

Remove last specific character in a string c#

When you have spaces at the end. you can use beliow.

ProcessStr = ProcessStr.Replace(" ", "");
Emails     = ProcessStr.TrimEnd(';');

After installation of Gulp: “no command 'gulp' found”

I solved the issue removing gulp and installing gulp-cli again:

rm /usr/local/bin/gulp
npm install -g gulp-cli

Finding import static statements for Mockito constructs

The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.

One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.

Also, when using mocks, I try to avoid assertThat in favor other other assertions and verify, e.g.

assertEquals(1, 1);
verify(someMock).someMethod(eq(1));

instead of

assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));

If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.

Get Locale Short Date Format using javascript

I don't know of a way to do that (you can get the language and try to deduct the locale from that).

I tried to cook a little something to try and do that (only tested on Firefox with one locale). should work as long as the short date string includes the date as digits, so it might fail for, say, arabic. It might have other bugs too, i don't know all the different locales peculiarities, this is just a concept...

function getShortDateFormat() {
    var d = new Date(1992, 0, 7);
    var s = d.toLocaleDateString();

    function formatReplacer(str) {
        var num = parseInt(str);
        switch (num % 100) {
            case 92:
                return str.replace(/.{1}/g, "Y");
            case 1:
                return str.length == 1 ? "mM" : "MM"
            case 7:
                return str.length == 1 ? "dD" : "DD"
        }
    }

    shortDateFormat = s.replace(/\d+/g, formatReplacer);
    return shortDateFormat;
}

getShortDateFormat();

The outputted format will be:

  • Y: the number of digits to represent years
  • dD = short day (i.e. use only one digit when possible)
  • DD = long day format (i.e. two digits always)
  • mM/MM - same for months

So in my browser, the shortDateformat you get is "MM/DD/YYYY".

Debug assertion failed. C++ vector subscript out of range

v has 10 element, the index starts from 0 to 9.

for(int j=10;j>0;--j)
{
    cout<<v[j];   // v[10] out of range
}

you should update for loop to

for(int j=9; j>=0; --j)
//      ^^^^^^^^^^
{
    cout<<v[j];   // out of range
}

Or use reverse iterator to print element in reverse order

for (auto ri = v.rbegin(); ri != v.rend(); ++ri)
{
  std::cout << *ri << std::endl;
}

Press TAB and then ENTER key in Selenium WebDriver

WebElement webElement = driver.findElement(By.xpath(""));

//Enter the xpath or ID.

     webElement.sendKeys("");

//Input the string to pass.

     webElement.sendKeys(Keys.TAB);

//This will enter the string which you want to pass and will press "Tab" button .

Namespace for [DataContract]

[DataContract] and [DataMember] attribute are found in System.ServiceModel namespace which is in System.ServiceModel.dll .

System.ServiceModel uses the System and System.Runtime.Serialization namespaces to serialize the datamembers.

Global variables in Java

Nothing should be global, except for constants.

public class MyMainClass {
    public final static boolean DEBUGMODE=true;
}

Put this within your main class. In other .java files, use it through:

if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");

Make sure when you move your code off the cutting room floor and into release you remove or comment out this functionality.

If you have a workhorse method, like a randomizer, I suggest creating a "Toolbox" package! All coders should have one, then whenever you want to use it in a .java, just import it!

How do I download a binary file over HTTP?

Expanding on Dejw's answer (edit2):

File.open(filename,'w'){ |f|
  uri = URI.parse(url)
  Net::HTTP.start(uri.host,uri.port){ |http| 
    http.request_get(uri.path){ |res| 
      res.read_body{ |seg|
        f << seg
#hack -- adjust to suit:
        sleep 0.005 
      }
    }
  }
}

where filename and url are strings.

The sleep command is a hack that can dramatically reduce CPU usage when the network is the limiting factor. Net::HTTP doesn't wait for the buffer (16kB in v1.9.2) to fill before yielding, so the CPU busies itself moving small chunks around. Sleeping for a moment gives the buffer a chance to fill between writes, and CPU usage is comparable to a curl solution, 4-5x difference in my application. A more robust solution might examine progress of f.pos and adjust the timeout to target, say, 95% of the buffer size -- in fact that's how I got the 0.005 number in my example.

Sorry, but I don't know a more elegant way of having Ruby wait for the buffer to fill.

Edit:

This is a version that automatically adjusts itself to keep the buffer just at or below capacity. It's an inelegant solution, but it seems to be just as fast, and to use as little CPU time, as it's calling out to curl.

It works in three stages. A brief learning period with a deliberately long sleep time establishes the size of a full buffer. The drop period reduces the sleep time quickly with each iteration, by multiplying it by a larger factor, until it finds an under-filled buffer. Then, during the normal period, it adjusts up and down by a smaller factor.

My Ruby's a little rusty, so I'm sure this can be improved upon. First of all, there's no error handling. Also, maybe it could be separated into an object, away from the downloading itself, so that you'd just call autosleep.sleep(f.pos) in your loop? Even better, Net::HTTP could be changed to wait for a full buffer before yielding :-)

def http_to_file(filename,url,opt={})
  opt = {
    :init_pause => 0.1,    #start by waiting this long each time
                           # it's deliberately long so we can see 
                           # what a full buffer looks like
    :learn_period => 0.3,  #keep the initial pause for at least this many seconds
    :drop => 1.5,          #fast reducing factor to find roughly optimized pause time
    :adjust => 1.05        #during the normal period, adjust up or down by this factor
  }.merge(opt)
  pause = opt[:init_pause]
  learn = 1 + (opt[:learn_period]/pause).to_i
  drop_period = true
  delta = 0
  max_delta = 0
  last_pos = 0
  File.open(filename,'w'){ |f|
    uri = URI.parse(url)
    Net::HTTP.start(uri.host,uri.port){ |http|
      http.request_get(uri.path){ |res|
        res.read_body{ |seg|
          f << seg
          delta = f.pos - last_pos
          last_pos += delta
          if delta > max_delta then max_delta = delta end
          if learn <= 0 then
            learn -= 1
          elsif delta == max_delta then
            if drop_period then
              pause /= opt[:drop_factor]
            else
              pause /= opt[:adjust]
            end
          elsif delta < max_delta then
            drop_period = false
            pause *= opt[:adjust]
          end
          sleep(pause)
        }
      }
    }
  }
end

SVN icon overlays not showing properly

This is not a problem, like Avada Kedavra said, actually, this is documented here, in the section "Icon Overlay Settings", and I also show bellow. You can read that, and choose the one you like most.

Since it takes quite a while to fetch the status of a working copy, TortoiseSVN uses a cache to store the status so the explorer doesn't get hogged too much when showing the overlays. You can choose which type of cache TortoiseSVN should use according to your system and working copy size here:

Default

Caches all status information in a separate process (TSVNCache.exe). That process watches all drives for changes and fetches the status again if files inside a working copy get modified. The process runs with the least possible priority so other programs don't get hogged because of it. That also means that the status information is not real time but it can take a few seconds for the overlays to change.

Advantage: the overlays show the status recursively, i.e. if a file deep inside a working copy is modified, all folders up to the working copy root will also show the modified overlay. And since the process can send notifications to the shell, the overlays on the left tree view usually change too.

Disadvantage: the process runs constantly, even if you're not working on your projects. It also uses around 10-50 MB of RAM depending on number and size of your working copies.

Shell

Caching is done directly inside the shell extension dll, but only for the currently visible folder. Each time you navigate to another folder, the status information is fetched again.

Advantage: needs only very little memory (around 1 MB of RAM) and can show the status in real time.

Disadvantage: Since only one folder is cached, the overlays don't show the status recursively. For big working copies, it can take more time to show a folder in explorer than with the default cache. Also the mime-type column is not available.

None

With this setting, the TortoiseSVN does not fetch the status at all in Explorer. Because of that, files don't get an overlay and folders only get a 'normal' overlay if they're versioned. No other overlays are shown, and no extra columns are available either.

Advantage: uses absolutely no additional memory and does not slow down the Explorer at all while browsing.

Disadvantage: Status information of files and folders is not shown in Explorer. To see if your working copies are modified, you have to use the “Check for modifications” dialog.

XML parsing of a variable string in JavaScript

<script language="JavaScript">
function importXML()
{
    if (document.implementation && document.implementation.createDocument)
    {
            xmlDoc = document.implementation.createDocument("", "", null);
            xmlDoc.onload = createTable;
    }
    else if (window.ActiveXObject)
    {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.onreadystatechange = function () {
                    if (xmlDoc.readyState == 4) createTable()
            };
    }
    else
    {
            alert('Your browser can\'t handle this script');
            return;
    }
    xmlDoc.load("emperors.xml");
}

function createTable()
{
    var theData="";
    var x = xmlDoc.getElementsByTagName('emperor');
    var newEl = document.createElement('TABLE');
    newEl.setAttribute('cellPadding',3);
    newEl.setAttribute('cellSpacing',0);
    newEl.setAttribute('border',1);
    var tmp = document.createElement('TBODY');
    newEl.appendChild(tmp);
    var row = document.createElement('TR');
    for (j=0;j<x[0].childNodes.length;j++)
    {
            if (x[0].childNodes[j].nodeType != 1) continue;
            var container = document.createElement('TH');
            theData = document.createTextNode(x[0].childNodes[j].nodeName);
            container.appendChild(theData);
            row.appendChild(container);
    }
    tmp.appendChild(row);
    for (i=0;i<x.length;i++)
    {
            var row = document.createElement('TR');
            for (j=0;j<x[i].childNodes.length;j++)
            {
                    if (x[i].childNodes[j].nodeType != 1) continue;
                    var container = document.createElement('TD');
                    var theData = document.createTextNode(x[i].childNodes[j].firstChild.nodeValue);
                    container.appendChild(theData);
                    row.appendChild(container);
            }
            tmp.appendChild(row);
    }
    document.getElementById('writeroot').appendChild(newEl);
}
</script>
</HEAD>

<BODY onLoad="javascript:importXML();">
<p id=writeroot> </p>
</BODY>

For more info refer this http://www.easycodingclub.com/xml-parser-in-javascript/javascript-tutorials/

Difference between git stash pop and git stash apply

Assuming there will be no errors thrown, and you want to work on the top stash item in the list of available stashes:

git stash pop = git stash apply + git stash drop

Can I use if (pointer) instead of if (pointer != NULL)?

Yes, you can. In fact, I prefer to use if(pointer) because it's simpler to read and write once you get used to it.

Also note that C++11 introduced nullptr which is preferred over NULL.

Submit form using a button outside the <form> tag

A solution that works great for me, is still missing here. It requires having a visually hidden <submit> or <input type="submit"> element whithin the <form>, and an associated <label> element outside of it. It would look like this:

<form method="get" action="something.php">
     <input type="text" name="name" />
     <input type="submit" id="submit-form" class="hidden" />
</form>

<label for="submit-form" tabindex="0">Submit</label>

Now this link enables you to 'click' the form <submit> element by clicking the <label> element.

Get root password for Google Cloud Engine VM

I had the same problem. Even after updating the password using sudo passwd it was not working. I had to give "multiple" roles for my user through IAM & Admin Refer Screen Shot on IAM & Admin screen of google cloud

After that i restarted the VM. Then again changed the password and then it worked.

user1@sap-hanaexpress-public-1-vm:~> sudo passwd
New password: 
Retype new password: 
passwd: password updated successfully
user1@sap-hanaexpress-public-1-vm:~> su
Password: 
sap-hanaexpress-public-1-vm:/home/user1 # whoami
root
sap-hanaexpress-public-1-vm:/home/user1 #

jQuery selector to get form by name

    // this will give all the forms on the page.

    $('form')

   // If you know the name of form then.

    $('form[name="myFormName"]')

  //  If you don't know know the name but the position (starts with 0)

    $('form:eq(1)')  // 2nd form will be fetched.

Powershell 2 copy-item which creates a folder if doesn't exist

My favorite is to use the .Net [IO.DirectoryInfo] class, which takes care of some of the logic. I actually use this for a lot of similar scripting challenges. It has a .Create() method that creates directories that don't exist, without errors if they do.

Since this is still a two step problem, I use the foreach alias to keep it simple. For single files:

[IO.DirectoryInfo]$to |% {$_.create(); cp $from $_}

As far as your multi file/directory match, I would use RoboCopy over xcopy. Remove the "*" from your from and just use:

RoboCopy.exe $from $to *

You can still add the /r (Recurse), /e (Recurse including Empty), and there are 50 other useful switches.

Edit: Looking back at this it is terse, but not very readable if you are not using the code often. Usually I have it split into two, like so:

([IO.DirectoryInfo]$to).Create()
cp $from $to

Also, DirectoryInfo is the type of the Parent property of FileInfo, so if your $to is a file, you can use them together:

([IO.FileInfo]$to).Parent.Create()
cp $from $to

Bootstrap 3: Offset isn't working?

If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:

<div class="container">
    <div class="row">
        <div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
        <div class="hidden-md hidden-lg col-xs-3">b</div>
    </div>
    <div class="row">
        <div class="hidden-xs hidden-sm">c</div>

    </div>
</div>

On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).

Position a CSS background image x pixels from the right?

Just put the pixel padding into the image - add 10px or whatever to the canvas size of the image in photohop and align it right in CSS.

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain

Setting the accept headers in the request should get the correct type:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.

The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.

Following code is cleaner and should work (untested, but works in my case):

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
    var model = await response.Content.ReadAsAsync<List<Job>>();

How to find MAC address of an Android device programmatically

See this post where I have submitted Utils.java example to provide pure-java implementations and works without WifiManager. Some android devices may not have wifi available or are using ethernet wiring.

Utils.getMACAddress("wlan0");
Utils.getMACAddress("eth0");
Utils.getIPAddress(true); // IPv4
Utils.getIPAddress(false); // IPv6 

How do I use reflection to call a generic method?

Nobody provided the "classic Reflection" solution, so here is a complete code example:

using System;
using System.Collections;
using System.Collections.Generic;

namespace DictionaryRuntime
{
    public class DynamicDictionaryFactory
    {
        /// <summary>
        /// Factory to create dynamically a generic Dictionary.
        /// </summary>
        public IDictionary CreateDynamicGenericInstance(Type keyType, Type valueType)
        {
            //Creating the Dictionary.
            Type typeDict = typeof(Dictionary<,>);

            //Creating KeyValue Type for Dictionary.
            Type[] typeArgs = { keyType, valueType };

            //Passing the Type and create Dictionary Type.
            Type genericType = typeDict.MakeGenericType(typeArgs);

            //Creating Instance for Dictionary<K,T>.
            IDictionary d = Activator.CreateInstance(genericType) as IDictionary;

            return d;

        }
    }
}

The above DynamicDictionaryFactory class has a method

CreateDynamicGenericInstance(Type keyType, Type valueType)

and it creates and returns an IDictionary instance, the types of whose keys and values are exactly the specified on the call keyType and valueType.

Here is a complete example how to call this method to instantiate and use a Dictionary<String, int> :

using System;
using System.Collections.Generic;

namespace DynamicDictionary
{
    class Test
    {
        static void Main(string[] args)
        {
            var factory = new DictionaryRuntime.DynamicDictionaryFactory();
            var dict = factory.CreateDynamicGenericInstance(typeof(String), typeof(int));

            var typedDict = dict as Dictionary<String, int>;

            if (typedDict != null)
            {
                Console.WriteLine("Dictionary<String, int>");

                typedDict.Add("One", 1);
                typedDict.Add("Two", 2);
                typedDict.Add("Three", 3);

                foreach(var kvp in typedDict)
                {
                    Console.WriteLine("\"" + kvp.Key + "\": " + kvp.Value);
                }
            }
            else
                Console.WriteLine("null");
        }
    }
}

When the above console application is executed, we get the correct, expected result:

Dictionary<String, int>
"One": 1
"Two": 2
"Three": 3

PostgreSQL column 'foo' does not exist

You accidentally created the column name with a trailing space and presumably phpPGadmin created the column name with double quotes around it:

create table your_table (
    "foo " -- ...
)

That would give you a column that looked like it was called foo everywhere but you'd have to double quote it and include the space whenever you use it:

select ... from your_table where "foo " is not null

The best practice is to use lower case unquoted column names with PostgreSQL. There should be a setting in phpPGadmin somewhere that will tell it to not quote identifiers (such as table and column names) but alas, I don't use phpPGadmin so I don't where that setting is (or even if it exists).

Is there a way to remove the separator line from a UITableView?

I still had a dark grey line after attempting the other answers. I had to add the following two lines to make everything "invisible" in terms of row lines between cells.

self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
self.tableView.separatorColor = [UIColor clearColor];

Submit form on pressing Enter with AngularJS

Use ng-submit and just wrap both inputs in separate form tags:

<div ng-controller="mycontroller">

  <form ng-submit="myFunc()">
    <input type="text" ng-model="name" <!-- Press ENTER and call myFunc --> />
  </form>

  <br />

  <form ng-submit="myFunc()">
    <input type="text" ng-model="email" <!-- Press ENTER and call myFunc --> />
  </form>

</div>

Wrapping each input field in its own form tag allows ENTER to invoke submit on either form. If you use one form tag for both, you will have to include a submit button.

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

How to unescape a Java string literal in Java?

I know this question was old, but I wanted a solution that doesn't involve libraries outside those included JRE6 (i.e. Apache Commons is not acceptable), and I came up with a simple solution using the built-in java.io.StreamTokenizer:

import java.io.*;

// ...

String literal = "\"Has \\\"\\\\\\\t\\\" & isn\\\'t \\\r\\\n on 1 line.\"";
StreamTokenizer parser = new StreamTokenizer(new StringReader(literal));
String result;
try {
  parser.nextToken();
  if (parser.ttype == '"') {
    result = parser.sval;
  }
  else {
    result = "ERROR!";
  }
}
catch (IOException e) {
  result = e.toString();
}
System.out.println(result);

Output:

Has "\  " & isn't
 on 1 line.

Disable scrolling in an iPhone web application?

If you are using jquery 1.7+, this works well:

$("donotscrollme").on("touchmove", false);

How to remove an element from a list by index

This depends on what you want to do.

If you want to return the element you removed, use pop():

>>> l = [1, 2, 3, 4, 5]
>>> l.pop(2)
3
>>> l
[1, 2, 4, 5]

However, if you just want to delete an element, use del:

>>> l = [1, 2, 3, 4, 5]
>>> del l[2]
>>> l
[1, 2, 4, 5]

Additionally, del allows you to use slices (e.g. del[2:]).

Most useful NLog configurations

I provided a couple of reasonably interesting answers to this question:

Nlog - Generating Header Section for a log file

Adding a Header:

The question wanted to know how to add a header to the log file. Using config entries like this allow you to define the header format separately from the format of the rest of the log entries. Use a single logger, perhaps called "headerlogger" to log a single message at the start of the application and you get your header:

Define the header and file layouts:

  <variable name="HeaderLayout" value="This is the header.  Start time = ${longdate} Machine = ${machinename} Product version = ${gdc:item=version}"/>
  <variable name="FileLayout" value="${longdate} | ${logger} | ${level} | ${message}" />

Define the targets using the layouts:

<target name="fileHeader" xsi:type="File" fileName="xxx.log" layout="${HeaderLayout}" />
<target name="file" xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" />

Define the loggers:

<rules>
  <logger name="headerlogger" minlevel="Trace" writeTo="fileHeader" final="true" />
  <logger name="*" minlevel="Trace" writeTo="file" />
</rules>

Write the header, probably early in the program:

  GlobalDiagnosticsContext.Set("version", "01.00.00.25");

  LogManager.GetLogger("headerlogger").Info("It doesn't matter what this is because the header format does not include the message, although it could");

This is largely just another version of the "Treating exceptions differently" idea.

Log each log level with a different layout

Similarly, the poster wanted to know how to change the format per logging level. It wasn't clear to me what the end goal was (and whether it could be achieved in a "better" way), but I was able to provide a configuration that did what he asked:

  <variable name="TraceLayout" value="This is a TRACE - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="DebugLayout" value="This is a DEBUG - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="InfoLayout" value="This is an INFO - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="WarnLayout" value="This is a WARN - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="ErrorLayout" value="This is an ERROR - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <variable name="FatalLayout" value="This is a FATAL - ${longdate} | ${logger} | ${level} | ${message}"/> 
  <targets> 
    <target name="fileAsTrace" xsi:type="FilteringWrapper" condition="level==LogLevel.Trace"> 
      <target xsi:type="File" fileName="xxx.log" layout="${TraceLayout}" /> 
    </target> 
    <target name="fileAsDebug" xsi:type="FilteringWrapper" condition="level==LogLevel.Debug"> 
      <target xsi:type="File" fileName="xxx.log" layout="${DebugLayout}" /> 
    </target> 
    <target name="fileAsInfo" xsi:type="FilteringWrapper" condition="level==LogLevel.Info"> 
      <target xsi:type="File" fileName="xxx.log" layout="${InfoLayout}" /> 
    </target> 
    <target name="fileAsWarn" xsi:type="FilteringWrapper" condition="level==LogLevel.Warn"> 
      <target xsi:type="File" fileName="xxx.log" layout="${WarnLayout}" /> 
    </target> 
    <target name="fileAsError" xsi:type="FilteringWrapper" condition="level==LogLevel.Error"> 
      <target xsi:type="File" fileName="xxx.log" layout="${ErrorLayout}" /> 
    </target> 
    <target name="fileAsFatal" xsi:type="FilteringWrapper" condition="level==LogLevel.Fatal"> 
      <target xsi:type="File" fileName="xxx.log" layout="${FatalLayout}" /> 
    </target> 
  </targets> 


    <rules> 
      <logger name="*" minlevel="Trace" writeTo="fileAsTrace,fileAsDebug,fileAsInfo,fileAsWarn,fileAsError,fileAsFatal" /> 
      <logger name="*" minlevel="Info" writeTo="dbg" /> 
    </rules> 

Again, very similar to Treating exceptions differently.

When to use NSInteger vs. int

int = 4 byte (fixed irrespective size of the architect) NSInteger = depend upon size of the architect(e.g. for 4 byte architect = 4 byte NSInteger size)

Unable to generate an explicit migration in entity framework

This isn't going to be the answer for many people, but EF will chuck this error when it can't connect to the DB. If you're working from home like I am, make sure you're still connected to your VPN!

How do I seed a random class to avoid getting duplicate random values

this workes for me:

private int GetaRandom()
    {
        Thread.Sleep(1);
        return new Random(DateTime.Now.Millisecond).Next();
    }

How do I create a custom Error in JavaScript?

The constructor needs to be like a factory method and return what you want. If you need additional methods/properties, you can add them to the object before returning it.

function NotImplementedError(message) { return new Error("Not implemented", message); }

x = new NotImplementedError();

Though I'm not sure why you'd need to do this. Why not just use new Error... ? Custom exceptions don't really add much in JavaScript (or probably any untyped language).

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

batch file to copy files to another location?

It's easy to copy a folder in a batch file.

 @echo off
 set src_folder = c:\whatever\*.*
 set dst_folder = c:\foo
 xcopy /S/E/U %src_folder% %dst_folder%

And you can add that batch file to your Windows login script pretty easily (assuming you have admin rights on the machine). Just go to the "User Manager" control panel, choose properties for your user, choose profile and set a logon script.

How you get to the user manager control panel depends on which version of Windows you run. But right clicking on My Computer and choosing manage and then choosing Local users and groups works for most versions.

The only sticky bit is "when the folder is updated". This sounds like a folder watcher, which you can't do in a batch file, but you can do pretty easily with .NET.

pandas unique values multiple columns

here's another way


import numpy as np
set(np.concatenate(df.values))