Programs & Examples On #Nls lang

How to upgrade rubygems

I wouldn't use the debian packages, have a look at RVM or Rbenv.

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

The performance impact of using instanceof in Java

I just made a simple test to see how instanceOf performance is comparing to a simple s.equals() call to a string object with only one letter.

in a 10.000.000 loop the instanceOf gave me 63-96ms, and the string equals gave me 106-230ms

I used java jvm 6.

So in my simple test is faster to do a instanceOf instead of a one character string comparison.

using Integer's .equals() instead of string's gave me the same result, only when I used the == i was faster than instanceOf by 20ms (in a 10.000.000 loop)

Securely storing passwords for use in python script

the secure way is encrypt your sensitive data by AES and the encryption key is derivation by password-based key derivation function (PBE), the master password used to encrypt/decrypt the encrypt key for AES.

master password -> secure key-> encrypt data by the key

You can use pbkdf2

from PBKDF2 import PBKDF2
from Crypto.Cipher import AES
import os
salt = os.urandom(8)    # 64-bit salt
key = PBKDF2("This passphrase is a secret.", salt).read(32) # 256-bit key
iv = os.urandom(16)     # 128-bit IV
cipher = AES.new(key, AES.MODE_CBC, iv)

make sure to store the salt/iv/passphrase , and decrypt using same salt/iv/passphase

Weblogic used similar approach to protect passwords in config files

How can I view the allocation unit size of a NTFS partition in Vista?

I know this is an old thread, but there's a newer way then having to use fsutil or diskpart.

Run this powershell command.

Get-Volume | Format-List AllocationUnitSize, FileSystemLabel

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

My solution that finally worked was to clean all projects, close eclipse, clean all projects, close eclipse, and so on at least 5-6 times. Eventually it all settled down and everything was as expected. Weirdest thing ever!!

And no there were no errors in the Problem or console view.

Also this happened after a computer crash. The last time it happened my whole workspace was completely lost. It was still there on the computer, but when I tried to access it, it would be all blank.

For whatever reason computer crashes are really really really badly handled by eclipse.

Trusting all certificates using HttpClient over HTTPS

Any body still struggling with StartCom SSL Certificates on Android 2.1 visit https://www.startssl.com/certs/ and download the ca.pem, now in the answer provided by @emmby replace

`export CLASSPATH=bcprov-jdk16-145.jar
 CERTSTORE=res/raw/mystore.bks
      if [ -a $CERTSTORE ]; then
          rm $CERTSTORE || exit 1
      fi
 keytool \
  -import \
  -v \
  -trustcacerts \
  -alias 0 \
  -file <(openssl x509 -in mycert.pem) \
  -keystore $CERTSTORE \
  -storetype BKS \
  -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
  -providerpath /usr/share/java/bcprov.jar \
  -storepass some-password`

with

 `export CLASSPATH=bcprov-jdk16-145.jar
 CERTSTORE=res/raw/mystore.bks
      if [ -a $CERTSTORE ]; then
          rm $CERTSTORE || exit 1
      fi
 keytool \
  -import \
  -v \
  -trustcacerts \
  -alias 0 \
  -file <(openssl x509 -in ca.pem) \
  -keystore $CERTSTORE \
  -storetype BKS \
  -provider org.bouncycastle.jce.provider.BouncyCastleProvider \
  -providerpath /usr/share/java/bcprov.jar \
  -storepass some-password`

Should work out of the box. I was struggling it for over a day even after a perfect answer by @emmby.. Hope this helps someone...

How set maximum date in datepicker dialog in android?

private void selectDOB() {

    final Calendar calendar = Calendar.getInstance();
    mYear = calendar.get(Calendar.YEAR);
    mDay = calendar.get(Calendar.DATE);
    mMonth = calendar.get(Calendar.MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
        @SuppressLint("LongLogTag")
        @Override
        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
            strDateOfBirth = (month + 1) + "-" + dayOfMonth + "-" + year;

            //********************** check and set date with append 0 at starting***************************
            if (dayOfMonth < 10) {
                strNewDay = "0" + dayOfMonth;
            } else {
                strNewDay = dayOfMonth + "";
            }
            if (month + 1 < 10) {
                strNewMonth = "0" + (month + 1);
            } else {
                strNewMonth = (month + 1) + "";
            }

            Log.e("strnewDay *****************", strNewDay + "");
            Log.e("strNewMonth *****************", strNewMonth + "");

            //    etDateOfBirth.setText(dayOfMonth + " / " + (month + 1) + " / " + year);
            etDateOfBirth.setText(strNewDay + " / " + strNewMonth + " / " + year);

            Log.e("strDateOfBirth *******************", strDateOfBirth + "");

        }
    }, mYear, mMonth, mDay);

    datePickerDialog.show();

    //*************** input date of birth must be greater than or equal to 18 ************************************

    Calendar maxDate = Calendar.getInstance();
    maxDate.set(Calendar.DAY_OF_MONTH, mDay);
    maxDate.set(Calendar.MONTH, mMonth);
    maxDate.set(Calendar.YEAR, mYear - 18);
    datePickerDialog.getDatePicker().setMaxDate(maxDate.getTimeInMillis());

    //*************** input date of birth must be less than today date ************************************
    //   datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());

}

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

pip install wheel

worked for me, but you can also add this

setup(
    ...
    setup_requires=['wheel']
)

to setup.py and save yourself a pip install command

How can I set multiple CSS styles in JavaScript?

Simplest way for me was just using a string/template litteral:

elementName.style.cssText = `
                                width:80%;
                                margin: 2vh auto;
                                background-color: rgba(5,5,5,0.9);
                                box-shadow: 15px 15px 200px black; `;

Great option cause you can use multiple line strings making life easy.

Check out string/template litterals here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Installation failed with message Invalid File

Please follow the below steps File > Settings > Build,Execution,Deployment > Instant Run > Un-check (Enable Instant Run to hot swap code)

this is working for me

thanks

Difference between .dll and .exe?

Difference in DLL and EXE:

1) DLL is an In-Process Component which means running in the same memory space as the client process. EXE is an Out-Process Component which means it runs in its own separate memory space.

2) The DLL contains functions and procedures that other programs can use (promotes reuability) while EXE cannot be shared with other programs.

3) DLL cannot be directly executed as they're designed to be loaded and run by other programs. EXE is a program that is executed directly.

SQL Server - NOT IN

You're probably better off comparing the fields individually, rather than concatenating the strings.

SELECT t1.*
    FROM Table1 t1
        LEFT JOIN Table2 t2
            ON t1.MAKE = t2.MAKE
                AND t1.MODEL = t2.MODEL
                AND t1.[serial number] = t2.[serial number]
    WHERE t2.MAKE IS NULL

How do I get elapsed time in milliseconds in Ruby?

ezpz's answer is almost perfect, but I hope I can add a little more.

Geo asked about time in milliseconds; this sounds like an integer quantity, and I wouldn't take the detour through floating-point land. Thus my approach would be:

irb(main):038:0> t8 = Time.now
=> Sun Nov 01 15:18:04 +0100 2009
irb(main):039:0> t9 = Time.now
=> Sun Nov 01 15:18:18 +0100 2009
irb(main):040:0> dif = t9 - t8
=> 13.940166
irb(main):041:0> (1000 * dif).to_i
=> 13940

Multiplying by an integer 1000 preserves the fractional number perfectly and may be a little faster too.

If you're dealing with dates and times, you may need to use the DateTime class. This works similarly but the conversion factor is 24 * 3600 * 1000 = 86400000 .

I've found DateTime's strptime and strftime functions invaluable in parsing and formatting date/time strings (e.g. to/from logs). What comes in handy to know is:

  • The formatting characters for these functions (%H, %M, %S, ...) are almost the same as for the C functions found on any Unix/Linux system; and

  • There are a few more: In particular, %L does milliseconds!

How to change TextField's height and width?

You can simply wrap Text field widget in padding widget..... Like this,

Padding(
         padding: EdgeInsets.only(left: 5.0, right: 5.0),
          child: TextField(
            cursorColor: Colors.blue,

            decoration: InputDecoration(
                labelText: 'Email',
                hintText: '[email protected]',
                //labelStyle: textStyle,
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                  borderSide: BorderSide(width: 2, color: Colors.blue,)),
              focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: BorderSide(width: 2, color: Colors.green)),
                )

            ),
          ),

How do I set up a private Git repository on GitHub? Is it even possible?

If you are a student you can get a free private repository at https://github.com/edu

Update

As noted in another answer, now there is an option for private repos also for simple users

XPath using starts-with function

Try this

//ITEM/*[starts-with(text(),'2552')]/following-sibling::*

Force add despite the .gitignore file

Despite Daniel Böhmer's working solution, Ohad Schneider offered a better solution in a comment:

If the file is usually ignored, and you force adding it - it can be accidentally ignored again in the future (like when the file is deleted, then a commit is made and the file is re-created.

You should just un-ignore it in the .gitignore file like that: Unignore subdirectories of ignored directories in Git

Make the size of a heatmap bigger with seaborn

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

Exit Shell Script Based on Process Exit Code

If you want to work with $?, you'll need to check it after each command, since $? is updated after each command exits. This means that if you execute a pipeline, you'll only get the exit code of the last process in the pipeline.

Another approach is to do this:

set -e
set -o pipefail

If you put this at the top of the shell script, it looks like Bash will take care of this for you. As a previous poster noted, "set -e" will cause Bash to exit with an error on any simple command. "set -o pipefail" will cause Bash to exit with an error on any command in a pipeline as well.

See here or here for a little more discussion on this problem. Here is the Bash manual section on the set builtin.

How can I set an SQL Server connection string?

You need to understand that a database server or DBA would not want just anyone to be able to connect or modify the contents of the server. This is the whole purpose of security accounts. If a single username/password would work on just any machine, it would provide no protection.

That "sa" thing you have heard of, does not work with SQL Server 2005, 2008 or 2012. I am not sure about previous versions though. I believe somewhere in the early days of SQL Server, the default username and password used to be sa/sa, but that is no longer the case.

FYI, database security and roles are much more complicated nowadays. You may want to look into the details of Windows-based authentication. If your SQL Server is configured for it, you don't need any username/password in the connection string to connect to it. All you need to change is the server machine name and the same connection string will work with both your machines, given both have same database name of course.

How do I get an OAuth 2.0 authentication token in C#

https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.

Get most recent row for given ID

Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID

SELECT id, signin, signout
FROM dTable
INNER JOIN(
  SELECT id, MAX(signin) AS signin
  FROM dTable
  GROUP BY id
) AS t1 USING(id, signin)

how to make label visible/invisible?

You should be able to get it to hide/show by setting:

.style.display = 'none';
.style.display = 'inline';

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

set column width of a gridview in asp.net

<asp:GridView ID="GridView1" runat="server">
    <HeaderStyle Width="10%" />
    <RowStyle Width="10%" />
    <FooterStyle Width="10%" />
    <Columns>
        <asp:BoundField HeaderText="Name" DataField="LastName" 
            HeaderStyle-Width="10%" ItemStyle-Width="10%"
            FooterStyle-Width="10%" />
    </Columns>
</asp:GridView>

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

DateDiff to output hours and minutes

Just change the

DATEDIFF(Hour,InTime, [TimeOut]) TotalHours

part to

CONCAT((DATEDIFF(Minute,InTime,[TimeOut])/60),':',
       (DATEDIFF(Minute,InTime,[TimeOut])%60)) TotalHours 

The /60 gives you hours, the %60 gives you the remaining minutes, and CONCAT lets you put a colon between them.

I know it's an old question, but I came across it and thought it might help if someone else comes across it.

"Cross origin requests are only supported for HTTP." error when loading a local file

For all y'all on MacOS... setup a simple LaunchAgent to enable these glamorous capabilities in your own copy of Chrome...

Save a plist, named whatever (launch.chrome.dev.mode.plist, for example) in ~/Library/LaunchAgents with similar content to...

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>launch.chrome.dev.mode</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Applications/Google Chrome.app/Contents/MacOS/Google Chrome</string>
        <string>-allow-file-access-from-files</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

It should launch at startup.. but you can force it to do so at any time with the terminal command

launchctl load -w ~/Library/LaunchAgents/launch.chrome.dev.mode.plist

TADA!

How do I move a table into a schema in T-SQL

Short answer:

ALTER SCHEMA new_schema TRANSFER old_schema.table_name

I can confirm that the data in the table remains intact, which is probably quite important :)

Long answer as per MSDN docs,

ALTER SCHEMA schema_name 
   TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]

If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.

Getting Error "Form submission canceled because the form is not connected"

<button type="button">my button</button>

we have to add attribute above in our button element

How to check for the type of a template parameter?

I think todays, it is better to use, but only with C++17.

#include <type_traits>

template <typename T>
void foo() {
    if constexpr (std::is_same_v<T, animal>) {
        // use type specific operations... 
    } 
}

If you use some type specific operations in if expression body without constexpr, this code will not compile.

jQuery function to get all unique elements from an array?

As of jquery 3.0 you can use $.uniqueSort(ARRAY)

Example

array = ["1","2","1","2"]
$.uniqueSort(array)
=> ["1", "2"]

How to check if a variable is equal to one string or another string?

if var == 'stringone' or var == 'stringtwo':
    do_something()

or more pythonic,

if var in ['string one', 'string two']:
    do_something()

How do I read a text file of about 2 GB?

