Programs & Examples On #Commission junction

Commission Junction is an Affiliate Marketing provider for web-sites.

Using android.support.v7.widget.CardView in my project (Eclipse)

Simply add the following line in your build.gradle project

dependencies {
    ...
    compile 'com.android.support:cardview-v7:24.0.0'
}

And sync the project with gradle.

Postgres: clear entire database before re-creating / re-populating from bash script

I'd just drop the database and then re-create it. On a UNIX or Linux system, that should do it:

$ dropdb development_db_name
$ createdb developmnent_db_name

That's how I do it, actually.

How to connect to a remote Windows machine to execute commands using python?

Many answers already, but one more option

PyPSExec https://pypi.org/project/pypsexec/

It's a python clone of the famous psexec. Works without any installation on the remote windows machine.

Use mysql_fetch_array() with foreach() instead of while()

There's not a good way to convert it to foreach, because mysql_fetch_array() just fetches the next result from $result_select. If you really wanted to foreach, you could do pull all the results into an array first, doing something like the following:

$result_list = array();
while($row = mysql_fetch_array($result_select)) {
   result_list[] = $row;
}

foreach($result_list as $row) {
   ...
}

But there's no good reason I can see to do that - and you still have to use the while loop, which is unavoidable due to how mysql_fetch_array() works. Why is it so important to use a foreach()?

EDIT: If this is just for learning purposes: you can't convert this to a foreach. You have to have a pre-existing array to use a foreach() instead of a while(), and mysql_fetch_array() fetches one result per call - there's no pre-existing array for foreach() to iterate through.

How to grep for two words existing on the same line?

Use grep:

grep -wE "string1|String2|...." file_name

Or you can use:

echo string | grep -wE "string1|String2|...."

What is the behavior difference between return-path, reply-to and from?

I had to add a Return-Path header in emails send by a Redmine instance. I agree with greatwolf only the sender can determine a correct (non default) Return-Path. The case is the following : E-mails are send with the default email address : [email protected] But we want that the real user initiating the action receives the bounce emails, because he will be the one knowing how to fix wrong recipients emails (and not the application adminstrators that have other cats to whip :-) ). We use this and it works perfectly well with exim on the application server and zimbra as the final company mail server.

Android: How to bind spinner to custom object list?

Works fine for me, the code needed around the getResource() thing is as follows:

spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> spinner, View v,
                int arg2, long arg3) {
            String selectedVal = getResources().getStringArray(R.array.compass_rate_values)[spinner.getSelectedItemPosition()];
            //Do something with the value
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    });

Just need to make sure (by yourself) the values in the two arrays are aligned properly!

Sum of values in an array using jQuery

You can do it in this way.

var somearray = ["20","40","80","400"];

somearray = somearray.map(Number);

var total = somearray.reduce(function(a,b){  return a+b },0)

console.log(total);

Find a string between 2 known values

string input = "Exemple of value between two string FirstString text I want to keep SecondString end of my string";
var match = Regex.Match(input, @"FirstString (.+?) SecondString ").Groups[1].Value;

How to customize listview using baseadapter

public class ListElementAdapter extends BaseAdapter{

    String[] data;
    Context context;
    LayoutInflater layoutInflater;


    public ListElementAdapter(String[] data, Context context) {
        super();
        this.data = data;
        this.context = context;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {

        return data.length;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        convertView= layoutInflater.inflate(R.layout.item, null);

        TextView txt=(TextView)convertView.findViewById(R.id.text);

        txt.setText(data[position]);



        return convertView;
    }
}

Just call ListElementAdapter in your Main Activity and set Adapter to ListView.

How to combine paths in Java?

Late to the party perhaps, but I wanted to share my take on this. I'm using a Builder pattern and allow conveniently chained append(more) calls, and allows mixing File and String. It can easily be extended to support working with Path objects as well, and furthermore handles the different path separators correctly on both Linux, Macintosh, etc.

public class Files  {
    public static class PathBuilder {
        private File file;

        private PathBuilder ( File root ) {
            file = root;
        }

        private PathBuilder ( String root ) {
            file = new File(root);
        }

        public PathBuilder append ( File more ) {
            file = new File(file, more.getPath()) );
            return this;
        }

        public PathBuilder append ( String more ) {
            file = new File(file, more);
            return this;
        }

        public File buildFile () {
            return file;
        }
    }

    public static PathBuilder buildPath ( File root ) {
        return new PathBuilder(root);
    }

    public static PathBuilder buildPath ( String root ) {
        return new PathBuilder(root);
    }
}

Example of usage:

File root = File.listRoots()[0];
String hello = "hello";
String world = "world";
String filename = "warez.lha"; 

File file = Files.buildPath(root).append(hello).append(world)
              .append(filename).buildFile();
String absolute = file.getAbsolutePath();

The resulting absolute will contain something like:

/hello/world/warez.lha

or maybe even:

A:\hello\world\warez.lha

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

Use this. Works fine

input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
input.setKeyListener(DigitsKeyListener.getInstance("0123456789"));

EDIT

kotlin version

fun EditText.onlyNumbers() {
    inputType = InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or
        InputType.TYPE_NUMBER_FLAG_SIGNED
    keyListener = DigitsKeyListener.getInstance("0123456789")
}

Calling C/C++ from Python?

ctypes module is part of the standard library, and therefore is more stable and widely available than swig, which always tended to give me problems.

With ctypes, you need to satisfy any compile time dependency on python, and your binding will work on any python that has ctypes, not just the one it was compiled against.

Suppose you have a simple C++ example class you want to talk to in a file called foo.cpp:

#include <iostream>

class Foo{
    public:
        void bar(){
            std::cout << "Hello" << std::endl;
        }
};

Since ctypes can only talk to C functions, you need to provide those declaring them as extern "C"

extern "C" {
    Foo* Foo_new(){ return new Foo(); }
    void Foo_bar(Foo* foo){ foo->bar(); }
}

Next you have to compile this to a shared library

g++ -c -fPIC foo.cpp -o foo.o
g++ -shared -Wl,-soname,libfoo.so -o libfoo.so  foo.o

And finally you have to write your python wrapper (e.g. in fooWrapper.py)

from ctypes import cdll
lib = cdll.LoadLibrary('./libfoo.so')

class Foo(object):
    def __init__(self):
        self.obj = lib.Foo_new()

    def bar(self):
        lib.Foo_bar(self.obj)

Once you have that you can call it like

f = Foo()
f.bar() #and you will see "Hello" on the screen

How to send email in ASP.NET C#

This is the easiest script to test.

<%@ Import Namespace="System.Net" %> 
<%@ Import Namespace="System.Net.Mail" %> 

<script language="C#" runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
       //create the mail message 
        MailMessage mail = new MailMessage(); 

        //set the addresses 
        mail.From = new MailAddress("From email account"); 
        mail.To.Add("To email account"); 

        //set the content 
        mail.Subject = "This is a test email from C# script"; 
        mail.Body = "This is a test email from C# script"; 
        //send the message 
         SmtpClient smtp = new SmtpClient("mail.domainname.com"); 

         NetworkCredential Credentials = new NetworkCredential("to email account", "Password"); 
         smtp.Credentials = Credentials;
         smtp.Send(mail); 
         lblMessage.Text = "Mail Sent"; 
    } 
</script> 
<html> 
<body> 
    <form runat="server"> 
        <asp:Label id="lblMessage" runat="server"></asp:Label> 
    </form> 
</body>

How to remove specific element from an array using python

You don't need to iterate the array. Just:

>>> x = ['[email protected]', '[email protected]']
>>> x
['[email protected]', '[email protected]']
>>> x.remove('[email protected]')
>>> x
['[email protected]']

This will remove the first occurence that matches the string.

EDIT: After your edit, you still don't need to iterate over. Just do:

index = initial_list.index(item1)
del initial_list[index]
del other_list[index]

How to replace an entire line in a text file by line number

Given this test file (test.txt)

Lorem ipsum dolor sit amet,
consectetur adipiscing elit. 
Duis eu diam non tortor laoreet 
bibendum vitae et tellus.

the following command will replace the first line to "newline text"

$ sed '1 c\
> newline text' test.txt

Result:

newline text
consectetur adipiscing elit. 
Duis eu diam non tortor laoreet 
bibendum vitae et tellus.

more information can be found here

http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/

What does numpy.random.seed(0) do?

If you set the np.random.seed(a_fixed_number) every time you call the numpy's other random function, the result will be the same:

>>> import numpy as np
>>> np.random.seed(0) 
>>> perm = np.random.permutation(10) 
>>> print perm 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10) 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10) 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10) 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.rand(4) 
[0.5488135  0.71518937 0.60276338 0.54488318]
>>> np.random.seed(0) 
>>> print np.random.rand(4) 
[0.5488135  0.71518937 0.60276338 0.54488318]

However, if you just call it once and use various random functions, the results will still be different:

>>> import numpy as np
>>> np.random.seed(0) 
>>> perm = np.random.permutation(10)
>>> print perm 
[2 8 4 9 1 6 7 3 0 5]
>>> np.random.seed(0) 
>>> print np.random.permutation(10)
[2 8 4 9 1 6 7 3 0 5]
>>> print np.random.permutation(10) 
[3 5 1 2 9 8 0 6 7 4]
>>> print np.random.permutation(10) 
[2 3 8 4 5 1 0 6 9 7]
>>> print np.random.rand(4) 
[0.64817187 0.36824154 0.95715516 0.14035078]
>>> print np.random.rand(4) 
[0.87008726 0.47360805 0.80091075 0.52047748]

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Reusing a PreparedStatement multiple times

The second way is a tad more efficient, but a much better way is to execute them in batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
        }

        statement.executeBatch();
    }
}

You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.

If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (Connection connection = dataSource.getConnection()) {
        connection.setAutoCommit(false);

        try (PreparedStatement statement = connection.prepareStatement(SQL)) {
            // ...

            try {
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    }
}

Git add all files modified, deleted, and untracked?

Try:

git add -A

Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:

git add -A .

Also see: Difference of git add -A and git add .

Sort an Array by keys based on another Array?

First Suggestion

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key) {
        if(array_key_exists($key,$array)) {
            $ordered[$key] = $array[$key];
            unset($array[$key]);
        }
    }
    return $ordered + $array;
}

Second Suggestion

$properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer);

I wanted to point out that both of these suggestions are awesome. However, they are apples and oranges. The difference? One is non-associative friendly and the other is associative friendly. If you are using 2 fully associative arrays then the array merge/flip will actually merge and overwrite the other associative array. In my case that is not the results I was looking for. I used a settings.ini file to create my sort order array. The data array I was sorting did not need to written over by my associative sorting counterpart. Thus array merge would destroy my data array. Both are great methods, both need to be archived in any developers toolbox. Based on your needs you may find you actually need both concepts in your archives.

insert a NOT NULL column to an existing table

Alter TABLE 'TARGET' add 'ShouldAddColumn' Integer Not Null default "0"

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

enable/disable zoom in Android WebView

The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:

User Pinch Zooms and controls appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP

User Pinch Zoom and Controls don't appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP

Can you shed more light on your solution?

What does "hashable" mean in Python?

From the Python glossary:

An object is hashable if it has a hash value which never changes during its lifetime (it needs a __hash__() method), and can be compared to other objects (it needs an __eq__() or __cmp__() method). Hashable objects which compare equal must have the same hash value.

Hashability makes an object usable as a dictionary key and a set member, because these data structures use the hash value internally.

All of Python’s immutable built-in objects are hashable, while no mutable containers (such as lists or dictionaries) are. Objects which are instances of user-defined classes are hashable by default; they all compare unequal, and their hash value is their id().

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

C fopen vs open

First, there is no particularly good reason to use fdopen if fopen is an option and open is the other possible choice. You shouldn't have used open to open the file in the first place if you want a FILE *. So including fdopen in that list is incorrect and confusing because it isn't very much like the others. I will now proceed to ignore it because the important distinction here is between a C standard FILE * and an OS-specific file descriptor.

There are four main reasons to use fopen instead of open.

  1. fopen provides you with buffering IO that may turn out to be a lot faster than what you're doing with open.
  2. fopen does line ending translation if the file is not opened in binary mode, which can be very helpful if your program is ever ported to a non-Unix environment (though the world appears to be converging on LF-only (except IETF text-based networking protocols like SMTP and HTTP and such)).
  3. A FILE * gives you the ability to use fscanf and other stdio functions.
  4. Your code may someday need to be ported to some other platform that only supports ANSI C and does not support the open function.

In my opinion the line ending translation more often gets in your way than helps you, and the parsing of fscanf is so weak that you inevitably end up tossing it out in favor of something more useful.

And most platforms that support C have an open function.

That leaves the buffering question. In places where you are mainly reading or writing a file sequentially, the buffering support is really helpful and a big speed improvement. But it can lead to some interesting problems in which data does not end up in the file when you expect it to be there. You have to remember to fclose or fflush at the appropriate times.

If you're doing seeks (aka fsetpos or fseek the second of which is slightly trickier to use in a standards compliant way), the usefulness of buffering quickly goes down.

Of course, my bias is that I tend to work with sockets a whole lot, and there the fact that you really want to be doing non-blocking IO (which FILE * totally fails to support in any reasonable way) with no buffering at all and often have complex parsing requirements really color my perceptions.

Git push rejected after feature branch rebase

One solution to this is to do what msysGit's rebasing merge script does - after the rebase, merge in the old head of feature with -s ours. You end up with the commit graph:

A--B--C------F--G (master)
       \         \
        \         D'--E' (feature)
         \           /
          \       --
           \    /
            D--E (old-feature)

... and your push of feature will be a fast-forward.

In other words, you can do:

git checkout feature
git branch old-feature
git rebase master
git merge -s ours old-feature
git push origin feature

(Not tested, but I think that's right...)

from jquery $.ajax to angular $http

The AngularJS way of calling $http would look like:

$http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {"foo":"bar"}
}).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.data = response.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.error = response.statusText;
});

or could be written even simpler using shortcut methods:

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);

There are number of things to notice:

  • AngularJS version is more concise (especially using .post() method)
  • AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)
  • Callback functions are named success and error respectively (also please note parameters of each callback) - Deprecated in angular v1.5
  • use then function instead.
  • More info of then usage can be found here

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

Get user location by IP address

IPInfoDB has an API that you can call in order to find a location based on an IP address.

For "City Precision", you call it like this (you'll need to register to get a free API key):

 http://api.ipinfodb.com/v2/ip_query.php?key=<your_api_key>&ip=74.125.45.100&timezone=false

Here's an example in both VB and C# that shows how to call the API.

How to capitalize the first letter of text in a TextView in an Android Application

For future visitors, you can also (best IMHO) import WordUtil from Apache and add a lot of useful methods to you app, like capitalize as shown here:

How to capitalize the first character of each word in a string

Detect Windows version in .net

The above answers would give me Major version 6 on Windows 10.

The solution that I have found to work without adding extra VB libraries was following:

var versionString = (string)Microsoft.Win32.Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows NT\\CurrentVersion")?.GetValue("productName");

I wouldn't consider this the best way to get the version, but the upside this is oneliner no extra libraries, and in my case checking if it contains "10" was good enough.

Error: allowDefinition='MachineToApplication' beyond application level

I had this error when building the solution with Web Deployment Project created into my solution. I resolve the error by deleting the folder where Web Deployment Project is built to. This folder is specified in "Project Folder" attribute of WDP properties

Check if string is upper, lower, or mixed case in Python

There are a number of "is methods" on strings. islower() and isupper() should meet your needs:

>>> 'hello'.islower()
True

>>> [m for m in dir(str) if m.startswith('is')]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

Here's an example of how to use those methods to classify a list of strings:

>>> words = ['The', 'quick', 'BROWN', 'Fox', 'jumped', 'OVER', 'the', 'Lazy', 'DOG']
>>> [word for word in words if word.islower()]
['quick', 'jumped', 'the']
>>> [word for word in words if word.isupper()]
['BROWN', 'OVER', 'DOG']
>>> [word for word in words if not word.islower() and not word.isupper()]
['The', 'Fox', 'Lazy']

How to adjust text font size to fit textview

The solution below incorporates all of the suggestions here. It starts with what was originally posted by Dunni. It uses a binary search like gjpc's, but it is a bit more readable. It also include's gregm's bug fixes and a bug-fix of my own.

import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

public class FontFitTextView extends TextView {

    public FontFitTextView(Context context) {
        super(context);
        initialise();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise();
    }

    private void initialise() {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());
        //max size defaults to the initially specified text size unless it is too small
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth) 
    { 
        if (textWidth <= 0)
            return;
        int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
        float hi = 100;
        float lo = 2;
        final float threshold = 0.5f; // How close we have to be

        mTestPaint.set(this.getPaint());

        while((hi - lo) > threshold) {
            float size = (hi+lo)/2;
            mTestPaint.setTextSize(size);
            if(mTestPaint.measureText(text) >= targetWidth) 
                hi = size; // too big
            else
                lo = size; // too small
        }
        // Use lo so that we undershoot rather than overshoot
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int height = getMeasuredHeight();
        refitText(this.getText().toString(), parentWidth);
        this.setMeasuredDimension(parentWidth, height);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        refitText(text.toString(), this.getWidth());
    }

    @Override
    protected void onSizeChanged (int w, int h, int oldw, int oldh) {
        if (w != oldw) {
            refitText(this.getText().toString(), w);
        }
    }

    //Attributes
    private Paint mTestPaint;
}

