Programs & Examples On #Paintbox

How to put space character into a string name in XML?

You can use following as well

<string name="spelatonertext3"> "-4,  5, -5,   6,  -6, "> </string>

Put anything in " "(quotation) with space, and it should work

Relational Database Design Patterns?

Depends what you mean by a pattern. If you're thinking Person/Company/Transaction/Product and such, then yes - there are a lot of generic database schemas already available.

If you're thinking Factory, Singleton... then no - you don't need any of these as they're too low level for DB programming.

If you're thinking database object naming, then it's under the category of conventions, not design per se.

BTW, S.Lott, one-to-many and many-to-many relationships aren't "patterns". They're the basic building blocks of the relational model.

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

Attempt to write a readonly database - Django w/ SELinux error

You have to add writing rights to the directory in which your sqlite database is stored. So running chmod 664 /srv/mysite should help.

This is a security risk, so better solution is to change the owner of your database to www-data:

chown www-data:www-data /srv/mysite
chown www-data:www-data /srv/mysite/DATABASE.sqlite

How to set margin with jquery?

try

el.css('margin-left',mrg+'px');

Android/Eclipse: how can I add an image in the res/drawable folder?

Do you want to add an image from your computer? Just right click the folder in Eclipse and click Import

remove all variables except functions

I wrote this to remove all objects apart from functions from the current environment (Programming language used is R with IDE R-Studio):

    remove_list=c()                             # create a vector

      for(i in 1:NROW(ls())){                   # repeat over all objects in environment
        if(class(get(ls()[i]))!="function"){    # if object is *not* a function
         remove_list=c(remove_list,ls()[i])     # ..add to vector remove_list
         }    
      }

    rm(list=remove_list)                        # remove all objects named in remove_list

Notes-

The argument "list" in rm(list=) must be a character vector.

The name of an object in position i of the current environment is returned from ls()[i] and the object itself from get(ls()[i]). Therefore the class of an object is returned from class(get(ls()[i]))

What is the difference between const int*, const int * const, and int const *?

Simple Use of const.

The simplest use is to declare a named constant. To do this, one declares a constant as if it was a variable but add const before it. One has to initialize it immediately in the constructor because, of course, one cannot set the value later as that would be altering it. For example:

const int Constant1=96; 

will create an integer constant, unimaginatively called Constant1, with the value 96.

Such constants are useful for parameters which are used in the program but are do not need to be changed after the program is compiled. It has an advantage for programmers over the C preprocessor #define command in that it is understood & used by the compiler itself, not just substituted into the program text by the preprocessor before reaching the main compiler, so error messages are much more helpful.

It also works with pointers but one has to be careful where const to determine whether the pointer or what it points to is constant or both. For example:

const int * Constant2 

declares that Constant2 is variable pointer to a constant integer and:

int const * Constant2

is an alternative syntax which does the same, whereas

int * const Constant3

declares that Constant3 is constant pointer to a variable integer and

int const * const Constant4

declares that Constant4 is constant pointer to a constant integer. Basically ‘const’ applies to whatever is on its immediate left (other than if there is nothing there in which case it applies to whatever is its immediate right).

ref: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

.Net picking wrong referenced assembly version

Try:

  • cleaning temporary project files
  • cleaning build and obj files
  • cleaning old versions installed at C:\Users\USERNAME\.nuget\packages\

That worked for me.

Mongoose query where value is not null

Ok guys I found a possible solution to this problem. I realized that joins do not exists in Mongo, that's why first you need to query the user's ids with the role you like, and after that do another query to the profiles document, something like this:

    const exclude: string = '-_id -created_at -gallery -wallet -MaxRequestersPerBooking -active -__v';

  // Get the _ids of users with the role equal to role.
    await User.find({role: role}, {_id: 1, role: 1, name: 1},  function(err, docs) {

        // Map the docs into an array of just the _ids
        var ids = docs.map(function(doc) { return doc._id; });

        // Get the profiles whose users are in that set.
        Profile.find({user: {$in: ids}}, function(err, profiles) {
            // docs contains your answer
            res.json({
                code: 200,
                profiles: profiles,
                page: page
            })
        })
        .select(exclude)
        .populate({
            path: 'user',
            select: '-password -verified -_id -__v'
            // group: { role: "$role"} 
          })
    });

How to change an application icon programmatically in Android?

AndroidManifest.xml example:

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name="com.pritesh.resourceidentifierexample.MainActivity"
                  android:label="@string/app_name"
                  android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <!--<category android:name="android.intent.category.LAUNCHER"/>-->
            </intent-filter>
        </activity>

        <activity-alias android:label="RED"
                        android:icon="@drawable/ic_android_red"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Red"
                        android:enabled="true"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="GREEN"
                        android:icon="@drawable/ic_android_green"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Green"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

        <activity-alias android:label="BLUE"
                        android:icon="@drawable/ic_android_blue"
                        android:name="com.pritesh.resourceidentifierexample.MainActivity-Blue"
                        android:enabled="false"
                        android:targetActivity="com.pritesh.resourceidentifierexample.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity-alias>

    </application>

Then follow below given code in MainActivity:

ImageView imageView = (ImageView)findViewById(R.id.imageView);
            int imageResourceId;
            String currentDateTimeString = DateFormat.getDateTimeInstance().format(new Date());
            int hours = new Time(System.currentTimeMillis()).getHours();
            Log.d("DATE", "onCreate: "  + hours);

            getPackageManager().setComponentEnabledSetting(
                    getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

            if(hours == 13)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_red", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Red"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            }else if(hours == 14)
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_green", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Green"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }else
            {
                imageResourceId = this.getResources().getIdentifier("ic_android_blue", "drawable", this.getPackageName());
                getPackageManager().setComponentEnabledSetting(
                        new ComponentName("com.pritesh.resourceidentifierexample", "com.pritesh.resourceidentifierexample.MainActivity-Blue"),
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);

            }

            imageView.setImageResource(imageResourceId);

Should I use the datetime or timestamp data type in MySQL?

I always use DATETIME fields for anything other than row metadata (date created or modified).

As mentioned in the MySQL documentation:

The DATETIME type is used when you need values that contain both date and time information. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

...

The TIMESTAMP data type has a range of '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in.

You're quite likely to hit the lower limit on TIMESTAMPs in general use -- e.g. storing birthdate.

How to remove underline from a link in HTML?

The other answers all mention text-decoration. Sometimes you use a Wordpress theme or someone else's CSS where links are underlined by other methods, so that text-decoration: none won't turn off the underlining.

Border and box-shadow are two other methods I'm aware of for underlining links. To turn these off:

border: none;

and

box-shadow: none;

Java: How to convert List to Map

Alexis has already posted an answer in Java 8 using method toMap(keyMapper, valueMapper). As per doc for this method implementation:

There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

So in case we are interested in a specific implementation of Map interface e.g. HashMap then we can use the overloaded form as:

Map<String, Item> map2 =
                itemList.stream().collect(Collectors.toMap(Item::getKey, //key for map
                        Function.identity(),    // value for map
                        (o,n) -> o,             // merge function in case of conflict with keys
                        HashMap::new));         // map factory - we want HashMap and not any Map implementation

Though using either Function.identity() or i->i is fine but it seems Function.identity() instead of i -> i might save some memory as per this related answer.

How to shrink/purge ibdata1 file in MySQL

If you use the InnoDB storage engine for (some of) your MySQL tables, you’ve probably already came across a problem with its default configuration. As you may have noticed in your MySQL’s data directory (in Debian/Ubuntu – /var/lib/mysql) lies a file called ‘ibdata1'. It holds almost all the InnoDB data (it’s not a transaction log) of the MySQL instance and could get quite big. By default this file has a initial size of 10Mb and it automatically extends. Unfortunately, by design InnoDB data files cannot be shrinked. That’s why DELETEs, TRUNCATEs, DROPs, etc. will not reclaim the space used by the file.

I think you can find good explanation and solution there :

http://vdachev.net/2007/02/22/mysql-reducing-ibdata1/

How to make a HTML Page in A4 paper size page(s)?

It would be fairly easy to force the web browser to display the page with the same pixel dimensions as A4. However, there may be a few quirks when things are rendered.

Assuming your monitors display 72 dpi, you could add something like this:

<!DOCTYPE html>
<html>
  <head>
    <style>
    body {
        height: 842px;
        width: 595px;
        /* to centre page on screen*/
        margin-left: auto;
        margin-right: auto;
    }
    </style>
  </head>
  <body>
  </body>
</html>

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

How to add anything in <head> through jquery/javascript?

Try a javascript pure:

Library JS:

appendHtml = function(element, html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    while (div.children.length > 0) {
        element.appendChild(div.children[0]);
    }
}

Type: appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');

or jQuery:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));

Numpy matrix to array

This will convert the matrix into array

A = np.ravel(M).T

JOptionPane - input dialog box program

import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.JOptionPane;
import javax.swing.JFrame;

public class Average {

    public static void main(String [] args) {

        String test1= JOptionPane.showInputDialog("Please input mark for test 1: ");

        String test2= JOptionPane.showInputDialog("Please input mark for test 2: ");

        String test3= JOptionPane.showInputDialog("Please input mark for test 3: ");

        int int1 = Integer.parseInt(test1);
        int int2 = Integer.parseInt(test2);
        int int3 = Integer.parseInt(test3);

        SortedSet<Integer> set = new TreeSet<>();
        set.add(int1);
        set.add(int2);
        set.add(int3);

        Integer [] intArray = set.toArray(new Integer[3]);
        JFrame frame = new JFrame();
        JOptionPane.showInternalMessageDialog(frame.getContentPane(), String.format("Result %f", (intArray[1] + intArray[2]) / 2.0));

    }

}

Formatting struct timespec

One way to format it is:

printf("%lld.%.9ld", (long long)ts.tv_sec, ts.tv_nsec);

Inputting a default image in case the src attribute of an html <img> is not valid?

Simple and neat solution involving some good answers and comment.

<img src="foo.jpg" onerror="this.src='error.jpg';this.onerror='';">

It even solve infinite loop risk.

Worked for me.

How do I see which version of Swift I'm using?

From Xcode 8.3 onward Build Settings has key Swift Language Version with a value of swift version your target is using.

For older Xcodes use this solution, open terminal and type following command(s)

Case 1: You have installed only one Xcode App

swift -version

Case 2: You have installed multiple Xcode Apps

  • Switch active developer directory (Replace Xcode_7.3.app from following command with your Xcode app file name from Application directory for which you want to check swift version)

     sudo xcode-select --switch /Applications/Xcode_7.3.app/Contents/Developer
    
  • Then

     swift -version
    

NOTE: From Xcode 8 to Xcode 8.2.x you can use swift 2.3 even though Xcode 8 uses swift 3.x as default swift version. To use swift 2.3, just turn on flag Use Legacy Swift Language Version to YES from Build Setting and XCode will use Swift 2.3 for that project target.

How to place div side by side

CSS3 introduced flexible boxes (aka. flex box) which can also achieve this behavior.

Simply define the width of the first div, and then give the second a flex-grow value of 1 which will allow it to fill the remaining width of the parent.

.container{
    display: flex;
}
.fixed{
    width: 200px;
}
.flex-item{
    flex-grow: 1;
}
<div class="container">
  <div class="fixed"></div>
  <div class="flex-item"></div>
</div>

Demo:

_x000D_
_x000D_
div {
    color: #fff;
    font-family: Tahoma, Verdana, Segoe, sans-serif;
    padding: 10px;
}
.container {
    background-color:#2E4272;
    display:flex;
}
.fixed {
    background-color:#4F628E;
    width: 200px;
}
.flex-item {
    background-color:#7887AB;
    flex-grow: 1;
}
_x000D_
<div class="container">
    <div class="fixed">Fixed width</div>
    <div class="flex-item">Dynamically sized content</div>
</div>
_x000D_
_x000D_
_x000D_

Note that flex boxes are not backwards compatible with old browsers, but is a great option for targeting modern browsers (see also Caniuse and MDN). A great comprehensive guide on how to use flex boxes is available on CSS Tricks.

Unique constraint violation during insert: why? (Oracle)

Your error looks like you are duplicating an already existing Primary Key in your DB. You should modify your sql code to implement its own primary key by using something like the IDENTITY keyword.

CREATE TABLE [DB] (
    [DBId] bigint NOT NULL IDENTITY,
    ...

    CONSTRAINT [DB_PK] PRIMARY KEY ([DB] ASC),

); 

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I was suffering from this problem for long times.

  • I had about 100 projects different version was deployed in different server.

  • Updating xunit from 2.2.0 to 2.3.1 was not a solution because build was failing in 2.3.1.

Then I just updated xunit.runner.visualstudio to 2.3.1 and everything started to work fine. I have used this command in my package manager console to updated my xunit.runner.visualstudio package

Get-Project ComapanyName.ProjectName.*.Tests | Install-Package xunit.runner.visualstudio -Version 2.3.1

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

Disable Buttons in jQuery Mobile

Try one of the statements below:

$('input[type=submit]').attr('disabled','disabled');

or

$('input[type=button]').attr('disabled','disabled');

UPDATE

To target a particular button, given the HTML you provided:

$('div#DT1S input[type=button]').attr('disabled','disabled');

http://jsfiddle.net/kZcd8/

how to insert value into DataGridView Cell?

int index= datagridview.rows.add();
datagridview.rows[index].cells[1].value=1;
datagridview.rows[index].cells[2].value="a";
datagridview.rows[index].cells[3].value="b";

hope this help! :)

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

Python Binomial Coefficient

For everyone looking for the log of the binomial coefficient (Theano calls this binomln), this answer has it:

from numpy import log
from scipy.special import betaln

def binomln(n, k):
    "Log of scipy.special.binom calculated entirely in the log domain"
    return -betaln(1 + n - k, 1 + k) - log(n + 1)

