Programs & Examples On #Backgrounding

Backgrounding is the act of executing an application while it is in the background.

How to exit an Android app programmatically?

This can work I tried it too.

this.finishAffinity();

Select N random elements from a List<T> in C#

I recently did this on my project using an idea similar to Tyler's point 1.
I was loading a bunch of questions and selecting five at random. Sorting was achieved using an IComparer.
aAll questions were loaded in the a QuestionSorter list, which was then sorted using the List's Sort function and the first k elements where selected.

    private class QuestionSorter : IComparable<QuestionSorter>
    {
        public double SortingKey
        {
            get;
            set;
        }

        public Question QuestionObject
        {
            get;
            set;
        }

        public QuestionSorter(Question q)
        {
            this.SortingKey = RandomNumberGenerator.RandomDouble;
            this.QuestionObject = q;
        }

        public int CompareTo(QuestionSorter other)
        {
            if (this.SortingKey < other.SortingKey)
            {
                return -1;
            }
            else if (this.SortingKey > other.SortingKey)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }

Usage:

    List<QuestionSorter> unsortedQuestions = new List<QuestionSorter>();

    // add the questions here

    unsortedQuestions.Sort(unsortedQuestions as IComparer<QuestionSorter>);

    // select the first k elements

How to make a Bootstrap accordion collapse when clicking the header div?

Another way is make your <a> full fill all the space of the panel-heading. Use this style to do so:

.panel-title a {
    display: block;
    padding: 10px 15px;
    margin: -10px -15px;
}

Check this demo (http://jsfiddle.net/KbQyx/).

Then when you clicking on the heading, you are actually clicking on the <a>.

How to get exact browser name and version?

Use get_browser()

From Manual:

echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);

Will return:

Array
(
    [browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
    [browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*/
    [parent] => Firefox 0.9
    [platform] => WinXP
    [browser] => Firefox
    [version] => 0.9
    [majorver] => 0
    [minorver] => 9
    [cssversion] => 2
    [frames] => 1
    [iframes] => 1
    [tables] => 1
    [cookies] => 1
    [backgroundsounds] =>
    [vbscript] =>
    [javascript] => 1
    [javaapplets] => 1
    [activexcontrols] =>
    [cdf] =>
    [aol] =>
    [beta] => 1
    [win16] =>
    [crawler] =>
    [stripper] =>
    [wap] =>
    [netclr] =>
)

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

What is the maximum recursion depth in Python, and how to increase it?

We could also use a variation of dynamic programming bottom up approach

def fib_bottom_up(n):

    bottom_up = [None] * (n+1)
    bottom_up[0] = 1
    bottom_up[1] = 1

    for i in range(2, n+1):
        bottom_up[i] = bottom_up[i-1] + bottom_up[i-2]

    return bottom_up[n]

print(fib_bottom_up(20000))

Setting the Textbox read only property to true using JavaScript

Using asp.net, I believe you can do it this way :

myTextBox.Attributes.Add("readonly","readonly")

where is create-react-app webpack config and files?

A lot of people come to this page with the goal of finding the webpack config and files in order to add their own configuration to them. Another way to achieve this without running npm run eject is to use react-app-rewired. This allows you to overwrite your webpack config file without ejecting.

How to get a list of sub-folders and their files, ordered by folder-names

Hej man, why are you using this ?

dir /s/b/o:gn > f.txt (wrong one)

Don't you know what is that 'g' in '/o' ??

Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help

You should be using this instead:

dir /s/b/o:n > f.txt (right one)

How to get "wc -l" to print just the number of lines without file name?

Comparison of Techniques

I had a similar issue attempting to get a character count without the leading whitespace provided by wc, which led me to this page. After trying out the answers here, the following are the results from my personal testing on Mac (BSD Bash). Again, this is for character count; for line count you'd do wc -l. echo -n omits the trailing line break.

FOO="bar"
echo -n "$FOO" | wc -c                          # "       3"    (x)
echo -n "$FOO" | wc -c | bc                     # "3"           (v)
echo -n "$FOO" | wc -c | tr -d ' '              # "3"           (v)
echo -n "$FOO" | wc -c | awk '{print $1}'       # "3"           (v)
echo -n "$FOO" | wc -c | cut -d ' ' -f1         # "" for -f < 8 (x)
echo -n "$FOO" | wc -c | cut -d ' ' -f8         # "3"           (v)
echo -n "$FOO" | wc -c | perl -pe 's/^\s+//'    # "3"           (v)
echo -n "$FOO" | wc -c | grep -ch '^'           # "1"           (x)
echo $( printf '%s' "$FOO" | wc -c )            # "3"           (v)

I wouldn't rely on the cut -f* method in general since it requires that you know the exact number of leading spaces that any given output may have. And the grep one works for counting lines, but not characters.

bc is the most concise, and awk and perl seem a bit overkill, but they should all be relatively fast and portable enough.

Also note that some of these can be adapted to trim surrounding whitespace from general strings, as well (along with echo `echo $FOO`, another neat trick).

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

jQuery UI Dialog - missing close icon

This appears to be a bug in the way jQuery ships. You can fix it manually with some dom manipulation on the Dialog Open event:

$("#selector").dialog({
    open: function() {
        $(this).closest(".ui-dialog")
        .find(".ui-dialog-titlebar-close")
        .removeClass("ui-dialog-titlebar-close")
        .html("<span class='ui-button-icon-primary ui-icon ui-icon-closethick'></span>");
    }
});

How to round up the result of integer division?

Found an elegant solution:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

Source: Number Conversion, Roland Backhouse, 2001

How do I pull my project from github?

Run these commands:

cd /pathToYourLocalProjectFolder

git pull origin master

Fatal error compiling: invalid target release: 1.8 -> [Help 1]

This question wasn't asking explicitly about Docker, but I received the same error when I had a pom.xml file that was targeting 1.9...

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.9</maven.compiler.source>
  <maven.compiler.target>1.9</maven.compiler.target>
</properties>

... but then tried to run tests against a Docker container by specifying "maven" by itself.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven mvn -e test

For me, the fix was to target the exact version I needed.

docker run -t --rm -v m2_repository:/root/.m2/repository -v $(pwd):/work -w /work maven:3.5.2-jdk-9 mvn test

(You can learn more here.)

How to get a substring between two strings in PHP?

Got best solution for this from tonyspiro

function getBetween($content,$start,$end){
   $r = explode($start, $content);
   if (isset($r[1])){
       $r = explode($end, $r[1]);
       return $r[0];
   }
   return '';
}

Responsive timeline UI with Bootstrap3

"Timeline (responsive)" snippet:

This looks very, very close to what your example shows. The bootstrap snippet linked below covers all the bases you are looking for. I've been considering it myself, with the same requirements you have ( especially responsiveness ). This morphs well between screen sizes and devices.

You can fork this and use it as a great starting point for your specific expectations:


Here are two screenshots I took for you... wide and thin:

wide thin

Java, Check if integer is multiple of a number

Use the remainder operator (also known as the modulo operator) which returns the remainder of the division and check if it is zero:

if (j % 4 == 0) {
     // j is an exact multiple of 4
}

How to adjust layout when soft keyboard appears

This code works for me. When keyboard appears, you can scroll screen

In AndroidManifest.xml

<activity android:name=".signup.screen_2.SignUpNameAndPasswordActivity"
                  android:screenOrientation="portrait"
                  android:windowSoftInputMode="adjustResize">
</activity>

activity_sign_up.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        tools:context=".signup.screen_2.SignUpNameAndPasswordActivity">
    <LinearLayout
            android:fitsSystemWindows="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

        <LinearLayout
                android:layout_marginTop="@dimen/dp_24"
                android:layout_marginStart="@dimen/dp_24"
                android:layout_marginEnd="@dimen/dp_24"
                android:id="@+id/lin_name_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

            <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:fontFamily="sans-serif-medium"
                    android:text="@string/name_and_password"
                    android:textColor="@color/colorBlack"
                    android:layout_marginTop="@dimen/dp_5"
                    android:textSize="@dimen/ts_16"/>

            <EditText
                    android:id="@+id/edit_full_name"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp_44"
                    app:layout_constraintTop_toTopOf="parent"
                    android:hint="@string/email_address_hint"
                    android:inputType="textPersonName"
                    android:imeOptions="flagNoFullscreen"
                    android:textSize="@dimen/ts_15"
                    android:background="@drawable/rounded_border_edittext"
                    android:layout_marginTop="@dimen/dp_15"
                    android:paddingStart="@dimen/dp_8"
                    android:paddingEnd="@dimen/dp_8"
                    android:maxLength="100"
                    android:maxLines="1"/>

            <EditText
                    android:id="@+id/edit_password"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp_44"
                    app:layout_constraintTop_toTopOf="parent"
                    android:hint="@string/password"
                    android:inputType="textPassword"
                    android:imeOptions="flagNoFullscreen"
                    android:textSize="@dimen/ts_15"
                    android:background="@drawable/rounded_border_edittext"
                    android:layout_marginTop="@dimen/dp_15"
                    android:paddingStart="@dimen/dp_8"
                    android:paddingEnd="@dimen/dp_8"
                    android:maxLength="100"
                    android:maxLines="1"/>

            <TextView
                    android:id="@+id/btn_continue_and_sync_contacts"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp_44"
                    android:gravity="center"
                    android:clickable="true"
                    android:focusable="true"
                    android:layout_marginTop="@dimen/dp_15"
                    android:background="@drawable/btn_blue_selector"
                    android:enabled="false"
                    android:text="@string/continue_and_sync_contacts"
                    android:textColor="@color/colorWhite"
                    android:textSize="@dimen/ts_15"
                    android:textStyle="bold"/>

            <TextView
                    android:id="@+id/btn_continue_without_syncing_contacts"
                    android:layout_width="match_parent"
                    android:layout_height="@dimen/dp_44"
                    android:gravity="center"
                    android:clickable="true"
                    android:focusable="true"
                    android:layout_marginTop="@dimen/dp_10"
                    android:enabled="false"
                    android:text="@string/continue_without_syncing_contacts"
                    android:textColor="@color/colorBlue"
                    android:textSize="@dimen/ts_15"
                    android:textStyle="bold"/>

        </LinearLayout>
        <!--RelativeLayout is scaled when keyboard appears-->
        <RelativeLayout
                android:layout_marginStart="@dimen/dp_24"
                android:layout_marginEnd="@dimen/dp_24"
                android:layout_marginBottom="@dimen/dp_20"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

            <LinearLayout
                    android:layout_alignParentBottom="true"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
                <TextView
                        android:id="@+id/tv_learn_more_1"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:clickable="true"
                        android:focusable="true"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/learn_more_syncing_contacts"
                        android:textColor="@color/black_alpha_70"
                        android:gravity="center"
                        android:layout_marginBottom="1dp"
                        android:textSize="@dimen/ts_13"/>

                <TextView
                        android:id="@+id/tv_learn_more_2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:clickable="true"
                        android:focusable="true"
                        android:layout_gravity="center_horizontal"
                        android:text="@string/learn_more"
                        android:fontFamily="sans-serif-medium"
                        android:textColor="@color/black_alpha_70"
                        android:textSize="@dimen/ts_13"/>
            </LinearLayout>
        </RelativeLayout>
    </LinearLayout>
</ScrollView>

rounded_border_edittext.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_activated="true">
        <shape android:shape="rectangle">
            <solid android:color="#F6F6F6"/>
            <corners android:radius="3dp"/>
            <stroke
                    android:width="1dp"
                    android:color="@color/red"/>
        </shape>
    </item>
    <item android:state_activated="false">
        <shape android:shape="rectangle">
            <solid android:color="#F6F6F6"/>
            <corners android:radius="3dp"/>
            <stroke
                    android:width="1dp"
                    android:color="@color/colorGray"/>
        </shape>
    </item>
</selector>

btn_blue_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true" android:state_pressed="true">
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <solid android:color="@color/colorBlueLight"/>
            <stroke android:width="1dp" android:color="@color/colorBlueLight"/>
        </shape>
    </item>
    <item android:state_enabled="true">
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <solid android:color="@color/colorBlue"/>
            <stroke android:width="1dp" android:color="@color/colorBlue"/>
        </shape>
    </item>
    <item android:state_enabled="false">
        <shape android:shape="rectangle">
            <corners android:radius="3dp"/>
            <solid android:color="@color/colorBlueAlpha"/>
            <stroke android:width="0dp" android:color="@color/colorBlueAlpha"/>
        </shape>
    </item>
</selector>

How to get the employees with their managers

Perhaps your subquery (SELECT ename FROM EMP WHERE empno = mgr) thinks, give me the employee records that are their own managers! (i.e., where the empno of a row is the same as the mgr of the same row.)

have you considered perhaps rewriting this to use an inner (self) join? (I'm asking, becuase i'm not even sure if the following will work or not.)

SELECT t1.ename, t1.empno, t2.ename as MANAGER, t1.mgr
from emp as t1
inner join emp t2 ON t1.mgr = t2.empno
order by t1.empno;

How do I reference tables in Excel using VBA?

A "table" in Excel is indeed known as a ListObject.

The "proper" way to reference a table is by getting its ListObject from its Worksheet i.e. SheetObject.ListObjects(ListObjectName).

If you want to reference a table without using the sheet, you can use a hack Application.Range(ListObjectName).ListObject.

NOTE: This hack relies on the fact that Excel always creates a named range for the table's DataBodyRange with the same name as the table. However this range name can be changed...though it's not something you'd want to do since the name will reset if you edit the table name! Also you could get a named range with no associated ListObject.

Given Excel's not-very-helpful 1004 error message when you get the name wrong, you may want to create a wrapper...

Public Function GetListObject(ByVal ListObjectName As String, Optional ParentWorksheet As Worksheet = Nothing) As Excel.ListObject
On Error Resume Next

    If (Not ParentWorksheet Is Nothing) Then
        Set GetListObject = ParentWorksheet.ListObjects(ListObjectName)
    Else
        Set GetListObject = Application.Range(ListObjectName).ListObject
    End If

On Error GoTo 0 'Or your error handler

    If (Not GetListObject Is Nothing) Then
        'Success
    ElseIf (Not ParentWorksheet Is Nothing) Then
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found on sheet '" & ParentWorksheet.Name & "'!")
    Else
        Call Err.Raise(1004, ThisWorkBook.Name, "ListObject '" & ListObjectName & "' not found!")
    End If

End Function

Also some good ListObject info here.

Calculate percentage saved between two numbers?

    function calculatePercentage($oldFigure, $newFigure)
{
    $percentChange = (($oldFigure - $newFigure) / $oldFigure) * 100;
    return round(abs($percentChange));
}

How can I convert a cv::Mat to a gray scale in OpenCv?

May be helpful for late comers.

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"

using namespace cv;
using namespace std;

int main(int argc, char *argv[])
{
  if (argc != 2) {
    cout << "Usage: display_Image ImageToLoadandDisplay" << endl;
    return -1;
}else{
    Mat image;
    Mat grayImage;

    image = imread(argv[1], IMREAD_COLOR);
    if (!image.data) {
        cout << "Could not open the image file" << endl;
        return -1;
    }
    else {
        int height = image.rows;
        int width = image.cols;

        cvtColor(image, grayImage, CV_BGR2GRAY);


        namedWindow("Display window", WINDOW_AUTOSIZE);
        imshow("Display window", image);

        namedWindow("Gray Image", WINDOW_AUTOSIZE);
        imshow("Gray Image", grayImage);
        cvWaitKey(0);
        image.release();
        grayImage.release();
        return 0;
    }

  }

}

YouTube Autoplay not working

This code allows you to autoplay iframe video

<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1"  width="560" height="315"  frameborder="0" allowfullscreen></iframe>

Here Is working fiddle

Environment variables for java installation

In Windows 7, right-click on Computer -> Properties -> Advanced system settings; then in the Advanced tab, click Environment Variables... -> System variables -> New....

Give the new system variable the name JAVA_HOME and the value C:\Program Files\Java\jdk1.7.0_79 (depending on your JDK installation path it varies).

Then select the Path system variable and click Edit.... Keep the variable name as Path, and append C:\Program Files\Java\jdk1.7.0_79\bin; or %JAVA_HOME%\bin; (both mean the same) to the variable value.

Once you are done with above changes, try below steps. If you don't see similar results, restart the computer and try again. If it still doesn't work you may need to reinstall JDK.

Open a Windows command prompt (Windows key + R -> enter cmd -> OK), and check the following:

java -version

You will see something like this:

java version "1.7.0_79"
Java(TM) SE Runtime Environment (build 1.7.0_79-b15)
Java HotSpot(TM) 64-Bit Server VM (build 24.79-b02, mixed mode)

Then check the following:

javac -version

You will see something like this:

javac 1.7.0_79

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to parse XML using shellscript?

Here's a full working example.
If it's only extracting email addresses you could just do something like:
1) Suppose XML file spam.xml is like

<spam>
<victims>
  <victim>
    <name>The Pope</name>
    <email>[email protected]</email>
    <is_satan>0</is_satan>
  </victim>
  <victim>
    <name>George Bush</name>
    <email>[email protected]</email>
    <is_satan>1</is_satan>
  </victim>
  <victim>
    <name>George Bush Jr</name>
    <email>[email protected]</email>
    <is_satan>0</is_satan>
  </victim>
</victims>
</spam>

2) You can get the emails and process them with this short bash code:

#!/bin/bash
emails=($(grep -oP '(?<=email>)[^<]+' "/my_path/spam.xml"))

for i in ${!emails[*]}
do
  echo "$i" "${emails[$i]}"
  # instead of echo use the values to send emails, etc
done

Result of this example is:

0 [email protected]
1 [email protected]
2 [email protected]

Important note:
Don't use this for serious matters. This is OK for playing around, getting quick results, learning grep, etc. but you should definitely look for, learn and use an XML parser for production (see Micha's comment below).

