Programs & Examples On #Main method

Invoking Java main method with parameters from Eclipse

Another idea:

Place all your parameters in a properties file (one parameter = one property in this file), then in your main method, load this file (using Properties.load(*fileInputStream*)). So if you want to modify one argument, you will just need to edit your args.properties file, and launch your application without more steps to do...

Of course, this is only for development purposes, but can be really helpfull if you have to change your arguments often...

Arguments to main in C

Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

.jar error - could not find or load main class

You can always run this:

java -cp HelloWorld.jar HelloWorld

-cp HelloWorld.jar adds the jar to the classpath, then HelloWorld runs the class you wrote.

To create a runnable jar with a main class with no package, add Class-Path: . to the manifest:

Manifest-Version: 1.0
Class-Path: .
Main-Class: HelloWorld

I would advise using a package to give your class its own namespace. E.g.

package com.stackoverflow.user.blrp;

public class HelloWorld {
    ...
}

How to validate domain credentials?

Here's how to determine a local user:

    public bool IsLocalUser()
    {
        return windowsIdentity.AuthenticationType == "NTLM";
    }

Edit by Ian Boyd

You should not use NTLM anymore at all. It is so old, and so bad, that Microsoft's Application Verifier (which is used to catch common programming mistakes) will throw a warning if it detects you using NTLM.

Here's a chapter from the Application Verifier documentation about why they have a test if someone is mistakenly using NTLM:

Why the NTLM Plug-in is Needed

NTLM is an outdated authentication protocol with flaws that potentially compromise the security of applications and the operating system. The most important shortcoming is the lack of server authentication, which could allow an attacker to trick users into connecting to a spoofed server. As a corollary of missing server authentication, applications using NTLM can also be vulnerable to a type of attack known as a “reflection” attack. This latter allows an attacker to hijack a user’s authentication conversation to a legitimate server and use it to authenticate the attacker to the user’s computer. NTLM’s vulnerabilities and ways of exploiting them are the target of increasing research activity in the security community.

Although Kerberos has been available for many years many applications are still written to use NTLM only. This needlessly reduces the security of applications. Kerberos cannot however replace NTLM in all scenarios – principally those where a client needs to authenticate to systems that are not joined to a domain (a home network perhaps being the most common of these). The Negotiate security package allows a backwards-compatible compromise that uses Kerberos whenever possible and only reverts to NTLM when there is no other option. Switching code to use Negotiate instead of NTLM will significantly increase the security for our customers while introducing few or no application compatibilities. Negotiate by itself is not a silver bullet – there are cases where an attacker can force downgrade to NTLM but these are significantly more difficult to exploit. However, one immediate improvement is that applications written to use Negotiate correctly are automatically immune to NTLM reflection attacks.

By way of a final word of caution against use of NTLM: in future versions of Windows it will be possible to disable the use of NTLM at the operating system. If applications have a hard dependency on NTLM they will simply fail to authenticate when NTLM is disabled.

How the Plug-in Works

The Verifier plug detects the following errors:

  • The NTLM package is directly specified in the call to AcquireCredentialsHandle (or higher level wrapper API).

  • The target name in the call to InitializeSecurityContext is NULL.

  • The target name in the call to InitializeSecurityContext is not a properly-formed SPN, UPN or NetBIOS-style domain name.

The latter two cases will force Negotiate to fall back to NTLM either directly (the first case) or indirectly (the domain controller will return a “principal not found” error in the second case causing Negotiate to fall back).

The plug-in also logs warnings when it detects downgrades to NTLM; for example, when an SPN is not found by the Domain Controller. These are only logged as warnings since they are often legitimate cases – for example, when authenticating to a system that is not domain-joined.

NTLM Stops

5000 – Application Has Explicitly Selected NTLM Package

Severity – Error

The application or subsystem explicitly selects NTLM instead of Negotiate in the call to AcquireCredentialsHandle. Even though it may be possible for the client and server to authenticate using Kerberos this is prevented by the explicit selection of NTLM.

How to Fix this Error

The fix for this error is to select the Negotiate package in place of NTLM. How this is done will depend on the particular Network subsystem being used by the client or server. Some examples are given below. You should consult the documentation on the particular library or API set that you are using.

APIs(parameter) Used by Application    Incorrect Value  Correct Value  
=====================================  ===============  ========================
AcquireCredentialsHandle (pszPackage)  “NTLM”           NEGOSSP_NAME “Negotiate”

What is /dev/null 2>&1?

Let's break >> /dev/null 2>&1 statement into parts:


Part 1: >> output redirection

This is used to redirect the program output and append the output at the end of the file. More...


Part 2: /dev/null special file

This is a Pseudo-devices special file.

Command ls -l /dev/null will give you details of this file:

crw-rw-rw-. 1 root root 1, 3 Mar 20 18:37 /dev/null

Did you observe crw? Which means it is a pseudo-device file which is of character-special-file type that provides serial access.

/dev/null accepts and discards all input; produces no output (always returns an end-of-file indication on a read). Reference: Wikipedia


Part 3: 2>&1 file descriptor

Whenever you execute a program, the operating system always opens three files, standard input, standard output, and standard error as we know whenever a file is opened, the operating system (from kernel) returns a non-negative integer called a file descriptor. The file descriptor for these files are 0, 1, and 2, respectively.

So 2>&1 simply says redirect standard error to standard output.

& means whatever follows is a file descriptor, not a filename.

In short, by using this command you are telling your program not to shout while executing.

What is the importance of using 2>&1?

If you don't want to produce any output, even in case of some error produced in the terminal. To explain more clearly, let's consider the following example:

$ ls -l > /dev/null

For the above command, no output was printed in the terminal, but what if this command produces an error:

$ ls -l file_doesnot_exists > /dev/null
ls: cannot access file_doesnot_exists: No such file or directory

Despite I'm redirecting output to /dev/null, it is printed in the terminal. It is because we are not redirecting error output to /dev/null, so in order to redirect error output as well, it is required to add 2>&1:

$ ls -l file_doesnot_exists > /dev/null 2>&1

Pandas KeyError: value not in index

I had a very similar issue. I got the same error because the csv contained spaces in the header. My csv contained a header "Gender " and I had it listed as:

[['Gender']]

If it's easy enough for you to access your csv, you can use the excel formula trim() to clip any spaces of the cells.

or remove it like this

df.columns = df.columns.to_series().apply(lambda x: x.strip())

Ignore Typescript Errors "property does not exist on value of type"

I know the question is already closed but I've found it searching for same TypeScriptException, maybe some one else hit this question searching for this problem.

The problem lays in missing TypeScript typing:

var coordinates = outerElement[0].getBBox();

Throws The property 'getBBox' does not exist on value of type 'HTMLElement'.


The easiest way is to explicitly type variable as `any`
var outerHtmlElement: any = outerElement[0];
var coordinates = outerHtmlElement.getBBox();

Edit, late 2016

Since TypeScript 1.6, the prefered casting operator is as, so those lines can be squashed into:

let coordinates = (outerElement[0] as any).getBBox();


Other solutions

Of course if you'd like to do it right, which is an overkill sometimes, you can:

  1. Create own interface which simply extends HTMLElement
  2. Introduce own typing which extends HTMLElement

How do I get the name of the current executable in C#?

System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;

will give you FileName of your app like; "MyApplication.exe"

Test if numpy array contains only zeros

As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0 is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*

>>> a = np.zeros(10)
>>> not np.any(a)
True

However, the answer claimed that any was faster than other options due partly to short-circuiting. As of 2018, Numpy's all and any do not short-circuit.

If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba:

import numba as nb

# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
    for x in array.flat:
        if x:
            return True
    return False

# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
    for x in array.flat:
        if not x:
            return False
    return True

These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero is the slowest.

Some input to check performance:

import numpy as np

n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]

Check:

## count_nonzero
%timeit np.count_nonzero(all_0) 
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

* Helpful all and any equivalences:

np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))

Get integer value from string in swift

Simple but dirty way

// Swift 1.2
if let intValue = "42".toInt() {
    let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int(stringNumber)

// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)

The extension-way

This is better, really, because it'll play nicely with locales and decimals.

extension String {

    var numberValue:NSNumber? {
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .DecimalStyle
        return formatter.numberFromString(self)
    }
}

Now you can simply do:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue

SQL Server: Cannot insert an explicit value into a timestamp column

Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.

This fails with the timestamp error:

Insert Into Table2
Select Table1.A, Table1.B, Table1.TimeStamp From Table1

This works:

Insert Into Table2
Select Table1.A, Table1.B, null From Table1

Convert multidimensional array into single array

I had come across the same requirement to flatter multidimensional array into single dimensional array than search value using text in key. here is my code

$data = '{
    "json_data": [{
            "downtime": true,
            "pfix": {
                "max": 100,
                "threshold": 880
            },
            "ints": {
                "int": [{
                    "rle": "pri",
                    "device": "laptop",
                    "int": "Ether3",
                    "ip": "127.0.0.3"
                }],
                "eth": {
                    "lan": 57
                }
            }
        },
        {
            "downtime": false,
            "lsi": "987654",
            "pfix": {
                "min": 10000,
                "threshold": 890
            },
            "mana": {
                "mode": "NONE"
            },
            "ints": {
                "int": [{
                    "rle": "sre",
                    "device": "desk",
                    "int": "Ten",
                    "ip": "1.1.1.1",
                    "UF": true
                }],
                "ethernet": {
                    "lan": 2
                }
            }
        }
    ]
}
';

$data = json_decode($data,true);


$stack = &$data;
$separator = '.';
$toc = array();

while ($stack) {
    list($key, $value) = each($stack);
    unset($stack[$key]);
    if (is_array($value)) {
        $build = array($key => ''); # numbering without a title.
        foreach ($value as $subKey => $node)
            $build[$key . $separator . $subKey] = $node;
        $stack = $build + $stack;
        continue;
    }
    if(!is_numeric($key)){
        $toc[$key] = $value;
    }
}


echo '<pre/>';
print_r($toc);


My output:

Array
(
    [json_data] => 
    [json_data.0] => 
    [json_data.0.downtime] => 1
    [json_data.0.pfix] => 
    [json_data.0.pfix.max] => 100
    [json_data.0.pfix.threshold] => 880
    [json_data.0.ints] => 
    [json_data.0.ints.int] => 
    [json_data.0.ints.int.0] => 
    [json_data.0.ints.int.0.rle] => pri
    [json_data.0.ints.int.0.device] => laptop
    [json_data.0.ints.int.0.int] => Ether3
    [json_data.0.ints.int.0.ip] => 127.0.0.3
    [json_data.0.ints.eth] => 
    [json_data.0.ints.eth.lan] => 57
    [json_data.1] => 
    [json_data.1.downtime] => 
    [json_data.1.lsi] => 987654
    [json_data.1.pfix] => 
    [json_data.1.pfix.min] => 10000
    [json_data.1.pfix.threshold] => 890
    [json_data.1.mana] => 
    [json_data.1.mana.mode] => NONE
    [json_data.1.ints] => 
    [json_data.1.ints.int] => 
    [json_data.1.ints.int.0] => 
    [json_data.1.ints.int.0.rle] => sre
    [json_data.1.ints.int.0.device] => desk
    [json_data.1.ints.int.0.int] => Ten
    [json_data.1.ints.int.0.ip] => 1.1.1.1
    [json_data.1.ints.int.0.UF] => 1
    [json_data.1.ints.ethernet] => 
    [json_data.1.ints.ethernet.lan] => 2
)

Ruby capitalize every word first letter

"hello world".split.each{|i| i.capitalize!}.join(' ')

What is WebKit and how is it related to CSS?

Update: So apparently, WebKit is a HTML/CSS web browser rendering engine for Safari/Chrome. Are there such engines for IE/Opera/Firefox and what are the differences, pros and cons of using one over the other? Can I use WebKit features in Firefox for example?

Every browser is backed by a rendering engine to draw the HTML/CSS web page.

  • IE → Trident (discontinued)
  • Edge ? EdgeHTML (clean-up fork of Trident) (Edge switched to Blink in 2019)
  • Firefox → Gecko
  • Opera → Presto (no longer uses Presto since Feb 2013, consider Opera = Chrome, therefore Blink nowadays)
  • Safari → WebKit
  • Chrome → Blink (a fork of Webkit).

See Comparison of web browser engines for a list of comparisons in different areas.

The ultimate question... is WebKit supported by IE?

Not natively.

Why is Visual Studio 2013 very slow?

I was also facing this issue for quite long time. Below are the steps that I perform, and it works for me always:

  • Deleting the solution's .suo file.
  • Deleting the Temporary ASP.NET Files (You can find it at find it at %WINDOW%\Microsoft.NET\Framework\Temporary ASP.NET Files)
  • Deleting all breakpoints in the application.

Pure JavaScript: a function like jQuery's isNumeric()

function IsNumeric(val) {
    return Number(parseFloat(val)) === val;
}

CSS Input field text color of inputted text

I always do input prompts, like this:

    <input style="color: #C0C0C0;" value="[email protected]" 
    onfocus="this.value=''; this.style.color='#000000'">

Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:

    <script language = "text/Javascript"> 
    cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
    function clearField(t){                   //declaring the array outside of the
    if(! cleared[t.id]){                      // function makes it static and global
        cleared[t.id] = 1;  // you could use true and false, but that's more typing
        t.value='';         // with more chance of typos
        t.style.color='#000000';
        }
    }
    </script>

Your <input> field then looks like this:

    <input id = 0; style="color: #C0C0C0;" value="[email protected]" 
    onfocus=clearField(this)>

How can I upgrade specific packages using pip and a requirements file?

According to pip documentation example 3:

pip install --upgrade django

But based on my experience, using this method will also upgrade any package related to it. Example:

Assume you want to upgrade somepackage that require Django >= 1.2.4 using this kind of method it will also upgrade somepackage and django to the newest update. Just to be safe, do:

# Assume you want to keep Django 1.2.4
pip install --upgrade somepackage django==1.2.4

Doing this will upgrade somepackage and keeping Django to the 1.2.4 version.

JavaScript hide/show element

You can also use this code to show/hide elements:

document.getElementById(id).style.visibility = "hidden";
document.getElementById(id).style.visibility = "visible";

Note The difference between style.visibility and style.display is when using visibility:hidden unlike display:none, the tag is not visible, but space is allocated for it on the page. The tag is rendered, it just isn't seen on the page.

See this link to see the differences.

Position absolute but relative to parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

Order a List (C#) by many fields?

Use ThenBy:

var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)

See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx

How do I resolve a TesseractNotFoundError?

One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:

pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

How to overlay one div over another div

The new Grid CSS specification provides a far more elegant solution. Using position: absolute may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.

Most minimal Grid Overlay example:

HTML

<div class="container">
  <div class="content">This is the content</div>
  <div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>

CSS

.container {
  display: grid;
}

.content, .overlay {
  grid-area: 1 / 1;
}

That's it. If you don't build for Internet Explorer, your code will most probably work.

How to get multiple selected values from select box in JSP?

Something along the lines of (using JSTL):

<p>Selected Values:
<ul>
  <c:forEach items="${paramValues['select2']}" var="selectedValue">
    <li><c:out value="${selectedValue}" /></li>
  </c:forEach>
</ul>
</p>

How to remove selected commit log entries from a Git repository while keeping their changes?

I find this process much safer and easier to understand by creating another branch from the SHA1 of A and cherry-picking the desired changes so I can make sure I'm satisfied with how this new branch looks. After that, it is easy to remove the old branch and rename the new one.

git checkout <SHA1 of A>
git log #verify looks good
git checkout -b rework
git cherry-pick <SHA1 of D>
....
git log #verify looks good
git branch -D <oldbranch>
git branch -m rework <oldbranch>

Test if string is URL encoded in PHP

Here is something i just put together.

if ( urlencode(urldecode($data)) === $data){
    echo 'string urlencoded';
} else {
    echo 'string is NOT urlencoded';
}

Trying to get Laravel 5 email to work

None of the above solutions worked for me on localhost. I even allowed access from less secure apps, allowed access through display unlock captcha and set the verify peer and verify peer name to false for SSL.

Eventually, I used the open source SMTP testing solution of MailHog. The steps are as follows:

  1. Download the latest version of MailHog for your OS
  2. Specify the following settings in your .env file

MAIL_DRIVER=smtp

MAIL_HOST=127.0.0.1

MAIL_PORT=1025

MAIL_USERNAME=testuser

MAIL_PASSWORD=testpwd

MAIL_ENCRYPTION=null

[email protected]

  1. Run the downloaded file of MailHog
  2. Send Email
  3. Check sent email by going to localhost:8025

What is an Intent in Android?

According to their documentation:

An Intent is an object that provides runtime binding between separate components (such as two activities). The Intent represents an app’s "intent to do something." You can use intents for a wide variety of tasks, but most often they’re used to start another activity.

Here is the link with example: http://developer.android.com/training/basics/firstapp/starting-activity.html#BuildIntent

As the document describes, in order to start an activity (you also need to understand what activity is) use the intent like below

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}

How to use Bash to create a folder if it doesn't already exist?

Cleaner way, exploit shortcut evaluation of shell logical operators. Right side of the operator is executed only if left side is true.

[ ! -d /home/mlzboy/b2c2/shared/db ] && mkdir -p /home/mlzboy/b2c2/shared/db

What is a unix command for deleting the first N characters of a line?

Here is simple function, tested in bash. 1st param of function is string, 2nd param is number of characters to be stripped

function stringStripNCharsFromStart { echo ${1:$2:${#1}} }

Usage: enter image description here

What svn command would list all the files modified on a branch?

echo You must invoke st from within branch directory
SvnUrl=`svn info | grep URL | sed 's/URL: //'`
SvnVer=`svn info | grep Revision | sed 's/Revision: //'`
svn diff -r $SvnVer --summarize $SvnUrl

fatal: could not create work tree dir 'kivy'

sudo chmod 777 DIR_NAME
cd DIR_NAME
git clone https://github.com/mygitusername/kivy.git

should work fine

Responsive bootstrap 3 timepicker?

As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

Split value from one field to two

This takes smhg from here and curt's from Last index of a given substring in MySQL and combines them. This is for mysql, all I needed was to get a decent split of name to first_name last_name with the last name a single word, the first name everything before that single word, where the name could be null, 1 word, 2 words, or more than 2 words. Ie: Null; Mary; Mary Smith; Mary A. Smith; Mary Sue Ellen Smith;

So if name is one word or null, last_name is null. If name is > 1 word, last_name is last word, and first_name all words before last word.

Note that I've already trimmed off stuff like Joe Smith Jr. ; Joe Smith Esq. and so on, manually, which was painful, of course, but it was small enough to do that, so you want to make sure to really look at the data in the name field before deciding which method to use.

Note that this also trims the outcome, so you don't end up with spaces in front of or after the names.

I'm just posting this for others who might google their way here looking for what I needed. This works, of course, test it with the select first.

It's a one time thing, so I don't care about efficiency.

SELECT TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        LEFT(`name`, LENGTH(`name`) - LOCATE(' ', REVERSE(`name`))),
        `name`
    ) 
) AS first_name,
TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        SUBSTRING_INDEX(`name`, ' ', -1) ,
        NULL
    ) 
) AS last_name
FROM `users`;


UPDATE `users` SET
`first_name` = TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        LEFT(`name`, LENGTH(`name`) - LOCATE(' ', REVERSE(`name`))),
        `name`
    ) 
),
`last_name` = TRIM( 
    IF(
        LOCATE(' ', `name`) > 0,
        SUBSTRING_INDEX(`name`, ' ', -1) ,
        NULL
    ) 
);

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

Upper memory limit?

Python can use all memory available to its environment. My simple "memory test" crashes on ActiveState Python 2.6 after using about

1959167 [MiB]

On jython 2.5 it crashes earlier:

 239000 [MiB]

probably I can configure Jython to use more memory (it uses limits from JVM)

Test app:

import sys

sl = []
i = 0
# some magic 1024 - overhead of string object
fill_size = 1024
if sys.version.startswith('2.7'):
    fill_size = 1003
if sys.version.startswith('3'):
    fill_size = 497
print(fill_size)
MiB = 0
while True:
    s = str(i).zfill(fill_size)
    sl.append(s)
    if i == 0:
        try:
            sys.stderr.write('size of one string %d\n' % (sys.getsizeof(s)))
        except AttributeError:
            pass
    i += 1
    if i % 1024 == 0:
        MiB += 1
        if MiB % 25 == 0:
            sys.stderr.write('%d [MiB]\n' % (MiB))

In your app you read whole file at once. For such big files you should read the line by line.

Java GC (Allocation Failure)

"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.

GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html

How to enable C++11 in Qt Creator?

Add this to your .pro file

QMAKE_CXXFLAGS += -std=c++11

or

CONFIG += c++11

Ruby: What is the easiest way to remove the first element from an array?

Use shift method

array.shift(n) => Remove first n elements from array 
array.shift(1) => Remove first element

https://ruby-doc.org/core-2.2.0/Array.html#method-i-shift

Select records from NOW() -1 Day

Be aware that the result may be slightly different than you expect.

NOW() returns a DATETIME.

And INTERVAL works as named, e.g. INTERVAL 1 DAY = 24 hours.

So if your script is cron'd to run at 03:00, it will miss the first three hours of records from the 'oldest' day.

To get the whole day use CURDATE() - INTERVAL 1 DAY. This will get back to the beginning of the previous day regardless of when the script is run.

Rendering HTML inside textarea

With an editable div you can use the method document.execCommand (more details) to easily provide the support for the tags you specified and for some other functionality..

_x000D_
_x000D_
#text {_x000D_
    width : 500px;_x000D_
 min-height : 100px;_x000D_
 border : 2px solid;_x000D_
}
_x000D_
<div id="text" contenteditable="true"></div>_x000D_
<button onclick="document.execCommand('bold');">toggle bold</button>_x000D_
<button onclick="document.execCommand('italic');">toggle italic</button>_x000D_
<button onclick="document.execCommand('underline');">toggle underline</button>
_x000D_
_x000D_
_x000D_

How to determine whether a given Linux is 32 bit or 64 bit?

If you were running a 64 bit platform you would see x86_64 or something very similar in the output from uname -a

To get your specific machine hardware name run

uname -m

You can also call

getconf LONG_BIT

which returns either 32 or 64

R object identification

attributes(someObject) 

Can also be useful

Import error: No module name urllib2

For a script working with Python 2 (tested versions 2.7.3 and 2.6.8) and Python 3 (3.2.3 and 3.3.2+) try:

#! /usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

html = urlopen("http://www.google.com/")
print(html.read())

Write applications in C or C++ for Android?

For anyone coming to this via Google, note that starting from SDK 1.6 Android now has an official native SDK.

You can download the Android NDK (Native Development Kit) from here: https://developer.android.com/ndk/downloads/index.html

Also there is an blog post about the NDK:
http://android-developers.blogspot.com/2009/06/introducing-android-15-ndk-release-1.html

WPF User Control Parent

Try using the following:

Window parentWindow = Window.GetWindow(userControlReference);

The GetWindow method will walk the VisualTree for you and locate the window that is hosting your control.

You should run this code after the control has loaded (and not in the Window constructor) to prevent the GetWindow method from returning null. E.g. wire up an event:

this.Loaded += new RoutedEventHandler(UserControl_Loaded); 

Vuex - passing multiple parameters to mutation

Mutations expect two arguments: state and payload, where the current state of the store is passed by Vuex itself as the first argument and the second argument holds any parameters you need to pass.

The easiest way to pass a number of parameters is to destruct them:

mutations: {
    authenticate(state, { token, expiration }) {
        localStorage.setItem('token', token);
        localStorage.setItem('expiration', expiration);
    }
}

Then later on in your actions you can simply

store.commit('authenticate', {
    token,
    expiration,
});

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

There is one alternate solution (NOT the best solution) for this problem, but works. Using flag you can handle it, like below

/**
 * Flag to avoid "java.lang.IllegalStateException: Can not perform this action after
 * onSaveInstanceState". Avoid Fragment transaction until onRestoreInstanceState or onResume
 * gets called.
 */
private boolean isOnSaveInstanceStateCalled = false;


@Override
public void onRestoreInstanceState(final Bundle bundle) {
    .....
    isOnSaveInstanceStateCalled = false;
    .....
}

@Override
public void onSaveInstanceState(final Bundle outState) {
    .....
    isOnSaveInstanceStateCalled = true;
    .....
}

@Override
public void onResume() {
    super.onResume();
    isOnSaveInstanceStateCalled = false;
    .....
}

And you can check this boolean value while doing fragment transaction.

private void fragmentReplace(Fragment fragment, String fragmentTag){
    if (!isOnSaveInstanceStateCalled) {
        getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.layout_container, fragment, fragmentTag)
                .commit();
    }
}

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

What is the best way to do a substring in a batch file?

Well, for just getting the filename of your batch the easiest way would be to just use %~n0.

@echo %~n0

will output the name (without the extension) of the currently running batch file (unless executed in a subroutine called by call). The complete list of such “special” substitutions for path names can be found with help for, at the very end of the help:

In addition, substitution of FOR variable references has been enhanced. You can now use the following optional syntax:

%~I         - expands %I removing any surrounding quotes (")
%~fI        - expands %I to a fully qualified path name
%~dI        - expands %I to a drive letter only
%~pI        - expands %I to a path only
%~nI        - expands %I to a file name only
%~xI        - expands %I to a file extension only
%~sI        - expanded path contains short names only
%~aI        - expands %I to file attributes of file
%~tI        - expands %I to date/time of file
%~zI        - expands %I to size of file
%~$PATH:I   - searches the directories listed in the PATH
               environment variable and expands %I to the
               fully qualified name of the first one found.
               If the environment variable name is not
               defined or the file is not found by the
               search, then this modifier expands to the
               empty string

The modifiers can be combined to get compound results:

%~dpI       - expands %I to a drive letter and path only
%~nxI       - expands %I to a file name and extension only
%~fsI       - expands %I to a full path name with short names only

To precisely answer your question, however: Substrings are done using the :~start,length notation:

%var:~10,5%

will extract 5 characters from position 10 in the environment variable %var%.

NOTE: The index of the strings is zero based, so the first character is at position 0, the second at 1, etc.

To get substrings of argument variables such as %0, %1, etc. you have to assign them to a normal environment variable using set first:

:: Does not work:
@echo %1:~10,5

:: Assign argument to local variable first:
set var=%1
@echo %var:~10,5%

The syntax is even more powerful:

  • %var:~-7% extracts the last 7 characters from %var%
  • %var:~0,-4% would extract all characters except the last four which would also rid you of the file extension (assuming three characters after the period [.]).

See help set for details on that syntax.

Annotation-specified bean name conflicts with existing, non-compatible bean def

In an XML file, there is a sequence of declarations, and you may override a previous definition with a newer one. When you use annotations, there is no notion of before or after. All the beans are at the same level. You defined two beans with the same name, and Spring doesn't know which one it should choose.

Give them a different name (staticConverterDAO, inMemoryConverterDAO for example), create an alias in the Spring XML file (theConverterDAO for example), and use this alias when injecting the converter:

@Autowired @Qualifier("theConverterDAO")

Set NOW() as Default Value for datetime datatype?

As of MySQL 5.6.5, you can use the DATETIME type with a dynamic default value:

CREATE TABLE foo (
    creation_time      DATETIME DEFAULT   CURRENT_TIMESTAMP,
    modification_time  DATETIME ON UPDATE CURRENT_TIMESTAMP
)

Or even combine both rules:

modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Reference:
http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html
http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html

Prior to 5.6.5, you need to use the TIMESTAMP data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated TIMESTAMP field can exist per table.

CREATE TABLE mytable (
  mydate TIMESTAMP
)

See: http://dev.mysql.com/doc/refman/5.1/en/create-table.html

If you want to prevent MySQL from updating the timestamp value on UPDATE (so that it only triggers on INSERT) you can change the definition to:

CREATE TABLE mytable (
  mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)

How to compare types

You can compare for exactly the same type using:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof returns the Type object from a given class.

But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

How can I see which Git branches are tracking which remote / upstream branch?

I use this alias

git config --global alias.track '!f() { ([ $# -eq 2 ] && ( echo "Setting tracking for branch " $1 " -> " $2;git branch --set-upstream $1 $2; ) || ( git for-each-ref --format="local: %(refname:short) <--sync--> remote: %(upstream:short)" refs/heads && echo --Remotes && git remote -v)); }; f'

then

git track

Adding n hours to a date in Java?

You can use this method, It is easy to understand and implement :

public static java.util.Date AddingHHMMSSToDate(java.util.Date date, int nombreHeure, int nombreMinute, int nombreSeconde) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.add(Calendar.HOUR_OF_DAY, nombreHeure);
    calendar.add(Calendar.MINUTE, nombreMinute);
    calendar.add(Calendar.SECOND, nombreSeconde);
    return calendar.getTime();
}

Transposing a 1D NumPy array

You can convert an existing vector into a matrix by wrapping it in an extra set of square brackets...

from numpy import *
v=array([5,4]) ## create a numpy vector
array([v]).T ## transpose a vector into a matrix

numpy also has a matrix class (see array vs. matrix)...

matrix(v).T ## transpose a vector into a matrix

Non-invocable member cannot be used like a method?

It have happened because you are trying to use the property "OffenceBox.Text" like a method. Try to remove parenteses from OffenceBox.Text() and it'll work fine.

Remember that you cannot create a method and a property with the same name in a class.


By the way, some alias could confuse you, since sometimes it's method or property, e.g: "Count" alias:


Namespace: System.Linq

using System.Linq

namespace Teste
{
    public class TestLinq
    {
        public return Foo()
        {
            var listX = new List<int>();
            return listX.Count(x => x.Id == 1);
        }
    }
}


Namespace: System.Collections.Generic

using System.Collections.Generic

namespace Teste
{
    public class TestList
    {
        public int Foo()
        {
            var listX = new List<int>();
            return listX.Count;
        }
    }
}

How to check a string against null in java?

With Java 7 you can use

if (Objects.equals(foo, null)) {
    ...
}

which will return true if both parameters are null.

How to open google chrome from terminal?

on mac terminal (at least in ZSH): open stackoverflow.com (opens site in new tab in your chrome default browser)

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

Make cross-domain ajax JSONP request with jQuery

Concept explained

Are you trying do a cross-domain AJAX call? Meaning, your service is not hosted in your same web application path? Your web-service must support method injection in order to do JSONP.

Your code seems fine and it should work if your web services and your web application hosted in the same domain.

When you do a $.ajax with dataType: 'jsonp' meaning that jQuery is actually adding a new parameter to the query URL.

For instance, if your URL is http://10.211.2.219:8080/SampleWebService/sample.do then jQuery will add ?callback={some_random_dynamically_generated_method}.

This method is more kind of a proxy actually attached in window object. This is nothing specific but does look something like this:

window.some_random_dynamically_generated_method = function(actualJsonpData) {
    //here actually has reference to the success function mentioned with $.ajax
    //so it just calls the success method like this: 
    successCallback(actualJsonData);
}

Summary

Your client code seems just fine. However, you have to modify your server-code to wrap your JSON data with a function name that passed with query string. i.e.

If you have reqested with query string

?callback=my_callback_method

then, your server must response data wrapped like this:

my_callback_method({your json serialized data});

how to take user input in Array using java?

You can do the following:

    import java.util.Scanner;

    public class Test {

            public static void main(String[] args) {

            int arr[];
            Scanner scan = new Scanner(System.in);
            // If you want to take 5 numbers for user and store it in an int array
            for(int i=0; i<5; i++) {
                System.out.print("Enter number " + (i+1) + ": ");
                arr[i] = scan.nextInt();    // Taking user input
            }

            // For printing those numbers
            for(int i=0; i<5; i++) 
                System.out.println("Number " + (i+1) + ": " + arr[i]);
        }
    }

Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest

We see this a lot with OAuth2 integrations. We provide API services to our Customers, and they'll naively try to put their private key into an AJAX call. This is really poor security. And well-coded API Gateways, backends for frontend, and other such proxies, do not allow this. You should get this error.

I will quote @aspillers comment and change a single word: "Access-Control-Allow-Origin is a header sent in a server response which indicates IF the client is allowed to see the contents of a result".

ISSUE: The problem is that a developer is trying to include their private key inside a client-side (browser) JavaScript request. They will get an error, and this is because they are exposing their client secret.

SOLUTION: Have the JavaScript web application talk to a backend service that holds the client secret securely. That backend service can authenticate the web app to the OAuth2 provider, and get an access token. Then the web application can make the AJAX call.

How to pass an object from one activity to another on Android

I found a simple & elegant method:

  • NO Parcelable
  • NO Serializable
  • NO Static Field
  • No Event Bus

Method 1

Code for the first activity:

    final Object objSent = new Object();
    final Bundle bundle = new Bundle();
    bundle.putBinder("object_value", new ObjectWrapperForBinder(objSent));
    startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));        
    Log.d(TAG, "original object=" + objSent);

Code for the second activity:

    final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value")).getData();
    Log.d(TAG, "received object=" + objReceived);

you will find objSent & objReceived have the same hashCode, so they are identical.

But why can we pass a java object in this way?

Actually, android binder will create global JNI reference for java object and release this global JNI reference when there are no reference for this java object. binder will save this global JNI reference in the Binder object.

*CAUTION: this method ONLY work unless the two activities run in the same process, otherwise throw ClassCastException at (ObjectWrapperForBinder)getIntent().getExtras().getBinder("object_value") *

class ObjectWrapperForBinder defination

public class ObjectWrapperForBinder extends Binder {

    private final Object mData;

    public ObjectWrapperForBinder(Object data) {
        mData = data;
    }

    public Object getData() {
        return mData;
    }
}

Method 2

  • for the sender,
    1. use custom native method to add your java object to JNI global reference table(via JNIEnv::NewGlobalRef)
    2. put the return integer (actually, JNIEnv::NewGlobalRef return jobject, which is a pointer, we can cast it to int safely) to your Intent(via Intent::putExtra)
  • for the receiver
    1. get integer from Intent(via Intent::getInt)
    2. use custom native method to restore your java object from JNI global reference table (via JNIEnv::NewLocalRef)
    3. remove item from JNI global reference table(via JNIEnv::DeleteGlobalRef),

But Method 2 has a little but serious issue, if the receiver fail to restore the java object (for example, some exception happen before restore the java object, or the receiver Activity does not exist at all), then the java object will become an orphan or memory leak, Method 1 don't have this issue, because android binder will handle this exception

Method 3

To invoke the java object remotely, we will create a data contract/interface to describe the java object, we will use the aidl file

IDataContract.aidl

package com.example.objectwrapper;
interface IDataContract {
    int func1(String arg1);
    int func2(String arg1);
}

Code for the first activity

    final IDataContract objSent = new IDataContract.Stub() {

        @Override
        public int func2(String arg1) throws RemoteException {
            // TODO Auto-generated method stub
            Log.d(TAG, "func2:: arg1=" + arg1);
            return 102;
        }

        @Override
        public int func1(String arg1) throws RemoteException {
            // TODO Auto-generated method stub
            Log.d(TAG, "func1:: arg1=" + arg1);
            return 101;
        }
    };
    final Bundle bundle = new Bundle();
    bundle.putBinder("object_value", objSent.asBinder());
    startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));
    Log.d(TAG, "original object=" + objSent);

Code for the second activity:

change the android:process attribute in AndroidManifest.xml to a non-empty process name to make sure the second activity run in another process

    final IDataContract objReceived = IDataContract.Stub.asInterface(getIntent().getExtras().getBinder("object_value"));
    try {
        Log.d(TAG, "received object=" + objReceived + ", func1()=" + objReceived.func1("test1") + ", func2()=" + objReceived.func2("test2"));
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

In this way, we can pass an interface between two activities even though they run in different process, and call the interface method remotely

Method 4

method 3 seem not simple enough because we must implement an aidl interface. If you just want to do simple task and the method return value is unnecessary, we can use android.os.Messenger

Code for the first activity( sender):

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";

    public static final int MSG_OP1 = 1;
    public static final int MSG_OP2 = 2;

    public static final String EXTRA_MESSENGER = "messenger";

    private final Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.e(TAG, "handleMessage:: msg=" + msg);
            switch (msg.what) {
            case MSG_OP1:

                break;
            case MSG_OP2:
                break;

            default:

                break;
            }
            super.handleMessage(msg);
        }

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startActivity(new Intent(this, SecondActivity.class).putExtra(EXTRA_MESSENGER, new Messenger(mHandler)));
    }
}

Code for the second activity ( receiver ):

public class SecondActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        final Messenger messenger = getIntent().getParcelableExtra(MainActivity.EXTRA_MESSENGER);
        try {
            messenger.send(Message.obtain(null, MainActivity.MSG_OP1, 101, 1001, "10001"));
            messenger.send(Message.obtain(null, MainActivity.MSG_OP2, 102, 1002, "10002"));
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

All the Messenger.send will execute in a Handler asynchronously and sequentially.

Actually, android.os.Messenger is also an aidl interface, if you have the android source code, you can find a file named IMessenger.aidl

package android.os;

import android.os.Message;

/** @hide */
oneway interface IMessenger {
    void send(in Message msg);
}

HTML how to clear input using javascript?

Try this :

<script type="text/javascript">
function clearThis(target){
    if(target.value == "[email protected]")
    {
        target.value= "";
    }
}
</script>

React Checkbox not sending onChange

onChange will not call handleChange on mobile when using defaultChecked. As an alternative you can can use onClick and onTouchEnd.

<input onClick={this.handleChange} onTouchEnd={this.handleChange} type="checkbox" defaultChecked={!!this.state.complete} />;

Can a java lambda have more than 1 parameter?

To make the use of lambda : There are three type of operation:
1. Accept parameter --> Consumer
2. Test parameter return boolean --> Predicate
3. Manipulate parameter and return value --> Function

Java Functional interface upto two parameter:
Single parameter interface
Consumer
Predicate
Function

Two parameter interface
BiConsumer
BiPredicate
BiFunction

For more than two, you have to create functional interface as follow(Consumer type):

@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
    public void accept(T t, U u, V v, W w, X x);
}

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

For those who like to work close to the metal, here is a command that will clear out the unwanted soot, without needing any special tools or scripts:

adb logcat "eglCodecCommon:S"

Making a POST call instead of GET using urllib2

This may have been answered before: Python URLLib / URLLib2 POST.

Your server is likely performing a 302 redirect from http://myserver/post_service to http://myserver/post_service/. When the 302 redirect is performed, the request changes from POST to GET (see Issue 1401). Try changing url to http://myserver/post_service/.

Remove multiple objects with rm()

Another variation you can try is(expanding @mnel's answer) if you have many temp'x'.

here "n" could be the number of temp variables present

rm(list = c(paste("temp",c(1:n),sep="")))

Can I animate absolute positioned element with CSS transition?

try this:

.test {
    position:absolute;
    background:blue;
    width:200px;
    height:200px;
    top:40px;
    transition:left 1s linear;
    left: 0;
}

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

You can do this:

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).

I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.

In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.

Converting String to Double in Android

I would do it this way:

try {
  txtProt = (EditText) findViewById(R.id.Protein); // Same
  p = txtProt.getText().toString(); // Same
  protein = Double.parseDouble(p); // Make use of autoboxing.  It's also easier to read.
} catch (NumberFormatException e) {
  // p did not contain a valid double
}

EDIT: "the program force closes immediately without leaving any info in the logcat"

I don't know bout not leaving information in the logcat output, but a force-close generally means there's an uncaught exception - like a NumberFormatException.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

What are non-recursive mutexes good for?

They are absolutely good when you have to make sure the mutex is unlocked before doing something. This is because pthread_mutex_unlock can guarantee that the mutex is unlocked only if it is non-recursive.

pthread_mutex_t      g_mutex;

void foo()
{
    pthread_mutex_lock(&g_mutex);
    // Do something.
    pthread_mutex_unlock(&g_mutex);

    bar();
}

If g_mutex is non-recursive, the code above is guaranteed to call bar() with the mutex unlocked.

Thus eliminating the possibility of a deadlock in case bar() happens to be an unknown external function which may well do something that may result in another thread trying to acquire the same mutex. Such scenarios are not uncommon in applications built on thread pools, and in distributed applications, where an interprocess call may spawn a new thread without the client programmer even realising that. In all such scenarios it's best to invoke the said external functions only after the lock is released.

If g_mutex was recursive, there would be simply no way to make sure it is unlocked before making a call.

How to pad a string with leading zeros in Python 3

Since python 3.6 you can use fstring :

>>> length = 1
>>> print(f'length = {length:03}')
length = 001

What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files?

All three template options - <%@include>, <jsp:include> and <%@tag> are valid, and all three cover different use cases.

With <@include>, the JSP parser in-lines the content of the included file into the JSP before compilation (similar to a C #include). You'd use this option with simple, static content: for example, if you wanted to include header, footer, or navigation elements into every page in your web-app. The included content becomes part of the compiled JSP and there's no extra cost at runtime.

<jsp:include> (and JSTL's <c:import>, which is similar and even more powerful) are best suited to dynamic content. Use these when you need to include content from another URL, local or remote; when the resource you're including is itself dynamic; or when the included content uses variables or bean definitions that conflict with the including page. <c:import> also allows you to store the included text in a variable, which you can further manipulate or reuse. Both these incur an additional runtime cost for the dispatch: this is minimal, but you need to be aware that the dynamic include is not "free".

Use tag files when you want to create reusable user interface components. If you have a List of Widgets, say, and you want to iterate over the Widgets and display properties of each (in a table, or in a form), you'd create a tag. Tags can take arguments, using <%@tag attribute> and these arguments can be either mandatory or optional - somewhat like method parameters.

Tag files are a simpler, JSP-based mechanism of writing tag libraries, which (pre JSP 2.0) you had to write using Java code. It's a lot cleaner to write JSP tag files when there's a lot of rendering to do in the tag: you don't need to mix Java and HTML code as you'd have to do if you wrote your tags in Java.

Sys is undefined

Make sure that any client scripts you have that interact with .NET AJAX have the following line at the end:

if (typeof(Sys) !== 'undefined')  Sys.Application.notifyScriptLoaded();

This tells the script manager that the whole script file has loaded and that it can begin to call client methods

Create list of single item repeated N times

You can also write:

[e] * n

You should note that if e is for example an empty list you get a list with n references to the same list, not n independent empty lists.

Performance testing

At first glance it seems that repeat is the fastest way to create a list with n identical elements:

>>> timeit.timeit('itertools.repeat(0, 10)', 'import itertools', number = 1000000)
0.37095273281943264
>>> timeit.timeit('[0] * 10', 'import itertools', number = 1000000)
0.5577236771712819

But wait - it's not a fair test...

>>> itertools.repeat(0, 10)
repeat(0, 10)  # Not a list!!!

The function itertools.repeat doesn't actually create the list, it just creates an object that can be used to create a list if you wish! Let's try that again, but converting to a list:

>>> timeit.timeit('list(itertools.repeat(0, 10))', 'import itertools', number = 1000000)
1.7508119747063233

So if you want a list, use [e] * n. If you want to generate the elements lazily, use repeat.

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

One way is to simply destroy the listener once you are done with it.

var removeListener = $scope.$on('navBarRight-ready', function () {
        $rootScope.$broadcast('workerProfile-display', $scope.worker)
        removeListener(); //destroy the listener
    })

HttpGet with HTTPS : SSLPeerUnverifiedException

Method returning a "secureClient" (in a Java 7 environnement - NetBeans IDE and GlassFish Server: port https by default 3920 ), hope this could help :

public DefaultHttpClient secureClient() {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    SSLSocketFactory sf;

    KeyStore trustStore;
    FileInputStream trustStream = null;
    File truststoreFile;
    // java.security.cert.PKIXParameters for the trustStore
    PKIXParameters pkixParamsTrust;

    KeyStore keyStore;
    FileInputStream keyStream = null;
    File keystoreFile;
    // java.security.cert.PKIXParameters for the keyStore
    PKIXParameters pkixParamsKey;

    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        truststoreFile = new File(TRUSTSTORE_FILE);
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystoreFile = new File(KEYSTORE_FILE);
        try {
            trustStream = new FileInputStream(truststoreFile);
            keyStream = new FileInputStream(keystoreFile);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            trustStore.load(trustStream, PASSWORD.toCharArray());
            keyStore.load(keyStream, PASSWORD.toCharArray());
        } catch (IOException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (CertificateException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsTrust = new PKIXParameters(trustStore);
            // accepts Server certificate generated with keytool and (auto) signed by SUN
            pkixParamsTrust.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            pkixParamsKey = new PKIXParameters(keyStore);
            // accepts Client certificate generated with keytool and (auto) signed by SUN
            pkixParamsKey.setPolicyQualifiersRejected(false);
        } catch (InvalidAlgorithmParameterException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            sf = new SSLSocketFactory(trustStore);
            ClientConnectionManager manager = httpclient.getConnectionManager();
            manager.getSchemeRegistry().register(new Scheme("https", 3920, sf));
        } catch (KeyManagementException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnrecoverableKeyException ex) {
            Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(ApacheHttpRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
    // use the httpclient for any httpRequest
    return httpclient;
}

MySQL error 1449: The user specified as a definer does not exist

you can create user with name web2vi and grant all privilage

Remove duplicate elements from array in Ruby

Just another alternative if anyone cares.

You can also use the to_set method of an array which converts the Array into a Set and by definition, set elements are unique.

[1,2,3,4,5,5,5,6].to_set => [1,2,3,4,5,6]

Error:Unknown host services.gradle.org. You may need to adjust the proxy settings in Gradle

Download a recent gradle release from gradle.org/releases Unzip the file and copy the gradle folder e.g. gradle 4.0 into C -- program files -- android -- android studio -- gradle. On your android studio goto file -- settings -- Build, Execution, Deployment --Build Tools -- Gradle and choose Use local gradle distribution, in the gradle home locate your gradle folder and click apply. Then click okay. This solved the problem for me. Your android studio might require a more recent gradle release, make sure you download a gradle that is compatible with your studio or latest releases.

Best way to show a loading/progress indicator?

Use ProgressDialog

ProgressDialog.show(Context context, CharSequence title, CharSequence message);

enter image description here

However this is considered as an anti pattern today (2013): http://www.youtube.com/watch?v=pEGWcMTxs3I

Entity framework self referencing loop detected

Self-referencing as example

public class Employee {
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public int ManagerId { get; set; }
    public virtual Employee Manager { get; set; }

    public virtual ICollection<Employee> Employees { get; set; }

    public Employee() {
        Employees = new HashSet<Employee>();
    }
}
HasMany(e => e.Employees)
    .WithRequired(e => e.Manager)
    .HasForeignKey(e => e.ManagerId)
    .WillCascadeOnDelete(false);

jQuery find element by data attribute value

you can also use andSelf() method to get wrapper DOM contain then find() can be work around as your idea

_x000D_
_x000D_
$(function() {_x000D_
  $('.slide-link').andSelf().find('[data-slide="0"]').addClass('active');_x000D_
})
_x000D_
.active {_x000D_
  background: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<a class="slide-link" href="#" data-slide="0">1</a>_x000D_
<a class="slide-link" href="#" data-slide="1">2</a>_x000D_
<a class="slide-link" href="#" data-slide="2">3</a>
_x000D_
_x000D_
_x000D_

Decompile .smali files on an APK

dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

Redirect echo output in shell script to logfile

You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:

{
  command1
  command2
  command3
  command4
} > file1
{
  command5
  command6
  command7
  command8
} > file2

HTML colspan in CSS

There is no colspan in css as far as I know, but there will be column-span for multi column layout in the near future, but since it is only a draft in CSS3, you can check it in here. Anyway you can do a workaround using div and span with table-like display like this.

This would be the HTML:

<div class="table">
  <div class="row">
    <span class="cell red first"></span>
    <span class="cell blue fill"></span>
    <span class="cell green last"></span>
  </div>
</div>
<div class="table">
  <div class="row">
    <span class="cell black"></span>
  </div>
</div>

And this would be the css:

  /* this is to reproduce table-like structure
     for the sake of table-less layout. */
  .table { display:table; table-layout:fixed; width:100px; }
  .row { display:table-row; height:10px; }
  .cell { display:table-cell; }

  /* this is where the colspan tricks works. */
  span { width:100%; }

  /* below is for visual recognition test purposes only. */
  .red { background:red; }
  .blue { background:blue; }
  .green { background:green; }
  .black { background:black; }

  /* this is the benefit of using table display, it is able 
     to set the width of it's child object to fill the rest of 
     the parent width as in table */
  .first { width: 20px; }
  .last { width: 30px; }
  .fill { width: 100%; }

The only reason to use this trick is to gain the benefit of table-layout behaviour, I use it alot if only setting div and span width to certain percentage didn't fullfil our design requirement.

But if you don't need to benefit from the table-layout behaviour, then durilai's answer would suit you enough.

Normalizing a list of numbers in Python

There isn't any function in the standard library (to my knowledge) that will do it, but there are absolutely modules out there which have such functions. However, its easy enough that you can just write your own function:

def normalize(lst):
    s = sum(lst)
    return map(lambda x: float(x)/s, lst)

Sample output:

>>> normed = normalize(raw)
>>> normed
[0.25, 0.5, 0.25]

symfony 2 twig limit the length of the text and put three dots

You can limit in following way. First is starting index and second is number of characters.

**{{ results['text'][4:2] }}**

JS map return object

If you want to alter the original objects, then a simple Array#forEach will do:

rockets.forEach(function(rocket) {
    rocket.launches += 10;
});

If you want to keep the original objects unaltered, then use Array#map and copy the objects using Object#assign:

var newRockets = rockets.forEach(function(rocket) {
    var newRocket = Object.assign({}, rocket);
    newRocket.launches += 10;
    return newRocket;
});

What is .htaccess file?

It is not so easy to give out specific addresses to people say for a conference or a specific project or product. It could be more secure to prevent hacking such as SQL injection attacks etc.

Webpack not excluding node_modules

If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true in your tsconfig.json file.

Python - difference between two strings

You can use ndiff in the difflib module to do this. It has all the information necessary to convert one string into another string.

A simple example:

import difflib

cases=[('afrykanerskojezyczny', 'afrykanerskojezycznym'),
       ('afrykanerskojezyczni', 'nieafrykanerskojezyczni'),
       ('afrykanerskojezycznym', 'afrykanerskojezyczny'),
       ('nieafrykanerskojezyczni', 'afrykanerskojezyczni'),
       ('nieafrynerskojezyczni', 'afrykanerskojzyczni'),
       ('abcdefg','xac')] 

for a,b in cases:     
    print('{} => {}'.format(a,b))  
    for i,s in enumerate(difflib.ndiff(a, b)):
        if s[0]==' ': continue
        elif s[0]=='-':
            print(u'Delete "{}" from position {}'.format(s[-1],i))
        elif s[0]=='+':
            print(u'Add "{}" to position {}'.format(s[-1],i))    
    print()      

prints:

afrykanerskojezyczny => afrykanerskojezycznym
Add "m" to position 20

afrykanerskojezyczni => nieafrykanerskojezyczni
Add "n" to position 0
Add "i" to position 1
Add "e" to position 2

afrykanerskojezycznym => afrykanerskojezyczny
Delete "m" from position 20

nieafrykanerskojezyczni => afrykanerskojezyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2

nieafrynerskojezyczni => afrykanerskojzyczni
Delete "n" from position 0
Delete "i" from position 1
Delete "e" from position 2
Add "k" to position 7
Add "a" to position 8
Delete "e" from position 16

abcdefg => xac
Add "x" to position 0
Delete "b" from position 2
Delete "d" from position 4
Delete "e" from position 5
Delete "f" from position 6
Delete "g" from position 7

How can I compare time in SQL Server?

Use Datepart function: DATEPART(datepart, date)

E.g#

SELECT DatePart(@YourVar, hh)*60) + DatePart(@YourVar, mi)*60)

This will give you total time of day in minutes allowing you to compare more easily.

You can use DateDiff if your dates are going to be the same, otherwise you'll need to strip out the date as above

Java HTTP Client Request with defined timeout

I found that setting the time out settings in HttpConnectionParams and HttpConnectionManager did not solve our case. We're limited to using org.apache.commons.httpclient version 3.0.1.

I ended up using an java.util.concurrent.ExecutorService to monitor the HttpClient.executeMethod() call.

Here's a small, self-contained example

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author Jeff Kirby
 * @since <pre>Jun 17, 2011</pre>
 */
public class Example {

   private static final String SITE = "http://some.website.com/upload";
   private static final int TIME_OUT_SECS = 5;

   // upload a file and return the response as a string
   public String post(File file) throws IOException, InterruptedException {
      final Part[] multiPart = { new FilePart("file", file.getName(), file) };
      final EntityEnclosingMethod post = new PostMethod(SITE);
      post.setRequestEntity(new MultipartRequestEntity(multiPart, post.getParams()));
      final ExecutorService executor = Executors.newSingleThreadExecutor();
      final List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(new KillableHttpClient(post)), TIME_OUT_SECS, TimeUnit.SECONDS);
      executor.shutdown();
      if(futures.get(0).isCancelled()) {
         throw new IOException(SITE + " has timed out. It has taken more than " + TIME_OUT_SECS + " seconds to respond");
      }
      return post.getResponseBodyAsString();
   }

   private static class KillableHttpClient implements Callable<Integer> {

      private final EntityEnclosingMethod post;

      private KillableHttpClient(EntityEnclosingMethod post) {
         this.post = post;
      }

      public Integer call() throws Exception {
         return new HttpClient().executeMethod(post);
      }
   }
}

Connect to SQL Server through PDO using SQL Server Driver

try
{

    $conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}
catch(PDOException $e)
{

    $e->getMessage();

}

Excel doesn't update value unless I hit Enter

Executive summary / TL;DR:
Try doing a find & replace of "=" with "=". Yes, replace the equals sign with itself. For my scenario, it forced everything to update.

Background:
I frequently make formulas across multiple columns then concatenate them together. After doing such, I'll copy & paste them as values to extract my created formula. After this process, they're typically stuck displaying a formula, and not displaying a value, unless I enter the cell and press Enter. Pressing F2 & Enter repeatedly is not fun.

How to use target in location.href

As of 2014, you can trigger the click on a <a/> tag. However, for security reasons, you have to do it in a click event handler, or the browser will tag it as a popup (some other events may allow you to safely trigger the opening).

jsFiddle

Extract specific columns from delimited file using Awk

Not using awk but the simplest way I was able to get this done was to just use csvtool. I had other use cases as well to use csvtool and it can handle the quotes or delimiters appropriately if they appear within the column data itself.

csvtool format '%(2)\n' input.csv
csvtool format '%(2),%(3),%(4)\n' input.csv

Replacing 2 with the column number will effectively extract the column data you are looking for.

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

A trick that works is to position box #2 with position: absolute instead of position: relative. We usually put a position: relative on an outer box (here box #2) when we want an inner box (here box #3) with position: absolute to be positioned relative to the outer box. But remember: for box #3 to be positioned relative to box #2, box #2 just need to be positioned. With this change, we get:

And here is the full code with this change:

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
        <style type="text/css">

            /* Positioning */
            #box1 { overflow: hidden }
            #box2 { position: absolute }
            #box3 { position: absolute; top: 10px }

            /* Styling */
            #box1 { background: #efe; padding: 5px; width: 125px }
            #box2 { background: #fee; padding: 2px; width: 100px; height: 100px }
            #box3 { background: #eef; padding: 2px; width: 75px; height: 150px }

        </style>
    </head>
    <body>
        <br/><br/><br/>
        <div id="box1">
            <div id="box2">
                <div id="box3"/>
            </div>
        </div>
    </body>
</html>

Get the size of the screen, current web page and browser window

This how I managed to get the screen width in React JS Project:

If width is equal to 1680 then return 570 else return 200

var screenWidth = window.screen.availWidth;

<Label style={{ width: screenWidth == "1680" ? 570 : 200, color: "transparent" }}>a  </Label>

Screen.availWidth

Use async await with Array.map

You can use:

for await (let resolvedPromise of arrayOfPromises) {
  console.log(resolvedPromise)
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of

If you wish to use Promise.all() instead you can go for Promise.allSettled() So you can have better control over rejected promises.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettled

What is the size of a boolean variable in Java?

Size of the boolean in java is virtual machine dependent. but Any Java object is aligned to an 8 bytes granularity. A Boolean has 8 bytes of header, plus 1 byte of payload, for a total of 9 bytes of information. The JVM then rounds it up to the next multiple of 8. so the one instance of java.lang.Boolean takes up 16 bytes of memory.

Android Room - simple select query - Cannot access database on the main thread

Simply you can use this code for solve it:

Executors.newSingleThreadExecutor().execute(new Runnable() {
                    @Override
                    public void run() {
                        appDb.daoAccess().someJobes();//replace with your code
                    }
                });

Or in lambda you can use this code:

Executors.newSingleThreadExecutor().execute(() -> appDb.daoAccess().someJobes());

You can replace appDb.daoAccess().someJobes() with your own code;

Python: Get HTTP headers from urllib2.urlopen call?

Use the response.info() method to get the headers.

From the urllib2 docs:

urllib2.urlopen(url[, data][, timeout])

...

This function returns a file-like object with two additional methods:

  • geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed
  • info() — return the meta-information of the page, such as headers, in the form of an httplib.HTTPMessage instance (see Quick Reference to HTTP Headers)

So, for your example, try stepping through the result of response.info().headers for what you're looking for.

Note the major caveat to using httplib.HTTPMessage is documented in python issue 4773.

Android Transparent TextView?

<TextView android:alpha="0.3" ..., for example.

How to Increase Import Size Limit in phpMyAdmin

Change the file phpmyadmin.conf on c:/wamp64/alias/phpmyadmin.conf

php_admin_value upload_max_filesize 512M
php_admin_value post_max_size 512M
php_admin_value max_execution_time 360
php_admin_value max_input_time 360

It's very important you increase the time to 5000 or higher, Thus, the process will not stop when you are uploading a large file.

That works for me.

Adding a simple UIAlertView

Here is a complete method that only has one button, an 'ok', to close the UIAlert:

- (void) myAlert: (NSString*)errorMessage
{
    UIAlertView *myAlert = [[UIAlertView alloc]
                          initWithTitle:errorMessage
                          message:@""
                          delegate:self
                          cancelButtonTitle:nil
                          otherButtonTitles:@"ok", nil];
    myAlert.cancelButtonIndex = -1;
    [myAlert setTag:1000];
    [myAlert show];
}

MySQL COUNT DISTINCT

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

Fixed header, footer with scrollable content

Now we've got CSS grid. Welcome to 2019.

_x000D_
_x000D_
/* Required */_x000D_
body {_x000D_
   margin: 0;_x000D_
   height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
   height: 100vh;_x000D_
   display: grid;_x000D_
   grid-template-rows: 30px 1fr 30px;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   overflow-y: scroll;_x000D_
}_x000D_
_x000D_
/* Optional */_x000D_
#wrapper > * {_x000D_
   padding: 5px;_x000D_
}_x000D_
_x000D_
#header {_x000D_
   background-color: #ff0000ff;_x000D_
}_x000D_
_x000D_
#content {_x000D_
   background-color: #00ff00ff;_x000D_
}_x000D_
_x000D_
#footer {_x000D_
   background-color: #0000ffff;_x000D_
}
_x000D_
<body>_x000D_
   <div id="wrapper">_x000D_
      <div id="header">Header Content</div>_x000D_
      <div id="content">_x000D_
         Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
      </div>_x000D_
      <div id="footer">Footer Content</div>_x000D_
   </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to change the color of the axis, ticks and labels for a plot in matplotlib

If you have several figures or subplots that you want to modify, it can be helpful to use the matplotlib context manager to change the color, instead of changing each one individually. The context manager allows you to temporarily change the rc parameters only for the immediately following indented code, but does not affect the global rc parameters.

This snippet yields two figures, the first one with modified colors for the axis, ticks and ticklabels, and the second one with the default rc parameters.

import matplotlib.pyplot as plt
with plt.rc_context({'axes.edgecolor':'orange', 'xtick.color':'red', 'ytick.color':'green', 'figure.facecolor':'white'}):
    # Temporary rc parameters in effect
    fig, (ax1, ax2) = plt.subplots(1,2)
    ax1.plot(range(10))
    ax2.plot(range(10))
# Back to default rc parameters
fig, ax = plt.subplots()
ax.plot(range(10))

enter image description here

enter image description here

You can type plt.rcParams to view all available rc parameters, and use list comprehension to search for keywords:

# Search for all parameters containing the word 'color'
[(param, value) for param, value in plt.rcParams.items() if 'color' in param]

Get last field using awk substr

In this case it is better to use basename instead of awk:

 $ basename /home/parent/child1/child2/filename
 filename

Chrome Dev Tools - Modify javascript and reload

I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler

(pretty sure some of the web devs already know about this tool)

  1. Save the file locally
  2. Edit as required
  3. Profit!

enter image description here

Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder

PS. I would rather have it implemented in Chrome as a flag preserve after reload, cannot do this now, forums and discussion groups blocked on corporate network :)

Add Class to Object on Page Load

This should work:

window.onload = function() {
  document.getElementById('about').className = 'expand';
};

Or if you're using jQuery:

$(function() {
  $('#about').addClass('expand');
});

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Scope means the code context that performs the INSERT statement SCOPE_IDENTITY(), as opposed to the global scope of @@IDENTITY.

CREATE TABLE Foo(
  ID INT IDENTITY(1,1),
  Dummy VARCHAR(100)
)

CREATE TABLE FooLog(
  ID INT IDENTITY(2,2),
  LogText VARCHAR(100)
)
go
CREATE TRIGGER InsertFoo ON Foo AFTER INSERT AS
BEGIN
  INSERT INTO FooLog (LogText) VALUES ('inserted Foo')
  INSERT INTO FooLog (LogText) SELECT Dummy FROM inserted
END

INSERT INTO Foo (Dummy) VALUES ('x')
SELECT SCOPE_IDENTITY(), @@IDENTITY 

Gives different results.

javax.persistence.NoResultException: No entity found for query

When using java 8, you may take advantage of stream API and simplify code to

return (YourEntityClass) entityManager.createQuery()
....
.getResultList()
.stream().findFirst();

That will give you java.util.Optional

If you prefer null instead, all you need is

 ...
.getResultList()
.stream().findFirst().orElse(null);

how to sort an ArrayList in ascending order using Collections and Comparator

Here a complete example :

Suppose we have a Person class like :

public class Person
{
    protected String fname;
    protected String lname;

    public Person()
    {

    }

    public Person(String fname, String lname)
    {
        this.fname = fname;
        this.lname = lname;
    }

    public boolean equals(Object objet)
    {
        if(objet instanceof Person)
        {
            Person p = (Person) objet;
            return (p.getFname().equals(this.fname)) && p.getLname().equals(this.lname));
        }
        else return super.equals(objet);
    }

    @Override
    public String toString()
    {
        return "Person(fname : " + getFname + ", lname : " + getLname + ")";
    }

    /** Getters and Setters **/
}

Now we create a comparator :

import java.util.Comparator;

public class ComparePerson implements Comparator<Person>
{
    @Override
    public int compare(Person p1, Person p2)
    {
        if(p1.getFname().equalsIgnoreCase(p2.getFname()))
        {
            return p1.getLname().compareTo(p2.getLname());
        }
        return p1.getFname().compareTo(p2.getFname());
    }
}

Finally suppose we have a group of persons :

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Group
{
    protected List<Person> listPersons;

    public Group()
    {
        this.listPersons = new ArrayList<Person>();
    }

    public Group(List<Person> listPersons)
    {
        this.listPersons = listPersons;
    }

    public void order(boolean asc)
    {
        Comparator<Person> comp = asc ? new ComparePerson() : Collections.reverseOrder(new ComparePerson());
        Collections.sort(this.listPersons, comp);
    }

    public void display()
    {
        for(Person p : this.listPersons)
        {
            System.out.println(p);
        }
    }

    /** Getters and Setters **/
}

Now we try this :

import java.util.ArrayList;
import java.util.List;

public class App
{
    public static void main(String[] args)
    {
        Group g = new Group();
        List listPersons = new ArrayList<Person>();
        g.setListPersons(listPersons);

        Person p;

        p = new Person("A", "B");
        listPersons.add(p);

        p = new Person("C", "D");
        listPersons.add(p);

        /** you can add Person as many as you want **/

        g.display();

        g.order(true);
        g.display();

        g.order(false);
        g.display();
    }
}

How to center text vertically with a large font-awesome icon?

Well, this question was asked years ago. I think technology has changed quite a bit and browser compatibility is much better. You could use vertical-align but I would consider that some what less scaleable and less reusable. I would recommend a flexbox approach.

Here is the same example the original poster used but with flexbox. It styles a single element. If a button size changes for whatever reason, it will continue to be vertically and horizontally centered.

.button {
    border: 1px solid #ccc;
    height: 40px;
    margin: 60px;
    padding: 4px;
    display: flex;
    justify-content: space-around;
    align-items: center;
}

Example: JsFiddle

Console.log not working at all

I just had a same issue of none of my console message showing. It was simply because I was using the new Edge (Chromium based) browser on Windows 10. It does not show my console messages whereas Chrome does. I guessed it was an issue with Edge because I had another odd issue with Edge because it treated strings with single quotes and double quotes differently.

Undefined reference to pthread_create in Linux

in eclipse

properties->c/c++Build->setting->GCC C++ linker->libraries in top part add "pthread"

Eclipse - Unable to install breakpoint due to missing line number attributes

I had the same error with JBoss 7.1.. And I did the same as Zefiro. Just ignored the error and i was able to place breakpoints normally. In my case i was building thought ant builder and this is my javac task:

<javac
        srcdir="${src.dir}"
        destdir="${build.classes.dir}" 
        includeantruntime="false" 
        debug="${debug}"
        verbose="false"
        debuglevel="lines,vars,source"
        source="1.6"
        target="1.6">

        <!-- Sppressing warning for setting an older source without bootclasspath
             (see: https://blogs.oracle.com/darcy/entry/bootclasspath_older_source) -->
        <compilerarg value="-Xlint:-options"/>

        <classpath>
            <fileset dir="${lib.dir}" includes="*.jar" />
            <fileset dir="${jboss.lib.dir}" includes="**/*.jar" />
        </classpath>

    </javac>

Recursive Fibonacci

int fib(int x) 
{
    if (x < 2)
      return x;
    else 
      return (fib(x - 1) + fib(x - 2));
}

How to search a string in String array

Each class implementing IList has a method Contains(Object value). And so does System.Array.

SQL Switch/Case in 'where' clause

declare @locationType varchar(50);
declare @locationID int;

SELECT column1, column2
FROM viewWhatever
WHERE
@locationID = 
  CASE @locationType
      WHEN 'location' THEN account_location
      WHEN 'area' THEN xxx_location_area 
      WHEN 'division' THEN xxx_location_division 
  END

How to copy to clipboard using Access/VBA?

I couldn't figure out how to use the API using the first Google results. Fortunately a thread somewhere pointed me to this link: http://access.mvps.org/access/api/api0049.htm

Which works nicely. :)

How do I write the 'cd' command in a makefile?

Starting from GNU make 3.82 (July 2010), you can use the .ONESHELL special target to run all recipe lines in a single instantiation of the shell (bold emphasis mine):

  • New special target: .ONESHELL instructs make to invoke a single instance of the shell and provide it with the entire recipe, regardless of how many lines it contains.
.ONESHELL: # Only applies to all target
all:
    cd ~/some_dir
    pwd # Prints ~/some_dir if cd succeeded

another_rule:
    cd ~/some_dir
    pwd # Oops, prints ~

Java String array: is there a size of method?

Not really the answer to your question, but if you want to have something like an array that can grow and shrink you should not use an array in java. You are probably best of by using ArrayList or another List implementation.

You can then call size() on it to get it's size.

UITableView - scroll to the top

This was the only code snippet that worked for me

Swift 4:

    tableView.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: true)
    tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
    tableView.setContentOffset(CGPoint(x: 0, y: -70), animated: true)

P.S. 70 is the height of my header and table view cell

Mime type for WOFF fonts?

For all Solution index.php remove form url and woff file allowed. for write below code in .htaccess file and and make this alternation to your application/config/config.php file: $config['index_page'] = '';

For only Linux hosting server. .htaccess file details

AddType font/ttf .ttf
AddType font/eot .eot
AddType font/otf .otf
AddType font/woff .woff
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /

    #Removes access to the system folder by users.
    #Additionally this will allow you to create a System.php controller,
    #previously this would not have been possible.
    #'system' can be replaced if you have renamed your system folder.
    RewriteCond %{REQUEST_URI} ^system.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #When your application folder isn't in the system folder
    #This snippet prevents user access to the application folder
    #Submitted by: Fabdrol
    #Rename 'application' to your applications folder name.
    RewriteCond %{REQUEST_URI} ^application.*
    RewriteRule ^(.*)$ /index.php?/$1 [L]

    #Checks to see if the user is attempting to access a valid file,
    #such as an image or css document, if this isn't true it sends the
    #request to index.php
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
    # If we don't have mod_rewrite installed, all 404's
    # can be sent to index.php, and everything works as normal.
    # Submitted by: ElliotHaughin

    ErrorDocument 404 /index.php
</IfModule>

How to create an array from a CSV file using PHP and the fgetcsv function

To get an array with the right keys, you can try this:

// Open file
$file = fopen($file_path, 'r');

// Headers
$headers = fgetcsv($file);

// Rows
$data = [];
while (($row = fgetcsv($file)) !== false)
{
    $item = [];
    foreach ($row as $key => $value)
        $item[$headers[$key]] = $value ?: null;
    $data[] = $item;
}

// Close file
fclose($file);

"The page has expired due to inactivity" - Laravel 5.5

I ran into the same issue in Laravel 5.5. In my case, it happened after changing a route from GET to POST. The issue was because I forgot to pass a CSRF token when I switched to POST.

You can either post a CSRF token in your form by calling:

 {{ csrf_field() }}

Or exclude your route in app/Http/Middleware/VerifyCsrfToken.php

 protected $except = [
        'your/route'
    ];

How does String.Index work in Swift

func change(string: inout String) {

    var character: Character = .normal

    enum Character {
        case space
        case newLine
        case normal
    }

    for i in stride(from: string.count - 1, through: 0, by: -1) {
        // first get index
        let index: String.Index?
        if i != 0 {
            index = string.index(after: string.index(string.startIndex, offsetBy: i - 1))
        } else {
            index = string.startIndex
        }

        if string[index!] == "\n" {

            if character != .normal {

                if character == .newLine {
                    string.remove(at: index!)
                } else if character == .space {
                    let number = string.index(after: string.index(string.startIndex, offsetBy: i))
                    if string[number] == " " {
                        string.remove(at: number)
                    }
                    character = .newLine
                }

            } else {
                character = .newLine
            }

        } else if string[index!] == " " {

            if character != .normal {

                string.remove(at: index!)

            } else {
                character = .space
            }

        } else {

            character = .normal

        }

    }

    // startIndex
    guard string.count > 0 else { return }
    if string[string.startIndex] == "\n" || string[string.startIndex] == " " {
        string.remove(at: string.startIndex)
    }

    // endIndex - here is a little more complicated!
    guard string.count > 0 else { return }
    let index = string.index(before: string.endIndex)
    if string[index] == "\n" || string[index] == " " {
        string.remove(at: index)
    }

}

Decreasing height of bootstrap 3.0 navbar

Working solution:

Bootstrap 3.0 by default has a 15px padding on top and bottom, so we just need to override it!

For example:

.navbar-nav > li > a {padding-top:10px !important; padding-bottom:10px !important;}
.navbar {min-height:40px !important}

How to parse month full form string using DateFormat in Java?

Just to top this up to the new Java 8 API:

DateTimeFormatter formatter = new DateTimeFormatterBuilder().appendPattern("MMMM dd, yyyy").toFormatter();
TemporalAccessor ta = formatter.parse("June 27, 2007");
Instant instant = LocalDate.from(ta).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
Date d = Date.from(instant);
assertThat(d.getYear(), is(107));
assertThat(d.getMonth(), is(5));

A bit more verbose but you also see that the methods of Date used are deprecated ;-) Time to move on.

How to install npm peer dependencies automatically?

The project npm-install-peers will detect peers and install them.

As of v1.0.1 it doesn't support writing back to the package.json automatically, which would essentially solve our need here.

Please add your support to issue in flight: https://github.com/spatie/npm-install-peers/issues/4

How to get the sizes of the tables of a MySQL database?

Try the following shell command (replace DB_NAME with your database name):

mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head

For Drupal/drush solution, check the following example script which will display the biggest tables in use:

#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20

ImportError: No Module named simplejson

For anyone coming across this years later:

TL;DR check your pip version (2 vs 3)

I had this same issue and it was not fixed by running pip install simplejson despite pip insisting that it was installed. Then I realized that I had both python 2 and python 3 installed.

> python -V
Python 2.7.12
> pip -V
pip 9.0.1 from /usr/local/lib/python3.5/site-packages (python 3.5)

Installing with the correct version of pip is as easy as using pip2:

> pip2 install simplejson

and then python 2 can import simplejson fine.

how to display data values on Chart.js

Edited @ajhuddy's answer a little. Only for bar charts. My version adds:

  • Fade in animation for the values.
  • Prevent clipping by positioning the value inside the bar if the bar is too high.
  • No blinking.

Example

Downside: When hovering over a bar that has value inside it the value might look a little jagged. I have not found a solution do disable hover effects. It might also need tweaking depending on your own settings.

Configuration:

bar: {
  tooltips: {
    enabled: false
  },
  hover: {
    animationDuration: 0
  },
  animation: {
    onComplete: function() {
      this.chart.controller.draw();
      drawValue(this, 1);
    },
    onProgress: function(state) {
      var animation = state.animationObject;
      drawValue(this, animation.currentStep / animation.numSteps);
    }
  }
}

Helpers:

// Font color for values inside the bar
var insideFontColor = '255,255,255';
// Font color for values above the bar
var outsideFontColor = '0,0,0';
// How close to the top edge bar can be before the value is put inside it
var topThreshold = 20;

var modifyCtx = function(ctx) {
  ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
  ctx.textAlign = 'center';
  ctx.textBaseline = 'bottom';
  return ctx;
};

var fadeIn = function(ctx, obj, x, y, black, step) {
  var ctx = modifyCtx(ctx);
  var alpha = 0;
  ctx.fillStyle = black ? 'rgba(' + outsideFontColor + ',' + step + ')' : 'rgba(' + insideFontColor + ',' + step + ')';
  ctx.fillText(obj, x, y);
};

var drawValue = function(context, step) {
  var ctx = context.chart.ctx;

  context.data.datasets.forEach(function (dataset) {
    for (var i = 0; i < dataset.data.length; i++) {
      var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
      var textY = (model.y > topThreshold) ? model.y - 3 : model.y + 20;
      fadeIn(ctx, dataset.data[i], model.x, textY, model.y > topThreshold, step);
    }
  });
};

How to find topmost view controller on iOS

To avoid a lot of complexity I keep track of the current viewController by creating a viewController in the delegate and set it to self inside each viewDidLoad method, this way anytime you load a new view the ViewController held in the delegate will correspond to that view's viewController. This may be ugly, but it works wonderfully, and theres no need to have a navigation controller or any of that nonsense.

Type or namespace name does not exist

I got a very similar error message that was caused by inadvertently having made a duplicate of a class in another project of my solution. Deleting the duplicate fixed the issue

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

How can I use MS Visual Studio for Android Development?

Yes, you can use Visual Studio for Android (native) using "vs-android".

Here are the steps to set it up:

  1. Download the Android SDK here.

  2. Download the Android NDK here.

  3. Download Cygwin here.

  4. Download the JDK here.

  5. Download Visual Studio 2010, 2012 or 2013 here.

  6. Download vs-android here.

  7. Download Apache Ant here.

  8. Set environment variables:

(Control Panel > System > Advanced > Environment Variables)

ANDROID_HOME = <install_path>\android-sdk
ANDROID_NDK_ROOT = <install_path>\android-ndk
ANT_HOME  = <install_path>\apache-ant
JAVA_HOME = <install_path>\jdk
_JAVA_OPTIONS = -Xms256m -Xmx512m  
  1. Download examples from here.

It works like a charm... and best so far to use.

How do I add my new User Control to the Toolbox or a new Winform?

One user control can't be applied to it ownself. So open another winform and the one will appear in the toolbox.

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Websocket and WebRTC can be used together, Websocket as a signal channel of WebRTC, and webrtc is a video/audio/text channel, also WebRTC can be in UDP also in TURN relay, TURN relay support TCP HTTP also HTTPS. Many projects use Websocket and WebRTC together.

Py_Initialize fails - unable to load the file system codec

I had this issue with python 3.5, anaconda 3, windows 7 32 bit. I solved it by moving my pythonX.lib and pythonX.dll files into my working directory and calling

Py_SetPythonHome(L"C:\\Path\\To\\My\\Python\\Installation");

before initialize so that it could find the headers that it needed, where my path was to "...\Anaconda3\". The extra step of calling Py_SetPythonHome was required for me or else I'd end up getting other strange errors where python import files.

Converting from hex to string

Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])

How can I turn a DataTable to a CSV?

I did this recently but included double quotes around my values.

For example, change these two lines:

sb.Append("\"" + col.ColumnName + "\","); 
...
sb.Append("\"" + row[i].ToString() + "\","); 

Cannot read property length of undefined

perhaps, you can first determine if the DOM does really exists,

function walkmydog() {
    //when the user starts entering
    var dom = document.getElementById('WallSearch');
    if(dom == null){
        alert('sorry, WallSearch DOM cannot be found');
        return false;    
    }

    if(dom.value.length == 0){
        alert("nothing");
    }
}

if (document.addEventListener){
    document.addEventListener("DOMContentLoaded", walkmydog, false);
}

Laravel Eloquent Sum of relation's column

this is not your answer but is for those come here searching solution for another problem. I wanted to get sum of a column of related table conditionally. In my database Deals has many Activities I wanted to get the sum of the "amount_total" from Activities table where activities.deal_id = deal.id and activities.status = paid so i did this.

$query->withCount([
'activity AS paid_sum' => function ($query) {
            $query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
        }
    ]);

it returns

"paid_sum_count" => "320.00"

in Deals attribute.

This it now the sum which i wanted to get not the count.

Python: print a generator expression?

Or you can always map over an iterator, without the need to build an intermediate list:

>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Force an Android activity to always use landscape mode

Press CTRL+F11 to rotate the screen.

SQL Server : error converting data type varchar to numeric

thanks, try this instead

Select 
  STR(account_code) as account_code_Numeric,
  descr 
from account 
where  STR(account_code) = 1

I'm happy to help you

Unsupported major.minor version 52.0 in my app

I installed Android Studio alongside to Xamarin Visual Studio (was already installed). After the installation (excluded SDK, because they were already installed) I started Android Studio and it downloaded, installed and added missing SDKs (after giving the path to the SDK location). As a result I got the error message on build

java.lang.UnsupportedClassVersionError: com/android/dx/command/Main : Unsupported major.minor version 52.0

As a solution I installed jdk-8u101-windows-i586.exe without JRE (because it was already installed). Before I tried the x64 version, but it disappeared ... Then you have to change the Java Development Kit location.

Change JDK location

This is done in Visual Studio by clicking Tools > Options > Xamarin > Android Settings. Here you can navigate to the correct location. In my case it was C:\Program Files (x86)\Java\jdk1.8.0_101.

Finally, clean your project and make a new build :-)

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

Add this dependency to your pom.xml file:

http://mvnrepository.com/artifact/junit/junit-dep/4.8.2

<!-- https://mvnrepository.com/artifact/junit/junit-dep -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit-dep</artifactId>
    <version>4.8.2</version>
</dependency>

Check/Uncheck all the checkboxes in a table

This will select and deselect all checkboxes:

function checkAll()
{
     var checkboxes = document.getElementsByTagName('input'), val = null;    
     for (var i = 0; i < checkboxes.length; i++)
     {
         if (checkboxes[i].type == 'checkbox')
         {
             if (val === null) val = checkboxes[i].checked;
             checkboxes[i].checked = val;
         }
     }
 }

Demo

Update:

You can use querySelectAll directly on the table to get the list of checkboxes instead of searching the whole document, but It might not be compatible with old browsers so you need to check that first:

 function checkAll()
 {
     var table = document.getElementById ('dataTable');
     var checkboxes = table.querySelectorAll ('input[type=checkbox]');
     var val = checkboxes[0].checked;
     for (var i = 0; i < checkboxes.length; i++) checkboxes[i].checked = val;
 }

Or to be more specific for the provided html structure in the OP question, this would be more efficient when selecting the checkboxes as it will access them directly instead of searching for them:

function checkAll (tableID)
{
    var table = document.getElementById (tableID);
    var val = table.rows[0].cells[0].children[0].checked;
    for (var i = 1; i < table.rows.length; i++)
    {
        table.rows[i].cells[0].children[0].checked = val;
    }
}

Demo

how to get current location in google map android

Why not to use FusedLocationApi instead of OnMyLocationChangeListener? You need to initialize GoogleApiClient object and use LocationServices.FusedLocationApi.requestLocationUpdates() method to register location change listener. It is important to note, that don't forget to remove the registered listener and disconnect GoogleApiClient.

private LocationRequest  mLocationRequest;
private GoogleApiClient  mGoogleApiClient;
private LocationListener mLocationListener;

private void initGoogleApiClient(Context context)
{
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(LocationServices.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks()
    {
        @Override
        public void onConnected(Bundle bundle)
        {
            mLocationRequest = LocationRequest.create();
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationRequest.setInterval(1000);

            setLocationListener();
        }

        @Override
        public void onConnectionSuspended(int i)
        {
            Log.i("LOG_TAG", "onConnectionSuspended");
        }
    }).build();

    if (mGoogleApiClient != null)
        mGoogleApiClient.connect();

}

private void setLocationListener()
{
    mLocationListener = new LocationListener()
    {
        @Override
        public void onLocationChanged(Location location)
        {
            String lat = String.valueOf(location.getLatitude());
            String lon = String.valueOf(location.getLongitude());
            Log.i("LOG_TAG", "Latitude = " + lat + " Longitude = " + lon);
        }
    };

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationListener);
}

private void removeLocationListener()
{
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationListener);
}

Open a PDF using VBA in Excel

Use Shell "program file path file path you want to open".

Example:

Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"

Install dependencies globally and locally using package.json

You could use a separate file, like npm_globals.txt, instead of package.json. This file would contain each module on a new line like this,

[email protected]
[email protected]
[email protected]
[email protected]
[email protected]

Then in the command line run,

< npm_globals.txt xargs npm install -g

Check that they installed properly with,

npm list -g --depth=0

As for whether you should do this or not, I think it all depends on use case. For most projects, this isn't necessary; and having your project's package.json encapsulate these tools and dependencies together is much preferred.

But nowadays I find that I'm always installing create-react-app and other CLI's globally when I jump on a new machine. It's nice to have an easy way to install a global tool and its dependencies when versioning doesn't matter much.

