Programs & Examples On #Routines

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'   
                                         ^^^^^

The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

Read file from resources folder in Spring Boot

Below is my working code.

List<sampleObject> list = new ArrayList<>();
File file = new ClassPathResource("json/test.json").getFile();
ObjectMapper objectMapper = new ObjectMapper();
sampleObject = Arrays.asList(objectMapper.readValue(file, sampleObject[].class));

Hope it helps one!

Solving sslv3 alert handshake failure when trying to use a client certificate

What SSL private key should be sent along with the client certificate?

None of them :)

One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.

Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.


Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure

Use TLS 1.0 and above; and use Server Name Indication.

You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:

openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
    -cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem

You can also use -CAfile to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

Make sure file name "Dockerfile" is not saved with any extension. Just create a file without any extension.

And make sure Dockerfile is in same directory from where you are trying to building docker image.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

Errors: "Bad encrypt / decrypt" "gitencrypt_smudge: FAILURE: openssl error decrypting file"

There are various error strings that are thrown from openssl, depending on respective versions, and scenarios. Below is the checklist I use in case of openssl related issues:

  1. Ideally, openssl is able to encrypt/decrypt using same key (+ salt) & enc algo only.
  2. Ensure that openssl versions (used to encrypt/decrypt), are compatible. For eg. the hash used in openssl changed at version 1.1.0 from MD5 to SHA256. This produces a different key from the same password. Fix: add "-md md5" in 1.1.0 to decrypt data from lower versions, and add "-md sha256 in lower versions to decrypt data from 1.1.0

  3. Ensure that there is a single openssl version installed in your machine. In case there are multiple versions installed simultaneously (in my machine, these were installed :- 'LibreSSL 2.6.5' and 'openssl 1.1.1d'), make the sure that only the desired one appears in your PATH variable.

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I faced a similar issue during work with Ubuntu 16.04 by using Docker. In my case that was a problem with Composer, but error message (and thus the problem) was the same.

Because of minimalist Docker-oriented base image I had missing ca-certificates package and simple apt-get install ca-certificates helped me.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

On my execution of openssl pkcs12 -export -out cacert.pkcs12 -in testca/cacert.pem, I received the following message:

unable to load private key 140707250050712:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:701:Expecting: ANY PRIVATE KEY`

Got this solved by providing the key file along with the command. The switch is -inkey inkeyfile.pem

wget ssl alert handshake failure

Below command for download files from TLSv1.2 website.

curl -v --tlsv1.2 https://example.com/filename.zip

It`s worked!

how to fix stream_socket_enable_crypto(): SSL operation failed with code 1

in my case i did following

$mail = new PHPMailer;
$mail->isSMTP();            
$mail->Host = '<YOUR HOST>';
$mail->Port = 587;
$mail->SMTPAuth = true;
$mail->Username = '<USERNAME>';
$mail->Password = '<PASSWORD>';
$mail->SMTPSecure = '';
$mail->smtpConnect([
    'ssl' => [
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    ]
]);
$mail->smtpClose();

$mail->From = '<[email protected]>';
$mail->FromName = '<MAIL FROM NAME>';

$mail->addAddress("<[email protected]>", '<SEND TO>');

$mail->isHTML(true);
$mail->Subject= '<SUBJECTHERE>';
$mail->Body =  '<h2>Test Mail</h2>';
$isSend = $mail->send();

How to get Python requests to trust a self signed SSL certificate?

Incase anyone happens to land here (like I did) looking to add a CA (in my case Charles Proxy) for httplib2, it looks like you can append it to the cacerts.txt file included with the python package.

For example:

cat ~/Desktop/charles-ssl-proxying-certificate.pem >> /usr/local/google-cloud-sdk/lib/third_party/httplib2/cacerts.txt

The environment variables referenced in other solutions appear to be requests-specific and were not picked up by httplib2 in my testing.

Shift elements in a numpy array

You can also do this with Pandas:

Using a 2356-long array:

import numpy as np

xs = np.array([...])

Using scipy:

from scipy.ndimage.interpolation import shift

%timeit shift(xs, 1, cval=np.nan)
# 956 µs ± 77.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Using Pandas:

import pandas as pd

%timeit pd.Series(xs).shift(1).values
# 377 µs ± 9.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In this example, using Pandas was about ~8 times faster than Scipy

TLS 1.2 not working in cURL

TLS 1.2 is only supported since OpenSSL 1.0.1 (see the Major version releases section), you have to update your OpenSSL.

It is not necessary to set the CURLOPT_SSLVERSION option. The request involves a handshake which will apply the newest TLS version both server and client support. The server you request is using TLS 1.2, so your php_curl will use TLS 1.2 (by default) as well if your OpenSSL version is (or newer than) 1.0.1.

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Previously, I've also solved this problem with custom SSLFactory implementation, but according to OkHttp docs the solution is much easier.

My final solution with needed TLS ciphers for 4.2+ devices looks like this:

public UsersApi provideUsersApi() {

    private ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS)
        .supportsTlsExtensions(true)
        .tlsVersions(TlsVersion.TLS_1_2, TlsVersion.TLS_1_1, TlsVersion.TLS_1_0)
        .cipherSuites(
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
                CipherSuite.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
                CipherSuite.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
                CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
                CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA)
        .build();

    OkHttpClient client = new OkHttpClient.Builder()
            .connectionSpecs(Collections.singletonList(spec))
            .build();

    return new Retrofit.Builder()
            .baseUrl(USERS_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
            .create(UsersApi.class);
}

Note that set of supported protocols depends on configured on your server.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

You should use

 SSLContext.getInstance("TLSv1.2"); 

for specific protocol version.

The second exception occured because default socketFactory used fallback SSLv3 protocol for failures.

You can use NoSSLFactory from main answer here for its suppression How to disable SSLv3 in android for HttpsUrlConnection?

Also you should init SSLContext with all your certificates(client and trusted ones if you need them)

But all of that is useless without using

ProviderInstaller.installIfNeeded(getContext())

Here is more information with proper usage scenario https://developer.android.com/training/articles/security-gms-provider.html

Hope it helps.

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

SL_CTX_use_PrivateKey("/etc/nginx/ssl/file") failed (SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch)

This error can happen, when the certificate private key (ssl_certificate_key, e.g. .key or .pem file) does not match the public certificate file (ssl_certificate) in your Nginx configuration (check nginx.conf or in sites-enabled/). Make sure both files are matching.

Check Nginx error logs for further details (e.g. /var/log/nginx/error.log).

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

Reason for this error is that PHP does not have a list of trusted certificate authorities.

PHP 5.6 and later try to load the CAs trusted by the system automatically. Issues with that can be fixed. See http://php.net/manual/en/migration56.openssl.php for more information.

PHP 5.5 and earlier are really hard to setup correctly since you manually have to specify the CA bundle in each request context, a thing you do not want to sprinkle around your code. So I decided for my code that for PHP versions < 5.6, SSL verification simply gets disabled:

$req = new HTTP_Request2($url);
if (version_compare(PHP_VERSION, '5.6.0', '<')) {
    //correct ssl validation on php 5.5 is a pain, so disable
    $req->setConfig('ssl_verify_host', false);
    $req->setConfig('ssl_verify_peer', false);
}

docker error: /var/run/docker.sock: no such file or directory

docker pull will fail if docker service is not running. Make sure it is running by

:~$ ps aux | grep docker
root     18745  1.7  0.9 284104 13976 ?   Ssl  21:19   0:01 /usr/bin/docker -d

If it is not running, you can start it by

sudo service docker start

For Ubuntu 15 and above use

sudo systemctl start docker

Why am I getting a "401 Unauthorized" error in Maven?

I had the same error. I tried and rechecked everything. I was so focused in the Stack trace that I didn't read the last lines of the build before the Reactor summary and the stack trace:

[DEBUG] Using connector AetherRepositoryConnector with priority 3.4028235E38 for http://www:8081/nexus/content/repositories/snapshots/
[INFO] Downloading: http://www:8081/nexus/content/repositories/snapshots/com/wdsuite/com.wdsuite.server.product/1.0.0-SNAPSHOT/maven-metadata.xml
[DEBUG] Could not find metadata com.group:artifact.product:version-SNAPSHOT/maven-metadata.xml in nexus (http://www:8081/nexus/content/repositories/snapshots/)
[DEBUG] Writing tracking file /home/me/.m2/repository/com/group/project/version-SNAPSHOT/resolver-status.properties
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.zip
[INFO] Uploading: http://www:8081/nexus/content/repositories/snapshots/com/...-1.0.0-20141118.124526-1.pom
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:

This was the key : "Could not find metadata". Although it said that it was an authentication error actually it got fixed doing a "rebuild metadata" in the nexus repository.

Hope it helps.

OpenSSL Command to check if a server is presenting a certificate

I encountered the write:errno=104 attempting to test connecting to an SSL-enabled RabbitMQ broker port with openssl s_client.

The issue turned out to be simply that the user RabbitMQ was running as did not have read permissions on the certificate file. There was little-to-no useful logging in RabbitMQ.

Node.js https pem error: routines:PEM_read_bio:no start line

If you log the

var options = {
  key: fs.readFileSync('./key.pem', 'utf8'),
  cert: fs.readFileSync('./csr.pem', 'utf8')
};

You might notice there are invalid characters due to improper encoding.

Java 8 Streams FlatMap method example

Extract unique words sorted ASC from a list of phrases:

List<String> phrases = Arrays.asList(
        "sporadic perjury",
        "confounded skimming",
        "incumbent jailer",
        "confounded jailer");

List<String> uniqueWords = phrases
        .stream()
        .flatMap(phrase -> Stream.of(phrase.split("\\s+")))
        .distinct()
        .sorted()
        .collect(Collectors.toList());
System.out.println("Unique words: " + uniqueWords);

... and the output:

Unique words: [confounded, incumbent, jailer, perjury, skimming, sporadic]

Generate random array of floats between a range

Why not to combine random.uniform with a list comprehension?

>>> def random_floats(low, high, size):
...    return [random.uniform(low, high) for _ in xrange(size)]
... 
>>> random_floats(0.5, 2.8, 5)
[2.366910411506704, 1.878800401620107, 1.0145196974227986, 2.332600336488709, 1.945869474662082]

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".

How to multiply duration by integer?

It's nice that Go has a Duration type -- having explicitly defined units can prevent real-world problems.

And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.

/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
    return time.Duration(factor) * d        // method 1 -- multiply in 'Duration'
 // return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}

The official documentation demonstrates using method #1:

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).

By the way, the int64 representation of Duration in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration, like int64, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292, and that's exactly how it is implemented:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

So, because we know that the underlying representation of Duration is an int64, performing the cast between int64 and Duration is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.

If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

openssl s_client -cert: Proving a client certificate was sent to the server

In order to verify a client certificate is being sent to the server, you need to analyze the output from the combination of the -state and -debug flags.

First as a baseline, try running

$ openssl s_client -connect host:443 -state -debug

You'll get a ton of output, but the lines we are interested in look like this:

SSL_connect:SSLv3 read server done A
write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
0000 - 16 03 01 00 07 0b 00 00-03                        .........
000c - <SPACES/NULS>
SSL_connect:SSLv3 write client certificate A

What's happening here:

  • The -state flag is responsible for displaying the end of the previous section:

    SSL_connect:SSLv3 read server done A  
    

    This is only important for helping you find your place in the output.

  • Then the -debug flag is showing the raw bytes being sent in the next step:

    write to 0x211efb0 [0x21ced50] (12 bytes => 12 (0xC))
    0000 - 16 03 01 00 07 0b 00 00-03                        .........
    000c - <SPACES/NULS>
    
  • Finally, the -state flag is once again reporting the result of the step that -debug just echoed:

    SSL_connect:SSLv3 write client certificate A
    

So in other words: s_client finished reading data sent from the server, and sent 12 bytes to the server as (what I assume is) a "no client certificate" message.


If you repeat the test, but this time include the -cert and -key flags like this:

$ openssl s_client -connect host:443 \
   -cert cert_and_key.pem \
   -key cert_and_key.pem  \
   -state -debug

your output between the "read server done" line and the "write client certificate" line will be much longer, representing the binary form of your client certificate:

SSL_connect:SSLv3 read server done A
write to 0x7bd970 [0x86d890] (1576 bytes => 1576 (0x628))
0000 - 16 03 01 06 23 0b 00 06-1f 00 06 1c 00 06 19 31   ....#..........1
(*SNIP*)
0620 - 95 ca 5e f4 2f 6c 43 11-                          ..^%/lC.
SSL_connect:SSLv3 write client certificate A

The 1576 bytes is an excellent indication on its own that the cert was transmitted, but on top of that, the right-hand column will show parts of the certificate that are human-readable: You should be able to recognize the CN and issuer strings of your cert in there.

SSL error : routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

could also happen when your local time is off (e.g. before certificate validation time), this was the case in my error...

pip issue installing almost any library

Pypi removed support for TLS versions less than 1.2

You need to re-install Pip, do

curl https://bootstrap.pypa.io/get-pip.py | python

or for global Python:

curl https://bootstrap.pypa.io/get-pip.py | sudo python

How to check a channel is closed or not without reading it?

From the documentation:

A channel may be closed with the built-in function close. The multi-valued assignment form of the receive operator reports whether a received value was sent before the channel was closed.

https://golang.org/ref/spec#Receive_operator

Example by Golang in Action shows this case:

// This sample program demonstrates how to use an unbuffered
// channel to simulate a game of tennis between two goroutines.
package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

// wg is used to wait for the program to finish.
var wg sync.WaitGroup

func init() {
    rand.Seed(time.Now().UnixNano())
}

// main is the entry point for all Go programs.
func main() {
    // Create an unbuffered channel.
    court := make(chan int)
    // Add a count of two, one for each goroutine.
    wg.Add(2)
    // Launch two players.
    go player("Nadal", court)
    go player("Djokovic", court)
    // Start the set.
    court <- 1
    // Wait for the game to finish.
    wg.Wait()
}

// player simulates a person playing the game of tennis.
func player(name string, court chan int) {
    // Schedule the call to Done to tell main we are done.
    defer wg.Done()
    for {
        // Wait for the ball to be hit back to us.
        ball, ok := <-court
        fmt.Printf("ok %t\n", ok)
        if !ok {
            // If the channel was closed we won.
            fmt.Printf("Player %s Won\n", name)
            return
        }
        // Pick a random number and see if we miss the ball.
        n := rand.Intn(100)
        if n%13 == 0 {
            fmt.Printf("Player %s Missed\n", name)
            // Close the channel to signal we lost.
            close(court)
            return
        }

        // Display and then increment the hit count by one.
        fmt.Printf("Player %s Hit %d\n", name, ball)
        ball++
        // Hit the ball back to the opposing player.
        court <- ball
    }
}

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

This was totally my bad.

I was using standard node http.request on a part of the code which should be sending requests to only http adresses. Seems like the db had a single https address which was queried with a random interval.

Simply, I was trying to send a http request to https.

How to correctly save instance state of Fragments in back stack?

On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity's fragments as you like using the FragmentTransaction. Just make sure that your fragments can be identified either with an id or tag.

The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate(). Instead, you should check if savedInstanceState is not null and find the old references to the created fragments in this case.

Here is an example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        myFragment = MyFragment.newInstance();
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
                .commit();
    } else {
        myFragment = (MyFragment) getSupportFragmentManager()
                .findFragmentByTag(MY_FRAGMENT_TAG);
    }