How to compile and run C/C++ in a Unix console/Mac terminal?

If it is a simple single source program:

make foo

where the source file is foo.c or foo.cpp, etc.

You dont even need a makefile. Make has enough built-in rules to build your source file into an executable of the same name, minus extension.

Running the executable just built is the same as running any program - but you will most often need to specify the path to the executable as the shell will only search what is in $PATH to find executables, and most often that does not include the current directory (.).

So to run the built executable foo:

./foo

android on Text Change Listener

var filenameText = findViewById(R.id.filename) as EditText
filenameText.addTextChangedListener(object : TextWatcher {
    override fun afterTextChanged(s: Editable?) {
        filename = filenameText.text.toString()
        Log.i("FileName: ", filename)
    }
    
    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}
    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})

Overloading operators in typedef structs (c++)

Instead of typedef struct { ... } pos; you should be doing struct pos { ... };. The issue here is that you are using the pos type name before it is defined. By moving the name to the top of the struct definition, you are able to use that name within the struct definition itself.

Further, the typedef struct { ... } name; pattern is a C-ism, and doesn't have much place in C++.

To answer your question about inline, there is no difference in this case. When a method is defined within the struct/class definition, it is implicitly declared inline. When you explicitly specify inline, the compiler effectively ignores it because the method is already declared inline.

(inline methods will not trigger a linker error if the same method is defined in multiple object files; the linker will simply ignore all but one of them, assuming that they are all the same implementation. This is the only guaranteed change in behavior with inline methods. Nowadays, they do not affect the compiler's decision regarding whether or not to inline functions; they simply facilitate making the function implementation available in all translation units, which gives the compiler the option to inline the function, if it decides it would be beneficial to do so.)

How to return data from PHP to a jQuery ajax call

It's an argument passed to your success function:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

What are the date formats available in SimpleDateFormat class?

Date and time formats are well described below

SimpleDateFormat (Java Platform SE 7) - Date and Time Patterns

There could be n Number of formats you can possibly make. ex - dd/MM/yyyy or YYYY-'W'ww-u or you can mix and match the letters to achieve your required pattern. Pattern letters are as follow.

  • G - Era designator (AD)
  • y - Year (1996; 96)
  • Y - Week Year (2009; 09)
  • M - Month in year (July; Jul; 07)
  • w - Week in year (27)
  • W - Week in month (2)
  • D - Day in year (189)
  • d - Day in month (10)
  • F - Day of week in month (2)
  • E - Day name in week (Tuesday; Tue)
  • u - Day number of week (1 = Monday, ..., 7 = Sunday)
  • a - AM/PM marker
  • H - Hour in day (0-23)
  • k - Hour in day (1-24)
  • K - Hour in am/pm (0-11)
  • h - Hour in am/pm (1-12)
  • m - Minute in hour (30)
  • s - Second in minute (55)
  • S - Millisecond (978)
  • z - General time zone (Pacific Standard Time; PST; GMT-08:00)
  • Z - RFC 822 time zone (-0800)
  • X - ISO 8601 time zone (-08; -0800; -08:00)

To parse:

2000-01-23T04:56:07.000+0000

Use: new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

Send password when using scp to copy files from one server to another

One of the ways to get around login issues with ssh, scp, and sftp (all use the same protocol and sshd server) is to create public/private key pairings.

Some servers may disallow this, but most sites don't. These directions are for Unix/Linux/Mac. As always, Windows is a wee bit different although the cygwin environment on Windows does follow these steps.

  • On your machine, create your public/private key using ssh-keygen. This can vary from system to system, but the program should lead you through this.
  • When ssh-keygen is finished, you will have a $HOME/.ssh directory on your machine. This directory will contain a public key and a private key. There will be two more files that are generated as you go along. One is known_hosts which contains the fingerprints of all known hosts you've logged into. The second will be called either authorized_keys or authorized_keys2 depending upon your implementation.
  • If it's not there already, log into the remote host, and run ssh-keygen there too. This will generate a $HOME/.ssh directory there as well as a private/public key pair. Don't do this if the $HOME/.ssh directory already exists and has a public and private key file. You don't want to regenerate it.
  • On the remote server in the $HOME/.ssh directory, create a file called authorized_keys. In this file, put your public key. This public key is found on your $HOME/.ssh directory on your local machine. It will end with *.pub. Paste the contents of that into authorized_keys. If authorized_keys already exists, paste your public key in the next line.

Now, when you log in using ssh, or you use scp or sftp, you will not be required to enter a password. By the way, the user IDs on the two machines do not have to agree. I've logged into many remote servers as a different user and setup my public key in authorized_keys and have no problems logging directly into that user.

Doing Private Public Key Authentication on Windows

If you use Windows, you will need something that can do ssh. Most people I know use PuTTY which can generate public/private keys, and do the key pairing when you login remotely. I can't remember all of the steps, but you generate two files (one contains the public key, one contains the private key), and configure PuTTY to use both of those when logging into a remote site. If that remote site is Linux/Unix/Mac, you can copy your public key and put it into the authorized_keys file.

If you can use SSH Public/Private keys, you can eliminate the need for passwords in your scripts. Otherwise, you will have to use something like Expect or Perl with Net::SSH which can watch the remote host and enter the password when prompted.

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

Rotate camera in Three.js with mouse

This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):

class CameraControl {
    zoomMode: boolean = false
    press: boolean = false
    sensitivity: number = 0.02

    constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
        renderer.domElement.addEventListener('mousemove', event => {
            if(!this.press){ return }

            if(event.button == 0){
                camera.position.y -= event.movementY * this.sensitivity
                camera.position.x -= event.movementX * this.sensitivity        
            } else if(event.button == 2){
                camera.quaternion.y -= event.movementX * this.sensitivity/10
                camera.quaternion.x -= event.movementY * this.sensitivity/10
            }

            updateCallback()
        })    

        renderer.domElement.addEventListener('mousedown', () => { this.press = true })
        renderer.domElement.addEventListener('mouseup', () => { this.press = false })
        renderer.domElement.addEventListener('mouseleave', () => { this.press = false })

        document.addEventListener('keydown', event => {
            if(event.key == 'Shift'){
                this.zoomMode = true
            }
        })

        document.addEventListener('keyup', event => {
            if(event.key == 'Shift'){
                this.zoomMode = false
            }
        })

        renderer.domElement.addEventListener('mousewheel', event => {
            if(this.zoomMode){ 
                camera.fov += event.wheelDelta * this.sensitivity
                camera.updateProjectionMatrix()
            } else {
                camera.position.z += event.wheelDelta * this.sensitivity
            }

            updateCallback()
        })
    }
}

drop it in like:

this.cameraControl = new CameraControl(renderer, camera, () => {
    // you might want to rerender on camera update if you are not rerendering all the time
    window.requestAnimationFrame(() => renderer.render(scene, camera))
})

Controls:

  • move while [holding mouse left / single finger on trackpad] to move camera in x/y plane
  • move [mouse wheel / two fingers on trackpad] to move up/down in z-direction
  • hold shift + [mouse wheel / two fingers on trackpad] to zoom in/out via increasing/decreasing field-of-view
  • move while holding [mouse right / two fingers on trackpad] to rotate the camera (quaternion)

Additionally:

If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:

// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)

Cancel a UIView animation?

Swift version of Stephen Darlington's solution