(And if your language/library lacks betaln but has gammaln, like Go, have no fear, since betaln(a, b) is just gammaln(a) + gammaln(b) - gammaln(a + b), per MathWorld.)

Using async/await with a forEach loop

Today I came across multiple solutions for this. Running the async await functions in the forEach Loop. By building the wrapper around we can make this happen.

More detailed explanation on how it works internally, for the native forEach and why it is not able to make a async function call and other details on the various methods are provided in link here

The multiple ways through which it can be done and they are as follows,

Method 1 : Using the wrapper.

await (()=>{
     return new Promise((resolve,reject)=>{
       items.forEach(async (item,index)=>{
           try{
               await someAPICall();
           } catch(e) {
              console.log(e)
           }
           count++;
           if(index === items.length-1){
             resolve('Done')
           }
         });
     });
    })();

Method 2: Using the same as a generic function of Array.prototype

Array.prototype.forEachAsync.js

if(!Array.prototype.forEachAsync) {
    Array.prototype.forEachAsync = function (fn){
      return new Promise((resolve,reject)=>{
        this.forEach(async(item,index,array)=>{
            await fn(item,index,array);
            if(index === array.length-1){
                resolve('done');
            }
        })
      });
    };
  }

Usage :

require('./Array.prototype.forEachAsync');

let count = 0;

let hello = async (items) => {

// Method 1 - Using the Array.prototype.forEach 

    await items.forEachAsync(async () => {
         try{
               await someAPICall();
           } catch(e) {
              console.log(e)
           }
        count++;
    });

    console.log("count = " + count);
}

someAPICall = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("done") // or reject('error')
        }, 100);
    })
}

hello(['', '', '', '']); // hello([]) empty array is also be handled by default

Method 3 :

Using Promise.all

  await Promise.all(items.map(async (item) => {
        await someAPICall();
        count++;
    }));

    console.log("count = " + count);

Method 4 : Traditional for loop or modern for loop

// Method 4 - using for loop directly

// 1. Using the modern for(.. in..) loop
   for(item in items){

        await someAPICall();
        count++;
    }

//2. Using the traditional for loop 

    for(let i=0;i<items.length;i++){

        await someAPICall();
        count++;
    }


    console.log("count = " + count);

Python conversion between coordinates

If you can't find it in numpy or scipy, here are a couple of quick functions and a point class:

import math

def rect(r, theta):
    """theta in degrees

    returns tuple; (float, float); (x,y)
    """
    x = r * math.cos(math.radians(theta))
    y = r * math.sin(math.radians(theta))
    return x,y

def polar(x, y):
    """returns r, theta(degrees)
    """
    r = (x ** 2 + y ** 2) ** .5
    theta = math.degrees(math.atan2(y,x))
    return r, theta

class Point(object):
    def __init__(self, x=None, y=None, r=None, theta=None):
        """x and y or r and theta(degrees)
        """
        if x and y:
            self.c_polar(x, y)
        elif r and theta:
            self.c_rect(r, theta)
        else:
            raise ValueError('Must specify x and y or r and theta')
    def c_polar(self, x, y, f = polar):
        self._x = x
        self._y = y
        self._r, self._theta = f(self._x, self._y)
        self._theta_radians = math.radians(self._theta)
    def c_rect(self, r, theta, f = rect):
        """theta in degrees
        """
        self._r = r
        self._theta = theta
        self._theta_radians = math.radians(theta)
        self._x, self._y = f(self._r, self._theta)
    def setx(self, x):
        self.c_polar(x, self._y)
    def getx(self):
        return self._x
    x = property(fget = getx, fset = setx)
    def sety(self, y):
        self.c_polar(self._x, y)
    def gety(self):
        return self._y
    y = property(fget = gety, fset = sety)
    def setxy(self, x, y):
        self.c_polar(x, y)
    def getxy(self):
        return self._x, self._y
    xy = property(fget = getxy, fset = setxy)
    def setr(self, r):
        self.c_rect(r, self._theta)
    def getr(self):
        return self._r
    r = property(fget = getr, fset = setr)
    def settheta(self, theta):
        """theta in degrees
        """
        self.c_rect(self._r, theta)
    def gettheta(self):
        return self._theta
    theta = property(fget = gettheta, fset = settheta)
    def set_r_theta(self, r, theta):
        """theta in degrees
        """
        self.c_rect(r, theta)
    def get_r_theta(self):
        return self._r, self._theta
    r_theta = property(fget = get_r_theta, fset = set_r_theta)
    def __str__(self):
        return '({},{})'.format(self._x, self._y)

Python loop counter in a for loop

I'll sometimes do this:

def draw_menu(options, selected_index):
    for i in range(len(options)):
        if i == selected_index:
            print " [*] %s" % options[i]
        else:
            print " [ ] %s" % options[i]

Though I tend to avoid this if it means I'll be saying options[i] more than a couple of times.

What is a loop invariant?

In Linear Search (as per exercise given in book), we need to find value V in given array.

Its simple as scanning the array from 0 <= k < length and comparing each element. If V found, or if scanning reaches length of array, just terminate the loop.

As per my understanding in above problem-

Loop Invariants(Initialization): V is not found in k - 1 iteration. Very first iteration, this would be -1 hence we can say V not found at position -1

Maintainance: In next iteration,V not found in k-1 holds true

Terminatation: If V found in k position or k reaches the length of the array, terminate the loop.

Rounding a variable to two decimal places C#

You should use a form of Math.Round. Be aware that Math.Round defaults to banker's rounding (rounding to the nearest even number) unless you specify a MidpointRounding value. If you don't want to use banker's rounding, you should use Math.Round(decimal d, int decimals, MidpointRounding mode), like so:

Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01
Math.Round(pay, 2, MidpointRounding.ToEven);       // .005 rounds to nearest even (0.00) 
Math.Round(pay, 2);    // Defaults to MidpointRounding.ToEven

(Why does .NET use banker's rounding?)

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

JQuery ajax call default timeout value

There doesn't seem to be a standardized default value. I have the feeling the default is 0, and the timeout event left totally dependent on browser and network settings.

For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).

/exclude in xcopy just for a file type

For excluding multiple file types, you can use '+' to concatenate other lists. For example:

xcopy /r /d /i /s /y /exclude:excludedfileslist1.txt+excludedfileslist2.txt C:\dev\apan C:\web\apan

Source: http://www.tech-recipes.com/rx/2682/xcopy_command_using_the_exclude_flag/

Efficient way to determine number of digits in an integer

for integer 'X' you want to know the number of digits , alright without using any loop , this solution act in one formula in one line only so this is the most optimal solution i have ever seen to this problem .

 int x = 1000 ; 
 cout<<numberOfDigits = 1+floor(log10(x))<<endl ; 

can you add HTTPS functionality to a python flask web server?

If this webserver is only for testing and demoing purposes. You can use ngrok, a open source too that tunnels your http traffic.

Bascially ngrok creates a public URL (both http and https) and then tunnels the traffic to whatever port your Flask process is running on.

https://ngrok.com/product

It only takes a couple minutes to set up. You first have to download the software. Then run the command
./ngrok http [port number your python process is running on]

It will then open up a window in terminal giving you both an http and https url to access your web app.

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

You are right about HashTable, you can forget about it.

Your article mentions the fact that while HashTable and the synchronized wrapper class provide basic thread-safety by only allowing one thread at a time to access the map, this is not 'true' thread-safety since many compound operations still require additional synchronization, for example:

synchronized (records) {
  Record rec = records.get(id);
  if (rec == null) {
      rec = new Record(id);
      records.put(id, rec);
  }
  return rec;
}

However, don't think that ConcurrentHashMap is a simple alternative for a HashMap with a typical synchronized block as shown above. Read this article to understand its intricacies better.

Clicking URLs opens default browser

Add this 2 lines in your code -

mWebView.setWebChromeClient(new WebChromeClient()); 
mWebView.setWebViewClient(new WebViewClient());?

push_back vs emplace_back

emplace_back conforming implementation will forward arguments to the vector<Object>::value_typeconstructor when added to the vector. I recall Visual Studio didn't support variadic templates, but with variadic templates will be supported in Visual Studio 2013 RC, so I guess a conforming signature will be added.

With emplace_back, if you forward the arguments directly to vector<Object>::value_type constructor, you don't need a type to be movable or copyable for emplace_back function, strictly speaking. In the vector<NonCopyableNonMovableObject> case, this is not useful, since vector<Object>::value_type needs a copyable or movable type to grow.

But note that this could be useful for std::map<Key, NonCopyableNonMovableObject>, since once you allocate an entry in the map, it doesn't need to be moved or copied ever anymore, unlike with vector, meaning that you can use std::map effectively with a mapped type that is neither copyable nor movable.

How to find a parent with a known class in jQuery?

Use .parentsUntil()

$(".d").parentsUntil(".a");

Execute a SQL Stored Procedure and process the results

Simplest way? It works. :)

    Dim queryString As String = "Stor_Proc_Name " & data1 & "," & data2
    Try
        Using connection As New SqlConnection(ConnStrg)
            connection.Open()
            Dim command As New SqlCommand(queryString, connection)
            Dim reader As SqlDataReader = command.ExecuteReader()
            Dim DTResults As New DataTable

            DTResults.Load(reader)
            MsgBox(DTResults.Rows(0)(0).ToString)

        End Using
    Catch ex As Exception
        MessageBox.Show("Error while executing .. " & ex.Message, "")
    Finally
    End Try

Adding items to a JComboBox

create a new class called ComboKeyValue.java

    public class ComboKeyValue {
        private String key;
        private String value;
    
        public ComboKeyValue(String key, String value) {
            this.key = key;
            this.value = value;
        }
        
        @Override
        public String toString(){
            return key;
        }
    
        public String getKey() {
            return key;
        }
    
        public String getValue() {
            return value;
        }
}

when you want to add a new item, just write the code as below

 DefaultComboBoxModel model = new DefaultComboBoxModel();
    model.addElement(new ComboKeyValue("key", "value"));
    properties.setModel(model);

jQuery - keydown / keypress /keyup ENTERKEY detection?

JavaScript/jQuery

$("#entersomething").keyup(function(e){ 
    var code = e.key; // recommended to use e.key, it's normalized across devices and languages
    if(code==="Enter") e.preventDefault();
    if(code===" " || code==="Enter" || code===","|| code===";"){
        $("#displaysomething").html($(this).val());
    } // missing closing if brace
});

HTML

<input id="entersomething" type="text" /> <!-- put a type attribute in -->
<div id="displaysomething"></div>

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

Tomcat 404 error: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

Hope this helps. From eclipse, you right click the project -> Run As -> Run on Server and then it worked for me. I used Eclipse Jee Neon and Apache Tomcat 9.0. :)

I just removed the head portion in index.html file and it worked fine.This is the head tag in html file

Set focus on <input> element

This is working i Angular 8 without setTimeout:

import {AfterContentChecked, Directive, ElementRef} from '@angular/core';

@Directive({
  selector: 'input[inputAutoFocus]'
})
export class InputFocusDirective implements AfterContentChecked {
  constructor(private element: ElementRef<HTMLInputElement>) {}

  ngAfterContentChecked(): void {
    this.element.nativeElement.focus();
  }
}

Explanation: Ok so this works because of: Change detection. It's the same reason that setTimout works, but when running a setTimeout in Angular it will bypass Zone.js and run all checks again, and it works because when the setTimeout is complete all changes are completed. With the correct lifecycle hook (AfterContentChecked) the same result can be be reached, but with the advantage that the extra cycle won't be run. The function will fire when all changes are checked and passed, and runs after the hooks AfterContentInit and DoCheck. If i'm wrong here please correct me.

More one lifecycles and change detection on https://angular.io/guide/lifecycle-hooks

UPDATE: I found an even better way to do this if one is using Angular Material CDK, the a11y-package. First import A11yModule in the the module declaring the component you have the input-field in. Then use cdkTrapFocus and cdkTrapFocusAutoCapture directives and use like this in html and set tabIndex on the input:

<div class="dropdown" cdkTrapFocus cdkTrapFocusAutoCapture>
    <input type="text tabIndex="0">
</div>

We had some issues with our dropdowns regarding positioning and responsiveness and started using the OverlayModule from the cdk instead, and this method using A11yModule works flawlessly.

Getters \ setters for dummies

If you're referring to the concept of accessors, then the simple goal is to hide the underlying storage from arbitrary manipulation. The most extreme mechanism for this is

function Foo(someValue) {
    this.getValue = function() { return someValue; }
    return this;
}

var myFoo = new Foo(5);
/* We can read someValue through getValue(), but there is no mechanism
 * to modify it -- hurrah, we have achieved encapsulation!
 */
myFoo.getValue();

If you're referring to the actual JS getter/setter feature, eg. defineGetter/defineSetter, or { get Foo() { /* code */ } }, then it's worth noting that in most modern engines subsequent usage of those properties will be much much slower than it would otherwise be. eg. compare performance of

var a = { getValue: function(){ return 5; }; }
for (var i = 0; i < 100000; i++)
    a.getValue();

vs.

var a = { get value(){ return 5; }; }
for (var i = 0; i < 100000; i++)
    a.value;

Launch Pycharm from command line (terminal)

You can launch Pycharm from Mac terminal using the open command. Just type open /path/to/App

Applications$ ls -lrt PyCharm\ CE.app/
total 8
drwxr-xr-x@ 71 amit  admin  2414 Sep 24 11:08 lib
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 help
drwxr-xr-x@ 12 amit  admin   408 Sep 24 11:08 plugins
drwxr-xr-x@ 29 amit  admin   986 Sep 24 11:08 license
drwxr-xr-x@  4 amit  admin   136 Sep 24 11:08 skeletons
-rw-r--r--@  1 amit  admin    10 Sep 24 11:08 build.txt
drwxr-xr-x@  6 amit  admin   204 Sep 24 11:12 Contents
drwxr-xr-x@ 14 amit  admin   476 Sep 24 11:12 bin
drwxr-xr-x@ 31 amit  admin  1054 Sep 25 21:43 helpers
/Applications$
/Applications$ open PyCharm\ CE.app/

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