I always use 010 Editor to open huge files. It can handle 2 GB easily. I was manipulating files with 50 GB with 010 Editor :-)

It's commercial now, but it has a trial version.

New warnings in iOS 9: "all bitcode will be dropped"

To fix the issues with the canOpenURL failing. This is because of the new App Transport Security feature in iOS9

Read this post to fix that issue http://discoverpioneer.com/blog/2015/09/18/updating-facebook-integration-for-ios-9/

How to do a logical OR operation for integer comparison in shell scripting?

This should work:

#!/bin/bash

if [ "$#" -eq 0 ] || [ "$#" -gt 1 ] ; then
    echo "hello"
fi

I'm not sure if this is different in other shells but if you wish to use <, >, you need to put them inside double parenthesis like so:

if (("$#" > 1))
 ...

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

EXCEL VBA Check if entry is empty or not 'space'

Here is the code to check whether value is present or not.

If Trim(textbox1.text) <> "" Then
     'Your code goes here
Else
     'Nothing
End If

I think this will help.

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

According to @Shovalt's answer, but in short:

Alternatively you could use the following lines of code

    from sklearn.metrics import f1_score
    metrics.f1_score(y_test, y_pred, labels=np.unique(y_pred))

This should remove your warning and give you the result you wanted, because it no longer considers the difference between the sets, by using the unique mode.

Make a dictionary in Python from input values

Assuming you have the text in variable s:

dict(map(lambda l: l.split(), s.splitlines()))

Field 'browser' doesn't contain a valid alias configuration

Add this to your package.json:

"browser": {
  "[module-name]": false   
},

How to increase Neo4j's maximum file open limit (ulimit) in Ubuntu?

ULIMIT configuration:

  1. Login by root
  2. vi security/limits.conf
  3. Make Below entry

    Ulimit configuration start for website user

    website   soft   nofile    8192
    website   hard   nofile    8192
    website   soft   nproc    4096
    website   hard   nproc    8192
    website   soft   core    unlimited
    website   hard   core    unlimited
    
  4. Make Below entry for ALL USER

    Ulimit configuration for every user

    *   soft   nofile    8192
    *   hard   nofile    8192
    *   soft   nproc    4096
    *   hard   nproc    8192
    *   soft   core    unlimited
    *   hard   core    unlimited
    
  5. After modifying the file, user need to logoff and login again to see the new values.

How to view the Folder and Files in GAC?

To view the files just browse them from the command prompt (cmd), eg.:

c:\>cd \Windows\assembly\GAC_32
c:\Windows\assembly\GAC_32> dir

To add and remove files from the GAC use the tool gacutil

How to concatenate properties from multiple JavaScript objects

This should do it:

_x000D_
_x000D_
function collect() {_x000D_
  var ret = {};_x000D_
  var len = arguments.length;_x000D_
  for (var i = 0; i < len; i++) {_x000D_
    for (p in arguments[i]) {_x000D_
      if (arguments[i].hasOwnProperty(p)) {_x000D_
        ret[p] = arguments[i][p];_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  return ret;_x000D_
}_x000D_
_x000D_
let a = { "one" : 1, "two" : 2 };_x000D_
let b = { "three" : 3 };_x000D_
let c = { "four" : 4, "five" : 5 };_x000D_
_x000D_
let d = collect(a, b, c);_x000D_
console.log(d);
_x000D_
_x000D_
_x000D_

Output:

{
  "one": 1,
  "two": 2,
  "three": 3,
  "four": 4,
  "five": 5
}

What causes signal 'SIGILL'?

Make sure that all functions with non-void return type have a return statement.

While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.

Could not find any resources appropriate for the specified culture or the neutral culture

I have a WinForms application with a single project in the solution.
Targeting .NET Framework 4.0
Using SharpDevelop 4.3 as my IDE

Sounds silly, but I happened to have the Logical Name property set to "Resources" on my "Resources.resx" file. Once I cleared that property, all works hunky-dory.

Normally, when you add random files as EmbeddedResource, you generally want to set the Logical Name to something reasonable, for some reason, I did the same on the Resources.resx file and that screwed it all up...

Hope this helps someone.

Dynamically Add Images React Webpack

here is the code

    import React, { Component } from 'react';
    import logo from './logo.svg';
    import './image.css';
    import Dropdown from 'react-dropdown';
    import axios from 'axios';

    let obj = {};

    class App extends Component {
      constructor(){
        super();
        this.state = {
          selectedFiles: []
        }
        this.fileUploadHandler = this.fileUploadHandler.bind(this);
      }

      fileUploadHandler(file){
        let selectedFiles_ = this.state.selectedFiles;
        selectedFiles_.push(file);
        this.setState({selectedFiles: selectedFiles_});
      }

      render() {
        let Images = this.state.selectedFiles.map(image => {
          <div className = "image_parent">

              <img src={require(image.src)}
              />
          </div>
        });

        return (
            <div className="image-upload images_main">

            <input type="file" onClick={this.fileUploadHandler}/>
            {Images}

            </div>
        );
      }
    }

    export default App;

How do you install an APK file in the Android emulator?

Follow the steps :

  1. make sure you have allowed installation from unknown sources in settings.
  2. Use the Android Device Monitor to copy the APK to the sdcard.
  3. Use the builtin browser in Android to navigate to file:///sdcard/apk-name.apk
  4. When the notification "Download complete" appears, click it.

Android: How to detect double-tap?

Improvised dhruvi code

public abstract class DoubleClickListener implements View.OnClickListener {

private static final long DOUBLE_CLICK_TIME_DELTA = 300;//milliseconds

long lastClickTime = 0;
boolean tap = true;

@Override
public void onClick(View v) {
    long clickTime = System.currentTimeMillis();
    if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA){
        onDoubleClick(v);
        tap = false;
    } else
        tap = true;

    v.postDelayed(new Runnable() {
        @Override
        public void run() {
            if(tap)
                onSingleClick();
        }
    },DOUBLE_CLICK_TIME_DELTA);

    lastClickTime = clickTime;
}

public abstract void onDoubleClick(View v);

public abstract void onSingleClick();
}

Send email from localhost running XAMMP in PHP using GMAIL mail server

Here's the link that gives me the answer:

[Install] the "fake sendmail for windows". If you are not using XAMPP you can download it here: http://glob.com.au/sendmail/sendmail.zip

[Modify] the php.ini file to use it (commented out the other lines):

[mail function]
; For Win32 only.
; SMTP = smtp.gmail.com
; smtp_port = 25

; For Win32 only.
; sendmail_from = <e-mail username>@gmail.com

; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(ignore the "Unix only" bit, since we actually are using sendmail)

You then have to configure the "sendmail.ini" file in the directory where sendmail was installed:

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=25
error_logfile=error.log
debug_logfile=debug.log
auth_username=<username>
auth_password=<password>
force_sender=<e-mail username>@gmail.com

To access a Gmail account protected by 2-factor verification, you will need to create an application-specific password. (source)

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

Steps to send a https request to a rest service in Node js

Using the request module solved the issue.

// Include the request library for Node.js   
var request = require('request');
//  Basic Authentication credentials   
var username = "vinod"; 
var password = "12345";
var authenticationHeader = "Basic " + new Buffer(username + ":" + password).toString("base64");
request(   
{
url : "https://133-70-97-54-43.sample.com/feedSample/Query_Status_View/Query_Status/Output1?STATUS=Joined%20school",
headers : { "Authorization" : authenticationHeader }  
},
 function (error, response, body) {
 console.log(body); }  );         

How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

Here is a solution that throws away staged changes:

git reset file/to/overwrite
git checkout file/to/overwrite

XSD - how to allow elements in any order any number of times?

If none of the above is working, you are probably working on EDI trasaction where you need to validate your result against an HIPPA schema or any other complex xsd for that matter. The requirement is that, say there 8 REF segments and any of them have to appear in any order and also not all are required, means to say you may have them in following order 1st REF, 3rd REF , 2nd REF, 9th REF. Under default situation EDI receive will fail, beacause default complex type is

<xs:sequence>
  <xs:element.../>
</xs:sequence>

The situation is even complex when you are calling your element by refrence and then that element in its original spot is quite complex itself. for example:

<xs:element>
<xs:complexType>
<xs:sequence>
<element name="REF1"  ref= "REF1_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF2"  ref= "REF2_Mycustomelment" minOccurs="0" maxOccurs="1">
<element name="REF3"  ref= "REF3_Mycustomelment" minOccurs="0" maxOccurs="1">
</xs:sequence>
</xs:complexType>
</xs:element>

Solution:

Here simply replacing "sequence" with "all" or using "choice" with min/max combinations won't work!

First thing replace "xs:sequence" with "<xs:all>" Now,You need to make some changes where you are Referring the element from, There go to:

<xs:annotation>
  <xs:appinfo>
    <b:recordinfo structure="delimited" field.........Biztalk/2003">

***Now in the above segment add trigger point in the end like this trigger_field="REF01_...complete name.." trigger_value = "38" Do the same for other REF segments where trigger value will be different like say "18", "XX" , "YY" etc..so that your record info now looks like:b:recordinfo structure="delimited" field.........Biztalk/2003" trigger_field="REF01_...complete name.." trigger_value="38">


This will make each element unique, reason being All REF segements (above example) have same structure like REF01, REF02, REF03. And during validation the structure validation is ok but it doesn't let the values repeat because it tries to look for remaining values in first REF itself. Adding triggers will make them all unique and they will pass in any order and situational cases (like use 5 out 9 and not all 9/9).

Hope it helps you, for I spent almost 20 hrs on this.

Good Luck

apache mod_rewrite is not working or not enabled

To get mod_rewrite to work for me in Apache 2.4, I had to add the "Require all granted" line below.

<Directory /var/www>
   # Required if running apache > 2.4
   Require all granted

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

supposedly a similar requirement exists for Apache 2.2 as well, if you're using that:

<Directory /var/www>
   # Required if running apache 2.2
   Order allow,deny
   Allow from all

   RewriteEngine on 
   RewriteRule ^cachebust-([a-z0-9]+)\/(.*) /$2 [L] 
 </Directory>

Note that an ErrorDocument 404 directive can sometimes override these things as well, so if it's not working try commenting out your ErrorDocument directive and see if it works. The above example can be used to ensure a site isn't served from cache by including a subfolder in the path, though the files reside at the root of the server.

Run JavaScript when an element loses focus

You want to use the onblur event.

<input type="text" name="name" value="value" onblur="alert(1);"/>

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

The SSL errors are often thrown by network management software such as Cyberroam.

To answer your question,

you will have to enter badidea into Chrome every time you visit a website.

You might at times have to enter it more than once, as the site may try to pull in various resources before load, hence causing multiple SSL errors

Receiving login prompt using integrated windows authentication

In our Intranet the issue was solved on the client side by tweaking settings in security as shown here. Either of the check boxes on the right worked for us.

IE Internet Options

How to determine when Fragment becomes visible in ViewPager

Only this worked for me!! and setUserVisibleHint(...) is now deprecated (I attached docs at end), which means any other answer is deprecated ;-)

public class FragmentFirewall extends Fragment {
    /**
     * Required cause "setMenuVisibility(...)" is not guaranteed to be
     * called after "onResume()" and/or "onCreateView(...)" method.
     */
    protected void didVisibilityChange() {
        Activity activity = getActivity();
        if (isResumed() && isMenuVisible()) {
            // Once resumed and menu is visible, at last
            // our Fragment is really visible to user.
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        didVisibilityChange();
    }

    @Override
    public void setMenuVisibility(boolean visible) {
        super.setMenuVisibility(visible);
        didVisibilityChange();
    }
}

Tested and works with NaviagationDrawer as well, there isMenuVisible() will always return true (and onResume() seems enough, but we want to support ViewPager too).

setUserVisibleHint is deprecated. If overriding this method, behavior implemented when passing in true should be moved to Fragment.onResume(), and behavior implemented when passing in false should be moved to Fragment.onPause().

Plot width settings in ipython notebook

If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:

width = 12
height = 12
plt.figure(figsize=(width, height))

Changing ViewPager to enable infinite page scrolling

For infinite scrolling with days it's important you have the good fragment in the pager therefore I wrote my answer on this on page (Viewpager in Android to switch between days endlessly)

It's working very well! Above answers did not work for me as I wanted it to work.

Change <br> height using CSS

You can't change the height of the br tag itself, as it's not an element that takes up space in the page. It's just an instruction to create a new line.

You can change the line height using the line-height style. That will change the distance between the text blocks that you have separated by empty lines, but natually also the distance between lines in a text block.

For completeness: Text blocks in HTML is usually done using the p tag around text blocks. That way you can control the line height inside the p tag, and also the spacing between the p tags.

How to group by month from Date field using sql

I used the FORMAT function to accomplish this:

select
 FORMAT(Closing_Date, 'yyyy_MM') AS Closing_Month
 , count(*) cc 
FROM
 MyTable
WHERE
 Defect_Status1 IS NOT NULL
 AND Closing_Date >= '2011-12-01'
 AND Closing_Date < '2016-07-01' 
GROUP BY FORMAT(Closing_Date, 'yyyy_MM')
ORDER BY Closing_Month

Test method is inconclusive: Test wasn't run. Error?

In my case I had an error in my application configuration file app.config. I had misplaced appsettings above the configSections instead of placing it inside. So a corrupt configuration file could be the cause of Resharper not running your tests responding Inconclusive.

How to set the min and max height or width of a Frame?

A workaround - at least for the minimum size: You can use grid to manage the frames contained in root and make them follow the grid size by setting sticky='nsew'. Then you can use root.grid_rowconfigure and root.grid_columnconfigure to set values for minsize like so:

from tkinter import Frame, Tk

class MyApp():
    def __init__(self):
        self.root = Tk()

        self.my_frame_red = Frame(self.root, bg='red')
        self.my_frame_red.grid(row=0, column=0, sticky='nsew')

        self.my_frame_blue = Frame(self.root, bg='blue')
        self.my_frame_blue.grid(row=0, column=1, sticky='nsew')

        self.root.grid_rowconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(0, minsize=200, weight=1)
        self.root.grid_columnconfigure(1, weight=1)

        self.root.mainloop()

if __name__ == '__main__':
    app = MyApp()

But as Brian wrote (in 2010 :D) you can still resize the window to be smaller than the frame if you don't limit its minsize.

module.exports vs exports in Node.js

enter image description here

Each file you create is a module. module is an object. It has property called exports : {} which is empty object by default.

you can create functions/middlewares and add to this empty exports object such as exports.findById() => { ... } then require anywhere in your app and use...

controllers/user.js

exports.findById = () => {
    //  do something
}

require in routes.js to use:

const {findyId} = './controllers/user'

Untrack files from git temporarily

you could keep your files untracked after

git rm -r --cached <file>

add your files with

git add -u

them push or do whatever you want.

What is context in _.each(list, iterator, [context])?

Simple use of _.each

_x000D_
_x000D_
_.each(['Hello', 'World!'], function(word){_x000D_
    console.log(word);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Here's simple example that could use _.each:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
_x000D_
var x = new basket();_x000D_
x.addItem('banana');_x000D_
x.addItem('apple');_x000D_
x.addItem('kiwi');_x000D_
x.show();
_x000D_
_x000D_
_x000D_

Output:

items:  [ 'banana', 'apple', 'kiwi' ]

Instead of calling addItem multiple times you could use underscore this way:

_.each(['banana', 'apple', 'kiwi'], function(item) { x.addItem(item); });

which is identical to calling addItem three times sequentially with these items. Basically it iterates your array and for each item calls your anonymous callback function that calls x.addItem(item). The anonymous callback function is similar to addItem member function (e.g. it takes an item) and is kind of pointless. So, instead of going through anonymous function it's better that _.each avoids this indirection and calls addItem directly:

_.each(['banana', 'apple', 'kiwi'], x.addItem);

but this won't work, as inside basket's addItem member function this won't refer to your x basket that you created. That's why you have an option to pass your basket x to be used as [context]:

_.each(['banana', 'apple', 'kiwi'], x.addItem, x);

Full example that uses _.each and context:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.addItem = function(item) {_x000D_
        this.items.push(item);_x000D_
    };_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], x.addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In short, if callback function that you pass to _.each in any way uses this then you need to specify what this should be referring to inside your callback function. It may seem like x is redundant in my example, but x.addItem is just a function and could be totally unrelated to x or basket or any other object, for example:

_x000D_
_x000D_
function basket() {_x000D_
    this.items = [];_x000D_
    this.show = function() {_x000D_
        console.log('items: ', this.items);_x000D_
    }_x000D_
}_x000D_
function addItem(item) {_x000D_
    this.items.push(item);_x000D_
};_x000D_
_x000D_
var x = new basket();_x000D_
_.each(['banana', 'apple', 'kiwi'], addItem, x);_x000D_
x.show();
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

In other words, you bind some value to this inside your callback, or you may as well use bind directly like this:

_.each(['banana', 'apple', 'kiwi'], addItem.bind(x));

how this feature can be useful with some different underscore methods?

In general, if some underscorejs method takes a callback function and if you want that callback be called on some member function of some object (e.g. a function that uses this) then you may bind that function to some object or pass that object as the [context] parameter and that's the primary intention. And at the top of underscorejs documentation, that's exactly what they state: The iteratee is bound to the context object, if one is passed

Onclick CSS button effect

You should apply the following styles:

#button:active {
    vertical-align: top;
    padding: 8px 13px 6px;
}

This will give you the necessary effect, demo here.

PuTTY scripting to log onto host

For me it works this way:

putty -ssh [email protected] 22 -pw password

putty, protocol, user name @ ip address port and password. To connect in less than a second.

How to run html file on localhost?

You can install Xampp and run apache serve and place your file to www folder and access your file at localhost/{file name} or simply at localhost if your file is named index.html

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

How to deploy a war file in JBoss AS 7?

I built the following ant-task for deployment based on the jboss deployment docs:

<target name="deploy" depends="jboss.environment, buildwar">
    <!-- Build path for deployed war-file -->
    <property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />

    <!-- remove current deployed war -->
    <delete file="${deployed.war}.deployed" failonerror="false" />
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.undeployed" />
    </waitfor>
    <delete dir="${deployed.war}" />

    <!-- copy war-file -->
    <copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />

    <!-- start deployment -->
    <echo>start deployment ...</echo>
    <touch file="${deployed.war}.dodeploy" />

    <!-- wait for deployment to complete -->
    <waitfor maxwait="10" maxwaitunit="second">
        <available file="${deployed.war}.deployed" />
    </waitfor>
    <echo>deployment ok!</echo>
</target>

${jboss.deploy.dir} is set to standalone/deployments

What's the difference between session.persist() and session.save() in Hibernate?

Here are the differences that can help you understand the advantages of persist and save methods:

  • First difference between save and persist is their return type. The return type of persist method is void while return type of save
    method is Serializable object.
  • The persist() method doesn’t guarantee that the identifier value will be assigned to the persistent state immediately, the assignment might happen at flush time.

  • The persist() method will not execute an insert query if it is called outside of transaction boundaries. While, the save() method returns an identifier so that an insert query is executed immediately to get the identifier, no matter if it are inside or outside of a transaction.

  • The persist method is called outside of transaction boundaries, it is useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.

  • Fifth difference between save and persist method in Hibernate: persist is supported by JPA, while save is only supported by Hibernate.

You can see the full working example from the post Difference between save and persist method in Hibernate

Where will log4net create this log file?

I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here

        log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
        var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

How can I make a JUnit test wait?

Thread.sleep() could work in most cases, but usually if you're waiting, you are actually waiting for a particular condition or state to occur. Thread.sleep() does not guarantee that whatever you're waiting for has actually happened.

If you are waiting on a rest request for example maybe it usually return in 5 seconds, but if you set your sleep for 5 seconds the day your request comes back in 10 seconds your test is going to fail.

To remedy this JayWay has a great utility called Awatility which is perfect for ensuring that a specific condition occurs before you move on.

It has a nice fluent api as well

await().until(() -> 
{
    return yourConditionIsMet();
});  

https://github.com/jayway/awaitility

How to escape a JSON string containing newline characters using JavaScript?

I got same situation in one of my Ajax calls, where JSON was throwing an error due to the newline in the Textarea field. The solution given here didn't worked for me. So i used Javascript's .escape function and it worked fine. Then to retrieve the value from JSON, I just unescaped using .unescape.

How do I explicitly specify a Model's table-name mapping in Rails?

class Countries < ActiveRecord::Base
    self.table_name = "cc"
end

In Rails 3.x this is the way to specify the table name.

Format cell color based on value in another sheet and cell

I've done this before with conditional formatting. It's a great way to visually inspect the cells in a workbook and spot the outliers in your data.

Making a request to a RESTful API using python

So you want to pass data in body of a GET request, better would be to do it in POST call. You can achieve this by using both Requests.

Raw Request

GET http://ES_search_demo.com/document/record/_search?pretty=true HTTP/1.1
Host: ES_search_demo.com
Content-Length: 183
User-Agent: python-requests/2.9.0
Connection: keep-alive
Accept: */*
Accept-Encoding: gzip, deflate

{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}

Sample call with Requests

import requests

def consumeGETRequestSync():
data = '{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = requests.get(url,data = data)
print "code:"+ str(response.status_code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "content:"+ str(response.text)

consumeGETRequestSync()

Jquery - How to make $.post() use contentType=application/json?

For some reason, setting the content type on the ajax request as @Adrien suggested didn't work in my case. However, you actually can change content type using $.post by doing this before:

$.ajaxSetup({
    'beforeSend' : function(xhr) {
        xhr.overrideMimeType('application/json; charset=utf-8');
    },
});

Then make your $.post call:

$.post(url, data, function(), "json")

I had trouble with jQuery + IIS, and this was the only solution that helped jQuery understand to use windows-1252 encoding for ajax requests.

How can I move a tag on a git branch to a different commit?

If you want to move an annotated tag, changing only the targeted commit but preserving the annotation message and other metadata use:

moveTag() {
  local tagName=$1
  # Support passing branch/tag names (not just full commit hashes)
  local newTarget=$(git rev-parse $2^{commit})

  git cat-file -p refs/tags/$tagName | 
    sed "1 s/^object .*$/object $newTarget/g" | 
    git hash-object -w --stdin -t tag | 
    xargs -I {} git update-ref refs/tags/$tagName {}
}

usage: moveTag <tag-to-move> <target>

The above function was developed by referencing teerapap/git-move-annotated-tag.sh.

How do I rename the android package name?

The best way to solve this is going to the AndroidManifest.xml: package="com.foocomp.fooapp:

  • Set the cursor on "foocomp"
  • Press Shift+F6
  • Rename Package to whatever you want
  • Repeat for "fooapp".

Works for me.

Also, replace in Path in Whole Project as it didn't change everything. Then Clean, Rebuild and it works --> In Android Studio / IntelliJ you should unmark "Compact Empty Middle Packages"

Include headers when using SELECT INTO OUTFILE?

Here is a way to get the header titles from the column names dynamically.

/* Change table_name and database_name */
SET @table_name = 'table_name';
SET @table_schema = 'database_name';
SET @default_group_concat_max_len = (SELECT @@group_concat_max_len);

/* Sets Group Concat Max Limit larger for tables with a lot of columns */
SET SESSION group_concat_max_len = 1000000;

SET @col_names = (
  SELECT GROUP_CONCAT(QUOTE(`column_name`)) AS columns
  FROM information_schema.columns
  WHERE table_schema = @table_schema
  AND table_name = @table_name);

SET @cols = CONCAT('(SELECT ', @col_names, ')');

SET @query = CONCAT('(SELECT * FROM ', @table_schema, '.', @table_name,
  ' INTO OUTFILE \'/tmp/your_csv_file.csv\'
  FIELDS ENCLOSED BY \'\\\'\' TERMINATED BY \'\t\' ESCAPED BY \'\'
  LINES TERMINATED BY \'\n\')');

/* Concatenates column names to query */
SET @sql = CONCAT(@cols, ' UNION ALL ', @query);

/* Resets Group Contact Max Limit back to original value */
SET SESSION group_concat_max_len = @default_group_concat_max_len;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Can't change z-index with JQuery

because your jQuery code is wrong. Correctly would be:

var theParent = $(this).parent().get(0); 
$(theParent).css('z-index', 3000);

Nginx 403 forbidden for all files

I've tried different cases and only when owner was set to nginx (chown -R nginx:nginx "/var/www/myfolder") - it started to work as expected.

Create a tar.xz in one command

If you like the pipe mode, this is the most clean solution:

tar c some-dir | xz > some-dir.tar.xz

It's not necessary to put the f option in order to deal with files and then to use - to specify that the file is the standard input. It's also not necessary to specify the -z option for xz, because it's default.

It works with gzip and bzip2 too:

tar c some-dir | gzip > some-dir.tar.gz

or

tar c some-dir | bzip2 > some-dir.tar.bz2

Decompressing is also quite straightforward:

xzcat tarball.tar.xz | tar x
bzcat tarball.tar.bz2 | tar x
zcat tarball.tar.gz | tar x

If you have only tar archive, you can use cat:

cat archive.tar | tar x

If you need to list the files only, use tar t.

Android: textview hyperlink

android:autoLink="web" simply works if you have full links in your HTML. The following will be highlighted in blue and clickable:

How to parse JSON string in Typescript

You can additionally use libraries that perform type validation of your json, such as Sparkson. They allow you to define a TypeScript class, to which you'd like to parse your response, in your case it could be:

import { Field } from "sparkson";
class Response {
   constructor(
      @Field("name") public name: string,
      @Field("error") public error: boolean
   ) {}
}

The library will validate if the required fields are present in the JSON payload and if their types are correct. It can also do a bunch of validations and conversions.

Finding child element of parent pure javascript

The children property returns an array of elements, like so:

parent = document.querySelector('.parent');
children = parent.children; // [<div class="child1">]

There are alternatives to querySelector, like document.getElementsByClassName('parent')[0] if you so desire.


Edit: Now that I think about it, you could just use querySelectorAll to get decendents of parent having a class name of child1:

children = document.querySelectorAll('.parent .child1');

The difference between qS and qSA is that the latter returns all elements matching the selector, while the former only returns the first such element.

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

In SQL Server 2008 R2, back-up the database as a file into a folder. Then chose the restore option that appears in the "Database" folder. In the wizard enter the new name that you want in the target database. And choose restore frrom file and use the file you just created. I jsut did it and it was very fast (my DB was small, but still) Pablo.

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

How do I drop a foreign key constraint only if it exists in sql server?

Declare @FKeyRemoveQuery NVarchar(max)

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))

