Programs & Examples On #Simplyvbunit

What do >> and << mean in Python?

12 << 2

48

Actual binary value of 12 is "00 1100" when we execute the above statement Left shift ( 2 places shifted left) returns the value 48 its binary value is "11 0000".

48 >> 2

12

The binary value of 48 is "11 0000", after executing above statement Right shift ( 2 places shifted right) returns the value 12 its binary value is "00 1100".

bundle install returns "Could not locate Gemfile"

I had this problem on Ubuntu 18.04. I updated the gem

sudo gem install rails
sudo gem install jekyll
sudo gem install jekyll bundler
cd ~/desiredFolder
jekyll new <foldername>
cd <foldername> OR 
bundle init
bundle install
bundle add jekyll
bundle exec jekyll serve

All worked and goto your browser just go to http://127.0.0.1:4000/ and it really should be running

How can I delay a :hover effect in CSS?

You can use transitions to delay the :hover effect you want, if the effect is CSS-based.

For example

div{
    transition: 0s background-color;
}

div:hover{
    background-color:red;    
    transition-delay:1s;
}

this will delay applying the the hover effects (background-color in this case) for one second.


Demo of delay on both hover on and off:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
    transition-delay:1s;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_

Demo of delay only on hover on:

_x000D_
_x000D_
div{_x000D_
    display:inline-block;_x000D_
    padding:5px;_x000D_
    margin:10px;_x000D_
    border:1px solid #ccc;_x000D_
    transition: 0s background-color;_x000D_
}_x000D_
div:hover{_x000D_
    background-color:red;    _x000D_
    transition-delay:1s;_x000D_
}
_x000D_
<div>delayed hover</div>
_x000D_
_x000D_
_x000D_


Vendor Specific Extentions for Transitions and W3C CSS3 transitions

Getting multiple values with scanf()

int a[1000] ;
for(int i = 0 ; i <= 3 , i++)
scanf("%d" , &a[i]) ;

nodejs module.js:340 error: cannot find module

While i tried to run my first node application i had encountered the same issue but when i tried to see what the issue might be it was the path of the file. I was running the node .js from different location and hence encountered the issue. When i fixed the path this worked fine.

ImportError: No module named pandas

As of Dec 2020, I had the same issue when installing python v 3.8.6 via pyenv. So, I started by:

  1. Installing pyenv via homebrew brew install pyenv
  2. Install xz compiling package via brew install xz
  3. pyenv install 3.8.6 pick the required version
  4. pyenv global 3.8.6 make this version as global
  5. python -m pip install -U pip to upgrade pip
  6. pip install virtualenv

After that, I initialized my new env, installed pandas via pip command, and everything worked again. The panda's version installed is 1.1.5 within my working project directory. I hope that might help!

Note: If you have installed python before xz, make sure to uninstall it first, otherwise the error might persist.

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.

As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:

$(window).resize(function() {
  //update stuff
});

How to allow download of .json file with ASP.NET

Solution is you need to add json file extension type in MIME Types

Method 1

Go to IIS, Select your application and Find MIME Types

enter image description here

Click on Add from Right panel

File Name Extension = .json

MIME Type = application/json

enter image description here

After adding .json file type in MIME Types, Restart IIS and try to access json file


Method 2

Go to web.config of that application and add this lines in it

 <system.webServer>
   <staticContent>
     <mimeMap fileExtension=".json" mimeType="application/json" />
   </staticContent>
 </system.webServer>

Eclipse - "Workspace in use or cannot be created, chose a different one."

An additional reason could be that you're pointing to a workspace on a drive that no longer exists, thinking that you're choosing the valid one. For instance, for me the workspace used to exist on the F drive, but now it is on my D drive. Even though I don't have the F drive anymore it is still listed as a workspace I once used during Eclipse startup. When I choose this old workspace Eclipse complains that the workspace is "in use", which is very strange.

Get index of array element faster than O(n)

Convert the array into a hash. Then look for the key.

array = ['a', 'b', 'c']
hash = Hash[array.map.with_index.to_a]    # => {"a"=>0, "b"=>1, "c"=>2}
hash['b'] # => 1

PDO get the last ID inserted

You can get the id of the last transaction by running lastInsertId() method on the connection object($conn).

Like this $lid = $conn->lastInsertId();

Please check out the docs https://www.php.net/manual/en/language.oop5.basic.php

How to generate range of numbers from 0 to n in ES2015 only?

You can use the spread operator on the keys of a freshly created array.

[...Array(n).keys()]

or

Array.from(Array(n).keys())

The Array.from() syntax is necessary if working with TypeScript

In-place edits with sed on OS X

sed -i -- "s/https/http/g" file.txt

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

Using <style> tags in the <body> with other HTML

The <style> tag belongs in the <head> section, separate from all the content.

References: W3C Specs and W3Schools

How to execute Python scripts in Windows?

Found an incredibly useful answer here: How to run different python versions in cmd?

I would suggest using the Python Launcher for Windows utility that introduced was into Python 3.3 a while ago. You can also manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.

Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py, .pyw, .pyc, and .pyo files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX comments at the beginning of your Python scripts.

As J.F. Sebastian suggests, Python Launcher for Windows is the best and default choice for launching different version of Python in Windows. It used to be a third-party tool, but now it is officially supported since Python 3.3.

New in version 3.3.

The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.

This is a great tool just use it!

Are PDO prepared statements sufficient to prevent SQL injection?

Prepared statements / parameterized queries are generally sufficient to prevent 1st order injection on that statement*. If you use un-checked dynamic sql anywhere else in your application you are still vulnerable to 2nd order injection.

2nd order injection means data has been cycled through the database once before being included in a query, and is much harder to pull off. AFAIK, you almost never see real engineered 2nd order attacks, as it is usually easier for attackers to social-engineer their way in, but you sometimes have 2nd order bugs crop up because of extra benign ' characters or similar.

You can accomplish a 2nd order injection attack when you can cause a value to be stored in a database that is later used as a literal in a query. As an example, let's say you enter the following information as your new username when creating an account on a web site (assuming MySQL DB for this question):

' + (SELECT UserName + '_' + Password FROM Users LIMIT 1) + '

If there are no other restrictions on the username, a prepared statement would still make sure that the above embedded query doesn't execute at the time of insert, and store the value correctly in the database. However, imagine that later the application retrieves your username from the database, and uses string concatenation to include that value a new query. You might get to see someone else's password. Since the first few names in users table tend to be admins, you may have also just given away the farm. (Also note: this is one more reason not to store passwords in plain text!)

We see, then, that prepared statements are enough for a single query, but by themselves they are not sufficient to protect against sql injection attacks throughout an entire application, because they lack a mechanism to enforce all access to a database within an application uses safe code. However, used as part of good application design — which may include practices such as code review or static analysis, or use of an ORM, data layer, or service layer that limits dynamic sql — prepared statements are the primary tool for solving the Sql Injection problem. If you follow good application design principles, such that your data access is separated from the rest of your program, it becomes easy to enforce or audit that every query correctly uses parameterization. In this case, sql injection (both first and second order) is completely prevented.


*It turns out that MySql/PHP are (okay, were) just dumb about handling parameters when wide characters are involved, and there is still a rare case outlined in the other highly-voted answer here that can allow injection to slip through a parameterized query.

Adding files to a GitHub repository

The general idea is to add, commit and push your files to the GitHub repo.

First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.

git --work-tree=yourSrcFolder add .

(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)

That way, you keep separate your initial source folder, from your Git working tree.


Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.

d

How to do a background for a label will be without color?

This uses Graphics.CopyFromScreen so the control needs to be added when it's visable on screen.

public partial class TransparentLabelControl : Label
{
    public TransparentLabelControl()
    {
        this.AutoSize = true;
        this.Visible = false;

        this.ImageAlign = ContentAlignment.TopLeft;
        this.Visible = true;

        this.Resize += TransparentLabelControl_Resize;
        this.LocationChanged += TransparentLabelControl_LocationChanged;
        this.TextChanged += TransparentLabelControl_TextChanged;
        this.ParentChanged += TransparentLabelControl_ParentChanged;
    }

    #region Events
    private void TransparentLabelControl_ParentChanged(object sender, EventArgs e)
    {
        SetTransparent();
        if (this.Parent != null)
        {
            this.Parent.ControlAdded += Parent_ControlAdded;
            this.Parent.ControlRemoved += Parent_ControlRemoved;
        }
    }

    private void Parent_ControlRemoved(object sender, ControlEventArgs e)
    {
        SetTransparent();
    }

    private void Parent_ControlAdded(object sender, ControlEventArgs e)
    {
        if (this.Bounds.IntersectsWith(e.Control.Bounds))
        {
            SetTransparent();
        }
    }

    private void TransparentLabelControl_TextChanged(object sender, EventArgs e)
    {
        SetTransparent();
    }

    private void TransparentLabelControl_LocationChanged(object sender, EventArgs e)
    {

        SetTransparent();
    }

    private void TransparentLabelControl_Resize(object sender, EventArgs e)
    {
        SetTransparent();
    }
    #endregion

    public void SetTransparent()
    {
        if (this.Parent!= null)
        {
            this.Visible = false;
            this.Image = this.takeComponentScreenShot(this.Parent);
            this.Visible = true;                
        }
    }

    private  Bitmap takeComponentScreenShot(Control control)
    {
        Rectangle rect = control.RectangleToScreen(this.Bounds);
        if (rect.Width == 0 || rect.Height == 0)
        {
            return null;
        }
        Bitmap bmp = new Bitmap(rect.Width, rect.Height, PixelFormat.Format32bppArgb);
        Graphics g = Graphics.FromImage(bmp);

        g.CopyFromScreen(rect.Left, rect.Top, 0, 0, bmp.Size, CopyPixelOperation.SourceCopy);

        return bmp;
    }

}

babel-loader jsx SyntaxError: Unexpected token

Add "babel-preset-react"

npm install babel-preset-react

and add "presets" option to babel-loader in your webpack.config.js

(or you can add it to your .babelrc or package.js: http://babeljs.io/docs/usage/babelrc/)

Here is an example webpack.config.js:

{ 
    test: /\.jsx?$/,         // Match both .js and .jsx files
    exclude: /node_modules/, 
    loader: "babel", 
    query:
      {
        presets:['react']
      }
}

Recently Babel 6 was released and there was a major change: https://babeljs.io/blog/2015/10/29/6.0.0

If you are using react 0.14, you should use ReactDOM.render() (from require('react-dom')) instead of React.render(): https://facebook.github.io/react/blog/#changelog

UPDATE 2018

Rule.query has already been deprecated in favour of Rule.options. Usage in webpack 4 is as follows:

npm install babel-loader babel-preset-react

Then in your webpack configuration (as an entry in the module.rules array in the module.exports object)

{
    test: /\.jsx?$/,
    exclude: /node_modules/,
    use: [
      {
        loader: 'babel-loader',
        options: {
          presets: ['react']
        }
      }
    ],
  }

Why is &#65279; appearing in my HTML?

If you are using Notepad++, "Menu" >> "Encoding" >> "Convert to UTF-8" your "include" files.

ImportError: No module named 'selenium'

If pip isn’t already installed, then first try to bootstrap it from the standard library:

sudo python -m ensurepip --default-pip

Ensure pip, setuptools, and wheel are up to date

sudo python -m pip install --upgrade pip setuptools wheel

Now Install Selenium

sudo pip install selenium

Now run your runner.

Hope this helps. Happy Coding !!

php check if array contains all array values from another array

How about this:

function array_keys_exist($searchForKeys = array(), $searchableArray) {
    $searchableArrayKeys = array_keys($searchableArray);

    return count(array_intersect($searchForKeys, $searchableArrayKeys)) == count($searchForKeys); 
}

How to set default value for HTML select?

Note: this is JQuery. See Sébastien answer for Javascript

$(function() {
    var temp="a"; 
    $("#MySelect").val(temp);
});

<select name="MySelect" id="MySelect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

Creating all possible k combinations of n items in C++

If the number of the set would be within 32, 64 or a machine native primitive size, then you can do it with a simple bit manipulation.

template<typename T>
void combo(const T& c, int k)
{
    int n = c.size();
    int combo = (1 << k) - 1;       // k bit sets
    while (combo < 1<<n) {

        pretty_print(c, combo);

        int x = combo & -combo;
        int y = combo + x;
        int z = (combo & ~y);
        combo = z / x;
        combo >>= 1;
        combo |= y;
    }
}

this example calls pretty_print() function by the dictionary order.

For example. You want to have 6C3 and assuming the current 'combo' is 010110. Obviously the next combo MUST be 011001. 011001 is : 010000 | 001000 | 000001

010000 : deleted continuously 1s of LSB side. 001000 : set 1 on the next of continuously 1s of LSB side. 000001 : shifted continuously 1s of LSB to the right and remove LSB bit.

int x = combo & -combo;

this obtains the lowest 1.

int y = combo + x;

this eliminates continuously 1s of LSB side and set 1 on the next of it (in the above case, 010000 | 001000)

int z = (combo & ~y)

this gives you the continuously 1s of LSB side (000110).

combo = z / x;
combo >> =1;

this is for 'shifted continuously 1s of LSB to the right and remove LSB bit'.

So the final job is to OR y to the above.

combo |= y;

Some simple concrete example :

#include <bits/stdc++.h>

using namespace std;

template<typename T>
void pretty_print(const T& c, int combo)
{
    int n = c.size();
    for (int i = 0; i < n; ++i) {
        if ((combo >> i) & 1)
            cout << c[i] << ' ';
    }
    cout << endl;
}

template<typename T>
void combo(const T& c, int k)
{
    int n = c.size();
    int combo = (1 << k) - 1;       // k bit sets
    while (combo < 1<<n) {

        pretty_print(c, combo);

        int x = combo & -combo;
        int y = combo + x;
        int z = (combo & ~y);
        combo = z / x;
        combo >>= 1;
        combo |= y;
    }
}

int main()
{
    vector<char> c0 = {'1', '2', '3', '4', '5'};
    combo(c0, 3);

    vector<char> c1 = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
    combo(c1, 4);
    return 0;
}

result :

1 2 3 
1 2 4 
1 3 4 
2 3 4 
1 2 5 
1 3 5 
2 3 5 
1 4 5 
2 4 5 
3 4 5 
a b c d 
a b c e 
a b d e 
a c d e 
b c d e 
a b c f 
a b d f 
a c d f 
b c d f 
a b e f 
a c e f 
b c e f 
a d e f 
b d e f 
c d e f 
a b c g 
a b d g 
a c d g 
b c d g 
a b e g 
a c e g 
b c e g 
a d e g 
b d e g 
c d e g 
a b f g 
a c f g 
b c f g 
a d f g 
b d f g 
c d f g 
a e f g 
b e f g 
c e f g 
d e f g 

How to change letter spacing in a Textview?

check out android:textScaleX

Depending on how much spacing you need, this might help. That's the only thing remotely related to letter-spacing in the TextView.

Edit: please see @JerabekJakub's response below for an updated, better method to do this starting with api 21 (Lollipop)

How to change line-ending settings

The normal way to control this is with git config

For example

git config --global core.autocrlf true

For details, scroll down in this link to Pro Git to the section named "core.autocrlf"


If you want to know what file this is saved in, you can run the command:

git config --global --edit

and the git global config file should open in a text editor, and you can see where that file was loaded from.

Passing structs to functions

It is possible to construct a struct inside the function arguments:

function({ .variable = PUT_DATA_HERE });

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

In my case this problem was occuring because i was accessing the file from shared folder by using computerName. OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',''Excel 8.0;Database='\ntpc0100\MysharedFolder\KPI_tempData\VariablePayoutDetails.xls';IMEX=1;'','.....) Insted of using computerName ntpc0100(whatever your machine name) you should specify IPaddress of your machine. for example:- OPENROWSET(''Microsoft.Jet.OLEDB.4.0'',''Excel 8.0; Database='\193.34.23.200\MysharedFolder\KPI_tempData\KPIVariablePayoutDetails.xls'....);