Curl GET request with json parameter

If you want to send your data inside the body, then you have to make a POST or PUT instead of GET.

For me, it looks like you're trying to send the query with uri parameters, which is not related to GET, you can also put these parameters on POST, PUT and so on.

The query is an optional part, separated by a question mark ("?"), that contains additional identification information that is not hierarchical in nature. The query string syntax is not generically defined, but it is commonly organized as a sequence of = pairs, with the pairs separated by a semicolon or an ampersand.

For example:

curl http://server:5050/a/c/getName?param0=foo&param1=bar

Force Internet Explorer to use a specific Java Runtime Environment install?

As has been mentioned here for JRE6 and JRE5, I will update for JRE1.4:

You will need to run the jpicpl32.exe application in the jre/bin directory of your java installation (e.g. c:\java\jdk1.4.2_07\jre\bin\jpicpl32.exe).

This is an earlier version of the application mentioned in Daniel Cassidy's post.

jQuery get input value after keypress

please use this code for input text

$('#search').on("input",function (e) {});

if you use .on("change",function (e) {}); then you need to blur input

if you use .on("keyup",function (e) {}); then you get value before the last character you typed

How to replace innerHTML of a div using jQuery?

you can use either html or text function in jquery to achieve it

$("#regTitle").html("hello world");

OR

$("#regTitle").text("hello world");

Php, wait 5 seconds before executing an action

In https://www.php.net/manual/es/function.usleep.php

<?php
// Wait 2 seconds
usleep(2000000);

// if you need 5 seconds
usleep(5000000);
?>

CREATE TABLE LIKE A1 as A2

Your attempt wasn't that bad. You have to do it with LIKE, yes.

In the manual it says:

Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table.

So you do:

CREATE TABLE New_Users  LIKE Old_Users;

Then you insert with

INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;

But you can not do it in one statement.

Javascript - Get Image height

My preferred solution for this would be to do the resizing server-side, so you are transmitting less unnecessary data.

If you have to do it client-side though, and need to keep the image ratio, you could use the below:

var image_from_ajax = new Image();
image_from_ajax.src = fetch_image_from_ajax(); // Downloaded via ajax call?

image_from_ajax = rescaleImage(image_from_ajax);

// Rescale the given image to a max of max_height and max_width
function rescaleImage(image_name)
{
    var max_height = 100;
    var max_width = 100;

    var height = image_name.height;
    var width = image_name.width;
    var ratio = height/width;

    // If height or width are too large, they need to be scaled down
    // Multiply height and width by the same value to keep ratio constant
    if(height > max_height)
    {
        ratio = max_height / height;
        height = height * ratio;
        width = width * ratio;
    }

    if(width > max_width)
    {
        ratio = max_width / width;
        height = height * ratio;
        width = width * ratio;
    }

    image_name.width = width;
    image_name.height = height;
    return image_name;
}

How do I clear/delete the current line in terminal?

Alt+# comments out the current line. It will be available in history if needed.

How to shift a column in Pandas DataFrame

If you don't want to lose the columns you shift past the end of your dataframe, simply append the required number first:

    offset = 5
    DF = DF.append([np.nan for x in range(offset)])
    DF = DF.shift(periods=offset)
    DF = DF.reset_index() #Only works if sequential index

How can I make git accept a self signed certificate?

This answer is excerpted from this article authored by Michael Kauffman.

Use Git for Windows with a corporate SSL certificate

Issue:

If you have a corporate SSL certificate and want to clone your repo from the console or VSCode you get the following error:

fatal: unable to access ‘https://myserver/tfs/DefaultCollection/_git/Proj/’: SSL certificate problem: unable to get local issuer certificate

Solution:

  1. Export the root self-signed Certificate to a file. You can do this from within your browser.

  2. Locate the “ca-bundle.crt” file in your git folder (current version C:\Program Files\Git\usr\ssl\certs but is has changed in the past). Copy the file to your user profile. Open it with a text editor like VSCode and add the content of your exported certificate to the end of the file.

Now we have to configure git to use the new file:

git config --global http.sslCAInfo C:/Users/<yourname>/ca-bundle.crt

This will add the following entry to your .gitconfig file in the root of your user profile.

[http] sslCAInfo = C:/Users/<yourname>/ca-bundle.crt

How to condense if/else into one line in Python?

Only for using as a value:

x = 3 if a==2 else 0

or

return 3 if a==2 else 0

What is the best way to remove accents (normalize) in a Python unicode string?

This handles not only accents, but also "strokes" (as in ø etc.):

import unicodedata as ud

def rmdiacritics(char):
    '''
    Return the base character of char, by "removing" any
    diacritics like accents or curls and strokes and the like.
    '''
    desc = ud.name(char)
    cutoff = desc.find(' WITH ')
    if cutoff != -1:
        desc = desc[:cutoff]
        try:
            char = ud.lookup(desc)
        except KeyError:
            pass  # removing "WITH ..." produced an invalid name
    return char

This is the most elegant way I can think of (and it has been mentioned by alexis in a comment on this page), although I don't think it is very elegant indeed. In fact, it's more of a hack, as pointed out in comments, since Unicode names are – really just names, they give no guarantee to be consistent or anything.

There are still special letters that are not handled by this, such as turned and inverted letters, since their unicode name does not contain 'WITH'. It depends on what you want to do anyway. I sometimes needed accent stripping for achieving dictionary sort order.

EDIT NOTE:

Incorporated suggestions from the comments (handling lookup errors, Python-3 code).

What is RSS and VSZ in Linux memory management

RSS is the Resident Set Size and is used to show how much memory is allocated to that process and is in RAM. It does not include memory that is swapped out. It does include memory from shared libraries as long as the pages from those libraries are actually in memory. It does include all stack and heap memory.

VSZ is the Virtual Memory Size. It includes all memory that the process can access, including memory that is swapped out, memory that is allocated, but not used, and memory that is from shared libraries.

So if process A has a 500K binary and is linked to 2500K of shared libraries, has 200K of stack/heap allocations of which 100K is actually in memory (rest is swapped or unused), and it has only actually loaded 1000K of the shared libraries and 400K of its own binary then:

RSS: 400K + 1000K + 100K = 1500K
VSZ: 500K + 2500K + 200K = 3200K

Since part of the memory is shared, many processes may use it, so if you add up all of the RSS values you can easily end up with more space than your system has.

The memory that is allocated also may not be in RSS until it is actually used by the program. So if your program allocated a bunch of memory up front, then uses it over time, you could see RSS going up and VSZ staying the same.

There is also PSS (proportional set size). This is a newer measure which tracks the shared memory as a proportion used by the current process. So if there were two processes using the same shared library from before:

PSS: 400K + (1000K/2) + 100K = 400K + 500K + 100K = 1000K

Threads all share the same address space, so the RSS, VSZ and PSS for each thread is identical to all of the other threads in the process. Use ps or top to view this information in linux/unix.

There is way more to it than this, to learn more check the following references:

Also see:

How do I detect the Python version at runtime?

Here's some code I use with sys.version_info to check the Python installation:

def check_installation(rv):
    current_version = sys.version_info
    if current_version[0] == rv[0] and current_version[1] >= rv[1]:
        pass
    else:
        sys.stderr.write( "[%s] - Error: Your Python interpreter must be %d.%d or greater (within major version %d)\n" % (sys.argv[0], rv[0], rv[1], rv[0]) )
        sys.exit(-1)
    return 0

...

# Calling the 'check_installation' function checks if Python is >= 2.7 and < 3
required_version = (2,7)
check_installation(required_version)

What is a lambda (function)?

The lambda calculus is a consistent mathematical theory of substitution. In school mathematics one sees for example x+y=5 paired with x-y=1. Along with ways to manipulate individual equations it's also possible to put the information from these two together, provided cross-equation substitutions are done logically. Lambda calculus codifies the correct way to do these substitutions.

Given that y = x-1 is a valid rearrangement of the second equation, this: ? y = x-1 means a function substituting the symbols x-1 for the symbol y. Now imagine applying ? y to each term in the first equation. If a term is y then perform the substitution; otherwise do nothing. If you do this out on paper you'll see how applying that ? y will make the first equation solvable.

That's an answer without any computer science or programming.

The simplest programming example I can think of comes from http://en.wikipedia.org/wiki/Joy_(programming_language)#How_it_works:

here is how the square function might be defined in an imperative programming language (C):

int square(int x)
{
    return x * x;
}

The variable x is a formal parameter which is replaced by the actual value to be squared when the function is called. In a functional language (Scheme) the same function would be defined:

(define square
  (lambda (x) 
    (* x x)))

This is different in many ways, but it still uses the formal parameter x in the same way.


Added: http://imgur.com/a/XBHub

lambda

Difference between multitasking, multithreading and multiprocessing?

None of the above answers except Mr Vaibhav Kumar's are clear or not ambiguous. [sorry, no offense]

Both multi programming and tasking are same concept of switching task in processor, difference is in the concept and reason of the switching.

MProgramming: to not keep processor idle when active task needs longer IO or other non CPU response then, processor loads and works on another task that is not waiting for IO and ready for process.

MTasking: even after MPrograming, to user it may feel like only one task is executing and another is simply waiting to come to cpu. So the active task is also swapped from active CPU and kept aside and another task is brought in CPU for a very small fraction of human time[second], and swapped back to the earlier task again. In this way user will feel both task are alive in CPU at same time. But actually each task is active only once at a given CPU time[in micro or nano second]

And MProcessing is, like my computer have quad core, so I use 4 processor at a time, means 4 different multiprogramming instances happen in my machine. And these 4 processors does another numerous no of MTasking.

So MProcessing>MProgramming>Mtasking

And MThreading n another breakup of each task. that also to give user a happy life. Here multiple tasks[like word doc and media player] are not coming in picture, rather small subtasks like coloring of text on word and automatic spell check in word are part of same word executable.

not sure if I was able to make clear all confusions...

How to correctly get image from 'Resources' folder in NetBeans

Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image. In one of my tries i use

    String pathToImageSortBy = "resources/testDataIcons/filling.png";
    ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

But correct way was use name of my project in path to resource

String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));

SQL query to get most recent row for each instance of a given key

I've been using this because I'm returning results from another table. Though I'm trying to avoid the nested join if it helps w/ one less step. Oh well. It returns the same thing.

select
users.userid
, lastIP.IP
, lastIP.maxdate

from users

inner join (
    select userid, IP, datetime
    from IPAddresses
    inner join (
        select userid, max(datetime) as maxdate
        from IPAddresses
        group by userid
        ) maxIP on IPAddresses.datetime = maxIP.maxdate and IPAddresses.userid = maxIP.userid
    ) as lastIP on users.userid = lastIP.userid

Can my enums have friendly names?

One problem with this trick is that description attribute cannot be localized. I do like a technique by Sacha Barber where he creates his own version of Description attribute which would pick up values from the corresponding resource manager.

http://www.codeproject.com/KB/WPF/FriendlyEnums.aspx

Although the article is around a problem that's generally faced by WPF developers when binding to enums, you can jump directly to the part where he creates the LocalizableDescriptionAttribute.

jQuery - Getting form values for ajax POST

var username = $('#username').val();
var email= $('#email').val();
var password= $('#password').val();

What is the benefit of zerofill in MySQL?

When you select a column with type ZEROFILL it pads the displayed value of the field with zeros up to the display width specified in the column definition. Values longer than the display width are not truncated. Note that usage of ZEROFILL also implies UNSIGNED.

Using ZEROFILL and a display width has no effect on how the data is stored. It affects only how it is displayed.

Here is some example SQL that demonstrates the use of ZEROFILL:

CREATE TABLE yourtable (x INT(8) ZEROFILL NOT NULL, y INT(8) NOT NULL);
INSERT INTO yourtable (x,y) VALUES
(1, 1),
(12, 12),
(123, 123),
(123456789, 123456789);
SELECT x, y FROM yourtable;

Result:

        x          y
 00000001          1
 00000012         12
 00000123        123
123456789  123456789

How to display a loading screen while site content loads

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.

Generate signed apk android studio

Use Keytool binary or exe to generate a private keystore. Instructions here. You can then sign your app using this keystore. Keytool gets installed when you install Java.

NOTE: Save/backup this keystore because once you publish an app on play by signing it with this keystore, you will have to use the same keystore for any future updates. So, it's important that you back it up.

HTH.

Upload files with HTTPWebrequest (multipart/form-data)

Check out the MyToolkit library:

var request = new HttpPostRequest("http://www.server.com");
request.Data.Add("name", "value"); // POST data
request.Files.Add(new HttpPostFile("name", "file.jpg", "path/to/file.jpg")); 

await Http.PostAsync(request, OnRequestFinished);

http://mytoolkit.codeplex.com/wikipage?title=Http

Printing all properties in a Javascript Object

What about this:

var txt="";
var nyc = {
    fullName: "New York City",
    mayor: "Michael Bloomberg",
    population: 8000000,
    boroughs: 5
};

for (var x in nyc){
    txt += nyc[x];
}

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The Html.TextboxFor always creates a textbox (<input type="text" ...).

While the EditorFor looks at the type and meta information, and can render another control or a template you supply.

For example for DateTime properties you can create a template that uses the jQuery DatePicker.

How does the Python's range function work?

A "for loop" in most, if not all, programming languages is a mechanism to run a piece of code more than once.

This code:

for i in range(5):
    print i

can be thought of working like this:

i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

So you see, what happens is not that i gets the value 0, 1, 2, 3, 4 at the same time, but rather sequentially.

I assume that when you say "call a, it gives only 5", you mean like this:

for i in range(5):
    a=i+1
print a

this will print the last value that a was given. Every time the loop iterates, the statement a=i+1 will overwrite the last value a had with the new value.

Code basically runs sequentially, from top to bottom, and a for loop is a way to make the code go back and something again, with a different value for one of the variables.

I hope this answered your question.

Angular ng-if="" with multiple arguments

It is possible.

<span ng-if="checked && checked2">
  I'm removed when the checkbox is unchecked.
</span>

http://plnkr.co/edit/UKNoaaJX5KG3J7AswhLV?p=preview

Graphviz: How to go from .dot to a graph?

You can use a very good online tool for it. Here is the link dreampuf.github.io Just replace the code inside editer with your code.

Parsing huge logfiles in Node.js - read in line-by-line

I used https://www.npmjs.com/package/line-by-line for reading more than 1 000 000 lines from a text file. In this case, an occupied capacity of RAM was about 50-60 megabyte.

    const LineByLineReader = require('line-by-line'),
    lr = new LineByLineReader('big_file.txt');

    lr.on('error', function (err) {
         // 'err' contains error object
    });

    lr.on('line', function (line) {
        // pause emitting of lines...
        lr.pause();

        // ...do your asynchronous line processing..
        setTimeout(function () {
            // ...and continue emitting lines.
            lr.resume();
        }, 100);
    });

    lr.on('end', function () {
         // All lines are read, file is closed now.
    });

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");

The mm is minutes you want MM

CODE

public class Test {

    public static void main(String[] args) throws ParseException {
        java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
                .parse("2012-07-10 14:58:00.000000");
        System.out.println(temp);
    }
}

Prints:

Tue Jul 10 14:58:00 EDT 2012

Replace an element into a specific position of a vector

You can do that using at. You can try out the following simple example:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method at returns an allocator_type::reference, which is that case is a int&. Using at is equivalent to assigning values like vec[i]=....


There is a difference between at and insert as it can be understood with the following example:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vec we will get:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

1 2 10 4 5 0 0 0

Git branching: master vs. origin/master vs. remotes/origin/master

Technically there aren't actually any "remote" things at all1 in your Git repo, there are just local names that should correspond to the names on another, different repo. The ones named origin/whatever will initially match up with those on the repo you cloned-from:

git clone ssh://some.where.out.there/some/path/to/repo # or git://some.where...