And nowadays, I'm using npx, an npm package runner, instead of installing packages globally.

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

You need to identify the primary key in TableA in order to delete the correct record. The primary key may be a single column or a combination of several columns that uniquely identifies a row in the table. If there is no primary key, then the ROWID pseudo column may be used as the primary key.

DELETE FROM tableA
WHERE ROWID IN 
  ( SELECT q.ROWID
    FROM tableA q
      INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum) 
    WHERE (LENGTH(q.memotext) NOT IN (8,9,10) OR q.memotext NOT LIKE '%/%/%')
      AND (u.FldFormat = 'Date'));

Parsing JSON with Unix tools

On the basis that some of the recommendations here (esp in the comments) suggested the use of Python, I was disappointed not to find an example.

So, here's a one liner to get a single value from some JSON data. It assumes that you are piping the data in (from somewhere) and so should be useful in a scripting context.

echo '{"hostname":"test","domainname":"example.com"}' | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["hostname"]'

Drop all tables whose names begin with a certain string

On Oracle XE this works:

SELECT 'DROP TABLE "' || TABLE_NAME || '";'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Or if you want to remove the constraints and free up space as well, use this:

SELECT 'DROP TABLE "' || TABLE_NAME || '" cascade constraints PURGE;'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Which will generate a bunch of DROP TABLE cascade constraints PURGE statements...

For VIEWS use this:

SELECT 'DROP VIEW "' || VIEW_NAME || '";'
FROM USER_VIEWS
WHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

This error

Failure [INSTALL_FAILED_OLDER_SDK]

Means that you're trying to install an app that has a higher minSdkVersion specified in its manifest than the device's API level. Change that number to 8 and it should work. I'm not sure about the other error, but it may be related to this one.

How to capture a backspace on the onkeydown event

not sure if it works outside of firefox:

callback (event){
  if (event.keyCode === event.DOM_VK_BACK_SPACE || event.keyCode === event.DOM_VK_DELETE)
    // do something
  }
}

if not, replace event.DOM_VK_BACK_SPACE with 8 and event.DOM_VK_DELETE with 46 or define them as constant (for better readability)

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

Does return stop a loop?

"return" does exit the function but if you want to return large sums of data, you can store it in an array and then return it instead of trying to returning each piece of data 1 by 1 in the loop.

How to update a record using sequelize for node?

If Model.update statement does not work for you, you can try like this:

try{ 
    await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})
}
catch(err){
    console.log(err)
}

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

UTL_FILE.FOPEN() procedure not accepting path for directory?

The directory name seems to be case sensitive. I faced the same issue but when I provided the directory name in upper case it worked.

How to use cURL to send Cookies?

I'm using Debian, and I was unable to use tilde for the path. Originally I was using

curl -c "~/cookie" http://localhost:5000/login -d username=myname password=mypassword

I had to change this to:

curl -c "/tmp/cookie" http://localhost:5000/login -d username=myname password=mypassword

-c creates the cookie, -b uses the cookie

so then I'd use for instance:

curl -b "/tmp/cookie" http://localhost:5000/getData

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

An alternative that always exists for learning purpose is to build your custom collector through Collector.of() though toMap() JDK collector here is succinct (+1 here) .

Map<String,Integer> newMap = givenMap.
                entrySet().
                stream().collect(Collector.of
               ( ()-> new HashMap<String,Integer>(),
                       (mutableMap,entryItem)-> mutableMap.put(entryItem.getKey(),Integer.parseInt(entryItem.getValue())),
                       (map1,map2)->{ map1.putAll(map2); return map1;}
               ));

Is there an easy way to attach source in Eclipse?

I've found that sometimes, you point to the directory you'd assume was correct, and then it still states that it can't find the file in the attached source blah blah.

These times, I've realized that the last path element was "src". Just removing this path element (thus indeed pointing one level above the actual path where the "org" or "com" folder is located) magically makes it work.

Somehow, Eclipse seems to imply this "src" path element if present, and if you then have it included in the source path, Eclipse chokes. Or something like that.

How to determine if one array contains all elements of another array

You can monkey-patch the Array class:

class Array
    def contains_all?(ary)
        ary.uniq.all? { |x| count(x) >= ary.count(x) }
    end
end

test

irb(main):131:0> %w[a b c c].contains_all? %w[a b c]
=> true
irb(main):132:0> %w[a b c c].contains_all? %w[a b c c]
=> true
irb(main):133:0> %w[a b c c].contains_all? %w[a b c c c]
=> false
irb(main):134:0> %w[a b c c].contains_all? %w[a]
=> true
irb(main):135:0> %w[a b c c].contains_all? %w[x]
=> false
irb(main):136:0> %w[a b c c].contains_all? %w[]
=> true
irb(main):137:0> %w[a b c d].contains_all? %w[d c h]
=> false
irb(main):138:0> %w[a b c d].contains_all? %w[d b c]
=> true

Of course the method can be written as a standard-alone method, eg

def contains_all?(a,b)
    b.uniq.all? { |x| a.count(x) >= b.count(x) }
end

and you can invoke it like

contains_all?(%w[a b c c], %w[c c c])

Indeed, after profiling, the following version is much faster, and the code is shorter.

def contains_all?(a,b)
    b.all? { |x| a.count(x) >= b.count(x) }
end

How do I push amended commit to the remote Git repository?

The following worked for me when changing Author and Committer of a commit.

git push -f origin master

Git was smart enough to figure out that these were commits of identical deltas which only differed in the meta information section.

Both the local and remote heads pointed to the commits in question.

grep for special characters in Unix

You could try removing any alphanumeric characters and space. And then use -n will give you the line number. Try following:

grep -vn "^[a-zA-Z0-9 ]*$" application.log

Change header text of columns in a GridView

You can do it with gridview's datarow bound event. try the following sample of code:

protected void grv_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "TiTle";
}
}

For more details about the row databound event study Thsi....

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

One line solution:

& ((Split-Path $MyInvocation.InvocationName) + "\MyScript1.ps1")

Enzyme - How to access and set <input> value?

I use Wrapper's setValue[https://vue-test-utils.vuejs.org/api/wrapper/#setvalue-value] method to set value.

inputA = wrapper.findAll('input').at(0)
inputA.setValue('123456')

How do I add target="_blank" to a link within a specified div?

Using jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });

CSS Inset Borders

Simple SCSS solution with pseudo-elements

Live demo: https://codepen.io/vlasterx/pen/xaMgag

_x000D_
_x000D_
// Change border size here_x000D_
$border-width: 5px;_x000D_
_x000D_
.element-with-border {_x000D_
 display: flex;_x000D_
 height: 100px;_x000D_
 width: 100%;_x000D_
 position: relative;_x000D_
 background-color: #f2f2f2;_x000D_
 box-sizing: border-box;_x000D_
 _x000D_
 // Use pseudo-element to create inset border_x000D_
 &:before {_x000D_
  position: absolute;_x000D_
  content: ' ';_x000D_
  display: flex;_x000D_
  border: $border-width solid black;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  border: $border-width solid black;_x000D_
  // Important: We must deduct border size from width and height_x000D_
  width: calc(100% - $border-width); _x000D_
  height: calc(100% - $border-width);_x000D_
 }_x000D_
}
_x000D_
<div class="element-with-border">_x000D_
  Lorem ipsum dolor sit amet_x000D_
</div>
_x000D_
_x000D_
_x000D_

Git Remote: Error: fatal: protocol error: bad line length character: Unab

In my case the problem was 32-bit Putty and pageant.exe - it can't communicate with 64-bit TortoisePlink.exe. Replacing 32-bit Putty with a 64-bit version solved the problem.

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Popup Message boxes

first you have to import: import javax.swing.JOptionPane; then you can call it using this:

JOptionPane.showMessageDialog(null, 
                              "ALERT MESSAGE", 
                              "TITLE", 
                              JOptionPane.WARNING_MESSAGE);

the null puts it in the middle of the screen. put whatever in quotes under alert message. Title is obviously title and the last part will format it like an error message. if you want a regular message just replace it with PLAIN_MESSAGE. it works pretty well in a lot of ways mostly for errors.

Create an Android GPS tracking application

Basically you need following things to make location detector android app

Now if you write each of these module yourself then it needs much time and efforts. So it would be better to use ready resources that are being maintained already.

Using all these resources, you will be able to create an flawless android location detection app.

1. Location Listening

You will first need to listen for current location of user. You can use any of below libraries to quick start.

Google Play Location Samples

This library provide last known location, location updates

Location Manager

With this library you just need to provide a Configuration object with your requirements, and you will receive a location or a fail reason with all the stuff are described above handled.

Live Location Sharing

Use this open source repo of the Hypertrack Live app to build live location sharing experience within your app within a few hours. HyperTrack Live app helps you share your Live Location with friends and family through your favorite messaging app when you are on the way to meet up. HyperTrack Live uses HyperTrack APIs and SDKs.

2. Markers Library

Google Maps Android API utility library

  • Marker clustering — handles the display of a large number of points
  • Heat maps — display a large number of points as a heat map
  • IconGenerator — display text on your Markers
  • Poly decoding and encoding — compact encoding for paths, interoperability with Maps API web services
  • Spherical geometry — for example: computeDistance, computeHeading, computeArea
  • KML — displays KML data
  • GeoJSON — displays and styles GeoJSON data

3. Polyline Libraries

DrawRouteMaps

If you want to add route maps feature in your apps you can use DrawRouteMaps to make you work more easier. This is lib will help you to draw route maps between two point LatLng.

trail-android

Simple, smooth animation for route / polylines on google maps using projections. (WIP)

Google-Directions-Android

This project allows you to calculate the direction between two locations and display the route on a Google Map using the Google Directions API.

A map demo app for quick start with maps

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Try this:

location / {
    root /path/to/root;
    expires 30d;
    access_log off;
}

location ~* ^.*\.php$ {
    if (!-f $request_filename) {
        return 404;
    }
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php should be forwared to Apache if only a corresponding .php file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.

How do I list all files of a directory?

I prefer using the glob module, as it does pattern matching and expansion.

import glob
print(glob.glob("/home/adam/*.txt"))

It will return a list with the queried files:

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

Is there a way to get a list of column names in sqlite?

Quick, interactive way to see column names

If you're working interactively in Python and just want to quickly 'see' the column names, I found cursor.description to work.

import sqlite3
conn = sqlite3.connect('test-db.db')
cursor = conn.execute('select * from mytable')
cursor.description

Outputs something like this:

(('Date', None, None, None, None, None, None),
 ('Object-Name', None, None, None, None, None, None),
 ('Object-Count', None, None, None, None, None, None))

Or, quick way to access and print them out.

colnames = cursor.description
for row in colnames:
    print row[0]

Outputs something like this:

Date
Object-Name
Object-Count

Android Gradle Apache HttpClient does not exist?

This is what I did, and it works for me.

step 1: add this in the build.grade(module: app)

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

step 2: sync the project and done.

How can I simulate an array variable in MySQL?

Both versions using sets didn't work for me (tested with MySQL 5.5). The function ELT() returns the whole set. Considering the WHILE statement is only avaible in PROCEDURE context i added it to my solution:

DROP PROCEDURE IF EXISTS __main__;

DELIMITER $
CREATE PROCEDURE __main__()
BEGIN
    SET @myArrayOfValue = '2,5,2,23,6,';

    WHILE (LOCATE(',', @myArrayOfValue) > 0)
    DO
        SET @value = LEFT(@myArrayOfValue, LOCATE(',',@myArrayOfValue) - 1);    
        SET @myArrayOfValue = SUBSTRING(@myArrayOfValue, LOCATE(',',@myArrayOfValue) + 1);
    END WHILE;
END;
$
DELIMITER ;

CALL __main__;

To be honest, i don't think this is a good practice. Even if its realy necessary, this is barely readable and quite slow.

Java JTable getting the data of the selected row

You can use the following code to get the value of the first column of the selected row of your table.

int column = 0;
int row = table.getSelectedRow();
String value = table.getModel().getValueAt(row, column).toString();