UIView.beginAnimations(nil, context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(0.1)
// other animation properties

// set view properties
UIView.commitAnimations()

List Directories and get the name of the Directory

Listing the entries in the current directory (for directories in os.listdir(os.getcwd()):) and then interpreting those entries as subdirectories of an entirely different directory (dir = os.path.join('/home/user/workspace', directories)) is one thing that looks fishy.

How to scroll to bottom in a ScrollView on activity startup

Try this

    final ScrollView scrollview = ((ScrollView) findViewById(R.id.scrollview));
    scrollview.post(new Runnable() {
       @Override
       public void run() {
         scrollview.fullScroll(ScrollView.FOCUS_DOWN);
       }
    });

How can I group data with an Angular filter?

If you need that in js code. You can use injected method of angula-filter lib. Like this.

function controller($scope, $http, groupByFilter) {     

   var groupedData = groupByFilter(originalArray, 'groupPropName');

}

https://github.com/a8m/angular-filter/wiki/Common-Questions#inject-filters

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

Storing Data in MySQL as JSON

This is an old question, but I am still able to see this at the top of the search result of Google, so I guess it would be meaningful to add a new answer 4 years after the question is asked.

First of all, there is better support in storing JSON in RDBMS. You may consider switching to PostgreSQL (although MySQL has supported JSON since v5.7.7). PostgreSQL uses very similar SQL commands as MySQL except they support more functions. One of the functions they added is that they provide JSON data type and you are now able to query the JSON stored. (Some reference on this) If you are not making up the query directly in your program, for example, using PDO in php or eloquent in Laravel, all you need to do is just to install PostgreSQL on your server and change database connection settings. You don't even need to change your code.

Most of the time, as the other answers suggested, storing data as JSON directly in RDBMS is not a good idea. There are some exception though. One situation I can think of is a field with variable number of linked entry.

For example, for storing tag of a blog post, normally you will need to have a table for blog post, a table of tag and a matching table. So, when the user wants to edit a post and you need to display which tag is related to that post, you will need to query 3 tables. This will damage the performance a lot if your matching table / tag table is long.

By storing the tags as JSON in the blog post table, the same action only requires a single table search. The user will then be able to see the blog post to be edit quicker, but this will damage the performance if you want to make a report on what post is linked to a tag, or maybe search by tag.

You may also try to de-normalize the database. By duplicating the data and storing the data in both ways, you can receive benefit of both method. You will just need a little bit more time to store your data and more storage space (which is cheap comparing to the cost of more computing power)

Convert number of minutes into hours & minutes using PHP

The easiest way is :

    gmdate('H:i', $numberOfSeconds * 60)

Excel select a value from a cell having row number calculated

You could use the INDIRECT function. This takes a string and converts it into a range

More info here

=INDIRECT("K"&A2)

But it's preferable to use INDEX as it is less volatile.

=INDEX(K:K,A2)

This returns a value or the reference to a value from within a table or range

More info here

Put either function into cell B2 and fill down.

Running an outside program (executable) in Python?

for the above question this solution works.

just change the path to where your executable file is located.

import sys, string, os

os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')

os.system("C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\flowwork.exe")


'''import sys, string, os

os.chdir('C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\\bin64')

os.system(r"C:\\Downloads\\xpdf-tools-win-4.00\\xpdf-tools-win-4.00\bin64\\pdftopng.exe test1.pdf rootimage")'''

Here test1.pdf rootimage is for my code .

Reset AutoIncrement in SQL Server after Delete

DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)

if number=0 then in the next insert the auto increment field will contain value 1

if number=101 then in the next insert the auto increment field will contain value 102


Some additional info... May be useful to you

Before giving auto increment number in above query, you have to make sure your existing table's auto increment column contain values less that number.

To get the maximum value of a column(column_name) from a table(table1), you can use following query

 SELECT MAX(column_name) FROM table1

JUnit Testing Exceptions

are you sure you told it to expect the exception?

for newer junit (>= 4.7), you can use something like (from here)

@Rule
public ExpectedException exception = ExpectedException.none();

@Test
public void testRodneCisloRok(){
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("error1");
    new RodneCislo("891415",dopocitej("891415"));
}

and for older junit, this:

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
  int i = 1/0;
}

Find in Files: Search all code in Team Foundation Server

In my case, writing a small utility in C# helped. Links that helped me - http://pascallaurin42.blogspot.com/2012/05/tfs-queries-searching-in-all-files-of.html

How to list files of a team project using tfs api?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Framework.Client;
using System.IO;

namespace TFSSearch
{
class Program
{
    static string[] textPatterns = new[] { "void main(", "exception", "RegisterScript" };  //Text to search
    static string[] filePatterns = new[] { "*.cs", "*.xml", "*.config", "*.asp", "*.aspx", "*.js", "*.htm", "*.html", 
                                           "*.vb", "*.asax", "*.ashx", "*.asmx", "*.ascx", "*.master", "*.svc"}; //file extensions

    static void Main(string[] args)
    {
        try
        {
            var tfs = TfsTeamProjectCollectionFactory
             .GetTeamProjectCollection(new Uri("http://{tfsserver}:8080/tfs/}")); // one some servers you also need to add collection path (if it not the default collection)

            tfs.EnsureAuthenticated();

            var versionControl = tfs.GetService<VersionControlServer>();


            StreamWriter outputFile = new StreamWriter(@"C:\Find.txt");
            var allProjs = versionControl.GetAllTeamProjects(true);
            foreach (var teamProj in allProjs)
            {
                foreach (var filePattern in filePatterns)
                {
                    var items = versionControl.GetItems(teamProj.ServerItem + "/" + filePattern, RecursionType.Full).Items
                                .Where(i => !i.ServerItem.Contains("_ReSharper"));  //skipping resharper stuff
                    foreach (var item in items)
                    {
                        List<string> lines = SearchInFile(item);
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine("FILE:" + item.ServerItem);
                            outputFile.WriteLine(lines.Count.ToString() + " occurence(s) found.");
                            outputFile.WriteLine();
                        }
                        foreach (string line in lines)
                        {
                            outputFile.WriteLine(line);
                        }
                        if (lines.Count > 0)
                        {
                            outputFile.WriteLine();
                        }
                    }
                }
                outputFile.Flush();
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }
        Console.WriteLine("========");
        Console.Read();
    }

    // Define other methods and classes here
    private static List<string> SearchInFile(Item file)
    {
        var result = new List<string>();

        try
        {
            var stream = new StreamReader(file.DownloadFile(), Encoding.Default);

            var line = stream.ReadLine();
            var lineIndex = 0;

            while (!stream.EndOfStream)
            {
                if (textPatterns.Any(p => line.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0))
                    result.Add("=== Line " + lineIndex + ": " + line.Trim());

                line = stream.ReadLine();
                lineIndex++;
            }
        }
        catch (Exception e)
        {
            string ex = e.Message;
            Console.WriteLine("!!EXCEPTION: " + e.Message);
            Console.WriteLine("Continuing... ");
        }

        return result;
    }
}
}

How to remove a build from itunes connect?

Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing

  1. I set release to "manual" and saved
  2. I tried to create and app release
  3. got an error message something like "you can only have one release at a time"
  4. where the save button was there was not an option to cancel release
  5. the version of the app is not marked "developer rejected" with a red dot

To replace the bad build I did the following

  1. if you click on the "+ version or platform" to create a new version you will not be be able to create a new iOS version
  2. you need to upload a new build
  3. in your rejected app, select the new build
  4. save
  5. submit for review

c# search string in txt file

If your pair of lines will only appear once in your file, you could use

File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .Skip(1) // optional
    .TakeWhile(line => !line.Contains("CustomerCh"));

If you could have multiple occurrences in one file, you're probably better off using a regular foreach loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:

List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
    if (line.Contains("CustomerEN") && current == null)
        current = new List<string>();
    else if (line.Contains("CustomerCh") && current != null)
    {
        groups.Add(current);
        current = null;
    }
    if (current != null)
        current.Add(line);
}

How do I break a string across more than one line of code in JavaScript?

Put the backslash at the end of the line:

alert("Please Select file\
 to delete");

Edit    I have to note that this is not part of ECMAScript strings as line terminating characters are not allowed at all:

A 'LineTerminator' character cannot appear in a string literal, even if preceded by a backslash \. The correct way to cause a line terminator character to be part of the string value of a string literal is to use an escape sequence such as \n or \u000A.

So using string concatenation is the better choice.


Update 2015-01-05    String literals in ECMAScript5 allow the mentioned syntax:

A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as \n or \u000A.

How can I set NODE_ENV=production on Windows?

In case you are using GITBASH terminal "set NODE_ENV=production" will not work, what can you do is type "export NODE_ENV=production"

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

Which Protocols are used for PING?

Internet Control Message Protocol

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

ICMP is built on top of a bunch of other protocols, so in that sense your TA is correct. However, ping itself is ICMP.

instantiate a class from a variable in PHP?

class Test {
    public function yo() {
        return 'yoes';
    }
}

$var = 'Test';

$obj = new $var();
echo $obj->yo(); //yoes

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

setInterval in a React app

Manage setInterval with React Hooks:

  const [seconds, setSeconds] = useState(0)

  const interval = useRef(null)

  useEffect(() => { if (seconds === 60) stopCounter() }, [seconds])

  const startCounter = () => interval.current = setInterval(() => {
    setSeconds(prevState => prevState + 1)
  }, 1000)

  const stopCounter = () => clearInterval(interval.current)

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

Flask raises TemplateNotFound error even though template file exists

Check that:

  1. the template file has the right name
  2. the template file is in a subdirectory called templates
  3. the name you pass to render_template is relative to the template directory (index.html would be directly in the templates directory, auth/login.html would be under the auth directory in the templates directory.)
  4. you either do not have a subdirectory with the same name as your app, or the templates directory is inside that subdir.

If that doesn't work, turn on debugging (app.debug = True) which might help figure out what's wrong.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

Full solution in Firefox 5:

<html>
<head>
</head>
<body>
 <form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
  <input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input> 
 </form>

<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>"; 


$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {

 echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
 $ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1); 

 // generate a random new file name to avoid name conflict
 $fPath = md5(rand() * time()) . ".$ext";

 echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
 $result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);

 if (strlen($ext) > 0){
  echo "Uploaded ". $fPath ." succefully. <br>";
 }
}
echo "Upload complete.<br>";
?>

</body>
</html>

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

Finding Key associated with max Value in a Java Map

1. Using Stream

public <K, V extends Comparable<V>> V maxUsingStreamAndLambda(Map<K, V> map) {
    Optional<Entry<K, V>> maxEntry = map.entrySet()
        .stream()
        .max((Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
            .compareTo(e2.getValue())
        );

    return maxEntry.get().getKey();
}

2. Using Collections.max() with a Lambda Expression

    public <K, V extends Comparable<V>> V maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
        Entry<K, V> maxEntry = Collections.max(map.entrySet(), (Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue()
            .compareTo(e2.getValue()));
        return maxEntry.getKey();
    }

3. Using Stream with Method Reference

    public <K, V extends Comparable<V>> V maxUsingStreamAndMethodReference(Map<K, V> map) {
        Optional<Entry<K, V>> maxEntry = map.entrySet()
            .stream()
            .max(Comparator.comparing(Map.Entry::getValue));
        return maxEntry.get()
            .getKey();
    }

4. Using Collections.max()

    public <K, V extends Comparable<V>> V maxUsingCollectionsMax(Map<K, V> map) {
        Entry<K, V> maxEntry = Collections.max(map.entrySet(), new Comparator<Entry<K, V>>() {
            public int compare(Entry<K, V> e1, Entry<K, V> e2) {
                return e1.getValue()
                    .compareTo(e2.getValue());
            }
        });
        return maxEntry.getKey();
    }

5. Using Simple Iteration

public <K, V extends Comparable<V>> V maxUsingIteration(Map<K, V> map) {
    Map.Entry<K, V> maxEntry = null;
    for (Map.Entry<K, V> entry : map.entrySet()) {
        if (maxEntry == null || entry.getValue()
            .compareTo(maxEntry.getValue()) > 0) {
            maxEntry = entry;
        }
    }
    return maxEntry.getKey();
}

Returning JSON response from Servlet to Javascript/JSP page

Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:

JSONObject json      = new JSONObject();
JSONArray  addresses = new JSONArray();
JSONObject address;
try
{
   int count = 15;

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("CustomerName"     , "Decepticons" + i);
       address.put("AccountId"        , "1999" + i);
       address.put("SiteId"           , "1888" + i);
       address.put("Number"            , "7" + i);
       address.put("Building"          , "StarScream Skyscraper" + i);
       address.put("Street"            , "Devestator Avenue" + i);
       address.put("City"              , "Megatron City" + i);
       address.put("ZipCode"          , "ZZ00 XX1" + i);
       address.put("Country"           , "CyberTron" + i);
       addresses.add(address);
   }
   json.put("Addresses", addresses);
}
catch (JSONException jse)
{ 

}
response.setContentType("application/json");
response.getWriter().write(json.toString());

This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel

Is there a way to reduce the size of the git folder?

One scenario where your git repo will get seriously bigger with each commit is one where you are committing binary files that you generate regularly. Their storage won't be as efficient than text file.

Another is one where you have a huge number of files within one repo (which is a limit of git) instead of several subrepos (managed as submodules).

In this article on git space, AlBlue mentions:

Note that Git (and Hg, and other DVCSs) do suffer from a problem where (large) binaries are checked in, then deleted, as they'll still show up in the repository and take up space, even if they're not current.

If you have large binaries stored in your git repo, you may consider:

As I mentioned in "What are the file limits in Git (number and size)?", the more recent (2015, 5 years after this answer) Git LFS from GitHub is a way to manage those large files (by storing them outside the Git repository).

Combining border-top,border-right,border-left,border-bottom in CSS

Or if all borders have same style, just:

border:10px;

TypeError: $ is not a function WordPress

Function errors are a common thing in almost all content management systems and there is a few ways you can approach this.

  1. Wrap your code using:

    <script> 
    jQuery(function($) {
    
    YOUR CODE GOES HERE
    
    });
    </script>
    
  2. You can also use jQuery's API using noConflict();

    <script>
    $.noConflict();
    jQuery( document ).ready(function( $ ) {
    // Code that uses jQuery's $ can follow here.
    });
    // Code that uses other library's $ can follow here.
    </script>
    
  3. Another example of using noConflict without using document ready:

    <script>
    jQuery.noConflict();
        (function( $ ) {
            $(function() { 
                // YOUR CODE HERE
            });
         });
    </script>
    
  4. You could even choose to create your very alias to avoid conflicts like so:

    var jExample = jQuery.noConflict();
    // Do something with jQuery
    jExample( "div p" ).hide();
    
  5. Yet another longer solution is to rename all referances of $ to jQuery:

    $( "div p" ).hide(); to jQuery( "div p" ).hide();

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