To add to the answers here, ensure there's no space between the select and [name...

Wrong:

'select [name=' + name + ']'
       ^

Right:

'select[name=' + name + ']'

How to make git mark a deleted and a new file as a file move?

There is a probably a better “command line” way to do this, and I know this is a hack, but I’ve never been able to find a good solution.

Using TortoiseGIT: If you have a GIT commit where some file move operations are showing up as load of adds/deletes rather than renames, even though the files only have small changes, then do this:

  1. Check in what you have done locally
  2. Check in a mini one-line change in a 2nd commit
  3. Go to GIT log in tortoise git
  4. Select the two commits, right click, and select “merge into one commit”

The new commit will now properly show the file renames… which will help maintain proper file history.

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

My sphinx.conf

source post_source 
{
    type = mysql

    sql_host = localhost
    sql_user = ***
    sql_pass = ***
    sql_db =   ***
    sql_port = 3306

    sql_query_pre = SET NAMES utf8
    # query before fetching rows to index

    sql_query = SELECT *, id AS pid, CRC32(safetag) as safetag_crc32 FROM hb_posts


    sql_attr_uint = pid  
    # pid (as 'sql_attr_uint') is necessary for sphinx
    # this field must be unique

    # that is why I like sphinx
    # you can store custom string fields into indexes (memory) as well
    sql_field_string = title
    sql_field_string = slug
    sql_field_string = content
    sql_field_string = tags

    sql_attr_uint = category
    # integer fields must be defined as sql_attr_uint

    sql_attr_timestamp = date
    # timestamp fields must be defined as sql_attr_timestamp

    sql_query_info_pre = SET NAMES utf8
    # if you need unicode support for sql_field_string, you need to patch the source
    # this param. is not supported natively

    sql_query_info = SELECT * FROM my_posts WHERE id = $id
}

index posts 
{
    source = post_source
    # source above

    path = /var/data/posts
    # index location

    charset_type = utf-8
}

Test script:

<?php

    require "sphinxapi.php";

    $safetag = $_GET["my_post_slug"];
//  $safetag = preg_replace("/[^a-z0-9\-_]/i", "", $safetag);

    $conf = getMyConf();

    $cl = New SphinxClient();

    $cl->SetServer($conf["server"], $conf["port"]);
    $cl->SetConnectTimeout($conf["timeout"]);
    $cl->setMaxQueryTime($conf["max"]);

    # set search params
    $cl->SetMatchMode(SPH_MATCH_FULLSCAN);
    $cl->SetArrayResult(TRUE);

    $cl->setLimits(0, 1, 1); 
    # looking for the post (not searching a keyword)

    $cl->SetFilter("safetag_crc32", array(crc32($safetag)));

    # fetch results
    $post = $cl->Query(null, "post_1");

    echo "<pre>";
    var_dump($post);
    echo "</pre>";
    exit("done");
?>

Sample result:

[array] => 
  "id" => 123,
  "title" => "My post title.",
  "content" => "My <p>post</p> content.",
   ...
   [ and other fields ]

Sphinx query time:

0.001 sec.

Sphinx query time (1k concurrent):

=> 0.346 sec. (average)
=> 0.340 sec. (average of last 10 query)

MySQL query time:

"SELECT * FROM hb_posts WHERE id = 123;"
=> 0.001 sec.

MySQL query time (1k concurrent):

"SELECT * FROM my_posts WHERE id = 123;" 
=> 1.612 sec. (average)
=> 1.920 sec. (average of last 10 query)

jQuery UI Dialog with ASP.NET button postback

ken's answer above did the trick for me. The problem with the accepted answer is that it only works if you have a single modal on the page. If you have multiple modals, you'll need to do it inline in the "open" param while initializing the dialog, not after the fact.

open: function(type,data) { $(this).parent().appendTo("form"); }

If you do what the first accepted answer tells you with multiple modals, you'll only get the last modal on the page working firing postbacks properly, not all of them.

How to run Maven from another directory (without cd to project dir)?

You can use the parameter -f (or --file) and specify the path to your pom file, e.g. mvn -f /path/to/pom.xml

This runs maven "as if" it were in /path/to for the working directory.

Most efficient way to append arrays in C#?

Here is a usable class based on what Constantin said:

class Program
{
    static void Main(string[] args)
    {
        FastConcat<int> i = new FastConcat<int>();
        i.Add(new int[] { 0, 1, 2, 3, 4 });
        Console.WriteLine(i[0]);
        i.Add(new int[] { 5, 6, 7, 8, 9 });
        Console.WriteLine(i[4]);

        Console.WriteLine("Enumerator:");
        foreach (int val in i)
            Console.WriteLine(val);

        Console.ReadLine();
    }
}

class FastConcat<T> : IEnumerable<T>
{
    LinkedList<T[]> _items = new LinkedList<T[]>();
    int _count;

    public int Count
    {
        get
        {
            return _count;
        }
    }

    public void Add(T[] items)
    {
        if (items == null)
            return;
        if (items.Length == 0)
            return;

        _items.AddLast(items);
        _count += items.Length;
    }

    private T[] GetItemIndex(int realIndex, out int offset)
    {
        offset = 0; // Offset that needs to be applied to realIndex.
        int currentStart = 0; // Current index start.

        foreach (T[] items in _items)
        {
            currentStart += items.Length;
            if (currentStart > realIndex)
                return items;
            offset = currentStart;
        }
        return null;
    }

    public T this[int index]
    {
        get
        {
            int offset;
            T[] i = GetItemIndex(index, out offset);
            return i[index - offset];
        }
        set
        {
            int offset;
            T[] i = GetItemIndex(index, out offset);
            i[index - offset] = value;
        }
    }

    #region IEnumerable<T> Members

    public IEnumerator<T> GetEnumerator()
    {
        foreach (T[] items in _items)
            foreach (T item in items)
                yield return item;
    }

    #endregion

    #region IEnumerable Members

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    #endregion
}

Oracle sqlldr TRAILING NULLCOLS required, but why?

I had similar issue when I had plenty of extra records in csv file with empty values. If I open csv file in notepad then empty lines looks like this: ,,,, ,,,, ,,,, ,,,,

You can not see those if open in Excel. Please check in Notepad and delete those records

Delete a row in DataGridView Control in VB.NET

For Each row As DataGridViewRow In yourDGV.SelectedRows
    yourDGV.Rows.Remove(row)
Next

This will delete all rows that had been selected.

Generating a PDF file from React Components

This may or may not be a sub-optimal way of doing things, but the simplest solution to the multi-page problem I found was to ensure all rendering is done before calling the jsPDFObj.save method.

As for rendering hidden articles, this is solved with a similar fix to css image text replacement, I position absolutely the element to be rendered -9999px off the page left, this doesn't affect layout and allows for the elem to be visible to html2pdf, especially when using tabs, accordions and other UI components that depend on {display: none}.

This method wraps the prerequisites in a promise and calls pdf.save() in the finally() method. I cannot be sure that this is foolproof, or an anti-pattern, but it would seem that it works in most cases I have thrown at it.

_x000D_
_x000D_
// Get List of paged elements._x000D_
let elems = document.querySelectorAll('.elemClass');_x000D_
let pdf = new jsPDF("portrait", "mm", "a4");_x000D_
_x000D_
// Fix Graphics Output by scaling PDF and html2canvas output to 2_x000D_
pdf.scaleFactor = 2;_x000D_
_x000D_
// Create a new promise with the loop body_x000D_
let addPages = new Promise((resolve,reject)=>{_x000D_
  elems.forEach((elem, idx) => {_x000D_
    // Scaling fix set scale to 2_x000D_
    html2canvas(elem, {scale: "2"})_x000D_
      .then(canvas =>{_x000D_
        if(idx < elems.length - 1){_x000D_
          pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
          pdf.addPage();_x000D_
        } else {_x000D_
          pdf.addImage(canvas.toDataURL("image/png"), 0, 0, 210, 297);_x000D_
          console.log("Reached last page, completing");_x000D_
        }_x000D_
  })_x000D_
  _x000D_
  setTimeout(resolve, 100, "Timeout adding page #" + idx);_x000D_
})_x000D_
_x000D_
addPages.finally(()=>{_x000D_
   console.log("Saving PDF");_x000D_
   pdf.save();_x000D_
});
_x000D_
_x000D_
_x000D_

How do I display an alert dialog on Android?

With Anko (official library from developers of Kotlin), you can simple use

alert("Alert title").show()

or more complex one:

alert("Hi, I'm Roy", "Have you tried turning it off and on again?") {
    yesButton { toast("Oh…") }
    noButton {}
}.show()

To import Anko:

implementation "org.jetbrains.anko:anko:0.10.8"

How to Detect Browser Back Button event - Cross Browser

Browser: https://jsfiddle.net/Limitlessisa/axt1Lqoz/

For mobile control: https://jsfiddle.net/Limitlessisa/axt1Lqoz/show/

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('body').on('click touch', '#share', function(e) {_x000D_
    $('.share').fadeIn();_x000D_
  });_x000D_
});_x000D_
_x000D_
// geri butonunu yakalama_x000D_
window.onhashchange = function(e) {_x000D_
  var oldURL = e.oldURL.split('#')[1];_x000D_
  var newURL = e.newURL.split('#')[1];_x000D_
_x000D_
  if (oldURL == 'share') {_x000D_
    $('.share').fadeOut();_x000D_
    e.preventDefault();_x000D_
    return false;_x000D_
  }_x000D_
  //console.log('old:'+oldURL+' new:'+newURL);_x000D_
}
_x000D_
.share{position:fixed; display:none; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.8); color:white; padding:20px;
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
    <title>Back Button Example</title>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body style="text-align:center; padding:0;">_x000D_
    <a href="#share" id="share">Share</a>_x000D_
    <div class="share" style="">_x000D_
        <h1>Test Page</h1>_x000D_
        <p> Back button press please for control.</p>_x000D_
    </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to get the last five characters of a string using Substring() in C#?

Substring. This method extracts strings. It requires the location of the substring (a start index, a length). It then returns a new string with the characters in that range.

See a small example :

string input = "OneTwoThree";
// Get first three characters.
string sub = input.Substring(0, 3);
Console.WriteLine("Substring: {0}", sub);

Output : Substring: One

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

Webpack "OTS parsing error" loading fonts

The best and easiest method is to base64 encode the font file. And use it in font-face. For encoding, go to the folder having the font-file and use the command in terminal:

base64 Roboto.ttf > basecodedtext.txt

You will get an output file named basecodedtext.txt. Open that file. Remove any white spaces in that.

Copy that code and add the following line to the CSS file:

@font-face {
  font-family: "font-name";
  src: url(data:application/x-font-woff;charset=utf-8;base64,<<paste your code here>>) format('woff');
}  

Then you can use the font-family: "font-name" in your CSS.

Plotting power spectrum in python

if rate is the sampling rate(Hz), then np.linspace(0, rate/2, n) is the frequency array of every point in fft. You can use rfft to calculate the fft in your data is real values:

import numpy as np
import pylab as pl
rate = 30.0
t = np.arange(0, 10, 1/rate)
x = np.sin(2*np.pi*4*t) + np.sin(2*np.pi*7*t) + np.random.randn(len(t))*0.2
p = 20*np.log10(np.abs(np.fft.rfft(x)))
f = np.linspace(0, rate/2, len(p))
plot(f, p)

enter image description here

signal x contains 4Hz & 7Hz sin wave, so there are two peaks at 4Hz & 7Hz.

Clear android application user data

To clear Application Data Please Try this way.

    public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null &amp;&amp; dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