How can I display a list view in an Android Alert Dialog?

According to the documentation, there are three kinds of lists that can be used with an AlertDialog:

  1. Traditional single-choice list
  2. Persistent single-choice list (radio buttons)
  3. Persistent multiple-choice list (checkboxes)

I will give an example of each below.

Traditional single-choice list

The way to make a traditional single-choice list is to use setItems.

enter image description here

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
builder.setItems(animals, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0: // horse
            case 1: // cow
            case 2: // camel
            case 3: // sheep
            case 4: // goat
        }
    }
});

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
builder.setItems(animals) { dialog, which ->
    when (which) {
        0 -> { /* horse */ }
        1 -> { /* cow   */ }
        2 -> { /* camel */ }
        3 -> { /* sheep */ }
        4 -> { /* goat  */ }
    }
}

// create and show the alert dialog
val dialog = builder.create()
dialog.show()

Radio button list

enter image description here

The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose an animal");

// add a radio button list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
int checkedItem = 1; // cow
builder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user checked an item
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose an animal")

// add a radio button list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItem = 1 // cow
builder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->
    // user checked an item
}


// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
}
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()
dialog.show()

Checkbox list

enter image description here

The way to make a checkbox list is to use setMultiChoiceItems.

Java version

// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");

// add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which, boolean isChecked) {
        // user checked or unchecked a box
    }
});

// add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // user clicked OK
    }
});
builder.setNegativeButton("Cancel", null);

// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();

Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.

Kotlin version

// setup the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")

// add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
    // user checked or unchecked a box
}

// add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
    // user clicked OK
}
builder.setNegativeButton("Cancel", null)

// create and show the alert dialog
val dialog = builder.create()
dialog.show()

Notes

  • For the context in the code above, don't use getApplicationContext() or you will get an IllegalStateException (see here for why). Instead, get a reference to the activity context, such as with this.
  • You can also populate the list items from a database or another source using setAdapter or setCursor or passing in a Cursor or ListAdapter into the setSingleChoiceItems or setMultiChoiceItems.
  • If the list is longer than will fit on the screen then the dialog will automatically scroll it. If you have a really long list, though, I'm guessing that you should probably make a custom dialog with a RecyclerView.
  • To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:

    import android.support.v7.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        Context context;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            context = this;
        }
    
        public void showAlertDialogButtonClicked(View view) {
    
            // example code to create alert dialog lists goes here
        }
    }
    

Related

In Python, when to use a Dictionary, List or Set?

When use them, I make an exhaustive cheatsheet of their methods for your reference:

class ContainerMethods:
    def __init__(self):
        self.list_methods_11 = {
                    'Add':{'append','extend','insert'},
                    'Subtract':{'pop','remove'},
                    'Sort':{'reverse', 'sort'},
                    'Search':{'count', 'index'},
                    'Entire':{'clear','copy'},
                            }
        self.tuple_methods_2 = {'Search':'count','index'}

        self.dict_methods_11 = {
                    'Views':{'keys', 'values', 'items'},
                    'Add':{'update'},
                    'Subtract':{'pop', 'popitem',},
                    'Extract':{'get','setdefault',},
                    'Entire':{ 'clear', 'copy','fromkeys'},
                            }
        self.set_methods_17 ={
                    'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
                    'Subtract':{'pop', 'remove','discard'},
                    'Relation':{'isdisjoint', 'issubset', 'issuperset'},
                    'operation':{'union' 'intersection','difference', 'symmetric_difference'}
                    'Entire':{'clear', 'copy'}}

IllegalMonitorStateException on wait() call

You need to be in a synchronized block in order for Object.wait() to work.

Also, I recommend looking at the concurrency packages instead of the old school threading packages. They are safer and way easier to work with.

Happy coding.

EDIT

I assumed you meant Object.wait() as your exception is what happens when you try to gain access without holding the objects lock.

Set the table column width constant regardless of the amount of text in its cells?

You need to write this inside the corresponding CSS

table-layout:fixed;

cannot import name patterns

Seems you are using outdated version of django.. Simply update django and try again.. Following command will update your django version..

pip install --upgrade django

Sql connection-string for localhost server

You can also use Dot(.) for local key i.e;

Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True

If you have the default server instance i.e. MSSQLSERVER, then just use dot for Data Source.

Data Source=.;Initial Catalog=master;Integrated Security=True

How to update a menu item shown in the ActionBar?

To refresh menu from Fragment simply call:

getActivity().invalidateOptionsMenu();

c# Image resizing to different size while preserving aspect ratio

This should do it.

private void resizeImage(string path, string originalFilename, 
                     /* note changed names */
                     int canvasWidth, int canvasHeight, 
                     /* new */
                     int originalWidth, int originalHeight)
{
    Image image = Image.FromFile(path + originalFilename);

    System.Drawing.Image thumbnail = 
        new Bitmap(canvasWidth, canvasHeight); // changed parm names
    System.Drawing.Graphics graphic = 
                 System.Drawing.Graphics.FromImage(thumbnail);

    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = SmoothingMode.HighQuality;
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphic.CompositingQuality = CompositingQuality.HighQuality;

    /* ------------------ new code --------------- */

    // Figure out the ratio
    double ratioX = (double) canvasWidth / (double) originalWidth;
    double ratioY = (double) canvasHeight / (double) originalHeight;
    // use whichever multiplier is smaller
    double ratio = ratioX < ratioY ? ratioX : ratioY;

    // now we can get the new height and width
    int newHeight = Convert.ToInt32(originalHeight * ratio);
    int newWidth = Convert.ToInt32(originalWidth * ratio);

    // Now calculate the X,Y position of the upper-left corner 
    // (one of these will always be zero)
    int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
    int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);

    graphic.Clear(Color.White); // white padding
    graphic.DrawImage(image, posX, posY, newWidth, newHeight);

    /* ------------- end new code ---------------- */

    System.Drawing.Imaging.ImageCodecInfo[] info =
                     ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,
                     100L);            
    thumbnail.Save(path + newWidth + "." + originalFilename, info[1], 
                     encoderParameters);
}

Edited to add:

Those who want to improve this code should put it in the comments, or a new answer. Don't edit this code directly.

getting only name of the class Class.getName()

Get simple name instead of path.

String onlyClassName =  this.getLocalClassName(); 

call above method in onCreate

How can I read and manipulate CSV file data in C++?

I've worked with a lot of CSV files in my time. I'd like to add the advice:

1 - Depending on the source (Excel, etc), commas or tabs may be embedded in a field. Usually, the rule is that they will be 'protected' because the field will be double-quote delimited, as in "Boston, MA 02346".

2 - Some sources will not double-quote delimit all text fields. Other sources will. Others will delimit all fields, even numerics.

3 - Fields containing double-quotes usually get the embedded double quotes doubled up (and the field itself delimited with double quotes, as in "George ""Babe"" Ruth".

4 - Some sources will embed CR/LFs (Excel is one of these!). Sometimes it'll be just a CR. The field will usually be double-quote delimited, but this situation is very difficult to handle.

Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

Sub Copy5CellsToRight()
    ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub

If you want to include the activecell in the range that gets copied, you don't need the offset:

Sub ExtendAndCopy5CellsToRight()
    ActiveCell.Resize(1, 6).Copy
End Sub

Note that you don't need to select before copying.

Export SQL query data to Excel

If you're just needing to export to excel, you can use the export data wizard. Right click the database, Tasks->Export data.

How to loop and render elements in React-native?

If u want a direct/ quick away, without assing to variables:

{
 urArray.map((prop, key) => {
     console.log(emp);
     return <Picker.Item label={emp.Name} value={emp.id} />;
 })
}

The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>)

Inside ContentPlaceholder, put the placeholder control.For Example like this,

<asp:Content ID="header" ContentPlaceHolderID="head" runat="server">
       <asp:PlaceHolder ID="metatags" runat="server">
        </asp:PlaceHolder>
</asp:Content>

Code Behind:

HtmlMeta hm1 = new HtmlMeta();
hm1.Name = "Description";
hm1.Content = "Content here";
metatags.Controls.Add(hm1);

File Upload In Angular?

In the simplest form, the following code works in Angular 6/7

this.http.post("http://destinationurl.com/endpoint", fileFormData)
  .subscribe(response => {
    //handle response
  }, err => {
    //handle error
  });

Here is the complete implementation

*.h or *.hpp for your class definitions

I prefer .hpp for C++ to make it clear to both editors and to other programmers that it is a C++ header rather than a C header file.

In JavaScript can I make a "click" event fire programmatically for a file input element?

It works :

For security reasons on Firefox and Opera, you can't fire the click on file input, but you can simulate with MouseEvents :

<script>
click=function(element){
    if(element!=null){
        try {element.click();}
        catch(e) {
            var evt = document.createEvent("MouseEvents");
            evt.initMouseEvent("click",true,true,window,0,0,0,0,0,false,false,false,false,0,null);
            element.dispatchEvent(evt);
            }
        }
    };
</script>

<input type="button" value="upload" onclick="click(document.getElementById('inputFile'));"><input type="file" id="inputFile" style="display:none">

How to call a JavaScript function within an HTML body

Try to use createChild() method of DOM or insertRow() and insertCell() method of table object in script tag.

How to get query params from url in Angular 2?

Hi you can use URLSearchParams, you can read more about it here.

import:

import {URLSearchParams} from "@angular/http";

and function:

getParam(){
  let params = new URLSearchParams(window.location.search);
  let someParam = params.get('someParam');
  return someParam;
}

Notice: It's not supported by all platforms and seems to be in "EXPERIMENTAL" state by angular docs

Error QApplication: no such file or directory

I suggest you to update your SDK and start new project and recompile everything you have. It seems you have some inner program errors. Or you are missing package.

And ofc do what Abdijeek said.

How to force IE10 to render page in IE9 document mode

there are many ways can do this:

add X-UA-Compatible tag to head http response header

using IE tools F12

change windows Registry

Binding multiple events to a listener (without JQuery)?

I have a simpler solution for you:

window.onload = window.onresize = (event) => {
    //Your Code Here
}

I've tested this an it works great, on the plus side it's compact and uncomplicated like the other examples here.

Check if all elements in a list are identical

Use itertools.groupby (see the itertools recipes):

from itertools import groupby
def all_equal(iterable):
    g = groupby(iterable)
    return next(g, True) and not next(g, False)

or without groupby:

def all_equal(iterator):
    iterator = iter(iterator)
    try:
        first = next(iterator)
    except StopIteration:
        return True
    return all(first == rest for rest in iterator)