Some limitations though to Steven Bethard's solution :

When you register your class method as a function, the destructor of your class is surprisingly called every time your method processing is finished. So if you have 1 instance of your class that calls n times its method, members may disappear between 2 runs and you may get a message malloc: *** error for object 0x...: pointer being freed was not allocated (e.g. open member file) or pure virtual method called, terminate called without an active exception (which means than the lifetime of a member object I used was shorter than what I thought). I got this when dealing with n greater than the pool size. Here is a short example :

from multiprocessing import Pool, cpu_count
from multiprocessing.pool import ApplyResult

# --------- see Stenven's solution above -------------
from copy_reg import pickle
from types import MethodType

def _pickle_method(method):
    func_name = method.im_func.__name__
    obj = method.im_self
    cls = method.im_class
    return _unpickle_method, (func_name, obj, cls)

def _unpickle_method(func_name, obj, cls):
    for cls in cls.mro():
        try:
            func = cls.__dict__[func_name]
        except KeyError:
            pass
        else:
            break
    return func.__get__(obj, cls)


class Myclass(object):

    def __init__(self, nobj, workers=cpu_count()):

        print "Constructor ..."
        # multi-processing
        pool = Pool(processes=workers)
        async_results = [ pool.apply_async(self.process_obj, (i,)) for i in range(nobj) ]
        pool.close()
        # waiting for all results
        map(ApplyResult.wait, async_results)
        lst_results=[r.get() for r in async_results]
        print lst_results

    def __del__(self):
        print "... Destructor"

    def process_obj(self, index):
        print "object %d" % index
        return "results"

pickle(MethodType, _pickle_method, _unpickle_method)
Myclass(nobj=8, workers=3)
# problem !!! the destructor is called nobj times (instead of once)

Output:

Constructor ...
object 0
object 1
object 2
... Destructor
object 3
... Destructor
object 4
... Destructor
object 5
... Destructor
object 6
... Destructor
object 7
... Destructor
... Destructor
... Destructor
['results', 'results', 'results', 'results', 'results', 'results', 'results', 'results']
... Destructor

The __call__ method is not so equivalent, because [None,...] are read from the results :

from multiprocessing import Pool, cpu_count
from multiprocessing.pool import ApplyResult

class Myclass(object):

    def __init__(self, nobj, workers=cpu_count()):

        print "Constructor ..."
        # multiprocessing
        pool = Pool(processes=workers)
        async_results = [ pool.apply_async(self, (i,)) for i in range(nobj) ]
        pool.close()
        # waiting for all results
        map(ApplyResult.wait, async_results)
        lst_results=[r.get() for r in async_results]
        print lst_results

    def __call__(self, i):
        self.process_obj(i)

    def __del__(self):
        print "... Destructor"

    def process_obj(self, i):
        print "obj %d" % i
        return "result"

Myclass(nobj=8, workers=3)
# problem !!! the destructor is called nobj times (instead of once), 
# **and** results are empty !

So none of both methods is satisfying...

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to escape double quotes in a title attribute

Using &quot; is the way to do it. I tried your second code snippet, and it works in both Firefox and Internet Explorer.

Method Call Chaining; returning a pointer vs a reference?

Very interesting question.

I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.

But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.

What is the best way to use a HashMap in C++?

A hash_map is an older, unstandardized version of what for standardization purposes is called an unordered_map (originally in TR1, and included in the standard since C++11). As the name implies, it's different from std::map primarily in being unordered -- if, for example, you iterate through a map from begin() to end(), you get items in order by key1, but if you iterate through an unordered_map from begin() to end(), you get items in a more or less arbitrary order.

An unordered_map is normally expected to have constant complexity. That is, an insertion, lookup, etc., typically takes essentially a fixed amount of time, regardless of how many items are in the table. An std::map has complexity that's logarithmic on the number of items being stored -- which means the time to insert or retrieve an item grows, but quite slowly, as the map grows larger. For example, if it takes 1 microsecond to lookup one of 1 million items, then you can expect it to take around 2 microseconds to lookup one of 2 million items, 3 microseconds for one of 4 million items, 4 microseconds for one of 8 million items, etc.

From a practical viewpoint, that's not really the whole story though. By nature, a simple hash table has a fixed size. Adapting it to the variable-size requirements for a general purpose container is somewhat non-trivial. As a result, operations that (potentially) grow the table (e.g., insertion) are potentially relatively slow (that is, most are fairly fast, but periodically one will be much slower). Lookups, which cannot change the size of the table, are generally much faster. As a result, most hash-based tables tend to be at their best when you do a lot of lookups compared to the number of insertions. For situations where you insert a lot of data, then iterate through the table once to retrieve results (e.g., counting the number of unique words in a file) chances are that an std::map will be just as fast, and quite possibly even faster (but, again, the computational complexity is different, so that can also depend on the number of unique words in the file).


1 Where the order is defined by the third template parameter when you create the map, std::less<T> by default.

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

How to trigger event in JavaScript?

You can use below code to fire event using Element method:

if (!Element.prototype.triggerEvent) {
    Element.prototype.triggerEvent = function (eventName) {
        var event;

        if (document.createEvent) {
            event = document.createEvent("HTMLEvents");
            event.initEvent(eventName, true, true);
        } else {
            event = document.createEventObject();
            event.eventType = eventName;
        }

        event.eventName = eventName;

        if (document.createEvent) {
            this.dispatchEvent(event);
        } else {
            this.fireEvent("on" + event.eventType, event);
        }
    };
}

_x000D_
_x000D_
if (!Element.prototype.triggerEvent) {_x000D_
    Element.prototype.triggerEvent = function (eventName) {_x000D_
        var event;_x000D_
_x000D_
        if (document.createEvent) {_x000D_
            event = document.createEvent("HTMLEvents");_x000D_
            event.initEvent(eventName, true, true);_x000D_
        } else {_x000D_
            event = document.createEventObject();_x000D_
            event.eventType = eventName;_x000D_
        }_x000D_
_x000D_
        event.eventName = eventName;_x000D_
_x000D_
        if (document.createEvent) {_x000D_
            this.dispatchEvent(event);_x000D_
        } else {_x000D_
            this.fireEvent("on" + event.eventType, event);_x000D_
        }_x000D_
    };_x000D_
}_x000D_
_x000D_
var input = document.getElementById("my_input");_x000D_
var button = document.getElementById("my_button");_x000D_
_x000D_
input.addEventListener('change', function (e) {_x000D_
    alert('change event fired');_x000D_
});_x000D_
button.addEventListener('click', function (e) {_x000D_
    input.value = "Bye World";_x000D_
    input.triggerEvent("change");_x000D_
});
_x000D_
<input id="my_input" type="input" value="Hellow World">_x000D_
<button id="my_button">Change Input</button>
_x000D_
_x000D_
_x000D_

What is JSONP, and why was it created?

JSONP is a great away to get around cross-domain scripting errors. You can consume a JSONP service purely with JS without having to implement a AJAX proxy on the server side.

You can use the b1t.co service to see how it works. This is a free JSONP service that alllows you to minify your URLs. Here is the url to use for the service:

http://b1t.co/Site/api/External/MakeUrlWithGet?callback=[resultsCallBack]&url=[escapedUrlToMinify]

For example the call, http://b1t.co/Site/api/External/MakeUrlWithGet?callback=whateverJavascriptName&url=google.com

would return

whateverJavascriptName({"success":true,"url":"http://google.com","shortUrl":"http://b1t.co/54"});

And thus when that get's loaded in your js as a src, it will automatically run whateverJavascriptName which you should implement as your callback function:

function minifyResultsCallBack(data)
{
    document.getElementById("results").innerHTML = JSON.stringify(data);
}

To actually make the JSONP call, you can do it about several ways (including using jQuery) but here is a pure JS example:

function minify(urlToMinify)
{
   url = escape(urlToMinify);
   var s = document.createElement('script');
   s.id = 'dynScript';
   s.type='text/javascript';
   s.src = "http://b1t.co/Site/api/External/MakeUrlWithGet?callback=resultsCallBack&url=" + url;
   document.getElementsByTagName('head')[0].appendChild(s);
}

A step by step example and a jsonp web service to practice on is available at: this post

How can I get the MAC and the IP address of a connected client in PHP?

You can use the following solution to solve your problem:

$mac='UNKNOWN';
foreach(explode("\n",str_replace(' ','',trim(`getmac`,"\n"))) as $i)
if(strpos($i,'Tcpip')>-1){$mac=substr($i,0,17);break;}
echo $mac;

UITableViewCell Selected Background Color on Multiple Selection

By adding a custom view with the background color of your own you can have a custom selection style in table view.

let customBGColorView = UIView()
customBGColorView.backgroundColor = UIColor(hexString: "#FFF900")
cellObj.selectedBackgroundView = customBGColorView