BEGIN
    SELECT @FKeyRemoveQuery='ALTER TABLE dbo.TableName DROP CONSTRAINT [' + LTRIM(RTRIM([name])) + ']'   
    FROM sys.foreign_keys
    WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')

    EXECUTE Sp_executesql @FKeyRemoveQuery 

END

Checking if a folder exists (and creating folders) in Qt, C++

To both check if it exists and create if it doesn't, including intermediaries:

QDir dir("path/to/dir");
if (!dir.exists())
    dir.mkpath(".");

How can I add a PHP page to WordPress?

The best way to add PHP pages in WordPress to Page Template in the child-theme folder.

How to create Page Template in WordPress.

Create a file named template-custom.php and put it in /wp-content/theme/my-theme/.

<?php
 /*
 * Template Name: Custom Template
 * Custom template used for custom php code display
 * @package   Portafolio WordPress Theme
 * @author    Gufran Hasan
 * @copyright Copyright templatecustom.com
 * @link      http://www.templatecustom.com
 */
?>
<?php get_header(); ?>
<?php
  //write code here

 ?>

<?php get_footer(); ?>

For more details

Find all files with name containing string

find $HOME -name "hello.c" -print

This will search the whole $HOME (i.e. /home/username/) system for any files named “hello.c” and display their pathnames:

/Users/user/Downloads/hello.c
/Users/user/hello.c

However, it will not match HELLO.C or HellO.C. To match is case insensitive pass the -iname option as follows:

find $HOME -iname "hello.c" -print

Sample outputs:

/Users/user/Downloads/hello.c
/Users/user/Downloads/Y/Hello.C
/Users/user/Downloads/Z/HELLO.c
/Users/user/hello.c

Pass the -type f option to only search for files:

find /dir/to/search -type f -iname "fooBar.conf.sample" -print
find $HOME -type f -iname "fooBar.conf.sample" -print

The -iname works either on GNU or BSD (including OS X) version find command. If your version of find command does not supports -iname, try the following syntax using grep command:

find $HOME | grep -i "hello.c"
find $HOME -name "*" -print | grep -i "hello.c"

OR try

find $HOME -name '[hH][eE][lL][lL][oO].[cC]' -print

Sample outputs:

/Users/user/Downloads/Z/HELLO.C
/Users/user/Downloads/Z/HEllO.c
/Users/user/Downloads/hello.c
/Users/user/hello.c

View HTTP headers in Google Chrome?

My favorite way in Chrome is clicking on a bookmarklet:

javascript:(function(){function read(url){var r=new XMLHttpRequest();r.open('HEAD',url,false);r.send(null);return r.getAllResponseHeaders();}alert(read(window.location))})();

Put this code in your developer console pad.

Source: http://www.danielmiessler.com/blog/a-bookmarklet-that-displays-http-headers

Python Accessing Nested JSON Data

In your code j is Already json data and j['places'] is list not dict.

 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = r.json()

 print j['state']
 for each in j['places']:
    print each['latitude']

How to add new DataRow into DataTable?

You have to add the row explicitly to the table

table.Rows.Add(row);

How do I check in JavaScript if a value exists at a certain array index?

OK, let's first see what would happens if an array value not exist in JavaScript, so if we have an array like below:

const arr = [1, 2, 3, 4, 5];

and now we check if 6 is there at index 5 or not:

arr[5];

and we get undefined...

So that's basically give us the answer, the best way to check if undefined, so something like this:

if("undefined" === typeof arrayName[index]) {
  //array value is not there...
}

It's better NOT doing this in this case:

if(!arrayName[index]) {
  //Don't check like this..
}

Because imagine we have this array:

const arr = [0, 1, 2];

and we do:

if(!arr[0]) {
  //This get passed, because in JavaScript 0 is falsy
}

So as you see, even 0 is there, it doesn't get recognised, there are few other things which can do the same and make you application buggy, so be careful, I list them all down:

  1. undefined: if the value is not defined and it's undefined
  2. null: if it's null, for example if a DOM element not exists...
  3. empty string: ''
  4. 0: number zero
  5. NaN: not a number
  6. false

Validate select box

you want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done?

You can do this by simple adding attribute required = "required" in the select tag. you can see it in below code

<select id="select" required="required">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>

It worked fine for me at chorme, firefox and internet explorer. Thanks

Using NULL in C++?

From crtdbg.h (and many other headers):

#ifndef NULL
#ifdef __cplusplus
#define NULL    0
#else
#define NULL    ((void *)0)
#endif
#endif

Therefore NULL is 0, at least on the Windows platform. So no, not that I know of.

Format datetime in asp.net mvc 4

Thanks Darin, For me, to be able to post to the create method, It only worked after I modified the BindModel code to :

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
    var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

    if (!string.IsNullOrEmpty(displayFormat) && value != null)
    {
        DateTime date;
        displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
        // use the format specified in the DisplayFormat attribute to parse the date
         if (DateTime.TryParse(value.AttemptedValue, CultureInfo.GetCultureInfo("en-GB"), DateTimeStyles.None, out date))
        {
            return date;
        }
        else
        {
            bindingContext.ModelState.AddModelError(
                bindingContext.ModelName,
                string.Format("{0} is an invalid date format", value.AttemptedValue)
            );
        }
    }

    return base.BindModel(controllerContext, bindingContext);
}

Hope this could help someone else...

How to open remote files in sublime text 3

On server

Install rsub:

wget -O /usr/local/bin/rsub \https://raw.github.com/aurora/rmate/master/rmate
chmod a+x /usr/local/bin/rsub

On local

  1. Install rsub Sublime3 package:

On Sublime Text 3, open Package Manager (Ctrl-Shift-P on Linux/Win, Cmd-Shift-P on Mac, Install Package), and search for rsub and install it

  1. Open command line and connect to remote server:

ssh -R 52698:localhost:52698 server_user@server_address

  1. after connect to server run this command on server:

rsub path_to_file/file.txt

  1. File opening auto in Sublime 3

As of today (2018/09/05) you should use : https://github.com/randy3k/RemoteSubl because you can find it in packagecontrol.io while "rsub" is not present.

How do I iterate over the words of a string?

For a ridiculously large and probably redundant version, try a lot of for loops.

string stringlist[10];
int count = 0;

for (int i = 0; i < sequence.length(); i++)
{
    if (sequence[i] == ' ')
    {
        stringlist[count] = sequence.substr(0, i);
        sequence.erase(0, i+1);
        i = 0;
        count++;
    }
    else if (i == sequence.length()-1)  // Last word
    {
        stringlist[count] = sequence.substr(0, i+1);
    }
}

It isn't pretty, but by and large (Barring punctuation and a slew of other bugs) it works!

How to check if a file exists in Go?

You should use the os.Stat() and os.IsNotExist() functions as in the following example:

// Exists reports whether the named file or directory exists.
func Exists(name string) bool {
    if _, err := os.Stat(name); err != nil {
        if os.IsNotExist(err) {
            return false
        }
    }
    return true
}

The example is extracted from here.

How to get JSON object from Razor Model object in javascript

In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().

It should be as simple as:

<script>
  var json = @Json.Serialize(Model.CollegeInformationlist);
</script>

How to remove the underline for anchors(links)?

The underline may be removed by a CSS property called text decoration.

<style>
    a {
        text-decoration:none;
    }
</style>

If you want to remove the underline for the text present in the elements other than a, the following syntax should be used.

<style>
    element-name{
        text-decoration:none;
    }
</style>

There are many other text-decoration values that may help you to design links.

Running vbscript from batch file

You can use %~dp0 to get the path of the currently running batch file.

Edited to change directory to the VBS location before running

If you want the VBS to synchronously run in the same window, then

@echo off
pushd %~dp0
cscript necdaily.vbs

If you want the VBS to synchronously run in a new window, then

@echo off
pushd %~dp0
start /wait "" cmd /c cscript necdaily.vbs

If you want the VBS to asynchronously run in the same window, then

@echo off
pushd %~dp0
start /b "" cscript necdaily.vbs

If you want the VBS to asynchronously run in a new window, then

@echo off
pushd %~dp0
start "" cmd /c cscript necdaily.vbs

LaTeX: remove blank page after a \part or \chapter

A solution that works:

Wrap the part of the document that needs this modified behavior with the code provided below. In my case the portion to wrap is a \part{} and some text following it.

\makeatletter\@openrightfalse
\part{Whatever}

Some text

\chapter{Foo}
\@openrighttrue\makeatother 

The wrapped portion should also include the chapter at the beginning of which this behavior needs to stop. Otherwise LaTeX may generate an empty page before this chapter.

Source: folks at the #latex IRC channel on irc.freenode.net

'Syntax Error: invalid syntax' for no apparent reason

I noticed that invalid syntax error for no apparent reason can be caused by using space in:

print(f'{something something}')

Python IDLE seems to jump and highlight a part of the first line for some reason (even if the first line happens to be a comment), which is misleading.

How to Decode Json object in laravel and apply foreach loop on that in laravel

your string is NOT a valid json to start with.

a valid json will be,

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

if you do a json_decode, it will yield,

stdClass Object
(
    [area] => Array
        (
            [0] => stdClass Object
                (
                    [area] => kothrud
                )

            [1] => stdClass Object
                (
                    [area] => katraj
                )

        )

)

Update: to use

$string = '

{
    "area": [
        {
            "area": "kothrud"
        },
        {
            "area": "katraj"
        }
    ]
}

';
            $area = json_decode($string, true);

            foreach($area['area'] as $i => $v)
            {
                echo $v['area'].'<br/>';
            }

Output:

kothrud
katraj

Update #2:

for that true:

When TRUE, returned objects will be converted into associative arrays. for more information, click here

How do we download a blob url video

  1. Find the playlist/manifest with the developer tools network tab. There is always one, as that's how it works. It might have a m3u8 extension that you can type into the Filter. (The youtube-dl tool can also find the m3u8 tool automatically some time give it direct link to the webpage where the video is being displayed.)

  2. Give it to the youtube-dl tool (Download) . It can download much more than just YouTube. It'll auto-download each segment then combine everything with FFmpeg then discard the parts. There is a good chance it supports the site you want to download from natively, and you don't even need to do step #1.

  3. If you find a site that is stubborn and you run into 403 errors... Telerik Fiddler to the rescue. It can catch and save anything transmitted (such as the video file) as it acts as a local proxy. Everything you see/hear can be downloaded, unless it's DRM content like Spotify.

Note: in windows, you can use youtube-dl.exe using "Command Prompt" or creating a batch file. i.e

d:\youtube-dl.exe https://www.youtube.com/watch?v=gbdFOwKHil0

Thanks

Trouble setting up git with my GitHub Account error: could not lock config file

I am old to the party but may be this will help some one. Thanks to @paperclip

In Windows 10:

Step 1: Go to This PC > Right click Properties

step 2: Click Advanced System Settings and click Environment Variables

Step 3: Under System Variables create new variable called HOME and input the value as %USERPROFILE% like below

enter image description here

Step 4: Important You must restart your PC to take effect

Step 5: Install Git for Windows now and optional Tortoise Git for windows if you prefer.

Make a git clone request or try pushing something in to your repo. Magic it will work. All should work fine now.

How to change a TextView's style at runtime

Depending on which style you want to set, you have to use different methods. TextAppearance stuff has its own setter, TypeFace has its own setter, background has its own setter, etc.

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

UITableView with fixed section headers

You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.

Creating Accordion Table with Bootstrap

For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:

$('.collapse').on('show.bs.collapse', function () {
    $('.collapse.in').collapse('hide');
});

I modified this example to do so here: http://jsfiddle.net/QLfMU/116/

Auto populate columns in one sheet from another sheet

In Google Sheets you can use =ArrayFormula(Sheet1!B2:B)on the first cell and it will populate all column contents not sure if that will work in excel

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

How does += (plus equal) work?

1) 1 += 2 // equals ?

That is syntactically invalid. The left side must be a variable. For example.

var mynum = 1;
mynum += 2;
// now mynum is 3.

mynum += 2; is just a short form for mynum = mynum + 2;

2)

var data = [1,2,3,4,5];
var sum = 0;
data.forEach(function(value) {
    sum += value; 
});

Sum is now 15. Unrolling the forEach we have:

var sum = 0;
sum += 1; // sum is 1
sum += 2; // sum is 3
sum += 3; // sum is 6
sum += 4; // sum is 10
sum += 5; // sum is 15

How to loop through a collection that supports IEnumerable?

A regular for each will do:

foreach (var item in collection)
{
    // do your stuff   
}

Binding ConverterParameter

There is also an alternative way to use MarkupExtension in order to use Binding for a ConverterParameter. With this solution you can still use the default IValueConverter instead of the IMultiValueConverter because the ConverterParameter is passed into the IValueConverter just like you expected in your first sample.

Here is my reusable MarkupExtension:

/// <summary>
///     <example>
///         <TextBox>
///             <TextBox.Text>
///                 <wpfAdditions:ConverterBindableParameter Binding="{Binding FirstName}"
///                     Converter="{StaticResource TestValueConverter}"
///                     ConverterParameterBinding="{Binding ConcatSign}" />
///             </TextBox.Text>
///         </TextBox>
///     </example>
/// </summary>
[ContentProperty(nameof(Binding))]
public class ConverterBindableParameter : MarkupExtension
{
    #region Public Properties