...
}

Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.

Unable to establish SSL connection, how do I fix my SSL cert?

The problem I faced was in client server environment. The client was trying to connect over http port 80 but wanted the server proxy to redirect the request to some other port and data was https. So basically asking secure information over http. So server should have http port 80 as well as the port client is requesting, let's say urla:1111\subB.

The issue was server was hosting this on some other port e,g urla:2222\subB; so the client was trying to access over 1111 was receiving the error. Correcting the port number should fix this issue. In this case to port number 1111.

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

I have had this error when connecting to a RabbitMQ MQTT server via TLS. I'm pretty sure the server is broken but anyway it worked with OpenSSL 1.0.1, but not OpenSSL 1.0.2.

You can check your version in Python using this:

import ssl
ssl.OPENSSL_VERSION

I'm not sure how to downgrade OpenSSL within Python (it seems to be statically linked on Windows at least), other than using an older version of Python.

PIL image to array (numpy array to array) - Python

I think what you are looking for is:

list(im.getdata())

or, if the image is too big to load entirely into memory, so something like that:

for pixel in iter(im.getdata()):
    print pixel

from PIL documentation:

getdata

im.getdata() => sequence

Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened, so that values for line one follow directly after the values of line zero, and so on.

Note that the sequence object returned by this method is an internal PIL data type, which only supports certain sequence operations, including iteration and basic sequence access. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()).

Python Requests throwing SSLError

There is currently an issue in the requests module causing this error, present in v2.6.2 to v2.12.4 (ATOW): https://github.com/kennethreitz/requests/issues/2573

Workaround for this issue is adding the following line: requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS = 'ECDH+AESGCM:DH+AESGCM:ECDH+AES256:DH+AES256:ECDH+AES128:DH+AES:ECDH+3DES:DH+3DES:RSA+AESGCM:RSA+AES:RSA+3DES:!aNULL:!MD5:!DSS'

https connection using CURL from command line

Here you could find the CA certs with instructions to download and convert Mozilla CA certs. Once you get ca-bundle.crt or cacert.pem you just use:

curl.exe --cacert cacert.pem https://www.google.com

or

curl.exe --cacert ca-bundle.crt https://www.google.com

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

What are the situations where "yield from" is useful?

Every situation where you have a loop like this:

for x in subgenerator:
  yield x

As the PEP describes, this is a rather naive attempt at using the subgenerator, it's missing several aspects, especially the proper handling of the .throw()/.send()/.close() mechanisms introduced by PEP 342. To do this properly, rather complicated code is necessary.

What is the classic use case?

Consider that you want to extract information from a recursive data structure. Let's say we want to get all leaf nodes in a tree:

def traverse_tree(node):
  if not node.children:
    yield node
  for child in node.children:
    yield from traverse_tree(child)

Even more important is the fact that until the yield from, there was no simple method of refactoring the generator code. Suppose you have a (senseless) generator like this:

def get_list_values(lst):
  for item in lst:
    yield int(item)
  for item in lst:
    yield str(item)
  for item in lst:
    yield float(item)

Now you decide to factor out these loops into separate generators. Without yield from, this is ugly, up to the point where you will think twice whether you actually want to do it. With yield from, it's actually nice to look at:

def get_list_values(lst):
  for sub in [get_list_values_as_int, 
              get_list_values_as_str, 
              get_list_values_as_float]:
    yield from sub(lst)

Why is it compared to micro-threads?

I think what this section in the PEP is talking about is that every generator does have its own isolated execution context. Together with the fact that execution is switched between the generator-iterator and the caller using yield and __next__(), respectively, this is similar to threads, where the operating system switches the executing thread from time to time, along with the execution context (stack, registers, ...).

The effect of this is also comparable: Both the generator-iterator and the caller progress in their execution state at the same time, their executions are interleaved. For example, if the generator does some kind of computation and the caller prints out the results, you'll see the results as soon as they're available. This is a form of concurrency.

That analogy isn't anything specific to yield from, though - it's rather a general property of generators in Python.

Use of True, False, and None as return values in Python functions

For True, not None:

if foo:

For false, None:

if not foo:

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

Using openssl to get the certificate from a server

The easiest command line for this, which includes the PEM output to add it to the keystore, as well as a human readable output and also supports SNI, which is important if you are working with an HTTP server is:

openssl s_client -servername example.com -connect example.com:443 \
    </dev/null 2>/dev/null | openssl x509 -text

The -servername option is to enable SNI support and the openssl x509 -text prints the certificate in human readable format.

OpenSSL and error in reading openssl.conf file

This workaround helped us so much at my job (Tech Support), we made a simple batch file we could run from anywhere (We didnt have the permissions to install it). This workaround will set the variable and then run OpenSSL for you. It also opens up the bin folder for you (cause this is where any files you create or modify will be saved). Also, this is only for Windows.

How to Set Up:

  1. Download the OpenSSL binaries here. (Note that this is confirmed to work with version 0.9.8h.)
  2. Copy this code to a file named StartOpenSSL.bat. Save this to a location of your choice. It can be run from anywhere.

    @echo off
    title OpenSSL
    
    cd\openssl\bin
    
    if exist "C:\openssl\share\openssl.cnf" (
    
    set OPENSSL_CONF=c:/openssl/share/openssl.cnf
    start explorer.exe c:\openssl\bin
    
    echo Welcome to OpenSSL
    
    openssl
    
    ) else (
    
    echo Error: openssl.cnf was not found
    echo File openssl.cnf needs to be present in c:\openssl\share
    pause
    
    )
    
    exit
    
  3. Once you have downloaded the OpenSSL binaries, extract them to your C drive in a folder titled OpenSSL. (The path needs to be C:\OpenSSL). Do not move any of the folders contents around, just extract them to the folder.
  4. You are ready to use OpenSSL. This is a great workaround for Windows users who dont have the privileges to install it as it requires no permissions. Just run the bat file from earlier by double clicking it.

How to encrypt a large file in openssl using public key

In more explanation for n. 'pronouns' m.'s answer,

Public-key crypto is not for encrypting arbitrarily long files. One uses a symmetric cipher (say AES) to do the normal encryption. Each time a new random symmetric key is generated, used, and then encrypted with the RSA cipher (public key). The ciphertext together with the encrypted symmetric key is transferred to the recipient. The recipient decrypts the symmetric key using his private key, and then uses the symmetric key to decrypt the message.

There is the flow of Encryption:

+---------------------+      +--------------------+
|                     |      |                    |
| generate random key |      |   the large file   |
|        (R)          |      |        (F)         |
|                     |      |                    |
+--------+--------+---+      +----------+---------+
         |        |                     |
         |        +------------------+  |
         |                           |  |
         v                           v  v
+--------+------------+     +--------+--+------------+
|                     |     |                        |
| encrypt (R) with    |     | encrypt (F)            |
| your RSA public key |     | with symmetric key (R) |
|                     |     |                        |
|  ASym(PublicKey, R) |     |     EF = Sym(F, R)     |
|                     |     |                        |
+----------+----------+     +------------+-----------+
           |                             |
           +------------+ +--------------+
                        | |
                        v v
         +--------------+-+---------------+
         |                                |
         |   send this files to the peer  |
         |                                |
         |     ASym(PublicKey, R) + EF    |
         |                                |
         +--------------------------------+

And the flow of Decryption:

   +----------------+        +--------------------+
   |                |        |                    |
   | EF = Sym(F, R) |        | ASym(PublicKey, R) |
   |                |        |                    |
   +-----+----------+        +---------+----------+
         |                             |
         |                             |
         |                             v
         |   +-------------------------+-----------------+
         |   |                                           |
         |   |             restore key (R)               |
         |   |                                           |
         |   | R <= ASym(PrivateKey, ASym(PublicKey, R)) |
         |   |                                           |
         |   +---------------------+---------------------+
         |                         |
         v                         v
     +---+-------------------------+---+
     |                                 |
     |       restore the file (F)      |
     |                                 |
     |      F <= Sym(Sym(F, R), R)     |
     |                                 |
     +---------------------------------+

Besides, you can use this commands:

# generate random symmetric key
openssl rand -base64 32 > /config/key.bin

# encryption
openssl rsautl -encrypt -pubin -inkey /config/public_key.pem -in /config/key.bin -out /config/key.bin.enc
openssl aes-256-cbc -a -pbkdf2 -salt -in  $file_name -out $file_name.enc -k $(cat /config/key.bin)

# now you can send this files: $file_name.enc + /config/key.bin.enc

# decryption
openssl rsautl -decrypt -inkey /config/private_key.pem -in /config/key.bin.enc -out /config/key.bin
openssl aes-256-cbc -d -a -in $file_name.enc -out $file_name -k $(cat /config/key.bin)

JUnit Testing private variables?

I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

I have the same error on amazon AMI linux.

I Solved by setting curl.cainfo on /etc/php.d/curl.ini

https://gist.github.com/reinaldomendes/97fb2ce8a606ec813c4b

Addition October 2018

On Amazon Linux v1 edit this file

vi /etc/php.d/20-curl.ini

To add this line

curl.cainfo="/etc/ssl/certs/ca-bundle.crt"

Auto Scale TextView Text to Fit within Bounds

Here's a simple solution that uses TextView itself with a TextChangedListened added to it:

expressionView = (TextView) findViewById(R.id.expressionView);
expressionView.addTextChangedListener(textAutoResizeWatcher(expressionView, 25, 55));

private TextWatcher textAutoResizeWatcher(final TextView view, final int MIN_SP, final int MAX_SP) {
    return new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

        @Override
        public void afterTextChanged(Editable editable) {

            final int widthLimitPixels = view.getWidth() - view.getPaddingRight() - view.getPaddingLeft();
            Paint paint = new Paint();
            float fontSizeSP = pixelsToSp(view.getTextSize());
            paint.setTextSize(spToPixels(fontSizeSP));

            String viewText = view.getText().toString();

            float widthPixels = paint.measureText(viewText);

            // Increase font size if necessary.
            if (widthPixels < widthLimitPixels){
                while (widthPixels < widthLimitPixels && fontSizeSP <= MAX_SP){
                    ++fontSizeSP;
                    paint.setTextSize(spToPixels(fontSizeSP));
                    widthPixels = paint.measureText(viewText);
                }
                --fontSizeSP;
            }
            // Decrease font size if necessary.
            else {
                while (widthPixels > widthLimitPixels || fontSizeSP > MAX_SP) {
                    if (fontSizeSP < MIN_SP) {
                        fontSizeSP = MIN_SP;
                        break;
                    }
                    --fontSizeSP;
                    paint.setTextSize(spToPixels(fontSizeSP));
                    widthPixels = paint.measureText(viewText);
                }
            }

            view.setTextSize(fontSizeSP);
        }
    };
}

private float pixelsToSp(float px) {
    float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
    return px/scaledDensity;
}

private float spToPixels(float sp) {
    float scaledDensity = getResources().getDisplayMetrics().scaledDensity;
    return sp * scaledDensity;
}

This approach will increase or decrease the font size as needed to fit the text, respecting the MIN_SP and MAX_SP bounds received as parameters.

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

I wanted Git to use the updated certificate bundle without replacing the one my entire system uses. Here's how to have Git use a specific file in my home directory:

mkdir ~/certs
curl https://curl.haxx.se/ca/cacert.pem -o ~/certs/cacert.pem

Now update .gitconfig to use this for peer verification:

[http]
sslCAinfo = /home/radium/certs/cacert.pem

Note I'm using an absolute path. Git does no path expansion here, so you can't use ~ without an ugly kludge. Alternatively, you can skip the config file and set the path via the environment variable GIT_SSL_CAINFO instead.

To troubleshoot this, set GIT_CURL_VERBOSE=1. The path of the CA file Git is using will be shown on lines starting with "CAfile:" in the output.

Edited to change from http to https.

Excel tab sheet names vs. Visual Basic sheet names

In the Excel object model a Worksheet has 2 different name properties:

Worksheet.Name
Worksheet.CodeName

the Name property is read/write and contains the name that appears on the sheet tab. It is user and VBA changeable

the CodeName property is read-only

You can reference a particular sheet as Worksheets("Fred").Range("A1") where Fred is the .Name property or as Sheet1.Range("A1") where Sheet1 is the codename of the worksheet.

How does C compute sin() and other math functions?

Whenever such a function is evaluated, then at some level there is most likely either:

  • A table of values which is interpolated (for fast, inaccurate applications - e.g. computer graphics)
  • The evaluation of a series that converges to the desired value --- probably not a taylor series, more likely something based on a fancy quadrature like Clenshaw-Curtis.

If there is no hardware support then the compiler probably uses the latter method, emitting only assembler code (with no debug symbols), rather than using a c library --- making it tricky for you to track the actual code down in your debugger.

How to asynchronously call a method in Java

It's probably not a real solution, but now - in Java 8 - You can make this code look at least a little better using lambda expression.

final String x = "somethingelse";
new Thread(() -> {
        x.matches("something");             
    }
).start();

And You could even do this in one line, still having it pretty readable.

new Thread(() -> x.matches("something")).start();

How should I validate an e-mail address?

If you are using API 8 or above, you can use the readily available Patterns class to validate email. Sample code:

public final static boolean isValidEmail(CharSequence target) {
    if (target == null) 
        return false;

    return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
}

By chance if you are even supporting API level less than 8, then you can simply copy the Patterns.java file into your project and reference it. You can get the source code for Patterns.java from this link

Sending email with gmail smtp with codeigniter email library

Another option I have working, in a linux server with Postfix:

First, configure CI email to use your server's email system: eg, in email.php, for example

# alias to postfix in a typical Postfix server
$config['protocol'] = 'sendmail'; 
$config['mailpath'] = '/usr/sbin/sendmail'; 

Then configure your postfix to relay the mail to google (perhaps depending on the sender address). You'll probably need to put you user-password settings in /etc/postfix/sasl_passwd (docs)

This is much simpler (and less fragmente) if you have a linux box, already configured to send some/all of its outgoing emails to Google.

What is the best Java email address validation method?

If you're looking to verify whether an email address is valid, then VRFY will get you some of the way. I've found it's useful for validating intranet addresses (that is, email addresses for internal sites). However it's less useful for internet mail servers (see the caveats at the top of this page)

Performance of Java matrix math libraries?

I'm the main author of jblas and wanted to point out that I've released Version 1.0 in late December 2009. I worked a lot on the packaging, meaning that you can now just download a "fat jar" with ATLAS and JNI libraries for Windows, Linux, Mac OS X, 32 and 64 bit (except for Windows). This way you will get the native performance just by adding the jar file to your classpath. Check it out at http://jblas.org!

How can I check for Python version in a program that uses new language features?

I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.

eg:

try :
    # Do stuff
except : # Features weren't found.
    # Do stuff for older versions.

As long as you're specific in enough in using the try/except blocks, you can cover most of your bases.

Invoking JavaScript code in an iframe from the parent page

In the IFRAME, make your function public to the window object:

window.myFunction = function(args) {
   doStuff();
}

For access from the parent page, use this:

var iframe = document.getElementById("iframeId");
iframe.contentWindow.myFunction(args);

How many parameters are too many?

I'd draw the limit for public functions at 5 parameters myself.

IMHO, long parameter lists are only acceptable in private/local helper functions that are only meant to be called from a few specific places in the code. In those cases, you may need to pass a lot of state information along, but readability isn't as big of a concern since only you (or someone who will maintain your code and should understand the fundamentals of your module) have to care about calling that function.

How to create a GUID / UUID

Just thought I'd post yet another way of doing the same thing.

function guid() {
  var chars = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"];
  var str = "";
  for(var i=0;i<36;i++) {
    var str = str + ((i == 8 || i == 13 || i == 18 || i == 23) ? "-" : chars[Math.floor(Math.random()*chars.length)]);
  };
  return str;
}

Microsoft Excel mangles Diacritics in .csv files?

Echo UTF-8 BOM before outputing CSV data. This fixes all character issues in Windows but doesnt work for Mac.

echo "\xEF\xBB\xBF";

It works for me because I need to generate a file which will be used on Windows PCs only.

Center Div inside another (100% width) div

for detail info, let's say the code below will make a div aligned center:

margin-left: auto;
margin-right: auto;

or simply use:

margin: 0 auto;

but bear in mind, the above CSS code only works when you specify a fixed width (not 100%) on your html element. so the complete solution for your issue would be:

.your-inner-div {
      margin: 0 auto;
      width: 900px;
}

Array definition in XML?

As its name is "numbers" it is clear it is a list of number... So an array of number... no need of the attribute type... Although I like the principle of specifying the type of field in a type attribute...

is it possible to get the MAC address for machine using nmap

Just the standard scan will return the MAC.

nmap -sS target

Get full URL and query string in Servlet for both HTTP and HTTPS requests

I know this is a Java question, but if you're using Kotlin you can do this quite nicely:

val uri = request.run {
    if (queryString.isNullOrBlank()) requestURI else "$requestURI?$queryString"
}

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:

$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});

If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:

$.post('/url/to/page', {'someKeyName': ['value','value']});

If you want to pass a JavaScript array then you can do:

$.post('/url/to/page', {'someKeyName': variableName});

Java division by zero doesnt throw an ArithmeticException - why?

IEEE 754 defines 1.0 / 0.0 as Infinity and -1.0 / 0.0 as -Infinity and 0.0 / 0.0 as NaN.

By the way, floating point values also have -0.0 and so 1.0/ -0.0 is -Infinity.

Integer arithmetic doesn't have any of these values and throws an Exception instead.

To check for all possible values (e.g. NaN, 0.0, -0.0) which could produce a non finite number you can do the following.

if (Math.abs(tab[i] = 1 / tab[i]) < Double.POSITIVE_INFINITY)
   throw new ArithmeticException("Not finite");

Is it not possible to stringify an Error using JSON.stringify?

As no one is talking about the why part, I'm gonna answer it.

Why this JSON.stringify returns an empty object?

> JSON.stringify(error);
'{}'

Answer

From the document of JSON.stringify(),

For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.

and Error object doesn't have its enumerable properties, that's why it prints an empty object.

How to Validate a DateTime in C#?

protected static bool CheckDate(DateTime date)
{
    if(new DateTime() == date)      
        return false;       
    else        
        return true;        
} 

When is null or undefined used in JavaScript?

A property, when it has no definition, is undefined. null is an object. It's type is null. undefined is not an object, its type is undefined.

This is a good article explaining the difference and also giving some examples.

null vs undefined

Redirect output of mongo query to a csv file

When executing a script in a remote server. Mongo will add its own logging output, which we might want to omit from our file. --quiet option will only disable connection related logs. Not all mongo logs. In such case we might need to filter out unneeded lines manually. A Windows based example:

mongo dbname --username userName --password password --host replicaset/ip:port --quiet printDataToCsv.js | findstr /v "NETWORK" > data.csv

This will pipe the script output and use findstr to filter out any lines, which have NETWORK string in them. More information on findstr: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr

A Linux version of this would use grep.

How to append something to an array?

Use concat:

_x000D_
_x000D_
a = [1, 2, 3];_x000D_
b = [3, 4, 5];_x000D_
a = a.concat(b);_x000D_
console.log(a);
_x000D_
_x000D_
_x000D_

Set start value for column with autoincrement

Also note that you cannot normally set a value for an IDENTITY column. You can, however, specify the identity of rows if you set IDENTITY_INSERT to ON for your table. For example:

SET IDENTITY_INSERT Orders ON

-- do inserts here

SET IDENTITY_INSERT Orders OFF

This insert will reset the identity to the last inserted value. From MSDN:

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

Is there a way of setting culture for a whole application? All current threads and new threads?

Here is the solution for c# MVC:

  1. First : Create a custom attribute and override method like this:

    public class CultureAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // Retreive culture from GET
            string currentCulture = filterContext.HttpContext.Request.QueryString["culture"];
    
            // Also, you can retreive culture from Cookie like this :
            //string currentCulture = filterContext.HttpContext.Request.Cookies["cookie"].Value;
    
            // Set culture
            Thread.CurrentThread.CurrentCulture = new CultureInfo(currentCulture);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentCulture);
        }
    }
    
  2. Second : In App_Start, find FilterConfig.cs, add this attribute. (this works for WHOLE application)

    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            // Add custom attribute here
            filters.Add(new CultureAttribute());
        }
    }    
    

That's it !

If you want to define culture for each controller/action in stead of whole application, you can use this attribute like this:

[Culture]
public class StudentsController : Controller
{
}

Or:

[Culture]
public ActionResult Index()
{
    return View();
}

Splitting string into multiple rows in Oracle

regular expressions is a wonderful thing :)

with temp as  (
       select 108 Name, 'test' Project, 'Err1, Err2, Err3' Error  from dual
       union all
       select 109, 'test2', 'Err1' from dual
     )

SELECT distinct Name, Project, trim(regexp_substr(str, '[^,]+', 1, level)) str
  FROM (SELECT Name, Project, Error str FROM temp) t
CONNECT BY instr(str, ',', 1, level - 1) > 0
order by Name

what does mysql_real_escape_string() really do?

The mysqli_real_escape_string() function escapes special characters in a string for use in an SQL statement.

Split a vector into chunks

If you don't like split() and you don't mind NAs padding out your short tail:

chunk <- function(x, n) { if((length(x)%%n)==0) {return(matrix(x, nrow=n))} else {return(matrix(append(x, rep(NA, n-(length(x)%%n))), nrow=n))} }

The columns of the returned matrix ([,1:ncol]) are the droids you are looking for.

Checking for Undefined In React

I was face same problem ..... And I got solution by using typeof()

if (typeof(value) !== 'undefined' && value != null) {
         console.log('Not Undefined and Not Null')
  } else {
         console.log('Undefined or Null')
}

You must have to use typeof() to identified undefined

What is the T-SQL syntax to connect to another SQL Server?

Update: for connecting to another sql server and executing sql statements, you have to use sqlcmd Utility. This is typically done in a batch file. You can combine this with xmp_cmdshell if you want to execute it within management studio.


one way is to configure a linked server. then you can append the linked server and the database name to the table name. (select * from linkedserver.database.dbo.TableName)

USE master
GO
EXEC sp_addlinkedserver 
    'SEATTLESales',
    N'SQL Server'
GO

What's the correct way to communicate between controllers in AngularJS?

You should use the Service , because $rootscope is access from whole Application , and it increases the load, or youc use the rootparams if your data is not more.

I want to load another HTML page after a specific amount of time

Use Javascript's setTimeout:

<body onload="setTimeout(function(){window.location = 'form2.html';}, 5000)">

Simple dynamic breadcrumb

I started with the code from Dominic Barnes, incorporated the feedback from cWoDeR and I still had problems with the breadcrumbs at the third level when I used a sub-directory. So I rewrote it and have included the code below.

Note that I have set up my web site structure such that pages to be subordinate to (linked from) a page at the root level are set up as follows:

  • Create a folder with the EXACT same name as the file (including capitalization), minus the suffix, as a folder at the root level

  • place all subordinate files/pages into this folder

(eg, if want sobordinate pages for Customers.php:

  • create a folder called Customers at the same level as Customers.php

  • add an index.php file into the Customers folder which redirects to the calling page for the folder (see below for code)

This structure will work for multiple levels of subfolders.

Just make sure you follow the file structure described above AND insert an index.php file with the code shown in each subfolder.

The code in the index.php page in each subfolder looks like:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Redirected</title>
</head>
<body>
<?php 
$root_dir = "web_root/" ;
$last_dir=array_slice(array_filter(explode('/',$_SERVER['PHP_SELF'])),-2,1,false) ;
$path_to_redirect = "/".$root_dir.$last_dir[0].".php" ; 
header('Location: '.$path_to_redirect) ; 
?>
</body>
</html>

If you use the root directory of the server as your web root (ie /var/www/html) then set $root_dir="": (do NOT leave the trailing "/" in). If you use a subdirectory for your web site (ie /var/www/html/web_root then set $root_dir = "web_root/"; (replace web_root with the actual name of your web directory)(make sure to include the trailing /)

at any rate, here is my (derivative) code:

<?php

// Big Thank You to the folks on StackOverflow
// See http://stackoverflow.com/questions/2594211/php-simple-dynamic-breadcrumb
// Edited to enable using subdirectories to /var/www/html as root
// eg, using /var/www/html/<this folder> as the root directory for this web site
// To enable this, enter the name of the subdirectory being used as web root
// in the $directory2 variable below
// Make sure to include the trailing "/" at the end of the directory name
// eg use      $directory2="this_folder/" ;
// do NOT use  $directory2="this_folder" ;
// If you actually ARE using /var/www/html as the root directory,
// just set $directory2 = "" (blank)
// with NO trailing "/"

// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' &raquo; ' , $home = 'Home') 
{

    // This sets the subdirectory as web_root (If you want to use a subdirectory)
    // If you do not use a web_root subdirectory, set $directory2=""; (NO trailing /)
    $directory2 = "web_root/" ;

    // This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
    $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ;
    $path_array = array_filter(explode('/',$path)) ;

    // This line of code accommodates using a subfolder (/var/www/html/<this folder>) as root
    // This removes the first item in the array path so it doesn't repeat
    if ($directory2 != "")
    {
    array_shift($path_array) ;
    }

    // This will build our "base URL" ... Also accounts for HTTPS :)
    $base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/'. $directory2 ;

    // Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
    $breadcrumbs = Array("<a href=\"$base\">$home</a>") ;

    // Get the index for the last value in our path array
    $last = end($path_array) ;

    // Initialize the counter
    $crumb_counter = 2 ;

    // Build the rest of the breadcrumbs
    foreach ($path_array as $crumb) 
    {
        // Our "title" is the text that will be displayed representing the filename without the .suffix
        // If there is no "." in the crumb, it is a directory
        if (strpos($crumb,".") == false)
        {
            $title = $crumb ;
        }
        else
        {
            $title = substr($crumb,0,strpos($crumb,".")) ;
        }

        // If we are not on the last index, then create a hyperlink
        if ($crumb != $last)
        {
            $calling_page_array = array_slice(array_values(array_filter(explode('/',$path))),0,$crumb_counter,false) ;
            $calling_page_path = "/".implode('/',$calling_page_array).".php" ;
            $breadcrumbs[] = "<a href=".$calling_page_path.">".$title."</a>" ;
        }

        // Otherwise, just display the title
        else
        {
            $breadcrumbs[] = $title ;
        }

        $crumb_counter = $crumb_counter + 1 ;

    }
    // Build our temporary array (pieces of bread) into one big string :)
    return implode($separator, $breadcrumbs) ;
}

// <p><?= breadcrumbs() ? ></p>
// <p><?= breadcrumbs(' > ') ? ></p>
// <p><?= breadcrumbs(' ^^ ', 'Index') ? ></p>
?>

Laravel Migration table already exists, but I want to add new not the older

I had the same trouble. The reason is that your file name in migrations folder does not match with name of migration in your database (see migrations table). They should be the same.

cut or awk command to print first field of first row

sed -n 1p /etc/*release |cut -d " " -f1

if tab delimited:

sed -n 1p /etc/*release |cut -f1

Which data structures and algorithms book should I buy?

Introduction to Algorithms by Cormen et. al. is a standard introductory algorithms book, and is used by many universities, including my own. It has pretty good coverage and is very approachable.

And anything by Robert Sedgewick is good too.

How to verify a Text present in the loaded page through WebDriver

If you are not bothered about the location of the text present, then you could use Driver.PageSource property as below:

Driver.PageSource.Contains("expected message");

Simple way to read single record from MySQL

'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:

with mysqli

$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();

with Zend Framework

//Inside the table class

$select = $this->select()->where('user_id = ?', 1);  
$row = $this->fetchRow($select);

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.

You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \rrather than the linux standard \n or better still the suspenders and belt approach of windows with \r\n.

pandas.read_csv(filename, sep='\t', lineterminator='\r')

You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.

import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep='\t')

C++ getters/setters coding style

It tends to be a bad idea to make non-const fields public because it then becomes hard to force error checking constraints and/or add side-effects to value changes in the future.

In your case, you have a const field, so the above issues are not a problem. The main downside of making it a public field is that you're locking down the underlying implementation. For example, if in the future you wanted to change the internal representation to a C-string or a Unicode string, or something else, then you'd break all the client code. With a getter, you could convert to the legacy representation for existing clients while providing the newer functionality to new users via a new getter.

I'd still suggest having a getter method like the one you have placed above. This will maximize your future flexibility.

How to delete a stash created with git stash create?

You should be using

git stash save

and not

git stash create

because this creates a stash (which is a regular commit object) and return its object name, without storing it anywhere in the ref namespace. Hence won't be accessible with stash apply.

Use git stash save "some comment" is used when you have unstaged changes you wanna replicate/move onto another branch

Use git stash apply stash@{0} (assuming your saved stash index is 0) when you want your saved(stashed) changes to reflect on your current branch

you can always use git stash list to check all you stash indexes

and use git stash drop stash@{0} (assuming your saved stash index is 0 and you wanna delete it) to delete a particular stash.

Javascript to check whether a checkbox is being checked or unchecked

To toggle a checkbox or you can use

element.checked = !element.checked;

so you could use

if (attribute == elementName)
{
    arrChecks[i].checked = !arrChecks[i].checked;
} else {
    arrChecks[i].checked = false;
}

Sort array of objects by single key with date value

The Array.sort() method sorts the elements of an array in place and returns the array. Be careful with Array.sort() as it's not Immutable. For immutable sort use immutable-sort.

This method is to sort the array using your current updated_at in ISO format. We use new Data(iso_string).getTime() to convert ISO time to Unix timestamp. A Unix timestamp is a number that we can do simple math on. We subtract the first and second timestamp the result is; if the first timestamp is bigger than the second the return number will be positive. If the second number is bigger than the first the return value will be negative. If the two are the same the return will be zero. This alines perfectly with the required return values for the inline function.

For ES6:

arr.sort((a,b) => new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime());

For ES5:

arr.sort(function(a,b){ 
 return new Date(a.updated_at).getTime() - new Date(b.updated_at).getTime();
});

If you change your updated_at to be unix timestamps you can do this:

For ES6:

arr.sort((a,b) => a.updated_at - b.updated_at);

For ES5:

arr.sort(function(a,b){ 
 return a.updated_at - b.updated_at;
});

At the time of this post, modern browsers do not support ES6. To use ES6 in modern browsers use babel to transpile the code to ES5. Expect browser support for ES6 in the near future.

Array.sort() should receave a return value of one of 3 possible outcomes:

  • A positive number (first item > second item)
  • A negative number (first item < second item)
  • 0 if the two items are equal

Note that the return value on the inline function can be any positive or negative number. Array.Sort() does not care what the return number is. It only cares if the return value is positive, negative or zero.

For Immutable sort: (example in ES6)

const sort = require('immutable-sort');
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

You can also write it this way:

import sort from 'immutable-sort';
const array = [1, 5, 2, 4, 3];
const sortedArray = sort(array);

The import-from you see is a new way to include javascript in ES6 and makes your code look very clean. My personal favorite.

Immutable sort doesn't mutate the source array rather it returns a new array. Using const is recommended on immutable data.

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Edit file /usr/share/phpmyadmin/libraries/sql.lib.php using this command:

sudo nano +613 /usr/share/phpmyadmin/libraries/sql.lib.php

On line 613 the count function always evaluates to true since there is no closing parenthesis after $analyzed_sql_results['select_expr']. Making the below replacements resolves this, then you will need to delete the last closing parenthesis on line 614, as it's now an extra parenthesis.

Replace:

((empty($analyzed_sql_results['select_expr']))
    || (count($analyzed_sql_results['select_expr'] == 1)
        && ($analyzed_sql_results['select_expr'][0] == '*')))

With:

((empty($analyzed_sql_results['select_expr']))
    || (count($analyzed_sql_results['select_expr']) == 1)
        && ($analyzed_sql_results['select_expr'][0] == '*'))

Restart the server apache:

sudo service apache2 restart

JavaScript to get rows count of a HTML table

You can use the .rows property and check it's .length, like this:

var rowCount = document.getElementById('myTableID').rows.length;

Static variable inside of a function in C

That is the same as having the following program:

static int x = 5;

void foo()
{
    x++;
    printf("%d", x);
}

int main()
{
     foo();
     foo();
     return 0;
}

All that the static keyword does in that program is it tells the compiler (essentially) 'hey, I have a variable here that I don't want anyone else accessing, don't tell anyone else it exists'.

Inside a method, the static keyword tells the compiler the same as above, but also, 'don't tell anyone that this exists outside of this function, it should only be accessible inside this function'.

I hope this helps

CSS to hide INPUT BUTTON value text

color:transparent; and then any text-transform property does the trick too.

For example:

color: transparent;
text-transform: uppercase;

Is there a Subversion command to reset the working copy?

Pure Windows cmd/bat solution:

svn cleanup .
svn revert -R .
For /f "tokens=1,2" %%A in ('svn status --no-ignore') Do (
     If [%%A]==[?] ( Call :UniDelete %%B
     ) Else If [%%A]==[I] Call :UniDelete %%B
   )
svn update .
goto :eof

:UniDelete delete file/dir
IF EXIST "%1\*" (
    RD /S /Q "%1"
) Else (
    If EXIST "%1" DEL /S /F /Q "%1"
)
goto :eof

Example to use shared_ptr?

#include <memory>
#include <iostream>

class SharedMemory {
    public: 
        SharedMemory(int* x):_capture(x){}
        int* get() { return (_capture.get()); }
    protected:
        std::shared_ptr<int> _capture;
};

int main(int , char**){
    SharedMemory *_obj1= new SharedMemory(new int(10));
    SharedMemory *_obj2 = new SharedMemory(*_obj1);
    std::cout << " _obj1: " << *_obj1->get() << " _obj2: " << *_obj2->get()
    << std::endl;
    delete _obj2;

    std::cout << " _obj1: " << *_obj1->get() << std::endl;
    delete _obj1;
    std::cout << " done " << std::endl;
}

This is an example of shared_ptr in action. _obj2 was deleted but pointer is still valid. output is, ./test _obj1: 10 _obj2: 10 _obj2: 10 done

Spring JPA and persistence.xml

This may be old, but if anyone has the same problem try changing unitname to just name in the PersistenceContext annotation:

From

@PersistenceContext(unitName="educationPU")

to

@PersistenceContext(name="educationPU")

Float right and position absolute doesn't work together

You can use "translateX(-100%)" and "text-align: right" if your absolute element is "display: inline-block"

<div class="box">
<div class="absolute-right"></div>
</div>

<style type="text/css">
.box{
    text-align: right;
}
.absolute-right{
    display: inline-block;
    position: absolute;
}

/*The magic:*/
.absolute-right{
-moz-transform: translateX(-100%);
-ms-transform: translateX(-100%);
-webkit-transform: translateX(-100%);
-o-transform: translateX(-100%);
transform: translateX(-100%);
}
</style>

You will get absolute-element aligned to the right relative its parent

How to hide a column (GridView) but still access its value?

Define a style in css:

.hiddencol { display: none; }

Then add the ItemStyle-CssClass="hiddencol" and the HeaderStyle-CssClass="hiddencol" attribute to the grid field:

<asp:BoundField DataField="ID" HeaderText="ID" ItemStyle-CssClass="hiddencol"  HeaderStyle-CssClass="hiddencol" ClientIDMode="Static" />

Tkinter understanding mainloop

while 1:
    root.update()

... is (very!) roughly similar to:

root.mainloop()

The difference is, mainloop is the correct way to code and the infinite loop is subtly incorrect. I suspect, though, that the vast majority of the time, either will work. It's just that mainloop is a much cleaner solution. After all, calling mainloop is essentially this under the covers:

while the_window_has_not_been_destroyed():
    wait_until_the_event_queue_is_not_empty()
    event = event_queue.pop()
    event.handle()

... which, as you can see, isn't much different than your own while loop. So, why create your own infinite loop when tkinter already has one you can use?

Put in the simplest terms possible: always call mainloop as the last logical line of code in your program. That's how Tkinter was designed to be used.

How to animate a View with Translate Animation in Android

In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.

You can try this sample code:

main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" android:id="@+id/rootLayout">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="MOVE" android:layout_centerHorizontal="true"/>

    <ImageView
        android:id="@+id/img1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
    <ImageView
        android:id="@+id/img2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
    <ImageView
        android:id="@+id/img3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">

        <ImageView
            android:id="@+id/img4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
    </LinearLayout>

</RelativeLayout>

Your activity

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            ImageView img = (ImageView) findViewById( R.id.img1 );              
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img2 );
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img3 );                
            moveViewToScreenCenter( img );
            img = (ImageView) findViewById( R.id.img4 );
            moveViewToScreenCenter( img );
        }
    });
}

private void moveViewToScreenCenter( View view )
{
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
    DisplayMetrics dm = new DisplayMetrics();
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();

    int originalPos[] = new int[2];
    view.getLocationOnScreen( originalPos );

    int xDest = dm.widthPixels/2;
    xDest -= (view.getMeasuredWidth()/2);
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;

    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
    anim.setDuration(1000);
    anim.setFillAfter( true );
    view.startAnimation(anim);
}

The method moveViewToScreenCenter gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.

Why does background-color have no effect on this DIV?

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

Generate insert script for selected records?

In SSMS execute your sql query. From the result window select all cells and copy the values. Goto below website and there you can paste the copied data and generate sql scripts. You can also save results of query from SSMS as CSV file and import the csv file in this website.

http://www.convertcsv.com/csv-to-sql.htm

Accessing dict_keys element by index in Python3

In many cases, this may be an XY Problem. Why are you indexing your dictionary keys by position? Do you really need to? Until recently, dictionaries were not even ordered in Python, so accessing the first element was arbitrary.

I just translated some Python 2 code to Python 3:

keys = d.keys()
for (i, res) in enumerate(some_list):
    k = keys[i]
    # ...

which is not pretty, but not very bad either. At first, I was about to replace it by the monstrous

    k = next(itertools.islice(iter(keys), i, None))

before I realised this is all much better written as

for (k, res) in zip(d.keys(), some_list):

which works just fine.

I believe that in many other cases, indexing dictionary keys by position can be avoided. Although dictionaries are ordered in Python 3.7, relying on that is not pretty. The code above only works because the contents of some_list had been recently produced from the contents of d.

Have a hard look at your code if you really need to access a disk_keys element by index. Perhaps you don't need to.

SQL DELETE with JOIN another table for WHERE condition

How about:

DELETE guide_category  
  WHERE id_guide_category IN ( 

        SELECT id_guide_category 
          FROM guide_category AS gc
     LEFT JOIN guide AS g 
            ON g.id_guide = gc.id_guide
         WHERE g.title IS NULL

  )

Are dictionaries ordered in Python 3.6+?

To fully answer this question in 2020, let me quote several statements from official Python docs:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

Changed in version 3.8: Dictionaries are now reversible.

Dictionaries and dictionary views are reversible.

A statement regarding OrderedDict vs Dict:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

C# "No suitable method found to override." -- but there is one

Probably your base class is a different one with the same name. Check by right click on the extended class and go to the definition. Check if the class is correct one.

Reading and writing environment variables in Python?

If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.

If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.

Remove border from buttons

You can also try background:none;border:0px to buttons.

also the css selectors are div#yes button{..} and div#no button{..} . hopes it helps

What are the differences between the BLOB and TEXT datatypes in MySQL?

According to High-performance Mysql book:

The only difference between the BLOB and TEXT families is that BLOB types store binary data with no collation or character set, but TEXT types have a character set and collation.

How to remove whitespace from a string in typescript?

The trim() method removes whitespace from both sides of a string.

To remove all the spaces from the string use .replace(/\s/g, "")

 this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();

How to add an element to the beginning of an OrderedDict?

There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend() method/function that operates on the OrderedDict internals with O(1) complexity.

For Python 3.2 and later, you should use the move_to_end method. The method accepts a last argument which indicates whether the element will be moved to the bottom (last=True) or the top (last=False) of the OrderedDict.

Finally, if you want a quick, dirty and slow solution, you can just create a new OrderedDict from scratch.

Details for the four different solutions:


Extend OrderedDict and add a new instance method

from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def prepend(self, key, value, dict_setitem=dict.__setitem__):

        root = self._OrderedDict__root
        first = root[1]

        if key in self:
            link = self._OrderedDict__map[key]
            link_prev, link_next, _ = link
            link_prev[1] = link_next
            link_next[0] = link_prev
            link[0] = root
            link[1] = first
            root[1] = first[0] = link
        else:
            root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
            dict_setitem(self, key, value)

Demo:

>>> d = MyOrderedDict([('a', '1'), ('b', '2')])
>>> d
MyOrderedDict([('a', '1'), ('b', '2')])
>>> d.prepend('c', 100)
>>> d
MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> d.prepend('a', d['a'])
>>> d
MyOrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> d.prepend('d', 200)
>>> d
MyOrderedDict([('d', 200), ('a', '1'), ('c', 100), ('b', '2')])

Standalone function that manipulates OrderedDict objects

This function does the same thing by accepting the dict object, key and value. I personally prefer the class:

from collections import OrderedDict

def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
    root = dct._OrderedDict__root
    first = root[1]

    if key in dct:
        link = dct._OrderedDict__map[key]
        link_prev, link_next, _ = link
        link_prev[1] = link_next
        link_next[0] = link_prev
        link[0] = root
        link[1] = first
        root[1] = first[0] = link
    else:
        root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
        dict_setitem(dct, key, value)

Demo:

>>> d = OrderedDict([('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'c', 100)
>>> d
OrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'a', d['a'])
>>> d
OrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> ordered_dict_prepend(d, 'd', 500)
>>> d
OrderedDict([('d', 500), ('a', '1'), ('c', 100), ('b', '2')])

Use OrderedDict.move_to_end() (Python >= 3.2)

Python 3.2 introduced the OrderedDict.move_to_end() method. Using it, we can move an existing key to either end of the dictionary in O(1) time.

>>> d1 = OrderedDict([('a', '1'), ('b', '2')])
>>> d1.update({'c':'3'})
>>> d1.move_to_end('c', last=False)
>>> d1
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])

If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend() wrapper (not presented here).


Create a new OrderedDict - slow!!!

If you don't want to do that and performance is not an issue then easiest way is to create a new dict:

from itertools import chain, ifilterfalse
from collections import OrderedDict


def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

d1 = OrderedDict([('a', '1'), ('b', '2'),('c', 4)])
d2 = OrderedDict([('c', 3), ('e', 5)])   #dict containing items to be added at the front
new_dic = OrderedDict((k, d2.get(k, d1.get(k))) for k in \
                                           unique_everseen(chain(d2, d1)))
print new_dic

output:

OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])

Multi value Dictionary

Dictionary<T1, Tuple<T2, T3>>

Edit: Sorry - I forgot you don't get Tuples until .NET 4.0 comes out. D'oh!

Android Left to Right slide animation

Also, you can do this:

FirstClass.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

And you don't need to add any animation xml

How can I change image tintColor in iOS and WatchKit

With iOS 13 and above, you can simply use

let image = UIImage(named: "Heart")?.withRenderingMode(.alwaysTemplate)
if #available(iOS 13.0, *) {
   imageView.image = image?.withTintColor(UIColor.white)
}

Reading in a JSON File Using Swift

Swift 4 using Decodable

struct ResponseData: Decodable {
    var person: [Person]
}
struct Person : Decodable {
    var name: String
    var age: String
    var employed: String
}

func loadJson(filename fileName: String) -> [Person]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(ResponseData.self, from: data)
            return jsonData.person
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

Swift 3

func loadJson(filename fileName: String) -> [String: AnyObject]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let object = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            if let dictionary = object as? [String: AnyObject] {
                return dictionary
            }
        } catch {
            print("Error!! Unable to parse  \(fileName).json")
        }
    }
    return nil
}

Can't connect to MySQL server error 111

It probably means that your MySQL server is only listening the localhost interface.

If you have lines like this :

bind-address = 127.0.0.1

In your my.cnf configuration file, you should comment them (add a # at the beginning of the lines), and restart MySQL.

sudo service mysql restart

Of course, to do this, you must be the administrator of the server.

Using AND/OR in if else PHP statement

AND is && and OR is || like in C.

How can you flush a write using a file descriptor?

You have two choices:

  1. Use fileno() to obtain the file descriptor associated with the stdio stream pointer

  2. Don't use <stdio.h> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write() call won't even return until the lower-level IO has completed (in theory).

For device-level IO I'd say it's pretty unusual to use stdio. I'd strongly recommend using the lower-level open(), read() and write() functions instead (based on your later reply):

int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

Check if property has attribute

There's no fast way to retrieve attributes. But code ought to look like this (credit to Aaronaught):

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var hasIsIdentity = Attribute.IsDefined(pi, typeof(IsIdentity));

If you need to retrieve attribute properties then

var t = typeof(YourClass);
var pi = t.GetProperty("Id");
var attr = (IsIdentity[])pi.GetCustomAttributes(typeof(IsIdentity), false);
if (attr.Length > 0) {
    // Use attr[0], you'll need foreach on attr if MultiUse is true
}

month name to month number and vice versa in python

To get the full calendar name from the month number, you can use calendar.month_name. Please see the documentation for more details: https://docs.python.org/2/library/calendar.html

month_no = 1
month = calendar.month_name[month_no]

# month provides "January":
print(month)


Angular cli generate a service and include the provider in one step

In Angular 5.12 and latest Angular CLI, do

ng generate service my-service -m app.module

Use :hover to modify the css of another class?

Provided .wrapper is inside .item, and provided you're either not in IE 6 or .item is an a tag, the CSS you have should work just fine. Do you have evidence to suggest it isn't?

EDIT:

CSS alone can't affect something not contained within it. To make this happen, format your menu like so:

<ul class="menu">
    <li class="menuitem">
        <a href="destination">menu text</a>
        <ul class="menu">
            <li class="menuitem">
                <a href="destination">part of pull-out menu</a>
... etc ...

and your CSS like this:

.menu .menu {
    display: none;
}

.menu .menuitem:hover .menu {
    display: block;
    float: left;
    // likely need to set top & left
}

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

we are using MSMQ in our system, this error message came. The reason was our queue was full and we did not handle the error logging mechanism properly so we were getting the above exception instead of msmq ful. We cleared the messages then it is working fine.

How to show a GUI message box from a bash script in linux?

Kdialog and dialog are both good, but I'd recommend Zenity. Quick, easy, and much better looking the xmessage or dialog.

How to create python bytes object from long hex string?

result = bytes.fromhex(some_hex_string)

Changing the maximum length of a varchar column?

This worked for me in db2:

alter table "JOBS"  alter column "JOB_TITLE" set  data type varchar(30);

What is the difference between cache and persist?

With cache(), you use only the default storage level :

  • MEMORY_ONLY for RDD
  • MEMORY_AND_DISK for Dataset

With persist(), you can specify which storage level you want for both RDD and Dataset.

From the official docs:

  • You can mark an RDD to be persisted using the persist() or cache() methods on it.
  • each persisted RDD can be stored using a different storage level
  • The cache() method is a shorthand for using the default storage level, which is StorageLevel.MEMORY_ONLY (store deserialized objects in memory).

Use persist() if you want to assign a storage level other than :

  • MEMORY_ONLY to the RDD
  • or MEMORY_AND_DISK for Dataset

Interesting link for the official documentation : which storage level to choose

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

This error can occur when an application makes a new connection for every database interaction or the connections are not closed properly. One of the free tools to monitor and confirm this is Oracle Sql developer (although this is not the only tool you can use to monitor DB sessions).

you can download the tool from oracle site Sql Developer

here is a screenshot of how to monitor you sessions. (if you see many sessions piling up for your application user during when you see the ORA-12514 error then it's a good indication that you may have connection pool problem).

enter image description here

How to get Android application id?

i'm not sure what "application id" you are referring to, but for a unique identifier of your application you can use:

getApplication().getPackageName() method from your current activity

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT 
   ActivityID,
   FieldName = CASE 
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END,
   FieldName2 = CASE
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END

oracle plsql: how to parse XML and insert into table

select *  
FROM XMLTABLE('/person/row'  
         PASSING   
            xmltype('
                <person>
                   <row>
                       <name>Tom</name>
                       <Address>
                           <State>California</State>
                           <City>Los angeles</City>
                       </Address>
                   </row>
                   <row>
                       <name>Jim</name>
                       <Address>
                           <State>California</State>
                           <City>Los angeles</City>
                       </Address>
                   </row>
                </person>
            ')
         COLUMNS  
            --describe columns and path to them:  
            name  varchar2(20)    PATH './name',  
            state varchar2(20)    PATH './Address/State',  
            city  varchar2(20)    PATH './Address/City'
     ) xmlt  
;  

How do I stop/start a scheduled task on a remote computer programmatically?

Note: "schtasks" (see the other, accepted response) has replaced "at". However, "at" may be of use if the situation calls for compatibility with older versions of Windows that don't have schtasks.

Command-line help for "at":

C:\>at /?
The AT command schedules commands and programs to run on a computer at
a specified time and date. The Schedule service must be running to use
the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\\computername     Specifies a remote computer. Commands are scheduled on the
                   local computer if this parameter is omitted.
id                 Is an identification number assigned to a scheduled
                   command.
/delete            Cancels a scheduled command. If id is omitted, all the
                   scheduled commands on the computer are canceled.
/yes               Used with cancel all jobs command when no further
                   confirmation is desired.
time               Specifies the time when command is to run.
/interactive       Allows the job to interact with the desktop of the user
                   who is logged on at the time the job runs.
/every:date[,...]  Runs the command on each specified day(s) of the week or
                   month. If date is omitted, the current day of the month
                   is assumed.
/next:date[,...]   Runs the specified command on the next occurrence of the
                   day (for example, next Thursday).  If date is omitted, the
                   current day of the month is assumed.
"command"          Is the Windows NT command, or batch program to be run.

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How to run single test method with phpunit?

So, something like this

phpunit --filter 'EscalationGroupTest::testSaveAndDrop' EscalationGroupTest escalation/EscalationGroupTest.php 

Without = and with '

https://phpunit.de/manual/3.7/en/textui.html

Get index of a key in json

Try this

var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);

var i = 0, req_index = "";
$.each(json, function(index, value){
    if(index == 'key2'){
        req_index = i;
    }
    i++;
});
alert(req_index);

how to git commit a whole folder?

OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.

  1. Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.

  2. Open your folder which you want to upload. drag and drop on the listing in browser. See the image here.

Can't create handler inside thread which has not called Looper.prepare()

The error is self-explanatory... doInBackground() runs on a background thread which, since it is not intended to loop, is not connected to a Looper.

You most likely don't want to directly instantiate a Handler at all... whatever data your doInBackground() implementation returns will be passed to onPostExecute() which runs on the UI thread.

   mActivity = ThisActivity.this; 

    mActivity.runOnUiThread(new Runnable() {
     public void run() {
     new asyncCreateText().execute();
     }
   });

ADDED FOLLOWING THE STACKTRACE APPEARING IN QUESTION:

Looks like you're trying to start an AsyncTask from a GL rendering thread... don't do that cos they won't ever Looper.loop() either. AsyncTasks are really designed to be run from the UI thread only.

The least disruptive fix would probably be to call Activity.runOnUiThread() with a Runnable that kicks off your AsyncTask.

Vue is not defined

I found two main problems with that implementation. First, when you import the vue.js script you use type="JavaScript" as content-type which is wrong. You should remove this type parameter because by default script tags have text/javascript as default content-type. Or, just replace the type parameter with the correct content-type which is type="text/javascript".

The second problem is that your script is embedded in the same HTML file means that it may be triggered first and probably the vue.js file was not loaded yet. You can fix this using a jQuery snippet $(function(){ /* ... */ }); or adding a javascript function as shown in this example:

_x000D_
_x000D_
// Verifies if the document is ready_x000D_
function ready(f) {_x000D_
  /in/.test(document.readyState) ? setTimeout('ready(' + f + ')', 9) : f();_x000D_
}_x000D_
_x000D_
ready(function() {_x000D_
  var demo = new Vue({_x000D_
    el: '#demo',_x000D_
    data: {_x000D_
      message: 'Hello Vue.js!'_x000D_
    }_x000D_
  })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<div id="demo">_x000D_
  <p>{{message}}</p>_x000D_
  <input v-model="message">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Referencing Row Number in R

Perhaps with dataframes one of the most easy and practical solution is:

data = dplyr::mutate(data, rownum=row_number())

Permutations in JavaScript?

  let permutations = []

  permutate([], {
    color: ['red', 'green'],
    size: ['big', 'small', 'medium'],
    type: ['saison', 'oldtimer']
  })

  function permutate (currentVals, remainingAttrs) {
    remainingAttrs[Object.keys(remainingAttrs)[0]].forEach(attrVal => {
      let currentValsNew = currentVals.slice(0)
      currentValsNew.push(attrVal)

      if (Object.keys(remainingAttrs).length > 1) {
        let remainingAttrsNew = JSON.parse(JSON.stringify(remainingAttrs))
        delete remainingAttrsNew[Object.keys(remainingAttrs)[0]]

        permutate(currentValsNew, remainingAttrsNew)
      } else {
        permutations.push(currentValsNew)
      }
    })
  }

Result:

[ 
  [ 'red', 'big', 'saison' ],
  [ 'red', 'big', 'oldtimer' ],
  [ 'red', 'small', 'saison' ],
  [ 'red', 'small', 'oldtimer' ],
  [ 'red', 'medium', 'saison' ],
  [ 'red', 'medium', 'oldtimer' ],
  [ 'green', 'big', 'saison' ],
  [ 'green', 'big', 'oldtimer' ],
  [ 'green', 'small', 'saison' ],
  [ 'green', 'small', 'oldtimer' ],
  [ 'green', 'medium', 'saison' ],
  [ 'green', 'medium', 'oldtimer' ] 
]

What does auto do in margin:0 auto?

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

0 is for top-bottom and auto for left-right. The browser sets the margin.

Check whether a cell contains a substring

This formula seems more intuitive to me:

=SUBSTITUTE(A1,"SomeText","") <> A1

this returns TRUE if "SomeText" is contained within A1.

The IsNumber/Search and IsError/Find formulas mentioned in the other answers certainly do work, but I always find myself needing to look at the help or experimenting in Excel too often with those ones.

Countdown timer in React

The problem is in your "this" value. Timer function cannot access the "state" prop because run in a different context. I suggest you to do something like this:

...
startTimer = () => {
  let interval = setInterval(this.timer.bind(this), 1000);
  this.setState({ interval });
};

As you can see I've added a "bind" method to your timer function. This allows the timer, when called, to access the same "this" of your react component (This is the primary problem/improvement when working with javascript in general).

Another option is to use another arrow function:

startTimer = () => {
  let interval = setInterval(() => this.timer(), 1000);
  this.setState({ interval });
};

How to check if image exists with given url?

Use the error handler like this:

$('#image_id').error(function() {
  alert('Image does not exist !!');
});

If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:

Update:

I think using:

$.ajax({url:'somefile.dat',type:'HEAD',error:do_something});

would be enough to check for a 404.

More Readings:

Update 2:

Your code should be like this:

$(this).error(function() {
  alert('Image does not exist !!');
});

No need for these lines and that won't check if the remote file exists anyway:

var imgcheck = imgsrc.width;    

if (imgcheck==0) {
  alert("You have a zero size image");
} else { 
  //execute the rest of code here 
}

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

Clone only one branch

--single-branch” switch is your answer, but it only works if you have git version 1.8.X onwards, first check

#git --version 

If you already have git version 1.8.X installed then simply use "-b branch and --single branch" to clone a single branch

#git clone -b branch --single-branch git://github/repository.git

By default in Ubuntu 12.04/12.10/13.10 and Debian 7 the default git installation is for version 1.7.x only, where --single-branch is an unknown switch. In that case you need to install newer git first from a non-default ppa as below.

sudo add-apt-repository ppa:pdoes/ppa
sudo apt-get update
sudo apt-get install git
git --version

Once 1.8.X is installed now simply do:

git clone -b branch --single-branch git://github/repository.git

Git will now only download a single branch from the server.

MYSQL order by both Ascending and Descending sorting

I don't understand what the meaning of ordering with the same column ASC and DESC in the same ORDER BY, but this how you can do it: naam DESC, naam ASC like so:

ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC

Groovy / grails how to determine a data type?

You can use the Membership Operator isCase() which is another groovy way:

assert Date.isCase(new Date())

Unresolved reference issue in PyCharm

I tried everything here twice and even more. I finally solved it doing something I hadn't seen anywhere online. If you go to Settings>Editor>File Types there is an 'Ignore Files and folders' line at the bottom. In my case, I was ignoring 'venv', which is what I always name my virtual environments. So I removed venv; from the list of directories to ignore and VOILA!! I was FINALLY able to fix this problem. Literally all of my import problems were fixed for the project.

BTW, I had installed each and every package using PyCharm, and not through a terminal. (Meaning, by going to Settings>Interpreter...). I had invalidated cache, changed 'Source Root', restarted PyCharm, refreshed my interpreters paths, changed interpreters, deleted my venv... I tried everything. This finally worked. Obviously there are multiple problems going on here with different people, so this may not work for you, but it's definitely worth a shot if nothing else has worked, and easy to reverse if it doesn't.

Adding an image to a PDF using iTextSharp and scale it properly

You can try something like this:

      Image logo = Image.GetInstance("pathToTheImage")
      logo.ScaleAbsolute(500, 300)

Splitting a string into separate variables

Try this:

$Object = 'FirstPart SecondPart' | ConvertFrom-String -PropertyNames Val1, Val2
$Object.Val1
$Object.Val2

Get first key in a (possibly) associative array?

Since PHP 7.3.0 function array_key_first() can be used.

There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill:

<?php
if (!function_exists('array_key_first')) {
    function array_key_first(array $arr) {
        foreach($arr as $key => $unused) {
            return $key;
        }
        return NULL;
    }
}
?>

Auto refresh code in HTML using meta tags

The quotes you use are the issue:

<meta http-equiv=”refresh” content=”5" >

You should use the "

<meta http-equiv="refresh" content="5">

Get Android Device Name

You can see answers at here Get Android Phone Model Programmatically

public String getDeviceName() {
   String manufacturer = Build.MANUFACTURER;
   String model = Build.MODEL;
   if (model.startsWith(manufacturer)) {
      return capitalize(model);
   } else {
      return capitalize(manufacturer) + " " + model;
   }
}


private String capitalize(String s) {
    if (s == null || s.length() == 0) {
        return "";
    }
    char first = s.charAt(0);
    if (Character.isUpperCase(first)) {
        return s;
    } else {
        return Character.toUpperCase(first) + s.substring(1);
    }
}

Can you use @Autowired with static fields?

You can achieve this using XML notation and the MethodInvokingFactoryBean. For an example look here.

private static StaticBean staticBean;

public void setStaticBean(StaticBean staticBean) {
   StaticBean.staticBean = staticBean;
}

You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.

Note testing can also be more difficult with this approach.

log4net hierarchy and logging levels

For most applications you would like to set a minimum level but not a maximum level.

For example, when debugging your code set the minimum level to DEBUG, and in production set it to WARN.

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

You have two options for displaying the Map

  1. Use Maps Library for Android to render the Map
  2. Use Maps API V3 inside a web view

For showing local POIs around a Lat, Long use Places APIs

Defining a variable with or without export

Here's yet another example:

VARTEST="value of VARTEST" 
#export VARTEST="value of VARTEST" 
sudo env | grep -i vartest 
sudo echo ${SUDO_USER} ${SUDO_UID}:${SUDO_GID} "${VARTEST}" 
sudo bash -c 'echo ${SUDO_USER} ${SUDO_UID}:${SUDO_GID} "${VARTEST}"'  

Only by using export VARTEST the value of VARTEST is available in sudo bash -c '...'!

For further examples see:

How to pass multiple arguments in processStartInfo?

For makecert, your startInfo.FileName should be the complete path of makecert (or just makecert.exe if it's in standard path) then the Arguments would be -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer now I'm bit unfamiliar with how certificate store works, but perhaps you'll need to set startInfo.WorkingDirectory if you're referring the .cer files outside the certificate store

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

Removing "http://" from a string

Use look behinds in preg_replace to remove anything before //.

preg_replace('(^[a-z]+:\/\/)', '', $url); 

This will only replace if found in the beginning of the string, and will ignore if found later

PHP - add 1 day to date format mm-dd-yyyy

The format you've used is not recognized by strtotime(). Replace

$date = "04-15-2013";

by

$date = "04/15/2013";

Or if you want to use - then use the following line with the year in front:

$date = "2013-04-15";

Batch command date and time in file name

You can add leading zeroes to a variable (value up to 99) like this in batch: IF 1%Var% LSS 100 SET Var=0%Var%

So you'd need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.

However, your underlying method for parsing date and time is dependent on system locale settings. If you're happy for your code not to be portable to other machines, that's probably fine, but if you expect it to work in different international contexts then you'll need a different approach, for example by reading out the registry settings:

HKEY_CURRENT_USER\Control Panel\International\iDate
HKEY_CURRENT_USER\Control Panel\International\iTime
HKEY_CURRENT_USER\Control Panel\International\iTLZero

(That last one controls whether there is a leading zero on times, but not dates as far as I know).

Python Binomial Coefficient

Your program will continue with the second if statement in the case of y == x, causing a ZeroDivisionError. You need to make the statements mutually exclusive; the way to do that is to use elif ("else if") instead of if:

import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))
if y == x:
    print(1)
elif y == 1:         # see georg's comment
    print(x)
elif y > x:          # will be executed only if y != 1 and y != x
    print(0)
else:                # will be executed only if y != 1 and y != x and x <= y
    a = math.factorial(x)
    b = math.factorial(y)
    c = math.factorial(x-y)  # that appears to be useful to get the correct result
    div = a // (b * c)
    print(div)  

How to print a query string with parameter values when using Hibernate

You can add category lines to log4j.xml:

<category name="org.hibernate.type">
    <priority value="TRACE"/>
</category>

and add hibernate properties:

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

Javascript ajax call on page onload

Or with Prototype:

Event.observe(this, 'load', function() { new Ajax.Request(... ) );

Or better, define the function elsewhere rather than inline, then:

Event.observe(this, 'load', functionName );

You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();").

However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.

How do I clear the std::queue efficiently?

Assuming your m_Queue contains integers:

std::queue<int>().swap(m_Queue)

Otherwise, if it contains e.g. pointers to Job objects, then:

std::queue<Job*>().swap(m_Queue)

This way you swap an empty queue with your m_Queue, thus m_Queue becomes empty.

Why does foo = filter(...) return a <filter object>, not a list?

the reason why it returns < filter object > is that, filter is class instead of built-in function.

help(filter) you will get following: Help on class filter in module builtins:

class filter(object)
 |  filter(function or None, iterable) --> filter object
 |  
 |  Return an iterator yielding those items of iterable for which function(item)
 |  is true. If function is None, return the items that are true.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.

How do I make Git ignore file mode (chmod) changes?

If you want to set filemode to false in config files recursively (including submodules) : find -name config | xargs sed -i -e 's/filemode = true/filemode = false/'

ADB Driver and Windows 8.1

In Windows 7, 8 or 8.1, in Devices Manager:

  1. Select tree 'Android Device': remove 'Android Composite ADB Interface' [?]
  2. Press on main root of devices tree and call context menu (by right mouse click) and click on 'Update configuration'
  3. After updating your device should appear in 'Other devices'
  4. Select your device, call context menu from it and choose 'Update driver' and perform this updating

Store query result in a variable using in PL/pgSQL

You can use the following example to store a query result in a variable using PL/pgSQL:

 select * into demo from maintenanceactivitytrack ; 
    raise notice'p_maintenanceid:%',demo;

C# Lambda expressions: Why should I use them?

Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:

using System;
using System.Linq;
using System.Linq.Expressions;


namespace ExpressionTreeThingy
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
            var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
            Console.WriteLine(del(5)); //we are just invoking a delegate at this point
            Console.ReadKey();
        }
    }
}

This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.

Best way to find if an item is in a JavaScript array?

A robust way to check if an object is an array in javascript is detailed here:

Here are two functions from the xa.js framework which I attach to a utils = {} ‘container’. These should help you properly detect arrays.

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     }
     if (utils.type(obj) === 'array') {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
};

If you then want to check if an object is in an array, I would also include this code:

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

And finally this in_array function:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

Could not find method compile() for arguments Gradle

It should be exclude module: 'net.milkbowl:vault:1.2.27'(add module:) as explained in documentation for DependencyHandler linked from http://www.gradle.org/docs/current/javadoc/org/gradle/api/Project.html#dependencies(groovy.lang.Closure) because ModuleDependency.exclude(java.util.Map) method is used.

How to execute mongo commands through shell scripts?

--shell flag can also be used for javascript files

 mongo --shell /path/to/jsfile/test.js 

PHP isset() with multiple parameters

The parameter(s) to isset() must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:

if (isset($_POST['search_term'], $_POST['postcode'])) {
}

This will return true only if all arguments to isset() are set and do not contain null.

Note that isset($var) and isset($var) == true have the same effect, so the latter is somewhat redundant.

Update

The second part of your expression uses empty() like this:

empty ($_POST['search_term'] . $_POST['postcode']) == false

This is wrong for the same reasons as above. In fact, you don't need empty() here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:

isset($_POST['search_term'], $_POST['postcode']) && 
    $_POST['search_term'] && 
    $_POST['postcode']

Or using an equivalent expression:

!empty($_POST['search_term']) && !empty($_POST['postcode'])

Final thoughts

You should consider using filter functions to manage the inputs:

$data = filter_input_array(INPUT_POST, array(
    'search_term' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
    'postcode' => array(
        'filter' => FILTER_UNSAFE_RAW,
        'flags' => FILTER_NULL_ON_FAILURE,
    ),
));

if ($data === null || in_array(null, $data, true)) {
    // some fields are missing or their values didn't pass the filter
    die("You did something naughty");
}

// $data['search_term'] and $data['postcode'] contains the fields you want

Btw, you can customize your filters to check for various parts of the submitted values.

Access mysql remote database from command line

edit my.cnf file:

vi /etc/my.cnf:

make sure that:

bind-address=YOUR-SERVER-IP

and if you have the line:

skip-networking

make sure to comment it:

#skip-networking

don't forget to restart:

/etc/init.d/mysqld restart

Converting int to bytes in Python 3

Python 3.5+ introduces %-interpolation (printf-style formatting) for bytes:

>>> b'%d\r\n' % 3
b'3\r\n'

See PEP 0461 -- Adding % formatting to bytes and bytearray.

On earlier versions, you could use str and .encode('ascii') the result:

>>> s = '%d\r\n' % 3
>>> s.encode('ascii')
b'3\r\n'

Note: It is different from what int.to_bytes produces:

>>> n = 3
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x03'
>>> b'3' == b'\x33' != '\x03'
True

Load Image from javascript

this worked for me though... i wanted to display the image after the pencil icon is being clicked... and i wanted it seamless.. and this was my approach..

pencil button to display image

i created an input[file] element and made it hidden,

<input type="file" id="upl" style="display:none"/>

this input-file's click event will be trigged by the getImage function.

<a href="javascript:;" onclick="getImage()"/>
    <img src="/assets/pen.png"/>
</a>

<script>
     function getImage(){
       $('#upl').click();
     }
</script>

this is done while listening to the change event of the input-file element with ID of #upl.

_x000D_
_x000D_
   $(document).ready(function(){_x000D_
     _x000D_
       $('#upl').bind('change', function(evt){_x000D_
         _x000D_
    var preview = $('#logodiv').find('img');_x000D_
    var file    = evt.target.files[0];_x000D_
    var reader  = new FileReader();_x000D_
  _x000D_
    reader.onloadend = function () {_x000D_
   $('#logodiv > img')_x000D_
    .prop('src',reader.result)  //set the scr prop._x000D_
    .prop('width', 216);  //set the width of the image_x000D_
    .prop('height',200);  //set the height of the image_x000D_
    }_x000D_
  _x000D_
    if (file) {_x000D_
   reader.readAsDataURL(file);_x000D_
    } else {_x000D_
   preview.src = "";_x000D_
    }_x000D_
  _x000D_
    });_x000D_
_x000D_
   })
_x000D_
_x000D_
_x000D_

and BOOM!!! - it WORKS....

No mapping found for HTTP request with URI Spring MVC

With the web.xml configured they way you have in the question, in particular:

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

ALL requests being made to your web app will be directed to the DispatcherServlet. This includes requests like /tasklist/, /tasklist/some-thing.html, /tasklist/WEB-INF/views/index.jsp.

Because of this, when your controller returns a view that points to a .jsp, instead of allowing your server container to service the request, the DispatcherServlet jumps in and starts looking for a controller that can service this request, it doesn't find any and hence the 404.

The simplest way to solve is to have your servlet url mapping as follows:

<servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Notice the missing *. This tells the container that any request that does not have a path info in it (urls without a .xxx at the end), should be sent to the DispatcherServlet. With this configuration, when a xxx.jsp request is received, the DispatcherServlet is not consulted, and your servlet container's default servlet will service the request and present the jsp as expected.

Hope this helps, I realize your earlier comments state that the problem has been resolved, but the solution CAN NOT be just adding method=RequestMethod.GET to the RequestMethod.

Best implementation for hashCode method for a collection

It is better to use the functionality provided by Eclipse which does a pretty good job and you can put your efforts and energy in developing the business logic.

Get size of folder or file

The File object has a length method:

f = new File("your/file/name");
f.length();

Failed to build gem native extension (installing Compass)

when

gem install overcommit

is run also this error have been placed in terminal.

Failed to build gem native extension

please do the same

xcode-select --install

and it will fix that issue too

Check file uploaded is in csv format

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
  // do something
} else {
  die("Sorry, mime type not allowed");
}

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.

Git ignore file for Xcode projects

Best of all,

gitignore.io

Go and choose your language, and then it'll give you the file.

Are PostgreSQL column names case-sensitive?

if use JPA I recommend change to lowercase schema, table and column names, you can use next intructions for help you:

select
    psat.schemaname,
    psat.relname,
    pa.attname,
    psat.relid
from
    pg_catalog.pg_stat_all_tables psat,
    pg_catalog.pg_attribute pa
where
    psat.relid = pa.attrelid

change schema name:

ALTER SCHEMA "XXXXX" RENAME TO xxxxx;

change table names:

ALTER TABLE xxxxx."AAAAA" RENAME TO aaaaa;

change column names:

ALTER TABLE xxxxx.aaaaa RENAME COLUMN "CCCCC" TO ccccc;

dropdownlist set selected value in MVC3 Razor

code bellow, get from, goes

Controller:

int DefaultId = 1;
ViewBag.Person = db.XXXX
        .ToList()
        .Select(x => new SelectListItem {
            Value = x.Id.ToString(),
            Text = x.Name,
            Selected = (x.Id == DefaultId)
        });

View:

@Html.DropDownList("Person")

Note: ViewBag.Person and @Html.DropDownList("Person") name should be as in view model

How to get first two characters of a string in oracle query?

SUBSTR (documentation):

SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName from shipment

When selected, it's like any other column. You should give it a name (with As keyword), and you can selected other columns in the same statement:

SELECT SUBSTR(OrderNo, 1, 2) As NewColumnName, column2, ... from shipment

Calling startActivity() from outside of an Activity context

For anybody getting this on Xamarin.Android (MonoDroid) even when StartActivity is called from activity - this is actually Xamarin bug with new ART runtime, see https://bugzilla.xamarin.com/show_bug.cgi?id=17630

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I want to correct little bit the above code

    public class MainActivity extends ActionBarActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,  mDrawerLayout, mToolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

and all the other things will remain same...

For those who are having problem Drawerlayout overlaying toolbar

add android:layout_marginTop="?attr/actionBarSize" to root layout of drawer content

Changing tab bar item image and text color iOS

You may also do by this way:

override func viewWillLayoutSubviews() {  
  if let items = self.tabBar.items {
    for item in 0..<items.count {
      items[item].image = items[item].image?.withRenderingMode(.alwaysOriginal)
            items[item].selectedImage = items[item].selectedImage?.withRenderingMode(.alwaysTemplate)
    }

Optional:

 UITabBar.appearance().tintColor = UIColor.red

I hope it will help you.

How to filter in NaN (pandas)?

Simplest of all solutions:

filtered_df = df[df['var2'].isnull()]

This filters and gives you rows which has only NaN values in 'var2' column.

Using two CSS classes on one element

If you want to apply styles only to an element which is its parents' first child, is it better to use :first-child pseudo-class

.social:first-child{
    border-bottom: dotted 1px #6d6d6d;
    padding-top: 0;
}
.social{
    border: 0;
    width: 330px;
    height: 75px;
    float: right;
    text-align: left;
    padding: 10px 0;
}

Then, the rule .social has both common styles and the last element's styles.

And .social:first-child overrides them with first element's styles.

You could also use :last-child selector, but :first-childis more supported by old browsers: see https://developer.mozilla.org/en-US/docs/CSS/:first-child#Browser_compatibility and https://developer.mozilla.org/es/docs/CSS/:last-child#Browser_compatibility.

Uncaught TypeError: Cannot read property 'top' of undefined

Your document does not contain any element with class content-nav, thus the method .offset() returns undefined which indeed has no top property.

You can see for yourself in this fiddle

alert($('.content-nav').offset());

(you will see "undefined")

To avoid crashing the whole code, you can have such code instead:

var top = ($('.content-nav').offset() || { "top": NaN }).top;
if (isNaN(top)) {
    alert("something is wrong, no top");
} else {
    alert(top);
}

Updated fiddle.

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

Declare variable in SQLite and use it

SQLite doesn't support native variable syntax, but you can achieve virtually the same using an in-memory temp table.

I've used the below approach for large projects and works like a charm.

/* Create in-memory temp table for variables */
BEGIN;

PRAGMA temp_store = 2;
CREATE TEMP TABLE _Variables(Name TEXT PRIMARY KEY, RealValue REAL, IntegerValue INTEGER, BlobValue BLOB, TextValue TEXT);

/* Declaring a variable */
INSERT INTO _Variables (Name) VALUES ('VariableName');

/* Assigning a variable (pick the right storage class) */
UPDATE _Variables SET IntegerValue = ... WHERE Name = 'VariableName';

/* Getting variable value (use within expression) */
... (SELECT coalesce(RealValue, IntegerValue, BlobValue, TextValue) FROM _Variables WHERE Name = 'VariableName' LIMIT 1) ...

DROP TABLE _Variables;
END;

How to truncate float values?

round(1.923328437452, 3)

See Python's documentation on the standard types. You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to.

Post Build exited with code 1

I had to run VS as Administrator to get my post-build copy to an OS protected "..\Common7\IDE\PrivateAssemblies" to work

Creating a BLOB from a Base64 string in JavaScript

The atob function will decode a Base64-encoded string into a new string with a character for each byte of the binary data.

const byteCharacters = atob(b64Data);

Each character's code point (charCode) will be the value of the byte. We can create an array of byte values by applying this using the .charCodeAt method for each character in the string.

const byteNumbers = new Array(byteCharacters.length);
for (let i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
}

You can convert this array of byte values into a real typed byte array by passing it to the Uint8Array constructor.

const byteArray = new Uint8Array(byteNumbers);

This in turn can be converted to a BLOB by wrapping it in an array and passing it to the Blob constructor.

const blob = new Blob([byteArray], {type: contentType});

The code above works. However the performance can be improved a little by processing the byteCharacters in smaller slices, rather than all at once. In my rough testing 512 bytes seems to be a good slice size. This gives us the following function.

const b64toBlob = (b64Data, contentType='', sliceSize=512) => {
  const byteCharacters = atob(b64Data);
  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);
    for (let i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i);
    }

    const byteArray = new Uint8Array(byteNumbers);
    byteArrays.push(byteArray);
  }

  const blob = new Blob(byteArrays, {type: contentType});
  return blob;
}
const blob = b64toBlob(b64Data, contentType);
const blobUrl = URL.createObjectURL(blob);

window.location = blobUrl;

Full Example:

_x000D_
_x000D_
const b64toBlob = (b64Data, contentType='', sliceSize=512) => {_x000D_
  const byteCharacters = atob(b64Data);_x000D_
  const byteArrays = [];_x000D_
_x000D_
  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {_x000D_
    const slice = byteCharacters.slice(offset, offset + sliceSize);_x000D_
_x000D_
    const byteNumbers = new Array(slice.length);_x000D_
    for (let i = 0; i < slice.length; i++) {_x000D_
      byteNumbers[i] = slice.charCodeAt(i);_x000D_
    }_x000D_
_x000D_
    const byteArray = new Uint8Array(byteNumbers);_x000D_
    byteArrays.push(byteArray);_x000D_
  }_x000D_
_x000D_
  const blob = new Blob(byteArrays, {type: contentType});_x000D_
  return blob;_x000D_
}_x000D_
_x000D_
const contentType = 'image/png';_x000D_
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
const blob = b64toBlob(b64Data, contentType);_x000D_
const blobUrl = URL.createObjectURL(blob);_x000D_
_x000D_
const img = document.createElement('img');_x000D_
img.src = blobUrl;_x000D_
document.body.appendChild(img);
_x000D_
_x000D_
_x000D_

ojdbc14.jar vs. ojdbc6.jar

I have same problem!

Found following in oracle site link text

As mentioned above, the 11.1 drivers by default convert SQL DATE to Timestamp when reading from the database. This always was the right thing to do and the change in 9i was a mistake. The 11.1 drivers have reverted to the correct behavior. Even if you didn't set V8Compatible in your application you shouldn't see any difference in behavior in most cases. You may notice a difference if you use getObject to read a DATE column. The result will be a Timestamp rather than a Date. Since Timestamp is a subclass of Date this generally isn't a problem. Where you might notice a difference is if you relied on the conversion from DATE to Date to truncate the time component or if you do toString on the value. Otherwise the change should be transparent.

If for some reason your app is very sensitive to this change and you simply must have the 9i-10g behavior, there is a connection property you can set. Set mapDateToTimestamp to false and the driver will revert to the default 9i-10g behavior and map DATE to Date.

How do you properly use namespaces in C++?

To avoid saying everything Mark Ingram already said a little tip for using namespaces:

Avoid the "using namespace" directive in header files - this opens the namespace for all parts of the program which import this header file. In implementation files (*.cpp) this is normally no big problem - altough I prefer to use the "using namespace" directive on the function level.

I think namespaces are mostly used to avoid naming conflicts - not necessarily to organize your code structure. I'd organize C++ programs mainly with header files / the file structure.

Sometimes namespaces are used in bigger C++ projects to hide implementation details.

Additional note to the using directive: Some people prefer using "using" just for single elements:

using std::cout;  
using std::endl;

matplotlib colorbar in each subplot

Specify the ax argument to matplotlib.pyplot.colorbar(), e.g.

import numpy as np
import matplotlib.pyplot as plt

fig, ax = plt.subplots(2, 2)
for i in range(2):
    for j in range(2):
         data = np.array([[i, j], [i+0.5, j+0.5]])
         im = ax[i, j].imshow(data)
         plt.colorbar(im, ax=ax[i, j])

plt.show()

enter image description here

How to resize Twitter Bootstrap modal dynamically based on the content

My search led me here so might as well add my two cents worth of idea. If you are using Monkey friendly Twitter Bootstrap modal then you can do something like this:

    var dialog = new BootstrapDialog({
        id: 'myDialog',
        title: 'Title',
        closable: false,
        // whatever you like configuration here...
    });

    dialog.realize();
    if (isContentAYoutubeVideo()) {
        dialog.getModalDialog().css('width', '80%'); // set the width to whatever you like
    }
    dialog.open();

Hope this helps.

Floating elements within a div, floats outside of div. Why?

As Lucas says, what you are describing is the intended behaviour for the float property. What confuses many people is that float has been pushed well beyond its original intended usage in order to make up for shortcomings in the CSS layout model.

Have a look at Floatutorial if you'd like to get a better understanding of how this property works.

Java: How to convert List to Map

With , you'll be able to do this in one line using streams, and the Collectors class.

Map<String, Item> map = 
    list.stream().collect(Collectors.toMap(Item::getKey, item -> item));

Short demo:

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Test{
    public static void main (String [] args){
        List<Item> list = IntStream.rangeClosed(1, 4)
                                   .mapToObj(Item::new)
                                   .collect(Collectors.toList()); //[Item [i=1], Item [i=2], Item [i=3], Item [i=4]]

        Map<String, Item> map = 
            list.stream().collect(Collectors.toMap(Item::getKey, item -> item));

        map.forEach((k, v) -> System.out.println(k + " => " + v));
    }
}
class Item {

    private final int i;

    public Item(int i){
        this.i = i;
    }

    public String getKey(){
        return "Key-"+i;
    }

    @Override
    public String toString() {
        return "Item [i=" + i + "]";
    }
}

Output:

Key-1 => Item [i=1]
Key-2 => Item [i=2]
Key-3 => Item [i=3]
Key-4 => Item [i=4]

As noted in comments, you can use Function.identity() instead of item -> item, although I find i -> i rather explicit.

And to be complete note that you can use a binary operator if your function is not bijective. For example let's consider this List and the mapping function that for an int value, compute the result of it modulo 3:

List<Integer> intList = Arrays.asList(1, 2, 3, 4, 5, 6);
Map<String, Integer> map = 
    intList.stream().collect(toMap(i -> String.valueOf(i % 3), i -> i));

When running this code, you'll get an error saying java.lang.IllegalStateException: Duplicate key 1. This is because 1 % 3 is the same as 4 % 3 and hence have the same key value given the key mapping function. In this case you can provide a merge operator.

Here's one that sum the values; (i1, i2) -> i1 + i2; that can be replaced with the method reference Integer::sum.

Map<String, Integer> map = 
    intList.stream().collect(toMap(i -> String.valueOf(i % 3), 
                                   i -> i, 
                                   Integer::sum));

which now outputs:

0 => 9 (i.e 3 + 6)
1 => 5 (i.e 1 + 4)
2 => 7 (i.e 2 + 5)

Hope it helps! :)

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

What's the difference between HEAD^ and HEAD~ in Git?

TLDR

~ is what you want most of the time, it references past commits to the current branch

^ references parents (git-merge creates a 2nd parent or more)

A~ is always the same as A^
A~~ is always the same as A^^, and so on
A~2 is not the same as A^2 however,
because ~2 is shorthand for ~~
while ^2 is not shorthand for anything, it means the 2nd parent

invalid types 'int[int]' for array subscript

You're trying to access a 3 dimensional array with 4 de-references

You only need 3 loops instead of 4, or int myArray[10][10][10][10];

Can you call Directory.GetFiles() with multiple filters?

i don t know what solution is better, but i use this:

String[] ext = "*.ext1|*.ext2".Split('|');

            List<String> files = new List<String>();
            foreach (String tmp in ext)
            {
                files.AddRange(Directory.GetFiles(dir, tmp, SearchOption.AllDirectories));
            }

Jinja2 template variable if None Object set a default value

As addition to other answers, one can write something else if variable is None like this:

{{ variable or '' }}

Get page title with Selenium WebDriver using Java

You can do it easily by Assertion using Selenium Testng framework.

Steps:

1.Create Firefox browser session

2.Initialize expected title name.

3.Navigate to "www.google.com" [As per you requirement, you can change] and wait for some time (15 seconds) to load the page completely.

4.Get the actual title name using "driver.getTitle()" and store it in String variable.

5.Apply the Assertion like below, Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle ),"Page title name not matched or Problem in loading grid");

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.myapplication.Utilty;

public class PageTitleVerification
{   
private static WebDriver driver = new FirefoxDriver();

@Test
public void test01_GooglePageTitleVerify()
{               
driver.navigate().to("https://www.google.com/");
String expectedGooglePageTitle = "Google";      
Utility.waitForElementInDOM(driver, "Google Search", 15);   
//Get page title
String actualGooglePageTitlte=driver.getTitle();
System.out.println("Google page title" + actualGooglePageTitlte);   
//Verify expected page title and actual page title is same  
Assert.assertTrue(actualGooglePageTitlte.equalsIgnoreCase(expectedGooglePageTitle 
),"Page title not matched or Problem in loading url page");     
}
}

import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class Utility {

/*Wait for an element to be present in DOM before specified time (in seconds ) has 
elapsed */
public static void waitForElementInDOM(WebDriver driver,String elementIdentifier, 
long timeOutInSeconds) 
{       
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds );
try
{
//this will wait for element to be visible for 15 seconds        
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath
(elementIdentifier))); 
}
catch(NoSuchElementException e)
{           
e.printStackTrace();
}           
}
}

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

Check if a process is running or not on Windows with Python

import psutil

for p in psutil.process_iter(attrs=['pid', 'name']):
    if "itunes.exe" in (p.info['name']).lower():
        print("yes", (p.info['name']).lower())

for python 3.7


import psutil

for p in psutil.process_iter(attrs=['pid', 'name']):
    if p.info['name'] == "itunes.exe":
        print("yes", (p.info['name']))

This works for python 3.8 & psutil 5.7.0, windows

How to append a newline to StringBuilder

In addition to K.S's response of creating a StringBuilderPlus class and utilising ther adapter pattern to extend a final class, if you make use of generics and return the StringBuilderPlus object in the new append and appendLine methods, you can make use of the StringBuilders many append methods for all different types, while regaining the ability to string string multiple append commands together, as shown below

public class StringBuilderPlus {

    private final StringBuilder stringBuilder;

    public StringBuilderPlus() {
        this.stringBuilder = new StringBuilder();
    }

    public <T> StringBuilderPlus append(T t) {
        stringBuilder.append(t);
        return this;
    }

    public <T> StringBuilderPlus appendLine(T t) {
        stringBuilder.append(t).append(System.lineSeparator());
        return this;
    }

    @Override
    public String toString() {
        return stringBuilder.toString();
    }

    public StringBuilder getStringBuilder() {
        return stringBuilder;
    }
}

you can then use this exactly like the original StringBuilder class:

StringBuilderPlus stringBuilder = new StringBuilderPlus();
stringBuilder.appendLine("test")
    .appendLine('c')
    .appendLine(1)
    .appendLine(1.2)
    .appendLine(1L);

stringBuilder.toString();

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

If you are not using Conda but vanilla Python, 'brew install graphviz' works.

Symbol for any number of any characters in regex?

You can use this regular expression (any whitespace or any non-whitespace) as many times as possible down to and including 0.

[\s\S]*

This expression will match as few as possible, but as many as necessary for the rest of the expression.

[\s\S]*?

For example, in this regex [\s\S]*?B will match aB in aBaaaaB. But in this regex [\s\S]*B will match aBaaaaB in aBaaaaB.

How to return a class object by reference in C++?

Well, it is maybe not a really beautiful solution in the code, but it is really beautiful in the interface of your function. And it is also very efficient. It is ideal if the second is more important for you (for example, you are developing a library).

The trick is this:

  1. A line A a = b.make(); is internally converted to a constructor of A, i.e. as if you had written A a(b.make());.
  2. Now b.make() should result a new class, with a callback function.
  3. This whole thing can be fine handled only by classes, without any template.

Here is my minimal example. Check only the main(), as you can see it is simple. The internals aren't.

From the viewpoint of the speed: the size of a Factory::Mediator class is only 2 pointers, which is more that 1 but not more. And this is the only object in the whole thing which is transferred by value.

#include <stdio.h>

class Factory {
  public:
    class Mediator;

    class Result {
      public:
        Result() {
          printf ("Factory::Result::Result()\n");
        };

        Result(Mediator fm) {
          printf ("Factory::Result::Result(Mediator)\n");
          fm.call(this);
        };
    };

    typedef void (*MakeMethod)(Factory* factory, Result* result);

    class Mediator {
      private:
        Factory* factory;
        MakeMethod makeMethod;

      public:
        Mediator(Factory* factory, MakeMethod makeMethod) {
          printf ("Factory::Mediator::Mediator(Factory*, MakeMethod)\n");
          this->factory = factory;
          this->makeMethod = makeMethod;
        };

        void call(Result* result) {
          printf ("Factory::Mediator::call(Result*)\n");
          (*makeMethod)(factory, result);
        };
    };
};

class A;

class B : private Factory {
  private:
    int v;

  public:
    B(int v) {
      printf ("B::B()\n");
      this->v = v;
    };

    int getV() const {
      printf ("B::getV()\n");
      return v;
    };

    static void makeCb(Factory* f, Factory::Result* a);

    Factory::Mediator make() {
      printf ("Factory::Mediator B::make()\n");
      return Factory::Mediator(static_cast<Factory*>(this), &B::makeCb);
    };
};

class A : private Factory::Result {
  friend class B;

  private:
    int v;

  public:
    A() {
      printf ("A::A()\n");
      v = 0;
    };

    A(Factory::Mediator fm) : Factory::Result(fm) {
      printf ("A::A(Factory::Mediator)\n");
    };

    int getV() const {
      printf ("A::getV()\n");
      return v;
    };

    void setV(int v) {
      printf ("A::setV(%i)\n", v);
      this->v = v;
    };
};

void B::makeCb(Factory* f, Factory::Result* r) {
      printf ("B::makeCb(Factory*, Factory::Result*)\n");
      B* b = static_cast<B*>(f);
      A* a = static_cast<A*>(r);
      a->setV(b->getV()+1);
    };

int main(int argc, char **argv) {
  B b(42);
  A a = b.make();
  printf ("a.v = %i\n", a.getV());
  return 0;
}

How to set or change the default Java (JDK) version on OS X?

Previously I used alias'es in .zshrc for easy switching between versions but today I use SDKMAN. SDKMAN can also handle setting default java for the system, and downloading and installing new java versions.

Once sdkman is installed you can then do commands similar to what is possible with the nvm tool for handling node versions.

sdk list java will list the java versions available on your system as well as available online for installation including their identifier that you can use in the sdk use, sdk default and sdk install commands.

e.g. to install Amazon Corretto 11.0.8 and ask if it should be the new default do this: sdk install java 11.0.8-amzn

A feature I also use regularly is the .sdkmanrc file. If you place that in a directory on your machine and run the sdk env command in the directory then you can configure tool versions used only in that directory. It is also possible to make sdkman switch tool versions automatically using the sdkman_auto_env=true configuration.

sdkman also supports handling other tools for the JVM such as gradle, kotlin, maven and more.

For more information check out https://sdkman.io/usage#env

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

I had the same issue on the Linux server I was working on. Connecting java to a X11 display worked on the head node, but not on any other. After contacting the administrator, it turned out that the current version of our job-scheduling system (SLURM) did not support X11 forwarding. They had to update SLURM (newer versions of SLURM support it) for it to work.

Global variables in header file

You should not define global variables in header files. You can declare them as extern in header file and define them in a .c source file.

(Note: In C, int i; is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)

TypeScript typed array usage

You have an error in your syntax here:

this._possessions = new Thing[100]();

This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:

this._possessions = [];

Of the array constructor if you want to set the length:

this._possessions = new Array(100);

I have created a brief working example you can try in the playground.

module Entities {  

    class Thing {

    }        

    export class Person {
        private _name: string;
        private _possessions: Thing[];
        private _mostPrecious: Thing;

        constructor (name: string) {
            this._name = name;
            this._possessions = [];
            this._possessions.push(new Thing())
            this._possessions[100] = new Thing();
        }
    }
}

How to make Google Fonts work in IE?

Google Fonts uses Web Open Font Format (WOFF), which is good, because it's the recommended font format by the W3C.

IE versions older than IE9 don't support Web Open Font Format (WOFF) because it didn't exist back then. To support < IE9, you need to serve your font in Embedded Open Type (EOT). To do this you will need to write your own @font-face css tag instead of using the embed script from Google. Also you need to convert the original WOFF file to EOT.