There are a number of alternative one-liners you might consider:

  1. Converting the input to a set and checking that it only has one or zero (in case the input is empty) items

    def all_equal2(iterator):
        return len(set(iterator)) <= 1
    
  2. Comparing against the input list without the first item

    def all_equal3(lst):
        return lst[:-1] == lst[1:]
    
  3. Counting how many times the first item appears in the list

    def all_equal_ivo(lst):
        return not lst or lst.count(lst[0]) == len(lst)
    
  4. Comparing against a list of the first element repeated

    def all_equal_6502(lst):
        return not lst or [lst[0]]*len(lst) == lst
    

But they have some downsides, namely:

  1. all_equal and all_equal2 can use any iterators, but the others must take a sequence input, typically concrete containers like a list or tuple.
  2. all_equal and all_equal3 stop as soon as a difference is found (what is called "short circuit"), whereas all the alternatives require iterating over the entire list, even if you can tell that the answer is False just by looking at the first two elements.
  3. In all_equal2 the content must be hashable. A list of lists will raise a TypeError for example.
  4. all_equal2 (in the worst case) and all_equal_6502 create a copy of the list, meaning you need to use double the memory.

On Python 3.9, using perfplot, we get these timings (lower Runtime [s] is better):

for a list with a difference in the first two elements, groupby is fastestfor a list with no differences, count(l[0]) is fastest

Visual Studio Code open tab in new window

Just an update, Feb 1, 2019: cmd+shift+n on Mac now opens a new window where you can drag over tabs. I didn't find that out until I when through KyleMit's response and saw his key mapping suggestion was already mapped to the correct action.

Creating a SearchView that looks like the material design guidelines

Another way you can achieve the desired effect is to use this Material Search View library. It handles search history automatically and it's possible to provide search suggestions to the view as well.

Sample: (It's shown in Portuguese, but it also works in english and italian).

Sample

Setup

Before you can use this lib, you have to implement a class named MsvAuthority inside the br.com.mauker package on your app module, and it should have a public static String variable called CONTENT_AUTHORITY. Give it the value you want and don't forget to add the same name on your manifest file. The lib will use this file to set the Content Provider authority.

Example:

MsvAuthority.java

package br.com.mauker;

public class MsvAuthority {
    public static final String CONTENT_AUTHORITY = "br.com.mauker.materialsearchview.searchhistorydatabase";
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>

    <application ... >
        <provider
        android:name="br.com.mauker.materialsearchview.db.HistoryProvider"
        android:authorities="br.com.mauker.materialsearchview.searchhistorydatabase"
        android:exported="false"
        android:protectionLevel="signature"
        android:syncable="true"/>
    </application>

</manifest>

Usage

To use it, add the dependency:

compile 'br.com.mauker.materialsearchview:materialsearchview:1.2.0'

And then, on your Activity layout file, add the following:

<br.com.mauker.materialsearchview.MaterialSearchView
    android:id="@+id/search_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

After that, you'll just need to get the MaterialSearchView reference by using getViewById(), and open it up or close it using MaterialSearchView#openSearch() and MaterialSearchView#closeSearch().

P.S.: It's possible to open and close the view not only from the Toolbar. You can use the openSearch() method from basically any Button, such as a Floating Action Button.

// Inside onCreate()
MaterialSearchView searchView = (MaterialSearchView) findViewById(R.id.search_view);
Button bt = (Button) findViewById(R.id.button);

bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            searchView.openSearch();
        }
    });

You can also close the view using the back button, doing the following:

@Override
public void onBackPressed() {
    if (searchView.isOpen()) {
        // Close the search on the back button press.
        searchView.closeSearch();
    } else {
        super.onBackPressed();
    }
}

For more information on how to use the lib, check the github page.

Where should I put <script> tags in HTML markup?

The best place to write your JavaScript code is at the end of the document after or right before the </body> tag to load the document first and then execute js code.

<script> ... your code here ... </script>
</body>

And if you write in JQuery the following can be in the head document and it will execute after the document loads:

<script>
$(document).ready(function(){
   //your code here...
});
</script>

PHPMailer character encoding issues

I work myself this way

  $mail->FromName = utf8_decode($_POST['name']);

http://php.net/manual/en/function.utf8-decode.php

Java URL encoding of query string parameters

URLEncoder is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.

String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);

When you're still not on Java 10 or newer, then use StandardCharsets.UTF_8.toString() as charset argument, or when you're still not on Java 7 or newer, then use "UTF-8".


Note that spaces in query parameters are represented by +, not %20, which is legitimately valid. The %20 is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?), not in query string (the part after ?).

Also note that there are three encode() methods. One without Charset as second argument and another with String as second argument which throws a checked exception. The one without Charset argument is deprecated. Never use it and always specify the Charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.

All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

See also:

Where does the @Transactional annotation belong?

The normal case would be to annotate on a service layer level, but this really depends on your requirements.

Annotating on a service layer will result in longer transactions than annotating on DAO level. Depending on the transaction isolation level that can youse problems, as concurrent transactions wont see each other's changes in eg. REPEATABLE READ.

Annotating on the DAOs will keep the transactions as short as possible, with the drawback that the functionality your service layer is exposing wont be done in a single (rollbackable) transaction.

It does not make sense to annotate both layers if the propagation mode is set to default.

How to set bot's status

    client.user.setStatus('dnd', 'Made by KwinkyWolf') 

And change 'dnd' to whatever status you want it to have. And then the next field 'Made by KwinkyWolf' is where you change the game. Hope this helped :)

List of status':

  • online
  • idle
  • dnd
  • invisible

Not sure if they're still the same, or if there's more but hope that helped too :)

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.

  • It Keeps the photos aspect ratio
  • Scales in vertical and horizontal
  • Centers vertically and horizontal
  • The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.

    Give it a try :)

*only tested in chrome so far

HTML:

<div class="frame">
  <img src="image.jpg"/>
</div>

CSS:

.frame {
  border: 1px solid red;

  min-height: 98%;
  max-height: 98%;
  min-width: 99%;
  max-width: 99%;

  text-align: center;
  margin: auto;
  position: absolute;
}
img {
  border: 1px solid blue;

  min-height: 98%;
  max-width: 99%;
  max-height: 98%;

  width: auto;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

How to make a list of n numbers in Python and randomly select any number?

You can create the enumeration of the elements by something like this:

mylist = list(xrange(10))

Then you can use the random.choice function to select your items:

import random
...
random.choice(mylist)

As Asim Ihsan correctly stated, my answer did not address the full problem of the OP. To remove the values from the list, simply list.remove() can be called:

import random
...
value = random.choice(mylist)
mylist.remove(value)

As takataka pointed out, the xrange builtin function was renamed to range in Python 3.

What is the default text size on Android?

In general:

Three "default" textSize values:

 - 14sp
 - 18sp
 - 22sp

These values are defined within the following TextAppearances:

 - TextAppearance.Small
 - TextAppearance.Medium
 - TextAppearance.Large

More information about Typography can be found in the design guidelines

Related to your question:

If you don't set a custom textSize or textAppearance, TextAppearance.Small will be used.


Update: Material design:

New guidelines related to font and typefaces. The standard rule of 14sp remains (body).

Examples how to set textappearances

AppCompat version:

android:textAppearance="@style/TextAppearance.AppCompat.Body"

Lollipop and up version:

android:textAppearance="@android:style/TextAppearance.Material.Body"

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

I did below modifications and I am able to start the Hive Shell without any errors:

1. ~/.bashrc

Inside bashrc file add the below environment variables at End Of File : sudo gedit ~/.bashrc

#Java Home directory configuration
export JAVA_HOME="/usr/lib/jvm/java-9-oracle"
export PATH="$PATH:$JAVA_HOME/bin"

# Hadoop home directory configuration
export HADOOP_HOME=/usr/local/hadoop
export PATH=$PATH:$HADOOP_HOME/bin
export PATH=$PATH:$HADOOP_HOME/sbin

export HIVE_HOME=/usr/lib/hive
export PATH=$PATH:$HIVE_HOME/bin

2. hive-site.xml

You have to create this file(hive-site.xml) in conf directory of Hive and add the below details

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<configuration>

<property>
  <name>javax.jdo.option.ConnectionURL</name>
  <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
</property>


<property>
  <name>javax.jdo.option.ConnectionDriverName</name>
  <value>com.mysql.jdbc.Driver</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionUserName</name>
  <value>root</value>
</property>

<property>
  <name>javax.jdo.option.ConnectionPassword</name>
  <value>root</value>
</property>

<property>
  <name>datanucleus.autoCreateSchema</name>
  <value>true</value>
</property>

<property>
  <name>datanucleus.fixedDatastore</name>
  <value>true</value>
</property>

<property>
 <name>datanucleus.autoCreateTables</name>
 <value>True</value>
 </property>

</configuration>

3. You also need to put the jar file(mysql-connector-java-5.1.28.jar) in the lib directory of Hive

4. Below installations required on your Ubuntu to Start the Hive Shell:

  1. MySql
  2. Hadoop
  3. Hive
  4. Java

5. Execution Part:

  1. Start all services of Hadoop: start-all.sh

  2. Enter the jps command to check whether all Hadoop services are up and running: jps

  3. Enter the hive command to enter into hive shell: hive

How do you run CMD.exe under the Local System Account?

There is another way. There is a program called PowerRun which allows for elevated cmd to be run. Even with TrustedInstaller rights. It allows for both console and GUI commands.

How to edit HTML input value colour?

Maybe something like this (just add your style):

<input type="text" 
       size="35" 
       value="Job Title e.g. Assistant Manager" 
       style="background-color:white; 
              border: solid 1px #6E6E6E;
              height: 30px; 
              font-size:18px; 
              vertical-align:9px;color:#bbb" 
        onfocus="if(this.value == 'Job Title e.g. Assistant Manager') {
                    this.value = '';
                    this.style.color='#000';
                 }" />

<input type="text" 
       name="searchterm" size="35" 
       style="background-color:white; 
              border: solid 1px #6E6E6E;
              height: 30px; 
              font-size:18px; 
              vertical-align:9px" />

UPDATE: Since placeholder attribute is very well supported on all major browsers, there is no need to do anything manually. Its possible to achieve the same thing with this:

<input type="text" 
       size="35" 
       placeholder="Job Title e.g. Assistant Manager" />

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

Optimistic vs. Pessimistic locking

There are basically two most popular answers. The first one basically says

Optimistic needs a three-tier architectures where you do not necessarily maintain a connection to the database for your session whereas Pessimistic Locking is when you lock the record for your exclusive use until you have finished with it. It has much better integrity than optimistic locking you need either a direct connection to the database.

Another answer is

optimistic (versioning) is faster because of no locking but (pessimistic) locking performs better when contention is high and it is better to prevent the work rather than discard it and start over.

or

Optimistic locking works best when you have rare collisions

As it is put on this page.

I created my answer to explain how "keep connection" is related to "low collisions".

To understand which strategy is best for you, think not about the Transactions Per Second your DB has but the duration of a single transaction. Normally, you open trasnaction, performa operation and close the transaction. This is a short, classical transaction ANSI had in mind and fine to get away with locking. But, how do you implement a ticket reservation system where many clients reserve the same rooms/seats at the same time?

You browse the offers, fill in the form with lots of available options and current prices. It takes a lot of time and options can become obsolete, all the prices invalid between you started to fill the form and press "I agree" button because there was no lock on the data you have accessed and somebody else, more agile, has intefered changing all the prices and you need to restart with new prices.

You could lock all the options as you read them, instead. This is pessimistic scenario. You see why it sucks. Your system can be brought down by a single clown who simply starts a reservation and goes smoking. Nobody can reserve anything before he finishes. Your cash flow drops to zero. That is why, optimistic reservations are used in reality. Those who dawdle too long have to restart their reservation at higher prices.

In this optimistic approach you have to record all the data that you read (as in mine Repeated Read) and come to the commit point with your version of data (I want to buy shares at the price you displayed in this quote, not current price). At this point, ANSI transaction is created, which locks the DB, checks if nothing is changed and commits/aborts your operation. IMO, this is effective emulation of MVCC, which is also associated with Optimistic CC and also assumes that your transaction restarts in case of abort, that is you will make a new reservation. A transaction here involves a human user decisions.

I am far from understanding how to implement the MVCC manually but I think that long-running transactions with option of restart is the key to understanding the subject. Correct me if I am wrong anywhere. My answer was motivated by this Alex Kuznecov chapter.

Reading data from XML

I don't think you can "legally" load only part of an XML file, since then it would be malformed (there would be a missing closing element somewhere).

Using LINQ-to-XML, you can do var doc = XDocument.Load("yourfilepath"). From there its just a matter of querying the data you want, say like this:

var authors = doc.Root.Elements().Select( x => x.Element("Author") );

HTH.

EDIT:

Okay, just to make this a better sample, try this (with @JWL_'s suggested improvement):

using System;
using System.Xml.Linq;

namespace ConsoleApplication1 {
    class Program {
        static void Main( string[] args )  {
            XDocument doc = XDocument.Load( "XMLFile1.xml" );
            var authors = doc.Descendants( "Author" );
            foreach ( var author in authors ) {
                Console.WriteLine( author.Value );
            }
            Console.ReadLine();
        }
    }
}

You will need to adjust the path in XDocument.Load() to point to your XML file, but the rest should work. Ask questions about which parts you don't understand.

A generic list of anonymous class

Here is the answer.

string result = String.Empty;

var list = new[]
{ 
    new { Number = 10, Name = "Smith" },
    new { Number = 10, Name = "John" } 
}.ToList();

foreach (var item in list)
{
    result += String.Format("Name={0}, Number={1}\n", item.Name, item.Number);
}

MessageBox.Show(result);

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Has Facebook sharer.php changed to no longer accept detailed parameters?

I review your url in use:

https://www.facebook.com/sharer/sharer.php?s=100&p[title]=EXAMPLE&p[summary]=EXAMPLE&p[url]=EXAMPLE&p[images][0]=EXAMPLE

and see this differences:

  1. The sharer URL not is same.
  2. The strings are in different order. ( Do not know if this affects ).

I use this URL string:

http://www.facebook.com/sharer.php?s=100&p[url]=http://www.example.com/&p[images][0]=/images/image.jpg&p[title]=Title&p[summary]=Summary

In the "title" and "summary" section, I use the php function urlencode(); like this:

<?php echo urlencode($detail->title); ?>

And working fine for me.

Loop through an array php

foreach($array as $item=>$values){
     echo $values->filepath;
    }

Oracle SQL update based on subquery between two tables

There are two ways to do what you are trying

One is a Multi-column Correlated Update

UPDATE PRODUCTION a
SET (name, count) = (
  SELECT name, count
  FROM STAGING b
  WHERE a.ID = b.ID);

DEMO

You can use merge

MERGE INTO PRODUCTION a
USING ( select id, name, count 
          from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN 
UPDATE SET  a.name = b.name,
            a.count = b.count

DEMO

How to check if a String is numeric in Java

I have illustrated some conditions to check numbers and decimals without using any API,

Check Fix Length 1 digit number

Character.isDigit(char)

Check Fix Length number (Assume length is 6)

String number = "132452";
if(number.matches("([0-9]{6})"))
System.out.println("6 digits number identified");

Check Varying Length number between (Assume 4 to 6 length)

//  {n,m}  n <= length <= m
String number = "132452";
if(number.matches("([0-9]{4,6})"))
System.out.println("Number Identified between 4 to 6 length");

String number = "132";
if(!number.matches("([0-9]{4,6})"))
System.out.println("Number not in length range or different format");

Check Varying Length decimal number between (Assume 4 to 7 length)

//  It will not count the '.' (Period) in length
String decimal = "132.45";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1.12";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1234";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "-10.123";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "123..4";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "132";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "1.1";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

Hope it will help manyone.

Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable

I had the same problem. The solution turned out to be much simpler. It appears that a datatable wants the method in the form of a getter, ie getSomeMethod(), not just someMethod(). In my case in the datatable I was calling findResults. I changed the method in my backing bean to getFindResults() and it worked.

A commandButton worked find without the get which served to make it only more confusing.

How do you use NSAttributedString?

You can load an HTML attributed string in Swift as follow

   var Str = NSAttributedString(
   data: htmlstring.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
   options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
   documentAttributes: nil,
   error: nil)

   label.attributedText = Str  

To load a html from file

   if let rtf = NSBundle.mainBundle().URLForResource("rtfdoc", withExtension: "rtf", subdirectory: nil, localization: nil) {

   let attributedString = NSAttributedString(fileURL: rtf, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil, error: nil)
        textView.attributedText = attributedString
        textView.editable = false
    }

http://sketchytech.blogspot.in/2013/11/creating-nsattributedstring-from-html.html

And setup string as per your required attribute....follow this..
http://makeapppie.com/2014/10/20/swift-swift-using-attributed-strings-in-swift/

Is there any way to do HTTP PUT in python

You can of course roll your own with the existing standard libraries at any level from sockets up to tweaking urllib.

http://pycurl.sourceforge.net/

"PyCurl is a Python interface to libcurl."

"libcurl is a free and easy-to-use client-side URL transfer library, ... supports ... HTTP PUT"

"The main drawback with PycURL is that it is a relative thin layer over libcurl without any of those nice Pythonic class hierarchies. This means it has a somewhat steep learning curve unless you are already familiar with libcurl's C API. "

How to get current time in milliseconds in PHP?

Use microtime. This function returns a string separated by a space. The first part is the fractional part of seconds, the second part is the integral part. Pass in true to get as a number:

var_dump(microtime());       // string(21) "0.89115400 1283846202"
var_dump(microtime(true));   // float(1283846202.89)

Beware of precision loss if you use microtime(true).

There is also gettimeofday that returns the microseconds part as an integer.

var_dump(gettimeofday());
/*
array(4) {
  ["sec"]=>
  int(1283846202)
  ["usec"]=>
  int(891199)
  ["minuteswest"]=>
  int(-60)
  ["dsttime"]=>
  int(1)
}
*/

Aligning text and image on UIButton with imageEdgeInsets and titleEdgeInsets

Also if you want to make something similar to

enter image description here

You need

1.Set horizontal and vertical alignment for button to

enter image description here

  1. Find all required values and set UIImageEdgeInsets

            CGSize buttonSize = button.frame.size;
            NSString *buttonTitle = button.titleLabel.text;
            CGSize titleSize = [buttonTitle sizeWithAttributes:@{ NSFontAttributeName : [UIFont camFontZonaProBoldWithSize:12.f] }];
            UIImage *buttonImage = button.imageView.image;
            CGSize buttonImageSize = buttonImage.size;
    
            CGFloat offsetBetweenImageAndText = 10; //vertical space between image and text
    
            [button setImageEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 - offsetBetweenImageAndText,
                                                        (buttonSize.width - buttonImageSize.width) / 2,
                                                        0,0)];                
            [button setTitleEdgeInsets:UIEdgeInsetsMake((buttonSize.height - (titleSize.height + buttonImageSize.height)) / 2 + buttonImageSize.height + offsetBetweenImageAndText,
                                                        titleSize.width + [button imageEdgeInsets].left > buttonSize.width ? -buttonImage.size.width  +  (buttonSize.width - titleSize.width) / 2 : (buttonSize.width - titleSize.width) / 2 - buttonImage.size.width,
                                                        0,0)];
    

This will arrange your title and image on button.

Also please note update this on each relayout


Swift

import UIKit

extension UIButton {
    // MARK: - UIButton+Aligment

    func alignContentVerticallyByCenter(offset:CGFloat = 10) {
        let buttonSize = frame.size

        if let titleLabel = titleLabel,
            let imageView = imageView {

            if let buttonTitle = titleLabel.text,
                let image = imageView.image {
                let titleString:NSString = NSString(string: buttonTitle)
                let titleSize = titleString.sizeWithAttributes([
                    NSFontAttributeName : titleLabel.font
                    ])
                let buttonImageSize = image.size

                let topImageOffset = (buttonSize.height - (titleSize.height + buttonImageSize.height + offset)) / 2
                let leftImageOffset = (buttonSize.width - buttonImageSize.width) / 2
                imageEdgeInsets = UIEdgeInsetsMake(topImageOffset,
                                                   leftImageOffset,
                                                   0,0)

                let titleTopOffset = topImageOffset + offset + buttonImageSize.height
                let leftTitleOffset = (buttonSize.width - titleSize.width) / 2 - image.size.width

                titleEdgeInsets = UIEdgeInsetsMake(titleTopOffset,
                                                   leftTitleOffset,
                                                   0,0)
            }
        }
    }
}

Linux: is there a read or recv from socket with timeout?

You can use the setsockopt function to set a timeout on receive operations:

SO_RCVTIMEO

Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. It accepts a timeval structure with the number of seconds and microseconds specifying the limit on how long to wait for an input operation to complete. If a receive operation has blocked for this much time without receiving additional data, it shall return with a partial count or errno set to [EAGAIN] or [EWOULDBLOCK] if no data is received. The default for this option is zero, which indicates that a receive operation shall not time out. This option takes a timeval structure. Note that not all implementations allow this option to be set.

// LINUX
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

// WINDOWS
DWORD timeout = timeout_in_seconds * 1000;
setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

// MAC OS X (identical to Linux)
struct timeval tv;
tv.tv_sec = timeout_in_seconds;
tv.tv_usec = 0;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);

Reportedly on Windows this should be done before calling bind. I have verified by experiment that it can be done either before or after bind on Linux and OS X.

Add column with constant value to pandas dataframe

The reason this puts NaN into a column is because df.index and the Index of your right-hand-side object are different. @zach shows the proper way to assign a new column of zeros. In general, pandas tries to do as much alignment of indices as possible. One downside is that when indices are not aligned you get NaN wherever they aren't aligned. Play around with the reindex and align methods to gain some intuition for alignment works with objects that have partially, totally, and not-aligned-all aligned indices. For example here's how DataFrame.align() works with partially aligned indices:

In [7]: from pandas import DataFrame

In [8]: from numpy.random import randint

In [9]: df = DataFrame({'a': randint(3, size=10)})

In [10]:

In [10]: df
Out[10]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [11]: s = df.a[:5]

In [12]: dfa, sa = df.align(s, axis=0)

In [13]: dfa
Out[13]:
   a
0  0
1  2
2  0
3  1
4  0
5  0
6  0
7  0
8  0
9  0

In [14]: sa
Out[14]:
0     0
1     2
2     0
3     1
4     0
5   NaN
6   NaN
7   NaN
8   NaN
9   NaN
Name: a, dtype: float64

How do I find which program is using port 80 in Windows?

If you want to be really fancy, download TCPView from Sysinternals:

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, and XP, TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows.

excel vba getting the row,cell value from selection.address

Is this what you are looking for ?

Sub getRowCol()

    Range("A1").Select ' example

    Dim col, row
    col = Split(Selection.Address, "$")(1)
    row = Split(Selection.Address, "$")(2)

    MsgBox "Column is : " & col
    MsgBox "Row is : " & row

End Sub

How do you read scanf until EOF in C?

Try:

while(scanf("%15s", words) != EOF)

You need to compare scanf output with EOF

Since you are specifying a width of 15 in the format string, you'll read at most 15 char. So the words char array should be of size 16 ( 15 +1 for null char). So declare it as:

char words[16];

How to get the file-path of the currently executing javascript code

I may be misunderstanding your question but it seems you should just be able to use a relative path as long as the production and development servers use the same path structure.

<script language="javascript" src="js/myLib.js" />

Jquery show/hide table rows

The filter function wasn't working for me at all; maybe the more recent version of jquery doesn't perform as the version used in above code. Regardless; I used:

    var black = $('.black');
    var white = $('.white');

The selector will find every element classed under black or white. Button functions stay as stated above:

    $('#showBlackButton').click(function() {
           black.show();
           white.hide();
    });

    $('#showWhiteButton').click(function() {
           white.show();
           black.hide();
    });

Best way to store time (hh:mm) in a database

You could store it as an integer of the number of minutes past midnight:

eg.

0 = 00:00 
60 = 01:00
252 = 04:12

You would however need to write some code to reconstitute the time, but that shouldn't be tricky.

Does Java have a complete enum for HTTP response codes?

The Interface javax.servlet.http.HttpServletResponse from the servlet API has all the response codes in the form of int constants names SC_<description>. See http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html

Input length must be multiple of 16 when decrypting with padded cipher

Had a similar issue. But it is important to understand the root cause and it may vary for different use cases.

Scenario 1
You are trying to decrypt a value which was not encoded correctly in the first place.

byte[] encryptedBytes = Base64.decodeBase64(encryptedBase64String);

If the String is misconfigured for certain reason or has not been encoded correctly, you would see the error " Input length must be multiple of 16 when decrypting with padded cipher"

Scenario 2
Now if by any chance you are using this encoded string in url (trying to pass in the base64Encoded value in url, it will fail. You should do URLEncoding and then pass in the token, it will work.

Scenario 3
When integrating with one of the vendors, we found that we had to do encryption of Base64 using URLEncoder but then we need not decode it because it was done internally by the Vendor

Last segment of URL in jquery

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1));

Use the native pathname property because it's simplest and has already been parsed and resolved by the browser. $(this).attr("href") can return values like ../.. which would not give you the correct result.

If you need to keep the search and hash (e.g. foo?bar#baz from http://quux.com/path/to/foo?bar#baz) use this:

window.alert(this.pathname.substr(this.pathname.lastIndexOf('/') + 1) + this.search + this.hash);

Rounding a double value to x number of decimal places in swift

Building on Yogi's answer, here's a Swift function that does the job:

func roundToPlaces(value:Double, places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return round(value * divisor) / divisor
}

Bitbucket fails to authenticate on git pull

You need to reset the password as shown below.

On macOS:

git config --global credential.helper osxkeychain

On Windows 10:

git config --global credential.helper store

After executing this, it prompts you for the user name and password for your repo.

How to split() a delimited string to a List<String>

Either use:

List<string> list = new List<string>(array);

or from LINQ:

List<string> list = array.ToList();

Or change your code to not rely on the specific implementation:

IList<string> list = array; // string[] implements IList<string>

how to make negative numbers into positive

a *= (-1);

problem solved. If there is a smaller solution for a problem, then why you guys going for a complex solution. Please direct people to use the base logic also because then only the people can train their programming logic.

Link to "pin it" on pinterest without generating a button

So you want the code to the pin it button without installing the button? If so just paste this code in the place of the url of the page you're pinning from. It should function as a pin it button without the button.

javascript:void((function(){var%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)})());

Uncaught TypeError: Cannot read property 'value' of undefined

Try this, It always works, and you will get NO TypeError:

try{

    var i1 = document.getElementById('i1');
    var i2 = document.getElementById('i2');
    var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
    if(  __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
    if(  __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }

}catch(e){
    if(e){
    // If fails, Do something else
    }
}

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

Below the function for taking snapshot a specific element in Selenium. Here the driver is a type of WebDriver.

private static void getScreenshot(final WebElement e, String fileName) throws IOException {
  final BufferedImage img;
  final Point topleft;
  final Point bottomright;
  final byte[] screengrab;
  screengrab = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
  img = ImageIO.read(new ByteArrayInputStream(screengrab));
  topleft = e.getLocation();
  bottomright = new Point(e.getSize().getWidth(), e.getSize().getHeight());
  BufferedImage imgScreenshot= 
      (BufferedImage)img.getSubimage(topleft.getX(), topleft.getY(), bottomright.getX(), bottomright.getY());
  File screenshotLocation = new File("Images/"+fileName +".png");    
  ImageIO.write(imgScreenshot, "png", screenshotLocation);
 }

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

How to combine date from one field with time from another field - MS SQL Server

Convert both field into DATETIME :

SELECT CAST(@DateField as DATETIME) + CAST(@TimeField AS DATETIME)

and if you're using Getdate() use this first:

DECLARE @FechaActual DATETIME = CONVERT(DATE, GETDATE());
SELECT CAST(@FechaActual as DATETIME) + CAST(@HoraInicioTurno AS DATETIME)

Select max value of each group

SELECT
  b.name,
  MAX(b.value) as MaxValue,
  MAX(b.Anothercolumn) as AnotherColumn
FROM out_pumptabl
INNER JOIN (SELECT 
              name,
              MAX(value) as MaxValue
            FROM out_pumptabl
            GROUP BY Name) a ON 
  a.name = b.name AND a.maxValue = b.value
GROUP BY b.Name

Note this would be far easier if you had a primary key. Here is an Example

SELECT * FROM out_pumptabl c
WHERE PK in 
    (SELECT
      MAX(PK) as MaxPK
    FROM out_pumptabl b
    INNER JOIN (SELECT 
                  name,
                  MAX(value) as MaxValue
                FROM out_pumptabl
                GROUP BY Name) a ON 
      a.name = b.name AND a.maxValue = b.value) 

ORA-30926: unable to get a stable set of rows in the source tables

Had the error today on a 12c and none of the existing answers fit (no duplicates, no non-deterministic expressions in the WHERE clause). My case was related to that other possible cause of the error, according to Oracle's message text (emphasis below):

ORA-30926: unable to get a stable set of rows in the source tables
Cause: A stable set of rows could not be got because of large dml activity or a non-deterministic where clause.

The merge was part of a larger batch, and was executed on a live database with many concurrent users. There was no need to change the statement. I just committed the transaction before the merge, then ran the merge separately, and committed again. So the solution was found in the suggested action of the message:

Action: Remove any non-deterministic where clauses and reissue the dml.

Why specify @charset "UTF-8"; in your CSS file?

One reason to always include a character set specification on every page containing text is to avoid cross site scripting vulnerabilities. In most cases the UTF-8 character set is the best choice for text, including HTML pages.

if statements matching multiple values

Easier is subjective, but maybe the switch statement would be easier? You don't have to repeat the variable, so more values can fit on the line, and a line with many comparisons is more legible than the counterpart using the if statement.

Printing everything except the first field with awk

Maybe the most concise way:

$ awk '{$(NF+1)=$1;$1=""}sub(FS,"")' infile
United Arab Emirates AE
Antigua & Barbuda AG
Netherlands Antilles AN
American Samoa AS
Bosnia and Herzegovina BA
Burkina Faso BF
Brunei Darussalam BN

Explanation:

$(NF+1)=$1: Generator of a "new" last field.

$1="": Set the original first field to null

sub(FS,""): After the first two actions {$(NF+1)=$1;$1=""} get rid of the first field separator by using sub. The final print is implicit.

How to change Oracle default data pump directory to import dumpfile?

use DIRECTORY option.

Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907

  DIRECTORY

  Default: DATA_PUMP_DIR

  Purpose

  Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.

  Syntax and Description

  DIRECTORY=directory_object
  The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.

  A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.

  Example

  The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".

  > impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp 
  LOGFILE=dpump_dir2:expfull.log
  This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.

Most concise way to test string equality (not object equality) for Ruby strings or symbols?

Your code sample didn't expand on part of your topic, namely symbols, and so that part of the question went unanswered.

If you have two strings, foo and bar, and both can be either a string or a symbol, you can test equality with

foo.to_s == bar.to_s

It's a little more efficient to skip the string conversions on operands with known type. So if foo is always a string

foo == bar.to_s

But the efficiency gain is almost certainly not worth demanding any extra work on behalf of the caller.

Prior to Ruby 2.2, avoid interning uncontrolled input strings for the purpose of comparison (with strings or symbols), because symbols are not garbage collected, and so you can open yourself to denial of service through resource exhaustion. Limit your use of symbols to values you control, i.e. literals in your code, and trusted configuration properties.

Ruby 2.2 introduced garbage collection of symbols.

HEAD and ORIG_HEAD in Git

From git reset

"pull" or "merge" always leaves the original tip of the current branch in ORIG_HEAD.

git reset --hard ORIG_HEAD

Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.

git reset --merge ORIG_HEAD

After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "git reset --hard ORIG_HEAD" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge" keeps your local changes.


Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
This is useful if you have problems with multiple commits, like running 'git am' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).

In addition, merge always sets '.git/ORIG_HEAD' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD'.


Note: from here

HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.

So HEAD is NOT a synonym for "current branch" everywhere already.

HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).

But it almost always means the "current commit".
It is the commit "git commit" builds on top of, and "git diff --cached" and "git status" compare against.
It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).

Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".

HEAD@{5.minutes.ago} could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".


git1.8.4 (July 2013) introduces introduced a new notation!
(Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.

Instead of typing four capital letters "HEAD", you can say "@" now,
e.g. "git log @".

See commit cdfd948

Typing 'HEAD' is tedious, especially when we can use '@' instead.

The reason for choosing '@' is that it follows naturally from the ref@op syntax (e.g. HEAD@{u}), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD'.

So now we can use 'git show @~1', and all that goody goodness.

Until now '@' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.

Getting data from selected datagridview row and which event?

You can use SelectionChanged event since you are using FullRowSelect selection mode. Than inside the handler you can access SelectedRows property and get data from it. Example:

private void dataGridView_SelectionChanged(object sender, EventArgs e) 
{
    foreach (DataGridViewRow row in dataGridView.SelectedRows) 
    {
        string value1 = row.Cells[0].Value.ToString();
        string value2 = row.Cells[1].Value.ToString();
        //...
    }
}

You can also walk through the column collection instead of typing indexes...

Storing and retrieving datatable from session

You can do it like that but storing a DataSet object in Session is not very efficient. If you have a web app with lots of users it will clog your server memory really fast.

If you really must do it like that I suggest removing it from the session as soon as you don't need the DataSet.

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Interface means a class that has no implementation of its method, but with just declaration.
Other hand, abstract class is a class that can have implementation of some method along with some method with just declaration, no implementation.
When we implement an interface to an abstract class, its means that the abstract class inherited all the methods of the interface. As, it is not important to implement all the method in abstract class however it comes to abstract class (by inheritance too), so the abstract class can left some of the method in interface without implementation here. But, when this abstract class will inherited by some concrete class, they must have to implements all those unimplemented method there in abstract class.

How do you set, clear, and toggle a single bit?

Using the Standard C++ Library: std::bitset<N>.

Or the Boost version: boost::dynamic_bitset.

There is no need to roll your own:

#include <bitset>
#include <iostream>

int main()
{
    std::bitset<5> x;

    x[1] = 1;
    x[2] = 0;
    // Note x[0-4]  valid

    std::cout << x << std::endl;
}

[Alpha:] > ./a.out
00010

The Boost version allows a runtime sized bitset compared with a standard library compile-time sized bitset.

How to run a Runnable thread in Android at defined intervals?

Kotlin with Coroutines

In Kotlin, using coroutines you can do the following:

CoroutineScope(Dispatchers.Main).launch { // Main, because UI is changed
    ticker(delayMillis = 1000, initialDelayMillis = 1000).consumeEach {
        tv.append("Hello World")
    }
}

Try it out here!

How to use "raise" keyword in Python

You can use it to raise errors as part of error-checking:

if (a < b):
    raise ValueError()

Or handle some errors, and then pass them on as part of error-handling:

try:
    f = open('file.txt', 'r')
except IOError:
    # do some processing here
    # and then pass the error on
    raise

Option to ignore case with .contains method?

You can apply little trick over this.
Change all the string to same case: either upper or lower case
For C# Code:

List searchResults = sl.FindAll(s => s.ToUpper().Contains(seachKeyword.ToUpper()));

For Java Code:

import java.util.*; 

class Test
{
    public static void main(String[] args)
    {
        String itemCheck="check";
        ArrayList<String> listItem =new ArrayList<String>();
        listItem.add("Check");
        listItem.add("check");
        listItem.add("CHeck");
        listItem.add("Make");
        listItem.add("CHecK");
        for(String item :listItem)
        {
            if(item.toUpperCase().equals(itemCheck.toUpperCase()))
            {
                System.out.println(item);
            }
        }

    }

}

What do Push and Pop mean for Stacks?

Hopefully this will help you visualize a Stack, and how it works.

Empty Stack:

|     |
|     |
|     |
-------

After Pushing A, you get:

|     |
|     |
|  A  |
-------

After Pushing B, you get:

|     |
|  B  |
|  A  |
-------

After Popping, you get:

|     |
|     |
|  A  |
-------

After Pushing C, you get:

|     |
|  C  |
|  A  |
-------

After Popping, you get:

|     |
|     |
|  A  |
-------

After Popping, you get:

|     |
|     |
|     |
-------

Trigger css hover with JS

I don't think what your asking is possible.

See: Hover Item with JQuery

Basically, adding a class is the only way to accomplish this that I am aware of.

Re-assign host access permission to MySQL user

I received the same error with RENAME USER and GRANTS aren't covered by the currently accepted solution:

The most reliable way seems to be to run SHOW GRANTS for the old user, find/replace what you want to change regarding the user's name and/or host and run them and then finally DROP USER the old user. Not forgetting to run FLUSH PRIVILEGES (best to run this after adding the new users' grants, test the new user, then drop the old user and flush again for good measure).

    > SHOW GRANTS FOR 'olduser'@'oldhost';
    +-----------------------------------------------------------------------------------+
    | Grants for olduser@oldhost                                                        |
    +-----------------------------------------------------------------------------------+
    | GRANT USAGE ON *.* TO 'olduser'@'oldhost' IDENTIFIED BY PASSWORD '*PASSHASH'      |
    | GRANT SELECT ON `db`.* TO 'olduser'@'oldhost'                                     |
    +-----------------------------------------------------------------------------------+
    2 rows in set (0.000 sec)

    > GRANT USAGE ON *.* TO 'newuser'@'newhost' IDENTIFIED BY PASSWORD '*SAME_PASSHASH';
    Query OK, 0 rows affected (0.006 sec)

    > GRANT SELECT ON `db`.* TO 'newuser'@'newhost';
    Query OK, 0 rows affected (0.007 sec)

    > DROP USER 'olduser'@'oldhost';
    Query OK, 0 rows affected (0.016 sec)

JFrame background image

You can do:

setContentPane(new JLabel(new ImageIcon("resources/taverna.jpg")));

At first line of the Jframe class constructor, that works fine for me

Git: can't undo local changes (error: path ... is unmerged)

This worked perfectly for me:

$ git reset -- foo/bar.txt
$ git checkout foo/bar.txt

Convert JS object to JSON string

The most popular way is below:

_x000D_
_x000D_
var obj = {name: "Martin", age: 30, country: "United States"};   _x000D_
// Converting JS object to JSON string_x000D_
var json = JSON.stringify(obj);_x000D_
console.log(json);
_x000D_
_x000D_
_x000D_

List<String> to ArrayList<String> conversion issue

First of all, why is the map a HashMap<String, ArrayList<String>> and not a HashMap<String, List<String>>? Is there some reason why the value must be a specific implementation of interface List (ArrayList in this case)?

Arrays.asList does not return a java.util.ArrayList, so you can't assign the return value of Arrays.asList to a variable of type ArrayList.

Instead of:

allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));

Try this:

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Node.js check if file exists

  fs.statSync(path, function(err, stat){
      if(err == null) {
          console.log('File exists');
          //code when all ok
      }else if (err.code == "ENOENT") {
        //file doesn't exist
        console.log('not file');

      }
      else {
        console.log('Some other error: ', err.code);
      }
    });

VBA check if file exists

For checking existence one can also use (works for both, files and folders):

Not Dir(DirFile, vbDirectory) = vbNullString

The result is True if a file or a directory exists.

Example:

If Not Dir("C:\Temp\test.xlsx", vbDirectory) = vbNullString Then
    MsgBox "exists"
Else
    MsgBox "does not exist"
End If

Call child component method from parent class - Angular

Angular – Call Child Component’s Method in Parent Component’s Template

You have ParentComponent and ChildComponent that looks like this.

parent.component.html

enter image description here

parent.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  constructor() {
  }
}

child.component.html

<p>
  This is child
</p>

child.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor() {
  }

  doSomething() {
    console.log('do something');
  }
}

When serve, it looks like this:

enter image description here

When user focus on ParentComponent’s input element, you want to call ChildComponent’s doSomething() method.

Simply do this:

  1. Give app-child selector in parent.component.html a DOM variable name (prefix with # – hashtag), in this case we call it appChild.
  2. Assign expression value (of the method you want to call) to input element’s focus event.

enter image description here

The result:

enter image description here

DateTime.MinValue and SqlDateTime overflow

If you use DATETIME2 you may find you have to pass the parameter in specifically as DATETIME2, otherwise it may helpfully convert it to DATETIME and have the same issue.

command.Parameters.Add("@FirstRegistration",SqlDbType.DateTime2).Value = installation.FirstRegistration;

Header and footer in CodeIgniter

Yes.

Create a file called template.php in your views folder.

The contents of template.php:

$this->load->view('templates/header');
$this->load->view($v);
$this->load->view('templates/footer');

Then from your controller you can do something like:

$d['v'] = 'body';
$this->load->view('template', $d);

This is actually a very simplistic version of how I personally load all of my views. If you take this idea to the extreme, you can make some interesting modular layouts:

Consider if you create a view called init.php that contains the single line:

$this->load->view('html');

Now create the view html.php with contents:

<!DOCTYPE html>
<html lang="en">
    <? $this->load->view('head'); ?>
    <? $this->load->view('body'); ?>
</html>

Now create a view head.php with contents:

<head>
<title><?= $title;?></title>
<base href="<?= site_url();?>">
<link rel="shortcut icon" href='favicon.ico'>
<script type='text/javascript'>//Put global scripts here...</script>
<!-- ETC ETC... DO A BUNCH OF OTHER <HEAD> STUFF... -->
</head>

And a body.php view with contents:

<body>
    <div id="mainWrap">
        <? $this->load->view('header'); ?>
        <? //FINALLY LOAD THE VIEW!!! ?>
        <? $this->load->view($v); ?>
        <? $this->load->view('footer'); ?>
    </div>
</body>

And create header.php and footer.php views as appropriate.

Now when you call the init from the controller all the heavy lifting is done and your views will be wrapped inside <html> and <body> tags, your headers and footers will be loaded in.

$d['v'] = 'fooview'
$this->load->view('init', $d);

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

It's the default formatting that Oracle provides. If you want leading zeros on output, you'll need to explicitly provide the format. Use:

SELECT TO_CHAR(0.56,'0.99') FROM DUAL;

or even:

SELECT TO_CHAR(.56,'0.99') FROM DUAL;

The same is true for trailing zeros:

SQL> SELECT TO_CHAR(.56,'0.990') val FROM DUAL;

VAL
------
 0.560

The general form of the TO_CHAR conversion function is:

TO_CHAR(number, format)

Automatically enter SSH password with script

The answer of @abbotto did not work for me, had to do some things differently:

  1. yum install sshpass changed to - rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/sshpass-1.05-1.el6.x86_64.rpm
  2. the command to use sshpass changed to - sshpass -p "pass" ssh user@mysite -p 2122

Assigning default value while creating migration file

Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":

class AddColumnToWidgets < ActiveRecord::Migration
  def change
    add_column :widgets, :colour, :string, default: 'red'
  end
end

This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.

Is Python faster and lighter than C++?

Also: Psyco vs. C++.

It's still a bad comparison, since noone would do the numbercrunchy stuff benchmarks tend to focus on in pure Python anyway. A better one would be comparing the performance of realistic applications, or C++ versus NumPy, to get an idea whether your program will be noticeably slower.

How to create a session using JavaScript?

<script type="text/javascript">
function myfunction()
{
    var IDSes= "10200";
    '<%Session["IDDiv"] = "' + $(this).attr('id') + '"; %>'
    '<%Session["IDSes"] = "' + IDSes+ '"; %>';
     alert('<%=Session["IDSes"] %>');
}
</script>

link

How to mock private method for testing using PowerMock?

i know a way ny which you can call you private function to test in mockito

@Test
    public  void  commandEndHandlerTest() throws  Exception
    {
        Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
        retryClientDetail_privateMethod.setAccessible(true);
        retryClientDetail_privateMethod.invoke(yourclass.class, null);
    }

How to use forEach in vueJs?

This is an example of forEach usage:

let arr = [];

this.myArray.forEach((value, index) => {
    arr.push(value);
    console.log(value);
    console.log(index);
});

In this case, "myArray" is an array on my data.

You can also loop through an array using filter, but this one should be used if you want to get a new list with filtered elements of your array.

Something like this:

const newArray = this.myArray.filter((value, index) => {
    console.log(value);
    console.log(index);
    if (value > 5) return true;
});

and the same can be written as:

const newArray = this.myArray.filter((value, index) => value > 5);

Both filter and forEach are javascript methods and will work just fine with VueJs. Also, it might be interesting taking a look at this:

https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Autoincrement VersionCode with gradle extra properties

Define versionName in AndroidManifest.xml

android:versionName="5.1.5"

Inside android{...} block in build.gradle of app level :

defaultConfig {
        applicationId "com.example.autoincrement"
        minSdkVersion 18
        targetSdkVersion 23
        multiDexEnabled true
        def version = getIncrementationVersionName()
        versionName version
}

Outside android{...} block in build.gradle of app level :

def getIncrementedVersionName() {
    List<String> runTasks = gradle.startParameter.getTaskNames();

    //find version name in manifest
    def manifestFile = file('src/main/AndroidManifest.xml')
    def matcher = Pattern.compile('versionName=\"(\\d+)\\.(\\d+)\\.(\\d+)\"').matcher(manifestFile.getText())
    matcher.find()

    //extract versionName parts
    def firstPart = Integer.parseInt(matcher.group(1))
    def secondPart = Integer.parseInt(matcher.group(2))
    def thirdPart = Integer.parseInt(matcher.group(3))

    //check is runTask release or not
    // if release - increment version
    for (String item : runTasks) {
        if (item.contains("assemble") && item.contains("Release")) {
            thirdPart++
            if (thirdPart == 10) {
                thirdPart = 0;
                secondPart++
                if (secondPart == 10) {
                    secondPart = 0;
                    firstPart++
                }
            }
        }
    }

    def versionName = firstPart + "." + secondPart + "." + thirdPart

    // update manifest
    def manifestContent = matcher.replaceAll('versionName=\"' + versionName + '\"')
    manifestFile.write(manifestContent)

    println "incrementVersionName = " + versionName

    return versionName
}

After create singed APK :

android:versionName="5.1.6"

Note : If your versionName different from my, you need change regex and extract parts logic.

how do I get the bullet points of a <ul> to center with the text?

ul {
  padding-left: 0;
  list-style-position: inside;
}

Explanation: The first property padding-left: 0 clears the default padding/spacing for the ul element while list-style-position: inside makes the dots/bullets of li aligned like a normal text.

So this code

<p>The ul element</p>
<ul>
asdfas
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

without any CSS will give us this:
enter image description here
but if we add in the CSS give at the top, that will give us this:
enter image description here

Apple Mach-O Linker Error when compiling for device

For me it was accidentally importing an implementation ".m" file instead of the corresponding header ".h" file. As soon as I caught that the project build was back to normal.

Easy way to concatenate two byte arrays

Here's a nice solution using Guava's com.google.common.primitives.Bytes:

byte[] c = Bytes.concat(a, b);

The great thing about this method is that it has a varargs signature:

public static byte[] concat(byte[]... arrays)

which means that you can concatenate an arbitrary number of arrays in a single method call.

How to access accelerometer/gyroscope data from Javascript?

The way to do this in 2019+ is to use DeviceOrientation API. This works in most modern browsers on desktop and mobile.

window.addEventListener("deviceorientation", handleOrientation, true);

After registering your event listener (in this case, a JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data.

The orientation event contains four values:

  • DeviceOrientationEvent.absolute
  • DeviceOrientationEvent.alpha
  • DeviceOrientationEvent.beta
  • DeviceOrientationEvent.gamma

The event handler function can look something like this:

function handleOrientation(event) {
  var absolute = event.absolute;
  var alpha    = event.alpha;
  var beta     = event.beta;
  var gamma    = event.gamma;
  // Do stuff with the new orientation data
}

Created Button Click Event c#

You need an event handler which will fire when the button is clicked. Here is a quick way -

  var button = new Button();
  button.Text = "my button";

  this.Controls.Add(button);

  button.Click += (sender, args) =>
                       {
                           MessageBox.Show("Some stuff");
                           Close();
                       };

But it would be better to understand a bit more about buttons, events, etc.

If you use the visual studio UI to create a button and double click the button in design mode, this will create your event and hook it up for you. You can then go to the designer code (the default will be Form1.Designer.cs) where you will find the event:

 this.button1.Click += new System.EventHandler(this.button1_Click);

You will also see a LOT of other information setup for the button, such as location, etc. - which will help you create one the way you want and will improve your understanding of creating UI elements. E.g. a default button gives this on my 2012 machine:

        this.button1.Location = new System.Drawing.Point(128, 214);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(75, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "button1";
        this.button1.UseVisualStyleBackColor = true;

As for closing the Form, it is as easy as putting Close(); within your event handler:

private void button1_Click(object sender, EventArgs e)
    {
       MessageBox.Show("some text");
       Close();
    }

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

Add column to SQL query results

why dont you add a "source" column to each of the queries with a static value like

select 'source 1' as Source, column1, column2...
from table1

UNION ALL

select 'source 2' as Source, column1, column2...
from table2

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

For your example, you'd add this:

interface JQuery{
    printArea():void;
}

Edit: oops, basarat is correct below. I'm not sure why I thought it was compiling but I've updated this answer.

In VBA get rid of the case sensitivity when comparing words?

There is a statement you can issue at the module level:

Option Compare Text

This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":

Option Compare Text

Sub testCase()
  If "UPPERcase" = "upperCASE" Then
    MsgBox "this is true: option Compare Text has been set!"
  End If
End Sub

See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match function) but it will take care of all the if a=b statements. As for Application.Match - you may want to convert the arguments to either upper case or lower case using the LCase function.

How do I check if PHP is connected to a database already?

Try using PHP's mysql_ping function:

echo @mysql_ping() ? 'true' : 'false';

You will need to prepend the "@" to suppose the MySQL Warnings you'll get for running this function without being connected to a database.

There are other ways as well, but it depends on the code that you're using.

Define variable to use with IN operator (T-SQL)

DECLARE @myList TABLE (Id BIGINT) INSERT INTO @myList(Id) VALUES (1),(2),(3),(4);
select * from myTable where myColumn in(select Id from @myList)

Please note that for long list or production systems it's not recommended to use this way as it may be much more slower than simple INoperator like someColumnName in (1,2,3,4) (tested using 8000+ items list)

How to compare files from two different branches?

In order to compare two files in the git bash you need to use the command:

git diff <Branch name>..master -- Filename.extension   

This command will show the difference between the two files in the bash itself.

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Use

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
    return shouldOverrideUrlLoading(view, request.getUrl().toString());
}

Get Enum from Description attribute

The solution works good except if you have a Web Service.

You would need to do the Following as the Description Attribute is not serializable.

[DataContract]
public enum ControlSelectionType
{
    [EnumMember(Value = "Not Applicable")]
    NotApplicable = 1,
    [EnumMember(Value = "Single Select Radio Buttons")]
    SingleSelectRadioButtons = 2,
    [EnumMember(Value = "Completely Different Display Text")]
    SingleSelectDropDownList = 3,
}

public static string GetDescriptionFromEnumValue(Enum value)
{
        EnumMemberAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(EnumMemberAttribute), false)
            .SingleOrDefault() as EnumMemberAttribute;
        return attribute == null ? value.ToString() : attribute.Value;
}

How to simulate a button click using code?

Android's callOnClick() (added in API 15) can sometimes be a better choice in my experience than performClick(). If a user has selection sounds enabled, then performClick() could cause the user to hear two continuous selection sounds that are somewhat layered on top of each other which can be jarring. (One selection sound for the user's first button click, and then another for the other button's OnClickListener that you're calling via code.)

Bootstrap dropdown menu not working (not dropping down when clicked)

I had the same issue I remove the following script and it worked for me.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>

How do I get textual contents from BLOB in Oracle SQL

Use TO_CHAR function.

select TO_CHAR(BLOB_FIELD) from TABLE_WITH_BLOB where ID = '<row id>'

Converts NCHAR, NVARCHAR2, CLOB, or NCLOB data to the database character set. The value returned is always VARCHAR2.

error: expected class-name before ‘{’ token

If you forward-declare Flight and Landing in Event.h, then you should be fixed.

Remember to #include "Flight.h" and #include "Landing.h" in your implementation file for Event.

The general rule of thumb is: if you derive from it, or compose from it, or use it by value, the compiler must know its full definition at the time of declaration. If you compose from a pointer-to-it, the compiler will know how big a pointer is. Similarly, if you pass a reference to it, the compiler will know how big the reference is, too.

How to: Add/Remove Class on mouseOver/mouseOut - JQuery .hover?

Your selector is missing a . and though you say you want to change the border-color - you're adding and removing a class that sets the background-color

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to know the git username and email saved during configuration?

List all variables set in the config file, along with their values.

git config --list

If you are new to git then use the following commands to set a user name and email address.

Set user name

git config --global user.name "your Name"

Set user email

git config --global user.email "[email protected]"

Check user name

git config user.name

Check user email

git config user.email

Connecting PostgreSQL 9.2.1 with Hibernate

This is a hibernate.cfg.xml for posgresql and it will help you with basic hibernate configurations for posgresql.

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>



        <property name="connection_pool_size">1</property>

        <property name="hbm2ddl.auto">create</property>

        <property name="show_sql">true</property>



       <mapping class="org.javabrains.sanjaya.dto.UserDetails"/>

    </session-factory>
</hibernate-configuration>

How can one run multiple versions of PHP 5.x on a development LAMP server?

One way to do this is to have your main version of php set up with mod_php and run all of the others through fast cgi on different ports (i.e. 81, 82, 83 etc). This won't guarantee totally consistent behavior though.

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

jquery if div id has children

There's actually quite a simple native method for this:

if( $('#myfav')[0].hasChildNodes() ) { ... }

Note that this also includes simple text nodes, so it will be true for a <div>text</div>.

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Generating a PNG with matplotlib when DISPLAY is undefined

What system are you on? It looks like you have a system with X11, but the DISPLAY environment variable was not properly set. Try executing the following command and then rerunning your program:

export DISPLAY=localhost:0

How to hide a button programmatically?

Kotlin code is a lot simpler:

if(isVisable) {
    clearButton.visibility = View.INVISIBLE
}
else {
    clearButton.visibility = View.VISIBLE
}

Convert spark DataFrame column to python list

I ran a benchmarking analysis and list(mvv_count_df.select('mvv').toPandas()['mvv']) is the fastest method. I'm very surprised.

I ran the different approaches on 100 thousand / 100 million row datasets using a 5 node i3.xlarge cluster (each node has 30.5 GBs of RAM and 4 cores) with Spark 2.4.5. Data was evenly distributed on 20 snappy compressed Parquet files with a single column.

Here's the benchmarking results (runtimes in seconds):

+-------------------------------------------------------------+---------+-------------+
|                          Code                               | 100,000 | 100,000,000 |
+-------------------------------------------------------------+---------+-------------+
| df.select("col_name").rdd.flatMap(lambda x: x).collect()    |     0.4 | 55.3        |
| list(df.select('col_name').toPandas()['col_name'])          |     0.4 | 17.5        |
| df.select('col_name').rdd.map(lambda row : row[0]).collect()|     0.9 | 69          |
| [row[0] for row in df.select('col_name').collect()]         |     1.0 | OOM         |
| [r[0] for r in mid_df.select('col_name').toLocalIterator()] |     1.2 | *           |
+-------------------------------------------------------------+---------+-------------+

* cancelled after 800 seconds

Golden rules to follow when collecting data on the driver node:

  • Try to solve the problem with other approaches. Collecting data to the driver node is expensive, doesn't harness the power of the Spark cluster, and should be avoided whenever possible.
  • Collect as few rows as possible. Aggregate, deduplicate, filter, and prune columns before collecting the data. Send as little data to the driver node as you can.

toPandas was significantly improved in Spark 2.3. It's probably not the best approach if you're using a Spark version earlier than 2.3.

See here for more details / benchmarking results.

Disable beep of Linux Bash on Windows 10

Uncommenting set bell-style none in /etc/inputrc and creating a .bash_profile with setterm -blength 0 didn't stop vim from beeping.

What worked for me was creating a .vimrc file in my home directory with set visualbell.

Source: https://linuxconfig.org/turn-off-beep-bell-on-linux-terminal

Inserting the same value multiple times when formatting a string

Fstrings

If you are using Python 3.6+ you can make use of the new so called f-strings which stands for formatted strings and it can be used by adding the character f at the beginning of a string to identify this as an f-string.

price = 123
name = "Jerry"
print(f"{name}!!, {price} is much, isn't {price} a lot? {name}!")
>Jerry!!, 123 is much, isn't 123 a lot? Jerry!

The main benefits of using f-strings is that they are more readable, can be faster, and offer better performance:

Source Pandas for Everyone: Python Data Analysis, By Daniel Y. Chen

Benchmarks

No doubt that the new f-strings are more readable, as you don't have to remap the strings, but is it faster though as stated in the aformentioned quote?

price = 123
name = "Jerry"

def new():
    x = f"{name}!!, {price} is much, isn't {price} a lot? {name}!"


def old():
    x = "{1}!!, {0} is much, isn't {0} a lot? {1}!".format(price, name)

import timeit
print(timeit.timeit('new()', setup='from __main__ import new', number=10**7))
print(timeit.timeit('old()', setup='from __main__ import old', number=10**7))
> 3.8741058271543776  #new
> 5.861819514350163   #old

Running 10 Million test's it seems that the new f-strings are actually faster in mapping.

How do I implement onchange of <input type="text"> with jQuery?

I would suggest using the keyup event something like below:

$('elementName').keyup(function() {
 alert("Key up detected");
});

There are a few ways of achieving the same result so I guess it's down to preference and depends on how you want it to work exactly.

Update: This only works for manual input not copy and paste.

For copy and paste I would recommend the following:

$('elementName').on('input',function(e){
 // Code here
});

Finding the source code for built-in Python functions?

Let's go straight to your question.

Finding the source code for built-in Python functions?

The source code is located at Python/bltinmodule.c

To find the source code in the GitHub repository go here. You can see that all in-built functions start with builtin_<name_of_function>, for instance, sorted() is implemented in builtin_sorted.

For your pleasure I'll post the implementation of sorted():

builtin_sorted(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)
{
    PyObject *newlist, *v, *seq, *callable;

    /* Keyword arguments are passed through list.sort() which will check
       them. */
    if (!_PyArg_UnpackStack(args, nargs, "sorted", 1, 1, &seq))
        return NULL;

    newlist = PySequence_List(seq);
    if (newlist == NULL)
        return NULL;

    callable = _PyObject_GetAttrId(newlist, &PyId_sort);
    if (callable == NULL) {
        Py_DECREF(newlist);
        return NULL;
    }

    assert(nargs >= 1);
    v = _PyObject_FastCallKeywords(callable, args + 1, nargs - 1, kwnames);
    Py_DECREF(callable);
    if (v == NULL) {
        Py_DECREF(newlist);
        return NULL;
    }
    Py_DECREF(v);
    return newlist;
}

As you may have noticed, that's not Python code, but C code.

percentage of two int?

float percent = (n / (v * 1.0f)) *100

Concatenate two NumPy arrays vertically

A not well known feature of numpy is to use r_. This is a simple way to build up arrays quickly:

import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = np.r_[a[None,:],b[None,:]]
print(c)
#[[1 2 3]
# [4 5 6]]

The purpose of a[None,:] is to add an axis to array a.

TypeError: Image data can not convert to float

try

import skimage
import random
from random import randint
import numpy as np
import matplotlib.pyplot as plt


xrow = raw_input("Enter the number of rows to be present in image.=>")
row = int(xrow)
ycolumn = raw_input("Enter the number of columns to be present in image.=>")
column = int(ycolumn)

A = np.zeros((row,column))
for x in xrange(1, row):
    for y in xrange(1, column):
        a = randint(0, 65535)
        A[x, y] = a

plt.imshow(A)
plt.show()

Show an image preview before upload

Here I did with jQuery using FileReader API.

Html Markup:

<input id="fileUpload" type="file" multiple />
<div id="image-holder"></div>

jQuery:

Here in jQuery code,first I check for file extension. i.e valid image file to be processed, then will check whether the browser support FileReader API is yes then only processed else display respected message

$("#fileUpload").on('change', function () {

     //Get count of selected files
     var countFiles = $(this)[0].files.length;

     var imgPath = $(this)[0].value;
     var extn = imgPath.substring(imgPath.lastIndexOf('.') + 1).toLowerCase();
     var image_holder = $("#image-holder");
     image_holder.empty();

     if (extn == "gif" || extn == "png" || extn == "jpg" || extn == "jpeg") {
         if (typeof (FileReader) != "undefined") {

             //loop for each file selected for uploaded.
             for (var i = 0; i < countFiles; i++) {

                 var reader = new FileReader();
                 reader.onload = function (e) {
                     $("<img />", {
                         "src": e.target.result,
                             "class": "thumb-image"
                     }).appendTo(image_holder);
                 }

                 image_holder.show();
                 reader.readAsDataURL($(this)[0].files[i]);
             }

         } else {
             alert("This browser does not support FileReader.");
         }
     } else {
         alert("Pls select only images");
     }
 });

Detailed Article: How to Preview Image before upload it, jQuery, HTML5 FileReader() with Live Demo

Android: How do bluetooth UUIDs work?

UUID is just a number. It has no meaning except you create on the server side of an Android app. Then the client connects using that same UUID.

For example, on the server side you can first run uuid = UUID.randomUUID() to generate a random number like fb36491d-7c21-40ef-9f67-a63237b5bbea. Then save that and then hard code that into your listener program like this:

 UUID uuid = UUID.fromString("fb36491d-7c21-40ef-9f67-a63237b5bbea"); 

Your Android server program will listen for incoming requests with that UUID like this:

    BluetoothServerSocket server = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("anyName", uuid);

BluetoothSocket socket = server.accept();

How can I restart a Java application?

Just adding information which is not present in other answers.

If procfs /proc/self/cmdline is available

If you are running in an environment which provides procfs and therefore has the /proc file system available (which means this is not a portable solution), you can have Java read /proc/self/cmdline in order to restart itself, like this:

public static void restart() throws IOException {
    new ProcessBuilder(getMyOwnCmdLine()).inheritIO().start();
}
public static String[] getMyOwnCmdLine() throws IOException {
    return readFirstLine("/proc/self/cmdline").split("\u0000");
}
public static String readFirstLine(final String filename) throws IOException {
    try (final BufferedReader in = new BufferedReader(new FileReader(filename))) {
        return in.readLine();
    }
}

On systems with /proc/self/cmdline available, this probably is the most elegant way of how to "restart" the current Java process from Java. No JNI involved, and no guessing of paths and stuff required. This will also take care of all JVM options passed to the java binary. The command line will be exactly identical to the one of the current JVM process.

Many UNIX systems including GNU/Linux (including Android) nowadays have procfs However on some like FreeBSD, it is deprecated and being phased out. Mac OS X is an exception in the sense that it does not have procfs. Windows also does not have procfs. Cygwin has procfs but it's invisible to Java because it's only visible to applications using the Cygwin DLLs instead of Windows system calls, and Java is unaware of Cygwin.

Don't forget to use ProcessBuilder.inheritIO()

The default is that stdin / stdout / stderr (in Java called System.in / System.out / System.err) of the started Process are set to pipes which allow the currently running process to communicate with the newly started process. If you want to restart the current process, this is most likely not what you want. Instead you would want that stdin / stdout / stderr are the same as those of the current VM. This is called inherited. You can do so by calling inheritIO() of your ProcessBuilder instance.

Pitfall on Windows

A frequent use case of a restart() function is to restart the application after an update. The last time I tried this on Windows this was problematic. When overwrote the application's .jar file with the new version, the application started to misbehave and giving exceptions about the .jar file. I'm just telling, in case this is your use case. Back then I solved the issue by wrapping the application in a batch file and using a magic return value from System.exit() that I queried in the batch file and had the batch file restart the application instead.

How do I exit from the text window in Git?

Since you are learning Git, know that this has little to do with git but with the text editor configured for use. In vim, you can press i to start entering text and save by pressing esc and :wq and enter, this will commit with the message you typed. In your current state, to just come out without committing, you can do :q instead of the :wq as mentioned above.

Alternatively, you can just do git commit -m '<message>' instead of having git open the editor to type the message.

Note that you can also change the editor and use something you are comfortable with ( like notepad) - How can I set up an editor to work with Git on Windows?

How to ignore deprecation warnings in Python

When you want to ignore warnings only in functions you can do the following.

import warnings
from functools import wraps


def ignore_warnings(f):
    @wraps(f)
    def inner(*args, **kwargs):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("ignore")
            response = f(*args, **kwargs)
        return response
    return inner

@ignore_warnings
def foo(arg1, arg2):
    ...
    write your code here without warnings
    ...

@ignore_warnings
def foo2(arg1, arg2, arg3):
    ...
    write your code here without warnings
    ...

Just add the @ignore_warnings decorator on the function you want to ignore all warnings

Right align text in android TextView

In my case, I was using Relative Layout for a emptyString

After struggling on this for an hour. Only this worked for me:

android:layout_toRightOf="@id/welcome"
android:layout_toEndOf="@id/welcome"
android:layout_alignBaseline="@id/welcome"

layout_toRightOf or layout_toEndOf both works, but to support it better, I used both.

To make it more clear:

This was what I was trying to do:

enter image description here

And this was the emulator's output

enter image description here

Layout:

<TextView
    android:id="@+id/welcome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text="Welcome "
    android:textSize="16sp" />
<TextView
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@id/welcome"
    android:layout_toRightOf="@id/welcome"
    android:text="@string/emptyString"
    android:textSize="16sp" />

Notice that:

  1. android:layout_width="wrap_content" works
  2. Gravity is not used

How to use (install) dblink in PostgreSQL?

I am using DBLINK to connect internal database for cross database queries.

Reference taken from this article.

Install DbLink extension.

CREATE EXTENSION dblink;

Verify DbLink:

SELECT pg_namespace.nspname, pg_proc.proname 
FROM pg_proc, pg_namespace 
WHERE pg_proc.pronamespace=pg_namespace.oid 
   AND pg_proc.proname LIKE '%dblink%';

Test connection of database:

SELECT dblink_connect('host=localhost user=postgres password=enjoy dbname=postgres');

Storing money in a decimal column - what precision and scale?

We recently implemented a system that needs to handle values in multiple currencies and convert between them, and figured out a few things the hard way.

NEVER USE FLOATING POINT NUMBERS FOR MONEY

Floating point arithmetic introduces inaccuracies that may not be noticed until they've screwed something up. All values should be stored as either integers or fixed-decimal types, and if you choose to use a fixed-decimal type then make sure you understand exactly what that type does under the hood (ie, does it internally use an integer or floating point type).

When you do need to do calculations or conversions:

  1. Convert values to floating point
  2. Calculate new value
  3. Round the number and convert it back to an integer

When converting a floating point number back to an integer in step 3, don't just cast it - use a math function to round it first. This will usually be round, though in special cases it could be floor or ceil. Know the difference and choose carefully.

Store the type of a number alongside the value

This may not be as important for you if you're only handling one currency, but it was important for us in handling multiple currencies. We used the 3-character code for a currency, such as USD, GBP, JPY, EUR, etc.

Depending on the situation, it may also be helpful to store:

  • Whether the number is before or after tax (and what the tax rate was)
  • Whether the number is the result of a conversion (and what it was converted from)

Know the accuracy bounds of the numbers you're dealing with

For real values, you want to be as precise as the smallest unit of the currency. This means you have no values smaller than a cent, a penny, a yen, a fen, etc. Don't store values with higher accuracy than that for no reason.

Internally, you may choose to deal with smaller values, in which case that's a different type of currency value. Make sure your code knows which is which and doesn't get them mixed up. Avoid using floating point values even here.


Adding all those rules together, we decided on the following rules. In running code, currencies are stored using an integer for the smallest unit.

class Currency {
   String code;       //  eg "USD"
   int value;         //  eg 2500
   boolean converted;
}

class Price {
   Currency grossValue;
   Currency netValue;
   Tax taxRate;
}

In the database, the values are stored as a string in the following format:

USD:2500

That stores the value of $25.00. We were able to do that only because the code that deals with currencies doesn't need to be within the database layer itself, so all values can be converted into memory first. Other situations will no doubt lend themselves to other solutions.


And in case I didn't make it clear earlier, don't use float!

How to use MD5 in javascript to transmit a password

crypto-js is a rich javascript library containing many cryptography algorithms.

All you have to do is just call CryptoJS.MD5(password)

$.post(
  'includes/login.php', 
  { user: username, pass: CryptoJS.MD5(password) },
  onLogin, 
  'json' );

C++ preprocessor __VA_ARGS__ number of arguments

With msvc extension:

#define Y_TUPLE_SIZE(...) Y_TUPLE_SIZE_II((Y_TUPLE_SIZE_PREFIX_ ## __VA_ARGS__ ## _Y_TUPLE_SIZE_POSTFIX,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0))
#define Y_TUPLE_SIZE_II(__args) Y_TUPLE_SIZE_I __args

#define Y_TUPLE_SIZE_PREFIX__Y_TUPLE_SIZE_POSTFIX ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,0

#define Y_TUPLE_SIZE_I(__p0,__p1,__p2,__p3,__p4,__p5,__p6,__p7,__p8,__p9,__p10,__p11,__p12,__p13,__p14,__p15,__p16,__p17,__p18,__p19,__p20,__p21,__p22,__p23,__p24,__p25,__p26,__p27,__p28,__p29,__p30,__p31,__n,...) __n

Works for 0 - 32 arguments. This limit can be easily extended.

EDIT: Simplified version (works in VS2015 14.0.25431.01 Update 3 & gcc 7.4.0) up to 100 arguments to copy & paste:

#define COUNTOF(...) _COUNTOF_CAT( _COUNTOF_A, ( 0, ##__VA_ARGS__, 100,\
    99, 98, 97, 96, 95, 94, 93, 92, 91, 90,\
    89, 88, 87, 86, 85, 84, 83, 82, 81, 80,\
    79, 78, 77, 76, 75, 74, 73, 72, 71, 70,\
    69, 68, 67, 66, 65, 64, 63, 62, 61, 60,\
    59, 58, 57, 56, 55, 54, 53, 52, 51, 50,\
    49, 48, 47, 46, 45, 44, 43, 42, 41, 40,\
    39, 38, 37, 36, 35, 34, 33, 32, 31, 30,\
    29, 28, 27, 26, 25, 24, 23, 22, 21, 20,\
    19, 18, 17, 16, 15, 14, 13, 12, 11, 10,\
    9, 8, 7, 6, 5, 4, 3, 2, 1, 0 ) )
#define _COUNTOF_CAT( a, b ) a b
#define _COUNTOF_A( a0, a1, a2, a3, a4, a5, a6, a7, a8, a9,\
    a10, a11, a12, a13, a14, a15, a16, a17, a18, a19,\
    a20, a21, a22, a23, a24, a25, a26, a27, a28, a29,\
    a30, a31, a32, a33, a34, a35, a36, a37, a38, a39,\
    a40, a41, a42, a43, a44, a45, a46, a47, a48, a49,\
    a50, a51, a52, a53, a54, a55, a56, a57, a58, a59,\
    a60, a61, a62, a63, a64, a65, a66, a67, a68, a69,\
    a70, a71, a72, a73, a74, a75, a76, a77, a78, a79,\
    a80, a81, a82, a83, a84, a85, a86, a87, a88, a89,\
    a90, a91, a92, a93, a94, a95, a96, a97, a98, a99,\
    a100, n, ... ) n

MySQL JOIN the most recent row only?

You may want to try the following:

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
JOIN      (
              SELECT    MAX(id) max_id, customer_id 
              FROM      customer_data 
              GROUP BY  customer_id
          ) c_max ON (c_max.customer_id = c.customer_id)
JOIN      customer_data cd ON (cd.id = c_max.max_id)
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

Note that a JOIN is just a synonym for INNER JOIN.

Test case:

CREATE TABLE customer (customer_id int);
CREATE TABLE customer_data (
   id int, 
   customer_id int, 
   title varchar(10),
   forename varchar(10),
   surname varchar(10)
);

INSERT INTO customer VALUES (1);
INSERT INTO customer VALUES (2);
INSERT INTO customer VALUES (3);

INSERT INTO customer_data VALUES (1, 1, 'Mr', 'Bobby', 'Smith');
INSERT INTO customer_data VALUES (2, 1, 'Mr', 'Bob', 'Smith');
INSERT INTO customer_data VALUES (3, 2, 'Mr', 'Jane', 'Green');
INSERT INTO customer_data VALUES (4, 2, 'Miss', 'Jane', 'Green');
INSERT INTO customer_data VALUES (5, 3, 'Dr', 'Jack', 'Black');

Result (query without the LIMIT and WHERE):

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
JOIN      (
              SELECT    MAX(id) max_id, customer_id 
              FROM      customer_data 
              GROUP BY  customer_id
          ) c_max ON (c_max.customer_id = c.customer_id)
JOIN      customer_data cd ON (cd.id = c_max.max_id);

+-----------------+
| name            |
+-----------------+
| Mr Bob Smith    |
| Miss Jane Green |
| Dr Jack Black   |
+-----------------+
3 rows in set (0.00 sec)

CSS hover vs. JavaScript mouseover

Why not both? Use jQuery for animated effects and CSS as the fallback. This gives you the benefits of jQuery with graceful degradation.

CSS:

a {color: blue;}
a:hover {color: red;}

jQuery (uses jQueryUI to animate color):

$('a').hover( 
  function() {
    $(this)
      .css('color','blue')
      .animate({'color': 'red'}, 400);
  },
  function() {
    $(this)
      .animate({'color': 'blue'}, 400);
  }
);

demo

Best Practice to Use HttpClient in Multithreaded Environment

With HttpClient 4.5 you can do this:

CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();

Note that this one implements Closeable (for shutting down of the connection manager).

How to deep watch an array in angularjs?

You can set the 3rd argument of $watch to true:

$scope.$watch('data', function (newVal, oldVal) { /*...*/ }, true);

See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watch

Since Angular 1.1.x you can also use $watchCollection to watch shallow watch (just the "first level" of) the collection.

$scope.$watchCollection('data', function (newVal, oldVal) { /*...*/ });

See https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchCollection

What is the bit size of long on 64-bit Windows?

If you need to use integers of certain length, you probably should use some platform independent headers to help you. Boost is a good place to look at.

XAMPP permissions on Mac OS X?

For new XAMPP-VM for Mac OS X,
I change the ownership to daemon user and solve the problem.

For example,

$ chown -R daemon:daemon /opt/lampp/htdocs/hello-laravel/storage

.Net picking wrong referenced assembly version

In case is saves someone else 3 hours... my case was a bit different. My code used DevExpress v11.1 v11.1.4.0. I had it all referenced correctly in my code. But .net memory profiler installed DevExpress v11.1 v11.1.12.0 in the GAC. In fact it wasn't the components I referenced but the ones they referenced internally that failed. Try as I might, the GAC is always checked first. It compiled and ran fine but I couldn't view the win forms designer and the stack trace was no help at all. Finally uninstalled .net memory profiler and all was restored.

Android Recyclerview GridLayoutManager column spacing

Here is my modification of SpacesItemDecoration which can take numOfColums and space equally on top, bottom, left and right.

public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;
    private int mNumCol;

    public SpacesItemDecoration(int space, int numCol) {
        this.space = space;
        this.mNumCol=numCol;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view,
                               RecyclerView parent, RecyclerView.State state) {

        //outRect.right = space;
        outRect.bottom = space;
        //outRect.left = space;

        //Log.d("ttt", "item position" + parent.getChildLayoutPosition(view));
        int position=parent.getChildLayoutPosition(view);

        if(mNumCol<=2) {
            if (position == 0) {
                outRect.left = space;
                outRect.right = space / 2;
            } else {
                if ((position % mNumCol) != 0) {
                    outRect.left = space / 2;
                    outRect.right = space;
                } else {
                    outRect.left = space;
                    outRect.right = space / 2;
                }
            }
        }else{
            if (position == 0) {
                outRect.left = space;
                outRect.right = space / 2;
            } else {
                if ((position % mNumCol) == 0) {
                    outRect.left = space;
                    outRect.right = space/2;
                } else if((position % mNumCol) == (mNumCol-1)){
                    outRect.left = space/2;
                    outRect.right = space;
                }else{
                    outRect.left=space/2;
                    outRect.right=space/2;
                }
            }

        }

        if(position<mNumCol){
            outRect.top=space;
        }else{
            outRect.top=0;
        }
        // Add top margin only for the first item to avoid double space between items
        /*
        if (parent.getChildLayoutPosition(view) == 0 ) {

        } else {
            outRect.top = 0;
        }*/
    }
}

and use below code on your logic.

recyclerView.addItemDecoration(new SpacesItemDecoration(spacingInPixels, numCol));

How do I remove duplicate items from an array in Perl?

Previous answers pretty much summarize the possible ways of accomplishing this task.

However, I suggest a modification for those who don't care about counting the duplicates, but do care about order.

my @record = qw( yeah I mean uh right right uh yeah so well right I maybe );
my %record;
print grep !$record{$_} && ++$record{$_}, @record;

Note that the previously suggested grep !$seen{$_}++ ... increments $seen{$_} before negating, so the increment occurs regardless of whether it has already been %seen or not. The above, however, short-circuits when $record{$_} is true, leaving what's been heard once 'off the %record'.

You could also go for this ridiculousness, which takes advantage of autovivification and existence of hash keys:

...
grep !(exists $record{$_} || undef $record{$_}), @record;

That, however, might lead to some confusion.

And if you care about neither order or duplicate count, you could for another hack using hash slices and the trick I just mentioned:

...
undef @record{@record};
keys %record; # your record, now probably scrambled but at least deduped

Android intent for playing video?

I have come across this with the Hero, using what I thought was a published API. In the end, I used a test to see if the intent could be received:

private boolean isCallable(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 
        PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

In use when I would usually just start the activity:

final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
if (isCallable(intent)) {
    // call the intent as you intended.
} else {
    // make alternative arrangements.
}

obvious: If you go down this route - using non-public APIs - you must absolutely provide a fallback which you know definitely works. It doesn't have to be perfect, it can be a Toast saying that this is unsupported for this handset/device, but you should avoid an uncaught exception. end obvious.


I find the Open Intents Registry of Intents Protocols quite useful, but I haven't found the equivalent of a TCK type list of intents which absolutely must be supported, and examples of what apps do different handsets.

How to perform keystroke inside powershell?

function Do-SendKeys {
    param (
        $SENDKEYS,
        $WINDOWTITLE
    )
    $wshell = New-Object -ComObject wscript.shell;
    IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
    Sleep 1
    IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'

Android Studio Gradle Configuration with name 'default' not found

I solved this issue by fixing some paths in settings.gradle as shown below:

include ':project-external-module'

project(':project-external-module').projectDir = file('/project/wrong/path')

I was including an external module to my project and had the wrong path for it.

How to specify legend position in matplotlib in graph coordinates

According to the matplotlib legend documentation:

The location can also be a 2-tuple giving the coordinates of the lower-left corner of the legend in axes coordinates (in which case bbox_to_anchor will be ignored).

Thus, one could use:

plt.legend(loc=(x, y))

to set the legend's lower left corner to the specified (x, y) position.