Programs & Examples On #Group concat

a function which returns a string representation of the concatenated, non-NULL values of a group

MySQL and GROUP_CONCAT() maximum length

The short answer: the setting needs to be setup when the connection to the MySQL server is established. For example, if using MYSQLi / PHP, it will look something like this:

$ myConn = mysqli_init(); 
$ myConn->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');

Therefore, if you are using a home-brewed framework, well, you need to look for the place in the code when the connection is establish and provide a sensible value.

I am still using Codeigniter 3 on 2020, so in this framework, the code to add is in the application/system/database/drivers/mysqli/mysqli_driver.php, the function is named db_connect();

public function db_connect($persistent = FALSE)
    {
        // Do we have a socket path?
        if ($this->hostname[0] === '/')
        {
            $hostname = NULL;
            $port = NULL;
            $socket = $this->hostname;
        }
        else
        {
            $hostname = ($persistent === TRUE)
                ? 'p:'.$this->hostname : $this->hostname;
            $port = empty($this->port) ? NULL : $this->port;
            $socket = NULL;
        }

        $client_flags = ($this->compress === TRUE) ? MYSQLI_CLIENT_COMPRESS : 0;
        $this->_mysqli = mysqli_init();

        $this->_mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 10);
        $this->_mysqli->options(MYSQLI_INIT_COMMAND, 'SET SESSION group_concat_max_len = 1000000');

...
    }

Postgresql GROUP_CONCAT equivalent?

My sugestion in postgresql

SELECT cpf || ';' || nome || ';' || telefone  
FROM (
      SELECT cpf
            ,nome
            ,STRING_AGG(CONCAT_WS( ';' , DDD_1, TELEFONE_1),';') AS telefone 
      FROM (
            SELECT DISTINCT * 
            FROM temp_bd 
            ORDER BY cpf DESC ) AS y
      GROUP BY 1,2 ) AS x   

Can I concatenate multiple MySQL rows into one field?

You can change the max length of the GROUP_CONCAT value by setting the group_concat_max_len parameter.

See details in the MySQL documantation.

How to concatenate text from multiple rows into a single text string in SQL server?

Although it's too late, and already has many solutions. Here is simple solution for MySQL:

SELECT t1.id,
        GROUP_CONCAT(t1.id) ids
 FROM table t1 JOIN table t2 ON (t1.id = t2.id)
 GROUP BY t1.id

MySQL DISTINCT on a GROUP_CONCAT()

Using DISTINCT will work

SELECT GROUP_CONCAT(DISTINCT(categories) SEPARATOR ' ') FROM table

REf:- this

GROUP_CONCAT ORDER BY

Try

SELECT li.clientid, group_concat(li.views ORDER BY li.views) AS views,
       group_concat(li.percentage ORDER BY li.percentage) 
FROM table_views li 
GROUP BY client_id

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat

How to use GROUP_CONCAT in a CONCAT in MySQL

Try:

CREATE TABLE test (
  ID INTEGER,
  NAME VARCHAR (50),
  VALUE INTEGER
);

INSERT INTO test VALUES (1, 'A', 4);
INSERT INTO test VALUES (1, 'A', 5);
INSERT INTO test VALUES (1, 'B', 8);
INSERT INTO test VALUES (2, 'C', 9);

SELECT ID, GROUP_CONCAT(NAME ORDER BY NAME ASC SEPARATOR ',')
FROM (
  SELECT ID, CONCAT(NAME, ':', GROUP_CONCAT(VALUE ORDER BY VALUE ASC SEPARATOR ',')) AS NAME
  FROM test
  GROUP BY ID, NAME
) AS A
GROUP BY ID;

SQL Fiddle: http://sqlfiddle.com/#!2/b5abe/9/0

GROUP_CONCAT comma separator - MySQL

Query to achieve your requirment

SELECT id,GROUP_CONCAT(text SEPARATOR ' ') AS text FROM table_name group by id;

How to insert an item into a key/value pair object?

List<KeyValuePair<string, string>> kvpList = new List<KeyValuePair<string, string>>()
{
    new KeyValuePair<string, string>("Key1", "Value1"),
    new KeyValuePair<string, string>("Key2", "Value2"),
    new KeyValuePair<string, string>("Key3", "Value3"),
};

kvpList.Insert(0, new KeyValuePair<string, string>("New Key 1", "New Value 1"));

Using this code:

foreach (KeyValuePair<string, string> kvp in kvpList)
{
    Console.WriteLine(string.Format("Key: {0} Value: {1}", kvp.Key, kvp.Value);
}

the expected output should be:

Key: New Key 1 Value: New Value 1
Key: Key 1 Value: Value 1
Key: Key 2 Value: Value 2
Key: Key 3 Value: Value 3

The same will work with a KeyValuePair or whatever other type you want to use..

Edit -

To lookup by the key, you can do the following:

var result = stringList.Where(s => s == "Lookup");

You could do this with a KeyValuePair by doing the following:

var result = kvpList.Where (kvp => kvp.Value == "Lookup");

Last edit -

Made the answer specific to KeyValuePair rather than string.

Make footer stick to bottom of page using Twitter Bootstrap

just add the class navbar-fixed-bottom to your footer.

<div class="footer navbar-fixed-bottom">

Update for Bootstrap 4 -

as mentioned by Sara Tibbetts - class is fixed-bottom

<div class="footer fixed-bottom">

Bash write to file without echo?

There are multiple ways to do it, let's run this script called exercise.sh

#!/usr/bin/env bash

> file1.txt cat <<< "This is a here-string with random value $RANDOM"

# Or if you prefer to see what is happening and write to file as well
tee file2.txt <<< "Here is another here-string I can see and write to file"

# if you want to work multiline easily
cat <<EOF > file3.txt
You don't need to escape any quotes here, $ marks start of variables, unless escaped.
This is random value from variable $RANDOM
This is literal \$RANDOM
EOF

# Let's say you have a variable with multiline text and you want to manipulate it
a="
1
2
3
33
"

# Assume I want to have lines containing "3". Instead of grep it can even be another script
a=$(echo "$a" | grep 3)

# Then you want to write this to a file, although here-string is fine,
# if you don't need single-liner command, prefer heredoc
# Herestring. (If it's single liner, variable needs to be quoted to preserve newlines)
> file4.txt cat <<< "$a"
# Heredoc
cat <<EOF > file5.txt
$a
EOF

This is the output you should see:

$ bash exercise.sh
Here is another here-string I can see and write to file

And files should contain these:

$ ls
exercise.sh  file1.txt  file2.txt  file3.txt  file4.txt  file5.txt
$ cat file1.txt
This is a here-string with random value 20914
$ cat file2.txt
Here is another here-string I can see and write to file
$ cat file3.txt
You don't need to escape any quotes here, $ marks start of variables, unless escaped.
This is random value from variable 15899
This is literal $RANDOM
$ cat file4.txt
3
33
$ cat file5.txt
3
33

How can I get Eclipse to show .* files?

1. From Package Explorer open the Filters... dialog:

enter image description here

2. Then uncheck .* resources option:

enter image description here

Should I use SVN or Git?

If your team is already familiar with version and source control softwares like cvs or svn, then, for a simple and small project (such as you claim it is), I would recommend you stick to SVN. I am really comfortable with svn, but for the current e-commerce project I am doing on django, I decided to work on git (I am using git in svn-mode, that is, with a centralised repo that I push to and pull from in order to collaborate with at least one other developer). The other developer is comfortable with SVN, and while others' experiences may differ, both of us are having a really bad time embracing git for this small project. (We are both hardcore Linux users, if it matters at all.)

Your mileage may vary, of course.

How to resize a VirtualBox vmdk file

I was able to resize the vmdk by cloning it and then modifying and resizing.

vboxmanage clonehd "virtualdisk.vmdk" "new-virtualdisk.vdi" --format vdi
vboxmanage modifyhd "new-virtualdisk.vdi" --resize 30720

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

getting only name of the class Class.getName()

Here is the Groovy way of accessing object properties:

this.class.simpleName    # returns the simple name of the current class

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Your problem is here:

2013-11-14 17:57:20 5180 [ERROR] InnoDB: .\ibdata1 can't be opened in read-write mode

There's some problem with the ibdata1 file - maybe the permissions have changed on it? Perhaps some other process has it open. Does it even exist?

Fix this and possibly everything else will fall into place.

Interpreting segfault messages

Error 4 means "The cause was a user-mode read resulting in no page being found.". There's a tool that decodes it here.

Here's the definition from the kernel. Keep in mind that 4 means that bit 2 is set and no other bits are set. If you convert it to binary that becomes clear.

/*
 * Page fault error code bits
 *      bit 0 == 0 means no page found, 1 means protection fault
 *      bit 1 == 0 means read, 1 means write
 *      bit 2 == 0 means kernel, 1 means user-mode
 *      bit 3 == 1 means use of reserved bit detected
 *      bit 4 == 1 means fault was an instruction fetch
 */
#define PF_PROT         (1<<0)
#define PF_WRITE        (1<<1)
#define PF_USER         (1<<2)
#define PF_RSVD         (1<<3)
#define PF_INSTR        (1<<4)

Now then, "ip 00007f9bebcca90d" means the instruction pointer was at 0x00007f9bebcca90d when the segfault happened.

"libQtWebKit.so.4.5.2[7f9beb83a000+f6f000]" tells you:

  • The object the crash was in: "libQtWebKit.so.4.5.2"
  • The base address of that object "7f9beb83a000"
  • How big that object is: "f6f000"

If you take the base address and subtract it from the ip, you get the offset into that object:

0x00007f9bebcca90d - 0x7f9beb83a000 = 0x49090D

Then you can run addr2line on it:

addr2line -e /usr/lib64/qt45/lib/libQtWebKit.so.4.5.2 -fCi 0x49090D
??
??:0

In my case it wasn't successful, either the copy I installed isn't identical to yours, or it's stripped.

CSS way to horizontally align table

<style>
    .abc {
        text-align: center;
    }
</style>

<table class="abc">
    <tr>
        <td>Item1</td>
        <td>Item2</td>
    </tr>
</table>

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT (in windows 10)

Android Studio Picture

Make sure you have an Android Virtual Device selected to output the app to. In the picture I put on this post you can see I selected the Android Virtual Device "Nexus 5" as the output device. Doing this removed the error for me.

How to compile Go program consisting of multiple files?

You can use

go build *.go 
go run *.go

both will work also you may use

go build .
go run .

SQL how to increase or decrease one for a int column in one command

@dotjoe It is cheaper to update and check @@rowcount, do an insert after then fact.

Exceptions are expensive && updates are more frequent

Suggestion: If you want to be uber performant in your DAL, make the front end pass in a unique ID for the row to be updated, if null insert.

The DALs should be CRUD, and not need to worry about being stateless.

If you make it stateless, With good indexes, you will not see a diff with the following SQL vs 1 statement. IF (select top 1 * form x where PK=@ID) Insert else update

Set a:hover based on class

Set a:hover based on class you can simply try:

a.main-nav-item:hover { }

How to add a scrollbar to an HTML5 table?

use this table into a DIV

<div class="tbl_container">
<table> .... </table>
</div>


.tbl_container{ overflow:auto; width: 500px;height: 200px; }

and beside this if you want to make it more beautiful and attractive use the jscollpane to customized your scrollbar..

How to view Plugin Manager in Notepad++

  1. You can download the latest Plugin Manager version PluginManager_latest_version_x64.zip.

  2. Unzip the file.

  3. Copy

PluginManager_latest_version_x64.zip\updater\gpup.exe

into

path-to-installed-notepad\notepad++\updater\

  1. Copy

PluginManager_latest_version_x64.zip\plugins\PluginManager.dll

into

path-to-installed-notepad\notepad++\plugins\

  1. Start or restart Notepad++.
  2. Enjoy!

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

convert UIImage to NSData

NSData *imageData = UIImagePNGRepresentation(myImage.image);

Getting Date or Time only from a DateTime Object

var currentDateTime = dateTime.Now();
var date=currentDateTime.Date;

How often should you use git-gc?

Note that the downside of garbage-collecting your repository is that, well, the garbage gets collected. As we all know as computer users, files we consider garbage right now might turn out to be very valuable three days in the future. The fact that git keeps most of its debris around has saved my bacon several times – by browsing all the dangling commits, I have recovered much work that I had accidentally canned.

So don’t be too much of a neat freak in your private clones. There’s little need for it.

OTOH, the value of data recoverability is questionable for repos used mainly as remotes, eg. the place all the devs push to and/or pulled from. There, it might be sensible to kick off a GC run and a repacking frequently.

PHP Pass by reference in foreach

Because if you create a reference to a variable, all names for that variable (including the original) BECOME REFERENCES.

How to get file URL using Storage facade in laravel 5?

This is how I got it to work - switching between s3 and local directory paths with an environment variable, passing the path to all views.

In .env:

APP_FILESYSTEM=local or s3
S3_BUCKET=BucketID

In config/filesystems.php:

'default' => env('APP_FILESYSTEM'),

In app/Providers/AppServiceProvider:

public function boot()
{
    view()->share('dynamic_storage', $this->storagePath());
}

protected function storagePath()
{
    if (Storage::getDefaultDriver() == 's3') {
        return Storage::getDriver()
                ->getAdapter()
                ->getClient()
                ->getObjectUrl(env('S3_BUCKET'), '');
    }

    return URL::to('/');
}

how to convert from int to char*?

You can use boost

#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

How to overlay image with color in CSS?

You may use negative superthick semi-transparent border...

_x000D_
_x000D_
.red {_x000D_
    outline: 100px solid rgba(255, 0, 0, 0.5) !important;_x000D_
    outline-offset: -100px;_x000D_
    overflow: hidden;_x000D_
    position: relative;_x000D_
    height: 200px;_x000D_
    width: 200px;_x000D_
}
_x000D_
<div class="red">Anything can be red.</div>_x000D_
<h1>Or even image...</h1>_x000D_
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" class="red"/>
_x000D_
_x000D_
_x000D_

This solution requires you to know exact sizes of covered object.

How to prevent column break within an element?

This works for me in 2015 :

_x000D_
_x000D_
li {_x000D_
  -webkit-column-break-inside: avoid;_x000D_
  /* Chrome, Safari, Opera */_x000D_
  page-break-inside: avoid;_x000D_
  /* Firefox */_x000D_
  break-inside: avoid;_x000D_
  /* IE 10+ */_x000D_
}_x000D_
.x {_x000D_
  -moz-column-count: 3;_x000D_
  column-count: 3;_x000D_
  width: 30em;_x000D_
}
_x000D_
<div class='x'>_x000D_
  <ul>_x000D_
    <li>Number one</li>_x000D_
    <li>Number two</li>_x000D_
    <li>Number three</li>_x000D_
    <li>Number four is a bit longer</li>_x000D_
    <li>Number five</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

pip install returning invalid syntax

You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

Get latitude and longitude automatically using php, API

Two ideas:

  • Are Address and Region URL Encoded?
  • Perhaps your computer running the code doesn't allow http access. Try loading another page (like 'http://www.google.com') and see if that works. If that also doesn't work, then there's something wrong with PHP settings.

How to make zsh run as a login shell on Mac OS X (in iTerm)?

Use the login utility to create a login shell. Assume that the user you want to log in has the username Alice and that zsh is installed in /opt/local/bin/zsh (e.g., a more recent version installed via MacPorts). In iTerm 2, go to Preferences, Profiles, select the profile that you want to set up, and enter in Command:

login -pfq Alice /opt/local/bin/zsh

See man login for more details on the options.

How to set a variable inside a loop for /F

I know this isn't what's asked but I benefited from this method, when trying to set a variable within a "loop". Uses an array. Alternative implementation option.

SETLOCAL ENABLEDELAYEDEXPANSION

...

set Services[0]=SERVICE1
set Services[1]=SERVICE2
set Services[2]=SERVICE3

set "i=0"

:ServicesLoop
if defined Services[%i%] (
    set SERVICE=!Services[%i%]!

    echo CurrentService: !SERVICE!

    set /a "i+=1"
    GOTO :ServicesLoop
)

android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()

Just paste the below code in activity onCreate()

StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());