    public Binding Binding { get; set; }
    public BindingMode Mode { get; set; }
    public IValueConverter Converter { get; set; }
    public Binding ConverterParameter { get; set; }

    #endregion

    public ConverterBindableParameter()
    { }

    public ConverterBindableParameter(string path)
    {
        Binding = new Binding(path);
    }

    public ConverterBindableParameter(Binding binding)
    {
        Binding = binding;
    }

    #region Overridden Methods

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var multiBinding = new MultiBinding();
        Binding.Mode = Mode;
        multiBinding.Bindings.Add(Binding);
        if (ConverterParameter != null)
        {
            ConverterParameter.Mode = BindingMode.OneWay;
            multiBinding.Bindings.Add(ConverterParameter);
        }
        var adapter = new MultiValueConverterAdapter
        {
            Converter = Converter
        };
        multiBinding.Converter = adapter;
        return multiBinding.ProvideValue(serviceProvider);
    }

    #endregion

    [ContentProperty(nameof(Converter))]
    private class MultiValueConverterAdapter : IMultiValueConverter
    {
        public IValueConverter Converter { get; set; }

        private object lastParameter;

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            if (Converter == null) return values[0]; // Required for VS design-time
            if (values.Length > 1) lastParameter = values[1];
            return Converter.Convert(values[0], targetType, lastParameter, culture);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            if (Converter == null) return new object[] { value }; // Required for VS design-time

            return new object[] { Converter.ConvertBack(value, targetTypes[0], lastParameter, culture) };
        }
    }
}

With this MarkupExtension in your code base you can simply bind the ConverterParameter the following way:

<Style TargetType="FrameworkElement">
<Setter Property="Visibility">
    <Setter.Value>
     <wpfAdditions:ConverterBindableParameter Binding="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}"
                 Converter="{StaticResource AccessLevelToVisibilityConverter}"
                 ConverterParameterBinding="{Binding RelativeSource={RelativeSource Mode=Self}, Path=Tag}" />          
    </Setter.Value>
</Setter>

Which looks almost like your initial proposal.

base64 encoded images in email signatures

Important

My answer below shows how to embed images using data URIs. This is useful for the web, but will not work reliably for most email clients. For email purposes be sure to read Shadow2531's answer.


Base-64 data is legal in an img tag and I believe your question is how to properly insert such an image tag.

You can use an online tool or a few lines of code to generate the base 64 string.

The syntax to source the image from inline data is:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot">

http://en.wikipedia.org/wiki/Data_URI_scheme

Confused about Service vs Factory

There is also a way to return a constructor function so you can return newable classes in factories, like this:

function MyObjectWithParam($rootScope, name) {
  this.$rootScope = $rootScope;
  this.name = name;
}
MyObjectWithParam.prototype.getText = function () {
  return this.name;
};

App.factory('MyObjectWithParam', function ($injector) {
  return function(name) { 
    return $injector.instantiate(MyObjectWithParam,{ name: name });
  };
}); 

So you can do this in a controller, which uses MyObjectWithParam:

var obj = new MyObjectWithParam("hello"),

See here the full example:
http://plnkr.co/edit/GKnhIN?p=preview

And here the google group pages, where it was discussed:
https://groups.google.com/forum/#!msg/angular/56sdORWEoqg/b8hdPskxZXsJ

SQL Server command line backup statement

if you need the batch file to schedule the backup, the SQL management tools have scheduled tasks built in...

How to get height of Keyboard?

Shorter version here:

func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            let keyboardHeight = keyboardSize.height
        }
}

CSS 100% height with padding/margin

The better way is with the calc() property. So your case would look like:

#myDiv {
    width: calc(100% - 5px);
    height: calc(100% - 5px);
    padding: 5px;
}

Simple, clean, no workarounds. Just make sure you don't forget the space between the values and the operator (eg (100%-5px) that will break the syntax. Enjoy!

Java String import

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).

Adding a line break in MySQL INSERT INTO text

INSERT INTO myTable VALUES("First line\r\nSecond line\r\nThird line");

How to query GROUP BY Month in a Year

For MS SQL you can do this.

    select  CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+ 
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
    group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
 CAST(DATEPART(YEAR, DateTyme) as VARCHAR) 

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

Counting inversions in an array

This answer contains the results of the timeit tests produced by the code in my main answer. Please see that answer for details!

count_inversions speed test results

Size = 5, hi = 2, 4096 loops
ltree_count_PM2R         : 0.04871, 0.04872, 0.04876
bruteforce_loops_PM2R    : 0.05696, 0.05700, 0.05776
solution_TimBabych       : 0.05760, 0.05822, 0.05943
solutionE_TimBabych      : 0.06642, 0.06704, 0.06760
bruteforce_sum_PM2R      : 0.07523, 0.07545, 0.07563
perm_sum_PM2R            : 0.09873, 0.09875, 0.09935
rank_sum_PM2R            : 0.10449, 0.10463, 0.10468
solution_python          : 0.13034, 0.13061, 0.13221
fenwick_inline_PM2R      : 0.14323, 0.14610, 0.18802
perm_radixR_PM2R         : 0.15146, 0.15203, 0.15235
merge_count_BM           : 0.16179, 0.16267, 0.16467
perm_radixI_PM2R         : 0.16200, 0.16202, 0.16768
perm_fenwick_PM2R        : 0.16887, 0.16920, 0.17075
merge_PM2R               : 0.18262, 0.18271, 0.18418
count_inversions_NiklasB : 0.19183, 0.19279, 0.20388
count_inversion_mkso     : 0.20060, 0.20141, 0.20398
inv_cnt_ZheHu            : 0.20815, 0.20841, 0.20906
fenwick_PM2R             : 0.22109, 0.22137, 0.22379
reversePairs_nomanpouigt : 0.29620, 0.29689, 0.30293
Value: 5

Size = 10, hi = 5, 2048 loops
solution_TimBabych       : 0.05954, 0.05989, 0.05991
solutionE_TimBabych      : 0.05970, 0.05972, 0.05998
perm_sum_PM2R            : 0.07517, 0.07519, 0.07520
ltree_count_PM2R         : 0.07672, 0.07677, 0.07684
bruteforce_loops_PM2R    : 0.07719, 0.07724, 0.07817
rank_sum_PM2R            : 0.08587, 0.08823, 0.08864
bruteforce_sum_PM2R      : 0.09470, 0.09472, 0.09484
solution_python          : 0.13126, 0.13154, 0.13185
perm_radixR_PM2R         : 0.14239, 0.14320, 0.14474
perm_radixI_PM2R         : 0.14632, 0.14669, 0.14679
fenwick_inline_PM2R      : 0.16796, 0.16831, 0.17030
perm_fenwick_PM2R        : 0.18189, 0.18212, 0.18638
merge_count_BM           : 0.19816, 0.19870, 0.19948
count_inversions_NiklasB : 0.21807, 0.22031, 0.22215
merge_PM2R               : 0.22037, 0.22048, 0.26106
fenwick_PM2R             : 0.24290, 0.24314, 0.24744
count_inversion_mkso     : 0.24895, 0.24899, 0.25205
inv_cnt_ZheHu            : 0.26253, 0.26259, 0.26590
reversePairs_nomanpouigt : 0.35711, 0.35762, 0.35973
Value: 20

Size = 20, hi = 10, 1024 loops
solutionE_TimBabych      : 0.05687, 0.05696, 0.05720
solution_TimBabych       : 0.06126, 0.06151, 0.06168
perm_sum_PM2R            : 0.06875, 0.06906, 0.07054
rank_sum_PM2R            : 0.07988, 0.07995, 0.08002
ltree_count_PM2R         : 0.11232, 0.11239, 0.11257
bruteforce_loops_PM2R    : 0.12553, 0.12584, 0.12592
solution_python          : 0.13472, 0.13540, 0.13694
bruteforce_sum_PM2R      : 0.15820, 0.15849, 0.16021
perm_radixI_PM2R         : 0.17101, 0.17148, 0.17229
perm_radixR_PM2R         : 0.17891, 0.18087, 0.18366
perm_fenwick_PM2R        : 0.20554, 0.20708, 0.21412
fenwick_inline_PM2R      : 0.21161, 0.21163, 0.22047
merge_count_BM           : 0.24125, 0.24261, 0.24565
count_inversions_NiklasB : 0.25712, 0.25754, 0.25778
merge_PM2R               : 0.26477, 0.26566, 0.31297
fenwick_PM2R             : 0.28178, 0.28216, 0.29069
count_inversion_mkso     : 0.30286, 0.30290, 0.30652
inv_cnt_ZheHu            : 0.32024, 0.32041, 0.32447
reversePairs_nomanpouigt : 0.45812, 0.45822, 0.46172
Value: 98

Size = 40, hi = 20, 512 loops
solutionE_TimBabych      : 0.05784, 0.05787, 0.05958
solution_TimBabych       : 0.06452, 0.06475, 0.06479
perm_sum_PM2R            : 0.07254, 0.07261, 0.07263
rank_sum_PM2R            : 0.08537, 0.08540, 0.08572
ltree_count_PM2R         : 0.11744, 0.11749, 0.11792
solution_python          : 0.14262, 0.14285, 0.14465
perm_radixI_PM2R         : 0.18774, 0.18776, 0.18922
perm_radixR_PM2R         : 0.19425, 0.19435, 0.19609
bruteforce_loops_PM2R    : 0.21500, 0.21511, 0.21686
perm_fenwick_PM2R        : 0.23338, 0.23375, 0.23674
fenwick_inline_PM2R      : 0.24947, 0.24958, 0.25189
bruteforce_sum_PM2R      : 0.27627, 0.27646, 0.28041
merge_count_BM           : 0.28059, 0.28128, 0.28294
count_inversions_NiklasB : 0.28557, 0.28759, 0.29022
merge_PM2R               : 0.29886, 0.29928, 0.30317
fenwick_PM2R             : 0.30241, 0.30259, 0.35237
count_inversion_mkso     : 0.34252, 0.34356, 0.34441
inv_cnt_ZheHu            : 0.37468, 0.37569, 0.37847
reversePairs_nomanpouigt : 0.50725, 0.50770, 0.50943
Value: 369

Size = 80, hi = 40, 256 loops
solutionE_TimBabych      : 0.06339, 0.06373, 0.06513
solution_TimBabych       : 0.06984, 0.06994, 0.07009
perm_sum_PM2R            : 0.09171, 0.09172, 0.09186
rank_sum_PM2R            : 0.10468, 0.10474, 0.10500
ltree_count_PM2R         : 0.14416, 0.15187, 0.18541
solution_python          : 0.17415, 0.17423, 0.17451
perm_radixI_PM2R         : 0.20676, 0.20681, 0.20936
perm_radixR_PM2R         : 0.21671, 0.21695, 0.21736
perm_fenwick_PM2R        : 0.26197, 0.26252, 0.26264
fenwick_inline_PM2R      : 0.28111, 0.28249, 0.28382
count_inversions_NiklasB : 0.31746, 0.32448, 0.32451
merge_count_BM           : 0.31964, 0.33842, 0.35276
merge_PM2R               : 0.32890, 0.32941, 0.33322
fenwick_PM2R             : 0.34355, 0.34377, 0.34873
count_inversion_mkso     : 0.37689, 0.37698, 0.38079
inv_cnt_ZheHu            : 0.42923, 0.42941, 0.43249
bruteforce_loops_PM2R    : 0.43544, 0.43601, 0.43902
bruteforce_sum_PM2R      : 0.52106, 0.52160, 0.52531
reversePairs_nomanpouigt : 0.57805, 0.58156, 0.58252
Value: 1467

Size = 160, hi = 80, 128 loops
solutionE_TimBabych      : 0.06766, 0.06784, 0.06963
solution_TimBabych       : 0.07433, 0.07489, 0.07516
perm_sum_PM2R            : 0.13143, 0.13175, 0.13179
rank_sum_PM2R            : 0.14428, 0.14440, 0.14922
solution_python          : 0.20072, 0.20076, 0.20084
ltree_count_PM2R         : 0.20314, 0.20583, 0.24776
perm_radixI_PM2R         : 0.23061, 0.23078, 0.23525
perm_radixR_PM2R         : 0.23894, 0.23915, 0.24234
perm_fenwick_PM2R        : 0.30984, 0.31181, 0.31503
fenwick_inline_PM2R      : 0.31933, 0.32680, 0.32722
merge_count_BM           : 0.36003, 0.36387, 0.36409
count_inversions_NiklasB : 0.36796, 0.36814, 0.37106
merge_PM2R               : 0.36847, 0.36848, 0.37127
fenwick_PM2R             : 0.37833, 0.37847, 0.38095
count_inversion_mkso     : 0.42746, 0.42747, 0.43184
inv_cnt_ZheHu            : 0.48969, 0.48974, 0.49293
reversePairs_nomanpouigt : 0.67791, 0.68157, 0.72420
bruteforce_loops_PM2R    : 0.82816, 0.83175, 0.83282
bruteforce_sum_PM2R      : 1.03322, 1.03378, 1.03562
Value: 6194