Why does adb return offline after the device string?

  1. make sure the device is set for usb debugging
  2. Have the adb client running (e.g. via "adb usb" or adb start-server"
  3. LEAVE the device connected via usb!!!
  4. AND THEN reboot the device.

This always brings my Motorola MB525 "online" again, after adb complains it would be "offline". I'm using OSX btw.

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

Difference between filter and filter_by in SQLAlchemy

filter_by uses keyword arguments, whereas filter allows pythonic filtering arguments like filter(User.name=="john")

Multiline editing in Visual Studio Code

Use Ctrl + D to use multi word edit of same words in Windows and Linux.

Use CMD + D for Mac.

Unable to open debugger port in IntelliJ IDEA

I had this exact message.

The reason was that some IDE (I use Eclipse and Intellij) failed to shutdown the tomcat server. Or maybe crashed before it could do so.

The solution was to navigate to C:\...\apache-tomcat-xxx\bin and run shutdown.

Python data structure sort list alphabetically

ListName.sort() will sort it alphabetically. You can add reverse=False/True in the brackets to reverse the order of items: ListName.sort(reverse=False)

JQuery Calculate Day Difference in 2 date textboxes

Hi, This is my example of calculating the difference between two dates

    <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <script src="https://code.jquery.com/jquery.min.js"></script>
  <title>JS Bin</title>
</head>
<body>
  <br>
<input class='fromdate' type="date"  />
<input class='todate' type="date" />
<div class='calculated' /><br>
<div class='minim' />  
<input class='todate' type="submit" onclick='showDays()' />

</body>
</html>

This is the function that calculates the difference :

function showDays(){

     var start = $('.fromdate').val();
     var end = $('.todate').val();

     var startDay = new Date(start);
     var endDay = new Date(end);
     var millisecondsPerDay = 1000 * 60 * 60 * 24;

     var millisBetween = endDay.getTime() - startDay.getTime();
     var days = millisBetween / millisecondsPerDay;

      // Round down.
       alert( Math.floor(days));

}

I hope I have helped you

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • Open Sublime Text from Terminal in macOS

    There is a easy way to do this. It only takes a couple steps and you don't need to use the command line too much. If you new to the command line this is the way to do it.

    Step 1 : Finding the bin file to put the subl executable file in

    1. Open up the terminal
    2. type in cd .. ---------------------this should go back a directory
    3. type in ls ------------------------to see a list of files in the directory
    4. type in cd .. ---------------------until you get a folder that contains usr
    5. type in open usr ---------------this should open the finder and you should see some folders
    6. open up the bin folder -------this is where you will copy your sublime executable file.

    Step 2: Finding the executable file

    1. open up the finder
    2. Under file open up a new finder window (CMD + N)
    3. Navigate to applications folder
    4. find Sublime Text and right click so you get a pulldown menu
    5. Click on Show Package Content
    6. Open up Content/SharedSupport/bin
    7. Copy the subl file
    8. Paste it in the bin folder in the usr folder we found earlier
    9. In the terminal type in subl --------------this should open Sublime Text

    Make sure that it gets copied and it's not a shortcut. If you do have a problem, view the usr/bin folder as icons and paste the subl in a empty area in the folder. It should not have a shortcut arrow in the icon image.

    Clear dropdownlist with JQuery

    I tried both .empty() as well as .remove() for my dropdown and both were slow. Since I had almost 4,000 options there.

    I used .html("") which is much faster in my condition.
    Which is below

      $(dropdown).html("");
    

    An URL to a Windows shared folder

    File protocol URIs are like this

    file://[HOST]/[PATH]

    that's why you often see file URLs like this (3 slashes) file:///c:\path...

    So if the host is server01, you want

    file://server01/folder/path....

    This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.

    What is the hamburger menu icon called and the three vertical dots icon called?

    We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.

    RAW POST using cURL in PHP

    Implementation with Guzzle library:

    use GuzzleHttp\Client;
    use GuzzleHttp\RequestOptions;
    
    $httpClient = new Client();
    
    $response = $httpClient->post(
        'https://postman-echo.com/post',
        [
            RequestOptions::BODY => 'POST raw request content',
            RequestOptions::HEADERS => [
                'Content-Type' => 'application/x-www-form-urlencoded',
            ],
        ]
    );
    
    echo(
        $response->getBody()->getContents()
    );
    

    PHP CURL extension:

    $curlHandler = curl_init();
    
    curl_setopt_array($curlHandler, [
        CURLOPT_URL => 'https://postman-echo.com/post',
        CURLOPT_RETURNTRANSFER => true,
    
        /**
         * Specify POST method
         */
        CURLOPT_POST => true,
    
        /**
         * Specify request content
         */
        CURLOPT_POSTFIELDS => 'POST raw request content',
    ]);
    
    $response = curl_exec($curlHandler);
    
    curl_close($curlHandler);
    
    echo($response);
    

    Source code

    Value does not fall within the expected range

    This might be due to the fact that you are trying to add a ListBoxItem with a same name to the page.

    If you want to refresh the content of the listbox with the newly retrieved values you will have to first manually remove the content of the listbox other wise your loop will try to create lb_1 again and add it to the same list.

    Look at here for a similar problem that occured Silverlight: Value does not fall within the expected range exception

    Cheers,

    How to know elastic search installed version from kibana?

    You can Try this, After starting Service of elasticsearch Type below line in your browser.

             localhost:9200
    
         It will give Output Something like that,
    
              {
               "status" : 200,
               "name" : "Hypnotia",
               "cluster_name" : "elasticsearch",
               "version" : {
               "number" : "1.7.1",
               "build_hash" : "b88f43fc40b0bcd7f173a1f9ee2e97816de80b19",
               "build_timestamp" : "2015-07-29T09:54:16Z",
               "build_snapshot" : false,
                "lucene_version" : "4.10.4"
                      },
                "tagline" : "You Know, for Search"
                      }
    

    entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

    I had the same problem and I could solve making a new instance of the object that I was trying to Update. Then I passed that object to my reposotory.

    ASP.NET Core Web API Authentication

    Now, after I was pointed in the right direction, here's my complete solution:

    This is the middleware class which is executed on every incoming request and checks if the request has the correct credentials. If no credentials are present or if they are wrong, the service responds with a 401 Unauthorized error immediately.

    public class AuthenticationMiddleware
    {
        private readonly RequestDelegate _next;
    
        public AuthenticationMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task Invoke(HttpContext context)
        {
            string authHeader = context.Request.Headers["Authorization"];
            if (authHeader != null && authHeader.StartsWith("Basic"))
            {
                //Extract credentials
                string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
                Encoding encoding = Encoding.GetEncoding("iso-8859-1");
                string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));
    
                int seperatorIndex = usernamePassword.IndexOf(':');
    
                var username = usernamePassword.Substring(0, seperatorIndex);
                var password = usernamePassword.Substring(seperatorIndex + 1);
    
                if(username == "test" && password == "test" )
                {
                    await _next.Invoke(context);
                }
                else
                {
                    context.Response.StatusCode = 401; //Unauthorized
                    return;
                }
            }
            else
            {
                // no authorization header
                context.Response.StatusCode = 401; //Unauthorized
                return;
            }
        }
    }
    

    The middleware extension needs to be called in the Configure method of the service Startup class

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
    
        app.UseMiddleware<AuthenticationMiddleware>();
    
        app.UseMvc();
    }
    

    And that's all! :)

    A very good resource for middleware in .Net Core and authentication can be found here: https://www.exceptionnotfound.net/writing-custom-middleware-in-asp-net-core-1-0/

    How to increment datetime by custom months in python without using library

    def month_sub(year, month, sub_month):
        result_month = 0
        result_year = 0
        if month > (sub_month % 12):
            result_month = month - (sub_month % 12)
            result_year = year - (sub_month / 12)
        else:
            result_month = 12 - (sub_month % 12) + month
            result_year = year - (sub_month / 12 + 1)
        return (result_year, result_month)
    
    def month_add(year, month, add_month):
        return month_sub(year, month, -add_month)
    
    >>> month_add(2015, 7, 1)                        
    (2015, 8)
    >>> month_add(2015, 7, 20)
    (2017, 3)
    >>> month_add(2015, 7, 12)
    (2016, 7)
    >>> month_add(2015, 7, 24)
    (2017, 7)
    >>> month_add(2015, 7, -2)
    (2015, 5)
    >>> month_add(2015, 7, -12)
    (2014, 7)
    >>> month_add(2015, 7, -13)
    (2014, 6)
    

    Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"

    Solution for HTTP Status 404 in NetBeans IDE: Right click on your project and go to your project properties, then click on run, then input your project relative URL like index.jsp.

    1. Project->Properties
    2. Click on Run
    3. Relative URL:/index.jsp (Select your project root URL)

    enter image description here

    How to access shared folder without giving username and password

    You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

    The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

    Calculating Time Difference

    You cannot calculate the differences separately ... what difference would that yield for 7:59 and 8:00 o'clock? Try

    import time
    time.time()
    

    which gives you the seconds since the start of the epoch.

    You can then get the intermediate time with something like

    timestamp1 = time.time()
    # Your code here
    timestamp2 = time.time()
    print "This took %.2f seconds" % (timestamp2 - timestamp1)
    

    Computing cross-correlation function?

    For 1D array, numpy.correlate is faster than scipy.signal.correlate, under different sizes, I see a consistent 5x peformance gain using numpy.correlate. When two arrays are of similar size (the bright line connecting the diagonal), the performance difference is even more outstanding (50x +).

    # a simple benchmark
    res = []
    for x in range(1, 1000):
        list_x = []
        for y in range(1, 1000): 
    
            # generate different sizes of series to compare
            l1 = np.random.choice(range(1, 100), size=x)
            l2 = np.random.choice(range(1, 100), size=y)
    
            time_start = datetime.now()
            np.correlate(a=l1, v=l2)
            t_np = datetime.now() - time_start
    
            time_start = datetime.now()
            scipy.signal.correlate(in1=l1, in2=l2)
            t_scipy = datetime.now() - time_start
    
            list_x.append(t_scipy / t_np)
        res.append(list_x)
    plt.imshow(np.matrix(res))
    

    enter image description here

    As default, scipy.signal.correlate calculates a few extra numbers by padding and that might explained the performance difference.

    >> l1 = [1,2,3,2,1,2,3]
    >> l2 = [1,2,3]
    >> print(numpy.correlate(a=l1, v=l2))
    >> print(scipy.signal.correlate(in1=l1, in2=l2))
    
    [14 14 10 10 14]
    [ 3  8 14 14 10 10 14  8  3]  # the first 3 is [0,0,1]dot[1,2,3]
    

    How to Convert an int to a String?

    Did you try:

    text_Rate.setText(String.valueOf(sdRate));
    

    Delete specific line from a text file?

    I cared about the file's original end line characters ("\n" or "\r\n") and wanted to maintain them in the output file (not overwrite them with what ever the current environment's char(s) are like the other answers appear to do). So I wrote my own method to read a line without removing the end line chars then used it in my DeleteLines method (I wanted the option to delete multiple lines, hence the use of a collection of line numbers to delete).

    DeleteLines was implemented as a FileInfo extension and ReadLineKeepNewLineChars a StreamReader extension (but obviously you don't have to keep it that way).

    public static class FileInfoExtensions
    {
        public static FileInfo DeleteLines(this FileInfo source, ICollection<int> lineNumbers, string targetFilePath)
        {
            var lineCount = 1;
    
            using (var streamReader = new StreamReader(source.FullName))
            {
                using (var streamWriter = new StreamWriter(targetFilePath))
                {
                    string line;
    
                    while ((line = streamReader.ReadLineKeepNewLineChars()) != null)
                    {
                        if (!lineNumbers.Contains(lineCount))
                        {
                            streamWriter.Write(line);
                        }
    
                        lineCount++;
                    }
                }
            }
    
            return new FileInfo(targetFilePath);
        }
    }
    
    public static class StreamReaderExtensions
    {
        private const char EndOfFile = '\uffff';
    
        /// <summary>
        /// Reads a line, similar to ReadLine method, but keeps any
        /// new line characters (e.g. "\r\n" or "\n").
        /// </summary>
        public static string ReadLineKeepNewLineChars(this StreamReader source)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));
    
            char ch = (char)source.Read();
    
            if (ch == EndOfFile)
                return null;
    
            var sb = new StringBuilder();
    
            while (ch !=  EndOfFile)
            {
                sb.Append(ch);
    
                if (ch == '\n')
                    break;
    
                ch = (char) source.Read();
            }
    
            return sb.ToString();
        }
    }
    

    Any reason to prefer getClass() over instanceof when generating .equals()?

    If you use instanceof, making your equals implementation final will preserve the symmetry contract of the method: x.equals(y) == y.equals(x). If final seems restrictive, carefully examine your notion of object equivalence to make sure that your overriding implementations fully maintain the contract established by the Object class.

    How to parse JSON boolean value?

    You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:

    boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))
    

    If it is a String, you could do this:

    boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))
    

    Rails migration for change column

    As I found by the previous answers, three steps are needed to change the type of a column:

    Step 1:

    Generate a new migration file using this code:

    rails g migration sample_name_change_column_type
    

    Step 2:

    Go to /db/migrate folder and edit the migration file you made. There are two different solutions.

    1. def change
          change_column(:table_name, :column_name, :new_type)
      end
      

    2.

        def up
            change_column :table_name, :column_name, :new_type
        end
    
        def down
            change_column :table_name, :column_name, :old_type
        end
    

    Step 3:

    Don't forget to do this command:

    rake db:migrate
    

    I have tested this solution for Rails 4 and it works well.

    LIMIT 10..20 in SQL Server

    Use all SQL server: ;with tbl as (SELECT ROW_NUMBER() over(order by(select 1)) as RowIndex,* from table) select top 10 * from tbl where RowIndex>=10

    How to upload files on server folder using jsp

    public class FileUploadExample extends HttpServlet {
         protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
                boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    
                if (isMultipart) {
                    // Create a factory for disk-based file items
                    FileItemFactory factory = new DiskFileItemFactory();
    
                    // Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(factory);
    
                    try {
                        // Parse the request
                        List items = upload.parseRequest(request);
                        Iterator iterator = items.iterator();
                        while (iterator.hasNext()) {
                            FileItem item = (FileItem) iterator.next();
                            if (!item.isFormField()) {
                                String fileName = item.getName();    
                                String root = getServletContext().getRealPath("/");
                                File path = new File(root + "/uploads");
                                if (!path.exists()) {
                                    boolean status = path.mkdirs();
                                }
    
                                File uploadedFile = new File(path + "/" + fileName);
                                System.out.println(uploadedFile.getAbsolutePath());
                                item.write(uploadedFile);
                            }
                        }
                    } catch (FileUploadException e) {
                        e.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    
    }
    

    Check element exists in array

    `e` in ['a', 'b', 'c']  # evaluates as False
    `b` in ['a', 'b', 'c']  # evaluates as True
    

    EDIT: With the clarification, new answer:

    Note that PHP arrays are vastly different from Python's, combining arrays and dicts into one confused structure. Python arrays always have indices from 0 to len(arr) - 1, so you can check whether your index is in that range. try/catch is a good way to do it pythonically, though.

    If you're asking about the hash functionality of PHP "arrays" (Python's dict), then my previous answer still kind of stands:

    `baz` in {'foo': 17, 'bar': 19}  # evaluates as False
    `foo` in {'foo': 17, 'bar': 19}  # evaluates as True
    

    HTTP post XML data in C#

    AlliterativeAlice's example helped me tremendously. In my case, though, the server I was talking to didn't like having single quotes around utf-8 in the content type. It failed with a generic "Server Error" and it took hours to figure out what it didn't like:

    request.ContentType = "text/xml; encoding=utf-8";
    

    Java: Integer equals vs. ==

    Besides these given great answers, What I have learned is that:

    NEVER compare objects with == unless you intend to be comparing them by their references.

    Check if character is number?

    This function works for all test cases that i could find. It's also faster than:

    function isNumeric (n) {
      if (!isNaN(parseFloat(n)) && isFinite(n) && !hasLeading0s(n)) {
        return true;
      }
      var _n = +n;
      return _n === Infinity || _n === -Infinity;
    }
    

    _x000D_
    _x000D_
    var isIntegerTest = /^\d+$/;_x000D_
    var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];_x000D_
    _x000D_
    function hasLeading0s(s) {_x000D_
      return !(typeof s !== 'string' ||_x000D_
        s.length < 2 ||_x000D_
        s[0] !== '0' ||_x000D_
        !isDigitArray[s[1]] ||_x000D_
        isIntegerTest.test(s));_x000D_
    }_x000D_
    var isWhiteSpaceTest = /\s/;_x000D_
    _x000D_
    function fIsNaN(n) {_x000D_
      return !(n <= 0) && !(n > 0);_x000D_
    }_x000D_
    _x000D_
    function isNumber(s) {_x000D_
      var t = typeof s;_x000D_
      if (t === 'number') {_x000D_
        return (s <= 0) || (s > 0);_x000D_
      } else if (t === 'string') {_x000D_
        var n = +s;_x000D_
        return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));_x000D_
      } else if (t === 'object') {_x000D_
        return !(!(s instanceof Number) || fIsNaN(+s));_x000D_
      }_x000D_
      return false;_x000D_
    }_x000D_
    _x000D_
    function testRunner(IsNumeric) {_x000D_
      var total = 0;_x000D_
      var passed = 0;_x000D_
      var failedTests = [];_x000D_
    _x000D_
      function test(value, result) {_x000D_
        total++;_x000D_
        if (IsNumeric(value) === result) {_x000D_
          passed++;_x000D_
        } else {_x000D_
          failedTests.push({_x000D_
            value: value,_x000D_
            expected: result_x000D_
          });_x000D_
        }_x000D_
      }_x000D_
      // true_x000D_
      test(0, true);_x000D_
      test(1, true);_x000D_
      test(-1, true);_x000D_
      test(Infinity, true);_x000D_
      test('Infinity', true);_x000D_
      test(-Infinity, true);_x000D_
      test('-Infinity', true);_x000D_
      test(1.1, true);_x000D_
      test(-0.12e-34, true);_x000D_
      test(8e5, true);_x000D_
      test('1', true);_x000D_
      test('0', true);_x000D_
      test('-1', true);_x000D_
      test('1.1', true);_x000D_
      test('11.112', true);_x000D_
      test('.1', true);_x000D_
      test('.12e34', true);_x000D_
      test('-.12e34', true);_x000D_
      test('.12e-34', true);_x000D_
      test('-.12e-34', true);_x000D_
      test('8e5', true);_x000D_
      test('0x89f', true);_x000D_
      test('00', true);_x000D_
      test('01', true);_x000D_
      test('10', true);_x000D_
      test('0e1', true);_x000D_
      test('0e01', true);_x000D_
      test('.0', true);_x000D_
      test('0.', true);_x000D_
      test('.0e1', true);_x000D_
      test('0.e1', true);_x000D_
      test('0.e00', true);_x000D_
      test('0xf', true);_x000D_
      test('0Xf', true);_x000D_
      test(Date.now(), true);_x000D_
      test(new Number(0), true);_x000D_
      test(new Number(1e3), true);_x000D_
      test(new Number(0.1234), true);_x000D_
      test(new Number(Infinity), true);_x000D_
      test(new Number(-Infinity), true);_x000D_
      // false_x000D_
      test('', false);_x000D_
      test(' ', false);_x000D_
      test(false, false);_x000D_
      test('false', false);_x000D_
      test(true, false);_x000D_
      test('true', false);_x000D_
      test('99,999', false);_x000D_
      test('#abcdef', false);_x000D_
      test('1.2.3', false);_x000D_
      test('blah', false);_x000D_
      test('\t\t', false);_x000D_
      test('\n\r', false);_x000D_
      test('\r', false);_x000D_
      test(NaN, false);_x000D_
      test('NaN', false);_x000D_
      test(null, false);_x000D_
      test('null', false);_x000D_
      test(new Date(), false);_x000D_
      test({}, false);_x000D_
      test([], false);_x000D_
      test(new Int8Array(), false);_x000D_
      test(new Uint8Array(), false);_x000D_
      test(new Uint8ClampedArray(), false);_x000D_
      test(new Int16Array(), false);_x000D_
      test(new Uint16Array(), false);_x000D_
      test(new Int32Array(), false);_x000D_
      test(new Uint32Array(), false);_x000D_
      test(new BigInt64Array(), false);_x000D_
      test(new BigUint64Array(), false);_x000D_
      test(new Float32Array(), false);_x000D_
      test(new Float64Array(), false);_x000D_
      test('.e0', false);_x000D_
      test('.', false);_x000D_
      test('00e1', false);_x000D_
      test('01e1', false);_x000D_
      test('00.0', false);_x000D_
      test('01.05', false);_x000D_
      test('00x0', false);_x000D_
      test(new Number(NaN), false);_x000D_
      test(new Number('abc'), false);_x000D_
      console.log('Passed ' + passed + ' of ' + total + ' tests.');_x000D_
      if (failedTests.length > 0) console.log({_x000D_
        failedTests: failedTests_x000D_
      });_x000D_
    }_x000D_
    testRunner(isNumber)
    _x000D_
    _x000D_
    _x000D_

    Where is NuGet.Config file located in Visual Studio project?

    If you use proxy, you will have to edit the Nuget.config file.

    In Windows 7 and 10, this file is in the path:
    C:\Users\YouUser\AppData\Roaming\NuGet.

    Include the setting:

    <config>
      <add key = "http_proxy" value = "http://Youproxy:8080" />
      <add key = "http_proxy.user" value = "YouProxyUser" />
    </config>
    

    Microsoft SQL Server 2005 service fails to start

    While that error message is on the screen (before the rollback begins) go to Control Panel -> Administrative Tools -> Services and see if the service is actually installed. Also check what account it is using to run as. If it's not using Local System, then double and triple check that the account it's using has rights to the program directory where MS SQL installed to.

    How to customize the background color of a UITableViewCell?

    vlado.grigorov has some good advice - the best way is to create a backgroundView, and give that a colour, setting everything else to the clearColor. Also, I think that way is the only way to correctly clear the colour (try his sample - but set 'clearColor' instead of 'yellowColor'), which is what I was trying to do.

    How to embed small icon in UILabel

     func atributedLabel(str: String, img: UIImage)->NSMutableAttributedString
    {   let iconsSize = CGRect(x: 0, y: -2, width: 16, height: 16)
        let attributedString = NSMutableAttributedString()
        let attachment = NSTextAttachment()
        attachment.image = img
        attachment.bounds = iconsSize
        attributedString.append(NSAttributedString(attachment: attachment))
        attributedString.append(NSAttributedString(string: str))
    
        return attributedString
    } 
    

    You can use this function to add images or small icons to the label

    PHP, getting variable from another php-file

    using include 'page1.php' in second page is one option but it can generate warnings and errors of undefined variables.
    Three methods by which you can use variables of one php file in another php file:

    • use session to pass variable from one page to another
      method:
      first you have to start the session in both the files using php command

      sesssion_start();
      then in first file consider you have one variable
      $x='var1';

      now assign value of $x to a session variable using this:
      $_SESSION['var']=$x;
      now getting value in any another php file:
      $y=$_SESSION['var'];//$y is any declared variable

    • using get method and getting variables on clicking a link
      method

      <a href="page2.php?variable1=value1&variable2=value2">clickme</a>
      getting values in page2.php file by $_GET function:
      $x=$_GET['variable1'];//value1 be stored in $x
      $y=$_GET['variable2'];//vale2 be stored in $y

    • if you want to pass variable value using button then u can use it by following method:

      $x='value1'
      <input type="submit" name='btn1' value='.$x.'/>
      in second php
      $var=$_POST['btn1'];

    Hidden Features of Xcode

    Use AppKiDo to browse the documentation.

    Use Accessorizer for a bunch of mundane, repetitive tasks in Xcode.

    How to load external scripts dynamically in Angular?

    This might work. This Code dynamically appends the <script> tag to the head of the html file on button clicked.

    const url = 'http://iknow.com/this/does/not/work/either/file.js';
    
    export class MyAppComponent {
        loadAPI: Promise<any>;
    
        public buttonClicked() {
            this.loadAPI = new Promise((resolve) => {
                console.log('resolving promise...');
                this.loadScript();
            });
        }
    
        public loadScript() {
            console.log('preparing to load...')
            let node = document.createElement('script');
            node.src = url;
            node.type = 'text/javascript';
            node.async = true;
            node.charset = 'utf-8';
            document.getElementsByTagName('head')[0].appendChild(node);
        }
    }
    

    Javascript : get <img> src and set as variable?

    in this situation, you would grab the element by its id using getElementById and then just use .src

    var youtubeimgsrc = document.getElementById("youtubeimg").src;
    

    Java ArrayList - how can I tell if two lists are equal, order not mattering?

    If the cardinality of items doesn't matter (meaning: repeated elements are considered as one), then there is a way to do this without having to sort:

    boolean result = new HashSet<>(listA).equals(new HashSet<>(listB));

    This will create a Set out of each List, and then use HashSet's equals method which (of course) disregards ordering.

    If cardinality matters, then you must confine yourself to facilities provided by List; @jschoen's answer would be more fitting in that case.

    How to get an object's property's value by property name?

    Try this :

    $obj = @{
        SomeProp = "Hello"
    }
    
    Write-Host "Property Value is $($obj."SomeProp")"
    

    C compiling - "undefined reference to"?

    seems you need to link with the obj file that implements tolayer5()

    Update: your function declaration doesn't match the implementation:

          void tolayer5(int AorB, struct msg msgReceived)
          void tolayer5(int, char data[])
    

    So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().

    Angular2 - Input Field To Accept Only Numbers

    Well Thanks to JeanPaul A. and rdanielmurphy. I had made my own Custom directive for limiting input field to number only. Also added the max and min input attributes. Will work in angular 7 also.

    Angular

        import { Directive, ElementRef, Input, HostListener } from '@angular/core';
    
    @Directive({
      selector: '[appNumberOnly]'
    })
    export class NumberOnlyDirective {
      // Allow decimal numbers. The \. is only allowed once to occur
      private regex: RegExp = new RegExp(/^[0-9]+(\.[0-9]*){0,1}$/g);
    
      // Allow key codes for special events. Reflect :
      // Backspace, tab, end, home
      private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home'];
      constructor(private el: ElementRef) { }
    
      @Input() maxlength: number;
      @Input() min: number;
      @Input() max: number;
    
      @HostListener('keydown', ['$event'])
      onKeyDown(event: KeyboardEvent) {
        // Allow Backspace, tab, end, and home keys
        if (this.specialKeys.indexOf(event.key) !== -1) {
          return;
        }
    
        // Do not use event.keycode this is deprecated.
        // See: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
        const current: string = this.el.nativeElement.value;
    
        // We need this because the current value on the DOM element
        // is not yet updated with the value from this event
        const next: string = current.concat(event.key);
        if (next && !String(next).match(this.regex) || (this.maxlength && next.length > this.maxlength) ||
          (this.min && +next < this.min) ||
          (this.max && +next >= this.max)) {
          event.preventDefault();
        }
      }
    
      @HostListener('paste', ['$event']) onPaste(event) {
        // Don't allow pasted text that contains non-numerics
        const pastedText = (event.originalEvent || event).clipboardData.getData('text/plain');
    
        if (pastedText) {
          const regEx = new RegExp('^[0-9]*$');
          if (!regEx.test(pastedText) || (this.maxlength && pastedText.length > this.maxlength) ||
            (this.min && +pastedText < this.min) ||
            (this.max && +pastedText >= this.max)) {
            event.preventDefault();
          }
        }
      }
    
    }
    

    HTML

    <input type="text" class="text-area" [(ngModel)]="itemName" maxlength="3" appNumberOnly />
    

    How can I add reflection to a C++ application?

    What are you trying to do with reflection?
    You can use the Boost type traits and typeof libraries as a limited form of compile-time reflection. That is, you can inspect and modify the basic properties of a type passed to a template.

    how to remove "," from a string in javascript

    You can try something like:

    var str = "a,d,k";
    str.replace(/,/g, "");
    

    How to load a resource from WEB-INF directory of a web archive

    Use the getResourceAsStream() method on the ServletContext object, e.g.

    servletContext.getResourceAsStream("/WEB-INF/myfile");
    

    How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet or from a JSP?

    EDITED: If you're inside a Servlet object, then call getServletContext(). If you're in JSP, use the predefined variable application.

    How to get position of a certain element in strings vector, to use it as an index in ints vector?

    To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

    ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();
    

    Now you need to check pos against Names.size() to see if it is out of bounds or not:

    if(pos >= Names.size()) {
        //old_name_ not found
    }
    

    vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

    Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

    ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));
    

    Unable to Connect to GitHub.com For Cloning

    You can try to clone using the HTTPS protocol. Terminal command:

    git clone https://github.com/RestKit/RestKit.git
    

    ModuleNotFoundError: No module named 'sklearn'

    SOLVED:

    The above did not help. Then I simply installed sklearn from within Jypyter-lab, even though sklearn 0.0 shows in 'pip list':

    !pip install sklearn
    import sklearn
    

    What I learned later is that pip installs, in my case, packages in a different folder than Jupyter. This can be seen by executing:

    import sys
    print(sys.path)
    

    Once from within Jupyter_lab notebook, and once from the command line using 'py notebook.py'.

    In my case Jupyter list of paths where subfolders of 'anaconda' whereas Python list where subfolders of c:\users[username]...

    How to convert from Hex to ASCII in JavaScript?

    I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:

    buf = Buffer.from(data, 'hex');
    l = Buffer.byteLength(buf,'hex');
    for (i=0; i<l; i++){
    
        char = buf.toString('hex', i, i+1);
        msgArray.push(char);
    
    }
    

    Then .join it

    message = msgArray.join('');
    

    then I created a hexToAscii function just like in @Delan Azabani's answer above...

    function hexToAscii(str){
        hexString = str;
        strOut = '';
            for (x = 0; x < hexString.length; x += 2) {
                strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
            }
        return strOut;    
    }
    

    then called the hexToAscii function on 'message'

    message = hexToAscii(message);
    

    This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted. Hope this helps someone else!

    urllib2 and json

    To read json response use json.loads(). Here is the sample.

    import json
    import urllib
    import urllib2
    
    post_params = {
        'foo' : bar
    }
    
    params = urllib.urlencode(post_params)
    response = urllib2.urlopen(url, params)
    json_response = json.loads(response.read())
    

    Set up Python simpleHTTPserver on Windows

    From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

    The following works for me:

    python -m http.server [<portNo>]
    

    Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

    What is REST call and how to send a REST call?

    REST is just a software architecture style for exposing resources.

    • Use HTTP methods explicitly.
    • Be stateless.
    • Expose directory structure-like URIs.
    • Transfer XML, JavaScript Object Notation (JSON), or both.

    A typical REST call to return information about customer 34456 could look like:

    http://example.com/customer/34456
    

    Have a look at the IBM tutorial for REST web services

    How to resolve this System.IO.FileNotFoundException

    I came across a similar situation after publishing a ClickOnce application, and one of my colleagues on a different domain reported that it fails to launch.

    To find out what was going on, I added a try catch statement inside the MainWindow method as @BradleyDotNET mentioned in one comment on the original post, and then published again.

    public MainWindow()
    {
        try
        {
            InitializeComponent();
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.ToString());
        }
    }
    

    Then my colleague reported to me the exception detail, and it was a missing reference of a third party framework dll file.

    Added the reference and problem solved.

    Received an invalid column length from the bcp client for colid 6

    I know this post is old but I ran into this same issue and finally figured out a solution to determine which column was causing the problem and report it back as needed. I determined that colid returned in the SqlException is not zero based so you need to subtract 1 from it to get the value. After that it is used as the index of the _sortedColumnMappings ArrayList of the SqlBulkCopy instance not the index of the column mappings that were added to the SqlBulkCopy instance. One thing to note is that SqlBulkCopy will stop on the first error received so this may not be the only issue but at least helps to figure it out.

    try
    {
        bulkCopy.WriteToServer(importTable);
        sqlTran.Commit();
    }    
    catch (SqlException ex)
    {
        if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))
        {
            string pattern = @"\d+";
            Match match = Regex.Match(ex.Message.ToString(), pattern);
            var index = Convert.ToInt32(match.Value) -1;
    
            FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);
            var sortedColumns = fi.GetValue(bulkCopy);
            var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);
    
            FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);
            var metadata = itemdata.GetValue(items[index]);
    
            var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
            var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
            throw new DataFormatException(String.Format("Column: {0} contains data with a length greater than: {1}", column, length));
        }
    
        throw;
    }

    What does \0 stand for?

    To the C language, '\0' means exactly the same thing as the integer constant 0 (same value zero, same type int).

    To someone reading the code, writing '\0' suggests that you're planning to use this particular zero as a character.

    Insert data to MySql DB and display if insertion is success or failure

    According to the book PHP and MySQL for Dynamic Web Sites (4th edition)

    Example:

    $r = mysqli_query($dbc, $q);
    

    For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.

    Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.

    Then how to test?

    While the mysqli_num_rows() function will return the number of rows generated by a SELECT query, mysqli_affected_rows() returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:

    $num = mysqli_affected_rows($dbc);
    

    Unlike mysqli_num_rows(), the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).

    Server configuration by allow_url_fopen=0 in

    THIS IS A VERY SIMPLE PROBLEM

    Here is the best method for solve this problem.

    Step 1 : Login to your cPanel (http://website.com/cpanel OR http://cpanel.website.com).

    Step 2 : SOFTWARE -> Select PHP Version

    Step 3 : Change Your Current PHP version : 5.6

    Step 3 : HIT 'Set as current' [ ENJOY ]

    ORA-00932: inconsistent datatypes: expected - got CLOB

    The same error occurs also when doing SELECT DISTINCT ..., <CLOB_column>, ....

    If this CLOB column contains values shorter than limit for VARCHAR2 in all the applicable rows you may use to_char(<CLOB_column>) or concatenate results of multiple calls to DBMS_LOB.SUBSTR(<CLOB_column>, ...).

    How To Run PHP From Windows Command Line in WAMPServer

    UPDATED After few research, best solution was to use that info another stackoverflow thread to avoid ctrl+z input and also from the scree output. So, instead of php -a you should use call "php.exe" -f NAMED_SCRIPT.php

    OLD Readline not possible under Windows, so none of existent php shells written in php will work. But there's a workaround using -a interactive mode.

    2 commmon problems here. You cannot see result until executes CTRL Z command to indicate the final of code/file like EOF. When you do, result in most cases is printed result and fast closed window. Anyway, you will be returned to cmd not the -a interactive mode.

    Save this content into a .bat file, and define your PHP PATH into Windows variables, or modify php.exe to "full path to exe" instead:

    ::
    :: PHP Shell launch wrapper
    ::
    @ECHO off
    call "php.exe" -a
    
    echo.
    echo.
    
    call "PHP Shell.bat"
    

    This is a simple Batch launching -a mode of php.exe. When it launchs php, stop script even no pause is wrote because is "into" the interactive waiting for input. When you hit CTRL Z, gets the SIGSTEP (next step) not the SIGSTOP (close, CTRL+C usually), then read the next intruction, wich is a recursive call to .bat itself. Because you're always into PHP -a mode, no exit command. You must use CTRL+C or hit the exit cross with mouse. (No alt+f4)

    You can also use "Bat to Exe" converter to easy use.

    Mongoose: Find, modify, save

    Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:

    User.update({username: oldUsername}, {
        username: newUser.username, 
        password: newUser.password, 
        rights: newUser.rights
    }, function(err, numberAffected, rawResponse) {
       //handle it
    })
    

    What is the difference between fastcgi and fpm?

    What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

    For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

    I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

    Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

    What's the whole point of "localhost", hosts and ports at all?

    Regarding you question about betterhost and such, see host; basically every IP address is a host.

    I suggest you start reading-up from host and only than go on to localhost (which is a type of host)

    Get MD5 hash of big files in Python

    A Python 2/3 portable solution

    To calculate a checksum (md5, sha1, etc.), you must open the file in binary mode, because you'll sum bytes values:

    To be py27/py3 portable, you ought to use the io packages, like this:

    import hashlib
    import io
    
    
    def md5sum(src):
        md5 = hashlib.md5()
        with io.open(src, mode="rb") as fd:
            content = fd.read()
            md5.update(content)
        return md5
    

    If your files are big, you may prefer to read the file by chunks to avoid storing the whole file content in memory:

    def md5sum(src, length=io.DEFAULT_BUFFER_SIZE):
        md5 = hashlib.md5()
        with io.open(src, mode="rb") as fd:
            for chunk in iter(lambda: fd.read(length), b''):
                md5.update(chunk)
        return md5
    

    The trick here is to use the iter() function with a sentinel (the empty string).

    The iterator created in this case will call o [the lambda function] with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

    If your files are really big, you may also need to display progress information. You can do that by calling a callback function which prints or logs the amount of calculated bytes:

    def md5sum(src, callback, length=io.DEFAULT_BUFFER_SIZE):
        calculated = 0
        md5 = hashlib.md5()
        with io.open(src, mode="rb") as fd:
            for chunk in iter(lambda: fd.read(length), b''):
                md5.update(chunk)
                calculated += len(chunk)
                callback(calculated)
        return md5
    

    :first-child not working as expected

    :first-child selects the first h1 if and only if it is the first child of its parent element. In your example, the ul is the first child of the div.

    The name of the pseudo-class is somewhat misleading, but it's explained pretty clearly here in the spec.

    jQuery's :first selector gives you what you're looking for. You can do this:

    $('.detail_container h1:first').css("color", "blue");

    Observable Finally on Subscribe

    I'm now using RxJS 5.5.7 in an Angular application and using finalize operator has a weird behavior for my use case since is fired before success or error callbacks.

    Simple example:

    // Simulate an AJAX callback...
    of(null)
      .pipe(
        delay(2000),
        finalize(() => {
          // Do some work after complete...
          console.log('Finalize method executed before "Data available" (or error thrown)');
        })
      )
      .subscribe(
          response => {
            console.log('Data available.');
          },
          err => {
            console.error(err);
          }
      );
    

    I have had to use the add medhod in the subscription to accomplish what I want. Basically a finally callback after the success or error callbacks are done. Like a try..catch..finally block or Promise.finally method.

    Simple example:

    // Simulate an AJAX callback...
    of(null)
      .pipe(
        delay(2000)
      )
      .subscribe(
          response => {
            console.log('Data available.');
          },
          err => {
            console.error(err);
          }
      );
      .add(() => {
        // Do some work after complete...
        console.log('At this point the success or error callbacks has been completed.');
      });
    

    Copying files from one directory to another in Java

    Not even that complicated and no imports required in Java 7:

    The renameTo( ) method changes the name of a file:

    public boolean renameTo( File destination)

    For example, to change the name of the file src.txt in the current working directory to dst.txt, you would write:

    File src = new File(" src.txt"); File dst = new File(" dst.txt"); src.renameTo( dst); 
    

    That's it.

    Reference:

    Harold, Elliotte Rusty (2006-05-16). Java I/O (p. 393). O'Reilly Media. Kindle Edition.

    Best implementation for Key Value Pair Data Structure?

    Just one thing to add to this (although I do think you have already had your question answered by others). In the interests of extensibility (since we all know it will happen at some point) you may want to check out the Composite Pattern This is ideal for working with "Tree-Like Structures"..

    Like I said, I know you are only expecting one sub-level, but this could really be useful for you if you later need to extend ^_^

    How to change Bootstrap's global default font size?

    In v4 change the SASS variable:

    $font-size-base: 1rem !default;
    

    "Line contains NULL byte" in CSV reader (Python)

    Turning my linux environment into a clean complete UTF-8 environment made the trick for me. Try the following in your command line:

    export LC_ALL=en_US.UTF-8
    export LANG=en_US.UTF-8
    export LANGUAGE=en_US.UTF-8
    

    node.js Error: connect ECONNREFUSED; response from server

    just run the following command in the node project

    npm install
    

    its worked for me

    how to import csv data into django models

    You want to use the csv module that is part of the python language and you should use Django's get_or_create method

     with open(path) as f:
            reader = csv.reader(f)
            for row in reader:
                _, created = Teacher.objects.get_or_create(
                    first_name=row[0],
                    last_name=row[1],
                    middle_name=row[2],
                    )
                # creates a tuple of the new object or
                # current object and a boolean of if it was created
    

    In my example the model teacher has three attributes first_name, last_name and middle_name.

    Django documentation of get_or_create method

    JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

    Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

    The for loop you specified is absolutely correct.

    Although i will do all the loops for you once again.

    int sum = 0;
    // for loop
    
    for (int i = 1; i<= 100; i++){
        sum = sum + i;
    }
    System.out.println(sum);
    
    // while loop
    
    sum = 0;
    int j = 1;
    
    while(j<=100){
        sum = sum + j;
        j++;
    }
    
    System.out.println(sum);
    
    // do while loop
    
    sum = 0;
    j = 1;
    
    do{
        sum = sum + j;
        j++;
    }
    while(j<=100);
    
    System.out.println(sum);
    

    In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

    How can I get the line number which threw exception?

    If you need the line number for more than just the formatted stack trace you get from Exception.StackTrace, you can use the StackTrace class:

    try
    {
        throw new Exception();
    }
    catch (Exception ex)
    {
        // Get stack trace for the exception with source file information
        var st = new StackTrace(ex, true);
        // Get the top stack frame
        var frame = st.GetFrame(0);
        // Get the line number from the stack frame
        var line = frame.GetFileLineNumber();
    }
    

    Note that this will only work if there is a pdb file available for the assembly.

    Firestore Getting documents id from collection

    For angular 8 and Firebase 6 you can use the option id field

          getAllDocs() {
               const ref = this.db.collection('items');
               return ref.valueChanges({idField: 'customIdName'});
          }
    

    this adds the Id of the document on the object with a specified key (customIdName)

    Remove blank values from array using C#

    If you are using .NET 3.5+ you could use LINQ (Language INtegrated Query).

    test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
    

    PHP fopen() Error: failed to open stream: Permission denied

    [function.fopen]: failed to open stream

    If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :

    allow_url_fopen = off
    should bee this 
    allow_url_fopen = On
    
    And add this line below it:
    allow_url_include = off
    should bee this 
    allow_url_include = on
    

    How to reverse a 'rails generate'

    rails destroy controller lalala
    rails destroy model yadayada
    rails destroy scaffold hohoho
    

    Rails 3.2 adds a new d shortcut to the command, so now you can write:

    rails d controller lalala
    rails d model yadayada
    rails d scaffold hohoho
    

    AngularJS passing data to $http.get request

    You can pass params directly to $http.get() The following works fine

    $http.get(user.details_path, {
        params: { user_id: user.id }
    });
    

    What's the difference between a mock & stub?

    Say you have a class named EmployeeService that you want to test and that has one dependency on an interface named EmployeeDao:

    public class EmployeeService{
       private EmployeeDao dao;
       public EmployeeService(Dao dao){this.dao = dao;}
    
       public String getEmployeeName(int id){
         Employee emp = bar.goToDatabaseAndBringTheEmployeeWithId(id);
         return emp != null?emp.getFullName:null;
       }
       //Further state and behavior
    }
    
    public interface EmployeeDao{
      Employee goToDatabaseAndBringTheEmployeeWithId(int id);
    }
    

    Inside your test class:

    public class EmployeeServiceTest{
       EmployeeService service;
       EmployeeDao mockDao = Mockito.mock(EmployeeDao.class);//Line 3
    
       @Before
       public void setUp(){
         service = new EmployeeService(mockDao);
       }
       //Tests
       //....
    }
    

    In the above test class in line 3, we say to the mocking framework (in this case Mockito) "Hey, Mockito, craft me an object that has the EmployeeDao functionality." The framework is going to create an object that has the method goToDatabaseAndBringTheEmployeeWithId but actually with no body. It's your job to instruct that mock what to do. This is a mock.

    But you could also create a class that implements the EmployeeDao interface and use it in the test class instead:

    public EmployeeDaoStub implements EmployeeDao{
       public Employee goToDatabaseAndBringTheEmployeeWithId(int id){
          //No trip to DB, just returning a dummy Employee object
          return new Employee("John","Woo","123 Lincoln str");
       }
    }
    

    Inside your test class this time using stub instead of a mock:

    public class EmployeeServiceTest{
       EmployeeService service;
       EmployeeDao daoStub = new EmployeeDaoStub();//Line 3
    
       @Before
       public void setUp(){
         service = new EmployeeService(daoStub);
       }
       //Tests
       //....
    }
    

    So to wrap it all, stubs are the classes that you create(or somebody else does) specifically to imitate some dependency just for the sake of having the desired state. Yes, as all the other people state, it's mostly about a state Whereas mocks are typically created by a mocking framework and you have no idea what its guts look like. But with stubs you know what class you're going to get: It's the one you created.

    Oh, btw, if your dependency is a class rather than an interface, you can just extend that class to create your stub.

    jQuery get the location of an element relative to window

        function trbl(e, relative) {
                var r = $(e).get(0).getBoundingClientRect(); relative = $(relative);
    
                return {
                        t : r.top    + relative['scrollTop'] (),
                        r : r.right  + relative['scrollLeft'](),
                        b : r.bottom + relative['scrollTop'] (),
                        l : r.left   + relative['scrollLeft']() 
    
                }
        }
    
        // Example
        trbl(e, window);
    

    Reading a file line by line in Go

    Example from this gist

    func readLine(path string) {
      inFile, err := os.Open(path)
      if err != nil {
         fmt.Println(err.Error() + `: ` + path)
         return
      }
      defer inFile.Close()
    
      scanner := bufio.NewScanner(inFile)
      for scanner.Scan() {
        fmt.Println(scanner.Text()) // the line
      }
    }
    

    but this gives an error when there is a line that larger than Scanner's buffer.

    When that happened, what I do is use reader := bufio.NewReader(inFile) create and concat my own buffer either using ch, err := reader.ReadByte() or len, err := reader.Read(myBuffer)

    Another way that I use (replace os.Stdin with file like above), this one concats when lines are long (isPrefix) and ignores empty lines:

    
    func readLines() []string {
      r := bufio.NewReader(os.Stdin)
      bytes := []byte{}
      lines := []string{}
      for {
        line, isPrefix, err := r.ReadLine()
        if err != nil {
          break
        }
        bytes = append(bytes, line...)
        if !isPrefix {
          str := strings.TrimSpace(string(bytes))
          if len(str) > 0 {
            lines = append(lines, str)
            bytes = []byte{}
          }
        }
      }
      if len(bytes) > 0 {
        lines = append(lines, string(bytes))
      }
      return lines
    }
    

    LINQ-to-SQL vs stored procedures?

    IMHO, RAD = LINQ, RUP = Stored Procs. I worked for a large Fortune 500 company for many years, at many levels including management, and frankly, I would never hire RUP developers to do RAD development. They are so siloed that they very limited knowledge of what to do at other levels of the process. With a siloed environment, it makes sense to give DBAs control over the data through very specific entry points, because others frankly don't know the best ways to accomplish data management.

    But large enterprises move painfully slow in the development arena, and this is extremely costly. There are times when you need to move faster to save both time and money, and LINQ provides that and more in spades.

    Sometimes I think that DBAs are biased against LINQ because they feel it threatens their job security. But that's the nature of the beast, ladies and gentlemen.

    How do you find what version of libstdc++ library is installed on your linux machine?

    To find which library is being used you could run

     $ /sbin/ldconfig -p | grep stdc++
        libstdc++.so.6 (libc6) => /usr/lib/libstdc++.so.6
    

    The list of compatible versions for libstdc++ version 3.4.0 and above is provided by

     $ strings /usr/lib/libstdc++.so.6 | grep LIBCXX
     GLIBCXX_3.4
     GLIBCXX_3.4.1
     GLIBCXX_3.4.2
     ...
    

    For earlier versions the symbol GLIBCPP is defined.

    The date stamp of the library is defined in a macro __GLIBCXX__ or __GLIBCPP__ depending on the version:

    // libdatestamp.cxx
    #include <cstdio>
    
    int main(int argc, char* argv[]){
    #ifdef __GLIBCPP__
        std::printf("GLIBCPP: %d\n",__GLIBCPP__);
    #endif
    #ifdef __GLIBCXX__
        std::printf("GLIBCXX: %d\n",__GLIBCXX__);
    #endif
       return 0;
    }
    
    $ g++ libdatestamp.cxx -o libdatestamp
    $ ./libdatestamp
    GLIBCXX: 20101208
    

    The table of datestamps of libstdc++ versions is listed in the documentation:

    Remove certain characters from a string

    One issue with REPLACE will be where city names contain the district name. You can use something like.

    SELECT SUBSTRING(O.Ort, LEN(C.CityName) + 2, 8000)
    FROM   dbo.tblOrtsteileGeo O
           JOIN dbo.Cities C
             ON C.foo = O.foo
    WHERE  O.GKZ = '06440004' 
    

    How to call a REST web service API from JavaScript?

    Without a doubt, the simplest method uses an invisible FORM element in HTML specifying the desired REST method. Then the arguments can be inserted into input type=hidden value fields using JavaScript and the form can be submitted from the button click event listener or onclick event using one line of JavaScript. Here is an example that assumes the REST API is in file REST.php:

    <body>
    <h2>REST-test</h2>
    <input type=button onclick="document.getElementById('a').submit();"
        value="Do It">
    <form id=a action="REST.php" method=post>
    <input type=hidden name="arg" value="val">
    </form>
    </body>
    

    Note that this example will replace the page with the output from page REST.php. I'm not sure how to modify this if you wish the API to be called with no visible effect on the current page. But it's certainly simple.

    Backporting Python 3 open(encoding="utf-8") to Python 2

    Not a general answer, but may be useful for the specific case where you are happy with the default python 2 encoding, but want to specify utf-8 for python 3:

    if sys.version_info.major > 2:
        do_open = lambda filename: open(filename, encoding='utf-8')
    else:
        do_open = lambda filename: open(filename)
    
    with do_open(filename) as file:
        pass
    

    Installing tensorflow with anaconda in windows

    • Install Anaconda for Python 3.5 - Can install from here for 64 bit windows

    • Then install TensorFlow from here

    (I tried previously with Anaconda for Python 3.6 but failed even after creating Conda env for Python3.5)

    Additionally if you want to run a Jupyter Notebook and use TensorFlow in it. Use following steps.

    Change to TensorFlow env:

    C: > activate tensorflow
    (tensorflow) C: > pip install jupyter notebook
    

    Once installed, you can launch Jupyter Notebook and test

    (tensorflow) C: > jupyter notebook
    

    C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

    You do not need any client side code if doing this is ASP.NET. The example below is a boostrap input box with a search button with an fontawesome icon.

    You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

    In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

    <asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
    <asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
    <span class="input-group-btn">
        <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
    </span></asp:Panel>
    

    MongoDB relationships: embed or reference?

    Actually, I'm quite curious why nobody spoke about the UML specifications. A rule of thumb is that if you have an aggregation, then you should use references. But if it is a composition, then the coupling is stronger, and you should use embedded documents.

    And you will quickly understand why it is logical. If an object can exist independently of the parent, then you will want to access it even if the parent doesn't exist. As you just can't embed it in a non-existing parent, you have to make it live in it's own data structure. And if a parent exist, just link them together by adding a ref of the object in the parent.

    Don't really know what is the difference between the two relationships ? Here is a link explaining them: Aggregation vs Composition in UML

    Form inside a table

    Use the "form" attribute, if you want to save your markup:

    <form method="GET" id="my_form"></form>
    
    <table>
        <tr>
            <td>
                <input type="text" name="company" form="my_form" />
                <button type="button" form="my_form">ok</button>
            </td>
        </tr>
    </table>
    

    (*Form fields outside of the < form > tag)

    What is the easiest/best/most correct way to iterate through the characters of a string in Java?

    Elaborating on this answer and this answer.

    Above answers point out the problem of many of the solutions here which don't iterate by code point value -- they would have trouble with any surrogate chars. The java docs also outline the issue here (see "Unicode Character Representations"). Anyhow, here's some code that uses some actual surrogate chars from the supplementary Unicode set, and converts them back to a String. Note that .toChars() returns an array of chars: if you're dealing with surrogates, you'll necessarily have two chars. This code should work for any Unicode character.

        String supplementary = "Some Supplementary: ";
        supplementary.codePoints().forEach(cp -> 
                System.out.print(new String(Character.toChars(cp))));
    

    Determine if JavaScript value is an "integer"?

    Use jQuery's IsNumeric method.

    http://api.jquery.com/jQuery.isNumeric/

    if ($.isNumeric(id)) {
       //it's numeric
    }
    

    CORRECTION: that would not ensure an integer. This would:

    if ( (id+"").match(/^\d+$/) ) {
       //it's all digits
    }
    

    That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works

    PG::ConnectionBad - could not connect to server: Connection refused

    I had to reinstall my postgres, great instructions outlined here: https://medium.com/@zowoodward/effectively-uninstall-and-reinstall-psql-with-homebrew-on-osx-fabbc45c5d9d

    Then I had to create postgres user: /usr/local/opt/postgres/bin/createuser -s postgres

    This approach will clobber all of your local data so please back up your data if needed.

    Spring cron expression for every after 30 minutes

    Graphically, the cron syntax for Quarz is (source):

    +-------------------- second (0 - 59)
    |  +----------------- minute (0 - 59)
    |  |  +-------------- hour (0 - 23)
    |  |  |  +----------- day of month (1 - 31)
    |  |  |  |  +-------- month (1 - 12)
    |  |  |  |  |  +----- day of week (0 - 6) (Sunday=0 or 7)
    |  |  |  |  |  |  +-- year [optional]
    |  |  |  |  |  |  |
    *  *  *  *  *  *  * command to be executed 
    

    So if you want to run a command every 30 minutes you can say either of these:

    0 0/30 * * * * ?
    0 0,30 * * * * ?
    

    You can check crontab expressions using either of these:

    • crontab.guru — (disclaimer: I am not related to that page at all, only that I find it very useful). This page uses UNIX style of cron that does not have seconds in it, while Spring does as the first field.
    • Cron Expression Generator & Explainer - Quartz — cron formatter, allowing seconds also.

    How to parse JSON in Java

    Use minimal-json which is very fast and easy to use. You can parse from String obj and Stream.

    Sample data:

    {
      "order": 4711,
      "items": [
        {
          "name": "NE555 Timer IC",
          "cat-id": "645723",
          "quantity": 10,
        },
        {
          "name": "LM358N OpAmp IC",
          "cat-id": "764525",
          "quantity": 2
        }
      ]
    }
    

    Parsing:

    JsonObject object = Json.parse(input).asObject();
    int orders = object.get("order").asInt();
    JsonArray items = object.get("items").asArray();
    

    Creating JSON:

    JsonObject user = Json.object().add("name", "Sakib").add("age", 23);
    

    Maven:

    <dependency>
      <groupId>com.eclipsesource.minimal-json</groupId>
      <artifactId>minimal-json</artifactId>
      <version>0.9.4</version>
    </dependency>
    

    How do I convert hex to decimal in Python?

    If by "hex data" you mean a string of the form

    s = "6a48f82d8e828ce82b82"
    

    you can use

    i = int(s, 16)
    

    to convert it to an integer and

    str(i)
    

    to convert it to a decimal string.

    How to change current Theme at runtime in Android

    recreate() (as mentioned by TPReal) will only restart current activity, but the previous activities will still be in back stack and theme will not be applied to them.

    So, another solution for this problem is to recreate the task stack completely, like this:

        TaskStackBuilder.create(getActivity())
                .addNextIntent(new Intent(getActivity(), MainActivity.class))
                .addNextIntent(getActivity().getIntent())
                .startActivities();
    

    EDIT:

    Just put the code above after you perform changing of theme on the UI or somewhere else. All your activities should have method setTheme() called before onCreate(), probably in some parent activity. It is also a normal approach to store the theme chosen in SharedPreferences, read it and then set using setTheme() method.

    Rails 3: I want to list all paths defined in my rails application

    rake routes | grep <specific resource name>
    

    displays resource specific routes, if it is a pretty long list of routes.

    How can I get the domain name of my site within a Django template?

    I think what you want is to have access to the request context, see RequestContext.

    Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

    Thanks to the answer by @Aurelien Porte. Here is my solution

    Cause of this issue:-

    1. a UITableView doesn't like to have a header with a height of 0.0. If what's you're trying to do is to have a header with a height of 0, you can jump to the solution.
    2. even if later you assign a non 0.0 height to your header, a UITableView doesn't like to be assigned a header with a height of 0.0 at first.

    In ViewDidLoad:-

    self.edgesForExtendedLayout = UIRectEdge.None
    
    self.automaticallyAdjustsScrollViewInsets = false
    

    No Need For Something Like This :-

    self.myTableview.contentInset = UIEdgeInsetsMake(-56, 0, 0, 0)
    

    In heightForHeaderInSection delegate:-

    if section == 0
        {
            return 1
        }
        else
        {
            return 40; // your other headers height value
        }
    

    In viewForHeaderInSection delegate :-

    if section == 0 
    {  
       // Note CGFloat.min for swift
       // For Objective-c CGFLOAT_MIN 
       let headerView = UIView.init(frame: CGRectMake(0.0, 0.0, self.myShaadiTableview.bounds.size.width, CGFloat.min)) 
       return headerView
    }
    else
    { 
       // Construct your other headers here 
    }
    

    Download pdf file using jquery ajax

    For those looking a more modern approach, you can use the fetch API. The following example shows how to download a PDF file. It is easily done with the following code.

    fetch(url, {
        body: JSON.stringify(data),
        method: 'POST',
        headers: {
            'Content-Type': 'application/json; charset=utf-8'
        },
    })
    .then(response => response.blob())
    .then(response => {
        const blob = new Blob([response], {type: 'application/pdf'});
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "file.pdf";
        document.body.appendChild(a);
        a.click();
    })
    

    I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

    Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

    Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

    What are the advantages and disadvantages of recursion?

    To start:

    Pros:

    • It is the unique way of implementing a variable number of nested loops (and the only elegant way of implementing a big constant number of nested loops).

    Cons:

    • Recursive methods will often throw a StackOverflowException when processing big sets. Recursive loops don't have this problem though.

    Make an image width 100% of parent div, but not bigger than its own width

    I was also having the same problem, but I set the height value in my CSS to auto and that fixed my problem. Also, don't forget to do the display property.

      #image {
          height: auto;
          width: auto;
          max-height: 550px;
          max-width: 1200px;
          margin-left: auto;
          margin-right: auto;
          display: block;
     }  
    

    Efficiently sorting a numpy array in descending order?

    Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.

    x=np.sort(array)
    y=np.fliplr(x)
    

    np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!

    Hope it helps you out!

    I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.

    Convert a Map<String, String> to a POJO

    A solution with Gson:

    Gson gson = new Gson();
    JsonElement jsonElement = gson.toJsonTree(map);
    MyPojo pojo = gson.fromJson(jsonElement, MyPojo.class);
    

    How do I turn a String into a InputStreamReader in java?

    Same question as @Dan - why not StringReader ?

    If it has to be InputStreamReader, then:

    String charset = ...; // your charset
    byte[] bytes = string.getBytes(charset);
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    InputStreamReader isr = new InputStreamReader(bais);
    

    Port 80 is being used by SYSTEM (PID 4), what is that?

    An other service that could occupied the port 80 is BranchCache

    services.msc showing it as "BranchCache"

    or use the net command to stop the service like

    net stop PeerDistSvc
    

    Update:

    PeerDistSvc is a service behind svhost.exe, to view svchost services type

    tasklist /svc /fi "imagename eq svchost.exe"
    

    How do I convert a Python 3 byte-string variable into a regular string?

    Call decode() on a bytes instance to get the text which it encodes.

    str = bytes.decode()
    

    How to identify numpy types in python?

    Use the builtin type function to get the type, then you can use the __module__ property to find out where it was defined:

    >>> import numpy as np
    a = np.array([1, 2, 3])
    >>> type(a)
    <type 'numpy.ndarray'>
    >>> type(a).__module__
    'numpy'
    >>> type(a).__module__ == np.__name__
    True
    

    How to open a new window on form submit

    No need for Javascript, you just have to add a target="_blank" attribute in your form tag.

    <form target="_blank" action="http://example.com"
          method="post" id="mc-embedded-subscribe-form"
          name="mc-embedded-subscribe-form" class="validate"
    >
    

    Setting width and height

    You can change the aspectRatio according to your needs:

    options:{
         aspectRatio:4 //(width/height)
    }
    

    How to get the file path from HTML input form in Firefox 3

    Have a look at XPCOM, there might be something that you can use if Firefox 3 is used by a client.

    How do I tell Python to convert integers into words

    Well, the dead-simple way to do it is to make a list of all the numbers you're interested in:

    numbers = ["zero", "one", "two", "three", "four", "five", ... 
               "ninety-eight", "ninety-nine"]
    

    (The ... indicates where you'd type the text representations of other numbers. No, Python isn't going to magically fill that in for you, you'd have to type all of them to use that technique.)

    And then to print the number, just print numbers[i]. Easy peasy.

    Of course, that list is a lot of typing, so you might wonder about an easy way to generate it. English unfortunately has a lot of irregularities so you'd have to manually put in the first twenty (0-19), but you can use regularities to generate the rest up to 99. (You can also generate some of the teens, but only some of them, so it seems easiest to just type them in.)

    numbers = "zero one two three four five six seven eight nine".split()
    numbers.extend("ten eleven twelve thirteen fourteen fifteen sixteen".split())
    numbers.extend("seventeen eighteen nineteen".split())
    numbers.extend(tens if ones == "zero" else (tens + "-" + ones) 
        for tens in "twenty thirty forty fifty sixty seventy eighty ninety".split()
        for ones in numbers[0:10])
    
    print numbers[42]  # "forty-two"
    

    Another approach is to write a function that puts together the correct string each time. Again you'll have to hard-code the first twenty numbers, but after that you can easily generate them from scratch as needed. This uses a little less memory (a lot less once you start working with larger numbers).

    Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

    $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
    

    yes the above answer is correct, but it's not secure, you can login root user directlyinto phpMyAdmin.

    If you want to create new user with password and give grant permission, execute the below command in MySQL on terminal, Login into your server on terminal,

      # mysql
    
     mysql> GRANT ALL PRIVILEGES ON *.* TO  'user-name'@'%'  IDENTIFIED BY  'password'   REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
    

    Android Google Maps v2 - set zoom level for myLocation

    you have to write only one line in maps_activity.xml

    map:cameraZoom="13"
    

    I hope this will solve your problem...

    How to make a page redirect using JavaScript?

    You can append the values in the query string for the next page to see and process. You can wrap them inside the link tags:

    <a href="your_page.php?var1=value1&var2=value2">
    

    You separate each of those values with the & sign.

    Or you can create this on a button click like this:

    <input type="button" onclick="document.location.href = 'your_page.php?var1=value1&var2=value2';">
    

    How to refresh a Page using react-route Link

    If you just put '/' in the href it will reload the current window.

    _x000D_
    _x000D_
    <a href="/">
      Reload the page
    </a>
    _x000D_
    _x000D_
    _x000D_

    continuous page numbering through section breaks

    You can check out this post on SuperUser.

    Word starts page numbering over for each new section by default.

    I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

    My method:

    • open up the footer (or header if that's where your page number is)
    • drag-select the page number
    • right-click on it
    • hit Format Page Numbers
    • click on the Continue from Previous Section radio button under Page numbering

    I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

    Zsh: Conda/Pip installs command not found

    You need to fix the spacing and quotes:

    export PATH ="/Users/Dz/anaconda/bin:$PATH"
    

    Instead use

    export PATH="/Users/Dz/anaconda/bin":$PATH
    

    How to import JSON File into a TypeScript file?

    In angular7, I simply used

    let routesObject = require('./routes.json');
    

    My routes.json file looks like this

    {
    
        "routeEmployeeList":    "employee-list",
        "routeEmployeeDetail":      "employee/:id"
    }
    

    You access json items using

    routesObject.routeEmployeeList
    

    SSH to Vagrant box in Windows?

    Personally, I just use Cygwin. Which allows you to use many common *nix commands in Windows. SSH being one of them.

    Difference between System.DateTime.Now and System.DateTime.Today

    DateTime.Now returns a DateTime value that consists of the local date and time of the computer where the code is running. It has DateTimeKind.Local assigned to its Kind property. It is equivalent to calling any of the following:

    • DateTime.UtcNow.ToLocalTime()
    • DateTimeOffset.UtcNow.LocalDateTime
    • DateTimeOffset.Now.LocalDateTime
    • TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local)
    • TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local)

    DateTime.Today returns a DateTime value that has the same year, month, and day components as any of the above expressions, but with the time components set to zero. It also has DateTimeKind.Local in its Kind property. It is equivalent to any of the following:

    • DateTime.Now.Date
    • DateTime.UtcNow.ToLocalTime().Date
    • DateTimeOffset.UtcNow.LocalDateTime.Date
    • DateTimeOffset.Now.LocalDateTime.Date
    • TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Local).Date
    • TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.Local).Date

    Note that internally, the system clock is in terms of UTC, so when you call DateTime.Now it first gets the UTC time (via the GetSystemTimeAsFileTime function in the Win32 API) and then it converts the value to the local time zone. (Therefore DateTime.Now.ToUniversalTime() is more expensive than DateTime.UtcNow.)

    Also note that DateTimeOffset.Now.DateTime will have similar values to DateTime.Now, but it will have DateTimeKind.Unspecified rather than DateTimeKind.Local - which could lead to other errors depending on what you do with it.

    So, the simple answer is that DateTime.Today is equivalent to DateTime.Now.Date.
    But IMHO - You shouldn't use either one of these, or any of the above equivalents.

    When you ask for DateTime.Now, you are asking for the value of the local calendar clock of the computer that the code is running on. But what you get back does not have any information about that clock! The best that you get is that DateTime.Now.Kind == DateTimeKind.Local. But whose local is it? That information gets lost as soon as you do anything with the value, such as store it in a database, display it on screen, or transmit it using a web service.

    If your local time zone follows any daylight savings rules, you do not get that information back from DateTime.Now. In ambiguous times, such as during a "fall-back" transition, you won't know which of the two possible moments correspond to the value you retrieved with DateTime.Now. For example, say your system time zone is set to Mountain Time (US & Canada) and you ask for DateTime.Now in the early hours of November 3rd, 2013. What does the result 2013-11-03 01:00:00 mean? There are two moments of instantaneous time represented by this same calendar datetime. If I were to send this value to someone else, they would have no idea which one I meant. Especially if they are in a time zone where the rules are different.

    The best thing you could do would be to use DateTimeOffset instead:

    // This will always be unambiguous.
    DateTimeOffset now = DateTimeOffset.Now;
    

    Now for the same scenario I described above, I get the value 2013-11-03 01:00:00 -0600 before the transition, or 2013-11-03 01:00:00 -0700 after the transition. Anyone looking at these values can tell what I meant.

    I wrote a blog post on this very subject. Please read - The Case Against DateTime.Now.

    Also, there are some places in this world (such as Brazil) where the "spring-forward" transition happens exactly at Midnight. The clocks go from 23:59 to 01:00. This means that the value you get for DateTime.Today on that date, does not exist! Even if you use DateTimeOffset.Now.Date, you are getting the same result, and you still have this problem. It is because traditionally, there has been no such thing as a Date object in .Net. So regardless of how you obtain the value, once you strip off the time - you have to remember that it doesn't really represent "midnight", even though that's the value you're working with.

    If you really want a fully correct solution to this problem, the best approach is to use NodaTime. The LocalDate class properly represents a date without a time. You can get the current date for any time zone, including the local system time zone:

    using NodaTime;
    ...
    
    Instant now = SystemClock.Instance.Now;
    
    DateTimeZone zone1 = DateTimeZoneProviders.Tzdb.GetSystemDefault();
    LocalDate todayInTheSystemZone = now.InZone(zone1).Date;
    
    DateTimeZone zone2 = DateTimeZoneProviders.Tzdb["America/New_York"];
    LocalDate todayInTheOtherZone = now.InZone(zone2).Date;
    

    If you don't want to use Noda Time, there is now another option. I've contributed an implementation of a date-only object to the .Net CoreFX Lab project. You can find the System.Time package object in their MyGet feed. Once added to your project, you will find you can do any of the following:

    using System;
    ...
    
    Date localDate = Date.Today;
    
    Date utcDate = Date.UtcToday;
    
    Date tzSpecificDate = Date.TodayInTimeZone(anyTimeZoneInfoObject);
    

    Excel Formula: Count cells where value is date

    A bit long winded but it works for me: try this::

    =SUM(IF(OR(ISBLANK(AU2), NOT(ISERR(YEAR(AU2)))),0,1)
     +IF(OR(ISBLANK(AV2), NOT(ISERR(YEAR(AV2)))),0,1))
    

    first part of if will allow cell to be blank or if there is something in the cell it tries to convert to a year, if there is an error or there is something other than a date result = 1, do the same for each cell and sum the result

    Are there any free Xml Diff/Merge tools available?

    Altova's DiffDog has free 30-day trial and should do what you're looking for:

    http://www.altova.com/diffdog/diff-merge-tool.html

    jQuery.inArray(), how to use it right?

    The inArray function returns the index of the object supplied as the first argument to the function in the array supplied as the second argument to the function.

    When inArray returns 0 it is indicating that the first argument was found at the first position of the supplied array.

    To use inArray within an if statement use:

    if(jQuery.inArray("test", myarray) != -1) {
        console.log("is in array");
    } else {
        console.log("is NOT in array");
    }
    

    inArray returns -1 when the first argument passed to the function is not found in the array passed as the second argument.