Add this 3 line code in cellForRowAt method of TableView. I have used an extension in UIColor to add color with hexcode. Put this extension code at the end of any Class(Outside the class's body).

extension UIColor {    
convenience init(hexString: String) {
    let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
    var int = UInt32()
    Scanner(string: hex).scanHexInt32(&int)
    let a, r, g, b: UInt32
    switch hex.characters.count {
    case 3: // RGB (12-bit)
        (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
    case 6: // RGB (24-bit)
        (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
    case 8: // ARGB (32-bit)
        (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
    default:
        (a, r, g, b) = (255, 0, 0, 0)
    }
    self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
  }
}

How to use Collections.sort() in Java?

Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().

class RecipeCompare implements Comparator<Recipe> {

    @Override
    public int compare(Recipe o1, Recipe o2) {
        // write comparison logic here like below , it's just a sample
        return o1.getID().compareTo(o2.getID());
    }
}

Then use the Comparator as

Collections.sort(recipes,new RecipeCompare());

Setting a timeout for socket operations

You don't set a timeout for the socket, you set a timeout for the operations you perform on that socket.

For example socket.connect(otherAddress, timeout)

Or socket.setSoTimeout(timeout) for setting a timeout on read() operations.

See: http://docs.oracle.com/javase/7/docs/api/java/net/Socket.html

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Is there a decent wait function in C++?

getchar() provides a simplistic answer (waits for keyboard input). Call Sleep(milliseconds) to sleep before exit. Sleep function (MSDN)

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

Passing a URL with brackets to curl

Globbing uses brackets, hence the need to escape them with a slash \. Alternatively, the following command-line switch will disable globbing:

--globoff (or the short-option version: -g)

Ex:

curl --globoff https://www.google.com?test[]=1

Create parameterized VIEW in SQL Server 2008

in fact there exists one trick:

create view view_test as

select
  * 
from 
  table 
where id = (select convert(int, convert(binary(4), context_info)) from master.dbo.sysprocesses
where
spid = @@spid)

... in sql-query:

set context_info 2
select * from view_test

will be the same with

select * from table where id = 2

but using udf is more acceptable

Change private static final field using Java reflection

Just saw that question on one of the interview question, if possible to change final variable with reflection or in runtime. Got really interested, so that what I became with:

 /**
 * @author Dmitrijs Lobanovskis
 * @since 03/03/2016.
 */
public class SomeClass {

    private final String str;

    SomeClass(){
        this.str = "This is the string that never changes!";
    }

    public String getStr() {
        return str;
    }

    @Override
    public String toString() {
        return "Class name: " + getClass() + " Value: " + getStr();
    }
}

Some simple class with final String variable. So in the main class import java.lang.reflect.Field;

/**
 * @author Dmitrijs Lobanovskis
 * @since 03/03/2016.
 */
public class Main {


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

        SomeClass someClass = new SomeClass();
        System.out.println(someClass);

        Field field = someClass.getClass().getDeclaredField("str");
        field.setAccessible(true);

        field.set(someClass, "There you are");

        System.out.println(someClass);
    }
}

The output will be as follows:

Class name: class SomeClass Value: This is the string that never changes!
Class name: class SomeClass Value: There you are

Process finished with exit code 0

According to documentation https://docs.oracle.com/javase/tutorial/reflect/member/fieldValues.html

How to sort a List<Object> alphabetically using Object name field

something like

  List<FancyObject> theList = … ;
  Collections.sort (theList,
                    new Comparator<FancyObject> ()
                    { int compare (final FancyObject a, final FancyObject d)
                          { return (a.getName().compareTo(d.getName())); }});

In C#, can a class inherit from another class and an interface?

No, not exactly. But it can inherit from a class and implement one or more interfaces.

Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

Hide/Show Action Bar Option Menu Item for different fragments

Late to the party but the answers above didn't seem to work for me.

My first tab fragment (uses getChildFragmentManager() for inner tabs) has the menu to show a search icon and uses android.support.v7.widget.SearchView to search within the inner tab fragment but navigating to other tabs (which also have inner tabs using getChildFragmentManager()) would not remove the search icon (as not required) and therefore still accessible with no function, maybe as I am using the below (ie outer main tabs with each inner tabs)

getChildFragmentManager(); 

However I use the below in my fragments containing/using the getChildFragmentManager() for inner tabs.

    //region onCreate
    @Override
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    //access setHasOptionsMenu()
    setHasOptionsMenu(true);

    }
    //endregion onCreate

and then clear the menu item inside onPrepareOptionsMenu for fragments(search icon & functions)

    @Override
    public void onPrepareOptionsMenu(Menu menu) {

    super.onPrepareOptionsMenu(menu);

    //clear the menu/hide the icon & disable the search access/function ...
    //this will clear the menu entirely, so rewrite/draw the menu items after if needed
    menu.clear();

    }

Works well and navigating back to the tab/inner tab with the search icon functions re displays the search icon & functions.

Hope this helps...

WAMP 403 Forbidden message on Windows 7

hi there are 2 solutions :

  1. change the port 80 to 81 in the text file (httpd.conf) and click 127.0.0.1:81

  2. change setting the network go to control panel--network and internet--network and sharing center

click-->local area connection select-->propertis check true in the -allow other ..... and --- allo other .....

How do I use regex in a SQLite query?

You could use a regular expression with REGEXP, but that is a silly way to do an exact match.

You should just say WHERE x = '3'.

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

There could be several things causing this and it somewhat depends on what you have set up in your database.

First, you could be using a PK in the table that is also an FK to another table making the relationship 1-1. IN this case you may need to do an update rather than an insert. If you really can have only one address record for an order this may be what is happening.

Next you could be using some sort of manual process to determine the id ahead of time. The trouble with those manual processes is that they can create race conditions where two records gab the same last id and increment it by one and then the second one can;t insert.

Third, you query as it is sent to the database may be creating two records. To determine if this is the case, Run Profiler to see exactly what SQL code you are sending and if ti is a select instead of a values clause, then run the select and see if you have due to the joins gotten some records to be duplicated. IN any even when you are creating code on the fly like this the first troubleshooting step is ALWAYS to run Profiler and see if what got sent was what you expected to be sent.

Is the order of elements in a JSON list preserved?

"Is the order of elements in a JSON list maintained?" is not a good question. You need to ask "Is the order of elements in a JSON list maintained when doing [...] ?" As Felix King pointed out, JSON is a textual data format. It doesn't mutate without a reason. Do not confuse a JSON string with a (JavaScript) object.

You're probably talking about operations like JSON.stringify(JSON.parse(...)). Now the answer is: It depends on the implementation. 99%* of JSON parsers do not maintain the order of objects, and do maintain the order of arrays, but you might as well use JSON to store something like

{
    "son": "David",
    "daughter": "Julia",
    "son": "Tom",
    "daughter": "Clara"
}

and use a parser that maintains order of objects.

*probably even more :)

HTML favicon won't show on google chrome

I've found that (at Chrome 56, OSX) the favicon state appears to be cached for the browser lifetime, so if a favicon isn't being loaded, it won't be until after restarting Chrome. It appears that it doesn't show up in the "application" tab in dev tools and isn't cleared by a hard reload or 'Clear site data'.

Best way to check function arguments?

I did quite a bit of investigation on that topic recently since I was not satisfied with the many libraries I found out there.

I ended up developing a library to address this, it is named valid8. As explained in the documentation, it is for value validation mostly (although it comes bundled with simple type validation functions too), and you might wish to associate it with a PEP484-based type checker such as enforce or pytypes.

This is how you would perform validation with valid8 alone (and mini_lambda actually, to define the validation logic - but it is not mandatory) in your case:

# for type validation
from numbers import Integral
from valid8 import instance_of

# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len

@validate_arg('a', instance_of(Integral))
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', instance_of(str), Len(s) > 0)
def my_function(a: Integral, b, c: str):
    """an example function I'd like to check the arguments of."""
    # check that a is an int
    # check that 0 < b < 10
    # check that c is not an empty string

# check that it works
my_function(0.2, 1, 'r')  # InputValidationError for 'a' HasWrongType: Value should be an instance of <class 'numbers.Integral'>. Wrong value: [0.2].
my_function(0, 0, 'r')    # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0)      # InputValidationError for 'c' Successes: [] / Failures: {"instance_of_<class 'str'>": "HasWrongType: Value should be an instance of <class 'str'>. Wrong value: [0]", 'len(s) > 0': "TypeError: object of type 'int' has no len()"}.
my_function(0, 1, '')     # InputValidationError for 'c' Successes: ["instance_of_<class 'str'>"] / Failures: {'len(s) > 0': 'False'}

And this is the same example leveraging PEP484 type hints and delegating type checking to enforce:

# for type validation
from numbers import Integral
from enforce import runtime_validation, config
config(dict(mode='covariant'))  # type validation will accept subclasses too

# for value validation
from valid8 import validate_arg
from mini_lambda import x, s, Len

@runtime_validation
@validate_arg('b', (0 < x) & (x < 10))
@validate_arg('c', Len(s) > 0)
def my_function(a: Integral, b, c: str):
    """an example function I'd like to check the arguments of."""
    # check that a is an int
    # check that 0 < b < 10
    # check that c is not an empty string

# check that it works
my_function(0.2, 1, 'r')  # RuntimeTypeError 'a' was not of type <class 'numbers.Integral'>
my_function(0, 0, 'r')    # InputValidationError for 'b' [(x > 0) & (x < 10)] returned [False]
my_function(0, 1, 0)      # RuntimeTypeError 'c' was not of type <class 'str'>
my_function(0, 1, '')     # InputValidationError for 'c' [len(s) > 0] returned [False].

Java: Identifier expected

input.name() needs to be inside a function; classes contain declarations, not random code.

How do you remove duplicates from a list whilst preserving order?

from itertools import groupby
[ key for key,_ in groupby(sortedList)]

The list doesn't even have to be sorted, the sufficient condition is that equal values are grouped together.

Edit: I assumed that "preserving order" implies that the list is actually ordered. If this is not the case, then the solution from MizardX is the right one.

Community edit: This is however the most elegant way to "compress duplicate consecutive elements into a single element".

Javascript extends class

Take a look at Simple JavaScript Inheritance and Inheritance Patterns in JavaScript.

The simplest method is probably functional inheritance but there are pros and cons.

JQuery confirm dialog

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>?

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

?

convert from Color to brush

you can use this:

new SolidBrush(color)

where color is something like this:

Color.Red

or

Color.FromArgb(36,97,121))

or ...

How to enter in a Docker container already running with a new TTY

With docker 1.3, there is a new command docker exec. This allows you to enter a running container:

docker exec -it [container-id] bash

'IF' in 'SELECT' statement - choose output value based on column values

Most simplest way is to use a IF(). Yes Mysql allows you to do conditional logic. IF function takes 3 params CONDITION, TRUE OUTCOME, FALSE OUTCOME.

So Logic is

if report.type = 'p' 
    amount = amount 
else 
    amount = -1*amount 

SQL

SELECT 
    id, IF(report.type = 'P', abs(amount), -1*abs(amount)) as amount
FROM  report

You may skip abs() if all no's are +ve only

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

Insertion sort vs Bubble Sort Algorithms

insertion sort:

1.In the insertion sort swapping is not required.

2.the time complexity of insertion sort is O(n)for best case and O(n^2) worst case.

3.less complex as compared to bubble sort.

4.example: insert books in library, arrange cards.

bubble sort: 1.Swapping required in bubble sort.

2.the time complexity of bubble sort is O(n)for best case and O(n^2) worst case.

3.more complex as compared to insertion sort.

Downloading MySQL dump from command line

If you have the database named archiedb, use this:

mysql -p <password for the database> --databases archiedb > /home/database_backup.sql

Assuming this is Linux, choose where the backup file will be saved.

SharePoint : How can I programmatically add items to a custom list instance

This is how it was on the Microsoft site, with me just tweaking the SPSite and SPWeb since these might vary from environment to environment and it helps not to have to hard-code these:

using (SPSite oSiteCollection = new SPSite(SPContext.Current.Site.Url))
{
    using (SPWeb oWeb = oSiteCollection.OpenWeb(SPContext.Current.Web))
    {
        SPList oList = oWeb.Lists["Announcements"];
        // You may also use 
        // SPList oList = oWeb.GetList("/Lists/Announcements");
        // to avoid querying all of the sites' lists
        SPListItem oListItem = oList.Items.Add();
        oListItem["Title"] = "My Item";
        oListItem["Created"] = new DateTime(2004, 1, 23);
        oListItem["Modified"] = new DateTime(2005, 10, 1);
        oListItem["Author"] = 3;
        oListItem["Editor"] = 3;
        oListItem.Update();
    }
}

Source: SPListItemClass (Microsoft.SharePoint). (2012). Retrieved February 22, 2012, from http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.aspx.

Link vs compile vs controller

I wanted to add also what the O'Reily AngularJS book by the Google Team has to say:

Controller - Create a controller which publishes an API for communicating across directives. A good example is Directive to Directive Communication

Link - Programmatically modify resulting DOM element instances, add event listeners, and set up data binding.

Compile - Programmatically modify the DOM template for features across copies of a directive, as when used in ng-repeat. Your compile function can also return link functions to modify the resulting element instances.

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Best radio-button implementation for IOS

I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!

https://github.com/goosoftware/GSRadioButtonSetController

difference between iframe, embed and object elements

One reason to use object over iframe is that object re-sizes the embedded content to fit the object dimensions. most notable on safari in iPhone 4s where screen width is 320px and the html from the embedded URL may set dimensions greater.

Maven dependency for Servlet 3.0 API?

Just for newcomers.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>

Share data between AngularJS controllers

I've created a factory that controls shared scope between route path's pattern, so you can maintain the shared data just when users are navigating in the same route parent path.

.controller('CadastroController', ['$scope', 'RouteSharedScope',
    function($scope, routeSharedScope) {
      var customerScope = routeSharedScope.scopeFor('/Customer');
      //var indexScope = routeSharedScope.scopeFor('/');
    }
 ])

So, if the user goes to another route path, for example '/Support', the shared data for path '/Customer' will be automatically destroyed. But, if instead of this the user goes to 'child' paths, like '/Customer/1' or '/Customer/list' the the scope won't be destroyed.

You can see an sample here: http://plnkr.co/edit/OL8of9

How to get the last N records in mongodb?

You can try this method:

Get the total number of records in the collection with

db.dbcollection.count() 

Then use skip:

db.dbcollection.find().skip(db.dbcollection.count() - 1).pretty()

Batch Renaming of Files in a Directory

I prefer writing small one liners for each replace I have to do instead of making a more generic and complex code. E.g.:

This replaces all underscores with hyphens in any non-hidden file in the current directory

import os
[os.rename(f, f.replace('_', '-')) for f in os.listdir('.') if not f.startswith('.')]

How to properly set the 100% DIV height to match document/window height?

Use #element{ height:100vh}

This will set the height of the #element to 100% of viewport. Hope this helps.

HTML display result in text (input) field?

 <HTML>
      <HEAD>
        <TITLE>Sum</TITLE>

        <script type="text/javascript">
          function sum()
          {

             var num1 = document.myform.number1.value;
             var num2 = document.myform.number2.value;
             var sum = parseInt(num1) + parseInt(num2);
             document.getElementById('add').value = sum;
          }
        </script>
      </HEAD>

      <BODY>
        <FORM NAME="myform">
          <INPUT TYPE="text" NAME="number1" VALUE=""/> + 
          <INPUT TYPE="text" NAME="number2" VALUE=""/>
          <INPUT TYPE="button" NAME="button" Value="=" onClick="sum()"/>
          <INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
        </FORM>

      </BODY>
</HTML>

This should work properly. 1. use .value instead of "innerHTML" when setting the 3rd field (input field) 2. Close the input tags

Image library for Python 3

Depending on what is needed, scikit-image may be the best choice, with manipulations going way beyond PIL and the current version of Pillow. Very well-maintained, at least as much as Pillow. Also, the underlying data structures are from Numpy and Scipy, which makes its code incredibly interoperable. Examples that pillow can't handle:

Region Adjacency Graph Merging

Radon Transform

Histogram of oriented gradients

Approximate and subdivide polygons

You can see its power in the gallery. This paper provides a great intro to it. Good luck!

document.getElementById().value and document.getElementById().checked not working for IE

The code you pasted should work... There must be something else we are not seeing here.

Check this out. Working for me fine on IE7. When you submit you will see the variable passed in the URL.

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

Extracting an attribute value with beautifulsoup

Here is an example for how to extract the href attrbiutes of all a tags:

import requests as rq 
from bs4 import BeautifulSoup as bs

url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')

hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
    # print(href.get("href"))
    links = href.get("href")
    all_hrefs.append(links)

print(all_hrefs)

How to import and export components using React + ES6 + webpack?

Try defaulting the exports in your components:

import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';

export default class MyNavbar extends React.Component {
    render(){
      return (
        <Navbar className="navbar-dark" fluid>
        ...
        </Navbar>
      );
    }
}

by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed

How do I select elements of an array given condition?

For 2D arrays, you can do this. Create a 2D mask using the condition. Typecast the condition mask to int or float, depending on the array, and multiply it with the original array.

In [8]: arr
Out[8]: 
array([[ 1.,  2.,  3.,  4.,  5.],
       [ 6.,  7.,  8.,  9., 10.]])