Size = 320, hi = 160, 64 loops
solutionE_TimBabych      : 0.07467, 0.07470, 0.07483
solution_TimBabych       : 0.08036, 0.08066, 0.08077
perm_sum_PM2R            : 0.21142, 0.21201, 0.25766
solution_python          : 0.22410, 0.22644, 0.22897
rank_sum_PM2R            : 0.22820, 0.22851, 0.22877
ltree_count_PM2R         : 0.24424, 0.24595, 0.24645
perm_radixI_PM2R         : 0.25690, 0.25710, 0.26191
perm_radixR_PM2R         : 0.26501, 0.26504, 0.26729
perm_fenwick_PM2R        : 0.33483, 0.33507, 0.33845
fenwick_inline_PM2R      : 0.34413, 0.34484, 0.35153
merge_count_BM           : 0.39875, 0.39919, 0.40302
fenwick_PM2R             : 0.40434, 0.40439, 0.40845
merge_PM2R               : 0.40814, 0.41531, 0.51417
count_inversions_NiklasB : 0.41681, 0.42009, 0.42128
count_inversion_mkso     : 0.47132, 0.47192, 0.47385
inv_cnt_ZheHu            : 0.54468, 0.54750, 0.54893
reversePairs_nomanpouigt : 0.76164, 0.76389, 0.80357
bruteforce_loops_PM2R    : 1.59125, 1.60430, 1.64131
bruteforce_sum_PM2R      : 2.03734, 2.03834, 2.03975
Value: 24959

Run 2

Size = 640, hi = 320, 8 loops
solutionE_TimBabych      : 0.04135, 0.04374, 0.04575
ltree_count_PM2R         : 0.06738, 0.06758, 0.06874
perm_radixI_PM2R         : 0.06928, 0.06943, 0.07019
fenwick_inline_PM2R      : 0.07850, 0.07856, 0.08059
perm_fenwick_PM2R        : 0.08151, 0.08162, 0.08170
perm_sum_PM2R            : 0.09122, 0.09133, 0.09221
rank_sum_PM2R            : 0.09549, 0.09603, 0.11270
merge_count_BM           : 0.10733, 0.10807, 0.11032
count_inversions_NiklasB : 0.12460, 0.19865, 0.20205
solution_python          : 0.13514, 0.13585, 0.13814

Size = 1280, hi = 640, 8 loops
solutionE_TimBabych      : 0.04714, 0.04742, 0.04752
perm_radixI_PM2R         : 0.15325, 0.15388, 0.15525
solution_python          : 0.15709, 0.15715, 0.16076
fenwick_inline_PM2R      : 0.16048, 0.16160, 0.16403
ltree_count_PM2R         : 0.16213, 0.16238, 0.16428
perm_fenwick_PM2R        : 0.16408, 0.16416, 0.16449
count_inversions_NiklasB : 0.19755, 0.19833, 0.19897
merge_count_BM           : 0.23736, 0.23793, 0.23912
perm_sum_PM2R            : 0.32946, 0.32969, 0.33277
rank_sum_PM2R            : 0.34637, 0.34756, 0.34858

Size = 2560, hi = 1280, 8 loops
solutionE_TimBabych      : 0.10898, 0.11005, 0.11025
perm_radixI_PM2R         : 0.33345, 0.33352, 0.37656
ltree_count_PM2R         : 0.34670, 0.34786, 0.34833
perm_fenwick_PM2R        : 0.34816, 0.34879, 0.35214
fenwick_inline_PM2R      : 0.36196, 0.36455, 0.36741
solution_python          : 0.36498, 0.36637, 0.40887
count_inversions_NiklasB : 0.42274, 0.42745, 0.42995
merge_count_BM           : 0.50799, 0.50898, 0.50917
perm_sum_PM2R            : 1.27773, 1.27897, 1.27951
rank_sum_PM2R            : 1.29728, 1.30389, 1.30448

Size = 5120, hi = 2560, 8 loops
solutionE_TimBabych      : 0.26914, 0.26993, 0.27253
perm_radixI_PM2R         : 0.71416, 0.71634, 0.71753
perm_fenwick_PM2R        : 0.71976, 0.72078, 0.72078
fenwick_inline_PM2R      : 0.72776, 0.72804, 0.73143
ltree_count_PM2R         : 0.81972, 0.82043, 0.82290
solution_python          : 0.83714, 0.83756, 0.83962
count_inversions_NiklasB : 0.87282, 0.87395, 0.92087
merge_count_BM           : 1.09496, 1.09584, 1.10207
rank_sum_PM2R            : 5.02564, 5.06277, 5.06666
perm_sum_PM2R            : 5.09088, 5.12999, 5.13512

Size = 10240, hi = 5120, 8 loops
solutionE_TimBabych      : 0.71556, 0.71718, 0.72201
perm_radixI_PM2R         : 1.54785, 1.55096, 1.55515
perm_fenwick_PM2R        : 1.55103, 1.55353, 1.59298
fenwick_inline_PM2R      : 1.57118, 1.57240, 1.57271
ltree_count_PM2R         : 1.76240, 1.76247, 1.80944
count_inversions_NiklasB : 1.86543, 1.86851, 1.87208
solution_python          : 2.01490, 2.01519, 2.06423
merge_count_BM           : 2.35215, 2.35301, 2.40023
rank_sum_PM2R            : 20.07048, 20.08399, 20.13200
perm_sum_PM2R            : 20.10187, 20.12551, 20.12683

Run 3
Size = 20480, hi = 10240, 4 loops
solutionE_TimBabych      : 1.07636, 1.08243, 1.09569
perm_radixI_PM2R         : 1.59579, 1.60519, 1.61785
perm_fenwick_PM2R        : 1.66885, 1.68549, 1.71109
fenwick_inline_PM2R      : 1.72073, 1.72752, 1.77217
ltree_count_PM2R         : 1.96900, 1.97820, 2.02578
count_inversions_NiklasB : 2.03257, 2.05005, 2.18548
merge_count_BM           : 2.46768, 2.47377, 2.52133
solution_python          : 2.49833, 2.50179, 3.79819

Size = 40960, hi = 20480, 4 loops
solutionE_TimBabych      : 3.51733, 3.52008, 3.56996
perm_radixI_PM2R         : 3.51736, 3.52365, 3.56459
perm_fenwick_PM2R        : 3.76097, 3.80900, 3.87974
fenwick_inline_PM2R      : 3.95099, 3.96300, 3.99748
ltree_count_PM2R         : 4.49866, 4.54652, 5.39716
count_inversions_NiklasB : 4.61851, 4.64303, 4.73026
merge_count_BM           : 5.31945, 5.35378, 5.35951
solution_python          : 6.78756, 6.82911, 6.98217

Size = 81920, hi = 40960, 4 loops
perm_radixI_PM2R         : 7.68723, 7.71986, 7.72135
perm_fenwick_PM2R        : 8.52404, 8.53349, 8.53710
fenwick_inline_PM2R      : 8.97082, 8.97561, 8.98347
ltree_count_PM2R         : 10.01142, 10.01426, 10.03216
count_inversions_NiklasB : 10.60807, 10.62424, 10.70425
merge_count_BM           : 11.42149, 11.42342, 11.47003
solutionE_TimBabych      : 12.83390, 12.83485, 12.89747
solution_python          : 19.66092, 19.67067, 20.72204

Size = 163840, hi = 81920, 4 loops
perm_radixI_PM2R         : 17.14153, 17.16885, 17.22240
perm_fenwick_PM2R        : 19.25944, 19.27844, 20.27568
fenwick_inline_PM2R      : 19.78221, 19.80219, 19.80766
ltree_count_PM2R         : 22.42240, 22.43259, 22.48837
count_inversions_NiklasB : 22.97341, 23.01516, 23.98052
merge_count_BM           : 24.42683, 24.48559, 24.51488
solutionE_TimBabych      : 60.96006, 61.20145, 63.71835
solution_python          : 73.75132, 73.79854, 73.95874

Size = 327680, hi = 163840, 4 loops
perm_radixI_PM2R         : 36.56715, 36.60221, 37.05071
perm_fenwick_PM2R        : 42.21616, 42.21838, 42.26053
fenwick_inline_PM2R      : 43.04987, 43.09075, 43.13287
ltree_count_PM2R         : 49.87400, 50.08509, 50.69292
count_inversions_NiklasB : 50.74591, 50.75012, 50.75551
merge_count_BM           : 52.37284, 52.51491, 53.43003
solutionE_TimBabych      : 373.67198, 377.03341, 377.42360
solution_python          : 411.69178, 411.92691, 412.83856

Size = 655360, hi = 327680, 4 loops
perm_radixI_PM2R         : 78.51927, 78.66327, 79.46325
perm_fenwick_PM2R        : 90.64711, 90.80328, 91.76126
fenwick_inline_PM2R      : 93.32482, 93.39086, 94.28880
count_inversions_NiklasB : 107.74393, 107.80036, 108.71443
ltree_count_PM2R         : 109.11328, 109.23592, 110.18247
merge_count_BM           : 111.05633, 111.07840, 112.05861
solutionE_TimBabych      : 1830.46443, 1836.39960, 1849.53918
solution_python          : 1911.03692, 1912.04484, 1914.69786

Binding a list in @RequestParam

Arrays in @RequestParam are used for binding several parameters of the same name:

myparam=myValue1&myparam=myValue2&myparam=myValue3

If you need to bind @ModelAttribute-style indexed parameters, I guess you need @ModelAttribute anyway.

CSS @media print issues with background-color;

_x000D_
_x000D_
    body{
        background-color: #E5FFE5;
    }
    .bg_print{
       border-bottom: 30px solid #FFCC33;
    }
    .orange_bg_print_content{
        margin-top: -25px;
        padding: 0 10px;
    }
_x000D_
    <div class="bg_print">
    </div>
    <div class="orange_bg_print_content">
        My Content With Background!
    </div>
_x000D_
_x000D_
_x000D_

Tested and works in Chrome and Firefox and Edge...

Why is synchronized block better than synchronized method?

Because lock is expensive, when you are using synchronized block you lock only if _instance == null, and after _instance finally initialized you'll never lock. But when you synchronize on method you lock unconditionally, even after the _instance is initialized. This is the idea behind double-checked locking optimization pattern http://en.wikipedia.org/wiki/Double-checked_locking.

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

How to reference static assets within vue javascript

this finally worked for me, image passed as prop:

<img :src="require(`../../assets/${image}.svg`)">

Uncaught TypeError: Cannot read property 'split' of undefined

Your question answers itself ;) If og_date contains the date, it's probably a string, so og_date.value is undefined.

Simply use og_date.split('-') instead of og_date.value.split('-')

How to set level logging to DEBUG in Tomcat?

JULI logging levels for Tomcat

SEVERE - Serious failures

WARNING - Potential problems

INFO - Informational messages

CONFIG - Static configuration messages

FINE - Trace messages

FINER - Detailed trace messages

FINEST - Highly detailed trace messages

You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html

Invalid default value for 'create_date' timestamp field

You could just change this:

create_date datetime NOT NULL DEFAULT '0000-00-00 00:00:00',

To something like this:

create_date varchar(80) NOT NULL DEFAULT '0000-00-00 00:00:00',

Put content in HttpResponseMessage object?

Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...

        return new System.Web.Http.Results.ResponseMessageResult(
            new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
            });

See nashawn's answer for JsonContent.

How do I reformat HTML code using Sublime Text 2?

Just a general tip. What I did to auto-tidy up my HTML, was install the package HTML_Tidy, and then add the following keybinding to the default settings (which I use):

{ "keys": ["enter"], "command": "html_tidy" },

this runs HTML Tidy with every enter. There may be drawbacks to this, I'm quite new to Sublime myself, but it seems to do what I want :)

Excel VBA Check if directory exists error

To be certain that a folder exists (and not a file) I use this function:

Public Function FolderExists(strFolderPath As String) As Boolean
    On Error Resume Next
    FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory)
    On Error GoTo 0
End Function

It works both, with \ at the end and without.

How do I turn a python datetime into a string, with readable format date?

Using f-strings, in Python 3.6+.

from datetime import datetime

date_string = f'{datetime.now():%Y-%m-%d %H:%M:%S%z}'

Simple JavaScript login form validation

Here is some useful links with example Login form Validation in javascript

function validate() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        if (username == null || username == "") {
            alert("Please enter the username.");
            return false;
        }
        if (password == null || password == "") {
            alert("Please enter the password.");
            return false;
        }
        alert('Login successful');

    } 

  <input type="text" name="username" id="username" />
  <input type="password" name="password" id="password" />
  <input type="button" value="Login" id="submit" onclick="validate();" />

How do I hide anchor text without hiding the anchor?

Another option is to hide based on bootstraps "sr-only" class. If you wrap the text in a span with the class "sr-only" then the text will not be displayed, but screen readers will still have access to it. So you would have:

<li><a href="somehwere"><span class="sr-only">Link text</span></a></li>

If you are not using bootstrap, still keep the above, but also add the below css to define the "sr-only" class:

.sr-only {position: absolute;  width: 1px;  height: 1px;  padding: 0;  margin: -1px;  overflow: hidden;  clip: rect(0 0 0 0);  border: 0; }

Declare multiple module.exports in Node.js

You can write a function that manually delegates between the other functions:

module.exports = function(arg) {
    if(arg instanceof String) {
         return doStringThing.apply(this, arguments);
    }else{
         return doObjectThing.apply(this, arguments);
    }
};

How do I get the total Json record count using JQuery?

If you have something like this:

var json = [ {a:b, c:d}, {e:f, g:h, ...}, {..}, ... ]

then, you can do:

alert(json.length)

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

By default for development JVM uses small size and small config for other performance related features. But for production you can tune e.g. (In addition it Application Server specific config can exist) -> (If there still isn't enough memory to satisfy the request and the heap has already reached the maximum size, an OutOfMemoryError will occur)

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size

-XX:ParallelGCThreads=8
-XX:+CMSClassUnloadingEnabled
-XX:InitiatingHeapOccupancyPercent=70
-XX:+UnlockDiagnosticVMOptions
-XX:+UseConcMarkSweepGC
-Xms512m
-Xmx8192m
-XX:MaxPermSize=256m (in java 8 optional)

For example: On linux Platform for production mode preferable settings.

After downloading and configuring server with this way http://www.ehowstuff.com/how-to-install-and-setup-apache-tomcat-8-on-centos-7-1-rhel-7/

1.create setenv.sh file on folder /opt/tomcat/bin/

   touch /opt/tomcat/bin/setenv.sh

2.Open and write this params for setting preferable mode.

nano  /opt/tomcat/bin/setenv.sh 

export CATALINA_OPTS="$CATALINA_OPTS -XX:ParallelGCThreads=8"
export CATALINA_OPTS="$CATALINA_OPTS -XX:+CMSClassUnloadingEnabled"
export CATALINA_OPTS="$CATALINA_OPTS -XX:InitiatingHeapOccupancyPercent=70"
export CATALINA_OPTS="$CATALINA_OPTS -XX:+UnlockDiagnosticVMOptions"
export CATALINA_OPTS="$CATALINA_OPTS -XX:+UseConcMarkSweepGC"
export CATALINA_OPTS="$CATALINA_OPTS -Xms512m"
export CATALINA_OPTS="$CATALINA_OPTS -Xmx8192m"
export CATALINA_OPTS="$CATALINA_OPTS -XX:MaxMetaspaceSize=256M"

3.service tomcat restart

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

Count the frequency that a value occurs in a dataframe column

In 0.18.1 groupby together with count does not give the frequency of unique values:

>>> df
   a
0  a
1  b
2  s
3  s
4  b
5  a
6  b

>>> df.groupby('a').count()
Empty DataFrame
Columns: []
Index: [a, b, s]

However, the unique values and their frequencies are easily determined using size:

>>> df.groupby('a').size()
a
a    2
b    3
s    2

With df.a.value_counts() sorted values (in descending order, i.e. largest value first) are returned by default.

Finding the direction of scrolling in a UIScrollView?

Ok so for me this implementation is working really good:

@property (nonatomic, assign) CGPoint lastContentOffset;


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    _lastContentOffset.x = scrollView.contentOffset.x;
    _lastContentOffset.y = scrollView.contentOffset.y;

}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {

    if (_lastContentOffset.x < (int)scrollView.contentOffset.x) {
        // moved right
        NSLog(@"right");
    }
    else if (_lastContentOffset.x > (int)scrollView.contentOffset.x) {
        // moved left
        NSLog(@"left");

    }else if (_lastContentOffset.y<(int)scrollView.contentOffset.y){
        NSLog(@"up");

    }else if (_lastContentOffset.y>(int)scrollView.contentOffset.y){
        NSLog(@"down");
        [self.txtText resignFirstResponder];

    }
}

So this will fire textView to dismiss after drag ends

Where to download Microsoft Visual c++ 2003 redistributable

Storm's answer is not correct. No hard feelings Storm, and apologies to the OP as I'm a bit late to the party here (wish I could have helped sooner, but I didn't run into the problem until today, or this stack overflow answer until I was figuring out a solution.)

The Visual C++ 2003 runtime was not available as a seperate download because it was included with the .NET 1.1 runtime.

If you install the .NET 1.1 runtime you will get msvcr71.dll installed, and in addition added to C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322.

The .NET 1.1 runtime is available here: http://www.microsoft.com/downloads/en/details.aspx?familyid=262d25e3-f589-4842-8157-034d1e7cf3a3&displaylang=en (23.1 MB)

If you are looking for a file that ends with a "P" such as msvcp71.dll, this indicates that your file was compiled against a C++ runtime (as opposed to a C runtime), in some situations I noticed these files were only installed when I installed the full SDK. If you need one of these files, you may need to install the full .NET 1.1 SDK as well, which is available here: http://www.microsoft.com/downloads/en/details.aspx?FamilyID=9b3a2ca6-3647-4070-9f41-a333c6b9181d (106.2 MB)

After installing the SDK I now have both msvcr71.dll and msvcp71.dll in my System32 folder, and the application I'm trying to run (boomerang c++ decompiler) works fine without any missing DLL errors.

Also on a side note: be VERY aware of the difference between a Hotfix Update and a Regular Update. As noted in the linked KB932298 download (linked below by Storm): "Please be aware this Hotfix has not gone through full Microsoft product regression testing nor has it been tested in combination with other Hotfixes."

Hotfixes are NOT meant for general users, but rather users who are facing a very specific problem. As described in the article only install that Hotfix if you are have having specific daylight savings time issues with the rules that changed in 2007. -- Likely this was a pre-release for customers who "just couldn't wait" for the official update (probably for some business critical application) -- for regular users Windows Update should be all you need.

Thanks, and I hope this helps others who run into this issue!

JPA - Returning an auto generated id after persist()

@Entity
public class ABC implements Serializable {
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;   
}

check that @GeneratedValue notation is there in your entity class.This tells JPA about your entity property auto-generated behavior

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

    import urllib2

Traceback (most recent call last):

File "", line 1, in

    import urllib2

ImportError: No module named 'urllib2' So urllib2 has been been replaced by the package : urllib.request.

Here is the PEP link (Python Enhancement Proposals )

http://www.python.org/dev/peps/pep-3108/#urllib-package

so instead of urllib2 you can now import urllib.request and then use it like this:

    >>>import urllib.request

    >>>urllib.request.urlopen('http://www.placementyogi.com')

Original Link : http://placementyogi.com/articles/python/importerror-no-module-named-urllib2-in-python-3-x

Asynchronous Requests with Python requests

from threading import Thread

threads=list()

for requestURI in requests:
    t = Thread(target=self.openURL, args=(requestURI,))
    t.start()
    threads.append(t)

for thread in threads:
    thread.join()

...

def openURL(self, requestURI):
    o = urllib2.urlopen(requestURI, timeout = 600)
    o...

What is the purpose of nameof?

Your question already expresses the purpose. You must see this might be useful for logging or throwing exceptions.

For example:

public void DoStuff(object input)
{
    if (input == null)
    {
        throw new ArgumentNullException(nameof(input));
    }
}

This is good. If I change the name of the variable, the code will break instead of returning an exception with an incorrect message.


Of course, the uses are not limited to this simple situation. You can use nameof whenever it would be useful to code the name of a variable or property.

The uses are manifold when you consider various binding and reflection situations. It's an excellent way to bring what were run time errors to compile time.

Execute a PHP script from another PHP script

I prefer to use

require_once('phpfile.php');

lots of options out there for you. and a good way to keep things clean.

How do I get the logfile from an Android device?

I have created a small library (.aar) to retrieve the logs by email. You can use it with Gmail accounts. It is pretty simple but works. You can get a copy from here

The site is in Spanish, but there is a PDF with an english version of the product description.

I hope it can help.

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

Passing struct to function

You need to specify a type on person:

void addStudent(struct student person) {
...
}

Also, you can typedef your struct to avoid having to type struct every time you use it:

typedef struct student{
...
} student_t;

void addStudent(student_t person) {
...
}

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

ln (Natural Log) in Python

math.log is the natural logarithm:

From the documentation:

math.log(x[, base]) With one argument, return the natural logarithm of x (to base e).

Your equation is therefore:

n = math.log((1 + (FV * r) / p) / math.log(1 + r)))

Note that in your code you convert n to a str twice which is unnecessary

Only read selected columns

The vroom package provides a 'tidy' method of selecting / dropping columns by name during import. Docs: https://www.tidyverse.org/blog/2019/05/vroom-1-0-0/#column-selection

Column selection (col_select)

The vroom argument 'col_select' makes selecting columns to keep (or omit) more straightforward. The interface for col_select is the same as dplyr::select().

Select columns by name
data <- vroom("flights.tsv", col_select = c(year, flight, tailnum))
#> Observations: 336,776
#> Variables: 3
#> chr [1]: tailnum
#> dbl [2]: year, flight
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Drop columns by name
data <- vroom("flights.tsv", col_select = c(-dep_time, -air_time:-time_hour))
#> Observations: 336,776
#> Variables: 13
#> chr [4]: carrier, tailnum, origin, dest
#> dbl [9]: year, month, day, sched_dep_time, dep_delay, arr_time, sched_arr_time, arr...
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Use the selection helpers
data <- vroom("flights.tsv", col_select = ends_with("time"))
#> Observations: 336,776
#> Variables: 5
#> dbl [5]: dep_time, sched_dep_time, arr_time, sched_arr_time, air_time
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
Or rename columns by name
data <- vroom("flights.tsv", col_select = list(plane = tailnum, everything()))
#> Observations: 336,776
#> Variables: 19
#> chr  [ 4]: carrier, tailnum, origin, dest
#> dbl  [14]: year, month, day, dep_time, sched_dep_time, dep_delay, arr_time, sched_arr...
#> dttm [ 1]: time_hour
#> 
#> Call `spec()` for a copy-pastable column specification
#> Specify the column types with `col_types` to quiet this message
data
#> # A tibble: 336,776 x 19
#>    plane  year month   day dep_time sched_dep_time dep_delay arr_time
#>    <chr> <dbl> <dbl> <dbl>    <dbl>          <dbl>     <dbl>    <dbl>
#>  1 N142…  2013     1     1      517            515         2      830
#>  2 N242…  2013     1     1      533            529         4      850
#>  3 N619…  2013     1     1      542            540         2      923
#>  4 N804…  2013     1     1      544            545        -1     1004
#>  5 N668…  2013     1     1      554            600        -6      812
#>  6 N394…  2013     1     1      554            558        -4      740
#>  7 N516…  2013     1     1      555            600        -5      913
#>  8 N829…  2013     1     1      557            600        -3      709
#>  9 N593…  2013     1     1      557            600        -3      838
#> 10 N3AL…  2013     1     1      558            600        -2      753
#> # … with 336,766 more rows, and 11 more variables: sched_arr_time <dbl>,
#> #   arr_delay <dbl>, carrier <chr>, flight <dbl>, origin <chr>,
#> #   dest <chr>, air_time <dbl>, distance <dbl>, hour <dbl>, minute <dbl>,
#> #   time_hour <dttm>

What is the difference between i++ and ++i?

If you have:

int i = 10;
int x = ++i;

then x will be 11.

But if you have:

int i = 10;
int x = i++;

then x will be 10.

Note as Eric points out, the increment occurs at the same time in both cases, but it's what value is given as the result that differs (thanks Eric!).

Generally, I like to use ++i unless there's a good reason not to. For example, when writing a loop, I like to use:

for (int i = 0; i < 10; ++i) {
}

Or, if I just need to increment a variable, I like to use:

++x;

Normally, one way or the other doesn't have much significance and comes down to coding style, but if you are using the operators inside other assignments (like in my original examples), it's important to be aware of potential side effects.

Regular expression to get a string between two strings in Javascript

Here's a regex which will grab what's between cow and milk (without leading/trailing space):

srctext = "My cow always gives milk.";
var re = /(.*cow\s+)(.*)(\s+milk.*)/;
var newtext = srctext.replace(re, "$2");

An example: http://jsfiddle.net/entropo/tkP74/

Adding a collaborator to my free GitHub account?

2020 update

It's called Manage access now.

Go to your private repo, click the Settings tab, and choose Manage access from the menu on the left. You are allowed up to three collaborators with the free plan.

Note: If the account is an individual account you can still add collaborators that can do a variety of tasks, but a collaborator can't (as far as I know) sign the app in Xcode and submit it to the app store. You need an organization account for that kind of collaborator.

How many times a substring occurs

The best way to find overlapping sub-string in a given string is to use the python regular expression it will find all the overlapping matching using the regular expression library. Here is how to do it left is the substring and in right you will provide the string to match

print len(re.findall('(?=aa)','caaaab'))
3

Adding a Time to a DateTime in C#

If you are using two DateTime objects, one to store the date the other the time, you could do the following:

var date = new DateTime(2016,6,28);

var time = new DateTime(1,1,1,13,13,13);

var combinedDateTime = date.AddTicks(time.TimeOfDay.Ticks);

An example of this can be found here

Number of lines in a file in Java

I know this is an old question, but the accepted solution didn't quite match what I needed it to do. So, I refined it to accept various line terminators (rather than just line feed) and to use a specified character encoding (rather than ISO-8859-n). All in one method (refactor as appropriate):