You can convert your WOFF to EOT over here by first converting it to TTF and then to EOT: http://convertfonts.com/

Then you can serve the EOT font like this:

@font-face {
    font-family: 'MyFont';
    src: url('myfont.eot');
}

Now it works in < IE9. However, modern browsers don't support EOT anymore, so now your fonts won't work in modern browsers. So you need to specify them both. The src property supports this by comma seperating the font urls and specefying the type:

src: url('myfont.woff') format('woff'),
     url('myfont.eot') format('embedded-opentype');

However, < IE9 doesn't understand this, it just graps the text between the first quote and the last quote, so it will actually get:

myfont.woff') format('woff'),
url('myfont.eot') format('embedded-opentype

as the URL to the font. We can fix this by first specifying a src with only one url which is the EOT format, then specifying a second src property that's meant for the modern browsers and < IE9 will not understand. Because < IE9 will not understand it it will ignore the tag so the EOT will still be working. The modern browsers will use the last specified font they support, so probably WOFF.

src: url('myfont.eot');
src: url('myfont.woff') format('woff');

So only because in the second src property you specify the format('woff'), < IE9 won't understand it (or actually it just can't find the font at the url myfont.woff') format('woff) and will keep using the first specified one (eot).

So now you got your Google Webfonts working for < IE9 and modern browsers!

For more information about different font type and browser support, read this perfect article by Alex Tatiyants: http://tatiyants.com/how-to-get-ie8-to-support-html5-tags-and-web-fonts/

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I updated my package and even reinstalled it - but I was still getting the exact same error as the OP mentioned. I manually edited the referenced dll by doing the following.

I removed the newtonsoft.json.dll from my reference, then manually deleted the .dll from the bin directoy. Then i manually copied the newtonsoft.json.dll from the nuget package folder into the project bin, then added the reference by browsing to the .dll file.

Now my project builds again.

Meaning of .Cells(.Rows.Count,"A").End(xlUp).row

The first part:

.Cells(.Rows.Count,"A")

Sends you to the bottom row of column A, which you knew already.

The End function starts at a cell and then, depending on the direction you tell it, goes that direction until it reaches the edge of a group of cells that have text. Meaning, if you have text in cells C4:E4 and you type:

Sheet1.Cells(4,"C").End(xlToRight).Select

The program will select E4, the rightmost cell with text in it.

In your case, the code is spitting out the row of the very last cell with text in it in column A. Does that help?

TypeError: 'builtin_function_or_method' object is not subscriptable

Looks like you typed brackets instead of parenthesis by mistake.

Test if string begins with a string?

Judging by the declaration and description of the startsWith Java function, the "most straight forward way" to implement it in VBA would either be with Left:

Public Function startsWith(str As String, prefix As String) As Boolean
    startsWith = Left(str, Len(prefix)) = prefix
End Function

Or, if you want to have the offset parameter available, with Mid:

Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
    startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function

Populate data table from data reader

As Sagi stated in their answer DataTable.Load is a good solution. If you are trying to load multiple tables from a single reader you do not need to call DataReader.NextResult. The DataTable.Load method also advances the reader to the next result set (if any).

// Read every result set in the data reader.
while (!reader.IsClosed)
{
    DataTable dt = new DataTable();
    // DataTable.Load automatically advances the reader to the next result set
    dt.Load(reader);
    items.Add(dt);
}

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

ESLint not working in VS Code?

In my case, it wasn't working because I had added only one folder of the monorepo to the project, even though I had the package.json and the extension configured. I worked only when I added the whole project (which contained the package.json file) to the VS Code.

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

Read Session Id using Javascript

you can probably ping the server via ajax inside javascript. The php file might look something like:

<?php
session_start();
$id = session_id();
echo $id;
?>

This will return you the current session id. Was this what you were looking for.

jQuery: click function exclude children.

To do this, stop the click on the child using .stopPropagation:

$(".example").click(function(){
  $(this).fadeOut("fast");
}).children().click(function(e) {
  return false;
});

This will stop the child clicks from bubbling up past their level so the parent won't receive the click.

.not() is used a bit differently, it filters elements out of your selector, for example:

<div class="bob" id="myID"></div>
<div class="bob"></div>

$(".bob").not("#myID"); //removes the element with myID

For clicking, your problem is that the click on a child bubbles up to the parent, not that you've inadvertently attached a click handler to the child.

Creating and appending text to txt file in VB.NET

Try it this way:

Dim filePath As String = 
  String.Format("C:\ErrorLog_{0}.txt", DateTime.Today.ToString("dd-MMM-yyyy"))

if File.Exists(filePath) then

Using writer As New StreamWriter(filePath, True)
writer.WriteLine("Error Message in  Occured at-- " & DateTime.Now)

Else
writer.WriteLine("Start Error Log for today")
End Using

end if

How to set root password to null

I noticed a few of these solutions above are now deprecated.

To set an empty password simply follow these steps:

mysql -u root -p

use mysql

SET PASSWORD FOR 'root'@'localhost' = '';

\q (to quit)

now run: mysql -u root

You should be able to start mysql up without a password now.

Python read-only property

someone mentioned using a proxy object, I didn't see an example of that so I ended up trying it out, [poorly].

/!\ Please prefer class definitions and class constructors if possible

this code is effectively re-writing class.__new__ (class constructor) except worse in every way. Save yourself the pain and do not use this pattern if you can.

def attr_proxy(obj):
    """ Use dynamic class definition to bind obj and proxy_attrs.
        If you can extend the target class constructor that is 
        cleaner, but its not always trivial to do so.
    """
    proxy_attrs = dict()

    class MyObjAttrProxy():
        def __getattr__(self, name):
            if name in proxy_attrs:
                return proxy_attrs[name]  # overloaded

            return getattr(obj, name)  # proxy

        def __setattr__(self, name, value):
            """ note, self is not bound when overloading methods
            """
            proxy_attrs[name] = value

    return MyObjAttrProxy()


myobj = attr_proxy(Object())
setattr(myobj, 'foo_str', 'foo')

def func_bind_obj_as_self(func, self):
    def _method(*args, **kwargs):
        return func(self, *args, **kwargs)
    return _method

def mymethod(self, foo_ct):
    """ self is not bound because we aren't using object __new__
        you can write the __setattr__ method to bind a self 
        argument, or declare your functions dynamically to bind in 
        a static object reference.
    """
    return self.foo_str + foo_ct

setattr(myobj, 'foo', func_bind_obj_as_self(mymethod, myobj))

Get generic type of java.util.List

Expanding on Steve K's answer:

/** 
* Performs a forced cast.  
* Returns null if the collection type does not match the items in the list.
* @param data The list to cast.
* @param listType The type of list to cast to.
*/
static <T> List<? super T> castListSafe(List<?> data, Class<T> listType){
    List<T> retval = null;
    //This test could be skipped if you trust the callers, but it wouldn't be safe then.
    if(data!=null && !data.isEmpty() && listType.isInstance(data.iterator().next().getClass())) {
        @SuppressWarnings("unchecked")//It's OK, we know List<T> contains the expected type.
        List<T> foo = (List<T>)data;
        return retval;
    }
    return retval;
}
Usage:

protected WhateverClass add(List<?> data) {//For fluant useage
    if(data==null) || data.isEmpty(){
       throw new IllegalArgumentException("add() " + data==null?"null":"empty" 
       + " collection");
    }
    Class<?> colType = data.iterator().next().getClass();//Something
    aMethod(castListSafe(data, colType));
}

aMethod(List<Foo> foo){
   for(Foo foo: List){
      System.out.println(Foo);
   }
}

aMethod(List<Bar> bar){
   for(Bar bar: List){
      System.out.println(Bar);
   }
}

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

How do I get an OAuth 2.0 authentication token in C#

In Postman, click Generate Code and then in Generate Code Snippets dialog you can select a different coding language, including C# (RestSharp).

Also, you should only need the access token URL. The form parameters are then:

grant_type=client_credentials
client_id=abc    
client_secret=123

Code Snippet:

/* using RestSharp; // https://www.nuget.org/packages/RestSharp/ */

var client = new RestClient("https://service.endpoint.com/api/oauth2/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=client_credentials&client_id=abc&client_secret=123", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

From the response body you can then obtain your access token. For instance for a Bearer token type you can then add the following header to subsequent authenticated requests:

request.AddHeader("authorization", "Bearer <access_token>");

Set value to an entire column of a pandas dataframe

df.loc[:,'industry'] = 'yyy'

This does the magic. You are to add '.loc' with ':' for all rows. Hope it helps

Disabling of EditText in Android

Using android:editable="false" is Depracted. Instead you'll need to Use android:focusable="false"

Is it a good idea to index datetime field in mysql?

MySQL recommends using indexes for a variety of reasons including elimination of rows between conditions: http://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html

This makes your datetime column an excellent candidate for an index if you are going to be using it in conditions frequently in queries. If your only condition is BETWEEN NOW() AND DATE_ADD(NOW(), INTERVAL 30 DAY) and you have no other index in the condition, MySQL will have to do a full table scan on every query. I'm not sure how many rows are generated in 30 days, but as long as it's less than about 1/3 of the total rows it will be more efficient to use an index on the column.

Your question about creating an efficient database is very broad. I'd say to just make sure that it's normalized and all appropriate columns are indexed (i.e. ones used in joins and where clauses).

Access to the requested object is only available from the local network phpmyadmin

I newer version of xampp you may use another method first open your httpd-xampp.conf file and find the string "phpmyadmin" using ctrl+F command (Windows). and then replace this code

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require local
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

with this

Alias /phpmyadmin "D:/server/phpMyAdmin/"
<Directory "D:/server/phpMyAdmin">
    AllowOverride AuthConfig
    Require all granted
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</Directory>

Don't Forget to Restart your Xampp.

How to get browser width using JavaScript code?

An important addition to Travis' answer; you need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth(). What i did ;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
</body>

and call aWidth variable anywhere afterwards.

Call fragment from fragment

I think now Fragment nesting is available just update the back computability jar

now lets dig in the problem it self .

public void onClick2(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment1, fragment2);
    fragmentTransaction.commit();
}

I think the R.id.fragment1 belongs to a TextView which is not a good place to include child views in because its not a ViewGroup, you can remove the textView from the xml and replace it with a LinearLayout lets say and it will work , if not tell me what the error .

fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f0f0"
android:orientation="vertical" >

<LinearLayout 
    android:id="@+id/fragment1"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    />

<Button 
    android:id="@+id/btn_frag2"
    android:text="Call Fragment 2"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
</LinearLayout>

Update for the error in the comment

public class Fragment1 extends Fragment implements OnClickListener{

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment1, container, false);
((Button) v.findViewById(R.id.btn_frag2)).setOnClickListener(this);
    return v;
}

public void onClick(View view) {
    Fragment2 fragment2 = new Fragment2();
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction =        fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, fragment2);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

}

How to perform update operations on columns of type JSONB in Postgres 9.4

Ideally, you don't use JSON documents for structured, regular data that you want to manipulate inside a relational database. Use a normalized relational design instead.

JSON is primarily intended to store whole documents that do not need to be manipulated inside the RDBMS. Related:

Updating a row in Postgres always writes a new version of the whole row. That's the basic principle of Postgres' MVCC model. From a performance perspective, it hardly matters whether you change a single piece of data inside a JSON object or all of it: a new version of the row has to be written.

Thus the advice in the manual:

JSON data is subject to the same concurrency-control considerations as any other data type when stored in a table. Although storing large documents is practicable, keep in mind that any update acquires a row-level lock on the whole row. Consider limiting JSON documents to a manageable size in order to decrease lock contention among updating transactions. Ideally, JSON documents should each represent an atomic datum that business rules dictate cannot reasonably be further subdivided into smaller datums that could be modified independently.

The gist of it: to modify anything inside a JSON object, you have to assign a modified object to the column. Postgres supplies limited means to build and manipulate json data in addition to its storage capabilities. The arsenal of tools has grown substantially with every new release since version 9.2. But the principal remains: You always have to assign a complete modified object to the column and Postgres always writes a new row version for any update.

Some techniques how to work with the tools of Postgres 9.3 or later:

This answer has attracted about as many downvotes as all my other answers on SO together. People don't seem to like the idea: a normalized design is superior for non-dynamic data. This excellent blog post by Craig Ringer explains in more detail:

Change x axes scale in matplotlib

The scalar formatter supports collecting the exponents. The docs are as follows:

class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter

Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.

your technique would be:

from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3))  # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)

To get the exponent displayed in the format x10^5, instantiate the ScalarFormatter with useMathText=True.

After Image

You could also use:

xfmt.set_useOffset(10000)

To get a result like this:

enter image description here

JS. How to replace html element with another element/text, represented in string?

use the attribute "innerHTML"

somehow select the table:

var a = document.getElementById('table, div, whatever node, id')
a.innerHTML = your_text

Excel VBA For Each Worksheet Loop

Instead of adding "ws." before every Range, as suggested above, you can add "ws.activate" before Call instead.

This will get you into the worksheet you want to work on.

General error: 1364 Field 'user_id' doesn't have a default value

Try

'user_id' => auth()->id
or

'user_id' => Auth::user()->id

instead of

'user_id' => auth()->id()

How do I get the fragment identifier (value after hash #) from a URL?

I had the URL from run time, below gave the correct answer:

let url = "www.site.com/index.php#hello";
alert(url.split('#')[1]);

hope this helps

How do I add all new files to SVN

svn status | grep "^\?" | awk '{print $2}' | xargs svn add

Taken from somewhere on the web but I've been using it for a while and it works well.

SQLAlchemy: What's the difference between flush() and commit()?

A Session object is basically an ongoing transaction of changes to a database (update, insert, delete). These operations aren't persisted to the database until they are committed (if your program aborts for some reason in mid-session transaction, any uncommitted changes within are lost).

The session object registers transaction operations with session.add(), but doesn't yet communicate them to the database until session.flush() is called.

session.flush() communicates a series of operations to the database (insert, update, delete). The database maintains them as pending operations in a transaction. The changes aren't persisted permanently to disk, or visible to other transactions until the database receives a COMMIT for the current transaction (which is what session.commit() does).

session.commit() commits (persists) those changes to the database.

flush() is always called as part of a call to commit() (1).

When you use a Session object to query the database, the query will return results both from the database and from the flushed parts of the uncommitted transaction it holds. By default, Session objects autoflush their operations, but this can be disabled.

Hopefully this example will make this clearer:

#---
s = Session()

s.add(Foo('A')) # The Foo('A') object has been added to the session.
                # It has not been committed to the database yet,
                #   but is returned as part of a query.
print 1, s.query(Foo).all()
s.commit()

#---
s2 = Session()
s2.autoflush = False

s2.add(Foo('B'))
print 2, s2.query(Foo).all() # The Foo('B') object is *not* returned
                             #   as part of this query because it hasn't
                             #   been flushed yet.
s2.flush()                   # Now, Foo('B') is in the same state as
                             #   Foo('A') was above.
print 3, s2.query(Foo).all() 
s2.rollback()                # Foo('B') has not been committed, and rolling
                             #   back the session's transaction removes it
                             #   from the session.
print 4, s2.query(Foo).all()

#---
Output:
1 [<Foo('A')>]
2 [<Foo('A')>]
3 [<Foo('A')>, <Foo('B')>]
4 [<Foo('A')>]