In [9]: arr*(arr % 2 == 0).astype(np.int) 
Out[9]: 
array([[ 0.,  2.,  0.,  4.,  0.],
       [ 6.,  0.,  8.,  0., 10.]])

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

Difference between ${} and $() in Bash

  1. your understanding is right. For detailed info on {} see bash ref - parameter expansion

  2. 'for' and 'while' have different syntax and offer different styles of programmer control for an iteration. Most non-asm languages offer a similar syntax.

With while, you would probably write i=0; while [ $i -lt 10 ]; do echo $i; i=$(( i + 1 )); done in essence manage everything about the iteration yourself

jQuery add class .active on menu

Use window.location.pathname and compare it with your links. You can do something like this:

$('a[href="~/' + currentSiteVar + '/"').addClass('active');

But first you have to prepare currentSiteVar to put it into selecor.

How do I split an int into its digits?

You can just use a sequence of x/10.0f and std::floor operations to have "math approach". Or you can also use boost::lexical_cast(the_number) to obtain a string and then you can simply do the_string.c_str()[i] to access the individual characters (the "string approach").

How to let an ASMX file output JSON

This is probably old news by now, but the magic seems to be:

  • [ScriptService] attribute on web service class
  • [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] on method
  • Content-type: application/json in request

With those pieces in place, a GET request is successful.

For a HTTP POST

  • [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)] on method

and on the client side (assuming your webmethod is called MethodName, and it takes a single parameter called searchString):

        $.ajax({
            url: "MyWebService.asmx/MethodName",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({ searchString: q }),
            success: function (response) {                  
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert(textStatus + ": " + jqXHR.responseText);
            }
        });

Insert into ... values ( SELECT ... FROM ... )

This is another example using values with select:

INSERT INTO table1(desc, id, email) 
SELECT "Hello World", 3, email FROM table2 WHERE ...

HTTP Status 404 - The requested resource (/) is not available

Please check in your server specification again, if you have changed your port number to something else. And change the port number in your link whatever new port number it is.

Also check whether your server is running properly before you try accessing your localhost.

What is the difference between C and embedded C?

Embedded C is generally an extension of the C language, they are more or less similar. However, some differences do exist, such as:

  • C is generally used for desktop computers, while embedded C is for microcontroller based applications.

  • C can use the resources of a desktop PC like memory, OS, etc. While, embedded C has to use with the limited resources, such as RAM, ROM, I/Os on an embedded processor.

  • Embedded C includes extra features over C, such as fixed point types, multiple memory areas, and I/O register mapping.

  • Compilers for C (ANSI C) typically generate OS dependant executables. Embedded C requires compilers to create files to be downloaded to the microcontrollers/microprocessors where it needs to run.

Refer difference between C and embedded C

day of the week to day number (Monday = 1, Tuesday = 2)

The date function can return this if you specify the format correctly:

$daynum = date("w", strtotime("wednesday"));

will return 0 for Sunday through to 6 for Saturday.

An alternative format is:

$daynum = date("N", strtotime("wednesday"));

which will return 1 for Monday through to 7 for Sunday (this is the ISO-8601 represensation).

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even

SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;

Android: how to convert whole ImageView to Bitmap?

It works in Kotlin after buildDrawingCache() being deprecated

 // convert imageView to bitmap
val bitmap = (imageViewId.getDrawable() as BitmapDrawable).getBitmap()

Makefiles with source files in different directories

The traditional way is to have a Makefile in each of the subdirectories (part1, part2, etc.) allowing you to build them independently. Further, have a Makefile in the root directory of the project which builds everything. The "root" Makefile would look something like the following:

all:
    +$(MAKE) -C part1
    +$(MAKE) -C part2
    +$(MAKE) -C part3

Since each line in a make target is run in its own shell, there is no need to worry about traversing back up the directory tree or to other directories.

I suggest taking a look at the GNU make manual section 5.7; it is very helpful.

Create an array with same element repeated multiple times

This could be another answers.

let cards = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"];

let totalCards = [...cards, ...cards, ...cards, ...cards];

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had a related issue working within Spyder, but the problem seems to be the relationship between the escape character ( "\") and the "\" in the path name Here's my illustration and solution (note single \ vs double \\ ):

path =   'C:\Users\myUserName\project\subfolder'
path   # 'C:\\Users\\myUserName\\project\subfolder'
os.listdir(path)              # gives windows error
path =   'C:\\Users\\myUserName\\project\\subfolder'
os.listdir(path)              # gives expected behavior

Combine or merge JSON on node.js without jQuery

Lodash is a another powerful tool-belt option for these sorts of utilities. See: _.merge() (which is recursive)

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};
var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
}; 
_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } 

How to change RGB color to HSV?

This is the VB.net version which works fine for me ported from the C code in BlaM's post.

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.


Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
    Dim i As Integer
    Dim f, p, q, t As Double

    If (s = 0) Then
        ' achromatic (grey)
        r = v
        g = v
        b = v
        Exit Sub
    End If

    h /= 60 'sector 0 to 5
    i = Math.Floor(h)
    f = h - i 'factorial part of h
    p = v * (1 - s)
    q = v * (1 - s * f)
    t = v * (1 - s * (1 - f))

    Select Case (i)
        Case 0
            r = v
            g = t
            b = p
            Exit Select
        Case 1
            r = q
            g = v
            b = p
            Exit Select
        Case 2
            r = p
            g = v
            b = t
            Exit Select
        Case 3
            r = p
            g = q
            b = v
            Exit Select
        Case 4
            r = t
            g = p
            b = v
            Exit Select
        Case Else   'case 5:
            r = v
            g = p
            b = q
            Exit Select
    End Select
End Sub

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

Requires PHP5.3:

$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("l Y-m-d H:i:s\n");
}

This will output all days in the defined period between $start and $end. If you want to include the 10th, set $end to 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod.

Newline in string attribute

Also doesn't work with

<TextBlock><TextBlock.Text>NO USING ABOVE TECHNIQUE HERE</TextBlock.Text>

No big deal, just needed to use

<TextBlock Text="Cool &#x0a;Newline trick" />

instead.

How to Generate unique file names in C#

I have been using the following code and its working fine. I hope this might help you.

I begin with a unique file name using a timestamp -

"context_" + DateTime.Now.ToString("yyyyMMddHHmmssffff")

C# code -

public static string CreateUniqueFile(string logFilePath, string logFileName, string fileExt)
    {
        try
        {
            int fileNumber = 1;

            //prefix with . if not already provided
            fileExt = (!fileExt.StartsWith(".")) ? "." + fileExt : fileExt;

            //Generate new name
            while (File.Exists(Path.Combine(logFilePath, logFileName + "-" + fileNumber.ToString() + fileExt)))
                fileNumber++;

            //Create empty file, retry until one is created
            while (!CreateNewLogfile(logFilePath, logFileName + "-" + fileNumber.ToString() + fileExt))
                fileNumber++;

            return logFileName + "-" + fileNumber.ToString() + fileExt;
        }
        catch (Exception)
        {
            throw;
        }
    }

    private static bool CreateNewLogfile(string logFilePath, string logFile)
    {
        try
        {
            FileStream fs = new FileStream(Path.Combine(logFilePath, logFile), FileMode.CreateNew);
            fs.Close();
            return true;
        }
        catch (IOException)   //File exists, can not create new
        {
            return false;
        }
        catch (Exception)     //Exception occured
        {
            throw;
        }
    }

Regex for parsing directory and filename

Try this:

^(.+)\/([^\/]+)$

EDIT: escaped the forward slash to prevent problems when copy/pasting the Regex

Targeting .NET Framework 4.5 via Visual Studio 2010

I have been struggling with VS2010/DNFW 4.5 integration and have finally got this working. Starting in VS 2008, a cache of assemblies was introduced that is used by Visual Studio called the "Referenced Assemblies". This file cache for VS 2010 is located at \Reference Assemblies\Microsoft\Framework.NetFramework\v4.0. Visual Studio loads framework assemblies from this location instead of from the framework installation directory. When Microsoft says that VS 2010 does not support DNFW 4.5 what they mean is that this directory does not get updated when DNFW 4.5 is installed. Once you have replace the files in this location with the updated DNFW 4.5 files, you will find that VS 2010 will happily function with DNFW 4.5.

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

There are a couple of libraries out there. onnov/detect-encoding looks promising. It claims to do better than mb_detect_encoding

Example usage for converting string in unknown character encoding to UTF-8:

use Onnov\DetectEncoding\EncodingDetector;
$detector->iconvXtoEncoding('??????????? ?????')

To simply detect encoding:

$encoding = $detector->getEncoding('??????????? ?????');

How to convert from Hex to ASCII in JavaScript?

Another way to do it (if you use Node.js):

var input  = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output);  // Result: 32343630 -> 2460

How to check if spark dataframe is empty?

Since Spark 2.4.0 there is Dataset.isEmpty.

It's implementation is :

def isEmpty: Boolean = 
  withAction("isEmpty", limit(1).groupBy().count().queryExecution) { plan =>
    plan.executeCollect().head.getLong(0) == 0
}

Note that a DataFrame is no longer a class in Scala, it's just a type alias (probably changed with Spark 2.0):

type DataFrame = Dataset[Row]

YAML equivalent of array of objects in JSON

TL;DR

You want this:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Mappings

The YAML equivalent of a JSON object is a mapping, which looks like these:

# flow style
{ foo: 1, bar: 2 }
# block style
foo: 1
bar: 2

Note that the first characters of the keys in a block mapping must be in the same column. To demonstrate:

# OK
   foo: 1
   bar: 2
# Parse error
   foo: 1
    bar: 2

Sequences

The equivalent of a JSON array in YAML is a sequence, which looks like either of these (which are equivalent):

# flow style
[ foo bar, baz ]
# block style
- foo bar
- baz

In a block sequence the -s must be in the same column.

JSON to YAML

Let's turn your JSON into YAML. Here's your JSON:

{"AAPL": [
  {
    "shares": -75.088,
    "date": "11/27/2015"
  },
  {
    "shares": 75.088,
    "date": "11/26/2015"
  },
]}

As a point of trivia, YAML is a superset of JSON, so the above is already valid YAML—but let's actually use YAML's features to make this prettier.

Starting from the inside out, we have objects that look like this:

{
  "shares": -75.088,
  "date": "11/27/2015"
}

The equivalent YAML mapping is:

shares: -75.088
date: 11/27/2015

We have two of these in an array (sequence):

- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

Note how the -s line up and the first characters of the mapping keys line up.

Finally, this sequence is itself a value in a mapping with the key AAPL:

AAPL:
  - shares: -75.088
    date: 11/27/2015
  - shares: 75.088
    date: 11/26/2015

Parsing this and converting it back to JSON yields the expected result:

{
  "AAPL": [
    {
      "date": "11/27/2015", 
      "shares": -75.088
    }, 
    {
      "date": "11/26/2015", 
      "shares": 75.088
    }
  ]
}

You can see it (and edit it interactively) here.

JS strings "+" vs concat method

In JS, "+" concatenation works by creating a new String object.

For example, with...

var s = "Hello";

...we have one object s.

Next:

s = s + " World";

Now, s is a new object.

2nd method: String.prototype.concat

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

How to receive JSON as an MVC 5 action method parameter

There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing

data: JSON.stringify(usersRoles),

to

data: { model: JSON.stringify(usersRoles) },

Secondly, you aren't binding types correctly with your jquery call. If you remove

contentType: "application/json; charset=utf-8",

it will inherently bind back to a string.

All together, use the first ActionResult method and the following jquery ajax call:

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        dataType: "json",
        data: { model: JSON.stringify(usersRoles) },
        success: function (data) { alert(data); },
        failure: function (errMsg) {
        alert(errMsg);
        }
   });

Hash function that produces short hashes?