public static long getLinesCount(String fileName, String encodingName) throws IOException {
    long linesCount = 0;
    File file = new File(fileName);
    FileInputStream fileIn = new FileInputStream(file);
    try {
        Charset encoding = Charset.forName(encodingName);
        Reader fileReader = new InputStreamReader(fileIn, encoding);
        int bufferSize = 4096;
        Reader reader = new BufferedReader(fileReader, bufferSize);
        char[] buffer = new char[bufferSize];
        int prevChar = -1;
        int readCount = reader.read(buffer);
        while (readCount != -1) {
            for (int i = 0; i < readCount; i++) {
                int nextChar = buffer[i];
                switch (nextChar) {
                    case '\r': {
                        // The current line is terminated by a carriage return or by a carriage return immediately followed by a line feed.
                        linesCount++;
                        break;
                    }
                    case '\n': {
                        if (prevChar == '\r') {
                            // The current line is terminated by a carriage return immediately followed by a line feed.
                            // The line has already been counted.
                        } else {
                            // The current line is terminated by a line feed.
                            linesCount++;
                        }
                        break;
                    }
                }
                prevChar = nextChar;
            }
            readCount = reader.read(buffer);
        }
        if (prevCh != -1) {
            switch (prevCh) {
                case '\r':
                case '\n': {
                    // The last line is terminated by a line terminator.
                    // The last line has already been counted.
                    break;
                }
                default: {
                    // The last line is terminated by end-of-file.
                    linesCount++;
                }
            }
        }
    } finally {
        fileIn.close();
    }
    return linesCount;
}

This solution is comparable in speed to the accepted solution, about 4% slower in my tests (though timing tests in Java are notoriously unreliable).

Random word generator- Python

get the words online

from urllib.request import Request, urlopen
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')
print(webpage)

Randomizing the first 500 words

from urllib.request import Request, urlopen
import random


url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})

web_byte = urlopen(req).read()

webpage = web_byte.decode('utf-8')
first500 = webpage[:500].split("\n")
random.shuffle(first500)
print(first500)

Output

['abnegation', 'able', 'aborning', 'Abigail', 'Abidjan', 'ablaze', 'abolish', 'abbe', 'above', 'abort', 'aberrant', 'aboriginal', 'aborigine', 'Aberdeen', 'Abbott', 'Abernathy', 'aback', 'abate', 'abominate', 'AAA', 'abc', 'abed', 'abhorred', 'abolition', 'ablate', 'abbey', 'abbot', 'Abelson', 'ABA', 'Abner', 'abduct', 'aboard', 'Abo', 'abalone', 'a', 'abhorrent', 'Abelian', 'aardvark', 'Aarhus', 'Abe', 'abjure', 'abeyance', 'Abel', 'abetting', 'abash', 'AAAS', 'abdicate', 'abbreviate', 'abnormal', 'abject', 'abacus', 'abide', 'abominable', 'abode', 'abandon', 'abase', 'Ababa', 'abdominal', 'abet', 'abbas', 'aberrate', 'abdomen', 'abetted', 'abound', 'Aaron', 'abhor', 'ablution', 'abeyant', 'about']

How do I create a branch?

Top tip for new SVN users; this may help a little with getting the correct URLs quickly.

Run svn info to display useful information about the current checked-out branch.

The URL should (if you run svn in the root folder) give you the URL you need to copy from.

Also to switch to the newly created branch, use the svn switch command:

svn switch http://my.repo.url/myrepo/branches/newBranchName

HTML5 image icon to input placeholder

I don't know whether there's a better answer out there as time goes by but this is simple and it works;

input[type='email'] {
  background: white url(images/mail.svg) no-repeat ;
}
input[type='email']:focus {
  background-image: none;
}

Style it up to suit.

jQuery selector regular expressions

You can use the filter function to apply more complicated regex matching.

Here's an example which would just match the first three divs:

_x000D_
_x000D_
$('div')_x000D_
  .filter(function() {_x000D_
    return this.id.match(/abc+d/);_x000D_
  })_x000D_
  .html("Matched!");
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="abcd">Not matched</div>_x000D_
<div id="abccd">Not matched</div>_x000D_
<div id="abcccd">Not matched</div>_x000D_
<div id="abd">Not matched</div>
_x000D_
_x000D_
_x000D_

Android new Bottom Navigation bar or BottomNavigationView

Google has launched the BottomNavigationView after the version 25.0.0 of the design support library. But it came with the following limitations:

  1. You can't remove titles and center icon.
  2. You cant't change titles text size.
  3. Y?o?u? ?c?a?n?'?t? ?c?h?a?n?g?e? ?t?h?e? ?b?a?c?k?g?r?o?u?n?d? ?c?o?l?o?r? ?i?t? ?i?s? ?a?l?w?a?y?s? ?t?h?e? ?c?o?l?o?r?P?r?i?m?a?r?y?.?
  4. It doesn't have a BottomNavigationBehavior: so no integration with FAB or SnackBar through CordinatorLayout.
  5. Every menuItem is a pure extension of FrameLayout so it doesn't have any nice circle reveal effect

So the max you can do with this fist version of BottomNavigationView is: (without any reflection or implementing the lib by yourself).

enter image description here

So, If you want any of these. You can use a third part library like roughike/BottomBar or implement the lib by yourself.

‘ant’ is not recognized as an internal or external command

even with the environment variables set, I found that ant -version does not work in scripts. Try call ant -version

Truncating long strings with CSS: feasible yet?

2014 March: Truncating long strings with CSS: a new answer with focus on browser support

Demo on http://jsbin.com/leyukama/1/ (I use jsbin because it supports old version of IE).

<style type="text/css">
    span {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;     /** IE6+, Firefox 7+, Opera 11+, Chrome, Safari **/
        -o-text-overflow: ellipsis;  /** Opera 9 & 10 **/
        width: 370px; /* note that this width will have to be smaller to see the effect */
    }
</style>

<span>Some very long text that should be cut off at some point coz it's a bit too long and the text overflow ellipsis feature is used</span>

The -ms-text-overflow CSS property is not necessary: it is a synonym of the text-overflow CSS property, but versions of IE from 6 to 11 already support the text-overflow CSS property.

Successfully tested (on Browserstack.com) on Windows OS, for web browsers:

  • IE6 to IE11
  • Opera 10.6, Opera 11.1, Opera 15.0, Opera 20.0
  • Chrome 14, Chrome 20, Chrome 25
  • Safari 4.0, Safari 5.0, Safari 5.1
  • Firefox 7.0, Firefox 15

Firefox: as pointed out by Simon Lieschke (in another answer), Firefox only support the text-overflow CSS property from Firefox 7 onwards (released September 27th 2011).

I double checked this behavior on Firefox 3.0 & Firefox 6.0 (text-overflow is not supported).

Some further testing on a Mac OS web browsers would be needed.

Note: you may want to show a tooltip on mouse hover when an ellipsis is applied, this can be done via javascript, see this questions: HTML text-overflow ellipsis detection and HTML - how can I show tooltip ONLY when ellipsis is activated

Resources:

Using FileSystemWatcher to monitor a directory

The reason may be that watcher is declared as local variable to a method and it is garbage collected when the method finishes. You should declare it as a class member. Try the following:

FileSystemWatcher watcher;

private void watch()
{
  watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                         | NotifyFilters.FileName | NotifyFilters.DirectoryName;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

private void OnChanged(object source, FileSystemEventArgs e)
{
  //Copies file to another directory.
}

Text in a flex container doesn't wrap in IE11

The easiest solution I've found is just adding max-width: 100% to the element that's going out of bounds. If you're using it on something like a carousel remember to add a class with the max-width attribute.

Why shouldn't I use "Hungarian Notation"?

Joel is wrong, and here is why.

That "application" information he's talking about should be encoded in the type system. You should not depend on flipping variable names to make sure you don't pass unsafe data to functions requiring safe data. You should make it a type error, so that it is impossible to do so. Any unsafe data should have a type that is marked unsafe, so that it simply cannot be passed to a safe function. To convert from unsafe to safe should require processing with some kind of a sanitize function.

A lot of the things that Joel talks of as "kinds" are not kinds; they are, in fact, types.

What most languages lack, however, is a type system that's expressive enough to enforce these kind of distinctions. For example, if C had a kind of "strong typedef" (where the typedef name had all the operations of the base type, but was not convertible to it) then a lot of these problems would go away. For example, if you could say, strong typedef std::string unsafe_string; to introduce a new type unsafe_string that could not be converted to a std::string (and so could participate in overload resolution etc. etc.) then we would not need silly prefixes.

So, the central claim that Hungarian is for things that are not types is wrong. It's being used for type information. Richer type information than the traditional C type information, certainly; it's type information that encodes some kind of semantic detail to indicate the purpose of the objects. But it's still type information, and the proper solution has always been to encode it into the type system. Encoding it into the type system is far and away the best way to obtain proper validation and enforcement of the rules. Variables names simply do not cut the mustard.

In other words, the aim should not be "make wrong code look wrong to the developer". It should be "make wrong code look wrong to the compiler".

Increase max_execution_time in PHP?

Is very easy, this work for me:

PHP:

set_time_limit(300); // Time in seconds, max_execution_time

Here is the PHP documentation

JavaScript: Collision detection

hittest.js; detect two transparent PNG images (pixel) colliding.

Demo and download link

HTML code

<img id="png-object-1" src="images/object1.png" />
<img id="png-object-2" src="images/object2.png" />

Init function

var pngObject1Element = document.getElementById( "png-object-1" );
var pngObject2Element = document.getElementById( "png-object-2" );

var object1HitTest = new HitTest( pngObject1Element );

Basic usage

if( object1HitTest.toObject( pngObject2Element ) ) {
    // Collision detected
}

How to get access to job parameters from ItemReader, in Spring Batch?

Did you declare the jobparameters as map properly as bean?

Or did you perhaps accidently instantiate a JobParameters object, which has no getter for the filename?

For more on expression language you can find information in Spring documentation here.

iPhone 5 CSS media query

You should maybe down the "-webkit-min-device-pixel-ratio" to 1.5 to catch all iPhones ?

@media only screen and (max-device-width: 480px), only screen and (min-device-width: 640px) and (max-device-width: 1136px) and (-webkit-min-device-pixel-ratio: 1.5) {
/* iPhone only */
}

jQuery Datepicker close datepicker after selected date

There is another code that's works for me (jQuery).

_x000D_
_x000D_
$(".datepicker").datepicker({_x000D_
    format: "dd/mm/yyyy",_x000D_
    autoHide: true_x000D_
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datepicker/0.6.5/datepicker.css" />_x000D_
Date: <input type="text" readonly="true" class="datepicker">
_x000D_
_x000D_
_x000D_

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

For me in datetimepicker jquery plugin format:'d/m/Y' option is worked

$("#dobDate").datetimepicker({
lang:'en',
timepicker:false,
autoclose: true,
format:'d/m/Y',
onChangeDateTime:function( ct ){
   $(".xdsoft_datetimepicker").hide();
}
});

What is the difference between OFFLINE and ONLINE index rebuild in SQL Server?

Online index rebuilds are less intrusive when it comes to locking tables. Offline rebuilds cause heavy locking of tables which can cause significant blocking issues for things that are trying to access the database while the rebuild takes place.

"Table locks are applied for the duration of the index operation [during an offline rebuild]. An offline index operation that creates, rebuilds, or drops a clustered, spatial, or XML index, or rebuilds or drops a nonclustered index, acquires a Schema modification (Sch-M) lock on the table. This prevents all user access to the underlying table for the duration of the operation. An offline index operation that creates a nonclustered index acquires a Shared (S) lock on the table. This prevents updates to the underlying table but allows read operations, such as SELECT statements."

http://msdn.microsoft.com/en-us/library/ms188388(v=sql.110).aspx

Additionally online index rebuilds are a enterprise (or developer) version only feature.

How to track down access violation "at address 00000000"

When I've stumbled upon this problem I usually start looking at the places where I FreeAndNil() or just xxx := NIL; variables and the code after that.

When nothing else has helped I've added a Log() function to output messages from various suspect places during execution, and then later looked at that log to trace where in the code the access violation comes.

There are ofcourse many more elegant solutions available for tracing these violations, but if you do not have them at your disposal the old-fashioned trial & error method works fine.

What is the use of the @Temporal annotation in Hibernate?

We use @Temporal annotation to insert date, time or both in database table.Using TemporalType we can insert data, time or both int table.

@Temporal(TemporalType.DATE) // insert date
@Temporal(TemporalType.TIME) // insert time
@Temporal(TemporalType.TIMESTAMP) // insert  both time and date.

Python: Select subset from list based on index set

Use the built in function zip

property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]

EDIT

Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.

http://docs.python.org/library/itertools.html#itertools.compress

itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

I had similar problem. Difference was that I was getting this error for only one database out all my databases. I removed the password , restarted mysql many times and still it dint work :(

And when I cleared the cache of my browser it just started working !!!

This one really screwed my mind !

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Capturing TAB key in text box

I would advise against changing the default behaviour of a key. I do as much as possible without touching a mouse, so if you make my tab key not move to the next field on a form I will be very aggravated.

A shortcut key could be useful however, especially with large code blocks and nesting. Shift-TAB is a bad option because that normally takes me to the previous field on a form. Maybe a new button on the WMD editor to insert a code-TAB, with a shortcut key, would be possible?

JavaScript math, round to two decimal places

A small variation on the accepted answer. toFixed(2) returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:

var discount = + ((price / listprice).toFixed(2));

Edited: I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to

var discount = Math.round(price / listprice * 100) / 100;

This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388

Laravel 5 - redirect to HTTPS

I'm adding this alternative as I suffered a lot with this issue. I tried all different ways and nothing worked. So, I came up with a workaround for it. It might not be the best solution but it does work -

FYI, I am using Laravel 5.6

if (App::environment('production')) {
    URL::forceScheme('https');
}

production <- It should be replaced with the APP_ENV value in your .env file

how to call scalar function in sql server 2008

Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do

 select  dbo.fun_functional_score('01091400003') as [er]