makes a local copy of the other repo. Along the way it notes all the branches that were there, and the commits those refer-to, and sticks those into your local repo under the names refs/remotes/origin/.

Depending on how long you go before you git fetch or equivalent to update "my copy of what's some.where.out.there", they may change their branches around, create new ones, and delete some. When you do your git fetch (or git pull which is really fetch plus merge), your repo will make copies of their new work and change all the refs/remotes/origin/<name> entries as needed. It's that moment of fetching that makes everything match up (well, that, and the initial clone, and some cases of pushing too—basically whenever Git gets a chance to check—but see caveat below).

Git normally has you refer to your own refs/heads/<name> as just <name>, and the remote ones as origin/<name>, and it all just works because it's obvious which one is which. It's sometimes possible to create your own branch names that make it not obvious, but don't worry about that until it happens. :-) Just give Git the shortest name that makes it obvious, and it will go from there: origin/master is "where master was over there last time I checked", and master is "where master is over here based on what I have been doing". Run git fetch to update Git on "where master is over there" as needed.


Caveat: in versions of Git older than 1.8.4, git fetch has some modes that don't update "where master is over there" (more precisely, modes that don't update any remote-tracking branches). Running git fetch origin, or git fetch --all, or even just git fetch, does update. Running git fetch origin master doesn't. Unfortunately, this "doesn't update" mode is triggered by ordinary git pull. (This is mainly just a minor annoyance and is fixed in Git 1.8.4 and later.)


1Well, there is one thing that is called a "remote". But that's also local! The name origin is the thing Git calls "a remote". It's basically just a short name for the URL you used when you did the clone. It's also where the origin in origin/master comes from. The name origin/master is called a remote-tracking branch, which sometimes gets shortened to "remote branch", especially in older or more informal documentation.

How to find the unclosed div tag

As stated already, running your code through the W3C Validator is great but if your page is complex, you still may not know exactly where to find the open div.

I like using tabs to indent my code. It keeps it visually organized so that these issues are easier to find, children, siblings, parents, etc... they'll appear more obvious.

EDIT: Also, I'll use a few HTML comments to mark closing tags in the complex areas. I keep these to a minimum for neatness.

<body>

    <div>
        Main Content

        <div>
            Div #1 content

            <div>
               Child of div #1

               <div>
                   Child of child of div #1
               </div><!--// close of child of child of div #1 //-->
            </div><!--// close of child of div #1 //-->
        </div><!--// close of div #1 //-->

        <div>
            Div #2 content
        </div>

        <div>
            Div #3 content
        </div>

    </div><!--// close of Main Content div //-->

</body>

Password Protect a SQLite DB. Is it possible?

Use SQLCipher, it's an opensource extension for SQLite that provides transparent 256-bit AES encryption of database files. http://sqlcipher.net

Replace Fragment inside a ViewPager

As of November 13th 2012, repacing fragments in a ViewPager seems to have become a lot easier. Google released Android 4.2 with support for nested fragments, and it's also supported in the new Android Support Library v11 so this will work all the way back to 1.6

It's very similiar to the normal way of replacing a fragment except you use getChildFragmentManager. It seems to work except the nested fragment backstack isn't popped when the user clicks the back button. As per the solution in that linked question, you need to manually call the popBackStackImmediate() on the child manager of the fragment. So you need to override onBackPressed() of the ViewPager activity where you'll get the current fragment of the ViewPager and call getChildFragmentManager().popBackStackImmediate() on it.

Getting the Fragment currently being displayed is a bit hacky as well, I used this dirty "android:switcher:VIEWPAGER_ID:INDEX" solution but you can also keep track of all fragments of the ViewPager yourself as explained in the second solution on this page.

So here's my code for a ViewPager with 4 ListViews with a detail view shown in the ViewPager when the user clicks a row, and with the back button working. I tried to include just the relevant code for the sake of brevity so leave a comment if you want the full app uploaded to GitHub.

HomeActivity.java

 public class HomeActivity extends SherlockFragmentActivity {
FragmentAdapter mAdapter;
ViewPager mPager;
TabPageIndicator mIndicator;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mAdapter = new FragmentAdapter(getSupportFragmentManager());
    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(mAdapter);
    mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
    mIndicator.setViewPager(mPager);
}

// This the important bit to make sure the back button works when you're nesting fragments. Very hacky, all it takes is some Google engineer to change that ViewPager view tag to break this in a future Android update.
@Override
public void onBackPressed() {
    Fragment fragment = (Fragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":"+mPager.getCurrentItem());
    if (fragment != null) // could be null if not instantiated yet
    {
        if (fragment.getView() != null) {
            // Pop the backstack on the ChildManager if there is any. If not, close this activity as normal.
            if (!fragment.getChildFragmentManager().popBackStackImmediate()) {
                finish();
            }
        }
    }
}

class FragmentAdapter extends FragmentPagerAdapter {        
    public FragmentAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
            return ListProductsFragment.newInstance();
        case 1:
            return ListActiveSubstancesFragment.newInstance();
        case 2:
            return ListProductFunctionsFragment.newInstance();
        case 3:
            return ListCropsFragment.newInstance();
        default:
            return null;
        }
    }

    @Override
    public int getCount() {
        return 4;
    }

 }
}

ListProductsFragment.java

public class ListProductsFragment extends SherlockFragment {
private ListView list;

public static ListProductsFragment newInstance() {
    ListProductsFragment f = new ListProductsFragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View V = inflater.inflate(R.layout.list, container, false);
    list = (ListView)V.findViewById(android.R.id.list);
    list.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
            int position, long id) {
          // This is important bit
          Fragment productDetailFragment = FragmentProductDetail.newInstance();
          FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
          transaction.addToBackStack(null);
          transaction.replace(R.id.products_list_linear, productDetailFragment).commit();
        }
      });       
    return V;
}
}

How do I set default value of select box in angularjs

You can simple use ng-init like this

<select ng-init="somethingHere = options[0]" ng-model="somethingHere" ng-options="option.name for option in options"></select>

Splitting words into letters in Java

Including numbers but not whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("\\W","").toCharArray();

=> S, t, a, c, k, M, e, 1, 2, 3, H, e, p, p, a, 1, o, e, u

Without numbers and whitespace:

"Stack Me 123 Heppa1 oeu".replaceAll("[^a-z^A-Z]","").toCharArray()

=> S, t, a, c, k, M, e, H, e, p, p, a, o, e, u

best way to get folder and file list in Javascript

I don't like adding new package into my project just to handle this simple task.

And also, I try my best to avoid RECURSIVE algorithm.... since, for most cases it is slower compared to non Recursive one.

So I made a function to get all the folder content (and its sub folder).... NON-Recursively

var getDirectoryContent = function(dirPath) {
    /* 
        get list of files and directories from given dirPath and all it's sub directories
        NON RECURSIVE ALGORITHM
        By. Dreamsavior
    */
    var RESULT = {'files':[], 'dirs':[]};

    var fs = fs||require('fs');
    if (Boolean(dirPath) == false) {
        return RESULT;
    }
    if (fs.existsSync(dirPath) == false) {
        console.warn("Path does not exist : ", dirPath);
        return RESULT;
    }

    var directoryList = []
    var DIRECTORY_SEPARATOR = "\\";
    if (dirPath[dirPath.length -1] !== DIRECTORY_SEPARATOR) dirPath = dirPath+DIRECTORY_SEPARATOR;

    directoryList.push(dirPath); // initial

    while (directoryList.length > 0) {
        var thisDir  = directoryList.shift(); 
        if (Boolean(fs.existsSync(thisDir) && fs.lstatSync(thisDir).isDirectory()) == false) continue;

        var thisDirContent = fs.readdirSync(thisDir);
        while (thisDirContent.length > 0) { 
            var thisFile  = thisDirContent.shift(); 
            var objPath = thisDir+thisFile

            if (fs.existsSync(objPath) == false) continue;
            if (fs.lstatSync(objPath).isDirectory()) { // is a directory
                let thisDirPath = objPath+DIRECTORY_SEPARATOR; 
                directoryList.push(thisDirPath);
                RESULT['dirs'].push(thisDirPath);

            } else  { // is a file
                RESULT['files'].push(objPath); 

            } 
        } 

    }
    return RESULT;
}

the only drawback of this function is that this is Synchronous function... You have been warned ;)

Cannot connect to MySQL 4.1+ using old authentication

Had the same issue, but executing the queries alone will not help. To fix this I did the following,

  1. Set old_passwords=0 in my.cnf file
  2. Restart mysql
  3. Login to mysql as root user
  4. Execute FLUSH PRIVILEGES;

How to use pull to refresh in Swift?

you can use this subclass of tableView:

import UIKit

protocol PullToRefreshTableViewDelegate : class {
    func tableViewDidStartRefreshing(tableView: PullToRefreshTableView)
}

class PullToRefreshTableView: UITableView {

    @IBOutlet weak var pullToRefreshDelegate: AnyObject?
    private var refreshControl: UIRefreshControl!
    private var isFirstLoad = true

    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)

        if (isFirstLoad) {
            addRefreshControl()
            isFirstLoad = false
        }
    }

    private func addRefreshControl() {
        refreshControl = UIRefreshControl()
        refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
        refreshControl.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
        self.addSubview(refreshControl)
    }

    @objc private func refresh() {
       (pullToRefreshDelegate as? PullToRefreshTableViewDelegate)?.tableViewDidStartRefreshing(self)
    }

    func endRefreshing() {
        refreshControl.endRefreshing()
    }

}

1 - in interface builder change the class of your tableView to PullToRefreshTableView or create a PullToRefreshTableView programmatically

2 - implement the PullToRefreshTableViewDelegate in your view controller

3 - tableViewDidStartRefreshing(tableView: PullToRefreshTableView) will be called in your view controller when the table view starts refreshing

4 - call yourTableView.endRefreshing() to finish the refreshing

Global variables in R

What about .GlobalEnv$a <- "new" ? I saw this explicit way of creating a variable in a certain environment here: http://adv-r.had.co.nz/Environments.html. It seems shorter than using the assign() function.

SQL Server error on update command - "A severe error occurred on the current command"

One other possible solution we just found after having this issue across multiple databases/tables on the same server.

Is the max connections open to the sql server. We had an app that wasn't closing it's SQL connection and was leaving them open so we were running around 28K-31K connections (SQL Sever has a max out at 32K ish), and we noticed that once we killed a few thousand sleeping connections it took care of the error listed on this question.

The fix was to update the apps to make sure they closed their connections instead of leaving them open.

How to remove array element in mongodb?

This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

db.collection.update(
  { _id: id },
  { $pull: { 'contact': { number: '+1786543589455' } } }
);

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Use java.util.Date class instead of Timestamp.

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

This will get you the current date in the format specified.

Split string to equal length substrings in Java

i use the following java 8 solution:

public static List<String> splitString(final String string, final int chunkSize) {
  final int numberOfChunks = (string.length() + chunkSize - 1) / chunkSize;
  return IntStream.range(0, numberOfChunks)
                  .mapToObj(index -> string.substring(index * chunkSize, Math.min((index + 1) * chunkSize, string.length())))
                  .collect(toList());
}

In Python, how do I split a string and keep the separators?

If one wants to split string while keeping separators by regex without capturing group:

def finditer_with_separators(regex, s):
    matches = []
    prev_end = 0
    for match in regex.finditer(s):
        match_start = match.start()
        if (prev_end != 0 or match_start > 0) and match_start != prev_end:
            matches.append(s[prev_end:match.start()])
        matches.append(match.group())
        prev_end = match.end()
    if prev_end < len(s):
        matches.append(s[prev_end:])
    return matches

regex = re.compile(r"[\(\)]")
matches = finditer_with_separators(regex, s)

If one assumes that regex is wrapped up into capturing group:

def split_with_separators(regex, s):
    matches = list(filter(None, regex.split(s)))
    return matches

regex = re.compile(r"([\(\)])")
matches = split_with_separators(regex, s)

Both ways also will remove empty groups which are useless and annoying in most of the cases.

What is AndroidX?

It is the same as AppCompat versions of support but it has less mess of v4 and v7 versions so it is much help from Using the different components of android XML elements.

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

1) Create KeyboardHeightHelper:

public class KeyboardHeightHelper {

    private final View decorView;
    private int lastKeyboardHeight = -1;

    public KeyboardHeightHelper(Activity activity, View activityRootView, OnKeyboardHeightChangeListener listener) {
        this.decorView = activity.getWindow().getDecorView();
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            int keyboardHeight = getKeyboardHeight();
            if (lastKeyboardHeight != keyboardHeight) {
                lastKeyboardHeight = keyboardHeight;
                listener.onKeyboardHeightChange(keyboardHeight);
            }
        });
    }

    private int getKeyboardHeight() {
        Rect rect = new Rect();
        decorView.getWindowVisibleDisplayFrame(rect);
        return decorView.getHeight() - rect.bottom;
    }

    public interface OnKeyboardHeightChangeListener {
        void onKeyboardHeightChange(int keyboardHeight);
    }
}

2) Let your activity be full screen:

activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

3) Listen for keyboard height changes and add bottom padding for your view:

View rootView = activity.findViewById(R.id.root); // your root view or any other you want to resize
KeyboardHeightHelper effectiveHeightHelper = new KeyboardHeightHelper(
        activity, 
        rootView,
        keyboardHeight -> rootView.setPadding(0, 0, 0, keyboardHeight));

So, each time keyboard will appear on the screen - bottom padding for your view will change, and content will be rearranged.

Function vs. Stored Procedure in SQL Server

Write a user-defined function when you want to compute and return a value for use in other SQL statements; write a stored procedure when you want instead is to group a possibly-complex set of SQL statements. These are two pretty different use cases, after all!

jquery ajax get responsetext from http url

As Karim said, cross domain ajax doesn't work unless the server allows for it. In this case Google does not, BUT, there is a simple trick to get around this in many cases. Just have your local server pass the content retrieved through HTTP or HTTPS.

For example, if you were using PHP, you could:

Create the file web_root/ajax_responders/google.php with:

<?php
  echo file_get_contents('http://www.google.de');
?>

And then alter your code to connect to that instead of to Google's domain directly in the javascript:

var response = $.ajax({ type: "GET",   
                        url: "/ajax_responders/google.php",   
                        async: false
                      }).responseText;
alert(response);

How can I build multiple submit buttons django form?

You can also do like this,

 <form method='POST'>
    {{form1.as_p}}
    <button type="submit" name="btnform1">Save Changes</button>
    </form>
    <form method='POST'>
    {{form2.as_p}}
    <button type="submit" name="btnform2">Save Changes</button>
    </form>

CODE

if request.method=='POST' and 'btnform1' in request.POST:
    do something...
if request.method=='POST' and 'btnform2' in request.POST:
    do something...

Spring's overriding bean

Not sure if that's exactly what you need, but we are using profiles to define the environment we are running at and specific bean for each environment, so it's something like that:

<bean name="myBean" class="myClass">
    <constructor-arg name="name" value="originalValue" />
</bean>
<beans profile="DEV, default">
     <!-- Specific DEV configurations, also default if no profile defined -->
    <bean name="myBean" class="myClass">
        <constructor-arg name="name" value="overrideValue" />
    </bean>
</beans>
<beans profile="CI, UAT">
     <!-- Specific CI / UAT configurations -->
</beans>
<beans profile="PROD">
     <!-- Specific PROD configurations -->
</beans>

So in this case, if I don't define a profile or if I define it as "DEV" myBean will get "overrideValue" for it's name argument. But if I set the profile to "CI", "UAT" or "PROD" it will get "originalValue" as the value.

JavaScript before leaving the page

Most of the solutions here did not work for me so I used the one found here

I also added a variable to allow the confirm box or not

window.hideWarning = false;
window.addEventListener('beforeunload', (event) => {
    if (!hideWarning) {
        event.preventDefault();
        event.returnValue = '';
    }

});

Add table row in jQuery

Pure JS is quite short in your case

myTable.firstChild.innerHTML += '<tr><td>my data</td><td>more data</td></tr>'

_x000D_
_x000D_
function add() {_x000D_
  myTable.firstChild.innerHTML+=`<tr><td>date</td><td>${+new Date}</td></tr>`_x000D_
}
_x000D_
td {border: 1px solid black;}
_x000D_
<button onclick="add()">Add</button><br>_x000D_
<table id="myTable"><tbody></tbody> </table>
_x000D_
_x000D_
_x000D_

(if we remove <tbody> and firstChild it will also works but wrap every row with <tbody>)

Vue.js get selected option on @change

Use v-model to bind the value of selected option's value. Here is an example.

<select name="LeaveType" @change="onChange($event)" class="form-control" v-model="key">
   <option value="1">Annual Leave/ Off-Day</option>
   <option value="2">On Demand Leave</option>
</select>
<script>
var vm = new Vue({
    data: {
        key: ""
    },
    methods: {
        onChange(event) {
            console.log(event.target.value)
        }
    }
}
</script>

More reference can been seen from here.

Getting json body in aws Lambda via API gateway

There are two different Lambda integrations you can configure in API Gateway, such as Lambda integration and Lambda proxy integration. For Lambda integration, you can customise what you are going to pass to Lambda in the payload that you don't need to parse the body, but when you are using Lambda Proxy integration in API Gateway, API Gateway will proxy everything to Lambda in payload like this,

{
    "message": "Hello me!",
    "input": {
        "path": "/test/hello",
        "headers": {
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Accept-Encoding": "gzip, deflate, lzma, sdch, br",
            "Accept-Language": "en-US,en;q=0.8",
            "CloudFront-Forwarded-Proto": "https",
            "CloudFront-Is-Desktop-Viewer": "true",
            "CloudFront-Is-Mobile-Viewer": "false",
            "CloudFront-Is-SmartTV-Viewer": "false",
            "CloudFront-Is-Tablet-Viewer": "false",
            "CloudFront-Viewer-Country": "US",
            "Host": "wt6mne2s9k.execute-api.us-west-2.amazonaws.com",
            "Upgrade-Insecure-Requests": "1",
            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
            "Via": "1.1 fb7cca60f0ecd82ce07790c9c5eef16c.cloudfront.net (CloudFront)",
            "X-Amz-Cf-Id": "nBsWBOrSHMgnaROZJK1wGCZ9PcRcSpq_oSXZNQwQ10OTZL4cimZo3g==",
            "X-Forwarded-For": "192.168.100.1, 192.168.1.1",
            "X-Forwarded-Port": "443",
            "X-Forwarded-Proto": "https"
        },
        "pathParameters": {"proxy": "hello"},
        "requestContext": {
            "accountId": "123456789012",
            "resourceId": "us4z18",
            "stage": "test",
            "requestId": "41b45ea3-70b5-11e6-b7bd-69b5aaebc7d9",
            "identity": {
                "cognitoIdentityPoolId": "",
                "accountId": "",
                "cognitoIdentityId": "",
                "caller": "",
                "apiKey": "",
                "sourceIp": "192.168.100.1",
                "cognitoAuthenticationType": "",
                "cognitoAuthenticationProvider": "",
                "userArn": "",
                "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36 OPR/39.0.2256.48",
                "user": ""
            },
            "resourcePath": "/{proxy+}",
            "httpMethod": "GET",
            "apiId": "wt6mne2s9k"
        },
        "resource": "/{proxy+}",
        "httpMethod": "GET",
        "queryStringParameters": {"name": "me"},
        "stageVariables": {"stageVarName": "stageVarValue"},
        "body": "{\"foo\":\"bar\"}",
        "isBase64Encoded": false
    }
}

For the example you are referencing, it is not getting the body from the original request. It is constructing the response body back to API Gateway. It should be in this format,

{
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "...",
    "isBase64Encoded": false
}

Get the value of bootstrap Datetimepicker in JavaScript

This is working for me using this Bootsrap Datetimepiker, it returns the value as it is shown in the datepicker input, e.g. 2019-04-11

$('#myDateTimePicker').on('click,focusout', function (){
    var myDate = $("#myDateTimePicker").val();
    //console.log(myDate);
    //alert(myDate);
});

How to check heap usage of a running JVM from the command line?

All procedure at once. Based on @Till Schäfer answer.

In KB...

jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10]); printf("%.2f KB\n",sum)}'

In MB...

jstat -gc $(ps axf | egrep -i "*/bin/java *" | egrep -v grep | awk '{print $1}') | tail -n 1 | awk '{split($0,a," "); sum=(a[3]+a[4]+a[6]+a[8]+a[10])/1024; printf("%.2f MB\n",sum)}'

"Awk sum" reference:

 a[1] - S0C
 a[2] - S1C
 a[3] - S0U
 a[4] - S1U
 a[5] - EC
 a[6] - EU
 a[7] - OC
 a[8] - OU
 a[9] - PC
a[10] - PU
a[11] - YGC
a[12] - YGCT
a[13] - FGC
a[14] - FGCT
a[15] - GCT

Used for "Awk sum":

a[3] -- (S0U) Survivor space 0 utilization (KB).
a[4] -- (S1U) Survivor space 1 utilization (KB).
a[6] -- (EU) Eden space utilization (KB).
a[8] -- (OU) Old space utilization (KB).
a[10] - (PU) Permanent space utilization (KB).

[Ref.: https://docs.oracle.com/javase/7/docs/technotes/tools/share/jstat.html ]

Thanks!

NOTE: Works to OpenJDK!

FURTHER QUESTION: Wrong information?

If you check memory usage with the ps command, you will see that the java process consumes much more...

ps -eo size,pid,user,command --sort -size | egrep -i "*/bin/java *" | egrep -v grep | awk '{ hr=$1/1024 ; printf("%.2f MB ",hr) } { for ( x=4 ; x<=NF ; x++ ) { printf("%s ",$x) } print "" }' | cut -d "" -f2 | cut -d "-" -f1

UPDATE (2021-02-16):

According to the reference below (and @Till Schäfer comment) "ps can show total reserved memory from OS" (adapted) and "jstat can show used space of heap and stack" (adapted). So, we see a difference between what is pointed out by the ps command and the jstat command.

According to our understanding, the most "realistic" information would be the ps output since we will have an effective response of how much of the system's memory is compromised. The command jstat serves for a more detailed analysis regarding the java performance in the consumption of reserved memory from OS.

[Ref.: http://www.openkb.info/2014/06/how-to-check-java-memory-usage.html ]

Efficiently convert rows to columns in sql server

This is rather a method than just a single script but gives you much more flexibility.

First of all There are 3 objects:

  1. User defined TABLE type [ColumnActionList] -> holds data as parameter
  2. SP [proc_PivotPrepare] -> prepares our data
  3. SP [proc_PivotExecute] -> execute the script

CREATE TYPE [dbo].[ColumnActionList] AS TABLE ( [ID] [smallint] NOT NULL, [ColumnName] nvarchar NOT NULL, [Action] nchar NOT NULL ); GO

    CREATE PROCEDURE [dbo].[proc_PivotPrepare] 
    (
    @DB_Name        nvarchar(128),
    @TableName      nvarchar(128)
    )
    AS
            SELECT @DB_Name = ISNULL(@DB_Name,db_name())
    DECLARE @SQL_Code nvarchar(max)

    DECLARE @MyTab TABLE (ID smallint identity(1,1), [Column_Name] nvarchar(128), [Type] nchar(1), [Set Action SQL] nvarchar(max));

    SELECT @SQL_Code        =   'SELECT [<| SQL_Code |>] = '' '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Declare user defined type [ID] / [ColumnName] / [PivotAction] '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''DECLARE @ColumnListWithActions ColumnActionList;'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Set [PivotAction] (''''S'''' as default) to select dimentions and values '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----|'''
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| ''''S'''' = Stable column || ''''D'''' = Dimention column || ''''V'''' = Value column '' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''INSERT INTO  @ColumnListWithActions VALUES ('' + CAST( ROW_NUMBER() OVER (ORDER BY [NAME]) as nvarchar(10)) + '', '' + '''''''' + [NAME] + ''''''''+ '', ''''S'''');'''
                                        + 'FROM [' + @DB_Name + '].sys.columns  '
                                        + 'WHERE object_id = object_id(''[' + @DB_Name + ']..[' + @TableName + ']'') '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''-----| Execute sp_PivotExecute with parameters: columns and dimentions and main table name'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '
                                        + 'UNION ALL '
                                        + 'SELECT ''EXEC [dbo].[sp_PivotExecute] @ColumnListWithActions, ' + '''''' + @TableName + '''''' + ';'''
                                        + 'UNION ALL '
                                        + 'SELECT ''----------------------------------------------------------------------------------------------------'' '                            
EXECUTE SP_EXECUTESQL @SQL_Code;

GO

CREATE PROCEDURE [dbo].[sp_PivotExecute]
(
@ColumnListWithActions  ColumnActionList ReadOnly
,@TableName                     nvarchar(128)
)
AS


--#######################################################################################################################
--###| Step 1 - Select our user-defined-table-variable into temp table
--#######################################################################################################################

IF OBJECT_ID('tempdb.dbo.#ColumnListWithActions', 'U') IS NOT NULL DROP TABLE #ColumnListWithActions; 
SELECT * INTO #ColumnListWithActions FROM @ColumnListWithActions;

--#######################################################################################################################
--###| Step 2 - Preparing lists of column groups as strings:
--#######################################################################################################################

DECLARE @ColumnName                     nvarchar(128)
DECLARE @Destiny                        nchar(1)

DECLARE @ListOfColumns_Stable           nvarchar(max)
DECLARE @ListOfColumns_Dimension    nvarchar(max)
DECLARE @ListOfColumns_Variable     nvarchar(max)
--############################
--###| Cursor for List of Stable Columns
--############################

DECLARE ColumnListStringCreator_S CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'S'
OPEN ColumnListStringCreator_S;
FETCH NEXT FROM ColumnListStringCreator_S
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Stable = ISNULL(@ListOfColumns_Stable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_S INTO @ColumnName
   END

CLOSE ColumnListStringCreator_S;
DEALLOCATE ColumnListStringCreator_S;

--############################
--###| Cursor for List of Dimension Columns
--############################

DECLARE ColumnListStringCreator_D CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'D'
OPEN ColumnListStringCreator_D;
FETCH NEXT FROM ColumnListStringCreator_D
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Dimension = ISNULL(@ListOfColumns_Dimension, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_D INTO @ColumnName
   END

CLOSE ColumnListStringCreator_D;
DEALLOCATE ColumnListStringCreator_D;

--############################
--###| Cursor for List of Variable Columns
--############################

DECLARE ColumnListStringCreator_V CURSOR FOR
SELECT      [ColumnName]
FROM        #ColumnListWithActions
WHERE       [Action] = 'V'
OPEN ColumnListStringCreator_V;
FETCH NEXT FROM ColumnListStringCreator_V
INTO @ColumnName
  WHILE @@FETCH_STATUS = 0

   BEGIN
        SELECT @ListOfColumns_Variable = ISNULL(@ListOfColumns_Variable, '') + ' [' + @ColumnName + '] ,';
        FETCH NEXT FROM ColumnListStringCreator_V INTO @ColumnName
   END

CLOSE ColumnListStringCreator_V;
DEALLOCATE ColumnListStringCreator_V;

SELECT @ListOfColumns_Variable      = LEFT(@ListOfColumns_Variable, LEN(@ListOfColumns_Variable) - 1);
SELECT @ListOfColumns_Dimension = LEFT(@ListOfColumns_Dimension, LEN(@ListOfColumns_Dimension) - 1);
SELECT @ListOfColumns_Stable            = LEFT(@ListOfColumns_Stable, LEN(@ListOfColumns_Stable) - 1);

--#######################################################################################################################
--###| Step 3 - Preparing table with all possible connections between Dimension columns excluding NULLs
--#######################################################################################################################
DECLARE @DIM_TAB TABLE ([DIM_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @DIM_TAB 
SELECT [DIM_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'D';

DECLARE @DIM_ID smallint;
SELECT      @DIM_ID = 1;


DECLARE @SQL_Dimentions nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_Dimentions', 'U') IS NOT NULL DROP TABLE ##ALL_Dimentions; 

SELECT @SQL_Dimentions      = 'SELECT [xxx_ID_xxx] = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Dimension + '), ' + @ListOfColumns_Dimension
                                            + ' INTO ##ALL_Dimentions '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Dimension + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) + ' IS NOT NULL ';
                                            SELECT @DIM_ID = @DIM_ID + 1;
            WHILE @DIM_ID <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
            BEGIN
            SELECT @SQL_Dimentions = @SQL_Dimentions + 'AND ' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @DIM_ID) +  ' IS NOT NULL ';
            SELECT @DIM_ID = @DIM_ID + 1;
            END

SELECT @SQL_Dimentions   = @SQL_Dimentions + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_Dimentions;

--#######################################################################################################################
--###| Step 4 - Preparing table with all possible connections between Stable columns excluding NULLs
--#######################################################################################################################
DECLARE @StabPos_TAB TABLE ([StabPos_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @StabPos_TAB 
SELECT [StabPos_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName] FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @StabPos_ID smallint;
SELECT      @StabPos_ID = 1;


DECLARE @SQL_MainStableColumnTable nvarchar(max);

IF OBJECT_ID('tempdb.dbo.##ALL_StableColumns', 'U') IS NOT NULL DROP TABLE ##ALL_StableColumns; 

SELECT @SQL_MainStableColumnTable       = 'SELECT xxx_ID_xxx = ROW_NUMBER() OVER (ORDER BY ' + @ListOfColumns_Stable + '), ' + @ListOfColumns_Stable
                                            + ' INTO ##ALL_StableColumns '
                                            + ' FROM (SELECT DISTINCT' + @ListOfColumns_Stable + ' FROM  ' + @TableName
                                            + ' WHERE ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) + ' IS NOT NULL ';
                                            SELECT @StabPos_ID = @StabPos_ID + 1;
            WHILE @StabPos_ID <= (SELECT MAX([StabPos_ID]) FROM @StabPos_TAB)
            BEGIN
            SELECT @SQL_MainStableColumnTable = @SQL_MainStableColumnTable + 'AND ' + (SELECT [ColumnName] FROM @StabPos_TAB WHERE [StabPos_ID] = @StabPos_ID) +  ' IS NOT NULL ';
            SELECT @StabPos_ID = @StabPos_ID + 1;
            END

SELECT @SQL_MainStableColumnTable    = @SQL_MainStableColumnTable + ' )x';

EXECUTE SP_EXECUTESQL  @SQL_MainStableColumnTable;

--#######################################################################################################################
--###| Step 5 - Preparing table with all options ID
--#######################################################################################################################

DECLARE @FULL_SQL_1 NVARCHAR(MAX)
SELECT @FULL_SQL_1 = ''

DECLARE @i smallint

IF OBJECT_ID('tempdb.dbo.##FinalTab', 'U') IS NOT NULL DROP TABLE ##FinalTab; 

SELECT @FULL_SQL_1 = 'SELECT t.*, dim.[xxx_ID_xxx] '
                                    + ' INTO ##FinalTab '
                                    +   'FROM ' + @TableName + ' t '
                                    +   'JOIN ##ALL_Dimentions dim '
                                    +   'ON t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = 1);
                                SELECT @i = 2                               
                                WHILE @i <= (SELECT MAX([DIM_ID]) FROM @DIM_TAB)
                                    BEGIN
                                    SELECT @FULL_SQL_1 = @FULL_SQL_1 + ' AND t.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i) + ' = dim.' + (SELECT [ColumnName] FROM @DIM_TAB WHERE [DIM_ID] = @i)
                                    SELECT @i = @i +1
                                END
EXECUTE SP_EXECUTESQL @FULL_SQL_1

--#######################################################################################################################
--###| Step 6 - Selecting final data
--#######################################################################################################################
DECLARE @STAB_TAB TABLE ([STAB_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @STAB_TAB 
SELECT [STAB_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'S';

DECLARE @VAR_TAB TABLE ([VAR_ID] smallint, [ColumnName] nvarchar(128))
INSERT INTO @VAR_TAB 
SELECT [VAR_ID] = ROW_NUMBER() OVER(ORDER BY [ColumnName]), [ColumnName]
FROM #ColumnListWithActions WHERE [Action] = 'V';

DECLARE @y smallint;
DECLARE @x smallint;
DECLARE @z smallint;


DECLARE @FinalCode nvarchar(max)

SELECT @FinalCode = ' SELECT ID1.*'
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                            BEGIN
                                                SELECT @z = 1
                                                WHILE @z <= (SELECT MAX([VAR_ID]) FROM @VAR_TAB)
                                                    BEGIN
                                                        SELECT @FinalCode = @FinalCode +    ', [ID' + CAST((@y) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z) + '] =  ID' + CAST((@y + 1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @VAR_TAB WHERE [VAR_ID] = @z)
                                                        SELECT @z = @z + 1
                                                    END
                                                    SELECT @y = @y + 1
                                                END
        SELECT @FinalCode = @FinalCode + 
                                        ' FROM ( SELECT * FROM ##ALL_StableColumns)ID1';
                                        SELECT @y = 1
                                        WHILE @y <= (SELECT MAX([xxx_ID_xxx]) FROM ##FinalTab)
                                        BEGIN
                                            SELECT @x = 1
                                            SELECT @FinalCode = @FinalCode 
                                                                                + ' LEFT JOIN (SELECT ' +  @ListOfColumns_Stable + ' , ' + @ListOfColumns_Variable 
                                                                                + ' FROM ##FinalTab WHERE [xxx_ID_xxx] = ' 
                                                                                + CAST(@y as varchar(10)) + ' )ID' + CAST((@y + 1) as varchar(10))  
                                                                                + ' ON 1 = 1' 
                                                                                WHILE @x <= (SELECT MAX([STAB_ID]) FROM @STAB_TAB)
                                                                                BEGIN
                                                                                    SELECT @FinalCode = @FinalCode + ' AND ID1.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x) + ' = ID' + CAST((@y+1) as varchar(10)) + '.' + (SELECT [ColumnName] FROM @STAB_TAB WHERE [STAB_ID] = @x)
                                                                                    SELECT @x = @x +1
                                                                                END
                                            SELECT @y = @y + 1
                                        END

SELECT * FROM ##ALL_Dimentions;
EXECUTE SP_EXECUTESQL @FinalCode;

From executing the first query (by passing source DB and table name) you will get a pre-created execution query for the second SP, all you have to do is define is the column from your source: + Stable + Value (will be used to concentrate values based on that) + Dim (column you want to use to pivot by)

Names and datatypes will be defined automatically!

I cant recommend it for any production environments but does the job for adhoc BI requests.

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

How to query as GROUP BY in django?

The following module allows you to group Django models and still work with a QuerySet in the result: https://github.com/kako-nawao/django-group-by

For example:

from django_group_by import GroupByMixin

class BookQuerySet(QuerySet, GroupByMixin):
    pass

class Book(Model):
    title = TextField(...)
    author = ForeignKey(User, ...)
    shop = ForeignKey(Shop, ...)
    price = DecimalField(...)

class GroupedBookListView(PaginationMixin, ListView):
    template_name = 'book/books.html'
    model = Book
    paginate_by = 100

    def get_queryset(self):
        return Book.objects.group_by('title', 'author').annotate(
            shop_count=Count('shop'), price_avg=Avg('price')).order_by(
            'name', 'author').distinct()

    def get_context_data(self, **kwargs):
        return super().get_context_data(total_count=self.get_queryset().count(), **kwargs)

'book/books.html'

<ul>
{% for book in object_list %}
    <li>
        <h2>{{ book.title }}</td>
        <p>{{ book.author.last_name }}, {{ book.author.first_name }}</p>
        <p>{{ book.shop_count }}</p>
        <p>{{ book.price_avg }}</p>
    </li>
{% endfor %}
</ul>

The difference to the annotate/aggregate basic Django queries is the use of the attributes of a related field, e.g. book.author.last_name.

If you need the PKs of the instances that have been grouped together, add the following annotation:

.annotate(pks=ArrayAgg('id'))

NOTE: ArrayAgg is a Postgres specific function, available from Django 1.9 onwards: https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg

Converting cv::Mat to IplImage*

One problem might be: when using external ipl and defining HAVE_IPL in your project, the ctor

_IplImage::_IplImage(const cv::Mat& m)
{
    CV_Assert( m.dims <= 2 );
    cvInitImageHeader(this, m.size(), cvIplDepth(m.flags), m.channels());
    cvSetData(this, m.data, (int)m.step[0]);
}

found in ../OpenCV/modules/core/src/matrix.cpp is not used/instanciated and conversion fails.

You may reimplement it in a way similar to :

IplImage& FromMat(IplImage& img, const cv::Mat& m)
{
    CV_Assert(m.dims <= 2);
    cvInitImageHeader(&img, m.size(), cvIplDepth(m.flags), m.channels());
    cvSetData(&img, m.data, (int)m.step[0]);
    return img;
}

IplImage img;
FromMat(img,myMat);

CSS center display inline block?

You don't need to use "display: table". The reason your margin: 0 auto centering attempt doesn't work is because you didn't specify a width.

This will work just fine:

.wrap {
    background: #aaa;
    margin: 0 auto;
    width: some width in pixels since it's the container;
}

You don't need to specify display: block since that div will be block by default. You can also probably lose the overflow: hidden.

How to access global js variable in AngularJS directive

I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).

The easiest solution that I have found is to do the following:

In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.

Example:

'use strict';

//my data variable that I need access to.
var data = null;

angular.module('sample', [])

Then in your controller:

.controller('SampleApp', function ($scope, $location) {

$scope.availableList = [];

$scope.init = function () {
    $scope.availableList = data;
}

Finally, you have to init everything (order matters):

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="/path/to/your/angular/js/sample.js"></script>
  <script type="text/javascript">
      data = <?= json_encode($cproducts); ?>
  </script>

Finally initialize your controller and init function.

  <div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">

By doing this you will now have access to whatever data you stuffed into the global variable.

ignoring any 'bin' directory on a git project

I think it is worth to mention for git beginners:

If you already have a file checked in, and you want to ignore it, Git will not ignore the file if you add a rule later. In those cases, you must untrack the file first, by running the following command in your terminal:

git rm --cached

So if you want add to ignore some directories in your local repository (which already exist) after editing .gitignore you want to run this on your root dir

git rm --cached -r .
git add .

It will basically 'refresh' your local repo and unstage ignored files.

See:

http://git-scm.com/docs/git-rm,

https://help.github.com/articles/ignoring-files/

How to disable CSS in Browser for testing purposes

Another way to achieve @David Baucum's solution in fewer steps:

  1. Right click -> inspect element
  2. Click on the stylesheet's name that affect your element (just on the right side of the declaration)
  3. Highlight all of the text and hit delete.

It could be handier in some cases.

What is an example of the Liskov Substitution Principle?

Let’s illustrate in Java:

class TrasportationDevice
{
   String name;
   String getName() { ... }
   void setName(String n) { ... }

   double speed;
   double getSpeed() { ... }
   void setSpeed(double d) { ... }

   Engine engine;
   Engine getEngine() { ... }
   void setEngine(Engine e) { ... }

   void startEngine() { ... }
}

class Car extends TransportationDevice
{
   @Override
   void startEngine() { ... }
}

There is no problem here, right? A car is definitely a transportation device, and here we can see that it overrides the startEngine() method of its superclass.

Let’s add another transportation device:

class Bicycle extends TransportationDevice
{
   @Override
   void startEngine() /*problem!*/
}

Everything isn’t going as planned now! Yes, a bicycle is a transportation device, however, it does not have an engine and hence, the method startEngine() cannot be implemented.

These are the kinds of problems that violation of Liskov Substitution Principle leads to, and they can most usually be recognized by a method that does nothing, or even can’t be implemented.

The solution to these problems is a correct inheritance hierarchy, and in our case we would solve the problem by differentiating classes of transportation devices with and without engines. Even though a bicycle is a transportation device, it doesn’t have an engine. In this example our definition of transportation device is wrong. It should not have an engine.

We can refactor our TransportationDevice class as follows:

class TrasportationDevice
{
   String name;
   String getName() { ... }
   void setName(String n) { ... }

   double speed;
   double getSpeed() { ... }
   void setSpeed(double d) { ... }
}

Now we can extend TransportationDevice for non-motorized devices.

class DevicesWithoutEngines extends TransportationDevice
{  
   void startMoving() { ... }
}

And extend TransportationDevice for motorized devices. Here is is more appropriate to add the Engine object.

class DevicesWithEngines extends TransportationDevice
{  
   Engine engine;
   Engine getEngine() { ... }
   void setEngine(Engine e) { ... }

   void startEngine() { ... }
}

Thus our Car class becomes more specialized, while adhering to the Liskov Substitution Principle.

class Car extends DevicesWithEngines
{
   @Override
   void startEngine() { ... }
}

And our Bicycle class is also in compliance with the Liskov Substitution Principle.

class Bicycle extends DevicesWithoutEngines
{
   @Override
   void startMoving() { ... }
}

CSV API for Java

You can use csvreader api & download from following location:

http://sourceforge.net/projects/javacsv/files/JavaCsv/JavaCsv%202.1/javacsv2.1.zip/download

or

http://sourceforge.net/projects/javacsv/

Use the following code:

/ ************ For Reading ***************/

import java.io.FileNotFoundException;
import java.io.IOException;

import com.csvreader.CsvReader;

public class CsvReaderExample {

    public static void main(String[] args) {
        try {

            CsvReader products = new CsvReader("products.csv");

            products.readHeaders();

            while (products.readRecord())
            {
                String productID = products.get("ProductID");
                String productName = products.get("ProductName");
                String supplierID = products.get("SupplierID");
                String categoryID = products.get("CategoryID");
                String quantityPerUnit = products.get("QuantityPerUnit");
                String unitPrice = products.get("UnitPrice");
                String unitsInStock = products.get("UnitsInStock");
                String unitsOnOrder = products.get("UnitsOnOrder");
                String reorderLevel = products.get("ReorderLevel");
                String discontinued = products.get("Discontinued");

                // perform program logic here
                System.out.println(productID + ":" + productName);
            }

            products.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

Write / Append to CSV file

Code:

/************* For Writing ***************************/

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import com.csvreader.CsvWriter;

public class CsvWriterAppendExample {

    public static void main(String[] args) {

        String outputFile = "users.csv";

        // before we open the file check to see if it already exists
        boolean alreadyExists = new File(outputFile).exists();

        try {
            // use FileWriter constructor that specifies open for appending
            CsvWriter csvOutput = new CsvWriter(new FileWriter(outputFile, true), ',');

            // if the file didn't already exist then we need to write out the header line
            if (!alreadyExists)
            {
                csvOutput.write("id");
                csvOutput.write("name");
                csvOutput.endRecord();
            }
            // else assume that the file already has the correct header line

            // write out a few records
            csvOutput.write("1");
            csvOutput.write("Bruce");
            csvOutput.endRecord();

            csvOutput.write("2");
            csvOutput.write("John");
            csvOutput.endRecord();

            csvOutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

How can I disable a specific LI element inside a UL?

I usualy use <li> to include <a> link. I disabled click action writing like this; You may not include <a> link, then you will ignore my post.

_x000D_
_x000D_
a.noclick       {_x000D_
  pointer-events: none;_x000D_
}
_x000D_
<a class="noclick" href="#">this is disabled</a>
_x000D_
_x000D_
_x000D_

Java ByteBuffer to String

the root of this question is how to decode bytes to string?

this can be done with the JAVA NIO CharSet:

public final CharBuffer decode(ByteBuffer bb)

FileChannel channel = FileChannel.open(
  Paths.get("files/text-latin1.txt", StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);

CharSet latin1 = StandardCharsets.ISO_8859_1;
CharBuffer latin1Buffer = latin1.decode(buffer);

String result = new String(latin1Buffer.array());
  • First we create a channel and read it in a buffer
  • Then decode method decodes a Latin1 buffer to a char buffer
  • We can then put the result, for instance, in a String

Angular - "has no exported member 'Observable'"

What helped me is:

  1. Get rid of all old import paths and replace them with new ones like this:

    import { Observable , BehaviorSubject } from 'rxjs';)

  2. Delete node_modules folder

  3. npm cache verify
  4. npm install

Array Index Out of Bounds Exception (Java)

import java.io.*;
import java.util.Scanner;
class ar1 {
    public static void main(String[] args) {
        //Scanner sc=new Scanner(System.in);
        int[] a={10,20,30,40,12,32};
        int bi=0,sm=0;
        //bi=sc.nextInt();
        //sm=sc.nextInt();
        for(int i=0;i<=a.length-1;i++) {
            if(a[i]>a[i+1]) 
                bi=a[i];

            if(a[i]<a[i+1])
                sm=a[i];
        }
        System.out.println("big"+bi+"small"+sm);
    }
}

Get Maven artifact version at runtime

I know it's a very late answer but I'd like to share what I did as per this link:

I added the below code to the pom.xml:

        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>build-info</id>
                    <goals>
                        <goal>build-info</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

And this Advice Controller in order to get the version as model attribute:

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

@ControllerAdvice
public class CommonControllerAdvice
{
       @Autowired
       BuildProperties buildProperties;
    
       @ModelAttribute("version")
       public String getVersion() throws IOException
       {
          String version = buildProperties.getVersion();
          return version;
       }
    }

C++ Double Address Operator? (&&)

This is C++11 code. In C++11, the && token can be used to mean an "rvalue reference".

How to convert nanoseconds to seconds using the TimeUnit enum?

TimeUnit is an enum, so you can't create a new one.

The following will convert 1000000000000ns to seconds.

TimeUnit.NANOSECONDS.toSeconds(1000000000000L);

How to remove files from git staging area?

You can unstage files from the index using

git reset HEAD -- path/to/file

Just like git add, you can unstage files recursively by directory and so forth, so to unstage everything at once, run this from the root directory of your repository:

git reset HEAD -- .

Also, for future reference, the output of git status will tell you the commands you need to run to move files from one state to another.

How to convert milliseconds into a readable date?

You can do it with just a few lines of pure js codes.

var date = new Date(1324339200000);
    var dateToStr = date.toUTCString().split(' ');
    var cleanDate = dateToStr[2] + ' ' + dateToStr[1] ;
console.log(cleanDate);

returns Dec 20. Hope it helps.

Python regex findall

Use this pattern,

pattern = '\[P\].+?\[\/P\]'

Check here

How Do I Upload Eclipse Projects to GitHub?

Jokab's answer helped me a lot but in my case I could not push to github until I logged in my github account to my git bash so i ran the following commands

git config credential.helper store

then

git push http://github.com/[user name]/[repo name].git

After the second command a GUI window appeared, I provided my login credentials and it worked for me.

Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

The accounts property is defined like this:

"accounts":{"github":"sergiotapia"}

Your POCO states this:

public List<Account> Accounts { get; set; }

Try using this Json:

"accounts":[{"github":"sergiotapia"}]

An array of items (which is going to be mapped to the list) is always enclosed in square brackets.

Edit: The Account Poco will be something like this:

class Account {
    public string github { get; set; }
}

and maybe other properties.

Edit 2: To not have an array use the property as follows:

public Account Accounts { get; set; }

with something like the sample class I've posted in the first edit.

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

If you want to upload the file /Applications/XAMPP/htdocs/keypairfile.pem to ec2-user@publicdns:/var/www/html, you can simply do:

scp -Cr /Applications/XAMPP/htdocs/keypairfile.pem/uploads/ ec2-user@publicdns:/var/www/html/

Where:

  • -C - Compress data
  • -r - Recursive

When do you use the "this" keyword?

I tend to use it everywhere as well, just to make sure that it is clear that it is instance members that we are dealing with.

String.contains in Java

Similarly:

"".contains("");     // Returns true.

Therefore, it appears that an empty string is contained in any String.

Convert Go map to json

Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal would work as expected.

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler 
type Num int

func (n *Num) UnmarshalText(text []byte) error {
    i, err := strconv.Atoi(string(text))
    if err != nil {
        return err
    }
    *n = Num(i)
    return nil
}

func (n Num) MarshalText() (text []byte, err error) {
    return []byte(strconv.Itoa(int(n))), nil
}

type Foo struct {
    Number Num    `json:"number"`
    Title  string `json:"title"`
}

func main() {
    datas := make(map[Num]Foo)

    for i := 0; i < 10; i++ {
        datas[Num(i)] = Foo{Number: 1, Title: "test"}
    }

    jsonString, err := json.Marshal(datas)
    if err != nil {
        panic(err)
    }

    fmt.Println(datas)
    fmt.Println(jsonString)

    m := make(map[Num]Foo)
    err = json.Unmarshal(jsonString, &m)
    if err != nil {
        panic(err)
    }

    fmt.Println(m)
}

Output:

map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]

How do I verify/check/test/validate my SSH passphrase?

You can verify your SSH key passphrase by attempting to load it into your SSH agent. With OpenSSH this is done via ssh-add.

Once you're done, remember to unload your SSH passphrase from the terminal by running ssh-add -d.

What does character set and collation mean exactly?

From MySQL docs:

A character set is a set of symbols and encodings. A collation is a set of rules for comparing characters in a character set. Let's make the distinction clear with an example of an imaginary character set.

Suppose that we have an alphabet with four letters: 'A', 'B', 'a', 'b'. We give each letter a number: 'A' = 0, 'B' = 1, 'a' = 2, 'b' = 3. The letter 'A' is a symbol, the number 0 is the encoding for 'A', and the combination of all four letters and their encodings is a character set.

Now, suppose that we want to compare two string values, 'A' and 'B'. The simplest way to do this is to look at the encodings: 0 for 'A' and 1 for 'B'. Because 0 is less than 1, we say 'A' is less than 'B'. Now, what we've just done is apply a collation to our character set. The collation is a set of rules (only one rule in this case): "compare the encodings." We call this simplest of all possible collations a binary collation.

But what if we want to say that the lowercase and uppercase letters are equivalent? Then we would have at least two rules: (1) treat the lowercase letters 'a' and 'b' as equivalent to 'A' and 'B'; (2) then compare the encodings. We call this a case-insensitive collation. It's a little more complex than a binary collation.

In real life, most character sets have many characters: not just 'A' and 'B' but whole alphabets, sometimes multiple alphabets or eastern writing systems with thousands of characters, along with many special symbols and punctuation marks. Also in real life, most collations have many rules: not just case insensitivity but also accent insensitivity (an "accent" is a mark attached to a character as in German 'ö') and multiple-character mappings (such as the rule that 'ö' = 'OE' in one of the two German collations).

How do I set default values for functions parameters in Matlab?

Yes, it might be really nice to have the capability to do as you have written. But it is not possible in MATLAB. Many of my utilities that allow defaults for the arguments tend to be written with explicit checks in the beginning like this:

if (nargin<3) or isempty(myParameterName)
  MyParameterName = defaultValue;
elseif (.... tests for non-validity of the value actually provided ...)
  error('The sky is falling!')
end

Ok, so I would generally apply a better, more descriptive error message. See that the check for an empty variable allows the user to pass in an empty pair of brackets, [], as a placeholder for a variable that will take on its default value. The author must still supply the code to replace that empty argument with its default value though.

My utilities that are more sophisticated, with MANY parameters, all of which have default arguments, will often use a property/value pair interface for default arguments. This basic paradigm is seen in the handle graphics tools in matlab, as well as in optimset, odeset, etc.

As a means to work with these property/value pairs, you will need to learn about varargin, as a way of inputing a fully variable number of arguments to a function. I wrote (and posted) a utility to work with such property/value pairs, parse_pv_pairs.m. It helps you to convert property/value pairs into a matlab structure. It also enables you to supply default values for each parameter. Converting an unwieldy list of parameters into a structure is a VERY nice way to pass them around in MATLAB.

Have Excel formulas that return 0, make the result blank

I noticed this issue recently and it is frustrating that excel changes a blank string into a 0. I do not think that a formula should solve this issue because adding more logic to a complex formula may be cumbersome and might even end up breaking the original formula. I have two non formula options below.

If you want to keep the formulas in the cells and have them return 0 instead of "" use the following Click Path:

  1. File
  2. Options
  3. Advanced

Scroll to "Display options for this worksheet:"

  1. Deselect "Show a zero in cells that have zero value"

I also want to give a simple manual solution if you want to change a value (as opposed to a formula) from 0 to a blank string. This solution is better than Find and Replace because it will not replace a number like 101 with 11.

  1. Select all of your data
  2. On the data tab, click the filter logo

The Filter Logo itself

  1. Click on the pick list of the column with the undesired 0(s) to select only rows with the value "0" (Make sure to only clear the contents of cells containing contents with the exact value 0!)

enter image description here

  1. Select the data (which is only 0s), right click and select clear contents

The other data will remain if you used the filter properly and the back button is always there if something goes wrong. I understand option 2 is very manual and "unelegant" but it does successfully convert a 0 into a blank string and it may relieve a frustrated individual who does not want to use an if statement.

I personally learned something exploring this (very dry) excel issue today and I am personally using these methods moving forward. A quick macro of option 2 could be a good option if this is a frequent task for an intermediate excel user.

Are there dictionaries in php?

http://php.net/manual/en/language.types.array.php

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Standard arrays can be used that way.

jQuery UI Dialog - missing close icon

I got stuck with the same problem and after read and try all the suggestions above I just tried to replace manually this image (which you can find it here) in the CSS after downloaded it and saved in the images folder on my app and voilá, problem solved!

here is the CSS:

.ui-state-default .ui-icon {
        background-image: url("../img/ui-icons_888888_256x240.png");
}

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Get local href value from anchor (a) tag

This code works for me to get all links of the document

var links=document.getElementsByTagName('a'), hrefs = [];
for (var i = 0; i<links.length; i++)
{   
    hrefs.push(links[i].href);
}

What is the right way to POST multipart/form-data using curl?

This is what worked for me

curl --form file='@filename' URL

It seems when I gave this answer (4+ years ago), I didn't really understand the question, or how form fields worked. I was just answering based on what I had tried in a difference scenario, and it worked for me.

So firstly, the only mistake the OP made was in not using the @ symbol before the file name. Secondly, my answer which uses file=... only worked for me because the form field I was trying to do the upload for was called file. If your form field is called something else, use that name instead.

Explanation

From the curl manpages; under the description for the option --form it says:

This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.

Chances are that if you are trying to do a form upload, you will most likely want to use the @ prefix to upload the file rather than < which uploads the contents of the file.

Addendum

Now I must also add that one must be careful with using the < symbol because in most unix shells, < is the input redirection symbol [which coincidentally will also supply the contents of the given file to the command standard input of the program before <]. This means that if you do not properly escape that symbol or wrap it in quotes, you may find that your curl command does not behave the way you expect.

On that same note, I will also recommend quoting the @ symbol.


You may also be interested in this other question titled: application/x-www-form-urlencoded or multipart/form-data?

I say this because curl offers other ways of uploading a file, but they differ in the content-type set in the header. For example the --data option offers a similar mechanism for uploading files as data, but uses a different content-type for the upload.

Anyways that's all I wanted to say about this answer since it started to get more upvotes. I hope this helps erase any confusions such as the difference between this answer and the accepted answer. There is really none, except for this explanation.

string sanitizer for filename

The best I know today is static method Strings::webalize from Nette framework.

BTW, this translates all diacritic signs to their basic.. š=>s ü=>u ß=>ss etc.

For filenames you have to add dot "." to allowed characters parameter.

/**
 * Converts to ASCII.
 * @param  string  UTF-8 encoding
 * @return string  ASCII
 */
public static function toAscii($s)
{
    static $transliterator = NULL;
    if ($transliterator === NULL && class_exists('Transliterator', FALSE)) {
        $transliterator = \Transliterator::create('Any-Latin; Latin-ASCII');
    }

    $s = preg_replace('#[^\x09\x0A\x0D\x20-\x7E\xA0-\x{2FF}\x{370}-\x{10FFFF}]#u', '', $s);
    $s = strtr($s, '`\'"^~?', "\x01\x02\x03\x04\x05\x06");
    $s = str_replace(
        array("\xE2\x80\x9E", "\xE2\x80\x9C", "\xE2\x80\x9D", "\xE2\x80\x9A", "\xE2\x80\x98", "\xE2\x80\x99", "\xC2\xB0"),
        array("\x03", "\x03", "\x03", "\x02", "\x02", "\x02", "\x04"), $s
    );
    if ($transliterator !== NULL) {
        $s = $transliterator->transliterate($s);
    }
    if (ICONV_IMPL === 'glibc') {
        $s = str_replace(
            array("\xC2\xBB", "\xC2\xAB", "\xE2\x80\xA6", "\xE2\x84\xA2", "\xC2\xA9", "\xC2\xAE"),
            array('>>', '<<', '...', 'TM', '(c)', '(R)'), $s
        );
        $s = @iconv('UTF-8', 'WINDOWS-1250//TRANSLIT//IGNORE', $s); // intentionally @
        $s = strtr($s, "\xa5\xa3\xbc\x8c\xa7\x8a\xaa\x8d\x8f\x8e\xaf\xb9\xb3\xbe\x9c\x9a\xba\x9d\x9f\x9e"
            . "\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3"
            . "\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8"
            . "\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf8\xf9\xfa\xfb\xfc\xfd\xfe"
            . "\x96\xa0\x8b\x97\x9b\xa6\xad\xb7",
            'ALLSSSSTZZZallssstzzzRAAAALCCCEEEEIIDDNNOOOOxRUUUUYTsraaaalccceeeeiiddnnooooruuuuyt- <->|-.');
        $s = preg_replace('#[^\x00-\x7F]++#', '', $s);
    } else {
        $s = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $s); // intentionally @
    }
    $s = str_replace(array('`', "'", '"', '^', '~', '?'), '', $s);
    return strtr($s, "\x01\x02\x03\x04\x05\x06", '`\'"^~?');
}


/**
 * Converts to web safe characters [a-z0-9-] text.
 * @param  string  UTF-8 encoding
 * @param  string  allowed characters
 * @param  bool
 * @return string
 */
public static function webalize($s, $charlist = NULL, $lower = TRUE)
{
    $s = self::toAscii($s);
    if ($lower) {
        $s = strtolower($s);
    }
    $s = preg_replace('#[^a-z0-9' . preg_quote($charlist, '#') . ']+#i', '-', $s);
    $s = trim($s, '-');
    return $s;
}

Margin while printing html page

I also recommend pt versus cm or mm as it's more precise. Also, I cannot get @page to work in Chrome (version 30.0.1599.69 m) It ignores anything I put for the margins, large or small. But, you can get it to work with body margins on the document, weird.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

My point is that I just want the raw DATETIME string, so I can parse it myself as is.

That makes me think that your "workaround" is not a workaround, but in fact the only way to get the value from the database into your code:

SELECT CAST(add_date AS CHAR) as add_date

By the way, some more notes from the MySQL documentation:

MySQL Constraints on Invalid Data:

Before MySQL 5.0.2, MySQL is forgiving of illegal or improper data values and coerces them to legal values for data entry. In MySQL 5.0.2 and up, that remains the default behavior, but you can change the server SQL mode to select more traditional treatment of bad values such that the server rejects them and aborts the statement in which they occur.

[..]

If you try to store NULL into a column that doesn't take NULL values, an error occurs for single-row INSERT statements. For multiple-row INSERT statements or for INSERT INTO ... SELECT statements, MySQL Server stores the implicit default value for the column data type.

MySQL 5.x Date and Time Types:

MySQL also allows you to store '0000-00-00' as a “dummy date” (if you are not using the NO_ZERO_DATE SQL mode). This is in some cases more convenient (and uses less data and index space) than using NULL values.

[..]

By default, when MySQL encounters a value for a date or time type that is out of range or otherwise illegal for the type (as described at the beginning of this section), it converts the value to the “zero” value for that type.

Extracting specific columns from a data frame

Using the dplyr package, if your data.frame is called df1:

library(dplyr)

df1 %>%
  select(A, B, E)

This can also be written without the %>% pipe as:

select(df1, A, B, E)

"NoClassDefFoundError: Could not initialize class" error

Realised that I was using OpenJDK when I saw this error. Fixed it once I installed the Oracle JDK instead.

Is there a way for non-root processes to bind to "privileged" ports on Linux?

At startup:

iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

Then you can bind to the port you forward to.

How can I check if a string is a number?

Try This

here i perform addition of no and concatenation of string

 private void button1_Click(object sender, EventArgs e)
        {
            bool chk,chk1;
            int chkq;
            chk = int.TryParse(textBox1.Text, out chkq);
            chk1 = int.TryParse(textBox2.Text, out chkq);
            if (chk1 && chk)
            {
                double a = Convert.ToDouble(textBox1.Text);
                double b = Convert.ToDouble(textBox2.Text);
                double c = a + b;
                textBox3.Text = Convert.ToString(c);
            }
            else
            {
                string f, d,s;
                f = textBox1.Text;
                d = textBox2.Text;
                s = f + d;
                textBox3.Text = s;
            }
        }

How to center content in a bootstrap column?

col-lg-4 col-md-6 col-sm-8 col-11 mx-auto

 1. col-lg-4 = 1200px (popular 1366, 1600, 1920+)
 2. col-md-6 = 970px (popular 1024, 1200)
 3. col-sm-8 = 768px (popular 800, 768)
 4. col-11 set default smaller devices for gutter (popular 600,480,414,375,360,312)
 5. mx-auto = always block center


Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

Show animated GIF

Try this:

// I suppose you have already set your JFrame 
Icon imgIcon = new ImageIcon(this.getClass().getResource("ajax-loader.gif"));
JLabel label = new JLabel(imgIcon);
label.setBounds(668, 43, 46, 14); // for example, you can use your own values
frame.getContentPane().add(label);

Found on this tutorial on how to display animated gif in java

Or live on youtube : https://youtu.be/_NEnhm9mgdE

How to replace existing value of ArrayList element in Java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

Converting between datetime, Timestamp and datetime64

I've come back to this answer more times than I can count, so I decided to throw together a quick little class, which converts a Numpy datetime64 value to Python datetime value. I hope it helps others out there.

from datetime import datetime
import pandas as pd

class NumpyConverter(object):
    @classmethod
    def to_datetime(cls, dt64, tzinfo=None):
        """
        Converts a Numpy datetime64 to a Python datetime.
        :param dt64: A Numpy datetime64 variable
        :type dt64: numpy.datetime64
        :param tzinfo: The timezone the date / time value is in
        :type tzinfo: pytz.timezone
        :return: A Python datetime variable
        :rtype: datetime
        """
        ts = pd.to_datetime(dt64)
        if tzinfo is not None:
            return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, tzinfo=tzinfo)
        return datetime(ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second)

I'm gonna keep this in my tool bag, something tells me I'll need it again.

Reactive forms - disabled attribute

I tried these in angular 7. It worked successfully.

this.form.controls['fromField'].reset();
if(condition){
      this.form.controls['fromField'].enable();
}
else{
      this.form.controls['fromField'].disable();
}

JQuery - Set Attribute value

You can add different classes to select, or select by type like this:

$('input[type="checkbox"]').removeAttr("disabled");

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

According to the Git repo of the BFG tool, it "removes large or troublesome blobs as git-filter-branch does, but faster - and is written in Scala".

https://github.com/rtyley/bfg-repo-cleaner

pandas: merge (join) two data frames on multiple columns

Another way of doing this: new_df = A_df.merge(B_df, left_on=['A_c1','c2'], right_on = ['B_c1','c2'], how='left')

ESLint Parsing error: Unexpected token

"parser": "babel-eslint" helped me to fix the issue

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 6,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true,
            "modules": true,
            "experimentalObjectRestSpread": true
        }
    },
    "plugins": [
        "react"
    ],
    "extends": ["eslint:recommended", "plugin:react/recommended"],
    "rules": {
        "comma-dangle": 0,
        "react/jsx-uses-vars": 1,
        "react/display-name": 1,
        "no-unused-vars": "warn",
        "no-console": 1,
        "no-unexpected-multiline": "warn"
    },
    "settings": {
        "react": {
            "pragma": "React",
            "version": "15.6.1"
        }
    }
}

Reference

Set the default value in dropdownlist using jQuery

$('#userZipFiles option').prop('selected', function() {
        return this.defaultSelected;
    });     

How do I fit an image (img) inside a div and keep the aspect ratio?

For me, the following CSS worked (tested in Chrome, Firefox and Safari).

There are multiple things working together:

  • max-height: 100%;, max-width: 100%; and height: auto;, width: auto; make the img scale to whichever dimension first reaches 100% while keeping the aspect ratio
  • position: relative; in the container and position: absolute; in the child together with top: 50%; and left: 50%; center the top left corner of the img in the container
  • transform: translate(-50%, -50%); moves the img back to the left and top by half its size, thus centering the img in the container

CSS:

.container {
    height: 48px;
    width: 48px;

    position: relative;
}

.container > img {
    max-height: 100%;
    max-width: 100%;
    height: auto;
    width: auto;

    position: absolute;
    top: 50%;
    left: 50%;

    transform: translate(-50%, -50%);
}

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

How to find the extension of a file in C#?

In addition, if you have a FileInfo fi, you can simply do:

string ext = fi.Extension;

and it'll hold the extension of the file (note: it will include the ., so a result of the above could be: .jpg .txt, and so on....

TempData keep() vs peek()

Just finished understanding Peek and Keep and had same confusion initially. The confusion arises becauses TempData behaves differently under different condition. You can watch this video which explains the Keep and Peek with demonstration https://www.facebook.com/video.php?v=689393794478113

Tempdata helps to preserve values for a single request and CAN ALSO preserve values for the next request depending on 4 conditions”.

If we understand these 4 points you would see more clarity.Below is a diagram with all 4 conditions, read the third and fourth point which talks about Peek and Keep.

enter image description here

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2 ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

string str = TempData["MyData"];

Even if you are displaying it’s a normal read like the code below.

@TempData["MyData"];

Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.

@TempData["MyData"];
TempData.Keep("MyData");

Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

string str = TempData.Peek("Td").ToString();

Reference :- http://www.codeproject.com/Articles/818493/MVC-Tempdata-Peek-and-Keep-confusion

Prevent wrapping of span or div

Particularly when using something like Twitter's Bootstrap, white-space: nowrap; doesn't always work in CSS when applying padding or margin to a child div. Instead however, adding an equivalent border: 20px solid transparent; style in place of padding/margin works more consistently.

"rm -rf" equivalent for Windows?

Try this command:

del /s foldername

Get Absolute URL from Relative path (refactored method)

This works fine too:

HttpContext.Current.Server.MapPath(relativePath)

Where relative path is something like "~/foo/file.jpg"

What does 'wb' mean in this code, using Python?

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

How to pull remote branch from somebody else's repo

git remote add coworker git://path/to/coworkers/repo.git
git fetch coworker
git checkout --track coworker/foo

This will setup a local branch foo, tracking the remote branch coworker/foo. So when your co-worker has made some changes, you can easily pull them:

git checkout foo
git pull

Response to comments:

Cool :) And if I'd like to make my own changes to that branch, should I create a second local branch "bar" from "foo" and work there instead of directly on my "foo"?

You don't need to create a new branch, even though I recommend it. You might as well commit directly to foo and have your co-worker pull your branch. But that branch already exists and your branch foo need to be setup as an upstream branch to it:

git branch --set-upstream foo colin/foo

assuming colin is your repository (a remote to your co-workers repository) defined in similar way:

git remote add colin git://path/to/colins/repo.git

What is the role of "Flatten" in Keras?

Here I would like to present another alternative to Flatten function. This may help to understand what is going on internally. The alternative method adds three more code lines. Instead of using

#==========================================Build a Model
model = tf.keras.models.Sequential()

model.add(keras.layers.Flatten(input_shape=(28, 28, 3)))#reshapes to (2352)=28x28x3
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
model.add(keras.layers.Dense(128,activation=tf.nn.relu))
model.add(keras.layers.Dense(2,activation=tf.nn.softmax))

model.build()
model.summary()# summary of the model

we can use

    #==========================================Build a Model
    tensor = tf.keras.backend.placeholder(dtype=tf.float32, shape=(None, 28, 28, 3))
    
    model = tf.keras.models.Sequential()
    
    model.add(keras.layers.InputLayer(input_tensor=tensor))
    model.add(keras.layers.Reshape([2352]))
model.add(layers.experimental.preprocessing.Rescaling(1./255))#normalize
    model.add(keras.layers.Dense(128,activation=tf.nn.relu))
    model.add(keras.layers.Dense(2,activation=tf.nn.softmax))
    
    model.build()
    model.summary()# summary of the model

In the second case, we first create a tensor (using a placeholder) and then create an Input layer. After, we reshape the tensor to flat form. So basically,

Create tensor->Create InputLayer->Reshape == Flatten

Flatten is a convenient function, doing all this automatically. Of course both ways has its specific use cases. Keras provides enough flexibility to manipulate the way you want to create a model.

Peak signal detection in realtime timeseries data

An iterative version in python/numpy for answer https://stackoverflow.com/a/22640362/6029703 is here. This code is faster than computing average and standard deviation every lag for large data (100000+).

def peak_detection_smoothed_zscore_v2(x, lag, threshold, influence):
    '''
    iterative smoothed z-score algorithm
    Implementation of algorithm from https://stackoverflow.com/a/22640362/6029703
    '''
    import numpy as np
    labels = np.zeros(len(x))
    filtered_y = np.array(x)
    avg_filter = np.zeros(len(x))
    std_filter = np.zeros(len(x))
    var_filter = np.zeros(len(x))

    avg_filter[lag - 1] = np.mean(x[0:lag])
    std_filter[lag - 1] = np.std(x[0:lag])
    var_filter[lag - 1] = np.var(x[0:lag])
    for i in range(lag, len(x)):
        if abs(x[i] - avg_filter[i - 1]) > threshold * std_filter[i - 1]:
            if x[i] > avg_filter[i - 1]:
                labels[i] = 1
            else:
                labels[i] = -1
            filtered_y[i] = influence * x[i] + (1 - influence) * filtered_y[i - 1]
        else:
            labels[i] = 0
            filtered_y[i] = x[i]
        # update avg, var, std
        avg_filter[i] = avg_filter[i - 1] + 1. / lag * (filtered_y[i] - filtered_y[i - lag])
        var_filter[i] = var_filter[i - 1] + 1. / lag * ((filtered_y[i] - avg_filter[i - 1]) ** 2 - (
            filtered_y[i - lag] - avg_filter[i - 1]) ** 2 - (filtered_y[i] - filtered_y[i - lag]) ** 2 / lag)
        std_filter[i] = np.sqrt(var_filter[i])

    return dict(signals=labels,
                avgFilter=avg_filter,
                stdFilter=std_filter)

How to execute a stored procedure inside a select query

As long as you're not doing any INSERT or UPDATE statements in your stored procedure, you will probably want to make it a function.

Stored procedures are for executing by an outside program, or on a timed interval.

The answers here will explain it better than I can:

Function vs. Stored Procedure in SQL Server

Add a tooltip to a div

It can be done with CSS only, no javascript at all : running demo

  1. Apply a custom HTML attribute, eg. data-tooltip="bla bla" to your object (div or whatever):

    <div data-tooltip="bla bla">
        something here
    </div>
    
  2. Define the :before pseudoelement of each [data-tooltip] object to be transparent, absolutely positioned and with data-tooltip="" value as content:

    [data-tooltip]:before {            
        position : absolute;
         content : attr(data-tooltip);
         opacity : 0;
    }
    
  3. Define :hover:before hovering state of each [data-tooltip] to make it visible:

    [data-tooltip]:hover:before {        
        opacity : 1;
    }
    
  4. Apply your styles (color, size, position etc) to the tooltip object; end of the story.

In the demo I've defined another rule to specify if the tooltip must disappear when hovering over it but outside of the parent, with another custom attribute, data-tooltip-persistent, and a simple rule:

[data-tooltip]:not([data-tooltip-persistent]):before {
    pointer-events: none;
}

Note 1: The browser coverage for this is very wide, but consider using a javascript fallback (if needed) for old IE.

Note 2: an enhancement might be adding a bit of javascript to calculate the mouse position and add it to the pseudo elements, by changing a class applied to it.

Interface type check with Typescript

I found an example from @progress/kendo-data-query in file filter-descriptor.interface.d.ts

Checker

declare const isCompositeFilterDescriptor: (source: FilterDescriptor | CompositeFilterDescriptor) => source is CompositeFilterDescriptor;

Example usage

const filters: Array<FilterDescriptor | CompositeFilterDescriptor> = filter.filters;

filters.forEach((element: FilterDescriptor | CompositeFilterDescriptor) => {
    if (isCompositeFilterDescriptor(element)) {
        // element type is CompositeFilterDescriptor
    } else {
        // element type is FilterDescriptor
    }
});

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

Calling Javascript from a html form

There are a few things to change in your edited version:

  1. You've taken the suggestion of using document.myform['whichThing'] a bit too literally. Your form is named "aye", so the code to access the whichThing radio buttons should use that name: `document.aye['whichThing'].

  2. There's no such thing as an action attribute for the <input> tag. Use onclick instead: <input name="Submit" type="submit" value="Update" onclick="handleClick();return false"/>

  3. Obtaining and cancelling an Event object in a browser is a very involved process. It varies a lot by browser type and version. IE and Firefox handle these things very differently, so a simple event.preventDefault() won't work... in fact, the event variable probably won't even be defined because this is an onclick handler from a tag. This is why Stephen above is trying so hard to suggest a framework. I realize you want to know the mechanics, and I recommend google for that. In this case, as a simple workaround, use return false in the onclick tag as in number 2 above (or return false from the function as stephen suggested).

  4. Because of #3, get rid of everything not the alert statement in your handler.

The code should now look like:

function handleClick()
      {
        alert("Favorite weird creature: "+getRadioButtonValue(document.aye['whichThing']));
      }
    </script>
  </head>
<body>
    <form name="aye">
      <input name="Submit"  type="submit" value="Update" onclick="handleClick();return false"/>
      Which of the following do you like best?
      <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
      <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
      <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
    </form>

Java replace issues with ' (apostrophe/single quote) and \ (backslash) together

First of all, if you are trying to encode apostophes for querystrings, they need to be URLEncoded, not escaped with a leading backslash. For that use URLEncoder.encode(String, String) (BTW: the second argument should always be "UTF-8"). Secondly, if you want to replace all instances of apostophe with backslash apostrophe, you must escape the backslash in your string expression with a leading backslash. Like this:

"This is' it".replace("'", "\\'");

Edit:

I see now that you are probably trying to dynamically build a SQL statement. Do not do it this way. Your code will be susceptible to SQL injection attacks. Instead use a PreparedStatement.

How can I add raw data body to an axios request?

The key is to use "Content-Type": "text/plain" as mentioned by @MadhuBhat.

axios.post(path, code, { headers: { "Content-Type": "text/plain" } }).then(response => {
    console.log(response);
});

A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":

axios.post(path, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {
    console.log(response);
});

C# Controller:

[HttpPost]
public async Task<ActionResult<string>> Post([FromBody] string code)
{
    return Ok(code);
}

https://weblog.west-wind.com/posts/2017/sep/14/accepting-raw-request-body-content-in-aspnet-core-api-controllers

You can also make a POST with query params if that helps:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

Source: https://stackoverflow.com/a/53501339/3850405

Including a css file in a blade template?

Work with this code :

{!! include ('css/app.css') !!}

How to get current time with jQuery

Using JavaScript native Date functions you can get hours, minutes and seconds as you want. If you wish to format date and time in particular way you may want to implement a method extending JavaScript Date prototype.

Here is one already implemented: https://github.com/jacwright/date.format

Photoshop text tool adds punctuation to the beginning of text

You can try : go to edit>preferencec>type.. select type > choose text engine options select east asian. Restart photoshop. Create new peroject. Try text tool again.

(if you want to use your project created with other text engine type) copy /paste all layers to new project.

How to add an Access-Control-Allow-Origin header

In your file.php of request ajax, can set value header.

<?php header('Access-Control-Allow-Origin: *'); //for all ?>

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

TypeError: Missing 1 required positional argument: 'self'

You need to instantiate a class instance here.

Use

p = Pump()
p.getPumps()

Small example -

>>> class TestClass:
        def __init__(self):
            print("in init")
        def testFunc(self):
            print("in Test Func")


>>> testInstance = TestClass()
in init
>>> testInstance.testFunc()
in Test Func

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

What data is stored in Ephemeral Storage of Amazon EC2 instance?

ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store

So Everything will be stored on ephemeral.

if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.

Python display text with font & color?

Yes. It is possible to draw text in pygame:

# initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error
myfont = pygame.font.SysFont("monospace", 15)

# render text
label = myfont.render("Some text!", 1, (255,255,0))
screen.blit(label, (100, 100))

How to force Laravel Project to use HTTPS for all routes?

Place this in the AppServiceProvider in the boot() method

if($this->app->environment('production')) {
    \URL::forceScheme('https');
}

What are some uses of template template parameters?

Actually, usecase for template template parameters is rather obvious. Once you learn that C++ stdlib has gaping hole of not defining stream output operators for standard container types, you would proceed to write something like:

template<typename T>
static inline std::ostream& operator<<(std::ostream& out, std::list<T> const& v)
{
    out << '[';
    if (!v.empty()) {
        for (typename std::list<T>::const_iterator i = v.begin(); ;) {
            out << *i;
            if (++i == v.end())
                break;
            out << ", ";
        }
    }
    out << ']';
    return out;
}

Then you'd figure out that code for vector is just the same, for forward_list is the same, actually, even for multitude of map types it's still just the same. Those template classes don't have anything in common except for meta-interface/protocol, and using template template parameter allows to capture the commonality in all of them. Before proceeding to write a template though, it's worth to check a reference to recall that sequence containers accept 2 template arguments - for value type and allocator. While allocator is defaulted, we still should account for its existence in our template operator<<:

template<template <typename, typename> class Container, class V, class A>
std::ostream& operator<<(std::ostream& out, Container<V, A> const& v)
...

Voila, that will work automagically for all present and future sequence containers adhering to the standard protocol. To add maps to the mix, it would take a peek at reference to note that they accept 4 template params, so we'd need another version of the operator<< above with 4-arg template template param. We'd also see that std:pair tries to be rendered with 2-arg operator<< for sequence types we defined previously, so we would provide a specialization just for std::pair.

Btw, with C+11 which allows variadic templates (and thus should allow variadic template template args), it would be possible to have single operator<< to rule them all. For example:

#include <iostream>
#include <vector>
#include <deque>
#include <list>

template<typename T, template<class,class...> class C, class... Args>
std::ostream& operator <<(std::ostream& os, const C<T,Args...>& objs)
{
    os << __PRETTY_FUNCTION__ << '\n';
    for (auto const& obj : objs)
        os << obj << ' ';
    return os;
}

int main()
{
    std::vector<float> vf { 1.1, 2.2, 3.3, 4.4 };
    std::cout << vf << '\n';

    std::list<char> lc { 'a', 'b', 'c', 'd' };
    std::cout << lc << '\n';

    std::deque<int> di { 1, 2, 3, 4 };
    std::cout << di << '\n';

    return 0;
}

Output

std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = float, C = vector, Args = <std::__1::allocator<float>>]
1.1 2.2 3.3 4.4 
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = char, C = list, Args = <std::__1::allocator<char>>]
a b c d 
std::ostream &operator<<(std::ostream &, const C<T, Args...> &) [T = int, C = deque, Args = <std::__1::allocator<int>>]
1 2 3 4 

How to convert dd/mm/yyyy string into JavaScript Date object?

Here is a way to transform a date string with a time of day to a date object. For example to convert "20/10/2020 18:11:25" ("DD/MM/YYYY HH:MI:SS" format) to a date object

    function newUYDate(pDate) {
      let dd = pDate.split("/")[0].padStart(2, "0");
      let mm = pDate.split("/")[1].padStart(2, "0");
      let yyyy = pDate.split("/")[2].split(" ")[0];
      let hh = pDate.split("/")[2].split(" ")[1].split(":")[0].padStart(2, "0");
      let mi = pDate.split("/")[2].split(" ")[1].split(":")[1].padStart(2, "0");
      let secs = pDate.split("/")[2].split(" ")[1].split(":")[2].padStart(2, "0");
    
      mm = (parseInt(mm) - 1).toString(); // January is 0
    
      return new Date(yyyy, mm, dd, hh, mi, secs);
    }

Removing the first 3 characters from a string

Use the substring method of the String class :

String removeCurrency=amount.getText().toString().substring(3);

Send FormData with other field in AngularJS

Assume that we want to get a list of certain images from a PHP server using the POST method.

You have to provide two parameters in the form for the POST method. Here is how you are going to do.

app.controller('gallery-item', function ($scope, $http) {

    var url = 'service.php'; 

    var data = new FormData();

    data.append("function", 'getImageList');
    data.append('dir', 'all');

    $http.post(url, data, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
      }).then(function (response) {

          // This function handles success
        console.log('angular:', response);

    }, function (response) {

        // this function handles error

    });
});

I have tested it on my system and it works.

Scala best way of turning a Collection into a Map-by-key?

This works for me:

val personsMap = persons.foldLeft(scala.collection.mutable.Map[Int, PersonDTO]()) {
    (m, p) => m(p.id) = p; m
}

The Map has to be mutable and the Map has to be return since adding to a mutable Map does not return a map.

How do I preserve line breaks when getting text from a textarea?

You could set width of div using Javascript and add white-space:pre-wrap to p tag, this break your textarea content at end of each line.

_x000D_
_x000D_
document.querySelector("button").onclick = function gt(){_x000D_
var card = document.createElement('div');_x000D_
card.style.width = "160px";_x000D_
card.style.background = "#eee";_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.style.whiteSpace = "pre-wrap";_x000D_
card.append(post);_x000D_
post.append(postText);_x000D_
document.body.append(card);_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required>_x000D_
Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea>_x000D_
<br><br>_x000D_
<button>Copy!!</button>
_x000D_
_x000D_
_x000D_

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

What is a loop invariant?

In simple words, a loop invariant is some predicate (condition) that holds for every iteration of the loop. For example, let's look at a simple for loop that looks like this:

int j = 9;
for(int i=0; i<10; i++)  
  j--;

In this example it is true (for every iteration) that i + j == 9. A weaker invariant that is also true is that i >= 0 && i <= 10.

How to get a list of all valid IP addresses in a local network?

If you want to see which IP addresses are in use on a specific subnet then there are several different IP Address managers.

Try Angry IP Scanner or Solarwinds or Advanced IP Scanner

Difference between Big-O and Little-O Notation

f ? O(g) says, essentially

For at least one choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) <= k g(x) holds for all x > a.

Note that O(g) is the set of all functions for which this condition holds.

f ? o(g) says, essentially

For every choice of a constant k > 0, you can find a constant a such that the inequality 0 <= f(x) < k g(x) holds for all x > a.

Once again, note that o(g) is a set.

In Big-O, it is only necessary that you find a particular multiplier k for which the inequality holds beyond some minimum x.

In Little-o, it must be that there is a minimum x after which the inequality holds no matter how small you make k, as long as it is not negative or zero.

These both describe upper bounds, although somewhat counter-intuitively, Little-o is the stronger statement. There is a much larger gap between the growth rates of f and g if f ? o(g) than if f ? O(g).

One illustration of the disparity is this: f ? O(f) is true, but f ? o(f) is false. Therefore, Big-O can be read as "f ? O(g) means that f's asymptotic growth is no faster than g's", whereas "f ? o(g) means that f's asymptotic growth is strictly slower than g's". It's like <= versus <.

More specifically, if the value of g(x) is a constant multiple of the value of f(x), then f ? O(g) is true. This is why you can drop constants when working with big-O notation.

However, for f ? o(g) to be true, then g must include a higher power of x in its formula, and so the relative separation between f(x) and g(x) must actually get larger as x gets larger.

To use purely math examples (rather than referring to algorithms):

The following are true for Big-O, but would not be true if you used little-o:

  • x² ? O(x²)
  • x² ? O(x² + x)
  • x² ? O(200 * x²)

The following are true for little-o:

  • x² ? o(x³)
  • x² ? o(x!)
  • ln(x) ? o(x)

Note that if f ? o(g), this implies f ? O(g). e.g. x² ? o(x³) so it is also true that x² ? O(x³), (again, think of O as <= and o as <)

Scale an equation to fit exact page width

I just had the situation that I wanted this only for lines exceeding \linewidth, that is: Squeezing long lines slightly. Since it took me hours to figure this out, I would like to add it here.

I want to emphasize that scaling fonts in LaTeX is a deadly sin! In nearly every situation, there is a better way (e.g. multline of the mathtools package). So use it conscious.

In this particular case, I had no influence on the code base apart the preamble and some lines slightly overshooting the page border when I compiled it as an eBook-scaled pdf.

\usepackage{environ}         % provides \BODY
\usepackage{etoolbox}        % provides \ifdimcomp
\usepackage{graphicx}        % provides \resizebox

\newlength{\myl}
\let\origequation=\equation
\let\origendequation=\endequation

\RenewEnviron{equation}{
  \settowidth{\myl}{$\BODY$}                       % calculate width and save as \myl
  \origequation
  \ifdimcomp{\the\linewidth}{>}{\the\myl}
  {\ensuremath{\BODY}}                             % True
  {\resizebox{\linewidth}{!}{\ensuremath{\BODY}}}  % False
  \origendequation
}

Before before After after

In Maven how to exclude resources from the generated jar?

Exclude specific pattern of file during creation of maven jar using maven-jar-plugin.

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-jar-plugin</artifactId>
  <version>2.3</version>
  <configuration>
    <excludes>
      <exclude>**/*.properties</exclude>
      <exclude>**/*.xml</exclude>
      <exclude>**/*.exe</exclude>
      <exclude>**/*.java</exclude>
      <exclude>**/*.xls</exclude>
    </excludes>
  </configuration>
</plugin>

Disable Logback in SpringBoot

Find spring-boot-starter-test in your pom.xml and modify it as follows:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <exclusions>
            <exclusion>
                <artifactId>commons-logging</artifactId>
                <groupId>commons-logging</groupId>
            </exclusion>
        </exclusions>
        <scope>test</scope>
    </dependency>

It fixed error like:

_Caused by: java.lang.IllegalArgumentException:_ **LoggerFactory** is not a **Logback LoggerContext** but *Logback* is on the classpath.

Either remove **Logback** or the competing implementation

(_class org.apache.logging.slf4j.Log4jLoggerFactory_
loaded from file: 

**${M2_HOME}/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.6.2/log4j-slf4j-impl-2.6.2.jar**).

If you are using WebLogic you will need to add **'org.slf4j'** to prefer-application-packages in WEB-INF/weblogic.xml: **org.apache.logging.slf4j.Log4jLoggerFactory**

Error: Jump to case label

The problem is that variables declared in one case are still visible in the subsequent cases unless an explicit { } block is used, but they will not be initialized because the initialization code belongs to another case.

In the following code, if foo equals 1, everything is ok, but if it equals 2, we'll accidentally use the i variable which does exist but probably contains garbage.

switch(foo) {
  case 1:
    int i = 42; // i exists all the way to the end of the switch
    dostuff(i);
    break;
  case 2:
    dostuff(i*2); // i is *also* in scope here, but is not initialized!
}

Wrapping the case in an explicit block solves the problem:

switch(foo) {
  case 1:
    {
        int i = 42; // i only exists within the { }
        dostuff(i);
        break;
    }
  case 2:
    dostuff(123); // Now you cannot use i accidentally
}

Edit

To further elaborate, switch statements are just a particularly fancy kind of a goto. Here's an analoguous piece of code exhibiting the same issue but using a goto instead of a switch:

int main() {
    if(rand() % 2) // Toss a coin
        goto end;

    int i = 42;

  end:
    // We either skipped the declaration of i or not,
    // but either way the variable i exists here, because
    // variable scopes are resolved at compile time.
    // Whether the *initialization* code was run, though,
    // depends on whether rand returned 0 or 1.
    std::cout << i;
}

SVN Commit failed, access forbidden

If the problem lies client side, this could be one of the causes of the error.

On clients TortoiseSVN saves client credentials under

Tortoise settings / saved data / authentication data.

I got the same error trying to commit my files, but my credentials were changed. Clearing this cache here will give you a popup on next commit attempt for re-entering your correct credentials.

Why is my Git Submodule HEAD detached from master?

As other people have said, the reason this happens is that the parent repo only contains a reference to (the SHA1 of) a specific commit in the submodule – it doesn't know anything about branches. This is how it should work: the branch that was at that commit may have moved forward (or backwards), and if the parent repo had referenced the branch then it could easily break when that happens.

However, especially if you are actively developing in both the parent repo and the submodule, detached HEAD state can be confusing and potentially dangerous. If you make commits in the submodule while it's in detached HEAD state, these become dangling and you can easily lose your work. (Dangling commits can usually be rescued using git reflog, but it's much better to avoid them in the first place.)

If you're like me, then most of the time if there is a branch in the submodule that points to the commit being checked out, you would rather check out that branch than be in detached HEAD state at the same commit. You can do this by adding the following alias to your gitconfig file:

[alias]
    submodule-checkout-branch = "!f() { git submodule -q foreach 'branch=$(git branch --no-column --format=\"%(refname:short)\" --points-at `git rev-parse HEAD` | grep -v \"HEAD detached\" | head -1); if [[ ! -z $branch && -z `git symbolic-ref --short -q HEAD` ]]; then git checkout -q \"$branch\"; fi'; }; f"

Now, after doing git submodule update you just need to call git submodule-checkout-branch, and any submodule that is checked out at a commit which has a branch pointing to it will check out that branch. If you don't often have multiple local branches all pointing to the same commit, then this will usually do what you want; if not, then at least it will ensure that any commits you do make go onto an actual branch instead of being left dangling.

Furthermore, if you have set up git to automatically update submodules on checkout (using git config --global submodule.recurse true, see this answer), you can make a post-checkout hook that calls this alias automatically:

$ cat .git/hooks/post-checkout 
#!/bin/sh
git submodule-checkout-branch

Then you don't need to call either git submodule update or git submodule-checkout-branch, just doing git checkout will update all submodules to their respective commits and check out the corresponding branches (if they exist).

Concatenate text files with Windows command line, dropping leading lines

Use the FOR command to echo a file line by line, and with the 'skip' option to miss a number of starting lines...

FOR /F "skip=1" %i in (file2.txt) do @echo %i

You could redirect the output of a batch file, containing something like...

FOR /F %%i in (file1.txt) do @echo %%i
FOR /F "skip=1" %%i in (file2.txt) do @echo %%i

Note the double % when a FOR variable is used within a batch file.

How do I view an older version of an SVN file?

I believe the best way to view revisions is to use a program/app that makes it easy for you. I like to use trac : http://trac.edgewall.org/wiki/TracSubversion

It provides a great svn browser and makes it really easy to go back through your revisions.

It may be a little overkill to set this up for one specific revision you want to check, but it could be useful if you're going to do this a lot in the future.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

This means the file isn't really a gzipped tar file -- or any kind of gzipped file -- in spite of being named like one.

When you download a file with wget, check for indications like Length: unspecified [text/html] which shows it is plain text (text) and that it is intended to be interpreted as html. Check the wget output below -

[root@XXXXX opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:39:40--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... 23.72.136.27, 23.72.136.67
Connecting to download.oracle.com (download.oracle.com)|23.72.136.27|:80... connected.
HTTP request sent, awaiting response... 302 Not Allowed
Location: http://XXXX/FAQs/URLFiltering/ProxyWarning.html [following]
--2017-10-12 12:39:40--  http://XXXX/FAQs/URLFiltering/ProxyWarning.html
Resolving XXXX (XXXXX)... XXX.XX.XX.XXX
Connecting to XXXX (XXXX)|XXX.XX.XX.XXX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17121 (17K) [text/html]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’

100%[=========================================================================================================================================================================>] 17,121      --.-K/s   in 0.05s   

2017-10-12 12:39:40 (349 KB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [17121/17121]

This sort of confirms that you haven't received a gzip file.

For a correct file, the wget output will show something like Length: 185515842 (177M) [application/x-gzip] as shown in the below output -

[root@txcdtl01ss270n opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:50:06--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... XX.XXX.XX.XX, XX.XX.XXX.XX
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz [following]
--2017-10-12 12:50:06--  https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving edelivery.oracle.com (edelivery.oracle.com)... XXX.XX.XXX.XX, 2600:1404:16:188::2d3e, 2600:1404:16:180::2d3e
Connecting to edelivery.oracle.com (edelivery.oracle.com)|XXX.XX.XX.XXX|:443... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61e7f202677f94afd [following]
--2017-10-12 12:50:07--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 185515842 (177M) [application/x-gzip]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’

100%[=========================================================================================================================================================================>] 185,515,842 6.60MB/s   in 28s    

2017-10-12 12:50:34 (6.43 MB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [185515842/185515842]

The above shows a correct gzip application file has been downloaded.

You can also file, head, less, view utilities to check the file. For example a HTML file would give below output -

[root@XXXXXX opt]# head jdk-8u144-linux-x64.tar.gz
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="/css/print.css" rel="stylesheet" media="print">
    <link href="/css/main.css" rel="stylesheet" media="screen">
    <link href="/css/font-awesome.min.css" rel="stylesheet">

The above shows it is indeed an HTML page which we are trying to unzip/untar - something that won't work. If it was indeed a correct zip file (binary in nature) the output of head would have produced garbage - something like below -

[root@XXXX opt]# head jdk-8u144-linux-x64.tar.gz 
x?rY?[ms?F???????t?l???DR??????j
                                       $?$,`0?h?_????/??=?@Q?w+???*?Hbfz?{?~?{?i?x??k?????}????z???w????g?????{???;{s????w?????7?N????i?
?????}
?¿g????????????7??s??????î??????~i??j?/??????#???=??=>???{}??|?????????????3???X???]9??????u?????%g?<^)?H?8?F?R?t?o?L?u??S%?ds5?2_EZn?t^??
                                                                                                                                                 ?N3??(??<??|'?q???R?N?gq?Uv!???p???rL??M??u??.?Q?5?T??BNw?!$??<>?7G'$?,Mt4WY?Gi"?=??p?)?VIN3????\ek??0??G
                                            ?<L?c?e?t-???2???G:?ia??I?<?g3???d?H????[2`?<I?A?6?W??<??C???????h??A0QL?2?4?-*
?x?????t%t1??f?>+A??,Lr?
                        ?Fe:MBH????
C?Q?r?S??<M?b?<,5???@???s???c??sp?f?=g?????k???4?}??kh)?¹Z??#d?*{???-?.N?)?e??s:?H(VQ??3*?$2??r?v?"o?_??!A???????B?l=A?|??@??0??1??5??4g?
?
???Se????H[2?????t??5?Df????$1???b$? h?Op????!Lvb!p??b?8^?Y???n?
                                                                          O??????|??lW?lu??*?N?M???
?/?^0~?~?#??q????????K??;?d???aw4?????'?~?7??ky?o?????????t?'k??f????!vo???'o???     ?.?Pn\?
               ?+??K"FA{????n2????v??!/Ok??r4?c5?x$'?.?&w?!?%??o??????2???i
                                                                               ?a0??Ag?d????GH)G7~?g???b??%?b??rt?m~?   ?????t0??   <????????????5?q?t??K(??+Z<??=???:1?\?x?p=t?`??G@F??    i?????p8?????H.???dMLE??e[?`?'n??*h[??;?0w'??6A??M?x?fpeB>&???MO???????`?@á/?"?????(??^???n??=????5??@?Mx??d:\YAn???]|?w>??S??FA9?J?k!?@?

Try downloading from the official site and check if their download links have changed. Also check your proxy settings and make sure you have the right proxies enabled to download/wget it from the correct source.

Hope this helps.

Move an array element from one array position to another

If you'd like a version on npm, array-move is the closest to this answer, although it's not the same implementation. See its usage section for more details. The previous version of this answer (that modified Array.prototype.move) can be found on npm at array.prototype.move.


I had fairly good success with this function:

_x000D_
_x000D_
function array_move(arr, old_index, new_index) {_x000D_
    if (new_index >= arr.length) {_x000D_
        var k = new_index - arr.length + 1;_x000D_
        while (k--) {_x000D_
            arr.push(undefined);_x000D_
        }_x000D_
    }_x000D_
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);_x000D_
    return arr; // for testing_x000D_
};_x000D_
_x000D_
// returns [2, 1, 3]_x000D_
console.log(array_move([1, 2, 3], 0, 1)); 
_x000D_
_x000D_
_x000D_

Note that the last return is simply for testing purposes: splice performs operations on the array in-place, so a return is not necessary. By extension, this move is an in-place operation. If you want to avoid that and return a copy, use slice.

Stepping through the code:

  1. If new_index is greater than the length of the array, we want (I presume) to pad the array properly with new undefineds. This little snippet handles this by pushing undefined on the array until we have the proper length.
  2. Then, in arr.splice(old_index, 1)[0], we splice out the old element. splice returns the element that was spliced out, but it's in an array. In our above example, this was [1]. So we take the first index of that array to get the raw 1 there.
  3. Then we use splice to insert this element in the new_index's place. Since we padded the array above if new_index > arr.length, it will probably appear in the right place, unless they've done something strange like pass in a negative number.

A fancier version to account for negative indices:

_x000D_
_x000D_
function array_move(arr, old_index, new_index) {_x000D_
    while (old_index < 0) {_x000D_
        old_index += arr.length;_x000D_
    }_x000D_
    while (new_index < 0) {_x000D_
        new_index += arr.length;_x000D_
    }_x000D_
    if (new_index >= arr.length) {_x000D_
        var k = new_index - arr.length + 1;_x000D_
        while (k--) {_x000D_
            arr.push(undefined);_x000D_
        }_x000D_
    }_x000D_
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);_x000D_
    return arr; // for testing purposes_x000D_
};_x000D_
    _x000D_
// returns [1, 3, 2]_x000D_
console.log(array_move([1, 2, 3], -1, -2));
_x000D_
_x000D_
_x000D_

Which should account for things like array_move([1, 2, 3], -1, -2) properly (move the last element to the second to last place). Result for that should be [1, 3, 2].

Either way, in your original question, you would do array_move(arr, 0, 2) for a after c. For d before b, you would do array_move(arr, 3, 1).

How to find event listeners on a DOM node when debugging or from the JavaScript code?

WebKit Inspector in Chrome or Safari browsers now does this. It will display the event listeners for a DOM element when you select it in the Elements pane.

Catch paste input

This code is working for me either paste from right click or direct copy paste

   $('.textbox').on('paste input propertychange', function (e) {
        $(this).val( $(this).val().replace(/[^0-9.]/g, '') );
    })

When i paste Section 1: Labour Cost it becomes 1 in text box.

To allow only float value i use this code

 //only decimal
    $('.textbox').keypress(function(e) {
        if(e.which == 46 && $(this).val().indexOf('.') != -1) {
            e.preventDefault();
        } 
       if (e.which == 8 || e.which == 46) {
            return true;
       } else if ( e.which < 48 || e.which > 57) {
            e.preventDefault();
      }
    });