Programs & Examples On #Nested controls

how to overlap two div in css?

I edited you fiddle you just need to add z-index to the front element and position it accordingly.

HTTP response code for POST when resource already exists

According to RFC 7231, a 303 See Other MAY be used If the result of processing a POST would be equivalent to a representation of an existing resource.

Android Writing Logs to text File

This variant is much shorter

try {
    final File path = new File(
            Environment.getExternalStorageDirectory(), "DBO_logs5");
    if (!path.exists()) {
        path.mkdir();
    }
    Runtime.getRuntime().exec(
            "logcat  -d -f " + path + File.separator
                    + "dbo_logcat"
                    + ".txt");
} catch (IOException e) {
    e.printStackTrace();
}

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

Authenticating in PHP using LDAP through Active Directory

PHP has libraries: http://ca.php.net/ldap

PEAR also has a number of packages: http://pear.php.net/search.php?q=ldap&in=packages&x=0&y=0

I haven't used either, but I was going to at one point and they seemed like they should work.

How to find the index of an element in an array in Java?

Alternatively, you can use Commons Lang ArrayUtils class:

int[] arr = new int{3, 5, 1, 4, 2};
int indexOfTwo = ArrayUtils.indexOf(arr, 2);

There are overloaded variants of indexOf() method for different array types.

Add zero-padding to a string

You can use PadLeft

var newString = Your_String.PadLeft(4, '0');

How to select distinct rows in a datatable and store into an array

DataTable dtbs = new DataTable(); 
DataView dvbs = new DataView(dt); 
dvbs.RowFilter = "ColumnName='Filtervalue'"; 
dtbs = dvbs.ToTable();

How do you UDP multicast in Python?

This example doesn't work for me, for an obscure reason.

Not obscure, it's simple routing.

On OpenBSD

route add -inet 224.0.0.0/4 224.0.0.1

You can set the route to a dev on Linux

route add -net 224.0.0.0 netmask 240.0.0.0 dev wlp2s0

force all multicast traffic to one interface on Linux

   ifconfig wlp2s0 allmulti

tcpdump is super simple

tcpdump -n multicast

In your code you have:

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"

Why 10240?

multicast packet size should be 1316 bytes

JavaScript adding decimal numbers issue

This is common issue with floating points.

Use toFixed in combination with parseFloat.

Here is example in JavaScript:

function roundNumber(number, decimals) {
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return parseFloat(newnumber); 
}

0.1 + 0.2;                    //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3

Auto generate function documentation in Visual Studio

In visual basic, if you create your function/sub first, then on the line above it, you type ' three times, it will auto-generate the relevant xml for documentation. This also shows up when you mouseover in intellisense, and when you are making use of the function.

Sum columns with null values in oracle

The other answers regarding the use of nvl() are correct however none seem to address a more salient point:

Should you even have NULLs in this column?

Do they have a meaning other than 0?

This seems like a case where you should have a NOT NULL DEFAULT 0 on th ecolumn

How to autosize a textarea using Prototype?

Here's a Prototype version of resizing a text area that is not dependent on the number of columns in the textarea. This is a superior technique because it allows you to control the text area via CSS as well as have variable width textarea. Additionally, this version displays the number of characters remaining. While not requested, it's a pretty useful feature and is easily removed if unwanted.

//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
if (window.Widget == undefined) window.Widget = {}; 

Widget.Textarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    this.options = $H({
      'min_height' : 30,
      'max_length' : 400
    }).update(options);

    this.textarea.observe('keyup', this.refresh.bind(this));

    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-10000px',
      left: '-10000px',
      width: this.textarea.getWidth() + 'px'
    });
    this.textarea.insert({ after: this._shadow });

    this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
    this.textarea.insert({after: this._remainingCharacters});  
    this.refresh();  
  },

  refresh: function()
  { 
    this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
    this.textarea.setStyle({
      height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
    });

    var remaining = this.options.get('max_length') - $F(this.textarea).length;
    this._remainingCharacters.update(Math.abs(remaining)  + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
  }
});

Create the widget by calling new Widget.Textarea('element_id'). The default options can be overridden by passing them as an object, e.g. new Widget.Textarea('element_id', { max_length: 600, min_height: 50}). If you want to create it for all textareas on the page, do something like:

Event.observe(window, 'load', function() {
  $$('textarea').each(function(textarea) {
    new Widget.Textarea(textarea);
  });   
});

How to run batch file from network share without "UNC path are not supported" message?

Instead of launching the batch directly from explorer - create a shortcut to the batch and set the starting directory in the properties of the shortcut to a local path like %TEMP% or something.

To delete the symbolic link, use the rmdir command.

How can I determine whether a specific file is open in Windows?

In OpenedFilesView, under the Options menu, there is a menu item named "Show Network Files". Perhaps with that enabled, the aforementioned utility is of some use.

Error: macro names must be identifiers using #ifdef 0

The #ifdef directive is used to check if a preprocessor symbol is defined. The standard (C11 6.4.2 Identifiers) mandates that identifiers must not start with a digit:

identifier:
    identifier-nondigit
    identifier identifier-nondigit
    identifier digit
identifier-nondigit:
    nondigit
    universal-character-name
    other implementation-defined characters>
nondigit: one of
    _ a b c d e f g h i j k l m
    n o p q r s t u v w x y z
    A B C D E F G H I J K L M
    N O P Q R S T U V W X Y Z
digit: one of
    0 1 2 3 4 5 6 7 8 9

The correct form for using the pre-processor to block out code is:

#if 0
: : :
#endif

You can also use:

#ifdef NO_CHANCE_THAT_THIS_SYMBOL_WILL_EVER_EXIST
: : :
#endif

but you need to be confident that the symbols will not be inadvertently set by code other than your own. In other words, don't use something like NOTUSED or DONOTCOMPILE which others may also use. To be safe, the #if option should be preferred.

How to post data in PHP using file_get_contents?

Sending an HTTP POST request using file_get_contents is not that hard, actually : as you guessed, you have to use the $context parameter.


There's an example given in the PHP manual, at this page : HTTP context options (quoting) :

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents -- nothing more ;-)


As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...

WhatsApp API (java/python)

This is the developers page of the Open WhatsApp official page: http://openwhatsapp.org/develop/

You can find a lot of information there about Yowsup.

Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): https://github.com/tgalal/yowsup

Enjoy!

Identify duplicate values in a list in Python

The following list comprehension will yield the duplicate values:

[x for x in mylist if mylist.count(x) >= 2]

Can I use Homebrew on Ubuntu?

Because all previous answers doesn't work for me for ubuntu 14.04 here what I did, if any one get the same problem:

git clone https://github.com/Linuxbrew/brew.git ~/.linuxbrew
PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$(brew --prefix)/share/man:$MANPATH"
export INFOPATH="$(brew --prefix)/share/info:$INFOPATH"

then

sudo apt-get install gawk
sudo yum install gawk
brew install hello

you can follow this link for more information.

Python Web Crawlers and "getting" html source code

Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).

I recommend you using the stdlib module urllib2, it will allow you to comfortably get web resources. Example:

import urllib2

response = urllib2.urlopen("http://google.de")
page_source = response.read()

For parsing the code, have a look at BeautifulSoup.

BTW: what exactly do you want to do:

Just for background, I need to download a page and replace any img with ones I have

Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests is a very nice high-level library which is easier to use than urllib2.

Git push error '[remote rejected] master -> master (branch is currently checked out)'

You can simply convert your remote repository to bare repository (there is no working copy in the bare repository - the folder contains only the actual repository data).

Execute the following command in your remote repository folder:

git config --bool core.bare true

Then delete all the files except .git in that folder. And then you will be able to perform git push to the remote repository without any errors.

Number of regex matches

If you find you need to stick with finditer(), you can simply use a counter while you iterate through the iterator.

Example:

>>> from re import *
>>> pattern = compile(r'.ython')
>>> string = 'i like python jython and dython (whatever that is)'
>>> iterator = finditer(pattern, string)
>>> count = 0
>>> for match in iterator:
        count +=1
>>> count
3

If you need the features of finditer() (not matching to overlapping instances), use this method.

Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

Fast ways to duplicate an array in JavaScript in Order:

#1: array1copy = [...array1];

#2: array1copy = array1.slice(0);

#3: array1copy = array1.slice();

If your array objects contain some JSON-non-serializable content (functions, Number.POSITIVE_INFINITY, etc.) better to use

array1copy = JSON.parse(JSON.stringify(array1))

Submit form after calling e.preventDefault()

In my case there was a race, as I needed the ajax response to fill a hidden field and send the form after it's filled. I fixed it with putting e.preventDefault() into a condition.

var all_is_done=false;
$("form").submit(function(e){
  if(all_is_done==false){
   e.preventDefault();
   do_the_stuff();
  }
});
function do_the_stuf(){
  //do stuff
  all_is_done=true;
  $("form").submit();
}

Bootstrap radio button "checked" flag

You have to use active in the label to make it work as mentioned above. But you can use checked="checked" and it will work too. It's not necessary but it's more legible and makes more sense as it is more html format compliance.

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Also, if your service is sending an object instead of an array add isArray:false to its declaration.

'query': {method: 'GET', isArray: false }

How to ssh from within a bash script?

If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:

#!/usr/bin/expect -f
spawn ssh user@hostname
expect "password:"
sleep 1
send "<your password>\r"
command1
command2
commandN

bower proxy configuration

There is no way to configure an exclusion to the proxy settings, but a colleague of mine had an create solution for that particular problem. He installed a local proxy server called cntlm. That server supports ntlm authentication and exclusions to the general proxy settings. A perfect match.

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Sorting a vector in descending order

Use the first:

std::sort(numbers.begin(), numbers.end(), std::greater<int>());

It's explicit of what's going on - less chance of misreading rbegin as begin, even with a comment. It's clear and readable which is exactly what you want.

Also, the second one may be less efficient than the first given the nature of reverse iterators, although you would have to profile it to be sure.

What is the difference between MySQL, MySQLi and PDO?

Those are different APIs to access a MySQL backend

  • The mysql is the historical API
  • The mysqli is a new version of the historical API. It should perform better and have a better set of function. Also, the API is object-oriented.
  • PDO_MySQL, is the MySQL for PDO. PDO has been introduced in PHP, and the project aims to make a common API for all the databases access, so in theory you should be able to migrate between RDMS without changing any code (if you don't use specific RDBM function in your queries), also object-oriented.

So it depends on what kind of code you want to produce. If you prefer object-oriented layers or plain functions...

My advice would be

  1. PDO
  2. MySQLi
  3. mysql

Also my feeling, the mysql API would probably being deleted in future releases of PHP.

Submit form without page reloading

You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/

Your code should be something along the lines of:

$('#submit').click(function() {
    $.ajax({
        url: 'send_email.php',
        type: 'POST',
        data: {
            email: '[email protected]',
            message: 'hello world!'
        },
        success: function(msg) {
            alert('Email Sent');
        }               
    });
});

The form will submit in the background to the send_email.php page which will need to handle the request and send the email.

How to compare two NSDates: Which is more recent?

In Swift, you can overload existing operators:

func > (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}

func < (lhs: NSDate, rhs: NSDate) -> Bool {
    return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}

Then, you can compare NSDates directly with <, >, and == (already supported).

Is it possible to break a long line to multiple lines in Python?

From PEP 8 - Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

Example of implicit line continuation:

a = some_function(
    '1' + '2' + '3' - '4')

On the topic of line-breaks around a binary operator, it goes on to say:-

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.

Example of explicit line continuation:

a = '1'   \
    + '2' \
    + '3' \
    - '4'

How to change the session timeout in PHP?

Just a notice for a sharing hosting server or added on domains =

For your settings to work you must have a different save session dir for added domain by using php_value session.save_path folderA/sessionsA.

So create a folder to your root server, not into the public_html and not to be publicity accessed from outside. For my cpanel/server worked fine the folder permissions 0700. Give a try...

# Session timeout, 2628000 sec = 1 month, 604800 = 1 week, 57600 = 16 hours, 86400 = 1 day
ini_set('session.save_path', '/home/server/.folderA_sessionsA');
ini_set('session.gc_maxlifetime', 57600); 
ini_set('session.cookie_lifetime', 57600);
# session.cache_expire is in minutes unlike the other settings above         
ini_set('session.cache_expire', 960);
ini_set('session.name', 'MyDomainA');

before session_start();

or put this in your .htaccess file.

php_value session.save_path /home/server/.folderA_sessionsA
php_value session.gc_maxlifetime 57600
php_value session.cookie_lifetime 57600
php_value session.cache_expire 57600
php_value session.name MyDomainA

After many researching and testing this worked fine for shared cpanel/php7 server. Many thanks to: NoiS

Why can I not push_back a unique_ptr into a vector?

You need to move the unique_ptr:

vec.push_back(std::move(ptr2x));

unique_ptr guarantees that a single unique_ptr container has ownership of the held pointer. This means that you can't make copies of a unique_ptr (because then two unique_ptrs would have ownership), so you can only move it.

Note, however, that your current use of unique_ptr is incorrect. You cannot use it to manage a pointer to a local variable. The lifetime of a local variable is managed automatically: local variables are destroyed when the block ends (e.g., when the function returns, in this case). You need to dynamically allocate the object:

std::unique_ptr<int> ptr(new int(1));

In C++14 we have an even better way to do so:

make_unique<int>(5);

Undefined reference to sqrt (or other mathematical functions)

You may find that you have to link with the math libraries on whatever system you're using, something like:

gcc -o myprog myprog.c -L/path/to/libs -lm
                                       ^^^ - this bit here.

Including headers lets a compiler know about function declarations but it does not necessarily automatically link to the code required to perform that function.

Failing that, you'll need to show us your code, your compile command and the platform you're running on (operating system, compiler, etc).

The following code compiles and links fine:

#include <math.h>
int main (void) {
    int max = sqrt (9);
    return 0;
}

Just be aware that some compilation systems depend on the order in which libraries are given on the command line. By that, I mean they may process the libraries in sequence and only use them to satisfy unresolved symbols at that point in the sequence.

So, for example, given the commands:

gcc -o plugh plugh.o -lxyzzy
gcc -o plugh -lxyzzy plugh.o

and plugh.o requires something from the xyzzy library, the second may not work as you expect. At the point where you list the library, there are no unresolved symbols to satisfy.

And when the unresolved symbols from plugh.o do appear, it's too late.

how to implement a long click listener on a listview

If you want to do it in the adapter, you can simply do this:

itemView.setOnLongClickListener(new View.OnLongClickListener()
        {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(mContext, "Long pressed on item", Toast.LENGTH_SHORT).show();
            }
        });

How to zip a whole folder using PHP

For anyone reading this post and looking for a why to zip the files using addFile instead of addFromString, that does not zip the files with their absolute path (just zips the files and nothing else), see my question and answer here

How to make pylab.savefig() save image for 'maximized' window instead of default size

I had this exact problem and this worked:

plt.savefig(output_dir + '/xyz.png', bbox_inches='tight')

Here is the documentation:

[https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.savefig.html][1]

How to programmatically take a screenshot on Android?

You can try to do something like this,

Getting a bitmap cache from a layout or a view by doing something like First you gotta setDrawingCacheEnabled to a layout(a linearlayout or relativelayout, or a view)

then

Bitmap bm = layout.getDrawingCache()

Then you do whatever you want with the bitmap. Either turning it into an image file, or send the bitmap's uri to somewhere else.

How to make html <select> element look like "disabled", but pass values?

One could use an additional hidden input element with the same name and value as that of the disabled list. This will ensure that the value is passed in $_POST variables.

Eg:

_x000D_
_x000D_
<select name="sel" disabled><option>123</select>_x000D_
<input type="hidden" name="sel" value=123>
_x000D_
_x000D_
_x000D_

Convert HTML to PDF in .NET

Most HTML to PDF converter relies on IE to do the HTML parsing and rendering. This can break when user updates their IE. Here is one that does not rely on IE.

The code is something like this:

EO.Pdf.HtmlToPdf.ConvertHtml(htmlText, pdfFileName);

Like many other converters, you can pass text, file name, or Url. The result can be saved into a file or a stream.

C++ -- expected primary-expression before ' '

You don't need "string" in your call to wordLengthFunction().

int wordLength = wordLengthFunction(string word);

should be

int wordLength = wordLengthFunction(word);

How to make my layout able to scroll down?

For using scroll view along with Relative layout :

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fillViewport="true"> <!--IMPORTANT otherwise backgrnd img. will not fill the whole screen -->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:background="@drawable/background_image"
    >

    <!-- Bla Bla Bla i.e. Your Textviews/Buttons etc. -->
    </RelativeLayout>
</ScrollView>

Get current value when change select option - Angular2

For me, passing ($event.target.value) as suggested by @microniks did not work. What worked was ($event.value) instead. I am using Angular 4.2.x and Angular Material 2

<select (change)="onItemChange($event.value)">
    <option *ngFor="#value of values" [value]="value.key">
       {{value.value}}
    </option>
</select>

Quickly reading very large tables as dataframes

A minor additional points worth mentioning. If you have a very large file you can on the fly calculate the number of rows (if no header) using (where bedGraph is the name of your file in your working directory):

>numRow=as.integer(system(paste("wc -l", bedGraph, "| sed 's/[^0-9.]*\\([0-9.]*\\).*/\\1/'"), intern=T))

You can then use that either in read.csv , read.table ...

>system.time((BG=read.table(bedGraph, nrows=numRow, col.names=c('chr', 'start', 'end', 'score'),colClasses=c('character', rep('integer',3)))))
   user  system elapsed 
 25.877   0.887  26.752 
>object.size(BG)
203949432 bytes

How to describe "object" arguments in jsdoc?

By now there are 4 different ways to document objects as parameters/types. Each has its own uses. Only 3 of them can be used to document return values, though.

For objects with a known set of properties (Variant A)

/**
 * @param {{a: number, b: string, c}} myObj description
 */

This syntax is ideal for objects that are used only as parameters for this function and don't require further description of each property. It can be used for @returns as well.

For objects with a known set of properties (Variant B)

Very useful is the parameters with properties syntax:

/**
 * @param {Object} myObj description
 * @param {number} myObj.a description
 * @param {string} myObj.b description
 * @param {} myObj.c description
 */

This syntax is ideal for objects that are used only as parameters for this function and that require further description of each property. This can not be used for @returns.

For objects that will be used at more than one point in source

In this case a @typedef comes in very handy. You can define the type at one point in your source and use it as a type for @param or @returns or other JSDoc tags that can make use of a type.

/**
 * @typedef {Object} Person
 * @property {string} name how the person is called
 * @property {number} age how many years the person lived
 */

You can then use this in a @param tag:

/**
 * @param {Person} p - Description of p
 */

Or in a @returns:

/**
 * @returns {Person} Description
 */

For objects whose values are all the same type

/**
 * @param {Object.<string, number>} dict
 */

The first type (string) documents the type of the keys which in JavaScript is always a string or at least will always be coerced to a string. The second type (number) is the type of the value; this can be any type. This syntax can be used for @returns as well.

Resources

Useful information about documenting types can be found here:

https://jsdoc.app/tags-type.html

PS:

to document an optional value you can use []:

/**
 * @param {number} [opt_number] this number is optional
 */

or:

/**
 * @param {number|undefined} opt_number this number is optional
 */

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

What's a good hex editor/viewer for the Mac?

One recommendation I've gotten is Hex Fiend.

get an element's id

In events handler you can get id as follows

_x000D_
_x000D_
function show(btn) {_x000D_
  console.log('Button id:',btn.id);_x000D_
}
_x000D_
<button id="myButtonId" onclick="show(this)">Click me</button>
_x000D_
_x000D_
_x000D_

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Update statement using with clause

If anyone comes here after me, this is the answer that worked for me.

NOTE: please make to read the comments before using this, this not complete. The best advice for update queries I can give is to switch to SqlServer ;)

update mytable t
set z = (
  with comp as (
    select b.*, 42 as computed 
    from mytable t 
    where bs_id = 1
  )
  select c.computed
  from  comp c
  where c.id = t.id
)

Good luck,

GJ

How do I analyze a program's core dump file with GDB when it has command-line parameters?

From RMS's GDB debugger tutorial:

prompt > myprogram
Segmentation fault (core dumped)
prompt > gdb myprogram
...
(gdb) core core.pid
...

Make sure your file really is a core image -- check it using file.

How to emulate a do-while loop in Python?

Quick hack:

def dowhile(func = None, condition = None):
    if not func or not condition:
        return
    else:
        func()
        while condition():
            func()

Use like so:

>>> x = 10
>>> def f():
...     global x
...     x = x - 1
>>> def c():
        global x
        return x > 0
>>> dowhile(f, c)
>>> print x
0

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

Only local connections are allowed Chrome and Selenium webdriver

C#:

    ChromeOptions options = new ChromeOptions();

    options.AddArgument("C:/Users/username/Documents/Visual Studio 2012/Projects/Interaris.Test/Interaris.Tes/bin/Debug/chromedriver.exe");

    ChromeDriver chrome = new ChromeDriver(options);

Worked for me.

How to insert newline in string literal?

newer .net versions allow you to use $ in front of the literal which allows you to use variables inside like follows:

var x = $"Line 1{Environment.NewLine}Line 2{Environment.NewLine}Line 3";

What is causing "Unable to allocate memory for pool" in PHP?

I received the error "Unable to allocate memory for pool" after moving an OpenCart installation to a different server. I also tried raising the memory_limit.

The error stopped after I changed the permissions of the file in the error message to have write access by the user that apache runs as (apache, www-data, etc.). Instead of modifying /etc/group directly (or chmod-ing the files to 0777), I used usermod:

usermod -a -G vhost-user-group apache-user

Then I had to restart apache for the change to take effect:

apachectl restart

Or

sudo /etc/init.d/httpd restart

Or whatever your system uses to restart apache.

If the site is on shared hosting, maybe you must change the file permissions with an FTP program, or contact the hosting provider?

How to sort by column in descending order in Spark SQL?

You can also sort the column by importing the spark sql functions

import org.apache.spark.sql.functions._
df.orderBy(asc("col1"))

Or

import org.apache.spark.sql.functions._
df.sort(desc("col1"))

importing sqlContext.implicits._

import sqlContext.implicits._
df.orderBy($"col1".desc)

Or

import sqlContext.implicits._
df.sort($"col1".desc)

Windows Forms ProgressBar: Easiest way to start/stop marquee?

Use a progress bar with the style set to Marquee. This represents an indeterminate progress bar.

myProgressBar.Style = ProgressBarStyle.Marquee;

You can also use the MarqueeAnimationSpeed property to set how long it will take the little block of color to animate across your progress bar.

How to add buttons dynamically to my form?

Two problems- List is empty. You need to add some buttons to the list first. Second problem: You can't add buttons to "this". "This" is not referencing what you think, I think. Change this to reference a Panel for instance.

//Assume you have on your .aspx page:
<asp:Panel ID="Panel_Controls" runat="server"></asp:Panel>


private void button1_Click(object sender, EventArgs e)
    {
        List<Button> buttons = new List<Button>();


        for (int i = 0; i < buttons.Capacity; i++)
        {
            Panel_Controls.Controls.Add(buttons[i]);   
        }
    }

How to repair a serialized string which has been corrupted by an incorrect byte count length?

You will have to alter the collation type to utf8_unicode_ci and the problem will be fixed.

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

it is very simple....

[in make file]

==== 1 ===================

OBJS = ....\

version.o <<== add to your obj lists

==== 2 ===================

DATE = $(shell date +'char szVersionStr[20] = "%Y-%m-%d %H:%M:%S";') <<== add

all:version $(ProgramID) <<== version add at first

version: <<== add

echo '$(DATE)' > version.c  <== add ( create version.c file)

[in program]

=====3 =============

extern char szVersionStr[20];

[ using ]

=== 4 ====

printf( "Version: %s\n", szVersionStr );

Add image to left of text via css

For adding background icon always before text when length of text is not known in advance.

.create:before{
content: "";
display: inline-block;
background: #ccc url(arrow.png) no-repeat;
width: 10px;background-size: contain;
height: 10px;
}

Table variable error: Must declare the scalar variable "@temp"

There is one another method of temp table

create table #TempTable (
ID int,
name varchar(max)
)

insert into #TempTable (ID,name)
Select ID,Name 
from Table

SELECT * 
FROM #TempTable
WHERE ID  = 1 

Make Sure You are selecting the right database.

Difference between List, List<?>, List<T>, List<E>, and List<Object>

The reason you cannot cast List<String> to List<Object> is that it would allow you to violate the constraints of the List<String>.

Think about the following scenario: If I have a List<String>, it is supposed to only contain objects of type String. (Which is a final class)

If I can cast that to a List<Object>, then that allows me to add Object to that list, thus violating the original contract of List<String>.

Thus, in general, if class C inherits from class P, you cannot say that GenericType<C> also inherits from GenericType<P>.

N.B. I already commented on this in a previous answer but wanted to expand on it.

Create a string with n characters

I know of no built-in method for what you're asking about. However, for a small fixed length like 10, your method should be plenty fast.

move column in pandas dataframe

This function will reorder your columns without losing data. Any omitted columns remain in the center of the data set:

def reorder_columns(columns, first_cols=[], last_cols=[], drop_cols=[]):
    columns = list(set(columns) - set(first_cols))
    columns = list(set(columns) - set(drop_cols))
    columns = list(set(columns) - set(last_cols))
    new_order = first_cols + columns + last_cols
    return new_order

Example usage:

my_list = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']
reorder_columns(my_list, first_cols=['fourth', 'third'], last_cols=['second'], drop_cols=['fifth'])

# Output:
['fourth', 'third', 'first', 'sixth', 'second']

To assign to your dataframe, use:

my_list = df.columns.tolist()
reordered_cols = reorder_columns(my_list, first_cols=['fourth', 'third'], last_cols=['second'], drop_cols=['fifth'])
df = df[reordered_cols]

How do you exit from a void function in C++?

Use a return statement!

return;

or

if (condition) return;

You don't need to (and can't) specify any values, if your method returns void.

Set the maximum character length of a UITextField in Swift

TextField Limit Character After Block the Text in Swift 4

func textField(_ textField: UITextField, shouldChangeCharactersIn range: 
    NSRange,replacementString string: String) -> Bool
{


    if textField == self.txtDescription {
        let maxLength = 200
        let currentString: NSString = textField.text! as NSString
        let newString: NSString = currentString.replacingCharacters(in: range, with: string) as NSString
        return newString.length <= maxLength
    }

    return true


}

Verify if file exists or not in C#

To test whether a file exists in .NET, you can use

System.IO.File.Exists (String)

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Just use these command lines:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

If needed, you can also follow this Ubuntu tutorial.

Make Bootstrap's Carousel both center AND responsive?

in bootstrap v4, i center and fill the carousel img to the screen using

<img class="d-block mx-auto" max-width="100%" max-height="100%">

pretty sure this requires parent elements' height or width to be set

html,body{height:100%;}
.carousel,.carousel-item,.active{height:100%;}
.carousel-inner{height:100%;}

How to avoid .pyc files?

You can set sys.dont_write_bytecode = True in your source, but that would have to be in the first python file loaded. If you execute python somefile.py then you will not get somefile.pyc.

When you install a utility using setup.py and entry_points= you will have set sys.dont_write_bytecode in the startup script. So you cannot rely on the "default" startup script generated by setuptools.

If you start Python with python file as argument yourself you can specify -B:

python -B somefile.py

somefile.pyc would not be generated anyway, but no .pyc files for other files imported too.

If you have some utility myutil and you cannot change that, it will not pass -B to the python interpreter. Just start it by setting the environment variable PYTHONDONTWRITEBYTECODE:

PYTHONDONTWRITEBYTECODE=x myutil

How to disable textbox from editing?

As mentioned above, you can change the property of the textbox "Read Only" to "True" from the properties window.

enter image description here

How can I hide a TD tag using inline JavaScript or CSS?

You can simply hide the <td> tag content by just including a style attribute: style = "display:none"

For e.g

<td style = "display:none" >
<p> I'm invisible </p>
</td>

Generic type conversion FROM string

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

Why compile Python code?

There is a performance increase in running compiled python. However when you run a .py file as an imported module, python will compile and store it, and as long as the .py file does not change it will always use the compiled version.

With any interpeted language when the file is used the process looks something like this:
1. File is processed by the interpeter.
2. File is compiled
3. Compiled code is executed.

obviously by using pre-compiled code you can eliminate step 2, this applies python, PHP and others.

Heres an interesting blog post explaining the differences http://julipedia.blogspot.com/2004/07/compiled-vs-interpreted-languages.html
And here's an entry that explains the Python compile process http://effbot.org/zone/python-compile.htm

Creating a JSON array in C#

You'd better create some class for each item instead of using anonymous objects. And in object you're serializing you should have array of those items. E.g.:

public class Item
{
    public string name { get; set; }
    public string index { get; set; }
    public string optional { get; set; }
}

public class RootObject
{
    public List<Item> items { get; set; }
}

Usage:

var objectToSerialize = new RootObject();
objectToSerialize.items = new List<Item> 
                          {
                             new Item { name = "test1", index = "index1" },
                             new Item { name = "test2", index = "index2" }
                          };

And in the result you won't have to change things several times if you need to change data-structure.

p.s. Here's very nice tool for complex jsons

Return values from the row above to the current row

You can also use =OFFSET([@column];-1;0) if you are in a named table.

How to add a “readonly” attribute to an <input>?

Use the setAttribute property. Note in example that if select 1 apply the readonly attribute on textbox, otherwise remove the attribute readonly.

http://jsfiddle.net/baqxz7ym/2/

document.getElementById("box1").onchange = function(){
  if(document.getElementById("box1").value == 1) {
    document.getElementById("codigo").setAttribute("readonly", true);
  } else {
    document.getElementById("codigo").removeAttribute("readonly");
  }
};

<input type="text" name="codigo" id="codigo"/>

<select id="box1">
<option value="0" >0</option>
<option value="1" >1</option>
<option value="2" >2</option>
</select>

How to use function srand() with time.h?

#include"stdio.h"
#include"conio.h"
#include"time.h"

void main()
{
  time_t t;
  int i;
  srand(time(&t));

  for(i=1;i<=10;i++)
    printf("%c\t",rand()%10);
  getch();
}

Rails 4: assets not loading in production

The default matcher for compiling files includes application.js, application.css and all non-JS/CSS files (this will include all image assets automatically) from app/assets folders including your gems:

If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the precompile array in config/initializers/assets.rb:

Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']

http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets

Swift convert unix time to date and time

Anyway @Nate Cook's answer is accepted but I would like to improve it with better date format.

with Swift 2.2, I can get desired formatted date

//TimeStamp
let timeInterval  = 1415639000.67457
print("time interval is \(timeInterval)")

//Convert to Date
let date = NSDate(timeIntervalSince1970: timeInterval)

//Date formatting
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd, MMMM yyyy HH:mm:a"
dateFormatter.timeZone = NSTimeZone(name: "UTC")
let dateString = dateFormatter.stringFromDate(date)
print("formatted date is =  \(dateString)")

the result is

time interval is 1415639000.67457

formatted date is = 10, November 2014 17:03:PM

Set padding for UITextField with UITextBorderStyleNone

Why not Attributed String !?!, this is one of the blessing feature of IOS 6.0 :)

NSMutableParagraphStyle *mps = [[NSMutableParagraphStyle alloc] init];
            mps.firstLineHeadIndent = 5.0f;
UIColor *placeColor = self.item.bgColor;

textFieldInstance.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"My Place Holder" attributes:@{NSForegroundColorAttributeName: placeColor, NSFontAttributeName : [UIFont systemFontOfSize:7.0f], NSParagraphStyleAttributeName : mps}];

postgresql duplicate key violates unique constraint

I have similar problem but I solved it by removing all the foreign key in my Postgresql

Can I run multiple programs in a Docker container?

There can be only one ENTRYPOINT, but that target is usually a script that launches as many programs that are needed. You can additionally use for example Supervisord or similar to take care of launching multiple services inside single container. This is an example of a docker container running mysql, apache and wordpress within a single container.

Say, You have one database that is used by a single web application. Then it is probably easier to run both in a single container.

If You have a shared database that is used by more than one application, then it would be better to run the database in its own container and the applications each in their own containers.

There are at least two possibilities how the applications can communicate with each other when they are running in different containers:

  1. Use exposed IP ports and connect via them.
  2. Recent docker versions support linking.

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Plotting power spectrum in python

Numpy has a convenience function, np.fft.fftfreq to compute the frequencies associated with FFT components:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2

time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)

plt.plot(freqs[idx], ps[idx])

enter image description here

Note that the largest frequency you see in your case is not 30 Hz, but

In [7]: max(freqs)
Out[7]: 14.950166112956811

You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).

How to map with index in Ruby?

If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index, when called without a block, return an Enumerator object, which you can call Enumerable methods like map on. So you can do:

arr.each_with_index.map { |x,i| [x, i+2] }

In 1.8.6 you can do:

require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }

JavaScript - populate drop down list with array

You'll need to loop through your array elements, create a new DOM node for each and append it to your object.

var select = document.getElementById("selectNumber"); 
var options = ["1", "2", "3", "4", "5"]; 

for(var i = 0; i < options.length; i++) {
    var opt = options[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);
}?

Live example

How is "mvn clean install" different from "mvn install"?

Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.

How can I show a message box with two buttons?

Remember - if you set the buttons to vbOkOnly - it will always return 1.

So you can't decide if a user clicked on the close or the OK button. You just have to add a vbOk option.

Multiple file upload in php

this simple script worked for me.

<?php

foreach($_FILES as $file){
  //echo $file['name']; 
  echo $file['tmp_name'].'</br>'; 
  move_uploaded_file($file['tmp_name'], "./uploads/".$file["name"]);
}

?>

Avoiding NullPointerException in Java

Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.

When the exception is thrown, examine the stack trace and work through the bug.

How to open Emacs inside Bash

Emacs takes many launch options. The one that you are looking for is emacs -nw. This will open Emacs inside the terminal disregarding the DISPLAY environment variable even if it is set. The long form of this flag is emacs --no-window-system.

More information about Emacs launch options can be found in the manual.

How Exactly Does @param Work - Java

You might miss @author and inside of @param you need to explain what's that parameter for, how to use it, etc.

creating a table in ionic

This is the way i use it. It's very simple and work very well.. Ionic html:

  <ion-content>
 

  <ion-grid class="ion-text-center">

    <ion-row class="ion-margin">
      <ion-col>
        <ion-title>
          <ion-text color="default">
            Your title remove if don't want use
          </ion-text>
        </ion-title>
      </ion-col>
    </ion-row>

    <ion-row class="header-row">
      <ion-col>
        <ion-text>Data</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Cliente</ion-text>
      </ion-col>

      <ion-col>
        <ion-text>Pagamento</ion-text>
      </ion-col>
    </ion-row>


    <ion-row>
      <ion-col>
        <ion-text>
            19/10/2020
        </ion-text>
      </ion-col>

        <ion-col>
          <ion-text>
            Nome
          </ion-text>
        </ion-col>
  
        <ion-col>
          <ion-text>
            R$ 200
          </ion-text>
        </ion-col>
    </ion-row>

  </ion-grid>
</ion-content>

CSS:

.header-row {
  background: #7163AA;
  color: #fff;
  font-size: 18px;
}

ion-col {
  border: 1px solid #ECEEEF;
}

Result of the code

How can I put CSS and HTML code in the same file?

<html>
<head>
    <style type="text/css">
    .title {
        color: blue;
        text-decoration: bold;
        text-size: 1em;
    }

    .author {
        color: gray;
    }
    </style>
</head>
<body>
    <p>
    <span class="title">La super bonne</span>
    <span class="author">proposée par Jérém</span>
    </p>
</body>
</html>

On a side note, it would have been much easier to just do this.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

Spring Boot without the web server

For Spring boot v2.1.3.RELEASE, just add the follow properties into application.propertes:

spring.main.web-application-type=none

How do I fix the indentation of selected lines in Visual Studio

Selecting the text to fix, and CtrlK, CtrlF shortcut certainly works. However, I generally find that if a particular method (for instance) has it's indentation messed up, simply removing the closing brace of the method, and re-adding, in fact fixes the indentation anyway, thereby doing without the need to select the code before hand, ergo is quicker. ymmv.

What is the default Jenkins password?

I am a Mac OS user & following credential pair worked for me:
Username: admin
Password: admin

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

Class type check in TypeScript

4.19.4 The instanceof operator

The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type.

So you could use

mySprite instanceof Sprite;

Note that this operator is also in ActionScript but it shouldn't be used there anymore:

The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

TypeScript's instanceof shares the same problems. As it is a language which is still in its development I recommend you to state a proposal of such facility.

See also:

find a minimum value in an array of floats

You need to iterate the 2d array in order to get the min value of each row, then you have to push any gotten min value to another array and finally you need to get the min value of the array where each min row value was pushed

def get_min_value(self, table):
    min_values = []
    for i in range(0, len(table)):
        min_value = min(table[i])
        min_values.append(min_value)

    return min(min_values)

How to pass object from one component to another in Angular 2?

Component 2, the directive component can define a input property (@input annotation in Typescript). And Component 1 can pass that property to the directive component from template.

See this SO answer How to do inter communication between a master and detail component in Angular2?

and how input is being passed to child components. In your case it is directive.

Storing C++ template function definitions in a .CPP file

None of above worked for me, so here is how y solved it, my class have only 1 method templated..

.h

class Model
{
    template <class T>
    void build(T* b, uint32_t number);
};

.cpp

#include "Model.h"
template <class T>
void Model::build(T* b, uint32_t number)
{
    //implementation
}

void TemporaryFunction()
{
    Model m;
    m.build<B1>(new B1(),1);
    m.build<B2>(new B2(), 1);
    m.build<B3>(new B3(), 1);
}

this avoid linker errors, and no need to call TemporaryFunction at all

Notification not showing in Oreo

Try this Code :

_x000D_
_x000D_
public class FirebaseMessagingServices extends com.google.firebase.messaging.FirebaseMessagingService {_x000D_
    private static final String TAG = "MY Channel";_x000D_
    Bitmap bitmap;_x000D_
_x000D_
    @Override_x000D_
    public void onMessageReceived(RemoteMessage remoteMessage) {_x000D_
        super.onMessageReceived(remoteMessage);_x000D_
        Utility.printMessage(remoteMessage.getNotification().getBody());_x000D_
_x000D_
        // Check if message contains a data payload._x000D_
        if (remoteMessage.getData().size() > 0) {_x000D_
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());_x000D_
_x000D_
            String title = remoteMessage.getData().get("title");_x000D_
            String body = remoteMessage.getData().get("body");_x000D_
            String message = remoteMessage.getData().get("message");_x000D_
            String imageUri = remoteMessage.getData().get("image");_x000D_
            String msg_id = remoteMessage.getData().get("msg-id");_x000D_
          _x000D_
_x000D_
            Log.d(TAG, "1: " + title);_x000D_
            Log.d(TAG, "2: " + body);_x000D_
            Log.d(TAG, "3: " + message);_x000D_
            Log.d(TAG, "4: " + imageUri);_x000D_
          _x000D_
_x000D_
            if (imageUri != null)_x000D_
                bitmap = getBitmapfromUrl(imageUri);_x000D_
_x000D_
            }_x000D_
_x000D_
            sendNotification(message, bitmap, title, msg_id);_x000D_
                    _x000D_
        }_x000D_
_x000D_
_x000D_
    }_x000D_
_x000D_
    private void sendNotification(String message, Bitmap image, String title,String msg_id) {_x000D_
        int notifyID = 0;_x000D_
        try {_x000D_
            notifyID = Integer.parseInt(msg_id);_x000D_
        } catch (NumberFormatException e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
_x000D_
        String CHANNEL_ID = "my_channel_01";            // The id of the channel._x000D_
        Intent intent = new Intent(this, HomeActivity.class);_x000D_
        intent.putExtra("title", title);_x000D_
        intent.putExtra("message", message);_x000D_
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);_x000D_
_x000D_
_x000D_
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,_x000D_
                PendingIntent.FLAG_ONE_SHOT);_x000D_
_x000D_
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);_x000D_
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "01")_x000D_
                .setContentTitle(title)_x000D_
                .setSmallIcon(R.mipmap.ic_notification)_x000D_
                .setStyle(new NotificationCompat.BigTextStyle()_x000D_
                        .bigText(message))_x000D_
                .setContentText(message)_x000D_
                .setAutoCancel(true)_x000D_
                .setSound(defaultSoundUri)_x000D_
                .setChannelId(CHANNEL_ID)_x000D_
                .setContentIntent(pendingIntent);_x000D_
_x000D_
        if (image != null) {_x000D_
            notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle()   //Set the Image in Big picture Style with text._x000D_
                    .bigPicture(image)_x000D_
                    .setSummaryText(message)_x000D_
                    .bigLargeIcon(null));_x000D_
        }_x000D_
_x000D_
_x000D_
        NotificationManager notificationManager =_x000D_
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);_x000D_
_x000D_
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {       // For Oreo and greater than it, we required Notification Channel._x000D_
           CharSequence name = "My New Channel";                   // The user-visible name of the channel._x000D_
            int importance = NotificationManager.IMPORTANCE_HIGH;_x000D_
_x000D_
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name, importance); //Create Notification Channel_x000D_
            notificationManager.createNotificationChannel(channel);_x000D_
        }_x000D_
_x000D_
        notificationManager.notify(notifyID /* ID of notification */, notificationBuilder.build());_x000D_
    }_x000D_
_x000D_
    public Bitmap getBitmapfromUrl(String imageUrl) {     //This method returns the Bitmap from Url;_x000D_
        try {_x000D_
            URL url = new URL(imageUrl);_x000D_
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();_x000D_
            connection.setDoInput(true);_x000D_
            connection.connect();_x000D_
            InputStream input = connection.getInputStream();_x000D_
            Bitmap bitmap = BitmapFactory.decodeStream(input);_x000D_
            return bitmap;_x000D_
_x000D_
        } catch (Exception e) {_x000D_
            // TODO Auto-generated catch block_x000D_
            e.printStackTrace();_x000D_
            return null;_x000D_
_x000D_
        }_x000D_
_x000D_
    }_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) on dispatch_semaphore_dispose

I had a different issue that brought me to this question, which will probably be more common than the overrelease issue in the accepted answer.

Root cause was our completion block being called twice due to bad if/else fallthrough in the network handler, leading to two calls of dispatch_group_leave for every one call to dispatch_group_enter.

Completion block called multiple times:

dispatch_group_enter(group);
[self badMethodThatCallsMULTIPLECompletions:^(NSString *completion) {

    // this block is called multiple times
    // one `enter` but multiple `leave`

    dispatch_group_leave(group);
}];

Debug via the dispatch_group's count

Upon the EXC_BAD_INSTRUCTION, you should still have access to your dispatch_group in the debugger. DispatchGroup: check how many "entered"

Print out the dispatch_group and you'll see:

<OS_dispatch_group: group[0x60800008bf40] = { xrefcnt = 0x2, refcnt = 0x1, port = 0x0, count = -1, waiters = 0 }>

When you see count = -1 it indicates that you've over-left the dispatch_group. Be sure to dispatch_enter and dispatch_leave the group in matched pairs.

How to restart Postgresql

macOS:

  1. On the top left of the MacOS menu bar you have the Postgres Icon
  2. Click on it this opens a drop down menu
  3. Click on Stop -> than click on start

Cannot kill Python script with Ctrl-C

KeyboardInterrupt and signals are only seen by the process (ie the main thread)... Have a look at Ctrl-c i.e. KeyboardInterrupt to kill threads in python

JSONObject - How to get a value?

String loudScreaming = json.getJSONObject("LabelData").getString("slogan");

Delete last commit in bitbucket

You can write the command also for Bitbucket as mentioned by Dustin:

git push -f origin HEAD^:master

Note: instead of master you can use any branch. And it deletes just push on Bitbucket.

To remove last commit locally in git use:

git reset --hard HEAD~1

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

Using a separate thread to display a simple please wait message is overkill especially if you don't have much experience with threading.

A much simpler approach is to create a "Please wait" form and display it as a mode-less window just before the slow loading form. Once the main form has finished loading, hide the please wait form.

In this way you are using just the one main UI thread to firstly display the please wait form and then load your main form.

The only limitation to this approach is that your please wait form cannot be animated (such as a animated GIF) because the thread is busy loading your main form.

PleaseWaitForm pleaseWait=new PleaseWaitForm ();

// Display form modelessly
pleaseWait.Show();

//  ALlow main UI thread to properly display please wait form.
Application.DoEvents();

// Show or load the main form.
mainForm.ShowDialog();

No 'Access-Control-Allow-Origin' header in Angular 2 app

Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).

That CORS header will have to be added to that endpoint on the server before you can make ANY requests.

How to make child process die after parent exits?

This solution worked for me:

  • Pass stdin pipe to child - you don't have to write any data into the stream.
  • Child reads indefinitely from stdin until EOF. An EOF signals that the parent has gone.
  • This is foolproof and portable way to detect when the parent has gone. Even if parent crashes, OS will close the pipe.

This was for a worker-type process whose existence only made sense when the parent was alive.

How do I generate random numbers in Dart?

Let me solve this question with a practical example in the form of a simple dice rolling app that calls 1 of 6 dice face images randomly to the screen when tapped.

first declare a variable that generates random numbers (don't forget to import dart.math). Then declare a variable that parses the initial random number within constraints between 1 and 6 as an Integer.

Both variables are static private in order to be initialized once.This is is not a huge deal but would be good practice if you had to initialize a whole bunch of random numbers.

static var _random = new Random();
static var _diceface = _random.nextInt(6) +1 ;

Now create a Gesture detection widget with a ClipRRect as a child to return one of the six dice face images to the screen when tapped.

GestureDetector(
          onTap: () {
            setState(() {
              _diceface = _rnd.nextInt(6) +1 ;
            });
          },
          child: ClipRRect(
            clipBehavior: Clip.hardEdge,
            borderRadius: BorderRadius.circular(100.8),
              child: Image(
                image: AssetImage('images/diceface$_diceface.png'),
                fit: BoxFit.cover,
              ),
          )
        ),

A new random number is generated each time you tap the screen and that number is referenced to select which dice face image is chosen.

I hoped this example helped :)

Dice rolling app using random numbers in dart

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

How to get autocomplete in jupyter notebook without using tab?

I would suggest hinterland extension.

In other answers I couldn't find the method for how to install it from pip, so this is how you install it.

First, install jupyter contrib nbextensions by running

pip install jupyter_contrib_nbextensions

Next install js and css file for jupyter by running

jupyter contrib nbextension install --user

and at the end run,

jupyter nbextension enable hinterland/hinterland

The output of last command will be

Enabling notebook extension hinterland/hinterland...
      - Validating: OK

Where Sticky Notes are saved in Windows 10 1607

It worked for me when HDD with win8.1 crashed and my new HDD has win10. Important to know - Create Legacy folder mentioned in this link. - Remember to rename the StickyNotes.snt to ThresholdNotes.snt. - Restart the app

Find details here https://www.reddit.com/r/Windows10/comments/4wxfds/transfermigrate_sticky_notes_to_new_anniversary/

Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"?

In general you want to program against an interface. This allows you to exchange the implementation at any time. This is very useful especially when you get passed an implementation you don't know.

However, there are certain situations where you prefer to use the concrete implementation. For example when serialize in GWT.

WARNING: UNPROTECTED PRIVATE KEY FILE! when trying to SSH into Amazon EC2 Instance

Make sure that the directory containing the private key files is set to 700

chmod 700 ~/.ec2

Endless loop in C/C++

I would recommend while (1) { } or while (true) { }. It's what most programmers would write, and for readability reasons you should follow the common idioms.

(Ok, so there is an obvious "citation needed" for the claim about most programmers. But from the code I've seen, in C since 1984, I believe it is true.)

Any reasonable compiler would compile all of them to the same code, with an unconditional jump, but I wouldn't be surprised if there are some unreasonable compilers out there, for embedded or other specialized systems.

Is it possible to 'prefill' a google form using data from a google spreadsheet?

You can create a pre-filled form URL from within the Form Editor, as described in the documentation for Drive Forms. You'll end up with a URL like this, for example:

https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=Mike+Jones&entry.787184751=1975-05-09&entry.1381372492&entry.960923899

buildUrls()

In this example, question 1, "Name", has an ID of 726721210, while question 2, "Birthday" is 787184751. Questions 3 and 4 are blank.

You could generate the pre-filled URL by adapting the one provided through the UI to be a template, like this:

function buildUrls() {
  var template = "https://docs.google.com/forms/d/--form-id--/viewform?entry.726721210=##Name##&entry.787184751=##Birthday##&entry.1381372492&entry.960923899";
  var ss = SpreadsheetApp.getActive().getSheetByName("Sheet1");  // Email, Name, Birthday
  var data = ss.getDataRange().getValues();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    var url = template.replace('##Name##',escape(data[i][1]))
                      .replace('##Birthday##',data[i][2].yyyymmdd());  // see yyyymmdd below
    Logger.log(url);  // You could do something more useful here.
  }
};

This is effective enough - you could email the pre-filled URL to each person, and they'd have some questions already filled in.

betterBuildUrls()

Instead of creating our template using brute force, we can piece it together programmatically. This will have the advantage that we can re-use the code without needing to remember to change the template.

Each question in a form is an item. For this example, let's assume the form has only 4 questions, as you've described them. Item [0] is "Name", [1] is "Birthday", and so on.

We can create a form response, which we won't submit - instead, we'll partially complete the form, only to get the pre-filled form URL. Since the Forms API understands the data types of each item, we can avoid manipulating the string format of dates and other types, which simplifies our code somewhat.

(EDIT: There's a more general version of this in How to prefill Google form checkboxes?)

/**
 * Use Form API to generate pre-filled form URLs
 */
function betterBuildUrls() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("Sheet1");
  var data = ss.getDataRange().getValues();  // Data for pre-fill

  var formUrl = ss.getFormUrl();             // Use form attached to sheet
  var form = FormApp.openByUrl(formUrl);
  var items = form.getItems();

  // Skip headers, then build URLs for each row in Sheet1.
  for (var i = 1; i < data.length; i++ ) {
    // Create a form response object, and prefill it
    var formResponse = form.createResponse();

    // Prefill Name
    var formItem = items[0].asTextItem();
    var response = formItem.createResponse(data[i][1]);
    formResponse.withItemResponse(response);

    // Prefill Birthday
    formItem = items[1].asDateItem();
    response = formItem.createResponse(data[i][2]);
    formResponse.withItemResponse(response);

    // Get prefilled form URL
    var url = formResponse.toPrefilledUrl();
    Logger.log(url);  // You could do something more useful here.
  }
};

yymmdd Function

Any date item in the pre-filled form URL is expected to be in this format: yyyy-mm-dd. This helper function extends the Date object with a new method to handle the conversion.

When reading dates from a spreadsheet, you'll end up with a javascript Date object, as long as the format of the data is recognizable as a date. (Your example is not recognizable, so instead of May 9th 1975 you could use 5/9/1975.)

// From http://blog.justin.kelly.org.au/simple-javascript-function-to-format-the-date-as-yyyy-mm-dd/
Date.prototype.yyyymmdd = function() {
  var yyyy = this.getFullYear().toString();                                    
  var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based         
  var dd  = this.getDate().toString();             

  return yyyy + '-' + (mm[1]?mm:"0"+mm[0]) + '-' + (dd[1]?dd:"0"+dd[0]);
};

Change DIV content using ajax, php and jQuery

<script>
$(function(){
    $('.movie').click(function(){
        var this_href=$(this).attr('href');
        $.ajax({
            url:this_href,
            type:'post',
            cache:false,
            success:function(data)
            {
                $('#summary').html(data);
            }
        });
        return false;
    });
});
</script>

Enumerations on PHP

There is a native extension, too. The SplEnum

SplEnum gives the ability to emulate and create enumeration objects natively in PHP.

http://www.php.net/manual/en/class.splenum.php

Attention:

https://www.php.net/manual/en/spl-types.installation.php

The PECL extension is not bundled with PHP.

A DLL for this PECL extension is currently unavailable.

How do I specify a password to 'psql' non-interactively?

An alternative to using the PGPASSWORD environment variable is to use the conninfo string according to the documentation:

An alternative way to specify connection parameters is in a conninfo string or a URI, which is used instead of a database name. This mechanism give you very wide control over the connection.

$ psql "host=<server> port=5432 dbname=<db> user=<user> password=<password>"

postgres=>

SOAP client in .NET - references or examples?

Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.

There are 2 main way of doing this:

A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.

Adding a service reference step by step

The simplest way is to generate proxy classes in C# application (this process is called adding service reference).

  1. Open your project (or create a new one) in visual studio
  2. Right click on the project (on the project and not the solution) in Solution Explorer and click Add Service Reference
  3. A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.

    add service reference dialog

    I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example

  4. Expand Service References in Solution Explorer and double click CalculatorServiceReference (or whatever you named the named the service in the previous step).

    You should see generated proxy class name and namespace.

    In my case, the namespace is SoapClient.CalculatorServiceReference, the name of proxy class is CalculatorSoapClient. As I said above, class names may vary in your case.

    service reference proxy calss

  5. Go to your C# source code and add the following

    using WindowsFormsApplication1.ServiceReference1
    
  6. Now you can call the service this way.

    Service1Client service = new Service1Client();
    int year = service.getCurrentYear();
    

Hope this helps. If you encounter any problems, let us know.

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

CSS Vertical align does not work with float

Edited:

The vertical-align CSS property specifies the vertical alignment of an inline, inline-block or table-cell element.

Read this article for Understanding vertical-align

How to check for file existence

Check out Pathname and in particular Pathname#exist?.

File and its FileTest module are perhaps simpler/more direct, but I find Pathname a nicer interface in general.

SQL Views - no variables?

What I do is create a view that performs the same select as the table variable and link that view into the second view. So a view can select from another view. This achieves the same result

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Run the command below;

sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib
pip install psycopg2

installing JDK8 on Windows XP - advapi32.dll error

Oracle has announced fix for Windows XP installation error

Oracle has decided to fix Windows XP installation. As of the JRE 8u25 release in 10/15/2014 the code of the installer has been changes so that installation on Windows XP is again possible.

However, this does not mean that Oracle is continuing to support Windows XP. They make no guarantee about current and future releases of JRE8 being compatible with Windows XP. It looks like it's a run at your own risk kind of thing.

See the Oracle blog post here.

You can get the latest JRE8 right off the Oracle downloads site.

Telling Python to save a .txt file to a certain directory on Windows and Mac

A small update to this. raw_input() is renamed as input() in Python 3.

Python 3 release note

How to go back last page

in angular 4 use preserveQueryParams, ex:

url: /list?page=1

<a [routerLink]="['edit',id]" [preserveQueryParams]="true"></a>

When clicking the link, you are redirected edit/10?page=1, preserving params

ref: https://angular.io/docs/ts/latest/guide/router.html#!#link-parameters-array

Nullable types: better way to check for null or zero in c#

You code sample will fail. If obj is null then the obj.ToString() will result in a null reference exception. I'd short cut the process and check for a null obj at the start of your helper function. As to your actual question, what's the type you're checking for null or zero? On String there's a great IsNullOrEmpty function, seems to me this would be a great use of extension methods to implement an IsNullOrZero method on the int? type.

Edit: Remember, the '?' is just compiler sugar for the INullable type, so you could probably take an INullable as the parm and then jsut compare it to null (parm == null) and if not null compare to zero.

Merge DLL into EXE?

NOTE: if you're trying to load a non-ILOnly assembly, then

Assembly.Load(block)

won't work, and an exception will be thrown: more details

I overcame this by creating a temporary file, and using

Assembly.LoadFile(dllFile)

Key existence check in HashMap

if(map.get(key) != null || (map.get(key) == null && map.containsKey(key)))

How can I find out if I have Xcode commandline tools installed?

I was able to find my version of Xcode on maxOS Sierra using this command:

pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version

as per this answer.

What is a "callback" in C and how are they implemented?

A simple call back program. Hope it answers your question.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include "../../common_typedef.h"

typedef void (*call_back) (S32, S32);

void test_call_back(S32 a, S32 b)
{
    printf("In call back function, a:%d \t b:%d \n", a, b);
}

void call_callback_func(call_back back)
{
    S32 a = 5;
    S32 b = 7;

    back(a, b);
}

S32 main(S32 argc, S8 *argv[])
{
    S32 ret = SUCCESS;

    call_back back;

    back = test_call_back;

    call_callback_func(back);

    return ret;
}

How to fix the "508 Resource Limit is reached" error in WordPress?

I've already encountered this error and this is the best solution I've found:

In your root folder (probably called public_html)please add this code to your .htaccess file...

REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999

#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>
<Files xmlrpc.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

In your wp-admin folder please add this code to your .htaccess file...

#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
        order deny,allow
        deny from all
        allow from 00.00.00.000
    </Files>

From: https://www.quora.com/I-am-using-shared-hosting-and-my-I-O-usage-is-full-after-every-minute-What-is-this-I-O-usage-in-cPanel-How-can-I-reduce-it

Owl Carousel Won't Autoplay

Yes, its a typing error.

Write

autoPlay

not

autoplay

The autoplay-plugin code defines the variable as "autoPlay".

Windows command for file size only

Try forfiles:

forfiles /p C:\Temp /m file1.txt /c "cmd /c echo @fsize"

The forfiles command runs command c for each file m in directory p.

The variable @fsize is replaced with the size of each file.

If the file C:\Temp\file1.txt is 27 bytes, forfiles runs this command:

cmd /c echo 27

Which prints 27 to the screen.

As a side-effect, it clears your screen as if you had run the cls command.

How to randomize (shuffle) a JavaScript array?

Use the underscore.js library. The method _.shuffle() is nice for this case. Here is an example with the method:

var _ = require("underscore");

var arr = [1,2,3,4,5,6];
// Testing _.shuffle
var testShuffle = function () {
  var indexOne = 0;
    var stObj = {
      '0': 0,
      '1': 1,
      '2': 2,
      '3': 3,
      '4': 4,
      '5': 5
    };
    for (var i = 0; i < 1000; i++) {
      arr = _.shuffle(arr);
      indexOne = _.indexOf(arr, 1);
      stObj[indexOne] ++;
    }
    console.log(stObj);
};
testShuffle();

WARNING: Exception encountered during context initialization - cancelling refresh attempt

  1. To closed ideas,
  2. To remove all folder and file C:/Users/UserName/.m2/org/*,
  3. Open ideas and update Maven project,(right click on project -> maven->update maven project)
  4. After that update the project.

form confirm before submit

$('#myForm').submit(function() {
    var c = confirm("Click OK to continue?");
    return c; //you can just return c because it will be true or false
});

Rails: How do I create a default value for attributes in Rails activerecord's model?

Just strengthening Jim's answer

Using presence one can do

class Task < ActiveRecord::Base
  before_save :default_values
  def default_values
    self.status = status.presence || 'P'
  end
end

How do I get the row count of a Pandas DataFrame?

...building on Jan-Philip Gehrcke's answer.

The reason why len(df) or len(df.index) is faster than df.shape[0]:

Look at the code. df.shape is a @property that runs a DataFrame method calling len twice.

df.shape??
Type:        property
String form: <property object at 0x1127b33c0>
Source:
# df.shape.fget
@property
def shape(self):
    """
    Return a tuple representing the dimensionality of the DataFrame.
    """
    return len(self.index), len(self.columns)

And beneath the hood of len(df)

df.__len__??
Signature: df.__len__()
Source:
    def __len__(self):
        """Returns length of info axis, but here we use the index """
        return len(self.index)
File:      ~/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py
Type:      instancemethod

len(df.index) will be slightly faster than len(df) since it has one less function call, but this is always faster than df.shape[0]

How to use "like" and "not like" in SQL MSAccess for the same field?

what's the problem with:

field like "*AA*" and field not like "*BB*"

it should be working.

Could you post some example of your data?

jquery input select all on focus

After careful review, I propose this as a far cleaner solution within this thread:

$("input").focus(function(){
    $(this).on("click.a keyup.a", function(e){      
        $(this).off("click.a keyup.a").select();
    });
});

Demo in jsFiddle

The Problem:

Here's a little bit of explanation:

First, let's take a look at the order of events when you mouse or tab into a field.
We can log all the relevant events like this:

$("input").on("mousedown focus mouseup click blur keydown keypress keyup change",
              function(e) { console.log(e.type); });

focus events

Note: I've changed this solution to use click rather than mouseup as it happens later in the event pipeline and seemed to be causing some issues in firefox as per @Jocie's comment

Some browsers attempt to position the cursor during the mouseup or click events. This makes sense since you might want to start the caret in one position and drag over to highlight some text. It can't make a designation about the caret position until you have actually lifted the mouse. So functions that handle focus are fated to respond too early, leaving the browser to override your positioning.

But the rub is that we really do want to handle the focus event. It lets us know the first time that someone has entered the field. After that point, we don't want to continue to override user selection behavior.

The Solution:

Instead, within the focus event handler, we can quickly attach listeners for the click (click in) and keyup (tab in) events that are about to fire.

Note: The keyup of a tab event will actually fire in the new input field, not the previous one

We only want to fire the event once. We could use .one("click keyup), but this would call the event handler once for each event type. Instead, as soon as either mouseup or keyup is pressed we'll call our function. The first thing we'll do, is remove the handlers for both. That way it won't matter whether we tabbed or moused in. The function should execute exactly once.

Note: Most browsers naturally select all text during a tab event, but as animatedgif pointed out, we still want to handle the keyup event, otherwise the mouseup event will still be lingering around anytime we've tabbed in. We listen to both so we can turn off the listeners as soon as we've processed the selection.

Now, we can call select() after the browser has made its selection so we're sure to override the default behavior.

Finally, for extra protection, we can add event namespaces to the mouseup and keyup functions so the .off() method doesn't remove any other listeners that might be in play.


Tested in IE 10+, FF 28+, & Chrome 35+


Alternatively, if you want to extend jQuery with a function called once that will fire exactly once for any number of events:

$.fn.once = function (events, callback) {
    return this.each(function () {
        var myCallback = function (e) {
            callback.call(this, e);
            $(this).off(events, myCallback);
        };
        $(this).on(events, myCallback);
    });
};

Then you can simplify the code further like this:

$("input").focus(function(){
    $(this).once("click keyup", function(e){      
        $(this).select();
    });
});

Demo in fiddle

Alternating Row Colors in Bootstrap 3 - No Table

I was having trouble coloring rows in table using bootstrap table-striped class then realized delete table-striped class and do this in css file

tr:nth-of-type(odd)
{  
background-color: red;
}
tr:nth-of-type(even)
{  
background-color: blue;
}

The bootstrap table-striped class will over ride your selectors.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

That's done for header files so that the contents only appear once in each preprocessed source file, even if it's included more than once (usually because it's included from other header files). The first time it's included, the symbol CLASS_H (known as an include guard) hasn't been defined yet, so all the contents of the file are included. Doing this defines the symbol, so if it's included again, the contents of the file (inside the #ifndef/#endif block) are skipped.

There's no need to do this for the source file itself since (normally) that's not included by any other files.

For your last question, class.h should contain the definition of the class, and declarations of all its members, associated functions, and whatever else, so that any file that includes it has enough information to use the class. The implementations of the functions can go in a separate source file; you only need the declarations to call them.

Convert a Unicode string to an escaped ASCII string

class Program
{
        static void Main(string[] args)
        {
            char[] originalString = "This string contains the unicode character Pi(p)".ToCharArray();
            StringBuilder asAscii = new StringBuilder(); // store final ascii string and Unicode points
            foreach (char c in originalString)
            {
                // test if char is ascii, otherwise convert to Unicode Code Point
                int cint = Convert.ToInt32(c);
                if (cint <= 127 && cint >= 0)
                    asAscii.Append(c);
                else
                    asAscii.Append(String.Format("\\u{0:x4} ", cint).Trim());
            }
            Console.WriteLine("Final string: {0}", asAscii);
            Console.ReadKey();
        }
}

All non-ASCII chars are converted to their Unicode Code Point representation and appended to the final string.

Difference between DOM parentNode and parentElement

In Internet Explorer, parentElement is undefined for SVG elements, whereas parentNode is defined.

Loading an image to a <img> from <input file>

_x000D_
_x000D_
var outImage ="imagenFondo";_x000D_
function preview_2(obj)_x000D_
{_x000D_
 if (FileReader)_x000D_
 {_x000D_
  var reader = new FileReader();_x000D_
  reader.readAsDataURL(obj.files[0]);_x000D_
  reader.onload = function (e) {_x000D_
  var image=new Image();_x000D_
  image.src=e.target.result;_x000D_
  image.onload = function () {_x000D_
   document.getElementById(outImage).src=image.src;_x000D_
  };_x000D_
  }_x000D_
 }_x000D_
 else_x000D_
 {_x000D_
      // Not supported_x000D_
 }_x000D_
}
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>preview photo</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<form>_x000D_
 <input type="file" onChange="preview_2(this);"><br>_x000D_
 <img id="imagenFondo" style="height: 300px;width: 300px;">_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

can't access mysql from command line mac

adding this code to my .profile worked for me: :/usr/local/mysql/bin

Thanks.

P.S This .profile is located in your user/ path. Its a hidden file so you will have to get to it either by a command in Terminal or using an html editor.

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

After my initial struggle with the link and controller functions and reading quite a lot about them, I think now I have the answer.

First lets understand,

How do angular directives work in a nutshell:

  • We begin with a template (as a string or loaded to a string)

    var templateString = '<div my-directive>{{5 + 10}}</div>';

  • Now, this templateString is wrapped as an angular element

    var el = angular.element(templateString);

  • With el, now we compile it with $compile to get back the link function.

    var l = $compile(el)

    Here is what happens,

    • $compile walks through the whole template and collects all the directives that it recognizes.
    • All the directives that are discovered are compiled recursively and their link functions are collected.
    • Then, all the link functions are wrapped in a new link function and returned as l.
  • Finally, we provide scope function to this l (link) function which further executes the wrapped link functions with this scope and their corresponding elements.

    l(scope)

  • This adds the template as a new node to the DOM and invokes controller which adds its watches to the scope which is shared with the template in DOM.

enter image description here

Comparing compile vs link vs controller :

  • Every directive is compiled only once and link function is retained for re-use. Therefore, if there's something applicable to all instances of a directive should be performed inside directive's compile function.

  • Now, after compilation we have link function which is executed while attaching the template to the DOM. So, therefore we perform everything that is specific to every instance of the directive. For eg: attaching events, mutating the template based on scope, etc.

  • Finally, the controller is meant to be available to be live and reactive while the directive works on the DOM (after getting attached). Therefore:

    (1) After setting up the view[V] (i.e. template) with link. $scope is our [M] and $controller is our [C] in M V C

    (2) Take advantage the 2-way binding with $scope by setting up watches.

    (3) $scope watches are expected to be added in the controller since this is what is watching the template during run-time.

    (4) Finally, controller is also used to be able to communicate among related directives. (Like myTabs example in https://docs.angularjs.org/guide/directive)

    (5) It's true that we could've done all this in the link function as well but its about separation of concerns.

Therefore, finally we have the following which fits all the pieces perfectly :

enter image description here

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

How to get a table creation script in MySQL Workbench?

Not sure if I fully understood your problem, but if it's just about creating export scripts, you should forward engineer to SQL script - Ctrl + Shift + G or File -> Export -> first option.

Change one value based on another value in pandas

This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.

In this way it's possible to avoid key errors.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
...     def __missing__(self, key):
...         return ''
...     
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

The same thing can be done more simply in the following way. The use of the 'default' argument for the get method of a dict object makes it unnecessary to subclass a dict.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

pandas: best way to select all columns whose names start with X

Based on @EdChum's answer, you can try the following solution:

df[df.columns[pd.Series(df.columns).str.contains("foo")]]

This will be really helpful in case not all the columns you want to select start with foo. This method selects all the columns that contain the substring foo and it could be placed in at any point of a column's name.

In essence, I replaced .startswith() with .contains().

Difference between _self, _top, and _parent in the anchor tag target attribute

target="_blank"

Opens a new window and show the related data.

target="_self"

Opens the window in the same frame, it means existing window itself.

target="_top"

Opens the linked document in the full body of the window.

target="_parent"

Opens data in the size of parent window.

Entity Framework : How do you refresh the model when the db changes?

This might help you guys.(I've applied this to my Projects)

Here's the 3 easy steps.

  1. Go to your Solution Explorer. Look for .edmx file (Usually found on root level)
  2. Open that .edmx file, a Model Diagram window appears. Right click anywhere on that window and select "Update Model from Database". An Update Wizard window appears. Click Finish to update your model.
  3. Save that .edmx file.

That's it. It will sync/refresh your Model base on the changes on your database.

For detailed instructions. Please visit the link below.

EF Database First with ASP.NET MVC: Changing the Database and updating its model.

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

How to set up subdomains on IIS 7

This one drove me crazy... basically you need two things:

1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.

2) You must add an additional website in IIS 7 named subdomain.example.com

  • Sites > Add Website
  • Site Name: subdomain.example.com
  • Physical Path: select the subdomain directory
  • Binding: same ip as example.com
  • Host name: subdomain.example.com

RE error: illegal byte sequence on Mac OS X

Does anyone know how to get sed to print the position of the illegal byte sequence? Or does anyone know what the illegal byte sequence is?

$ uname -a
Darwin Adams-iMac 18.7.0 Darwin Kernel Version 18.7.0: Tue Aug 20 16:57:14 PDT 2019; root:xnu-4903.271.2~2/RELEASE_X86_64 x86_64

I got part of the way to answering the above just by using tr.

I have a .csv file that is a credit card statement and I am trying to import it into Gnucash. I am based in Switzerland so I have to deal with words like Zürich. Suspecting Gnucash does not like " " in numeric fields, I decide to simply replace all

; ;

with

;;

Here goes:

$ head -3 Auswertungen.csv | tail -1 | sed -e 's/; ;/;;/g'
sed: RE error: illegal byte sequence

I used od to shed some light: Note the 374 halfway down this od -c output

$ head -3 Auswertungen.csv | tail -1 | od -c
0000000    1   6   8   7       9   6   1   9       7   1   2   2   ;   5
0000020    4   6   8       8   7   X   X       X   X   X   X       2   6
0000040    6   0   ;   M   Y       N   A   M   E       I   S   X   ;   1
0000060    4   .   0   2   .   2   0   1   9   ;   9   5   5   2       -
0000100        M   i   t   a   r   b   e   i   t   e   r   r   e   s   t
0000120                Z 374   r   i   c   h                            
0000140    C   H   E   ;   R   e   s   t   a   u   r   a   n   t   s   ,
0000160        B   a   r   s   ;   6   .   2   0   ;   C   H   F   ;    
0000200    ;   C   H   F   ;   6   .   2   0   ;       ;   1   5   .   0
0000220    2   .   2   0   1   9  \n                                    
0000227

Then I thought I might try to persuade tr to substitute 374 for whatever the correct byte code is. So first I tried something simple, which didn't work, but had the side effect of showing me where the troublesome byte was:

$ head -3 Auswertungen.csv | tail -1 | tr . .  ; echo
tr: Illegal byte sequence
1687 9619 7122;5468 87XX XXXX 2660;MY NAME ISX;14.02.2019;9552 - Mitarbeiterrest   Z

You can see tr bails at the 374 character.

Using perl seems to avoid this problem

$ head -3 Auswertungen.csv | tail -1 | perl -pne 's/; ;/;;/g'
1687 9619 7122;5468 87XX XXXX 2660;ADAM NEALIS;14.02.2019;9552 - Mitarbeiterrest   Z?rich       CHE;Restaurants, Bars;6.20;CHF;;CHF;6.20;;15.02.2019

Setting up a git remote origin

Using SSH

git remote add origin ssh://login@IP/path/to/repository

Using HTTP

git remote add origin http://IP/path/to/repository

However having a simple git pull as a deployment process is usually a bad idea and should be avoided in favor of a real deployment script.

How to include an HTML page into another HTML page without frame/iframe?

If you're willing to use jquery, there is a handy jquery plugin called "inc".

I use it often for website prototyping, where I just want to present the client with static HTML with no backend layer that can be quickly created/edited/improved/re-presented

http://johannburkard.de/blog/programming/javascript/inc-a-super-tiny-client-side-include-javascript-jquery-plugin.html

For example, things like the menu and footer need to be shown on every page, but you dont want to end up with a copy-and-paste-athon

You can include a page fragment as follows

<p class="inc:footer.htm"></p>

How to check if a service is running via batch file and start it, if it is not running?

Language independent version.

@Echo Off
Set ServiceName=Jenkins


SC queryex "%ServiceName%"|Find "STATE"|Find /v "RUNNING">Nul&&(
    echo %ServiceName% not running 
    echo Start %ServiceName%

    Net start "%ServiceName%">nul||(
        Echo "%ServiceName%" wont start 
        exit /b 1
    )
    echo "%ServiceName%" started
    exit /b 0
)||(
    echo "%ServiceName%" working
    exit /b 0
)

Java: recommended solution for deep cloning/copying an instance

I'd suggest to override Object.clone(), call super.clone() first and than call ref = ref.clone() on all references that you want to have deep copied. It's more or less Do it yourself approach but needs a bit less coding.

How to set up a cron job to run an executable every hour?

use

path_to_exe >> log_file

to see the output of your command also errors can be redirected with

path_to_exe &> log_file

also you can use

crontab -l

to check if your edits were saved.

Python - Check If Word Is In A String

What about to split the string and strip words punctuation?

w in [ws.strip(',.?!') for ws in p.split()]

Or working the case:

w.lower() in [ws.strip(',.?!') for ws in p.lower().split()]

Maybe that way:

def wsearch(word, phrase):
    # Attention about punctuation and about split characters
    punctuation = ',.?!'
    return word.lower() in [words.strip(punctuation) for words in phrase.lower().split()]

Sample:

print(wsearch('CAr', 'I own a caR.'))

I didn't check performance...

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

Is there a link to the "latest" jQuery library on Google APIs?

No. There isn't..

But, for development there is such a link on the jQuery code site.

Adding a column to an existing table in a Rails migration

You can also add column to a specific position using before column or after column like:

rails generate migration add_dob_to_customer dob:date

The migration file will generate the following code except after: :email. you need to add after: :email or before: :email

class AddDobToCustomer < ActiveRecord::Migration[5.2]
  def change
    add_column :customers, :dob, :date, after: :email
  end
end

C# Threading - How to start and stop a thread

Thread th = new Thread(function1);
th.Start();
th.Abort();

void function1(){
//code here
}

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

How should a model be structured in MVC?

More oftenly most of the applications will have data,display and processing part and we just put all those in the letters M,V and C.

Model(M)-->Has the attributes that holds state of application and it dont know any thing about V and C.

View(V)-->Has displaying format for the application and and only knows about how-to-digest model on it and does not bother about C.

Controller(C)---->Has processing part of application and acts as wiring between M and V and it depends on both M,V unlike M and V.

Altogether there is separation of concern between each. In future any change or enhancements can be added very easily.

Using async/await with a forEach loop

A simple drop-in solution for replacing a forEach() await loop that is not working is replacing forEach with map and adding Promise.all( to the beginning.

For example:

await y.forEach(async (x) => {

to

await Promise.all(y.map(async (x) => {

An extra ) is needed at the end.

Git: How to remove file from index without deleting files from any repository

Had the very same issue this week when I accidentally committed, then tried to remove a build file from a shared repository, and this:

http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html

has worked fine for me and not mentioned so far.

git update-index --assume-unchanged <file>

To remove the file you're interested in from version control, then use all your other commands as normal.

git update-index --no-assume-unchanged <file>

If you ever wanted to put it back in.

Edit: please see comments from Chris Johnsen and KPM, this only works locally and the file remains under version control for other users if they don't also do it. The accepted answer gives more complete/correct methods for dealing with this. Also some notes from the link if using this method:

Obviously there’s quite a few caveats that come into play with this. If you git add the file directly, it will be added to the index. Merging a commit with this flag on will cause the merge to fail gracefully so you can handle it manually.

Maven: best way of linking custom external JAR to my project?

The most efficient and cleanest way I have found to deal with this problem is by using Github Packages

  1. Create a simple empty public/private repository on GitHub as per your requirement whether you want your external jar to be publicly hosted or not.

  2. Run below maven command to deploy you external jar in above created github repository

    mvn deploy:deploy-file \ -DgroupId= your-group-id \ -DartifactId= your-artifact-id \ -Dversion= 1.0.0 -Dpackaging= jar -Dfile= path-to-file \ -DrepositoryId= id-to-map-on-server-section-of-settings.xml \ -Durl=https://maven.pkg.github.com/github-username/github-reponame-created-in-above-step

    Above command will deploy you external jar in GitHub repository mentioned in -Durl=. You can refer this link on How to deploy dependencies as GitHub Packages GitHub Package Deployment Tutorial

  3. After that you can add the dependency using groupId,artifactId and version mentioned in above step in maven pom.xml and run mvn install

  4. Maven will fetch the dependency of external jar from GitHub Packages registry and provide in your maven project.

  5. For this to work you will also need to configure you maven's settings.xml to fetch from GitHub Package registry.

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

How can I pass selected row to commandLink inside dataTable or ui:repeat?

In my view page:

<p:dataTable  ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}" 
               process="@this" update=":mainform:dialog_content"
           oncomplete="dlg2.show()">
    <h:graphicImage library="images" name="view.png"/>
    <f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>

backing bean

 public void viewDetail(ActionEvent e) {

    String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");

    for (DTO item : list) {
        if (item.get("trxNo").toString().equals(trxNo)) {
            System.out.println(trxNo);
            setSelectedItem(item);
            break;
        }
    }
}

Why does an SSH remote command get fewer environment variables then when run manually?

I found an easy resolution for this issue was to add source /etc/profile to the top of the script.sh file I was trying to run on the target system. On the systems here, this caused the environmental variables which were needed by script.sh to be configured as if running from a login shell.

In one of the prior responses it was suggested that ~/.bashr_profile etc... be used. I didn't spend much time on this but, the problem with this is if you ssh to a different user on the target system than the shell on the source system from which you log in it appeared to me that this causes the source system user name to be used for the ~.

What does the variable $this mean in PHP?

I know its old question, anyway another exact explanation about $this. $this is mainly used to refer properties of a class.

Example:

Class A
{
   public $myname;    //this is a member variable of this class

function callme() {
    $myname = 'function variable';
    $this->myname = 'Member variable';
    echo $myname;                  //prints function variable
    echo $this->myname;              //prints member variable
   }
}

output:

function variable

member variable

How to "Open" and "Save" using java

You may also want to consider the possibility of using SWT (another Java GUI library). Pros and cons of each are listed at:

Java Desktop application: SWT vs. Swing

error: pathspec 'test-branch' did not match any file(s) known to git

When I run git branch, it only shows *master, not the remaining two branches.

git branch doesn't list test_branch, because no such local branch exist in your local repo, yet. When cloning a repo, only one local branch (master, here) is created and checked out in the resulting clone, irrespective of the number of branches that exist in the remote repo that you cloned from. At this stage, test_branch only exist in your repo as a remote-tracking branch, not as a local branch.

And when I run

git checkout test-branch

I get the following error [...]

You must be using an "old" version of Git. In more recent versions (from v1.7.0-rc0 onwards),

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat [git checkout <branch>] as equivalent to

$ git checkout -b <branch> --track <remote>/<branch>

Simply run

git checkout -b test_branch --track origin/test_branch

instead. Or update to a more recent version of Git.

Is it possible to ignore one single specific line with Pylint?

I believe you're looking for...

import config.logging_settings  # @UnusedImport

Note the double space before the comment to avoid hitting other formatting warnings.

Also, depending on your IDE (if you're using one), there's probably an option to add the correct ignore rule (e.g., in Eclipse, pressing Ctrl + 1, while the cursor is over the warning, will auto-suggest @UnusedImport).