Just summarizing an answer that was helpful to me (noting @erasmospunk's comment about using base-64 encoding). My goal was to have a short string that was mostly unique...

I'm no expert, so please correct this if it has any glaring errors (in Python again like the accepted answer):

import base64
import hashlib
import uuid

unique_id = uuid.uuid4()
# unique_id = UUID('8da617a7-0bd6-4cce-ae49-5d31f2a5a35f')

hash = hashlib.sha1(str(unique_id).encode("UTF-8"))
# hash.hexdigest() = '882efb0f24a03938e5898aa6b69df2038a2c3f0e'

result = base64.b64encode(hash.digest())
# result = b'iC77DySgOTjliYqmtp3yA4osPw4='

The result here is using more than just hex characters (what you'd get if you used hash.hexdigest()) so it's less likely to have a collision (that is, should be safer to truncate than a hex digest).

Note: Using UUID4 (random). See http://en.wikipedia.org/wiki/Universally_unique_identifier for the other types.

SQL- Ignore case while searching for a string

You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI as your collation. The one you specify in your question is explictly case sensitive.

You can see a list of collations here.

Save file to specific folder with curl command

For powershell in Windows, you can add relative path + filename to --output flag:

curl -L  http://github.com/GorvGoyl/Notion-Boost-browser-extension/archive/master.zip --output build_firefox/master-repo.zip

here build_firefox is relative folder.

How do I perform HTML decoding/encoding using Python/Django?

Searching the simplest solution of this question in Django and Python I found you can use builtin theirs functions to escape/unescape html code.

Example

I saved your html code in scraped_html and clean_html:

scraped_html = (
    '&lt;img class=&quot;size-medium wp-image-113&quot; '
    'style=&quot;margin-left: 15px;&quot; title=&quot;su1&quot; '
    'src=&quot;http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg&quot; '
    'alt=&quot;&quot; width=&quot;300&quot; height=&quot;194&quot; /&gt;'
)
clean_html = (
    '<img class="size-medium wp-image-113" style="margin-left: 15px;" '
    'title="su1" src="http://blah.org/wp-content/uploads/2008/10/su1-300x194.jpg" '
    'alt="" width="300" height="194" />'
)

Django

You need Django >= 1.0

unescape

To unescape your scraped html code you can use django.utils.text.unescape_entities which:

Convert all named and numeric character references to the corresponding unicode characters.

>>> from django.utils.text import unescape_entities
>>> clean_html == unescape_entities(scraped_html)
True

escape

To escape your clean html code you can use django.utils.html.escape which:

Returns the given text with ampersands, quotes and angle brackets encoded for use in HTML.

>>> from django.utils.html import escape
>>> scraped_html == escape(clean_html)
True

Python

You need Python >= 3.4

unescape

To unescape your scraped html code you can use html.unescape which:

Convert all named and numeric character references (e.g. &gt;, &#62;, &x3e;) in the string s to the corresponding unicode characters.

>>> from html import unescape
>>> clean_html == unescape(scraped_html)
True

escape

To escape your clean html code you can use html.escape which:

Convert the characters &, < and > in string s to HTML-safe sequences.

>>> from html import escape
>>> scraped_html == escape(clean_html)
True

ListView with Add and Delete Buttons in each Row in android

on delete button click event

public void delete(View v){                

    ListView listview1;
    ArrayList<E> datalist;

    final int position = listview1.getPositionForView((View) v.getParent());
    datalist.remove(position);
    myAdapter.notifyDataSetChanged();

}

How do you execute an arbitrary native command from a string?

Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

iex $command

Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

$command = 'C:\somepath\someexe.exe somearg'
iex $command

However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

>> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"

And then in the script:

$command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
iex "& $command"

Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

function myeval($command) {
    if ($command[0] -eq '"') { iex "& $command" }
    else { iex $command }
}

But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

Create session factory in Hibernate 4

[quote from http://www.javabeat.net/session-factory-hibernate-4/]

There are many APIs deprecated in the hibernate core framework. One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. Also each incremental version gets changes on some of the important API. One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. In our earlier versions we have created the session factory as below:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. If you are using the hibernate 4.3.0 and above, your code has to be:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.

How to export html table to excel or pdf in php

<script src="jquery.min.js"></script>
<table border="1" id="ReportTable" class="myClass">
    <tr bgcolor="#CCC">
      <td width="100">xxxxx</td>
      <td width="700">xxxxxx</td>
      <td width="170">xxxxxx</td>
      <td width="30">xxxxxx</td>
    </tr>
    <tr bgcolor="#FFFFFF">
      <td><?php                 
            $date = date_create($row_Recordset3['fecha']);
            echo date_format($date, 'd-m-Y');
            ?></td>
      <td><?php echo $row_Recordset3['descripcion']; ?></td>
      <td><?php echo $row_Recordset3['producto']; ?></td>
      <td><img src="borrar.png" width="14" height="14" class="clickable" onClick="eliminarSeguimiento(<?php echo $row_Recordset3['idSeguimiento']; ?>)" title="borrar"></td>
    </tr>
  </table>

  <input type="hidden" id="datatodisplay" name="datatodisplay">  
    <input type="submit" value="Export to Excel"> 

exporttable.php

<?php
header('Content-Type: application/force-download');
header('Content-disposition: attachment; filename=export.xls');
// Fix for crappy IE bug in download.
header("Pragma: ");
header("Cache-Control: ");
echo $_REQUEST['datatodisplay'];
?>

Error creating bean with name

I think it comes from this line in your XML file:

<context:component-scan base-package="org.assessme.com.controller." />

Replace it by:

<context:component-scan base-package="org.assessme.com." />

It is because your Autowired service is not scanned by Spring since it is not in the right package.

Copy Paste in Bash on Ubuntu on Windows

Edit / Paste from the title bar's context menu (until they fix the control key shortcuts)

How to print object array in JavaScript?

Emm... Why not to use something like this?

_x000D_
_x000D_
function displayArrayObjects(arrayObjects) {_x000D_
        var len = arrayObjects.length, text = "";_x000D_
_x000D_
        for (var i = 0; i < len; i++) {_x000D_
            var myObject = arrayObjects[i];_x000D_
            _x000D_
            for (var x in myObject) {_x000D_
                text += ( x + ": " + myObject[x] + " ");_x000D_
            }_x000D_
            text += "<br/>";_x000D_
        }_x000D_
_x000D_
        document.getElementById("message").innerHTML = text;_x000D_
    }_x000D_
            _x000D_
            _x000D_
            var lineChartData = [{_x000D_
                date: new Date(2009, 10, 2),_x000D_
                value: 5_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 25),_x000D_
                value: 30_x000D_
            }, {_x000D_
                date: new Date(2009, 10, 26),_x000D_
                value: 72,_x000D_
                customBullet: "images/redstar.png"_x000D_
            }];_x000D_
_x000D_
            displayArrayObjects(lineChartData);
_x000D_
<h4 id="message"></h4>
_x000D_
_x000D_
_x000D_

result:

date: Mon Nov 02 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 5 
date: Wed Nov 25 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 30 
date: Thu Nov 26 2009 00:00:00 GMT+0200 (FLE Standard Time) value: 72 customBullet: images/redstar.png 

jsfiddle

jQuery ajax post file field

This should help. How can I upload files asynchronously?

As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.

Can someone post a well formed crossdomain.xml sample?

If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.

<?xml version="1.0" ?>
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

How to get a list of all files in Cloud Storage in a Firebase app?

I faced the same issue, mine is even more complicated.

Admin will upload audio and pdf files into storage:

  • audios/season1, season2.../class1, class 2/.mp3 files

  • books/.pdf files

Android app needs to get the list of sub folders and files.

The solution is catching the upload event on storage and create the same structure on firestore using cloud function.

Step 1: Create manually 'storage' collection and 'audios/books' doc on firestore

enter image description here

Step 2: Setup cloud function

Might take around 15 mins: https://www.youtube.com/watch?v=DYfP-UIKxH0&list=PLl-K7zZEsYLkPZHe41m4jfAxUi0JjLgSM&index=1

Step 3: Catch upload event using cloud function

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
admin.initializeApp(functions.config().firebase);
const path = require('path');

export const onFileUpload = functions.storage.object().onFinalize(async (object) => {
        let filePath = object.name; // File path in the bucket.
        const contentType = object.contentType; // File content type.
        const metageneration = object.metageneration; // Number of times metadata has been generated. New objects have a value of 1.
        if (metageneration !== "1") return;

        // Get the file name.
        const fileName = path.basename(filePath);
        filePath = filePath.substring(0, filePath.length - 1);
        console.log('contentType ' + contentType);
        console.log('fileName ' + fileName);
        console.log('filePath ' + filePath);
        console.log('path.dirname(filePath) ' + path.dirname(filePath));
        filePath = path.dirname(filePath);
        const pathArray = filePath.split("/");
        let ref = '';
        for (const item of pathArray) {
            if (ref.length === 0) {
                ref = item;
            }
            else {
                ref = ref.concat('/sub/').concat(item);
            }
        }

        ref = 'storage/'.concat(ref).concat('/sub')
        admin.firestore().collection(ref).doc(fileName).create({})
                .then(result => {console.log('onFileUpload:updated')})
                .catch(error => {
                    console.log(error);
                });
    });

Step 4: Retrieve list of folders/files on Android app using firestore

private static final String STORAGE_DOC = "storage/";
    public static void getMediaCollection(String path, OnCompleteListener onCompleteListener) {
        String[] pathArray = path.split("/");
        String doc = null;
        for (String item : pathArray) {
            if (TextUtils.isEmpty(doc)) doc = STORAGE_DOC.concat(item);
            else doc = doc.concat("/sub/").concat(item);
        }
        doc = doc.concat("/sub");

        getFirestore().collection(doc).get().addOnCompleteListener(onCompleteListener);
    }

Step 5: Get download url

public static void downloadMediaFile(String path, OnCompleteListener<Uri> onCompleteListener) {
        getStorage().getReference().child(path).getDownloadUrl().addOnCompleteListener(onCompleteListener);
    }

Note

We have to put "sub" collection to each item since firestore doesn't support to retrieve the list of collection.

It took me 3 days to find out the solution, hopefully will take you 3 hours at most.

Cheers.

Merge 2 arrays of objects

Based on @YOU's answer but keeping the order:

var arr3 = [];
for(var i in arr1){
   var shared = false;
   for (var j in arr2)
       if (arr2[j].name == arr1[i].name) {
           arr3.push(arr1[j]
           shared = true;
           break;
       }
   if(!shared) arr3.push(arr1[i])
}

for(var j in arr2){
   var shared = false;
   for (var i in arr1)
       if (arr2[j].name == arr1[i].name) {
           shared = true;
           break;
       }
   if(!shared) arr3.push(arr2[j])
}
arr3

I know this solution is less efficient, but it's necessary if you want to keep the order and still update the objects.

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

How to activate an Anaconda environment

let's assume your environment name is 'demo' and you are using anaconda and want to create a virtual environment:

(if you want python3)

    conda create -n demo python=3

(if you want python2)

    conda create -n demo python=2

After running above command you have to activate the environment by bellow command:

    source activate demo 

Overlay normal curve to histogram in R

Here's a nice easy way I found:

h <- hist(g, breaks = 10, density = 10,
          col = "lightgray", xlab = "Accuracy", main = "Overall") 
xfit <- seq(min(g), max(g), length = 40) 
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g)) 
yfit <- yfit * diff(h$mids[1:2]) * length(g) 

lines(xfit, yfit, col = "black", lwd = 2)

How to verify element present or visible in selenium 2 (Selenium WebDriver)

You could try something like:

    WebElement rxBtn = driver.findElement(By.className("icon-rx"));
    WebElement otcBtn = driver.findElement(By.className("icon-otc"));
    WebElement herbBtn = driver.findElement(By.className("icon-herb"));

    Assert.assertEquals(true, rxBtn.isDisplayed());
    Assert.assertEquals(true, otcBtn.isDisplayed());
    Assert.assertEquals(true, herbBtn.isDisplayed());

This is just an example. Basically you declare and define the WebElement variables you wish to use and then Assert whether or not they are displayed. This is using TestNG Assertions.

All shards failed

It is possible on your restart some shards were not recovered, causing the cluster to stay red.
If you hit:
http://<yourhost>:9200/_cluster/health/?level=shards you can look for red shards.

I have had issues on restart where shards end up in a non recoverable state. My solution was to simply delete that index completely. That is not an ideal solution for everyone.

It is also nice to visualize issues like this with a plugin like:
Elasticsearch Head

Get Today's date in Java at midnight time

    Calendar c = new GregorianCalendar();
    c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    Date d1 = c.getTime(); //the midnight, that's the first second of the day.

should be Fri Mar 09 00:00:00 IST 2012

Ignore self-signed ssl cert using Jersey Client

Since I am new to stackoverflow and have lesser reputation to comment on others' answers, I am putting the solution suggested by Chris Salij with some modification which worked for me.

            SSLContext ctx = null;
            TrustManager[] trustAllCerts = new X509TrustManager[]{new X509TrustManager(){
                public X509Certificate[] getAcceptedIssuers(){return null;}
                public void checkClientTrusted(X509Certificate[] certs, String authType){}
                public void checkServerTrusted(X509Certificate[] certs, String authType){}
            }};
            try {
                ctx = SSLContext.getInstance("SSL");
                ctx.init(null, trustAllCerts, null);
            } catch (NoSuchAlgorithmException | KeyManagementException e) {
                LOGGER.info("Error loading ssl context {}", e.getMessage());
            }

            SSLContext.setDefault(ctx);

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Putting this here in case I forget it later and Google it again.

In my case I wanted the extra column to have the same data for each row

Where $syncData is an array of IDs:

$syncData = array_map(fn($locationSysid) => ['other_column' => 'foo'], array_flip($syncData));

or without arrow

$syncData = array_map(function($locationSysid) {
      return ['ENTITY' => 'dbo.Cli_Core'];
   }, array_flip($syncData));

(array_flip means we're using the IDs as the index for the array)

Full-screen responsive background image

You can also make full screen banner section without use of JavaScript, pure css based responsive full screen banner section , using height: 100vh; in banner main div, here have live example for this

#bannersection {
    position: relative;
    display: table;
    width: 100%;
    background: rgba(99,214,250,1);
    height: 100vh;
}

https://www.htmllion.com/fullscreen-header-banner-section.html

Switch statement fall-through...should it be allowed?

Have you heard of Duff's device? This is a great example of using switch fallthrough.

It's a feature that can be used and it can be abused, like almost all language features.

Map.Entry: How to use it?

A Map is a collection of Key + Value pairs, which is visualized like this:

{[fooKey=fooValue],barKey=barValue],[quxKey=quxValue]}

The Map interface allows a few options for accessing this collection: The Key set [fooKey, barKey,quxKey], the Value set [fooValue, barValue, quxValue] and finally entry Set [fooKey=fooValue],barKey=barValue],[quxKey=quxValue].