It will ignore URI exposure

Composer killed while updating

If like me, you are using some micro VM lacking of memory, creating a swap file does the trick:

#Check free memory before
free -m

mkdir -p /var/_swap_
cd /var/_swap_
#Here, 1M * 2000 ~= 2GB of swap memory.  Feel free to add MORE
dd if=/dev/zero of=swapfile bs=1M count=2000
chmod 600 swapfile
mkswap swapfile
swapon swapfile
#Automatically mount this swap partition at startup
echo "/var/_swap_/swapfile none swap sw 0 0" >> /etc/fstab

#Check free memory after
free -m

As several comments pointed out, don't forget to add sudo if you don't work as root.

btw, feel free to select another location/filename/size for the file.
/var is probably not the best place, but I don't know which place would be, and rarely care since tiny servers are mostly used for testing purposes.

Landscape printing from HTML

In your CSS you can set the @page property as shown below.

@media print{@page {size: landscape}}

The @page is part of CSS 2.1 specification however this size is not as highlighted by the answer to the question Is @Page { size:landscape} obsolete?:

CSS 2.1 no longer specifies the size attribute. The current working draft for CSS3 Paged Media module does specify it (but this is not standard or accepted).

As stated the size option comes from the CSS 3 Draft Specification. In theory it can be set to both a page size and orientation although in my sample the size is omitted.

The support is very mixed with a bug report begin filed in firefox, most browsers do not support it.

It may seem to work in IE7 but this is because IE7 will remember the users last selection of landscape or portrait in print preview (only the browser is re-started).

This article does have some suggested work arounds using JavaScript or ActiveX that send keys to the users browser although it they are not ideal and rely on changing the browsers security settings.

Alternately you could rotate the content rather than the page orientation. This can be done by creating a style and applying it to the body that includes these two lines but this also has draw backs creating many alignment and layout issues.

<style type="text/css" media="print">
    .page
    {
     -webkit-transform: rotate(-90deg); 
     -moz-transform:rotate(-90deg);
     filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
    }
</style>

The final alternative I have found is to create a landscape version in a PDF. You can point to so when the user selects print it prints the PDF. However I could not get this to auto print work in IE7.

<link media="print" rel="Alternate" href="print.pdf">

In conclusion in some browsers it is relativity easy using the @page size option however in many browsers there is no sure way and it would depend on your content and environment. This maybe why Google Documents creates a PDF when print is selected and then allows the user to open and print that.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

org.glassfish.jersey.servlet.ServletContainer.class

here remove .class

org.glassfish.jersey.servlet.ServletContainer now you wont get

How to know when a web page was last updated?

In general, there is no way to know when something on another site has been changed. If the site offers an RSS feed, you should try that. If the site does not offer an RSS feed (or if the RSS feed doesn't include the information you're looking for), then you have to scrape and compare.

How can I disable a tab inside a TabControl?

I had to handle this a while back. I removed the Tab from the TabPages collection (I think that's it) and added it back in when the conditions changed. But that was only in Winforms where I could keep the tab around until I needed it again.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Hi I tested below code that worked fine :

    long timeInMillis = System.currentTimeMillis();
    Calendar cal1 = Calendar.getInstance();
    cal1.setTimeInMillis(timeInMillis);
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
    dateFormat.format(cal1.getTime());

Is there a CSS parent selector?

Just an idea for horizontal menu...

Part of HTML

<div class='list'>
  <div class='item'>
    <a>Link</a>
  </div>
  <div class='parent-background'></div>
  <!-- submenu takes this place -->
</div>

Part of CSS

/* Hide parent backgrounds... */
.parent-background {
  display: none; }

/* ... and show it when hover on children */
.item:hover + .parent-background {
  display: block;
  position: absolute;
  z-index: 10;
  top: 0;
  width: 100%; }

Updated demo and the rest of code

Another example how to use it with text-inputs - select parent fieldset

Set width of a "Position: fixed" div relative to parent div

Here is a little hack that we ran across while fixing some redraw issues on a large app.

Use -webkit-transform: translateZ(0); on the parent. Of course this is specific to Chrome.

http://jsfiddle.net/senica/bCQEa/

-webkit-transform: translateZ(0);

Array vs. Object efficiency in JavaScript

I had a similar problem that I am facing where I need to store live candlesticks from an event source limited to x items. I could have them stored in an object where the timestamp of each candle would act as the key and the candle itself would act as the value. Another possibility was that I could store it in an array where each item was the candle itself. One problem about live candles is that they keep sending updates on the same timestamp where the latest update holds the most recent data therefore you either update an existing item or add a new one. So here is a nice benchmark that attempts to combine all 3 possibilities. Arrays in the solution below are atleast 4x faster on average. Feel free to play

"use strict";

const EventEmitter = require("events");
let candleEmitter = new EventEmitter();

//Change this to set how fast the setInterval should run
const frequency = 1;

setInterval(() => {
    // Take the current timestamp and round it down to the nearest second
    let time = Math.floor(Date.now() / 1000) * 1000;
    let open = Math.random();
    let high = Math.random();
    let low = Math.random();
    let close = Math.random();
    let baseVolume = Math.random();
    let quoteVolume = Math.random();

    //Clear the console everytime before printing fresh values
    console.clear()

    candleEmitter.emit("candle", {
        symbol: "ABC:DEF",
        time: time,
        open: open,
        high: high,
        low: low,
        close: close,
        baseVolume: baseVolume,
        quoteVolume: quoteVolume
    });



}, frequency)

// Test 1 would involve storing the candle in an object
candleEmitter.on('candle', storeAsObject)

// Test 2 would involve storing the candle in an array
candleEmitter.on('candle', storeAsArray)

//Container for the object version of candles
let objectOhlc = {}

//Container for the array version of candles
let arrayOhlc = {}

//Store a max 30 candles and delete older ones
let limit = 30

function storeAsObject(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;

    // Create the object structure to store the current symbol
    if (typeof objectOhlc[symbol] === 'undefined') objectOhlc[symbol] = {}

    // The timestamp of the latest candle is used as key with the pair to store this symbol
    objectOhlc[symbol][time] = candle;

    // Remove entries if we exceed the limit
    const keys = Object.keys(objectOhlc[symbol]);
    if (keys.length > limit) {
        for (let i = 0; i < (keys.length - limit); i++) {
            delete objectOhlc[symbol][keys[i]];
        }
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]

    console.log("Storing as objects", end - start, Object.keys(objectOhlc[symbol]).length)
}

function storeAsArray(candle) {

    //measure the start time in nanoseconds
    const hrtime1 = process.hrtime()
    const start = hrtime1[0] * 1e9 + hrtime1[1]

    const { symbol, time } = candle;
    if (typeof arrayOhlc[symbol] === 'undefined') arrayOhlc[symbol] = []

    //Get the bunch of candles currently stored
    const candles = arrayOhlc[symbol];

    //Get the last candle if available
    const lastCandle = candles[candles.length - 1] || {};

    // Add a new entry for the newly arrived candle if it has a different timestamp from the latest one we storeds
    if (time !== lastCandle.time) {
        candles.push(candle);
    }

    //If our newly arrived candle has the same timestamp as the last stored candle, update the last stored candle
    else {
        candles[candles.length - 1] = candle
    }

    if (candles.length > limit) {
        candles.splice(0, candles.length - limit);
    }

    //measure the end time in nano seocnds
    const hrtime2 = process.hrtime()
    const end = hrtime2[0] * 1e9 + hrtime2[1]


    console.log("Storing as array", end - start, arrayOhlc[symbol].length)
}

Conclusion 10 is the limit here

Storing as objects 4183 nanoseconds 10
Storing as array 373 nanoseconds 10

remove table row with specific id

Use the :eq selector:

$("#test tr:eq(2)").remove();

How to redirect to previous page in Ruby On Rails?

This is how we do it in our application

def store_location
  session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end

def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
end

This way you only store last GET request in :return_to session param, so all forms, even when multiple time POSTed would work with :return_to.

Error: [ng:areq] from angular controller

I have made a stupid mistake and wasted lot of time so adding this answer over here so that it helps someone

I was incorrectly adding the $scope variable(dependency)(was adding it without single quotes)

for example what i was doing was something like this

angular.module("myApp",[]).controller('akshay',[$scope,

where the desired syntax is like this

angular.module("myApp",[]).controller('akshay',['$scope',

How can I pad a String in Java?

Let's me leave an answer for some cases that you need to give left/right padding (or prefix/suffix string or spaces) before you concatenate to another string and you don't want to test length or any if condition.

The same to the selected answer, I would prefer the StringUtils of Apache Commons but using this way:

StringUtils.defaultString(StringUtils.leftPad(myString, 1))

Explain:

  • myString: the string I input, can be null
  • StringUtils.leftPad(myString, 1): if string is null, this statement would return null too
  • then use defaultString to give empty string to prevent concatenate null

Remove Project from Android Studio

  1. Go to your Android project directory

    C:\Users\HP\AndroidStudioProjects
    

    Screenshot

  2. Delete which one you need to delete

  3. Restart Android Studio

javascript: pause setTimeout();

If anyone wants the TypeScript version shared by the Honorable @SeanVieira here, you can use this:

    public timer(fn: (...args: any[]) => void, countdown: number): { onCancel: () => void, onPause: () => void, onResume: () => void } {
        let ident: NodeJS.Timeout | number;
        let complete = false;
        let totalTimeRun: number;
        const onTimeDiff = (date1: number, date2: number) => {
            return date2 ? date2 - date1 : new Date().getTime() - date1;
        };

        const handlers = {
            onCancel: () => {
                clearTimeout(ident as NodeJS.Timeout);
            },
            onPause: () => {
                clearTimeout(ident as NodeJS.Timeout);
                totalTimeRun = onTimeDiff(startTime, null);
                complete = totalTimeRun >= countdown;
            },
            onResume: () => {
                ident = complete ? -1 : setTimeout(fn, countdown - totalTimeRun);
            }
        };

        const startTime = new Date().getTime();
        ident = setTimeout(fn, countdown);

        return handlers;
    }

How do I set headers using python's urllib?

For both Python 3 and Python 2, this works:

try:
    from urllib.request import Request, urlopen  # Python 3
except ImportError:
    from urllib2 import Request, urlopen  # Python 2

req = Request('http://api.company.com/items/details?country=US&language=en')
req.add_header('apikey', 'xxx')
content = urlopen(req).read()

print(content)

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

What is the "assert" function?

Stuff like 'raises exception' and 'halts execution' might be true for most compilers, but not for all. (BTW, are there assert statements that really throw exceptions?)

Here's an interesting, slightly different meaning of assert used by c6x and other TI compilers: upon seeing certain assert statements, these compilers use the information in that statement to perform certain optimizations. Wicked.

Example in C:

int dot_product(short *x, short *y, short z)
{
  int sum = 0
  int i;

  assert( ( (int)(x) & 0x3 ) == 0 );
  assert( ( (int)(y) & 0x3 ) == 0 );

  for( i = 0 ; i < z ; ++i )
    sum += x[ i ] * y[ i ];
  return sum;
}

This tells de compiler the arrays are aligned on 32-bits boundaries, so the compiler can generate specific instructions made for that kind of alignment.

How to dynamically insert a <script> tag via jQuery after page load?

Try the following:

<script type="text/javascript">
// Use any event to append the code
$(document).ready(function() 
{
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.src = "http://scriptlocation/das.js";
    // Use any selector
    $("head").append(s);
});

http://api.jquery.com/append

How can I display an RTSP video stream in a web page?

Try the QuickTime Player! Heres my JavaScript that generates the embedded object on a web page and plays the stream:

//SET THE RTSP STREAM ADDRESS HERE
var address = "rtsp://192.168.0.101/mpeg4/1/media.3gp";

var output = '<object width="640" height="480" id="qt" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab">';
    output += '<param name="src" value="'+address+'">';
    output += '<param name="autoplay" value="true">';
    output += '<param name="controller" value="false">';
    output += '<embed id="plejer" name="plejer" src="/poster.mov" bgcolor="000000" width="640" height="480" scale="ASPECT" qtsrc="'+address+'"  kioskmode="true" showlogo=false" autoplay="true" controller="false" pluginspage="http://www.apple.com/quicktime/download/">';
    output += '</embed></object>';

    //SET THE DIV'S ID HERE
    document.getElementById("the_div_that_will_hold_the_player_object").innerHTML = output;

Get parent directory of running script

To get the parentdir of the current script.

$parent_dir = dirname(__DIR__);

Using an if statement to check if a div is empty

If you want a quick demo how you check for empty divs I'd suggest you to try this link:

http://html-tuts.com/check-if-html-element-is-empty-or-has-children-tags/


Below you have some short examples:

Using CSS

If your div is empty without anything even no white-space, you can use CSS:

.someDiv:empty {
    display: none;
}

Unfortunately there is no CSS selector that selects the previous sibling element. There is only for the next sibling element: x ~ y

.someDiv:empty ~ .anotherDiv {
    display: none;
}

Using jQuery

Checking text length of element with text() function

if ( $('#leftmenu').text().length == 0 ) {
    // length of text is 0
}

Check if element has any children tags inside

if ( $('#leftmenu').children().length == 0 ) {
    // div has no other tags inside it
}

Check for empty elements if they have white-space

if ( $.trim( $('.someDiv').text() ).length == 0 ) {
    // white-space trimmed, div is empty
}

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Make sure you add following line in your top level build.gradle and that should fix it.

maven { url 'https://maven.google.com' }

I got exact same error you mentioned above, once I added this entry everything worked.

Must declare the scalar variable

If someone else comes across this question while no solution here made my sql file working, here's what my mistake was:

I have been exporting the contents of my database via the 'Generate Script' command of Microsofts' Server Management Studio and then doing some operations afterwards while inserting the generated data in another instance.

Due to the generated export, there have been a bunch of "GO" statements in the sql file.

What I didn't know was that variables declared at the top of a file aren't accessible as far as a GO statement is executed. Therefore I had to remove the GO statements in my sql file and the error "Must declare the scalar variable xy" was gone!

How do I test if a variable is a number in Bash?

This can be achieved by using grep to see if the variable in question matches an extended regular expression.

Test integer 1120:

yournumber=1120
if echo "$yournumber" | grep -qE '^[0-9]+$'; then
    echo "Valid number."
else
    echo "Error: not a number."
fi

Output: Valid number.

Test non-integer 1120a:

yournumber=1120a
if echo "$yournumber" | grep -qE '^[0-9]+$'; then
    echo "Valid number."
else
    echo "Error: not a number."
fi

Output: Error: not a number.


Explanation

  • The grep, the -E switch allows us to use extended regular expression '^[0-9]+$'. This regular expression means the variable should only [] contain the numbers 0-9 zero through nine from the ^ beginning to the $ end of the variable and should have at least + one character.
  • The grep, the -q quiet switch turns off any output whether or not it finds anything.
  • if checks the exit status of grep. Exit status 0 means success and anything greater means an error. The grep command has an exit status of 0 if it finds a match and 1 when it doesn't;

So putting it all together, in the if test, we echo the variable $yournumber and | pipe it to grep which with the -q switch silently matches the -E extended regular expression '^[0-9]+$' expression. The exit status of grep will be 0 if grep successfully found a match and 1 if it didn't. If succeeded to match, we echo "Valid number.". If it failed to match, we echo "Error: not a number.".


For Floats or Doubles

We can just change the regular expression from '^[0-9]+$' to '^[0-9]*\.?[0-9]+$' for floats or doubles.

Test float 1120.01:

yournumber=1120.01
if echo "$yournumber" | grep -qE '^[0-9]*\.?[0-9]+$'; then
    echo "Valid number."
else
    echo "Error: not a number."
fi

Output: Valid number.

Test float 11.20.01:

yournumber=11.20.01
if echo "$yournumber" | grep -qE '^[0-9]*\.?[0-9]+$'; then
    echo "Valid number."
else
    echo "Error: not a number."
fi

Output: Error: not a number.


For Negatives

To allow negative integers, just change the regular expression from '^[0-9]+$' to '^\-?[0-9]+$'.

To allow negative floats or doubles, just change the regular expression from '^[0-9]*\.?[0-9]+$' to '^\-?[0-9]*\.?[0-9]+$'.

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Each Java process has a pid, which you first need to find with the jps command.

Once you have the pid, you can use jstat -gc [insert-pid-here] to find statistics of the behavior of the garbage collected heap.

  • jstat -gccapacity [insert-pid-here] will present information about memory pool generation and space capabilities.

  • jstat -gcutil [insert-pid-here] will present the utilization of each generation as a percentage of its capacity. Useful to get an at a glance view of usage.

See jstat docs on Oracle's site.

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

Redirecting to URL in Flask

For this you can simply use the redirect function that is included in flask

from flask import Flask, redirect

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect("https://www.exampleURL.com", code = 302)

if __name__ == "__main__":
    app.run()

Another useful tip(as you're new to flask), is to add app.debug = True after initializing the flask object as the debugger output helps a lot while figuring out what's wrong.

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try this:

Select To_date ('15/2/2007 00:00:00', 'DD/MM/YYYY HH24:MI:SS'),
       To_date ('28/2/2007 10:12', 'DD/MM/YYYY HH24:MI:SS')
  From DUAL;

Source: http://notsyncing.org/2008/02/manipulando-fechas-con-horas-en-plsql-y-sql/

How do I get my C# program to sleep for 50 msec?

You can't specify an exact sleep time in Windows. You need a real-time OS for that. The best you can do is specify a minimum sleep time. Then it's up to the scheduler to wake up your thread after that. And never call .Sleep() on the GUI thread.

How to fix broken paste clipboard in VNC on Windows

http://rreddy.blogspot.com/2009/07/vncviewer-clipboard-operations-like.html

Many times you must have observed that clipboard operations like copy/cut and paste suddenly stops workings with the vncviewer. The main reason for this there is a program called as vncconfig responsible for these clipboard transfers. Some times the program may get closed because of some bug in vnc or some other reasons like you closed that window.

To get those clipboard operations back you need to run the program "vncconfig &".

After this your clipboard actions should work fine with out any problems.

Run "vncconfig &" on the client.

How to access the php.ini file in godaddy shared hosting linux

As pointed out by @Jason, for most shared hosting environments, having a copy of php.ini file in your public_html directory works to override the system default settings. A great way to do this is by copying the hosting company's copy. Put this in a file, say copyini.php

<?php
  system("cp /path/to/php/conf/file/php.ini  /home/yourusername/public_html/php.ini");
?>

Get /path/to/php/conf/file/php.ini from the output of phpinfo(); in a file. Then in your ini file, make your amendments Delete all files created during this process (Apart from php.ini of course :-) )

How to rotate x-axis tick labels in Pandas barplot

The question is clear but the title is not as precise as it could be. My answer is for those who came looking to change the axis label, as opposed to the tick labels, which is what the accepted answer is about. (The title has now been corrected).

for ax in plt.gcf().axes:
    plt.sca(ax)
    plt.xlabel(ax.get_xlabel(), rotation=90)

Load CSV file with Spark

Are you sure that all the lines have at least 2 columns? Can you try something like, just to check?:

sc.textFile("file.csv") \
    .map(lambda line: line.split(",")) \
    .filter(lambda line: len(line)>1) \
    .map(lambda line: (line[0],line[1])) \
    .collect()

Alternatively, you could print the culprit (if any):

sc.textFile("file.csv") \
    .map(lambda line: line.split(",")) \
    .filter(lambda line: len(line)<=1) \
    .collect()

How to make Bootstrap 4 cards the same height in card-columns?

I came across this problem, most people use jQuery... Here was my solution. "Do not mind, I am just a beginner in this..."

.cards-collection {
    .card-item { 
        width: 100%;
        margin: 20px 20px;
        padding:0 ;
        .card {
            border-radius: 10px;
                button {
                    border: inherit;
                }
        }
    }
}
     .container-fluid
         .row.cards-collection.justify-content-center
           .card-item.col-lg-3.col-md-4.col-sm-6.col-11
              .card.h-100

If any card item height is e.g. 400px (based on it's contents), because the default for flex-align is stretch, then .card-item (child of row or card-collection class) will be stretched. making the height of the card to be 100% of the parent will occupy this full height.

I hope I was correct. Am I?

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

Row numbers in query result using Microsoft Access

Though this is an old question, this has worked for me, but I've never tested its efficiency...

SELECT 
    (SELECT COUNT(t1.SourceID) 
     FROM [SourceTable] t1 
     WHERE t1.SourceID<t2.SourceID) AS RowID, 
    t2.field2, 
    t2.field3, 
    t2.field4, 
    t2.field5
FROM 
    SourceTable AS t2
ORDER BY 
    t2.SourceID;

Some advantages of this method:

  • It doesn't rely on the order of the table, either - the RowID is calculated on its actual value and those that are less than it.
  • This method can be applied to any (primary key) type (e.g. Number, String or Date).
  • This method is fairly SQL agnostic, or requires very little adaptation.

Final Thoughts

Though this will work with practically any data type, I must emphasise that, for some, it may create other problems. For instance, with strings, consider:

ID     Description    ROWID
aaa    Aardvark           1
bbb    Bear               2
ccc    Canary             3

If I were to insert: bba Boar, then the Canary RowID will change...

ID     Description    ROWID
aaa    Aardvark           1
bbb    Bear               2
bba    Boar               3
ccc    Canary             4

How to detect window.print() finish

You can detect when window.print() is finished simply by putting it in another function

//function to call if you want to print
var onPrintFinished=function(printed){console.log("do something...");}

//print command
onPrintFinished(window.print());

tested in Firefox,Google chrome,IE

super() raises "TypeError: must be type, not classobj" for new-style class

FWIW and though I'm no Python guru I got by with this

>>> class TextParser(HTMLParser):
...    def handle_starttag(self, tag, attrs):
...        if tag == "b":
...            self.all_data.append("bold")
...        else:
...            self.all_data.append("other")
...     
...         
>>> p = TextParser()
>>> p.all_data = []
>>> p.feed(text)
>>> print p.all_data
(...)

Just got me the parse results back as needed.

Cross domain POST request is not sending cookie Ajax Jquery

I had this same problem. The session ID is sent in a cookie, but since the request is cross-domain, the browser's security settings will block the cookie from being sent.

Solution: Generate the session ID on the client (in the browser), use Javascript sessionStorage to store the session ID then send the session ID with each request to the server.

I struggled a lot with this issue, and there weren't many good answers around. Here's an article detailing the solution: Javascript Cross-Domain Request With Session

How to bind multiple values to a single WPF TextBlock?

You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>
    <TextBlock.Text>    
        <MultiBinding StringFormat="{}{0} + {1}">
            <Binding Path="Name" />
            <Binding Path="ID" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.

Reporting Services permissions on SQL Server R2 SSRS

This problem occurs because of UAC and only when you are running IE on the same computer SSRS is on.

To fix it, you have to add an AD group of the users with read priviledges to the actual SSRS website directories and push the security down. UAC is dumb in how if you are an admin on the box. It won't let you access the data unless you also have access to the data through other means such as a non-administrator AD group that is applied to the files.

TypeScript, Looping through a dictionary

Shortest way to get all dictionary/object values:

Object.keys(dict).map(k => dict[k]);

Shorter syntax for casting from a List<X> to a List<Y>?

This is not quite the answer to this question, but it may be useful for some: as @SWeko said, thanks to covariance and contravariance, List<X> can not be cast in List<Y>, but List<X> can be cast into IEnumerable<Y>, and even with implicit cast.

Example:

List<Y> ListOfY = new List<Y>();
List<X> ListOfX = (List<X>)ListOfY; // Compile error

but

List<Y> ListOfY = new List<Y>();
IEnumerable<X> EnumerableOfX = ListOfY;  // No issue

The big advantage is that it does not create a new list in memory.

How to get a URL parameter in Express?

You can do something like req.param('tagId')

Serializing to JSON in jQuery

Works on IE8+

No need for jQuery, use:

JSON.stringify(countries); 

Output data with no column headings using PowerShell

The -expandproperty does not work with more than 1 object. You can use this one :

Select-Object Name | ForEach-Object {$_.Name}

If there is more than one value then :

Select-Object Name, Country | ForEach-Object {$_.Name + " " + $Country}

Forward declaring an enum in C++

[My answer is wrong, but I've left it here because the comments are useful].

Forward declaring enums is non-standard, because pointers to different enum types are not guaranteed to be the same size. The compiler may need to see the definition to know what size pointers can be used with this type.

In practice, at least on all the popular compilers, pointers to enums are a consistent size. Forward declaration of enums is provided as a language extension by Visual C++, for example.

Randomize a List<T>

Just wanted to suggest a variant using an IComparer<T> and List.Sort():

public class RandomIntComparer : IComparer<int>
{
    private readonly Random _random = new Random();
    
    public int Compare(int x, int y)
    {
        return _random.Next(-1, 2);
    }
}

Usage:

list.Sort(new RandomIntComparer());

How should I make my VBA code compatible with 64-bit Windows?

This work for me:

#If VBA7 And Win64 Then
    Private Declare PtrSafe Function ShellExecuteA Lib "Shell32.dll" _
        (ByVal hwnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
       ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) As Long
#Else

    Private Declare Function ShellExecuteA Lib "Shell32.dll" _
        (ByVal hwnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
        ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) As Long
#End If

Thanks Jon49 for insight.

How to convert a PIL Image into a numpy array?

You're not saying how exactly putdata() is not behaving. I'm assuming you're doing

>>> pic.putdata(a)
Traceback (most recent call last):
  File "...blablabla.../PIL/Image.py", line 1185, in putdata
    self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple

This is because putdata expects a sequence of tuples and you're giving it a numpy array. This

>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)

will work but it is very slow.

As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply

>>> pix = numpy.array(pic)

although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).

Then, after you make your changes to the array, you should be able to do either pic.putdata(pix) or create a new image with Image.fromarray(pix).

How to validate an OAuth 2.0 access token for a resource server?

OAuth 2.0 spec doesn't define the part. But there could be couple of options:

  1. When resource server gets the token in the Authz Header then it calls the validate/introspect API on Authz server to validate the token. Here Authz server might validate it either from using DB Store or verifying the signature and certain attributes. As part of response, it decodes the token and sends the actual data of token along with remaining expiry time.

  2. Authz Server can encrpt/sign the token using private key and then publickey/cert can be given to Resource Server. When resource server gets the token, it either decrypts/verifies signature to verify the token. Takes the content out and processes the token. It then can either provide access or reject.

Postgresql: error "must be owner of relation" when changing a owner object

From the fine manual.

You must own the table to use ALTER TABLE.

Or be a database superuser.

ERROR: must be owner of relation contact

PostgreSQL error messages are usually spot on. This one is spot on.

How can I see an the output of my C programs using Dev-C++?

For Dev-C++, the bits you need to add are:-

At the Beginning

#include <stdlib.h>

And at the point you want it to stop - i.e. before at the end of the program, but before the final }

system("PAUSE");

It will then ask you to "Press any key to continue..."

google chrome extension :: console.log() from background page?

To view console while debugging your chrome extension, you should use the chrome.extension.getBackgroundPage(); API, after that you can use console.log() as usual:

chrome.extension.getBackgroundPage().console.log('Testing');

This is good when you use multiple time, so for that you create custom function:

  const console = {
    log: (info) => chrome.extension.getBackgroundPage().console.log(info),
  };
  console.log("foo");

you only use console.log('learnin') everywhere

How to reset form body in bootstrap modal box?

Just find your form and clear before it opens!

    $modal = $('#modal');
    $modal.find('form')[0].reset();

Tkinter: How to use threads to preventing main event loop from "freezing"

I will submit the basis for an alternate solution. It is not specific to a Tk progress bar per se, but it can certainly be implemented very easily for that.

Here are some classes that allow you to run other tasks in the background of Tk, update the Tk controls when desired, and not lock up the gui!

Here's class TkRepeatingTask and BackgroundTask:

import threading

class TkRepeatingTask():

    def __init__( self, tkRoot, taskFuncPointer, freqencyMillis ):
        self.__tk_   = tkRoot
        self.__func_ = taskFuncPointer        
        self.__freq_ = freqencyMillis
        self.__isRunning_ = False

    def isRunning( self ) : return self.__isRunning_ 

    def start( self ) : 
        self.__isRunning_ = True
        self.__onTimer()

    def stop( self ) : self.__isRunning_ = False

    def __onTimer( self ): 
        if self.__isRunning_ :
            self.__func_() 
            self.__tk_.after( self.__freq_, self.__onTimer )

class BackgroundTask():

    def __init__( self, taskFuncPointer ):
        self.__taskFuncPointer_ = taskFuncPointer
        self.__workerThread_ = None
        self.__isRunning_ = False

    def taskFuncPointer( self ) : return self.__taskFuncPointer_

    def isRunning( self ) : 
        return self.__isRunning_ and self.__workerThread_.isAlive()

    def start( self ): 
        if not self.__isRunning_ :
            self.__isRunning_ = True
            self.__workerThread_ = self.WorkerThread( self )
            self.__workerThread_.start()

    def stop( self ) : self.__isRunning_ = False

    class WorkerThread( threading.Thread ):
        def __init__( self, bgTask ):      
            threading.Thread.__init__( self )
            self.__bgTask_ = bgTask

        def run( self ):
            try :
                self.__bgTask_.taskFuncPointer()( self.__bgTask_.isRunning )
            except Exception as e: print repr(e)
            self.__bgTask_.stop()

Here's a Tk test which demos the use of these. Just append this to the bottom of the module with those classes in it if you want to see the demo in action:

def tkThreadingTest():

    from tkinter import Tk, Label, Button, StringVar
    from time import sleep

    class UnitTestGUI:

        def __init__( self, master ):
            self.master = master
            master.title( "Threading Test" )

            self.testButton = Button( 
                self.master, text="Blocking", command=self.myLongProcess )
            self.testButton.pack()

            self.threadedButton = Button( 
                self.master, text="Threaded", command=self.onThreadedClicked )
            self.threadedButton.pack()

            self.cancelButton = Button( 
                self.master, text="Stop", command=self.onStopClicked )
            self.cancelButton.pack()

            self.statusLabelVar = StringVar()
            self.statusLabel = Label( master, textvariable=self.statusLabelVar )
            self.statusLabel.pack()

            self.clickMeButton = Button( 
                self.master, text="Click Me", command=self.onClickMeClicked )
            self.clickMeButton.pack()

            self.clickCountLabelVar = StringVar()            
            self.clickCountLabel = Label( master,  textvariable=self.clickCountLabelVar )
            self.clickCountLabel.pack()

            self.threadedButton = Button( 
                self.master, text="Timer", command=self.onTimerClicked )
            self.threadedButton.pack()

            self.timerCountLabelVar = StringVar()            
            self.timerCountLabel = Label( master,  textvariable=self.timerCountLabelVar )
            self.timerCountLabel.pack()

            self.timerCounter_=0

            self.clickCounter_=0

            self.bgTask = BackgroundTask( self.myLongProcess )

            self.timer = TkRepeatingTask( self.master, self.onTimer, 1 )

        def close( self ) :
            print "close"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass            
            self.master.quit()

        def onThreadedClicked( self ):
            print "onThreadedClicked"
            try: self.bgTask.start()
            except: pass

        def onTimerClicked( self ) :
            print "onTimerClicked"
            self.timer.start()

        def onStopClicked( self ) :
            print "onStopClicked"
            try: self.bgTask.stop()
            except: pass
            try: self.timer.stop()
            except: pass                        

        def onClickMeClicked( self ):
            print "onClickMeClicked"
            self.clickCounter_+=1
            self.clickCountLabelVar.set( str(self.clickCounter_) )

        def onTimer( self ) :
            print "onTimer"
            self.timerCounter_+=1
            self.timerCountLabelVar.set( str(self.timerCounter_) )

        def myLongProcess( self, isRunningFunc=None ) :
            print "starting myLongProcess"
            for i in range( 1, 10 ):
                try:
                    if not isRunningFunc() :
                        self.onMyLongProcessUpdate( "Stopped!" )
                        return
                except : pass   
                self.onMyLongProcessUpdate( i )
                sleep( 1.5 ) # simulate doing work
            self.onMyLongProcessUpdate( "Done!" )                

        def onMyLongProcessUpdate( self, status ) :
            print "Process Update: %s" % (status,)
            self.statusLabelVar.set( str(status) )

    root = Tk()    
    gui = UnitTestGUI( root )
    root.protocol( "WM_DELETE_WINDOW", gui.close )
    root.mainloop()

if __name__ == "__main__": 
    tkThreadingTest()

Two import points I'll stress about BackgroundTask:

1) The function you run in the background task needs to take a function pointer it will both invoke and respect, which allows the task to be cancelled mid way through - if possible.

2) You need to make sure the background task is stopped when you exit your application. That thread will still run even if your gui is closed if you don't address that!

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

Make install, but not to default directories?

I tried the above solutions. None worked.

In the end I opened Makefile file and manually changed prefix path to desired installation path like below.

PREFIX ?= "installation path"

When I tried --prefix, "make" complained that there is not such command input. However, perhaps some packages accepts --prefix which is of course a cleaner solution.

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

Android image caching

As Thunder Rabbit suggested, ImageDownloader is the best one for the job. I also found a slight variation of the class at:

http://theandroidcoder.com/utilities/android-image-download-and-caching/

The main difference between the two is that the ImageDownloader uses the Android caching system, and the modified one uses internal and external storage as caching, keeping the cached images indefinitely or until the user removes it manually. The author also mentions Android 2.1 compatibility.

Android Studio Checkout Github Error "CreateProcess=2" (Windows)

I faced same issue in android studio 3.2.1, solved the issue by setting git path in System Environment variable

C:\Program Files\Git\bin\,C:\Program Files\Git\bin\

And I imported the project once again and solved the issue!!!

Note : Check your android studio git settings has properly set the correct path to git.exe

enter image description here

How to display tables on mobile using Bootstrap?

All tables within bootstrap stretch according to the container they're in. You can put your tables inside a .span element to control the size. This SO Question may help you out

Why do Twitter Bootstrap tables always have 100% width?

PreparedStatement setNull(..)

but watch out for this....

Long nullLong = null;

preparedStatement.setLong( nullLong );

-thows null pointer exception-

because the protype is

setLong( long )   

NOT

setLong( Long )

nice one to catch you out eh.

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

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

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

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

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

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


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


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

Best way to check for null values in Java?

Your last proposal is the best.

if (foo != null && foo.bar()) {
    etc...
}

Because:

  1. It is easier to read.
  2. It is safe : foo.bar() will never be executed if foo == null.
  3. It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
  4. It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).

Finding the indices of matching elements in list in Python

if you're doing a lot of this kind of thing you should consider using numpy.

In [56]: import random, numpy

In [57]: lst = numpy.array([random.uniform(0, 5) for _ in range(1000)]) # example list

In [58]: a, b = 1, 3

In [59]: numpy.flatnonzero((lst > a) & (lst < b))[:10]
Out[59]: array([ 0, 12, 13, 15, 18, 19, 23, 24, 26, 29])

In response to Seanny123's question, I used this timing code:

import numpy, timeit, random

a, b = 1, 3

lst = numpy.array([random.uniform(0, 5) for _ in range(1000)])

def numpy_way():
    numpy.flatnonzero((lst > 1) & (lst < 3))[:10]

def list_comprehension():
    [e for e in lst if 1 < e < 3][:10]

print timeit.timeit(numpy_way)
print timeit.timeit(list_comprehension)

The numpy version is over 60 times faster.

jQuery click not working for dynamically created items

I faced this problem a few days ago - the solution for me was to use .bind() to bind the required function to the dynamically created link.

var catLink = $('<a href="#" id="' + i + '" class="lnkCat">' + category.category + '</a>');
catLink.bind("click", function(){
 $.categories.getSubCategories(this);
});

getSubCategories : function(obj) {
 //do something
}

I hope this helps.

Difference between socket and websocket?

Websockets use sockets in their implementation. Websockets are based on a standard protocol (now in final call, but not yet final) that defines a connection "handshake" and message "frame." The two sides go through the handshake procedure to mutually accept a connection and then use the standard message format ("frame") to pass messages back and forth.

I'm developing a framework that will allow you to communicate directly machine to machine with installed software. It might suit your purpose. You can follow my blog if you wish: http://highlevellogic.blogspot.com/2011/09/websocket-server-demonstration_26.html

Moment.js - tomorrow, today and yesterday

Here is how I do that using moment:

  let today = moment().format('DD MMMM YYYY');

  let tomorrow = moment().add(1, 'days').format('DD MMMM YYYY').toString();

  let yesterday = moment().subtract(1, 'days').startOf('day').format('DD MMMM YYYY').toString();

Remove '\' char from string c#

Trim only removes characters at the beginning and the end of the string, that's why your code doesn't quite work. You should use Replace instead:

line.Replace(@"\", string.Empty);

How to configure Docker port mapping to use Nginx as an upstream proxy?

Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.

How to clear browser cache with php?

header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Content-Type: application/xml; charset=utf-8");

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

Transfer data between iOS and Android via Bluetooth?

This question has been asked many times on this site and the definitive answer is: NO, you can't connect an Android phone to an iPhone over Bluetooth, and YES Apple has restrictions that prevent this.

Some possible alternatives:

  1. Bonjour over WiFi, as you mentioned. However, I couldn't find a comprehensive tutorial for it.
  2. Some internet based sync service, like Dropbox, Google Drive, Amazon S3. These usually have libraries for several platforms.
  3. Direct TCP/IP communication over sockets. (How to write a small (socket) server in iOS)
  4. Bluetooth Low Energy will be possible once the issues on the Android side are solved (Communicating between iOS and Android with Bluetooth LE)

Coolest alternative: use the Bump API. It has iOS and Android support and really easy to integrate. For small payloads this can be the most convenient solution.

Details on why you can't connect an arbitrary device to the iPhone. iOS allows only some bluetooth profiles to be used without the Made For iPhone (MFi) certification (HPF, A2DP, MAP...). The Serial Port Profile that you would require to implement the communication is bound to MFi membership. Membership to this program provides you to the MFi authentication module that has to be added to your hardware and takes care of authenticating the device towards the iPhone. Android phones don't have this module, so even though the physical connection may be possible to build up, the authentication step will fail. iPhone to iPhone communication is possible as both ends are able to authenticate themselves.

How to get base URL in Web API controller?

Url.Content("~/")

worked for me!

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

The culprit might lie in the fact that Global.asax has been placed in the wrong directory inside the mvc project. In my case it was placed under /Views but I had to move it should have been placed under the root folder of the project.

In your case you might be the exact opposite - run some tests and see for yourself.

https://stackoverflow.com/a/41467885/863651

Inserting a string into a list without getting split into characters

best put brackets around foo, and use +=

list+=['foo']

Calculate row means on subset of columns

(Another solution using pivot_longer & pivot_wider from latest Tidyr update)

You should try using pivot_longer to get your data from wide to long form Read latest tidyR update on pivot_longer & pivot_wider (https://tidyr.tidyverse.org/articles/pivot.html)

library(tidyverse)
C1<-c(3,2,4,4,5)
C2<-c(3,7,3,4,5)
C3<-c(5,4,3,6,3)
DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)

Output here

  ID     mean
  <fct> <dbl>
1 A      3.67
2 B      4.33
3 C      3.33
4 D      4.67
5 E      4.33

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

requestDispatcher - forward() method

  1. When we use the forward method, the request is transferred to another resource within the same server for further processing.

  2. In the case of forward, the web container handles all processing internally and the client or browser is not involved.

  3. When forward is called on the requestDispatcherobject, we pass the request and response objects, so our old request object is present on the new resource which is going to process our request.

  4. Visually, we are not able to see the forwarded address, it is transparent.

  5. Using the forward() method is faster than sendRedirect.

  6. When we redirect using forward, and we want to use the same data in a new resource, we can use request.setAttribute() as we have a request object available.

SendRedirect

  1. In case of sendRedirect, the request is transferred to another resource, to a different domain, or to a different server for further processing.

  2. When you use sendRedirect, the container transfers the request to the client or browser, so the URL given inside the sendRedirect method is visible as a new request to the client.

  3. In case of sendRedirect call, the old request and response objects are lost because it’s treated as new request by the browser.

  4. In the address bar, we are able to see the new redirected address. It’s not transparent.

  5. sendRedirect is slower because one extra round trip is required, because a completely new request is created and the old request object is lost. Two browser request are required.

  6. But in sendRedirect, if we want to use the same data for a new resource we have to store the data in session or pass along with the URL.

Which one is good?

Its depends upon the scenario for which method is more useful.

If you want control is transfer to new server or context, and it is treated as completely new task, then we go for sendRedirect. Generally, a forward should be used if the operation can be safely repeated upon a browser reload of the web page and will not affect the result.

Source

How can I convert a string to a number in Perl?

In comparisons it makes a difference if a scalar is a number of a string. And it is not always decidable. I can report a case where perl retrieved a float in "scientific" notation and used that same a few lines below in a comparison:

use strict;
....
next unless $line =~ /and your result is:\s*(.*)/;
my $val = $1;
if ($val < 0.001) {
   print "this is small\n";
}

And here $val was not interpreted as numeric for e.g. "2e-77" retrieved from $line. Adding 0 (or 0.0 for good ole C programmers) helped.

Environment variable substitution in sed

VAR=8675309
echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1' 

where VAR contains what you want to replace the field with

Convert Uri to String and String to Uri

I need to know way for converting uri to string and string to uri.

Use toString() to convert a Uri to a String. Use Uri.parse() to convert a String to a Uri.

this code doesn't work

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

Python decorators in classes

I have a Implementation of Decorators that Might Help

    import functools
    import datetime


    class Decorator(object):

        def __init__(self):
            pass


        def execution_time(func):

            @functools.wraps(func)
            def wrap(self, *args, **kwargs):

                """ Wrapper Function """

                start = datetime.datetime.now()
                Tem = func(self, *args, **kwargs)
                end = datetime.datetime.now()
                print("Exection Time:{}".format(end-start))
                return Tem

            return wrap


    class Test(Decorator):

        def __init__(self):
            self._MethodName = Test.funca.__name__

        @Decorator.execution_time
        def funca(self):
            print("Running Function : {}".format(self._MethodName))
            return True


    if __name__ == "__main__":
        obj = Test()
        data = obj.funca()
        print(data)

Automapper missing type map configuration or unsupported mapping - Error

Upgrade Automapper to version 6.2.2. It helped me

How does the "this" keyword work?

Here is one good source of this in JavaScript.

Here is the summary:

  • global this

    In a browser, at the global scope, this is the windowobject

    <script type="text/javascript">
      console.log(this === window); // true
      var foo = "bar";
      console.log(this.foo); // "bar"
      console.log(window.foo); // "bar"
    

    In node using the repl, this is the top namespace. You can refer to it as global.

    >this
      { ArrayBuffer: [Function: ArrayBuffer],
        Int8Array: { [Function: Int8Array] BYTES_PER_ELEMENT: 1 },
        Uint8Array: { [Function: Uint8Array] BYTES_PER_ELEMENT: 1 },
        ...
    >global === this
     true
    

    In node executing from a script, this at the global scope starts as an empty object. It is not the same as global

    \\test.js
    console.log(this);  \\ {}
    console.log(this === global); \\ fasle
    
  • function this

Except in the case of DOM event handlers or when a thisArg is provided (see further down), both in node and in a browser using this in a function that is not called with new references the global scope…

<script type="text/javascript">
    foo = "bar";

    function testThis() {
      this.foo = "foo";
    }

    console.log(this.foo); //logs "bar"
    testThis();
    console.log(this.foo); //logs "foo"
</script>

If you use use strict;, in which case this will be undefined

<script type="text/javascript">
    foo = "bar";

    function testThis() {
      "use strict";
      this.foo = "foo";
    }

    console.log(this.foo); //logs "bar"
    testThis();  //Uncaught TypeError: Cannot set property 'foo' of undefined 
</script>

If you call a function with new the this will be a new context, it will not reference the global this.

<script type="text/javascript">
    foo = "bar";

    function testThis() {
      this.foo = "foo";
    }

    console.log(this.foo); //logs "bar"
    new testThis();
    console.log(this.foo); //logs "bar"

    console.log(new testThis().foo); //logs "foo"
</script>
  • prototype this

Functions you create become function objects. They automatically get a special prototype property, which is something you can assign values to. When you create an instance by calling your function with new you get access to the values you assigned to the prototype property. You access those values using this.

function Thing() {
  console.log(this.foo);
}

Thing.prototype.foo = "bar";

var thing = new Thing(); //logs "bar"
console.log(thing.foo);  //logs "bar"

It is usually a mistake to assign arrays or objects on the prototype. If you want instances to each have their own arrays, create them in the function, not the prototype.

function Thing() {
    this.things = [];
}

var thing1 = new Thing();
var thing2 = new Thing();
thing1.things.push("foo");
console.log(thing1.things); //logs ["foo"]
console.log(thing2.things); //logs []
  • object this

You can use this in any function on an object to refer to other properties on that object. This is not the same as an instance created with new.

var obj = {
    foo: "bar",
    logFoo: function () {
        console.log(this.foo);
    }
};

obj.logFoo(); //logs "bar"
  • DOM event this

In an HTML DOM event handler, this is always a reference to the DOM element the event was attached to

function Listener() {
    document.getElementById("foo").addEventListener("click",
       this.handleClick);
}
Listener.prototype.handleClick = function (event) {
    console.log(this); //logs "<div id="foo"></div>"
}

var listener = new Listener();
document.getElementById("foo").click();

Unless you bind the context

function Listener() {
    document.getElementById("foo").addEventListener("click", 
        this.handleClick.bind(this));
}
Listener.prototype.handleClick = function (event) {
    console.log(this); //logs Listener {handleClick: function}
}

var listener = new Listener();
document.getElementById("foo").click();
  • HTML this

Inside HTML attributes in which you can put JavaScript, this is a reference to the element.

<div id="foo" onclick="console.log(this);"></div>
<script type="text/javascript">
document.getElementById("foo").click(); //logs <div id="foo"...
</script>
  • eval this

You can use eval to access this.

function Thing () {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
    eval("console.log(this.foo)"); //logs "bar"
}

var thing = new Thing();
thing.logFoo();
  • with this

You can use with to add this to the current scope to read and write to values on this without referring to this explicitly.

function Thing () {
}
Thing.prototype.foo = "bar";
Thing.prototype.logFoo = function () {
    with (this) {
        console.log(foo);
        foo = "foo";
    }
}

var thing = new Thing();
thing.logFoo(); // logs "bar"
console.log(thing.foo); // logs "foo"
  • jQuery this

the jQuery will in many places have this refer to a DOM element.

<div class="foo bar1"></div>
<div class="foo bar2"></div>
<script type="text/javascript">
$(".foo").each(function () {
    console.log(this); //logs <div class="foo...
});
$(".foo").on("click", function () {
    console.log(this); //logs <div class="foo...
});
$(".foo").each(function () {
    this.click();
});
</script>

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

Closing Applications

System.Windows.Forms.Application.Exit() - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed. This method stops all running message loops on all threads and closes all windows of the application. This method does not force the application to exit. The Exit() method is typically called from within a message loop, and forces Run() to return. To exit a message loop for the current thread only, call ExitThread(). This is the call to use if you are running a Windows Forms application. As a general guideline, use this call if you have called System.Windows.Forms.Application.Run().

System.Environment.Exit(exitCode) - Terminates this process and gives the underlying operating system the specified exit code. This call requires that you have SecurityPermissionFlag.UnmanagedCode permissions. If you do not, a SecurityException error occurs. This is the call to use if you are running a console application.

I hope it is best to use Application.Exit

See also these links:

How do you convert a jQuery object into a string?

With jQuery 1.6, this seems to be a more elegant solution:

$('#element-of-interest').prop('outerHTML');

What is cardinality in Databases?

A source of confusion may be the use of the word in two different contexts - data modelling and database query optimization.

In data modelling terms, cardinality is how one table relates to another.

  • 1-1 (one row in table A relates to one row in tableB)
  • 1-Many (one row in table A relates to many rows in tableB)
  • Many-Many (Many rows in table A relate to many rows in tableB)

There are also optional participation conditions to the above (where a row in one table doesn't have to relate to the other table at all).

See Wikipedia on Cardinality (data modelling).


When talking about database query optimization, cardinality refers to the data in a column of a table, specifically how many unique values are in it. This statistic helps with planning queries and optimizing the execution plans.

See Wikipedia on Cardinality (SQL statements).

Instagram: Share photo from webpage

Uploading on Instagram is possible. Their API provides a media upload endpoint, even if it's not documented.

POST https://instagram.com/api/v1/media/upload/

Check this code for example https://code.google.com/p/twitubas/source/browse/common/instagram.php

Oracle SQL: Update a table with data from another table

If your table t1 and it's backup t2 have many columns, here's a compact way to do it.

In addition, my related problem was that only some of the columns were modified and many rows had no edits to these columns, so I wanted to leave those alone - basically restore a subset of columns from a backup of the entire table. If you want to just restore all rows, skip the where clause.

Of course the simpler way would be to delete and insert as select, but in my case I needed a solution with just updates.

The trick is that when you do select * from a pair of tables with duplicate column names, the 2nd one will get named _1. So here's what I came up with:

  update (
    select * from t1 join t2 on t2.id = t1.id
    where id in (
      select id from (
        select id, col1, col2, ... from t2
        minus select id, col1, col2, ... from t1
      )
    )
  ) set col1=col1_1, col2=col2_1, ...

Java recursive Fibonacci sequence

Fibonacci series is one simple code that shows the power of dynamic programming. All we learned from school days is to run it via iterative or max recursive code. Recursive code works fine till 20 or so, if you give numbers bigger than that you will see it takes a lot of time to compute. In dynamic programming you can code as follows and it takes secs to compute the answer.

static double fib(int n) {
    if (n < 2)
        return n;
    if (fib[n] != 0)
        return fib[n];
    fib[n] = fib(n - 1) + fib(n - 2);
    return fib[n];
}

You store values in an array and proceed to fresh computation only when the array cannot provide you the answer.

How do I remove an item from a stl vector with a certain value?

If you want to do it without any extra includes:

vector<IComponent*> myComponents; //assume it has items in it already.
void RemoveComponent(IComponent* componentToRemove)
{
    IComponent* juggler;

    if (componentToRemove != NULL)
    {
        for (int currComponentIndex = 0; currComponentIndex < myComponents.size(); currComponentIndex++)
        {
            if (componentToRemove == myComponents[currComponentIndex])
            {
                //Since we don't care about order, swap with the last element, then delete it.
                juggler = myComponents[currComponentIndex];
                myComponents[currComponentIndex] = myComponents[myComponents.size() - 1];
                myComponents[myComponents.size() - 1] = juggler;

                //Remove it from memory and let the vector know too.
                myComponents.pop_back();
                delete juggler;
            }
        }
    }
}

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

You can use concat:

In [11]: pd.concat([df1['c'], df2['c']], axis=1, keys=['df1', 'df2'])
Out[11]: 
                 df1       df2
2014-01-01       NaN -0.978535
2014-01-02 -0.106510 -0.519239
2014-01-03 -0.846100 -0.313153
2014-01-04 -0.014253 -1.040702
2014-01-05  0.315156 -0.329967
2014-01-06 -0.510577 -0.940901
2014-01-07       NaN -0.024608
2014-01-08       NaN -1.791899

[8 rows x 2 columns]

The axis argument determines the way the DataFrames are stacked:

df1 = pd.DataFrame([1, 2, 3])
df2 = pd.DataFrame(['a', 'b', 'c'])

pd.concat([df1, df2], axis=0)
   0
0  1
1  2
2  3
0  a
1  b
2  c

pd.concat([df1, df2], axis=1)

   0  0
0  1  a
1  2  b
2  3  c

git-diff to ignore ^M

GitHub suggests that you should make sure to only use \n as a newline character in git-handled repos. There's an option to auto-convert:

$ git config --global core.autocrlf true

Of course, this is said to convert crlf to lf, while you want to convert cr to lf. I hope this still works …

And then convert your files:

# Remove everything from the index
$ git rm --cached -r .

# Re-add all the deleted files to the index
# You should get lots of messages like: "warning: CRLF will be replaced by LF in <file>."
$ git diff --cached --name-only -z | xargs -0 git add

# Commit
$ git commit -m "Fix CRLF"

core.autocrlf is described on the man page.

Getting a better understanding of callback functions in JavaScript

Callbacks are about signals and "new" is about creating object instances.

In this case it would be even more appropriate to execute just "callback();" than "return new callback()" because you aren't doing anything with a return value anyway.

(And the arguments.length==3 test is really clunky, fwiw, better to check that callback param exists and is a function.)

What are projection and selection?

Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).

In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.

Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:

Pointers in JavaScript?

Depending on what you would like to do, you could simply save the variable name, and then access it later on like so:

function toAccessMyVariable(variableName){
  alert(window[variableName]);
}

var myFavoriteNumber = 6; 

toAccessMyVariable("myFavoriteNumber");

To apply to your specific example, you could do something like this:

var x = 0;
var pointerToX = "x";

function a(variableName)
{
    window[variableName]++;
}
a(pointerToX);
alert(x); //Here I want to have 1 instead of 0

Multiple line code example in Javadoc comment

/**
 * <blockquote><pre>
 * {@code
 * public Foo(final Class<?> klass) {
 *     super();
 *     this.klass = klass;
 * }
 * }
 * </pre></blockquote>
 **/
  • <pre/> is required for preserving lines.
  • {@code must has its own line
  • <blockquote/> is just for indentation.
public Foo(final Class<?> klass) {
    super();
    this.klass = klass;
}


UPDATE with JDK8

The minimum requirements for proper codes are <pre/> and {@code}.

/**
 * test.
 *
 * <pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre>
 */

yields

 <T> void test(Class<? super T> type) {
     System.out.printf("hello, world\n");
 }

And an optional surrounding <blockquote/> inserts an indentation.

/**
 * test.
 *
 * <blockquote><pre>{@code
 * <T> void test(Class<? super T> type) {
 *     System.out.printf("hello, world\n");
 * }
 * }</pre></blockquote>
 */

yields

     <T> void test(Class<? super T> type) {
         System.out.printf("hello, world\n");
     }

Inserting <p> or surrounding with <p> and </p> yields warnings.

Synchronous request in Node.js

Using deferreds like Futures.

var sequence = Futures.sequence();

sequence
  .then(function(next) {
     http.get({}, next);
  })
  .then(function(next, res) {
     res.on("data", next);
  })
  .then(function(next, d) {
     http.get({}, next);
  })
  .then(function(next, res) {
    ...
  })

If you need to pass scope along then just do something like this

  .then(function(next, d) {
    http.get({}, function(res) {
      next(res, d);
    });
  })
  .then(function(next, res, d) { })
    ...
  })

Getting "TypeError: failed to fetch" when the request hasn't actually failed

I understand this question might have a React-specific cause, but it shows up first in search results for "Typeerror: Failed to fetch" and I wanted to lay out all possible causes here.

The Fetch spec lists times when you throw a TypeError from the Fetch API: https://fetch.spec.whatwg.org/#fetch-api

Relevant passages as of January 2021 are below. These are excerpts from the text.

4.6 HTTP-network fetch

To perform an HTTP-network fetch using request with an optional credentials flag, run these steps:
...
16. Run these steps in parallel:
...
2. If aborted, then:
...
3. Otherwise, if stream is readable, error stream with a TypeError.

To append a name/value name/value pair to a Headers object (headers), run these steps:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If headers’s guard is "immutable", then throw a TypeError.

Filling Headers object headers with a given object object:

To fill a Headers object headers with a given object object, run these steps:

  1. If object is a sequence, then for each header in object:
    1. If header does not contain exactly two items, then throw a TypeError.

Method steps sometimes throw TypeError:

The delete(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. If this’s guard is "immutable", then throw a TypeError.

The get(name) method steps are:

  1. If name is not a name, then throw a TypeError.
  2. Return the result of getting name from this’s header list.

The has(name) method steps are:

  1. If name is not a name, then throw a TypeError.

The set(name, value) method steps are:

  1. Normalize value.
  2. If name is not a name or value is not a value, then throw a TypeError.
  3. If this’s guard is "immutable", then throw a TypeError.

To extract a body and a Content-Type value from object, with an optional boolean keepalive (default false), run these steps:
...
5. Switch on object:
...
ReadableStream
If keepalive is true, then throw a TypeError.
If object is disturbed or locked, then throw a TypeError.

In the section "Body mixin" if you are using FormData there are several ways to throw a TypeError. I haven't listed them here because it would make this answer very long. Relevant passages: https://fetch.spec.whatwg.org/#body-mixin

In the section "Request Class" the new Request(input, init) constructor is a minefield of potential TypeErrors:

The new Request(input, init) constructor steps are:
...
6. If input is a string, then:
...
2. If parsedURL is a failure, then throw a TypeError.
3. IF parsedURL includes credentials, then throw a TypeError.
...
11. If init["window"] exists and is non-null, then throw a TypeError.
...
15. If init["referrer" exists, then:
...
1. Let referrer be init["referrer"].
2. If referrer is the empty string, then set request’s referrer to "no-referrer".
3. Otherwise:
1. Let parsedReferrer be the result of parsing referrer with baseURL.
2. If parsedReferrer is failure, then throw a TypeError.
...
18. If mode is "navigate", then throw a TypeError.
...
23. If request's cache mode is "only-if-cached" and request's mode is not "same-origin" then throw a TypeError.
...
27. If init["method"] exists, then:
...
2. If method is not a method or method is a forbidden method, then throw a TypeError.
...
32. If this’s request’s mode is "no-cors", then:
1. If this’s request’s method is not a CORS-safelisted method, then throw a TypeError.
...
35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is GET or HEAD, then throw a TypeError.
...
38. If body is non-null and body's source is null, then:
1. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
...
39. If inputBody is body and input is disturbed or locked, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In the Response class:

The new Response(body, init) constructor steps are:
...
2. If init["statusText"] does not match the reason-phrase token production, then throw a TypeError.
...
8. If body is non-null, then:
1. If init["status"] is a null body status, then throw a TypeError.
...

The static redirect(url, status) method steps are:
...
2. If parsedURL is failure, then throw a TypeError.

The clone() method steps are:

  1. If this is disturbed or locked, then throw a TypeError.

In section "The Fetch method"

The fetch(input, init) method steps are:
...
9. Run the following in parallel:
To process response for response, run these substeps:
...
3. If response is a network error, then reject p with a TypeError and terminate these substeps.

In addition to these potential problems, there are some browser-specific behaviors which can throw a TypeError. For instance, if you set keepalive to true and have a payload > 64 KB you'll get a TypeError on Chrome, but the same request can work in Firefox. These behaviors aren't documented in the spec, but you can find information about them by Googling for limitations for each option you're setting in fetch.

apt-get for Cygwin?

No. The only officially supported tool for downloading and updating Cygwin packages is the setup.exe file you used for the initial install, although that can be invoked with command line arguments to help the process.

From that same page:

The basic reason for not having a more full-featured package manager is that such a program would need full access to all of Cygwin's POSIX functionality. That is, however, difficult to provide in a Cygwin-free environment, such as exists on first installation. Additionally, Windows does not easily allow overwriting of in-use executables so installing a new version of the Cygwin DLL while a package manager is using the DLL is problematic.

Sum of Numbers C++

The loop is great; it's what's inside the loop that's wrong. You need a variable named sum, and at each step, add i+1 to sum. At the end of the loop, sum will have the right value, so print it.

Get the last insert id with doctrine 2?

You can access the id after calling the persist method of the entity manager.

$widgetEntity = new WidgetEntity();
$entityManager->persist($widgetEntity);
$entityManager->flush();
$widgetEntity->getId();

You do need to flush in order to get this id.

Syntax Error Fix: Added semi-colon after $entityManager->flush() is called.

Quicker way to get all unique values of a column in VBA?

PowerShell is a very powerful and efficient tool. This is cheating a little, but shelling PowerShell via VBA opens up lots of options

The bulk of the code below is simply to save the current sheet as a csv file. The output is another csv file with just the unique values

Sub AnotherWay()
Dim strPath As String
Dim strPath2 As String

Application.DisplayAlerts = False
strPath = "C:\Temp\test.csv"
strPath2 = "C:\Temp\testout.csv"
ActiveWorkbook.SaveAs strPath, xlCSV
x = Shell("powershell.exe $csv = import-csv -Path """ & strPath & """ -Header A | Select-Object -Unique A | Export-Csv """ & strPath2 & """ -NoTypeInformation", 0)
Application.DisplayAlerts = True

End Sub

What is the purpose of the word 'self'?

Let's say you have a class ClassA which contains a method methodA defined as:

def methodA(self, arg1, arg2):
    # do something

and ObjectA is an instance of this class.

Now when ObjectA.methodA(arg1, arg2) is called, python internally converts it for you as:

ClassA.methodA(ObjectA, arg1, arg2)

The self variable refers to the object itself.

Replace and overwrite instead of appending

Using truncate(), the solution could be

import re
#open the xml file for reading:
with open('path/test.xml','r+') as f:
    #convert to string:
    data = f.read()
    f.seek(0)
    f.write(re.sub(r"<string>ABC</string>(\s+)<string>(.*)</string>",r"<xyz>ABC</xyz>\1<xyz>\2</xyz>",data))
    f.truncate()

Python loop for inside lambda

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')

MySQL: Grant **all** privileges on database

Hello I used this code to have the super user in mysql

GRANT EXECUTE, PROCESS, SELECT, SHOW DATABASES, SHOW VIEW, ALTER, ALTER ROUTINE,
    CREATE, CREATE ROUTINE, CREATE TEMPORARY TABLES, CREATE VIEW, DELETE, DROP,
    EVENT, INDEX, INSERT, REFERENCES, TRIGGER, UPDATE, CREATE USER, FILE,
    LOCK TABLES, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHUTDOWN,
    SUPER
        ON *.* TO mysql@'%'
    WITH GRANT OPTION;

and then

FLUSH PRIVILEGES;

How can a Javascript object refer to values in itself?

Maybe you can think about removing the attribute to a function. I mean something like this:

_x000D_
_x000D_
var obj = {_x000D_
  key1: "it ",_x000D_
  key2: function() {_x000D_
    return this.key1 + " works!";_x000D_
  }_x000D_
};_x000D_
_x000D_
alert(obj.key2());
_x000D_
_x000D_
_x000D_

HttpClient.GetAsync(...) never returns when using await/async

In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also complete your 'await' gracefully.

public async Task<Stuff> GetStuff(string id)
{
    string path = $"/api/v2/stuff/{id}";
    try
    {
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.StatusCode == HttpStatusCode.OK)
        {
            string json = await response.Content.ReadAsStringAsync();
            return JsonUtility.FromJson<Stuff>(json);
        }
        else
        {
            Debug.LogError($"Could not retrieve stuff {id}");
        }
    }
    catch (Exception exception)
    {
        Debug.LogError($"Exception when retrieving stuff {exception}");
    }
    return null;
}

Embed YouTube Video with No Ads

If you play the video as a playlist and then single out that video you can get it without ads. Here is what I have done: https://www.youtube.com/v/VIDEO_ID?playlist=VIDEO_ID&autoplay=1&rel=0

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

Multiple try codes in one block

You can use fuckit module.
Wrap your code in a function with @fuckit decorator:

@fuckit
def func():
    code a
    code b #if b fails, it should ignore, and go to c.
    code c #if c fails, go to d
    code d

textarea character limit

Try using jQuery to avoid cross browser compatibility problems...

$("textarea").keyup(function(){
    if($(this).text().length > 500){
        var text = $(this).text();
        $(this).text(text.substr(0, 500));   
    }
});

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

Circular dependency in Spring

Circular dependency in Spring : Dependency of one Bean to other. Bean A ? Bean B ? Bean A

Solutions:

  1. Use @Lazy Annotation
  2. Redesign you class dependency
  3. Use Setter/Field Injection
  4. Use @PostConstruct Annotation

Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

AVG version 18.1.3044 (with Windows 10) interfer with my local Spring application.

Solution: enter in AVG section called "Web and email" and disable the "email protection". AVG block the certificate if the site isn't secure.

Compare two List<T> objects for equality, ignoring order

This worked for me:
If you are comparing two lists of objects depend upon single entity like ID, and you want a third list which matches that condition, then you can do the following:

var list3 = List1.Where(n => !List2.select(n1 => n1.Id).Contains(n.Id));

Refer: MSDN - C# Compare Two lists of objects

PHP import Excel into database (xls & xlsx)

If you can convert .xls to .csv before processing, you can use the query below to import the csv to the database:

load data local infile 'FILE.CSV' into table TABLENAME fields terminated by ',' enclosed by '"' lines terminated by '\n' (FIELD1,FIELD2,FIELD3)

Use string contains function in oracle SQL query

The answer of ADTC works fine, but I've find another solution, so I post it here if someone wants something different.

I think ADTC's solution is better, but mine's also works.

Here is the other solution I found

select p.name
from   person p
where  instr(p.name,chr(8211)) > 0; --contains the character chr(8211) 
                                    --at least 1 time

Thank you.

How do I check if a given string is a legal/valid file name under Windows?

One liner for verifying illigal chars in the string:

public static bool IsValidFilename(string testName) => !Regex.IsMatch(testName, "[" + Regex.Escape(new string(System.IO.Path.InvalidPathChars)) + "]");

How to make a radio button unchecked by clicking it?

If you are looking for solution in jQuery here it is. It is similar to this

_x000D_
_x000D_
    $('input:radio').click(function() { 
      let name = $(this).attr('name');
      let self = $(this);
      [].filter.call($(`input[name=${name}]`), function(ele){
        return self[0] !== $(ele)[0];
      }).forEach(function(otherEle){
        $(otherEle).removeAttr('data-check');
      });

      if($(this).attr('data-check')){
        $(this).prop("checked", false);
        $(this).removeAttr('data-check');
      }else{
        $(this).attr("data-check", "1");
      }
    });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input class="radio" name="A" type="radio">A
  <input class="radio" name="A" type="radio">B
  <input class="radio" name="A" type="radio">C
</form>

<form>
  <input class="radio" name="B" type="radio">D
  <input class="radio" name="B" type="radio">E
  <input class="radio" name="B" type="radio">F
</form>

<form>
  <input class="radio" name="C" type="radio">G
  <input class="radio" name="C" type="radio">H
  <input class="radio" name="C" type="radio">I
</form>
_x000D_
_x000D_
_x000D_

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

In my own case I have the following error

Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='

$this->db->select("users.username as matric_no, CONCAT(users.surname, ' ', users.first_name, ' ', users.last_name) as fullname") ->join('users', 'users.username=classroom_students.matric_no', 'left') ->where('classroom_students.session_id', $session) ->where('classroom_students.level_id', $level) ->where('classroom_students.dept_id', $dept);

After weeks of google searching I noticed that the two fields I am comparing consists of different collation name. The first one i.e username is of utf8_general_ci while the second one is of utf8_unicode_ci so I went back to the structure of the second table and changed the second field (matric_no) to utf8_general_ci and it worked like a charm.

How to make the Facebook Like Box responsive?

NOTE: Colin's solution didn't work for me. Facebook may have changed their markup. Using * should be more future-proof.

Wrap the Like box with a div:

<div id="likebox-wrapper">
    <iframe src="..."></iframe> <!-- likebox code -->
</div>

and add this to your css file:

#likebox-wrapper * {
   width: 100% !important;
}

CSS: Truncate table cells, but fit as much as possible

<table border="1" style="width: 100%;">
    <colgroup>
        <col width="100%" />
        <col width="0%" />
    </colgroup>
    <tr>
        <td style="white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:1px;">This cell has more content.This cell has more content.This cell has more content.This cell has more content.This cell has more content.This cell has more content.</td>
        <td style="white-space: nowrap;">Less content here.</td>
    </tr>
</table>

http://jsfiddle.net/7CURQ/

How do I count occurrence of duplicate items in array

array_count_values, enjoy :-)

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);
$vals = array_count_values($array);
echo 'No. of NON Duplicate Items: '.count($vals).'<br><br>';
print_r($vals);

Result:

No. of NON Duplicate Items: 7
Array
(
    [12] => 1
    [43] => 6
    [66] => 1
    [21] => 2
    [56] => 1
    [78] => 2
    [100] => 1
)

How can I generate a list of files with their absolute path in Linux?

Recursive files can be listed by many ways in Linux. Here I am sharing one liner script to clear all logs of files(only files) from /var/log/ directory and second check recently which logs file has made an entry.

First:

find /var/log/ -type f  #listing file recursively 

Second:

for i in $(find $PWD -type f) ; do cat /dev/null > "$i" ; done #empty files recursively 

Third use:

ls -ltr $(find /var/log/ -type f ) # listing file used in recent

Note: for directory location you can also pass $PWD instead of /var/log.

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

Apple Mach-O Linker Error when compiling for device

Try to clean your project, and Compile.

jQuery fade out then fade in

fade the other in in the callback of fadeout, which runs when fadeout is done. Using your code:

$('#two, #three').hide();
$('.slide').click(function(){
    var $this = $(this);
    $this.fadeOut(function(){ $this.next().fadeIn(); });
});

alternatively, you can just "pause" the chain, but you need to specify for how long:

$(this).fadeOut().next().delay(500).fadeIn();

Add centered text to the middle of a <hr/>-like line

Responsive, transparent background, variable height and style of divider, variable position of text, adjustable distance between divider and text. Can also be applied multiple times with different selectors for multiple divider styles in same project.
SCSS below.

Markup (HTML):

<div class="divider" text-position="right">Divider</div>

CSS:

.divider {
  display: flex;
  align-items: center;
  padding: 0 1rem;
}

.divider:before,
.divider:after {
  content: '';
  flex: 0 1 100%;
  border-bottom: 5px dotted #ccc;
  margin: 0 1rem;
}

.divider:before {
  margin-left: 0;
}

.divider:after {
  margin-right: 0;
}

.divider[text-position="right"]:after,
.divider[text-position="left"]:before {
  content: none;
}

Without text-position it defaults to center.

Demo:

_x000D_
_x000D_
.divider {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  padding: 0 1rem;_x000D_
}_x000D_
_x000D_
.divider:before,_x000D_
.divider:after {_x000D_
  content: '';_x000D_
  flex: 0 1 100%;_x000D_
  border-bottom: 5px dotted #ccc;_x000D_
  margin: 0 1rem;_x000D_
}_x000D_
_x000D_
.divider:before {_x000D_
  margin-left: 0;_x000D_
}_x000D_
_x000D_
.divider:after {_x000D_
  margin-right: 0;_x000D_
}_x000D_
_x000D_
.divider[text-position="right"]:after,_x000D_
.divider[text-position="left"]:before {_x000D_
  content: none;_x000D_
}
_x000D_
<span class="divider" text-position="left">Divider</span>_x000D_
<h2 class="divider">Divider</h2>_x000D_
<div class="divider" text-position="right">Divider</div>
_x000D_
_x000D_
_x000D_

And SCSS, to modify it quickly:

$divider-selector    : ".divider";
$divider-border-color: rgba(0,0,0,.21);
$divider-padding     : 1rem;
$divider-border-width: 1px;
$divider-border-style: solid;
$divider-max-width   : 100%;

#{$divider-selector} {
    display: flex;
    align-items: center;
    padding: 0 $divider-padding;
    max-width: $divider-max-width;
    margin-left: auto;
    margin-right: auto;

    &:before,
    &:after {
        content: '';
        flex: 0 1 100%;
        border-bottom: $divider-border-width $divider-border-style $divider-border-color;
        margin: 0 $divider-padding;
        transform: translateY(#{$divider-border-width} / 2)
    }

    &:before {
        margin-left: 0;
    }

    &:after {
        margin-right: 0;
    }

    &[text-position="right"]:after,
    &[text-position="left"]:before {
        content: none;
    }
}

fiddle here.

What is the difference between require() and library()?

Always use library. Never use require.

In a nutshell, this is because, when using require, your code might yield different, erroneous results, without signalling an error. This is rare but not hypothetical! Consider this code, which yields different results depending on whether {dplyr} can be loaded:

require(dplyr)

x = data.frame(y = seq(100))
y = 1
filter(x, y == 1)

This can lead to subtly wrong results. Using library instead of require throws an error here, signalling clearly that something is wrong. This is good.

It also makes debugging all other failures more difficult: If you require a package at the start of your script and use its exports in line 500, you’ll get an error message “object ‘foo’ not found” in line 500, rather than an error “there is no package called ‘bla’”.

The only acceptable use case of require is when its return value is immediately checked, as some of the other answers show. This is a fairly common pattern but even in these cases it is better (and recommended, see below) to instead separate the existence check and the loading of the package. That is: use requireNamespace instead of require in these cases.

More technically, require actually calls library internally (if the package wasn’t already attached — require thus performs a redundant check, because library also checks whether the package was already loaded). Here’s a simplified implementation of require to illustrate what it does:

require = function (package) {
    already_attached = paste('package:', package) %in% search()
    if (already_attached) return(TRUE)
    maybe_error = try(library(package, character.only = TRUE)) 
    success = ! inherits(maybe_error, 'try-error')
    if (! success) cat("Failed")
    success
}

Experienced R developers agree:

Yihui Xie, author of {knitr}, {bookdown} and many other packages says:

Ladies and gentlemen, I've said this before: require() is the wrong way to load an R package; use library() instead

Hadley Wickham, author of more popular R packages than anybody else, says

Use library(x) in data analysis scripts. […] You never need to use require() (requireNamespace() is almost always better)

How to find foreign key dependencies in SQL Server?

USE information_schema;

SELECT COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME
FROM KEY_COLUMN_USAGE
WHERE (table_name = *tablename*) AND NOT (REFERENCED_TABLE_NAME IS NULL)

How do I generate a random int number?

I wanted to demonstrate what happens when a new random generator is used every time. Suppose you have two methods or two classes each requiring a random number. And naively you code them like:

public class A
{
    public A()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        var rnd=new Random();
        ID=rnd.Next();
    }
    public int ID { get; private set; }
}

Do you think you will get two different IDs? NOPE

class Program
{
    static void Main(string[] args)
    {
        A a=new A();
        B b=new B();

        int ida=a.ID, idb=b.ID;
        // ida = 1452879101
        // idb = 1452879101
    }
}

The solution is to always use a single static random generator. Like this:

public static class Utils
{
    public static readonly Random random=new Random();
}

public class A
{
    public A()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}
public class B
{
    public B()
    {
        ID=Utils.random.Next();
    }
    public int ID { get; private set; }
}

How to call Makefile from another Makefile?

http://www.gnu.org/software/make/manual/make.html#Recursion

 subsystem:
         cd subdir && $(MAKE)

or, equivalently, this :

 subsystem:
         $(MAKE) -C subdir

What are functional interfaces used for in Java 8?

The documentation makes indeed a difference between the purpose

An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface as defined by the Java Language Specification.

and the use case

Note that instances of functional interfaces can be created with lambda expressions, method references, or constructor references.

whose wording does not preclude other use cases in general. Since the primary purpose is to indicate a functional interface, your actual question boils down to “Are there other use cases for functional interfaces other than lambda expressions and method/constructor references?”

Since functional interface is a Java language construct defined by the Java Language Specification, only that specification can answer that question:

JLS §9.8. Functional Interfaces:

In addition to the usual process of creating an interface instance by declaring and instantiating a class (§15.9), instances of functional interfaces can be created with method reference expressions and lambda expressions (§15.13, §15.27).

So the Java Language Specification doesn’t say otherwise, the only use case mentioned in that section is that of creating interface instances with method reference expressions and lambda expressions. (This includes constructor references as they are noted as one form of method reference expression in the specification).

So in one sentence, no, there is no other use case for it in Java 8.

React js change child component's state from parent component

You can use the createRef to change the state of the child component from the parent component. Here are all the steps.

  1. Create a method to change the state in the child component.

    2 - Create a reference for the child component in parent component using React.createRef().

    3 - Attach reference with the child component using ref={}.

    4 - Call the child component method using this.yor-reference.current.method.

Parent component


class ParentComponent extends Component {
constructor()
{
this.changeChild=React.createRef()
}
  render() {
    return (
      <div>
        <button onClick={this.changeChild.current.toggleMenu()}>
          Toggle Menu from Parent
        </button>
        <ChildComponent ref={this.changeChild} />
      </div>
    );
  }
}

Child Component


class ChildComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      open: false;
    }
  }

  toggleMenu=() => {
    this.setState({
      open: !this.state.open
    });
  }

  render() {
    return (
      <Drawer open={this.state.open}/>
    );
  }
}



Base64 PNG data to HTML5 canvas

Jerryf's answer is fine, except for one flaw.

The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.

(Like Totty.js pointed out.)

var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");

var image = new Image();
image.onload = function() {
    ctx.drawImage(image, 0, 0);
};
image.src = "data:image/  png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

database_password: password would between quotes: " or '.

like so:

database_password: "password"

What is the difference between json.load() and json.loads() functions

Documentation is quite clear: https://docs.python.org/2/library/json.html

json.load(fp[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize fp (a .read()-supporting file-like object containing a JSON document) to a Python object using this conversion table.

json.loads(s[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]])

Deserialize s (a str or unicode instance containing a JSON document) to a Python object using this conversion table.

So load is for a file, loads for a string

Converting java.util.Properties to HashMap<String,String>

this is only because the constructor of HashMap requires an arg of Map generic type and Properties implements Map.

This will work, though with a warning

    Properties properties = new Properties();
    Map<String, String> map = new HashMap(properties);

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

Pagination using MySQL LIMIT, OFFSET

If you want to keep it simple go ahead and try this out.

$page_number = mysqli_escape_string($con, $_GET['page']);
$count_per_page = 20;
$next_offset = $page_number * $count_per_page;
$cat =mysqli_query($con, "SELECT * FROM categories LIMIT $count_per_page OFFSET $next_offset");
while ($row = mysqli_fetch_array($cat))
        $count = $row[0];

The rest is up to you. If you have result comming from two tables i suggest you try a different approach.

In plain English, what does "git reset" do?

Checkout points the head at a specific commit.

Reset points a branch at a specific commit. (A branch is a pointer to a commit.)

Incidentally, if your head doesn’t point to a commit that’s also pointed to by a branch then you have a detached head. (turned out to be wrong. See comments...)

display HTML page after loading complete

Hide the body initially, and then show it with jQuery after it has loaded.

body {
    display: none;
}

$(function () {
    $('body').show();
}); // end ready

Also, it would be best to have $('body').show(); as the last line in your last and main .js file.

How do I run pip on python for windows?

First go to the pip documentation if not install before: http://pip.readthedocs.org/en/stable/installing/

and follow the install pip which is first download get-pip.py from https://bootstrap.pypa.io/get-pip.py

Then run the following (which may require administrator access): python get-pip.py

Spring - applicationContext.xml cannot be opened because it does not exist

You should keep your Spring files in another folder, marked as "source" (just like "src" or "resources").

WEB-INF is not a source folder, therefore it will not be included in the classpath (i.e. JUnit will not look for anything there).

Enter key pressed event handler

For those who struggle at capturing Enter key on TextBox or other input control, if your Form has AcceptButton defined, you will not be able to use KeyDown event to capture Enter.

What you should do is to catch the Enter key at form level. Add this code to the form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
    {
        //do something
        return true;
    }
    else
    {
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

Getting HTTP code in PHP using curl

Here is my solution need get Status Http for checking status of server regularly

$url = 'http://www.example.com'; // Your server link

while(true) {

    $strHeader = get_headers($url)[0];

    $statusCode = substr($strHeader, 9, 3 );

    if($statusCode != 200 ) {
        echo 'Server down.';
        // Send email 
    }
    else {
        echo 'oK';
    }

    sleep(30);
}

Which rows are returned when using LIMIT with OFFSET in MySQL?

OFFSET is nothing but a keyword to indicate starting cursor in table

SELECT column FROM table LIMIT 18 OFFSET 8 -- fetch 18 records, begin with record 9 (OFFSET 8)

you would get the same result form

SELECT column FROM table LIMIT 8, 18

visual representation (R is one record in the table in some order)

 OFFSET        LIMIT          rest of the table
 __||__   _______||_______   __||__
/      \ /                \ /
RRRRRRRR RRRRRRRRRRRRRRRRRR RRRR...
         \________________/
                 ||
             your result

What's the difference between process.cwd() vs __dirname?

Knowing the scope of each can make things easier to remember.

process is node's global object, and .cwd() returns where node is running.

__dirname is module's property, and represents the file path of the module. In node, one module resides in one file.

Similarly, __filename is another module's property, which holds the file name of the module.

How to specify the bottom border of a <tr>?

Add border-collapse:collapse to the table.

Example:

table.myTable{
  border-collapse:collapse;
}

table.myTable tr{
  border:1px solid red;
}

This worked for me.

CSS grid wrapping

Use either auto-fill or auto-fit as the first argument of the repeat() notation.

<auto-repeat> variant of the repeat() notation:

repeat( [ auto-fill | auto-fit ] , [ <line-names>? <fixed-size> ]+ <line-names>? )

auto-fill

When auto-fill is given as the repetition number, if the grid container has a definite size or max size in the relevant axis, then the number of repetitions is the largest possible positive integer that does not cause the grid to overflow its grid container.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fill

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

The grid will repeat as many tracks as possible without overflowing its container.

Using auto-fill as the repetition number of the repeat() notation

In this case, given the example above (see image), only 5 tracks can fit the grid-container without overflowing. There are only 4 items in our grid, so a fifth one is created as an empty track within the remaining space.

The rest of the remaining space, track #6, ends the explicit grid. This means there was not enough space to place another track.


auto-fit

The auto-fit keyword behaves the same as auto-fill, except that after grid item placement any empty repeated tracks are collapsed.

https://www.w3.org/TR/css-grid-1/#valdef-repeat-auto-fit

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, 186px);
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

The grid will still repeat as many tracks as possible without overflowing its container, but the empty tracks will be collapsed to 0.

A collapsed track is treated as having a fixed track sizing function of 0px.

Using auto-fit as the repetition number of the repeat() notation

Unlike the auto-fill image example, the empty fifth track is collapsed, ending the explicit grid right after the 4th item.


auto-fill vs auto-fit

The difference between the two is noticeable when the minmax() function is used.

Use minmax(186px, 1fr) to range the items from 186px to a fraction of the leftover space in the grid container.

When using auto-fill, the items will grow once there is no space to place empty tracks.

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_

When using auto-fit, the items will grow to fill the remaining space because all the empty tracks will be collapsed to 0px.

_x000D_
_x000D_
.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(186px, 1fr));
}

.grid>* {
  background-color: green;
  height: 200px;
}
_x000D_
<div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div>
_x000D_
_x000D_
_x000D_


Playground:

CodePen

Inspecting auto-fill tracks

auto-fill


Inspecting auto-fit tracks

auto-fit

String concatenation in MySQL

MySQL is different from most DBMSs use of + or || for concatenation. It uses the CONCAT function:

SELECT CONCAT(first_name, " ", last_name) AS Name FROM test.student

As @eggyal pointed out in comments, you can enable string concatenation with the || operator in MySQL by setting the PIPES_AS_CONCAT SQL mode.

How do I print a datetime in the local timezone?

This script demonstrates a few ways to show the local timezone using astimezone():

#!/usr/bin/env python3

import pytz
from datetime import datetime, timezone
from tzlocal import get_localzone

utc_dt = datetime.now(timezone.utc)

PST = pytz.timezone('US/Pacific')
EST = pytz.timezone('US/Eastern')
JST = pytz.timezone('Asia/Tokyo')
NZST = pytz.timezone('Pacific/Auckland')

print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Eastern time {}".format(utc_dt.astimezone(EST).isoformat()))
print("UTC time     {}".format(utc_dt.isoformat()))
print("Japan time   {}".format(utc_dt.astimezone(JST).isoformat()))

# Use astimezone() without an argument
print("Local time   {}".format(utc_dt.astimezone().isoformat()))

# Use tzlocal get_localzone
print("Local time   {}".format(utc_dt.astimezone(get_localzone()).isoformat()))

# Explicitly create a pytz timezone object
# Substitute a pytz.timezone object for your timezone
print("Local time   {}".format(utc_dt.astimezone(NZST).isoformat()))

It outputs the following:

$ ./timezones.py 
Pacific time 2019-02-22T17:54:14.957299-08:00
Eastern time 2019-02-22T20:54:14.957299-05:00
UTC time     2019-02-23T01:54:14.957299+00:00
Japan time   2019-02-23T10:54:14.957299+09:00
Local time   2019-02-23T14:54:14.957299+13:00
Local time   2019-02-23T14:54:14.957299+13:00
Local time   2019-02-23T14:54:14.957299+13:00

As of python 3.6 calling astimezone() without a timezone object defaults to the local zone (docs). This means you don't need to import tzlocal and can simply do the following:

#!/usr/bin/env python3

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc)

print("Local time {}".format(utc_dt.astimezone().isoformat()))

How to get the difference between two dictionaries in Python?

What about this? Not as pretty but explicit.

orig_dict = {'a' : 1, 'b' : 2}
new_dict = {'a' : 2, 'v' : 'hello', 'b' : 2}

updates = {}
for k2, v2 in new_dict.items():
    if k2 in orig_dict:    
        if v2 != orig_dict[k2]:
            updates.update({k2 : v2})
    else:
        updates.update({k2 : v2})

#test it
#value of 'a' was changed
#'v' is a completely new entry
assert all(k in updates for k in ['a', 'v'])

.htaccess or .htpasswd equivalent on IIS?

This is the documentation that you want: http://msdn.microsoft.com/en-us/library/aa292114(VS.71).aspx

I guess the answer is, yes, there is an equivalent that will accomplish the same thing, integrated with Windows security.

Convert floats to ints in Pandas?

Expanding on @Ryan G mentioned usage of the pandas.DataFrame.astype(<type>) method, one can use the errors=ignore argument to only convert those columns that do not produce an error, which notably simplifies the syntax. Obviously, caution should be applied when ignoring errors, but for this task it comes very handy.

>>> df = pd.DataFrame(np.random.rand(3, 4), columns=list('ABCD'))
>>> df *= 10
>>> print(df)
...           A       B       C       D
... 0   2.16861 8.34139 1.83434 6.91706
... 1   5.85938 9.71712 5.53371 4.26542
... 2   0.50112 4.06725 1.99795 4.75698

>>> df['E'] = list('XYZ')
>>> df.astype(int, errors='ignore')
>>> print(df)
...     A   B   C   D   E
... 0   2   8   1   6   X
... 1   5   9   5   4   Y
... 2   0   4   1   4   Z

From pandas.DataFrame.astype docs:

errors : {‘raise’, ‘ignore’}, default ‘raise’

Control raising of exceptions on invalid data for provided dtype.

  • raise : allow exceptions to be raised
  • ignore : suppress exceptions. On error return original object

New in version 0.20.0.

DateTime.TryParse issue with dates of yyyy-dd-MM format

From DateTime on msdn:

Type: System.DateTime% When this method returns, contains the DateTime value equivalent to the date and time contained in s, if the conversion succeeded, or MinValue if the conversion failed. The conversion fails if the s parameter is null, is an empty string (""), or does not contain a valid string representation of a date and time. This parameter is passed uninitialized.

Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.

How to create .pfx file from certificate and private key?

For pfx files from SSL for Free I find this https://decoder.link/converter easiest.

Simply make sure PEM -> PKCS#12 is selected, then upload the certificate, ca_bundle and key files and convert.

Remember the password, then upload with the password you used and add bindings.

Where do you include the jQuery library from? Google JSAPI? CDN?

Pros: Host on Google has benefits

  • Probably faster (their servers are more optimised)
  • They handle the caching correctly - 1 year (we struggle to be allowed to make the changes to get the headers right on our servers)
  • Users who have already had a link to the Google-hosted version on another domain already have the file in their cache

Cons:

  • Some browsers may see it as XSS cross-domain and disallow the file.
  • Particularly users running the NoScript plugin for Firefox

I wonder if you can INCLUDE from Google, and then check the presence of some Global variable, or somesuch, and if absence load from your server?