Entry set is simply a convenience to iterate over the key value pairs in the map, the Map.Entry is the representation of each key value pair. An equivalent way to do your last loop would be:

for (String buttonKey: listbouton.keySet()) {
    this.add(listbouton.get(buttonKey)) ;
}

or

for (JButton button: listbouton.values()) {
    this.add(button) ;
}

How to check whether input value is integer or float?

You can use RoundingMode.#UNNECESSARY if you want/accept exception thrown otherwise

new BigDecimal(value).setScale(2, RoundingMode.UNNECESSARY);

If this rounding mode is specified on an operation that yields an inexact result, an ArithmeticException is thrown.

Exception if not integer value:

java.lang.ArithmeticException: Rounding necessary

Best Java obfuscator?

We've had much better luck encrypting the jars rather than obfuscating. We use Classguard.

How do I redirect to another webpage?

  1. location.assign():

    To assign a route path by passing a path into it.. Assign will give you a history even after the path was assigned.

    Usage Method: value should be passed into it.

    For example: location.assign("http://google.com")

    Enter image description here

  2. location.href

    Can define give a path into it... And it will redirect into a given path once it setup, and it will keep history...

    Usage Method: value should be assign into it.

    For example: location.href = "http://google.com"

  3. location.replace():

    It will help to replace a path if you don't want to keep history. It won't give you a history once you replace its path.

    Usage Method: value should be pass into it.

    For example: location.replace("http://google.com")

    Enter image description here


assign() and href are similar, and both can hold history. assign will work by passing a value and href works by assigning.

You can achieve it using JavaScript itself without using jQuery by assigning,

window.location = "http://google.com"
location.href = "http://google.com"

You can achieve similar thing using jQuery like below. It will do exactly the same like above,

$(window).attr('location', "http://www.google.com");
$(location).attr('href', "http://www.google.com");

You can easily understand the difference between both...

Here is the Location object,

Location API from chrome

removing bold styling from part of a header

Better one: Instead of using extra span tags in html and increasing html code, you can do as below:

<div id="sc-nav-display">
    <table class="sc-nav-table">
      <tr>
        <th class="nav-invent-head">Inventory</th>
        <th class="nav-orders-head">Orders</th>
      </tr>
    </table>
  </div> 

Here, you can use CSS as below:

#sc-nav-display th{
    font-weight: normal;
}

You just need to use ID assigned to the respected div tag of table. I used "#sc-nav-display" with "th" in CSS, so that, every other table headings will remain BOLD until and unless you do the same to all others table head as I said.

How do I remove the old history from a git repository?

There are too many answers here which are not current and some don't fully explain the consequences. Here's what worked for me for trimming down the history using latest git 2.26:

First create a dummy commit. This commit will appear as the first commit in your truncated repo. You need this because this commit will hold all base files for the history you are keeping. The SHA is the ID of the previous commit of the commit you want to keep (in this example, 8365366). The string 'Initial' will show up as commit message of the first commit. If you are using Windows, type below command from Git Bash command prompt.

# 8365366 is id of parent commit after which you want to preserve history
echo 'Initial' | git commit-tree 8365366^{tree}

Above command will print SHA, for example, d10f7503bc1ec9d367da15b540887730db862023.

Now just type:

# d10f750 is commit ID from previous command
git rebase --onto d10f750 8365366

This will first put all files as-of commit 8365366 in to the dummy commit d10f750. Then it will play back all commits after 8365366 over the top of d10f750. Finally master branch pointer will be updated to last commit played back.

Now if you want to push these truncated repo, just do git push -f.

Few things to keep in mind (these applies to other methods as well as this one): Tags are not transferred. While commit IDs and timestamps are preserved, you will see GitHub show these commits in lumpsum heading like Commits on XY date.

Fortunately it is possible to keep truncated history as "archive" and later you can join back trimmed repo with archive repo. For doing this, see this guide.

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

How to get the GL library/headers?

In Visual Studio :

//OpenGL
#pragma comment(lib, "opengl32")
#pragma comment(lib, "glu32")
#include <gl/gl.h>
#include <gl/glu.h>

Headers are in the SDK : C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl

Get 2 Digit Number For The Month

My way of doing it is:

right('0'+right(datepart(month,[StartDate]),2),2)

The reason for the internal 'right' function is to prevent SQL from doing it as math add - which will leave us with one digit again.

Android Calling JavaScript functions in WebView

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

MainActivity.java


import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.bluapp.androidview.R;

public class WebViewActivity3 extends AppCompatActivity {
    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view3);
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/webview1.html");


        webView.setWebViewClient(new WebViewClient(){
            public void onPageFinished(WebView view, String weburl){
                webView.loadUrl("javascript:testEcho('Javascript function in webview')");
            }
        });
    }
}

assets file

<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.0//EN" "http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>WebView1</title>
<meta forua="true" http-equiv="Cache-Control" content="max-age=0"/>
</head>

<body style="background-color:#212121">
<script type="text/javascript">
function testEcho(p1){
document.write(p1);
}
</script>
</body>

</html>

How to find tag with particular text with Beautiful Soup?

You could solve this with some simple gazpacho parsing:

from gazpacho import Soup

soup = Soup(html)
tds = soup.find("td", {"class": "pos"})
tds[1].find("strong").text

Which will output:

text I am looking for

Save plot to image file instead of displaying it using Matplotlib

I used the following:

import matplotlib.pyplot as plt

p1 = plt.plot(dates, temp, 'r-', label="Temperature (celsius)")  
p2 = plt.plot(dates, psal, 'b-', label="Salinity (psu)")  
plt.legend(loc='upper center', numpoints=1, bbox_to_anchor=(0.5, -0.05),        ncol=2, fancybox=True, shadow=True)

plt.savefig('data.png')  
plt.show()  
f.close()
plt.close()

I found very important to use plt.show after saving the figure, otherwise it won't work.figure exported in png

HTML table with fixed headers?

TL;DR

If you target modern browsers and don't have extravagant styling needs: http://jsfiddle.net/dPixie/byB9d/3/ ... Although the big four version is pretty sweet as well this version handles fluid width a lot better.

Good news everyone!

With the advances of HTML5 and CSS3 this is now possible, at least for modern browsers. The slightly hackish implementation I came up with can be found here: http://jsfiddle.net/dPixie/byB9d/3/. I have tested it in FX 25, Chrome 31 and IE 10 ...

Relevant HTML (insert a HTML5 doctype at the top of your document though):

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
section {_x000D_
  position: relative;_x000D_
  border: 1px solid #000;_x000D_
  padding-top: 37px;_x000D_
  background: #500;_x000D_
}_x000D_
_x000D_
section.positioned {_x000D_
  position: absolute;_x000D_
  top: 100px;_x000D_
  left: 100px;_x000D_
  width: 800px;_x000D_
  box-shadow: 0 0 15px #333;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  overflow-y: auto;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-spacing: 0;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
td+td {_x000D_
  border-left: 1px solid #eee;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  border-bottom: 1px solid #eee;_x000D_
  background: #ddd;_x000D_
  color: #000;_x000D_
  padding: 10px 25px;_x000D_
}_x000D_
_x000D_
th {_x000D_
  height: 0;_x000D_
  line-height: 0;_x000D_
  padding-top: 0;_x000D_
  padding-bottom: 0;_x000D_
  color: transparent;_x000D_
  border: none;_x000D_
  white-space: nowrap;_x000D_
}_x000D_
_x000D_
th div {_x000D_
  position: absolute;_x000D_
  background: transparent;_x000D_
  color: #fff;_x000D_
  padding: 9px 25px;_x000D_
  top: 0;_x000D_
  margin-left: -25px;_x000D_
  line-height: normal;_x000D_
  border-left: 1px solid #800;_x000D_
}_x000D_
_x000D_
th:first-child div {_x000D_
  border: none;_x000D_
}
_x000D_
<section class="positioned">_x000D_
  <div class="container">_x000D_
    <table>_x000D_
      <thead>_x000D_
        <tr class="header">_x000D_
          <th>_x000D_
            Table attribute name_x000D_
            <div>Table attribute name</div>_x000D_
          </th>_x000D_
          <th>_x000D_
            Value_x000D_
            <div>Value</div>_x000D_
          </th>_x000D_
          <th>_x000D_
            Description_x000D_
            <div>Description</div>_x000D_
          </th>_x000D_
        </tr>_x000D_
      </thead>_x000D_
      <tbody>_x000D_
        <tr>_x000D_
          <td>align</td>_x000D_
          <td>left, center, right</td>_x000D_
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the alignment of a table according to surrounding text</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>bgcolor</td>_x000D_
          <td>rgb(x,x,x), #xxxxxx, colorname</td>_x000D_
          <td>Not supported in HTML5. Deprecated in HTML 4.01. Specifies the background color for a table</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>border</td>_x000D_
          <td>1,""</td>_x000D_
          <td>Specifies whether the table cells should have borders or not</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>cellpadding</td>_x000D_
          <td>pixels</td>_x000D_
          <td>Not supported in HTML5. Specifies the space between the cell wall and the cell content</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>cellspacing</td>_x000D_
          <td>pixels</td>_x000D_
          <td>Not supported in HTML5. Specifies the space between cells</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>frame</td>_x000D_
          <td>void, above, below, hsides, lhs, rhs, vsides, box, border</td>_x000D_
          <td>Not supported in HTML5. Specifies which parts of the outside borders that should be visible</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>rules</td>_x000D_
          <td>none, groups, rows, cols, all</td>_x000D_
          <td>Not supported in HTML5. Specifies which parts of the inside borders that should be visible</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>summary</td>_x000D_
          <td>text</td>_x000D_
          <td>Not supported in HTML5. Specifies a summary of the content of a table</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>width</td>_x000D_
          <td>pixels, %</td>_x000D_
          <td>Not supported in HTML5. Specifies the width of a table</td>_x000D_
        </tr>_x000D_
      </tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

But how?!

Simply put you have a table header, that you visually hide by making it 0px high, that also contains divs used as the fixed header. The table's container leaves enough room at the top to allow for the absolutely positioned header, and the table with scrollbars appear as you would expect.

The code above uses the positioned class to position the table absolutely (I'm using it in a popup style dialog) but you can use it in the flow of the document as well by removing the positioned class from the container.

But ...

It's not perfect. Firefox refuses to make the header row 0px (at least I did not find any way) but stubbornly keeps it at minimum 4px ... It's not a huge problem, but depending on your styling it will mess with your borders etc.

The table is also using a faux column approach where the background color of the container itself is used as the background for the header divs, that are transparent.

Summary

All in all there might be styling issues depending on your requirements, especially borders or complicated backgrounds. There might also be problems with computability, I haven't checked it in a wide variety of browsers yet (please comment with your experiences if you try it out), but I didn't find anything like it so I thought it was worth posting anyway ...

How do I select the "last child" with a specific class name in CSS?

You can use the adjacent sibling selector to achieve something similar, that might help.

.list-item.other-class + .list-item:not(.other-class)

Will effectively target the immediately following element after the last element with the class other-class.

Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

It's helped me, I uninstalled EF, restarted VS and I added 'using':

using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;

Is it possible to put a ConstraintLayout inside a ScrollView?

use NestedScrollView with viewport true is working good for me

<android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="700dp">

        </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>

Convert Swift string to array

In Swift 4, as String is a collection of Character, you need to use map

let array1 = Array("hello") // Array<Character>
let array2 = Array("hello").map({ "\($0)" }) // Array<String>
let array3 = "hello".map(String.init) // Array<String>

How to change font in ipython notebook

In JupyterNotebook cell, Simply you can use:

%%html
<style type='text/css'>
.CodeMirror{
font-size: 17px;
</style>

live output from subprocess command

import os

def execute(cmd, callback):
    for line in iter(os.popen(cmd).readline, ''): 
            callback(line[:-1])

execute('ls -a', print)

Resize command prompt through commands

Simply type

MODE [width],[height]

Example:

MODE 14,1

That is the smallest size possible.

MODE 1000,1000

is the largest possible, although it probably won't even fit your screen. If you want to minimize it, type

start /min [yourbatchfile/cmd]

and of course, to maximaze,

start /max [yourbatchfile/cmd]

I am currently working on doing this from the same batch files so that you don't have to have two or start it with cmd. of course, there are shortcuts, but I'm gonna try to figure it out.

PHP function ssh2_connect is not working

To expand on @neubert answer, if you are using Laravel 5 or similar, you can use phpseclib much simpler like this:

Run composer require phpseclib/phpseclib ~2.0

In your controller add

use phpseclib\Net\SSH2;

Then use it in a controller method like:

 $host = config('ssh.host');
 $username = config('ssh.username');
 $password = config('ssh.password'); 
 $command = 'php version';

 $ssh = new SSH2($host);
    if (!$ssh->login($username, $password)) {
        $output ='Login Failed';
    }
    else{
        $output = $ssh->exec($command);
 }

docker build with --build-arg with multiple arguments

Use --build-arg with each argument.

If you are passing two argument then add --build-arg with each argument like:

docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .