Programs & Examples On #Wtai

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

I normally use this statement:

ALTER TABLE `table_name`
  CHANGE COLUMN `col_name` `col_name` VARCHAR(10000);

But, I think SET will work too, never have tried it. :)

Convert String to Date in MS Access Query

cdate(Format([Datum im Format DDMMYYYY],'##/##/####') ) 

converts string without punctuation characters into date

What is deserialize and serialize in JSON?

In the context of data storage, serialization (or serialisation) is the process of translating data structures or object state into a format that can be stored (for example, in a file or memory buffer) or transmitted (for example, across a network connection link) and reconstructed later. [...]
The opposite operation, extracting a data structure from a series of bytes, is deserialization. From Wikipedia

In Python "serialization" does nothing else than just converting the given data structure (e.g. a dict) into its valid JSON pendant (object).

  • Python's True will be converted to JSONs true and the dictionary itself will then be encapsulated in quotes.
  • You can easily spot the difference between a Python dictionary and JSON by their Boolean values:
    • Python: True / False,
    • JSON: true / false
  • Python builtin module json is the standard way to do serialization:

Code example:

data = {
    "president": {
        "name": "Zaphod Beeblebrox",
        "species": "Betelgeusian",
        "male": True,
    }
}

import json
json_data = json.dumps(data, indent=2) # serialize
restored_data = json.loads(json_data) # deserialize

# serialized json_data now looks like:
# {
#   "president": {
#     "name": "Zaphod Beeblebrox",
#     "species": "Betelgeusian",
#     "male": true
#   }
# }

Source: realpython.com

HTTP GET request in JavaScript?

Short and clean:

_x000D_
_x000D_
const http = new XMLHttpRequest()_x000D_
_x000D_
http.open("GET", "https://api.lyrics.ovh/v1/toto/africa")_x000D_
http.send()_x000D_
_x000D_
http.onload = () => console.log(http.responseText)
_x000D_
_x000D_
_x000D_

Find unused npm packages in package.json

fiskeben wrote:

The downside is that it's not fully automatic, i.e. it doesn't extract package names from package.json and check them. You need to do this for each package yourself.

Let's make Fiskeben's answer automated if for whatever reason depcheck is not working properly! (E.g. I tried it with Typescript and it gave unnecessary parsing errors)

For parsing package.json we can use the software jq. The below shell script requires a directory name where to start.

#!/bin/bash
DIRNAME=${1:-.}
cd $DIRNAME

FILES=$(mktemp)
PACKAGES=$(mktemp)

find . \
    -path ./node_modules -prune -or \
    -path ./build -prune -or \
    \( -name "*.ts" -or -name "*.js" -or -name "*.json" \) -print > $FILES

function check {
    cat package.json \
        | jq "{} + .$1 | keys" \
        | sed -n 's/.*"\(.*\)".*/\1/p' > $PACKAGES

    echo "--------------------------"
    echo "Checking $1..."
    while read PACKAGE
    do
        RES=$(cat $FILES | xargs -I {} egrep -i "(import|require).*['\"]$PACKAGE[\"']" '{}' | wc -l)
        if [ $RES = 0 ]
        then
            echo -e "UNUSED\t\t $PACKAGE"
        else
            echo -e "USED ($RES)\t $PACKAGE"
        fi
    done < $PACKAGES
}

check "dependencies"
check "devDependencies"
check "peerDependencies"

First it creates two temporary files where we can cache package names and files.

It starts with the find command. The first and second line make it ignore the node_modules and build folders (or whatever you want). The third line contains allowed extensions, you can add more here e.g. JSX or JSON files.

A function will read dependendy types.

First it cats the package.json. Then, jq gets the required dependency group. ({} + is there so that it won't throw an error if e.g. there are no peer dependencies in the file.)

After that, sed extracts the parts between the quotes, the package name. -n and .../p tells it to print the matching parts and nothing else from jq's JSON output. Then we read this list of package names into a while loop.

RES is the number of occurrences of the package name in quotes. Right now it's import/require ... 'package'/"package". It does the job for most cases.

Then we simply count the number of result lines then print the result.

Caveats:

  • Won't find files in different imports e.g. tsconfig.json files (lib option)
  • You have to grep manually for only ^USED and UNUSED files.
  • It's slow for large projects - shell scripts often don't scale well. But hopefully you won't be running this many times.

Uncaught TypeError: Cannot read property 'split' of undefined

ogdate is itself a string, why are you trying to access it's value property that it doesn't have ?

console.log(og_date.split('-'));

JSFiddle

Best way in asp.net to force https for an entire site?

If you are unable to set this up in IIS for whatever reason, I'd make an HTTP module that does the redirect for you:

using System;
using System.Web;

namespace HttpsOnly
{
    /// <summary>
    /// Redirects the Request to HTTPS if it comes in on an insecure channel.
    /// </summary>
    public class HttpsOnlyModule : IHttpModule
    {
        public void Init(HttpApplication app)
        {
            // Note we cannot trust IsSecureConnection when 
            // in a webfarm, because usually only the load balancer 
            // will come in on a secure port the request will be then 
            // internally redirected to local machine on a specified port.

            // Move this to a config file, if your behind a farm, 
            // set this to the local port used internally.
            int specialPort = 443;

            if (!app.Context.Request.IsSecureConnection 
               || app.Context.Request.Url.Port != specialPort)
            {
               app.Context.Response.Redirect("https://" 
                  + app.Context.Request.ServerVariables["HTTP_HOST"] 
                  + app.Context.Request.RawUrl);    
            }
        }

        public void Dispose()
        {
            // Needed for IHttpModule
        }
    }
}

Then just compile it to a DLL, add it as a reference to your project and place this in web.config:

 <httpModules>
      <add name="HttpsOnlyModule" type="HttpsOnly.HttpsOnlyModule, HttpsOnly" />
 </httpModules>

Sorting by date & time in descending order?

I used a simpler solution found partly here:
How to sort details with Date and time in sql server ?
I used this query to get my results:

SELECT TOP (5) * FROM My_Table_Name WHERE id=WhateverValueINeed ORDER BY DateTimeColumnName DESC

This is more straight forward and worked for me.

Notice: the column of the Date has the "datetime" type

C# send a simple SSH command

I used SSH.Net in a project a while ago and was very happy with it. It also comes with a good documentation with lots of samples on how to use it.

The original package website can be still found here, including the documentation (which currently isn't available on GitHub).

For your case the code would be something like this.

using (var client = new SshClient("hostnameOrIp", "username", "password"))
{
    client.Connect();
    client.RunCommand("etc/init.d/networking restart");
    client.Disconnect();
}

What's the simplest way to print a Java array?

In java 8 it is easy. there are two keywords

  1. stream: Arrays.stream(intArray).forEach
  2. method reference: ::println

    int[] intArray = new int[] {1, 2, 3, 4, 5};
    Arrays.stream(intArray).forEach(System.out::println);
    

If you want to print all elements in the array in the same line, then just use print instead of println i.e.

int[] intArray = new int[] {1, 2, 3, 4, 5};
Arrays.stream(intArray).forEach(System.out::print);

Another way without method reference just use:

int[] intArray = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(intArray));

How to create a printable Twitter-Bootstrap page

Bootstrap 3.2 update: (current release)

Current stable Bootstrap version is 3.2.0.
With version 3.2 visible-print deprecated, so you should use like this:

Class                        Browser    Print
 -------------------------------------------------
.visible-print-block         Hidden        Visible (as block)
.visible-print-inline        Hidden        Visible (as inline)
.visible-print-inline-block  Hidden        Visible (as inline-block)
.hidden-print                Visible       Hidden

Bootstrap 3 update:

Print classes are now in documents: http://getbootstrap.com/css/#responsive-utilities-print

Similar to the regular responsive classes,
       use these for toggling content for print.

Class            Browser    Print
 ----------------------------------------
.visible-print   Hidden     Visible
.hidden-print    Visible    Hidden

Bootstrap 2.3.1 version:

After adding bootstrap.css file into your HTML,
Find the parts that you don't want to print and add hidden-print class into tags. Because css file includes this:

@media print {
  .visible-print  { display: inherit !important; }
  .hidden-print   { display: none !important; }
}

Bash script plugin for Eclipse?

ShellEd is a good plugin for Eclipse.

This link helped me to install it: http://mattnorris.me/blog/install-eclipse-shelled-plugin/

Steps:

  1. Download ShellEd: http://sourceforge.net/projects/shelled/files/latest/download - The file is a zipped archive named something like net.sourceforge.shelled-site-2.0.x.zip.

  2. Then click Help > Install New Software...

  3. Click Add... in the upper right.
  4. Click Archive...
  5. Navigate to where you saved the zipped archive net.sourceforge.shelled-site-2.0.x.zip and select it.
  6. Click OK. (Don't worry about the optional Name field. Eclipse will name it automatically.)
  7. Select the new Shell Script checkbox.
  8. Click Next.
  9. Click Next again.
  10. Select "I accept the terms of the license agreement."
  11. Click Finish.
  12. Restart Eclipse.

How can I process each letter of text using Javascript?

If you want to animate each character you might need to wrap it in span element;

var $demoText = $("#demo-text");
$demoText.html( $demoText.html().replace(/./g, "<span>$&amp;</span>").replace(/\s/g, " "));

I think this is the best way to do it, then process the spans. ( for example with TweenMax)

TweenMax.staggerFromTo( $demoText.find("span"), 0.2, {autoAlpha:0}, {autoAlpha:1}, 0.1 );

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

How can I return two values from a function in Python?

def test():
    r1 = 1
    r2 = 2
    r3 = 3
    return r1, r2, r3

x,y,z = test()
print x
print y
print z


> test.py 
1
2
3

Recursion or Iteration?

Recursion is more costly in memory, as each recursive call generally requires a memory address to be pushed to the stack - so that later the program could return to that point.

Still, there are many cases in which recursion is a lot more natural and readable than loops - like when working with trees. In these cases I would recommend sticking to recursion.

jQuery onclick toggle class name

jQuery has a toggleClass function:

<button class="switch">Click me</button>

<div class="text-block collapsed pressed">some text</div>

<script>    
    $('.switch').on('click', function(e) {
      $('.text-block').toggleClass("collapsed pressed"); //you can list several class names 
      e.preventDefault();
    });
</script>

Printing an array in C++?

// Just do this, use a vector with this code and you're good lol -Daniel

#include <Windows.h>
#include <iostream>
#include <vector>

using namespace std;


int main()
{

    std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
    
    if (arry.size() != arry.size() || arry.empty()) {
        printf("what happened to the array lol\n ");
        system("PAUSE");
    }
    for (int i = 0; i < arry.size(); i++)
    {   
        if (arry.max_size() == true) {
            cout << "Max size of array reached!";
        }
        cout << "Array Value " << i << " = " << arry.at(i) << endl;
            
    }
}

What is the default username and password in Tomcat?

Check the file in <TOMCAT_HOME>/conf named tomcat-users.xml.
If you don't find something there edit to look something like:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="admin"/>
  <user username="admin" password="password" roles="standard,manager,admin"/>
</tomcat-users>

HTTP Status 504

CheckUpDown has a nice explanation of the 504 error:

A server (not necessarily a Web server) is acting as a gateway or proxy to fulfil the request by the client (e.g. your Web browser or our CheckUpDown robot) to access the requested URL. This server did not receive a timely response from an upstream server it accessed to deal with your HTTP request.

This usually means that the upstream server is down (no response to the gateway/proxy), rather than that the upstream server and the gateway/proxy do not agree on the protocol for exchanging data.

This problem is entirely due to slow IP communication between back-end computers, possibly including the Web server. Only the people who set up the network at the site which hosts the Web server can fix this problem.

jQuery UI Sortable Position

You can use the ui object provided to the events, specifically you want the stop event, the ui.item property and .index(), like this:

$("#sortable").sortable({
    stop: function(event, ui) {
        alert("New position: " + ui.item.index());
    }
});

You can see a working demo here, remember the .index() value is zero-based, so you may want to +1 for display purposes.

Deserialize JSON array(or list) in C#

This code works for me:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Json
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DeserializeNames());
            Console.ReadLine();
        }

        public static string DeserializeNames()
        {
            var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";

            JavaScriptSerializer ser = new JavaScriptSerializer();

            nameList myNames = ser.Deserialize<nameList>(jsonData);

            return ser.Serialize(myNames);
        }

        //Class descriptions

        public class name
        {
            public string last { get; set; }
        }

        public class nameList
        {
            public List<name> name { get; set; }
        }
    }
}

The FastCGI process exited unexpectedly

if you have two application like (your app, phpmyadmin) just disable APC extension Hope that fix that issue it's worked with me

How can I insert new line/carriage returns into an element.textContent?

I know this question posted long time ago.

I had similar problem few days ago, passing value from web service in json format and place it in table cell contentText.

Because value is passed in format, for example, "text row1\r\ntext row2" and so on.

For new line in textContent You have to use \r\n and, finally, I had to use css white-space: pre-line; (Text will wrap when necessary, and on line breaks) and everything goes fine.

Or, You can use only white-space: pre; and then text will wrap only on line breaks (in this case \r\n).

So, there is example how to solve it with wrapping text only on line breaks :

_x000D_
_x000D_
var h1 = document.createElement("h1");_x000D_
_x000D_
//setting this css style solving problem with new line in textContent_x000D_
h1.setAttribute('style', 'white-space: pre;');_x000D_
_x000D_
//add \r\n in text everywhere You want for line-break (new line)_x000D_
h1.textContent = "This is a very long string and I would like to insert a carriage return \r\n...";_x000D_
h1.textContent += "moreover, I would like to insert another carriage return \r\n...";_x000D_
h1.textContent += "so this text will display in a new line";_x000D_
_x000D_
document.body.appendChild(h1);
_x000D_
_x000D_
_x000D_

Fatal error: Maximum execution time of 30 seconds exceeded

All the answers above are correct, but I use a simple way to avoid it in some cases.

Just put this command in the begining of your script:

set_time_limit(0);

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

public DateTime DateCreated
{
   get
   {
      return (this.dateCreated == default(DateTime))
         ? this.dateCreated = DateTime.Now
         : this.dateCreated;
   }

   set { this.dateCreated = value; }
}
private DateTime dateCreated = default(DateTime);

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

Annotation @Transactional. How to rollback?

or programatically

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

How do you loop in a Windows batch file?

@echo off
echo.
set /p num1=Enter Prelim:
echo.
set /p num2=Enter Midterm:
echo.
set /p num3=Enter Semi:
echo.
set /p num4=Enter Finals:
echo.
set /a ans=%num1%+%num2%+%num3%+%num4%
set /a avg=%ans%/4
ECHO %avg%
if %avg%>=`95` goto true
:true
echo The two numbers you entered were the same.
echo.
pause
exit

Location of the mongodb database on mac

Env: macOS Mojave 10.14.4

Install: homebrew

Location:/usr/local/Cellar/mongodb/4.0.3_1

Note :If update version by brew upgrade mongo,the folder 4.0.4_1 will be removed and replace with the new version folder

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

You should check if it's not defined using if (!Array.prototype.indexOf).

Also, your implementation of indexOf is not correct. You must use === instead of == in your if (this[i] == obj) statement, otherwise [4,"5"].indexOf(5) would be 1 according to your implementation, which is incorrect.

I recommend you use the implementation on MDC.

The default XML namespace of the project must be the MSBuild XML namespace

I was getting the same messages while I was running just msbuild from powershell.

dotnet msbuild "./project.csproj" worked for me.

Upload file to SFTP using PowerShell

I am able to sftp using PowerShell as below:

PS C:\Users\user\Desktop> sftp [email protected]                                                     
[email protected]'s password:
Connected to [email protected].
sftp> ls
testFolder
sftp> cd testFolder
sftp> ls
taj_mahal.jpeg
sftp> put taj_mahal_1.jpeg
Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
taj_mahal_1.jpeg                                                                      100%   11KB  35.6KB/s   00:00
sftp> ls
taj_mahal.jpeg      taj_mahal_1.jpeg
sftp>

I do not have installed Posh-SSH or anything like that. I am using Windows 10 Pro PowerShell. No additional modules installed.

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

How do I use arrays in C++?

Programmers often confuse multidimensional arrays with arrays of pointers.

Multidimensional arrays

Most programmers are familiar with named multidimensional arrays, but many are unaware of the fact that multidimensional array can also be created anonymously. Multidimensional arrays are often referred to as "arrays of arrays" or "true multidimensional arrays".

Named multidimensional arrays

When using named multidimensional arrays, all dimensions must be known at compile time:

int H = read_int();
int W = read_int();

int connect_four[6][7];   // okay

int connect_four[H][7];   // ISO C++ forbids variable length array
int connect_four[6][W];   // ISO C++ forbids variable length array
int connect_four[H][W];   // ISO C++ forbids variable length array

This is how a named multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
connect_four: |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+
              |   |   |   |   |   |   |   |
              +---+---+---+---+---+---+---+

Note that 2D grids such as the above are merely helpful visualizations. From the point of view of C++, memory is a "flat" sequence of bytes. The elements of a multidimensional array are stored in row-major order. That is, connect_four[0][6] and connect_four[1][0] are neighbors in memory. In fact, connect_four[0][7] and connect_four[1][0] denote the same element! This means that you can take multi-dimensional arrays and treat them as large, one-dimensional arrays:

int* p = &connect_four[0][0];
int* q = p + 42;
some_int_sequence_algorithm(p, q);

Anonymous multidimensional arrays

With anonymous multidimensional arrays, all dimensions except the first must be known at compile time:

int (*p)[7] = new int[6][7];   // okay
int (*p)[7] = new int[H][7];   // okay

int (*p)[W] = new int[6][W];   // ISO C++ forbids variable length array
int (*p)[W] = new int[H][W];   // ISO C++ forbids variable length array

This is how an anonymous multidimensional array looks like in memory:

              +---+---+---+---+---+---+---+
        +---> |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |     |   |   |   |   |   |   |   |
        |     +---+---+---+---+---+---+---+
        |
      +-|-+
   p: | | |
      +---+

Note that the array itself is still allocated as a single block in memory.

Arrays of pointers

You can overcome the restriction of fixed width by introducing another level of indirection.

Named arrays of pointers

Here is a named array of five pointers which are initialized with anonymous arrays of different lengths:

int* triangle[5];
for (int i = 0; i < 5; ++i)
{
    triangle[i] = new int[5 - i];
}

// ...

for (int i = 0; i < 5; ++i)
{
    delete[] triangle[i];
}

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
triangle: | | | | | | | | | | |
          +---+---+---+---+---+

Since each line is allocated individually now, viewing 2D arrays as 1D arrays does not work anymore.

Anonymous arrays of pointers

Here is an anonymous array of 5 (or any other number of) pointers which are initialized with anonymous arrays of different lengths:

int n = calculate_five();   // or any other number
int** p = new int*[n];
for (int i = 0; i < n; ++i)
{
    p[i] = new int[n - i];
}

// ...

for (int i = 0; i < n; ++i)
{
    delete[] p[i];
}
delete[] p;   // note the extra delete[] !

And here is how it looks like in memory:

          +---+---+---+---+---+
          |   |   |   |   |   |
          +---+---+---+---+---+
            ^
            | +---+---+---+---+
            | |   |   |   |   |
            | +---+---+---+---+
            |   ^
            |   | +---+---+---+
            |   | |   |   |   |
            |   | +---+---+---+
            |   |   ^
            |   |   | +---+---+
            |   |   | |   |   |
            |   |   | +---+---+
            |   |   |   ^
            |   |   |   | +---+
            |   |   |   | |   |
            |   |   |   | +---+
            |   |   |   |   ^
            |   |   |   |   |
            |   |   |   |   |
          +-|-+-|-+-|-+-|-+-|-+
          | | | | | | | | | | |
          +---+---+---+---+---+
            ^
            |
            |
          +-|-+
       p: | | |
          +---+

Conversions

Array-to-pointer decay naturally extends to arrays of arrays and arrays of pointers:

int array_of_arrays[6][7];
int (*pointer_to_array)[7] = array_of_arrays;

int* array_of_pointers[6];
int** pointer_to_pointer = array_of_pointers;

However, there is no implicit conversion from T[h][w] to T**. If such an implicit conversion did exist, the result would be a pointer to the first element of an array of h pointers to T (each pointing to the first element of a line in the original 2D array), but that pointer array does not exist anywhere in memory yet. If you want such a conversion, you must create and fill the required pointer array manually:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = connect_four[i];
}

// ...

delete[] p;

Note that this generates a view of the original multidimensional array. If you need a copy instead, you must create extra arrays and copy the data yourself:

int connect_four[6][7];

int** p = new int*[6];
for (int i = 0; i < 6; ++i)
{
    p[i] = new int[7];
    std::copy(connect_four[i], connect_four[i + 1], p[i]);
}

// ...

for (int i = 0; i < 6; ++i)
{
    delete[] p[i];
}
delete[] p;

Preloading images with JavaScript

The browser will work best using the link tag in the head.

export function preloadImages (imageSources: string[]): void {
  imageSources
    .forEach(i => {
      const linkEl = document.createElement('link');
      linkEl.setAttribute('rel', 'preload');
      linkEl.setAttribute('href', i);
      linkEl.setAttribute('as', 'image');
      document.head.appendChild(linkEl);
    });
}

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Include <tchar.h> which has the line:

#define _tWinMain wWinMain

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

How can you encode a string to Base64 in JavaScript?

I'd rather use the bas64 encode/decode methods from CryptoJS, the most popular library for standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns.

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

What are C++ functors and their uses?

Except for used in callback, C++ functors can also help to provide a Matlab liking access style to a matrix class. There is a example.

What is the difference between a URI, a URL and a URN?

Due to difficulties to clearly distinguish between URI and URL, as far as I remember W3C does not make a difference any longer between URI and URL (http://www.w3.org/Addressing/).

How do I convert a datetime to date?

you could enter this code form for (today date & Names of the Day & hour) : datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')

'19-09-09 Mon 17:37:56'

and enter this code for (today date simply): datetime.date.today().strftime('%y-%m-%d') '19-09-10'

for object : datetime.datetime.now().date() datetime.datetime.today().date() datetime.datetime.utcnow().date() datetime.datetime.today().time() datetime.datetime.utcnow().date() datetime.datetime.utcnow().time()

Swift: print() vs println() vs NSLog()

Moreover, Swift 2 has debugPrint() (and CustomDebugStringConvertible protocol)!

Don't forget about debugPrint() which works like print() but most suitable for debugging.

Examples:

  • Strings
    • print("Hello World!") becomes Hello World
    • debugPrint("Hello World!") becomes "Hello World" (Quotes!)
  • Ranges
    • print(1..<6) becomes 1..<6
    • debugPrint(1..<6) becomes Range(1..<6)

Any class can customize their debug string representation via CustomDebugStringConvertible protocol.

How to remove element from ArrayList by checking its value?

Just use myList.remove(myObject).

It uses the equals method of the class. See http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(java.lang.Object)

BTW, if you have more complex things to do, you should check out the guava library that has dozen of utility to do that with predicates and so on.

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

I landed here because of an XCTestCase, in which I'd disabled most of the tests by prefixing them with 'no_' as in no_testBackgroundAdding. Once I noticed that most of the answers had something to do with locks and threading, I realized the test contained a few instances of XCTestExpectation with corresponding waitForExpectations. They were all in the disabled tests, but apparently Xcode was still evaluating them at some level.

In the end I found an XCTestExpectation that was defined as @property but lacked the @synthesize. Once I added the synthesize directive, the EXC_BAD_INSTRUCTION disappeared.

Why doesn't Java allow overriding of static methods?

The following code shows that it is possible:

class OverridenStaticMeth {   

static void printValue() {   
System.out.println("Overriden Meth");   
}   

}   

public class OverrideStaticMeth extends OverridenStaticMeth {   

static void printValue() {   
System.out.println("Overriding Meth");   
}   

public static void main(String[] args) {   
OverridenStaticMeth osm = new OverrideStaticMeth();   
osm.printValue();   

System.out.println("now, from main");
printValue();

}   

} 

How to detect if numpy is installed

In the numpy README.txt file, it says

After installation, tests can be run with:

python -c 'import numpy; numpy.test()'

This should be a sufficient test for proper installation.

Creating a new empty branch for a new project

Make an empty new branch like this:

true | git mktree | xargs git commit-tree | xargs git branch proj-doc

If your proj-doc files are already in a commit under a single subdir you can make the new branch this way:

git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc

which might be more convenient than git branch --orphan if that would leave you with a lot of git rm and git mving to do.

Try

git branch --set-upstream proj-doc origin/proj-doc

and see if that helps with your fetching-too-much problem. Also if you really only want to fetch a single branch it's safest to just specify it on the commandline.

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

twitter bootstrap text-center when in xs mode

@media (max-width: 767px) {
    footer .text-right, 
    footer .text-left {
        text-align: center;
    } 
}

I updated @loddn's answer, making two changes

  • max-width of xs screens in bootstrap is 767px (768px is the start of sm screens)
  • (this one is a matter of preference) I used footer instead of col-* so that if the column widths change, the CSS doesn't need to be updated.

Change image size via parent div

I'm not sure about what you mean by "I have no access to image" But if you have access to parent div you can do the following:

Firs give id or class to your div:

<div class="parent">
   <img src="http://someimage.jpg">
</div>

Than add this to your css:

.parent {
   width: 42px; /* I took the width from your post and placed it in css */
   height: 42px;
}

/* This will style any <img> element in .parent div */
.parent img {
   height: 100%;
   width: 100%;
}

Merge two json/javascript arrays in to one array

You want the concat method.

var finalObj = json1.concat(json2);

Where is android studio building my .apk file?

When Gradle builds your project, it puts all APKs in build/apk directory. You could also just do a simple recursive find command for *.apk in the top level directory of your project.

Here is a better description...

http://i.stack.imgur.com/XwjEZ.png

View full image at http://i.stack.imgur.com/XwjEZ.png

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

I've just seen this problem myself, Jboss AS7 with jdk1.5.0_09. Update System Property JAVA_HOME to jdk1.7+ to fix (I'm using jdk1.7.0_67).

Match exact string

It depends. You could

string.match(/^abc$/)

But that would not match the following string: 'the first 3 letters of the alphabet are abc. not abc123'

I think you would want to use \b (word boundaries):

_x000D_
_x000D_
var str = 'the first 3 letters of the alphabet are abc. not abc123';_x000D_
var pat = /\b(abc)\b/g;_x000D_
console.log(str.match(pat));
_x000D_
_x000D_
_x000D_

Live example: http://jsfiddle.net/uu5VJ/

If the former solution works for you, I would advise against using it.

That means you may have something like the following:

var strs = ['abc', 'abc1', 'abc2']
for (var i = 0; i < strs.length; i++) {
    if (strs[i] == 'abc') {
        //do something 
    }
    else {
        //do something else
    }
}

While you could use

if (str[i].match(/^abc$/g)) {
    //do something 
}

It would be considerably more resource-intensive. For me, a general rule of thumb is for a simple string comparison use a conditional expression, for a more dynamic pattern use a regular expression.

More on JavaScript regexes: https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions

How can I detect if Flash is installed and if not, display a hidden div that informs the user?

You can use navigator.mimeTypes.

if (navigator.mimeTypes ["application/x-shockwave-flash"] == undefined)
    $("#someDiv").show ();

How to set a primary key in MongoDB?

If you're using Mongo on Meteor, you can use _ensureIndex:

CollectionName._ensureIndex({field:1 }, {unique: true});

How to convert a currency string to a double with jQuery or Javascript?

var parseCurrency = function (e) {
    if (typeof (e) === 'number') return e;
    if (typeof (e) === 'string') {
        var str = e.trim();
        var value = Number(e.replace(/[^0-9.-]+/g, ""));
        return str.startsWith('(') && str.endsWith(')') ? -value: value;
    }

    return e;
} 

File Upload In Angular?

I've upload file using reference. No package is required to upload file this way.

// code to be written in .ts file

@ViewChild("fileInput") fileInput;

addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
  let fileToUpload = fi.files[0];
    this.admin.addQuestionApi(fileToUpload)
      .subscribe(
        success => {
          this.loading = false;
          this.flashMessagesService.show('Uploaded successfully', {
            classes: ['alert', 'alert-success'],
            timeout: 1000,
          });
        },
        error => {
          this.loading = false;
          if(error.statusCode==401) this.router.navigate(['']);
          else
            this.flashMessagesService.show(error.message, {
              classes: ['alert', 'alert-danger'],
              timeout: 1000,
            });
        });
  }

}

// code to be written in service.ts file

addQuestionApi(fileToUpload: any){
var headers = this.getHeadersForMultipart();
let input = new FormData();
input.append("file", fileToUpload);

return this.http.post(this.baseUrl+'addQuestions', input, {headers:headers})
      .map(response => response.json())
      .catch(this.errorHandler);

}

// code to be written in html

<input type="file" #fileInput>

How to read a line from the console in C?

If you are using the GNU C library or another POSIX-compliant library, you can use getline() and pass stdin to it for the file stream.

Change image source in code behind - Wpf

The pack syntax you are using here is for an image that is contained as a Resource within your application, not for a loose file in the file system.

You simply want to pass the actual path to the UriSource:

logo.UriSource = new Uri(@"\\myserver\folder1\Customer Data\sample.png");

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

Thank you, user374559 and reneD -- that code and description is very helpful.

My stab at some Python to parse and print out the information in a Unix ls-l like format:

#!/usr/bin/env python
import sys

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
    return mbdb

def process_mbdx_file(filename):
    mbdx = {} # Map offset of info in the MBDB file => fileID string
    data = open(filename).read()
    if data[0:4] != "mbdx": raise Exception("This does not look like an MBDX file")
    offset = 4
    offset = offset + 2 # value 0x02 0x00, not sure what this is
    filecount, offset = getint(data, offset, 4) # 4-byte count of records 
    while offset < len(data):
        # 26 byte record, made up of ...
        fileID = data[offset:offset+20] # 20 bytes of fileID
        fileID_string = ''.join(['%02x' % ord(b) for b in fileID])
        offset = offset + 20
        mbdb_offset, offset = getint(data, offset, 4) # 4-byte offset field
        mbdb_offset = mbdb_offset + 6 # Add 6 to get past prolog
        mode, offset = getint(data, offset, 2) # 2-byte mode field
        mbdx[mbdb_offset] = fileID_string
    return mbdx

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

How to check if a user is logged in (how to properly use user.is_authenticated)?

Following block should work:

    {% if user.is_authenticated %}
        <p>Welcome {{ user.username }} !!!</p>       
    {% endif %}

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

Add up a column of numbers at the Unix shell

Here's mine

cat files.txt | xargs ls -l | cut -c 23-30 | sed -e :a -e '$!N;s/\n/+/;ta' | bc

How can I get the value of a registry key from within a batch script?

Based on tryingToBeClever solution (which I happened to also stumble upon and fixed myself by trial-and-error before finding it), I also suggest passing the result output of reg query through find in order to filter undesired lines due to the ! REG.EXE VERSION x.y inconsistency. The find filtering and tokens tweaking also allows to pick exactly what we want (typically the value). Also added quotes to avoid unexpected results with key/value names containing spaces.

Final result proposed when we are only interested in fetching the value:

@echo off
setlocal ENABLEEXTENSIONS
set KEY_NAME=HKCU\Software\Microsoft\Command Processor
set VALUE_NAME=DefaultColor
for /F "usebackq tokens=1,2,*" %%A IN (`reg query "%KEY_NAME%" /v "%VALUE_NAME%" 2^>nul ^| find "%VALUE_NAME%"`) do (
  echo %%C
)

A potential caveat of using find is that the errorlevel set by reg when errors occur is now obfuscated so one should only use this approach for keys known to be there and/or after a previous validation.

A tiny additional optimization (add skip=1 to avoid processing the first line of output) can be done in cases when the key name also contains the value name (as it is the case with HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion and CurrentVersion) but removes most flexibility so should only be used in particular use-cases.

How to get HTML 5 input type="date" working in Firefox and/or IE 10

I had to use bootstrap-datepicker plugin to get the calendar working on Firefox 55 Portable:

https://bootstrap-datepicker.readthedocs.io/en/latest/

Compatible with Bootstrap v2 and v3. It comes with a standalone stylesheet so you don't have to depend on Bootstrap.

Usage:

<input class="datepicker">

$('.datepicker').datepicker({
    format: 'mm/dd/yyyy'
});

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

Multi-line strings in PHP

Well,

$xml = "l
vv";

Works.

You can also use the following:

$xml = "l\nvv";

or

$xml = <<<XML
l
vv
XML;

Edit based on comment:

You can concatenate strings using the .= operator.

$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";

Multiplying across in a numpy array

Yet another trick (as of v1.6)

A=np.arange(1,10).reshape(3,3)
b=np.arange(3)

np.einsum('ij,i->ij',A,b)

I'm proficient with the numpy broadcasting (newaxis), but I'm still finding my way around this new einsum tool. So I had play around a bit to find this solution.

Timings (using Ipython timeit):

einsum: 4.9 micro
transpose: 8.1 micro
newaxis: 8.35 micro
dot-diag: 10.5 micro

Incidentally, changing a i to j, np.einsum('ij,j->ij',A,b), produces the matrix that Alex does not want. And np.einsum('ji,j->ji',A,b) does, in effect, the double transpose.

Ignore .pyc files in git repository

i try to use the sentence of a prior post and don't work recursively, then read some help and get this line:

find . -name "*.pyc" -exec git rm -f "{}" \;

p.d. is necessary to add *.pyc in .gitignore file to maintain git clean

echo "*.pyc" >> .gitignore

Enjoy.

Two HTML tables side by side, centered on the page

<style>
#outer { text-align: center; }
#inner { width:500px; text-align: left; margin: 0 auto; }
.t { float: left; width:240px; border: 1px solid black;}
#clearit { clear: both; }
</style>

How to set cursor position in EditText?

I believe the most simple way to do this is just use padding.

Say in your xml's edittext section, add android:paddingLeft="100dp" This will move your start position of cursor 100dp right from left end.

Same way, you can use android:paddingRight="100dp" This will move your end position of cursor 100dp left from right end.

For more detail, check this article on my blog: Android: Setting Cursor Starting and Ending Position in EditText Widget

How to check if number is divisible by a certain number?

package lecture3;

import java.util.Scanner;

public class divisibleBy2and5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter an integer number:");
        Scanner input = new Scanner(System.in);
        int x;
        x = input.nextInt();
         if (x % 2==0){
             System.out.println("The integer number you entered is divisible by 2");
         }
         else{
             System.out.println("The integer number you entered is not divisible by 2");
             if(x % 5==0){
                 System.out.println("The integer number you entered is divisible by 5");
             } 
             else{
                 System.out.println("The interger number you entered is not divisible by 5");
             }
        }

    }
}

Git: How to rebase to a specific commit?

Topic Solution

The correct command to answer the posted question could be any of the following (assuming branch topic is already checked out):

git rebase --onto B master
git rebase --onto master~1 master
git rebase --onto B A
git rebase --onto B C
git rebase --onto B

If topic is not checked out, you simply append topic to the command (except the last one) like so:

git rebase --onto B master topic

Alternatively, check out the branch first with:

git checkout topic

Rebase Any String of Commits to a Target Commit

The basic form of the command we need, cribbed from the documentation, is:

git rebase --onto <Target> [<Upstream> [<Branch>]]

<Branch> is optional and all it does is checks out the branch specified before executing the rest of the command. If you've already checked out the branch you want to rebase, then you don't need this. Note that you must have specified <Upstream> in order to specify <Branch> or git will think you are specifying <Upstream>.

<Target> is the commit we will attach our string of commits to. When providing a branch name, you are simply specifying the head commit of that branch. <Target> can be any commit that won't be contained in the string of commits being moved. For example:

A --- B --- C --- D         master
      \
       \-- X --- Y --- Z    feature

To move the entire feature branch, you can not select X, Y, Z, or feature as the <Target> since those all are commits inside the group being moved.

<Upstream> is special because it can mean two different things. If it is a commit that is an ancestor of the checked out branch, then it serves as the cut point. In the example I provided, this would be anything that isn't C, D, or master. All commits after <Upstream> until the head of the checked out branch are the ones that will be moved.

However, if <Upstream> is not an ancestor, then git backs up the chain from the specified commit until if finds a common ancestor with the checked out branch (and aborts if it can't find one). In our case, an <Upstream> of B, C, D, or master will all result in commit B serving as the cut point. <Upstream> is itself an optional command and if it is not specified, then git looks at the parent of the checked out branch which is the equivalent of entering master.

Now that git has selected the commits it will cut and move, it applies them in order to <Target>, skipping any that are already applied to target.

Interesting Examples and Results

Using this starting point:

A --- B --- C --- D --- E         master
            \
             \-- X --- Y --- Z    feature
  • git rebase --onto D A feature
    Will apply commits B, C, X, Y, Z to commit D and end up skipping B and C because they already have been applied.

  • git rebase --onto C X feature
    Will apply commits Y and Z to commit C, effectively deleting commit X

React - uncaught TypeError: Cannot read property 'setState' of undefined

When using ES6 code in React always use arrow functions, because the this context is automatically binded with it

Use this:

(videos) => {
    this.setState({ videos: videos });
    console.log(this.state.videos);
};

instead of:

function(videos) {
    this.setState({ videos: videos });
    console.log(this.state.videos);
};

How to make a phone call using intent in Android?

 if(ContextCompat.checkSelfPermission(
        mContext,android.Manifest.permission.CALL_PHONE) != 
              PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions((Activity) mContext, new 
                  String[]{android.Manifest.permission.CALL_PHONE}, 0);
                } else {
                    startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "Your Number")));
                }

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Display PDF within web browser

instead of using iframe and depending on the third party`think about using flexpaper, or pdf.js.

I used PDF.js, it works fine for me. Here is the demo.

How can I print each command before executing?

set -x is fine, but if you do something like:

set -x;
command;
set +x;

it would result in printing

+ command
+ set +x;

You can use a subshell to prevent that such as:

(set -x; command)

which would just print the command.

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

'too many values to unpack', iterating over a dict. key=>string, value=>list

data = (['President','George','Bush','is','.'],['O','B-PERSON','I-PERSON','O','O'])
corpus = []
for(doc,tags) in data:
    doc_tag = []
    for word,tag in zip(doc,tags):
        doc_tag.append((word,tag))
        corpus.append(doc_tag)
        print(corpus)

When to use Comparable and Comparator

Use Comparable if you want to define a default (natural) ordering behaviour of the object in question, a common practice is to use a technical or natural (database?) identifier of the object for this.

Use Comparator if you want to define an external controllable ordering behaviour, this can override the default ordering behaviour.

ProcessStartInfo hanging on "WaitForExit"? Why?

We have this issue as well (or a variant).

Try the following:

1) Add a timeout to p.WaitForExit(nnnn); where nnnn is in milliseconds.

2) Put the ReadToEnd call before the WaitForExit call. This is what we've seen MS recommend.

What's the difference between a method and a function?

General answer is:

method has object context (this, or class instance reference),

function has none context (null, or global, or static).

But answer to question is dependent on terminology of language you use.

  1. In JavaScript (ES 6) you are free to customising function context (this) for any you desire, which is normally must be link to the (this) object instance context.

  2. In Java world you always hear that "only OOP classes/objects, no functions", but if you watch in detailes to static methods in Java, they are really in global/null context (or context of classes, whithout instancing), so just functions whithout object. Java teachers could told you, that functions were rudiment of C in C++ and dropped in Java, but they told you it for simplification of history and avoiding unnecessary questions of newbies. If you see at Java after 7 version, you can find many elements of pure function programming (even not from C, but from older 1988 Lisp) for simplifying parallel computing, and it is not OOP classes style.

  3. In C++ and D world things are stronger, and you have separated functions and objects with methods and fields. But in practice, you again see functions without this and methods whith this (with object context).

  4. In FreePascal/Lazarus and Borland Pascal/Delphi things about separation terms of functions and objects (variables and fields) are usually similar to C++.

  5. Objective-C comes from C world, so you must separate C functions and Objective-C objects with methods addon.

  6. C# is very similar to Java, but has many C++ advantages.

How To limit the number of characters in JTextField?

import java.awt.KeyboardFocusManager;
import javax.swing.InputVerifier;
import javax.swing.JTextField;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;
import javax.swing.text.DocumentFilter.FilterBypass;

/**
 *
 * @author Igor
 */
public class CustomLengthTextField extends JTextField {

    protected boolean upper = false;
    protected int maxlength = 0;

    public CustomLengthTextField() {
        this(-1);
    }

    public CustomLengthTextField(int length, boolean upper) {
        this(length, upper, null);
    }

    public CustomLengthTextField(int length, InputVerifier inpVer) {
        this(length, false, inpVer);
    }

    /**
     *
     * @param length - maksimalan length
     * @param upper - turn it to upercase
     * @param inpVer - InputVerifier
     */
    public CustomLengthTextField(int length, boolean upper, InputVerifier inpVer) {
        super();
        this.maxlength = length;
        this.upper = upper;
        if (length > 0) {
            AbstractDocument doc = (AbstractDocument) getDocument();
            doc.setDocumentFilter(new DocumentSizeFilter());
        }
        setInputVerifier(inpVer);
    }

    public CustomLengthTextField(int length) {
        this(length, false);
    }

    public void setMaxLength(int length) {
        this.maxlength = length;
    }

    class DocumentSizeFilter extends DocumentFilter {

        public void insertString(FilterBypass fb, int offs, String str, AttributeSet a)
                throws BadLocationException {

            //This rejects the entire insertion if it would make
            //the contents too long. Another option would be
            //to truncate the inserted string so the contents
            //would be exactly maxCharacters in length.
            if ((fb.getDocument().getLength() + str.length()) <= maxlength) {
                super.insertString(fb, offs, str, a);
            }
        }

        public void replace(FilterBypass fb, int offs,
                int length,
                String str, AttributeSet a)
                throws BadLocationException {

            if (upper) {
                str = str.toUpperCase();
            }

            //This rejects the entire replacement if it would make
            //the contents too long. Another option would be
            //to truncate the replacement string so the contents
            //would be exactly maxCharacters in length.
            int charLength = fb.getDocument().getLength() + str.length() - length;

            if (charLength <= maxlength) {
                super.replace(fb, offs, length, str, a);
                if (charLength == maxlength) {
                    focusNextComponent();
                }
            } else {
                focusNextComponent();
            }
        }

        private void focusNextComponent() {
            if (CustomLengthTextField.this == KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner()) {
                KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
            }
        }
    }
}

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

As already said, your socket probably enter in TIME_WAIT state. This issue is well described by Thomas A. Fine here.

To summary, socket closing process follow diagram below:

Socket closing process

Thomas says:

Looking at the diagram above, it is clear that TIME_WAIT can be avoided if the remote end initiates the closure. So the server can avoid problems by letting the client close first. The application protocol must be designed so that the client knows when to close. The server can safely close in response to an EOF from the client, however it will also need to set a timeout when it is expecting an EOF in case the client has left the network ungracefully. In many cases simply waiting a few seconds before the server closes will be adequate.

Using SO_REUSEADDR is commonly suggested on internet, but Thomas add:

Oddly, using SO_REUSEADDR can actually lead to more difficult "address already in use" errors. SO_REUSADDR permits you to use a port that is stuck in TIME_WAIT, but you still can not use that port to establish a connection to the last place it connected to. What? Suppose I pick local port 1010, and connect to foobar.com port 300, and then close locally, leaving that port in TIME_WAIT. I can reuse local port 1010 right away to connect to anywhere except for foobar.com port 300.

How to throw an exception in C?

On Win with MSVC there's __try ... __except ... but it's really horrible and you don't want to use it if you can possibly avoid it. Better to say that there are no exceptions.

Is it possible to use a div as content for Twitter's Popover

First of all, if you want to use HTML inside the content you need to set the HTML option to true:

$('.danger').popover({ html : true});

Then you have two options to set the content for a Popover

  • Use the data-content attribute. This is the default option.
  • Use a custom JS function which returns the HTML content.

Using data-content: You need to escape the HTML content, something like this:

<a class='danger' data-placement='above' 
   data-content="&lt;div&gt;This is your div content&lt;/div&gt;" 
   title="Title" href='#'>Click</a>

You can either escape the HTML manually or use a function. I don't know about PHP but in Rails we use *html_safe*.

Using a JS function: If you do this, you have several options. The easiest I think is to put your div content hidden wherever you want and then write a function to pass its content to popover. Something like this:

$(document).ready(function(){
  $('.danger').popover({ 
    html : true,
    content: function() {
      return $('#popover_content_wrapper').html();
    }
  });
});

And then your HTML looks like this:

<a class='danger' data-placement='above' title="Popover Title" href='#'>Click</a>
<div id="popover_content_wrapper" style="display: none">
  <div>This is your div content</div>
</div>

Hope it helps!

PS: I've had some troubles when using popover and not setting the title attribute... so, remember to always set the title.

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the predefined environmental variable in Linux/Unix which sets the path which the linker should look in to while linking dynamic libraries/shared libraries.

LD_LIBRARY_PATH contains a colon separated list of paths and the linker gives priority to these paths over the standard library paths /lib and /usr/lib. The standard paths will still be searched, but only after the list of paths in LD_LIBRARY_PATH has been exhausted.

The best way to use LD_LIBRARY_PATH is to set it on the command line or script immediately before executing the program. This way the new LD_LIBRARY_PATH isolated from the rest of your system.

Example Usage:

$ export LD_LIBRARY_PATH="/list/of/library/paths:/another/path"
$ ./program

Since you talk about .dll you are on a windows system and a .dll must be placed at a path which the linker searches at link time, in windows this path is set by the environmental variable PATH, So add that .dll to PATH and it should work fine.

Empty an array in Java / processing

Take double array as an example, if the initial input values array is not empty, the following code snippet is superior to traditional direct for-loop in time complexity:

public static void resetValues(double[] values) {
  int len = values.length;
  if (len > 0) {
    values[0] = 0.0;
  }
  for (int i = 1; i < len; i += i) {
    System.arraycopy(values, 0, values, i, ((len - i) < i) ? (len - i) : i);
  }
}

Java replace all square brackets in a string

String str, str1;
Scanner sc = new Scanner(System.in);

System.out.print("Enter a String : ");
str = sc.nextLine();


str1 = str.replaceAll("[aeiouAEIOU]", "");



System.out.print(str1);

How to create SPF record for multiple IPs?

The open SPF wizard from the previous answer is no longer available, neither the one from Microsoft.

Day Name from Date in JS

Ahum, three years later...

Why nobody uses the methods provided by the standard javascript Date class (except Callum Linington)?

See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Getting the day name from a date:

function getDayName(dateStr, locale)
{
    var date = new Date(dateStr);
    return date.toLocaleDateString(locale, { weekday: 'long' });        
}

var dateStr = '05/23/2014';
var day = getDayName(dateStr, "nl-NL"); // Gives back 'Vrijdag' which is Dutch for Friday.

Getting all weekdays in an array:

function getWeekDays(locale)
{
    var baseDate = new Date(Date.UTC(2017, 0, 2)); // just a Monday
    var weekDays = [];
    for(i = 0; i < 7; i++)
    {       
        weekDays.push(baseDate.toLocaleDateString(locale, { weekday: 'long' }));
        baseDate.setDate(baseDate.getDate() + 1);       
    }
    return weekDays;
}

var weekDays = getWeekDays('nl-NL'); // Gives back { 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag', 'zondag'} which are the days of the week in Dutch.

For American dates use 'en-US' as locale.

How to display 3 buttons on the same line in css

You need to float all the buttons to left and make sure its width to fit within outer container.

CSS:

.btn{

   float:left;
}

HTML:

    <button type="submit" class="btn" onClick="return false;" >Save</button>
    <button type="submit" class="btn" onClick="return false;">Publish</button>
    <button class="btn">Back</button>

comparing two strings in ruby

Comparison of strings is very easy in Ruby:

v1 = "string1"
v2 = "string2"
puts v1 == v2 # prints false
puts "hello"=="there" # prints false
v1 = "string2"
puts v1 == v2 # prints true

Make sure your var2 is not an array (which seems to be like)

What is the meaning of "operator bool() const"

operator bool() const 
{
    return col != 0;
}

Defines how the class is convertable to a boolean value, the const after the () is used to indicate this method does not mutate (change the members of this class).

You would usually use such operators as follows:

airplaysdk sdkInstance;
if (sdkInstance) {
    std::cout << "Instance is active" << std::endl;
} else {
    std::cout << "Instance is in-active error!" << std::endl;
}

Converting from IEnumerable to List

If you're using an implementation of System.Collections.IEnumerable you can do like following to convert it to a List. The following uses Enumerable.Cast method to convert IEnumberable to a Generic List.

//ArrayList Implements IEnumerable interface
ArrayList _provinces = new System.Collections.ArrayList();
_provinces.Add("Western");
_provinces.Add("Eastern");

List<string> provinces = _provinces.Cast<string>().ToList();

If you're using Generic version IEnumerable<T>, The conversion is straight forward. Since both are generics, you can do like below,

IEnumerable<int> values = Enumerable.Range(1, 10);
List<int> valueList = values.ToList();

But if the IEnumerable is null, when you try to convert it to a List, you'll get ArgumentNullException saying Value cannot be null.

IEnumerable<int> values2 = null;
List<int> valueList2 = values2.ToList();

enter image description here

Therefore as mentioned in the other answer, remember to do a null check before converting it to a List.

What are good message queue options for nodejs?

Shameless plug: I'm working on Bokeh: a simple, scalable and blazing-fast task queue built on ZeroMQ. It supports pluggable data stores for persisting tasks, currently in-memory, Redis and Riak are supported. Check it out.

Draw a curve with css

You could use an asymmetrical border to make curves with CSS.

border-radius: 50%/100px 100px 0 0;

VIEW DEMO

_x000D_
_x000D_
.box {_x000D_
  width: 500px; _x000D_
  height: 100px;  _x000D_
  border: solid 5px #000;_x000D_
  border-color: #000 transparent transparent transparent;_x000D_
  border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

How to import and use image in a Vue single file component?

These both work for me in JavaScript and TypeScript

<img src="@/assets/images/logo.png" alt=""> 

or

 <img src="./assets/images/logo.png" alt="">

How to redirect output of an already running process

Screen

If process is running in a screen session you can use screen's log command to log the output of that window to a file:

Switch to the script's window, C-a H to log.
Now you can :

$ tail -f screenlog.2 | grep whatever

From screen's man page:

log [on|off]

Start/stop writing output of the current window to a file "screenlog.n" in the window's default directory, where n is the number of the current window. This filename can be changed with the 'logfile' command. If no parameter is given, the state of logging is toggled. The session log is appended to the previous contents of the file if it already exists. The current contents and the contents of the scrollback history are not included in the session log. Default is 'off'.

I'm sure tmux has something similar as well.

What's the meaning of System.out.println in Java?

System is a class of java.lang package, out is an object of PrintStream class and also static data member of System class, print() and println() is an instance method of PrintStream class. it is provide soft output on console.

jQuery post() with serialize and extra data

You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.

Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:

var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

I make it simple, if the layout is same i just put the intent it.

My code like this:

public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {


    private Button btnCertificate, btnSeminarKit;

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

        initClick();
    }

    private void initClick() {
        btnCertificate = (Button) findViewById(R.id.btn_Certificate);
        btnCertificate.setOnClickListener(this);

        btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
        btnSeminarKit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_Certificate:
                break;
            case R.id.btn_SeminarKit:
                break;
        }
        Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
        startActivity(intent);
    }
}

Reset/remove CSS styles for element only

If anyone is coming here looking for an answer that utilizes iframe here it is

<iframe srcdoc="<html><body>your-html-here</body></html>" />

https://caniuse.com/iframe-srcdoc

Remove duplicates from an array of objects in JavaScript

You could also use a Map:

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

Full sample:

const things = new Object();

things.thing = new Array();

things.thing.push({place:"here",name:"stuff"});
things.thing.push({place:"there",name:"morestuff"});
things.thing.push({place:"there",name:"morestuff"});

const dedupThings = Array.from(things.thing.reduce((m, t) => m.set(t.place, t), new Map()).values());

console.log(JSON.stringify(dedupThings, null, 4));

Result:

[
    {
        "place": "here",
        "name": "stuff"
    },
    {
        "place": "there",
        "name": "morestuff"
    }
]

How to configure PostgreSQL to accept all incoming connections

0.0.0.0/0 for all IPv4 addresses

::0/0 for all IPv6 addresses

all to match any IP address

samehost to match any of the server's own IP addresses

samenet to match any address in any subnet that the server is directly connected to.

e.g.

host    all             all             0.0.0.0/0            md5

How to check if an integer is within a range?

Most of the given examples assume that for the test range [$a..$b], $a <= $b, i.e. the range extremes are in lower - higher order and most assume that all are integer numbers.
But I needed a function to test if $n was between $a and $b, as described here:

Check if $n is between $a and $b even if:
    $a < $b  
    $a > $b
    $a = $b

All numbers can be real, not only integer.

There is an easy way to test.
I base the test it in the fact that ($n-$a) and ($n-$b) have different signs when $n is between $a and $b, and the same sign when $n is outside the $a..$b range.
This function is valid for testing increasing, decreasing, positive and negative numbers, not limited to test only integer numbers.

function between($n, $a, $b)
{
    return (($a==$n)&&($b==$n))? true : ($n-$a)*($n-$b)<0;
}

When to use @QueryParam vs @PathParam

From Wikipedia: Uniform Resource Locator

A path, which contains data, usually organized in hierarchical form, that appears as a sequence of segments separated by slashes.

An optional query, separated from the preceding part by a question mark (?), containing a query string of non-hierarchical data.

— According with the conceptual design of the URL, we might implement a PathParam for hierarchical data/directives/locator components, or implement a QueryParam when the data are not hierarchical. This makes sense because paths are naturally ordered, whereas queries contain variables which may be ordered arbitrarily (unordered variable/value pairs).

A previous commenter wrote,

I think that if the parameter identifies a specific entity you should use a path variable.

Another wrote,

Use @PathParam for retrieval based on id. User @QueryParam for filter or if you have any fixed list of options that user can pass.

Another,

I'd recommend putting any required parameters in the path, and any optional parameters should certainly be query string parameters.

— However, one might implement a flexible, non-hierarchical system for identifying specific entities! One might have multiple unique indexes on an SQL table, and allow entities to be identified using any combination of fields that comprise a unique index! Different combinations (perhaps also ordered differently), might be used for links from various related entities (referrers). In this case, we might be dealing with non-hierarchical data, used to identify individual entities — or in other cases, might only specify certain variables/fields — certain components of unique indexes — and retrieve a list/set of records. In such cases, it might be easier, more logical and reasonable to implement the URLs as QueryParams!

Could a long hexadecimal string dilute/diminish the value of keywords in the rest of the path? It might be worth considering the potential SEO implications of placing variables/values in the path, or in the query, and the human-interface implications of whether we want users to be able to traverse/explore the hierarchy of URLs by editing the contents of the address bar. My 404 Not Found page uses SSI variables to automatically redirect broken URLs to their parent! Search robots might also traverse the path hierarchy. On the other hand, personally, when I share URLs on social media, I manually strip out any private unique identifiers — typically by truncating the query from the URL, leaving only the path: in this case, there is some utility in placing unique identifiers in the path rather than in the query. Whether we want to facilitate the use of path components as a crude user-interface, perhaps depends on whether the data/components are human-readable or not. The question of human-readability relates somewhat to the question of hierarchy: often, data that may be expressed as human-readable keywords are also hierarchical; while hierarchical data may often be expressed as human-readable keywords. (Search engines themselves might be defined as augmenting the use of URLs as a user-interface.) Hierarchies of keywords or directives might not be strictly ordered, but they are usually close enough that we can cover alternative cases in the path, and label one option as the "canonical" case.

There are fundamentally several kinds of questions we might answer with the URL for each request:

  1. What kind of record/ thing are we requesting/ serving?
  2. Which one(s) are we interested in?
  3. How do we want to present the information/ records?

Q1 is almost certainly best covered by the path, or by PathParams. Q3 (which is probably controlled via a set of arbitrarily ordered optional parameters and default values); is almost certainly best covered by QueryParams. Q2: It depends…

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

Android: Vertical alignment for multi line EditText (Text area)

U can use this Edittext....This will help you.

<EditText
android:id="@+id/EditText02"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="5"
android:gravity="top|left"
android:inputType="textMultiLine" />

How to view table contents in Mysql Workbench GUI?

Inside the workbench right click the table in question and click "Select Rows - Limit 1000." It's the first option in the pop-up menu.

Printing Batch file results to a text file

For Print Result to text file

we can follow

echo "test data" > test.txt

This will create test.txt file and written "test data"

If you want to append then

echo "test data" >> test.txt

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

docker run <IMAGE> <MULTIPLE COMMANDS>

If you want to store the result in one file outside the container, in your local machine, you can do something like this.

RES_FILE=$(readlink -f /tmp/result.txt)

docker run --rm -v ${RES_FILE}:/result.txt img bash -c "cat /etc/passwd | grep root > /result.txt"

The result of your commands will be available in /tmp/result.txt in your local machine.

Case Function Equivalent in Excel

I know it a little late to answer but I think this short video will help you a lot.

http://www.xlninja.com/2012/07/25/excel-choose-function-explained/

Essentially it is using the choose function. He explains it very well in the video so I'll let do it instead of typing 20 pages.

Another video of his explains how to use data validation to populate a drop down which you can select from a limited range.

http://www.xlninja.com/2012/08/13/excel-data-validation-using-dependent-lists/

You could combine the two and use the value in the drop down as your index to the choose function. While he did not show how to combine them, I'm sure you could figure it out as his videos are good. If you have trouble, let me know and I'll update my answer to show you.

Finding the max value of an attribute in an array of objects

if you (or, someone here) are free to use lodash utility library, it has a maxBy function which would be very handy in your case.

hence you can use as such:

_.maxBy(jsonSlice, 'y');

How to list active connections on PostgreSQL?

Oh, I just found that command on PostgreSQL forum:

SELECT * FROM pg_stat_activity;

How to fix error Base table or view not found: 1146 Table laravel relationship table?

This problem occur due to wrong spell or undefined database name. Make sure your database name, table name and all column name is same as from phpmyadmin

Converting an array to a function arguments list

@bryc - yes, you could do it like this:

Element.prototype.setAttribute.apply(document.body,["foo","bar"])

But that seems like a lot of work and obfuscation compared to:

document.body.setAttribute("foo","bar")

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

do you try

[{"name":"myEnterprise", "departments":["HR"]}]

the square brace is the key point.

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

What GRANT USAGE ON SCHEMA exactly do?

Well, this is my final solution for a simple db, for Linux:

# Read this before!
#
# * roles in postgres are users, and can be used also as group of users
# * $ROLE_LOCAL will be the user that access the db for maintenance and
#   administration. $ROLE_REMOTE will be the user that access the db from the webapp
# * you have to change '$ROLE_LOCAL', '$ROLE_REMOTE' and '$DB'
#   strings with your desired names
# * it's preferable that $ROLE_LOCAL == $DB

#-------------------------------------------------------------------------------

//----------- SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - START ----------//

cd /etc/postgresql/$VERSION/main
sudo cp pg_hba.conf pg_hba.conf_bak
sudo -e pg_hba.conf

# change all `md5` with `scram-sha-256`
# save and exit

//------------ SKIP THIS PART UNTIL POSTGRES JDBC ADDS SCRAM - END -----------//

sudo -u postgres psql

# in psql:
create role $ROLE_LOCAL login createdb;
\password $ROLE_LOCAL
create role $ROLE_REMOTE login;
\password $ROLE_REMOTE

create database $DB owner $ROLE_LOCAL encoding "utf8";
\connect $DB $ROLE_LOCAL

# Create all tables and objects, and after that:

\connect $DB postgres

revoke connect on database $DB from public;
revoke all on schema public from public;
revoke all on all tables in schema public from public;

grant connect on database $DB to $ROLE_LOCAL;
grant all on schema public to $ROLE_LOCAL;
grant all on all tables in schema public to $ROLE_LOCAL;
grant all on all sequences in schema public to $ROLE_LOCAL;
grant all on all functions in schema public to $ROLE_LOCAL;

grant connect on database $DB to $ROLE_REMOTE;
grant usage on schema public to $ROLE_REMOTE;
grant select, insert, update, delete on all tables in schema public to $ROLE_REMOTE;
grant usage, select on all sequences in schema public to $ROLE_REMOTE;
grant execute on all functions in schema public to $ROLE_REMOTE;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on tables to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on sequences to $ROLE_LOCAL;

alter default privileges for role $ROLE_LOCAL in schema public
    grant all on functions to $ROLE_LOCAL;

alter default privileges for role $ROLE_REMOTE in schema public
    grant select, insert, update, delete on tables to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant usage, select on sequences to $ROLE_REMOTE;

alter default privileges for role $ROLE_REMOTE in schema public
    grant execute on functions to $ROLE_REMOTE;

# CTRL+D

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

What's the difference between Git Revert, Checkout and Reset?

These three commands have entirely different purposes. They are not even remotely similar.

git revert

This command creates a new commit that undoes the changes from a previous commit. This command adds new history to the project (it doesn't modify existing history).

git checkout

This command checks-out content from the repository and puts it in your work tree. It can also have other effects, depending on how the command was invoked. For instance, it can also change which branch you are currently working on. This command doesn't make any changes to the history.

git reset

This command is a little more complicated. It actually does a couple of different things depending on how it is invoked. It modifies the index (the so-called "staging area"). Or it changes which commit a branch head is currently pointing at. This command may alter existing history (by changing the commit that a branch references).

Using these commands

If a commit has been made somewhere in the project's history, and you later decide that the commit is wrong and should not have been done, then git revert is the tool for the job. It will undo the changes introduced by the bad commit, recording the "undo" in the history.

If you have modified a file in your working tree, but haven't committed the change, then you can use git checkout to checkout a fresh-from-repository copy of the file.

If you have made a commit, but haven't shared it with anyone else and you decide you don't want it, then you can use git reset to rewrite the history so that it looks as though you never made that commit.

These are just some of the possible usage scenarios. There are other commands that can be useful in some situations, and the above three commands have other uses as well.

Fixing a systemd service 203/EXEC failure (no such file or directory)

When this happened to me it was because my script had DOS line endings, which always messes up the shebang line at the top of the script. I changed it to Unix line endings and it worked.

Get IP address of an interface on Linux

My 2 cents: the same code works even if iOS:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    showIP();
}



void showIP()
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1)
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }


    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL)
            continue;

        s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

        if( /*(strcmp(ifa->ifa_name,"wlan0")==0)&&( */ ifa->ifa_addr->sa_family==AF_INET) // )
        {
            if (s != 0)
            {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("\tInterface : <%s>\n",ifa->ifa_name );
            printf("\t  Address : <%s>\n", host);
        }
    }

    freeifaddrs(ifaddr);
}


@end

I simply removed the test against wlan0 to see data. ps You can remove "family"

Redirect form to different URL based on select option element

you can use this simple way

<select onchange="location = this.value;">
                <option value="/finished">Finished</option>
                <option value="/break">Break</option>
                <option value="/issue">Issues</option>
                <option value="/downtime">Downtime</option>
</select>

will redirect to route url you can direct to .html page or direct to some link just change value in option.

Can we have multiple "WITH AS" in single sql - Oracle SQL

Aditya or others, can you join or match up t2 with t1 in your example, i.e. translated to my code,

with t1 as (select * from AA where FIRSTNAME like 'Kermit'),
     t2 as (select * from BB B join t1 on t1.FIELD1 = B.FIELD1)

I am not clear whether only WHERE is supported for joining, or what joining approach is supported within the 2nd WITH entity. Some of the examples have the WHERE A=B down in the body of the select "below" the WITH clauses.

The error I'm getting following these WITH declarations is the identifiers (field names) in B are not recognized, down in the body of the rest of the SQL. So the WITH syntax seems to run OK, but cannot access the results from t2.

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

Use { before $ sign. And also add addslashes function to escape special characters.

$sqlupdate1 = "UPDATE table SET commodity_quantity=".$qty."WHERE user=".addslashes($rows['user'])."'";

Why does my favicon not show up?

Try this:

<link href="img/favicon.ico" rel="shortcut icon" type="image/x-icon" />

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

A little late, but since I've run into the same problem, in your exact scenario, I figured I'd add my solution.

I have Windows 7 (64-bit) and Office 2010 (32-bit). I tried with the DSN-less connection string:

jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=I:/TeamForge/ORS/CTFORS.accdb

and I tried with the DSN connection, using both the System32 and SysWOW64 versions of the ODBC Admin, and none of that worked.

What finally worked, was to match the bit version of Java with the bit version of Office. Once I did that, I could use either the DSN or DSN less connection mode, without any fuss.

How to add Headers on RESTful call using Jersey Client API

Here is an example how I do it.

import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.util.Map;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

Gson gson = new Gson();
Type type = new TypeToken<Map<String, String>>() {
}.getType();
MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
formData.add("key1", "value1");
formData.add("key1", "value2");
WebTarget webTarget = ClientBuilder.newClient().target("https://some.server.url/");
String response = webTarget.path("subpath/subpath2").request().post(Entity.form(formData), String.class);
Map<String, String> gsonResponse = gson.fromJson(response, type);

Deleting objects from an ArrayList in Java

Maybe Iterator’s remove() method? The JDK’s default collection classes should all creator iterators that support this method.

Twig: in_array or similar possible within if statement?

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

Can I use Homebrew on Ubuntu?

I just tried installing it using the ruby command but somehow the dependencies are not resolved hence brew does not completely install. But, try installing by cloning:

git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew

and then add the following to your .bash_profile:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

It should work..

error code 1292 incorrect date value mysql

Insert date in the following format yyyy-MM-dd example,

INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) 
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')

Epoch vs Iteration when training neural networks

According to Google's Machine Learning Glossary, an epoch is defined as

"A full training pass over the entire dataset such that each example has been seen once. Thus, an epoch represents N/batch_size training iterations, where N is the total number of examples."

If you are training model for 10 epochs with batch size 6, given total 12 samples that means:

  1. the model will be able to see whole dataset in 2 iterations ( 12 / 6 = 2) i.e. single epoch.

  2. overall, the model will have 2 X 10 = 20 iterations (iterations-per-epoch X no-of-epochs)

  3. re-evaluation of loss and model parameters will be performed after each iteration!

How to call a method daily, at specific time, in C#?

As others have said you can use a console app to run when scheduled. What others haven't said is that you can this app trigger a cross process EventWaitHandle which you are waiting on in your main application.

Console App:

class Program
{
    static void Main(string[] args)
    {
        EventWaitHandle handle = 
            new EventWaitHandle(true, EventResetMode.ManualReset, "GoodMutexName");
        handle.Set();
    }
}

Main App:

private void Form1_Load(object sender, EventArgs e)
{
    // Background thread, will die with application
    ThreadPool.QueueUserWorkItem((dumby) => EmailWait());
}

private void EmailWait()
{
    EventWaitHandle handle = 
        new EventWaitHandle(false, EventResetMode.ManualReset, "GoodMutexName");

    while (true)
    {
        handle.WaitOne();

        SendEmail();

        handle.Reset();
    }
}

Jenkins not executing jobs (pending - waiting for next executor)

What worked for me: I finally noticed the Build Executor Status window on the left on the main Jenkins dashboard. I run a dev/test instance on my local system with 2 executors. Both were currently occupied with builds that were not running. Upon cancelling these to jobs, my third (pending) job was able to run.

Android ImageView's onClickListener does not work

Had the same problem, thanks for the Framelayout tip! I was using two overlapped images in a framelayout (the one at top was an alpha mask, to give the effect of soft borders)

I set in the xml android:clickable="true" for the image I wanted to launch the onClickListener, and android:clickable="false" to the alpha mask.

How to remove an HTML element using Javascript?

Your JavaScript is correct. Your button has type="submit" which is causing the page to refresh.

Delete certain lines in a txt file via a batch file

If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}" should do the trick.

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

Although this an old post, I am sharing another working example.

"COLUMN COUNT AS WELL AS EACH COLUMN DATATYPE MUST MATCH WHEN 'UNION' OR 'UNION ALL' IS USED"

Let us take an example:

1:

In SQL if we write - SELECT 'column1', 'column2' (NOTE: remember to specify names in quotes) In a result set, it will display empty columns with two headers - column1 and column2

2: I share one simple instance I came across.

I had seven columns with few different datatypes in SQL. I.e. uniqueidentifier, datetime, nvarchar

My task was to retrieve comma separated result set with column header. So that when I export the data to CSV I have comma separated rows with first row as header and has respective column names.

SELECT CONVERT(NVARCHAR(36), 'Event ID') + ', ' + 
'Last Name' + ', ' + 
'First Name' + ', ' + 
'Middle Name' + ', ' + 
CONVERT(NVARCHAR(36), 'Document Type') + ', ' + 
'Event Type' + ', ' + 
CONVERT(VARCHAR(23), 'Last Updated', 126)

UNION ALL

SELECT CONVERT(NVARCHAR(36), inspectionid) + ', ' + 
       individuallastname + ', ' + 
       individualfirstname + ', ' + 
       individualmiddlename + ', ' +
       CONVERT(NVARCHAR(36), documenttype) + ', ' + 
       'I' + ', ' +
       CONVERT(VARCHAR(23), modifiedon, 126)
FROM Inspection

Above, columns 'inspectionid' & 'documenttype' has uniqueidentifer datatype and so applied CONVERT(NVARCHAR(36)). column 'modifiedon' is datetime and so applied CONVERT(NVARCHAR(23), 'modifiedon', 126).

Parallel to above 2nd SELECT query matched 1st SELECT query as per datatype of each column.

How to make a hyperlink in telegram without using bots?

In telegram desktop, use this hotkey: ctrl+K

In android:

  1. type your text
  2. select it
  3. and click on Create Link from its options

You can see these steps in this image: link creation in telegram android

MySQL VARCHAR size?

100 characters.

This is the var (variable) in varchar: you only store what you enter (and an extra 2 bytes to store length upto 65535)

If it was char(200) then you'd always store 200 characters, padded with 100 spaces

See the docs: "The CHAR and VARCHAR Types"

Python xticks in subplots

See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:

  • If you want to set the xticklabels:

    ax.set_xticks([1,4,5]) 
    ax.set_xticklabels([1,4,5], fontsize=12)
    
  • If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):

    ax.tick_params(axis="x", labelsize=12) 
    
  • To do it all at once:

    plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold", 
             horizontalalignment="left")`
    

Can local storage ever be considered secure?

As an exploration of this topic, I have a presentation titled "Securing TodoMVC Using the Web Cryptography API" (video, code).

It uses the Web Cryptography API to store the todo list encrypted in localStorage by password protecting the application and using a password derived key for encryption. If you forget or lose the password, there is no recovery. (Disclaimer - it was a POC and not intended for production use.)

As the other answers state, this is still susceptible to XSS or malware installed on the client computer. However, any sensitive data would also be in memory when the data is stored on the server and the application is in use. I suggest that offline support may be the compelling use case.

In the end, encrypting localStorage probably only protects the data from attackers that have read only access to the system or its backups. It adds a small amount of defense in depth for OWASP Top 10 item A6-Sensitive Data Exposure, and allows you to answer "Is any of this data stored in clear text long term?" correctly.

Creating a list of objects in Python

It shouldn't be necessary to recreate the SimpleClass object each time, as some are suggesting, if you're simply using it to output data based on its attributes. However, you're not actually creating an instance of the class; you're simply creating a reference to the class object itself. Therefore, you're adding a reference to the same class attribute to the list (instead of instance attribute), over and over.

Instead of:

x = SimpleClass

you need:

x = SimpleClass()

How do I check if a string contains another string in Objective-C?

So personally I really hate NSNotFound but understand its necessity.

But some people may not understand the complexities of comparing against NSNotFound

For example, this code:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if([string rangeOfString:otherString].location != NSNotFound)
        return YES;
    else
        return NO;
}

has its problems:

1) Obviously if otherString = nil this code will crash. a simple test would be:

NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");

results in !! CRASH !!

2) What is not so obvious to someone new to objective-c is that the same code will NOT crash when string = nil. For example, this code:

NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");

and this code:

NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");

will both result in

does string contains string - YES

Which is clearly NOT what you want.

So the better solution that I believe works is to use the fact that rangeOfString returns the length of 0 so then a better more reliable code is this:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    if(otherString && [string rangeOfString:otherString].length)
        return YES;
    else
        return NO;
}

OR SIMPLY:

- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
    return (otherString && [string rangeOfString:otherString].length);
}

which will for cases 1 and 2 will return

does string contains string - NO

That's my 2 cents ;-)

Please check out my Gist for more helpful code.

How do I style a <select> dropdown with only CSS?

Use the clip property to crop the borders and the arrow of the select element, then add your own replacement styles to the wrapper:

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
      <head>_x000D_
        <style>_x000D_
          select { position: absolute; clip:rect(2px 49px 19px 2px); z-index:2; }_x000D_
          body > span { display:block; position: relative; width: 64px; height: 21px; border: 2px solid green;  background: url(http://www.stackoverflow.com/favicon.ico) right 1px no-repeat; }_x000D_
        </style>_x000D_
      </head>_x000D_
      <span>_x000D_
        <select>_x000D_
          <option value="">Alpha</option>_x000D_
          <option value="">Beta</option>_x000D_
          <option value="">Charlie</option>_x000D_
        </select>_x000D_
      </span>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Use a second select with zero opacity to make the button clickable:

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
      <head>_x000D_
        <style>_x000D_
          #real { position: absolute; clip:rect(2px 51px 19px 2px); z-index:2; }_x000D_
          #fake { position: absolute; opacity: 0; }_x000D_
    _x000D_
          body > span { display:block; position: relative; width: 64px; height: 21px; background: url(http://www.stackoverflow.com/favicon.ico) right 1px no-repeat; }_x000D_
        </style>_x000D_
      </head>_x000D_
      <span>_x000D_
        <select id="real">_x000D_
          <option value="">Alpha</option>_x000D_
          <option value="">Beta</option>_x000D_
          <option value="">Charlie</option>_x000D_
        </select>_x000D_
        <select id="fake">_x000D_
          <option value="">Alpha</option>_x000D_
          <option value="">Beta</option>_x000D_
          <option value="">Charlie</option>_x000D_
        </select>_x000D_
      </span>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Coordinates differ between Webkit and other browsers, but a @media query can cover that.

References

Play multiple CSS animations at the same time

You cannot play two animations since the attribute can be defined only once. Rather why don't you include the second animation in the first and adjust the keyframes to get the timing right?

_x000D_
_x000D_
.image {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    width: 120px;_x000D_
    height: 120px;_x000D_
    margin:-60px 0 0 -60px;_x000D_
    -webkit-animation:spin-scale 4s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin-scale { _x000D_
    50%{_x000D_
        transform: rotate(360deg) scale(2);_x000D_
    }_x000D_
    100% { _x000D_
        transform: rotate(720deg) scale(1);_x000D_
    } _x000D_
}
_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
_x000D_
_x000D_
_x000D_

Java JTextField with input hint

Here is a simple way that looks good in any L&F:

public class HintTextField extends JTextField {
    public HintTextField(String hint) {
        _hint = hint;
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (getText().length() == 0) {
            int h = getHeight();
            ((Graphics2D)g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            Insets ins = getInsets();
            FontMetrics fm = g.getFontMetrics();
            int c0 = getBackground().getRGB();
            int c1 = getForeground().getRGB();
            int m = 0xfefefefe;
            int c2 = ((c0 & m) >>> 1) + ((c1 & m) >>> 1);
            g.setColor(new Color(c2, true));
            g.drawString(_hint, ins.left, h / 2 + fm.getAscent() / 2 - 2);
        }
    }
    private final String _hint;
}

ssh: check if a tunnel is alive

#!/bin/bash

# Check do we have tunnel to example.com server
lsof -i tcp@localhost:6000 > /dev/null

# If exit code wasn't 0 then tunnel doesn't exist.
if [ $? -eq 1 ]
then
  echo ' > You missing ssh tunnel. Creating one..'
  ssh -L 6000:localhost:5432 example.com
fi

echo ' > DO YOUR STUFF < '

Count the number of occurrences of a string in a VARCHAR field?

This is the mysql function using the space technique (tested with mysql 5.0 + 5.5): CREATE FUNCTION count_str( haystack TEXT, needle VARCHAR(32)) RETURNS INTEGER DETERMINISTIC RETURN LENGTH(haystack) - LENGTH( REPLACE ( haystack, needle, space(char_length(needle)-1)) );

Android map v2 zoom to show all the markers

Show All Markers with Google map

In these Methods store all Markers and automatically zoom to show all markers in google map.

// Declare the Markers List.
List<MarkerOptions> markerList;
private BitmapDescriptor vnrPoint,banPoint;


public void storeAllMarkers()
{
      markerList=new ArrayList<>();
      markerList.removeAll(markerList);


      // latitude and longitude of Virudhunagar

      double latitude1=9.587209;
      double longitude1=77.951431;
   vnrPoint=BitmapDescriptorFactory.fromResource(R.drawable.location_icon_1);
      LatLng vnr = new LatLng(latitude1, longitude1);
      MarkerOptions vnrMarker = new MarkerOptions();
      vnrMarker.position(vnr);
      vnrMarker.icon(vnrPoint);
      markerList.add(vnrMarker);

      // latitude and longitude of Bengaluru

      double latitude2=12.972442;
      double longitude2=77.580643;

    banPoint=BitmapDescriptorFactory.fromResource(R.drawable.location_icon_2);

      LatLng ban = new LatLng(latitude2, longitude2);
      MarkerOptions bengalureMarker = new MarkerOptions();
      bengalureMarker.position(ban);
      bengalureMarker.icon(banPoint);
      markerList.add(bengalureMarker);

      // You can add any numbers of MarkerOptions like this.

     showAllMarkers();

 }


public void showAllMarkers()
{
    LatLngBounds.Builder builder = new LatLngBounds.Builder();

    for (MarkerOptions m : markerList) {
        builder.include(m.getPosition());
    }

    LatLngBounds bounds = builder.build();

    int width = getResources().getDisplayMetrics().widthPixels;
    int height = getResources().getDisplayMetrics().heightPixels;
    int padding = (int) (width * 0.30); 

    // Zoom and animate the google map to show all markers

    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, width, height, padding);
    googleMap.animateCamera(cu);
}

How to increase editor font size?

As a temporary tweak ( not permanent )

On Mac you would need to create your own shortcuts ..

Its easy. my set:

CMD + Wheel-up for increase font size

CMD + Wheel-down for decreasing font size

Prefernces => Keymap => Increase Font size/decrease Font size/Reset Font size

enter image description here

Good luck,'.

Difference between Hashing a Password and Encrypting it

Hashing is a one way function (well, a mapping). It's irreversible, you apply the secure hash algorithm and you cannot get the original string back. The most you can do is to generate what's called "a collision", that is, finding a different string that provides the same hash. Cryptographically secure hash algorithms are designed to prevent the occurrence of collisions. You can attack a secure hash by the use of a rainbow table, which you can counteract by applying a salt to the hash before storing it.

Encrypting is a proper (two way) function. It's reversible, you can decrypt the mangled string to get original string if you have the key.

The unsafe functionality it's referring to is that if you encrypt the passwords, your application has the key stored somewhere and an attacker who gets access to your database (and/or code) can get the original passwords by getting both the key and the encrypted text, whereas with a hash it's impossible.

People usually say that if a cracker owns your database or your code he doesn't need a password, thus the difference is moot. This is naïve, because you still have the duty to protect your users' passwords, mainly because most of them do use the same password over and over again, exposing them to a greater risk by leaking their passwords.

Failed to serialize the response in Web API with Json

Visual Studio 2017 or 2019 is totally unthoughtful on this, because Visual Studio itself requires the output to be in json format, while Visual Studio's default format is "XmlFormat" (config.Formatters.XmlFormatter).

Visual Studio should do this automatically instead of giving developers so much trouble.

To correct this problem, go to the WebApiConfig.cs file, and add

var json = config.Formatters.JsonFormatter; json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects; config.Formatters.Remove(config.Formatters.XmlFormatter);

after "config.MapHttpAttributeRoutes();" in the Register(HttpConfiguration config) method. This would allow your project to produce json output.

Convert pandas.Series from dtype object to float, and errors to nans

Use pd.to_numeric with errors='coerce'

# Setup
s = pd.Series(['1', '2', '3', '4', '.'])
s

0    1
1    2
2    3
3    4
4    .
dtype: object

pd.to_numeric(s, errors='coerce')

0    1.0
1    2.0
2    3.0
3    4.0
4    NaN
dtype: float64

If you need the NaNs filled in, use Series.fillna.

pd.to_numeric(s, errors='coerce').fillna(0, downcast='infer')

0    1
1    2
2    3
3    4
4    0
dtype: float64

Note, downcast='infer' will attempt to downcast floats to integers where possible. Remove the argument if you don't want that.

From v0.24+, pandas introduces a Nullable Integer type, which allows integers to coexist with NaNs. If you have integers in your column, you can use

pd.__version__
# '0.24.1'

pd.to_numeric(s, errors='coerce').astype('Int32')

0      1
1      2
2      3
3      4
4    NaN
dtype: Int32

There are other options to choose from as well, read the docs for more.


Extension for DataFrames

If you need to extend this to DataFrames, you will need to apply it to each row. You can do this using DataFrame.apply.

# Setup.
np.random.seed(0)
df = pd.DataFrame({
    'A' : np.random.choice(10, 5), 
    'C' : np.random.choice(10, 5), 
    'B' : ['1', '###', '...', 50, '234'], 
    'D' : ['23', '1', '...', '268', '$$']}
)[list('ABCD')]
df

   A    B  C    D
0  5    1  9   23
1  0  ###  3    1
2  3  ...  5  ...
3  3   50  2  268
4  7  234  4   $$

df.dtypes

A     int64
B    object
C     int64
D    object
dtype: object

df2 = df.apply(pd.to_numeric, errors='coerce')
df2

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

df2.dtypes

A      int64
B    float64
C      int64
D    float64
dtype: object

You can also do this with DataFrame.transform; although my tests indicate this is marginally slower:

df.transform(pd.to_numeric, errors='coerce')

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

If you have many columns (numeric; non-numeric), you can make this a little more performant by applying pd.to_numeric on the non-numeric columns only.

df.dtypes.eq(object)

A    False
B     True
C    False
D     True
dtype: bool

cols = df.columns[df.dtypes.eq(object)]
# Actually, `cols` can be any list of columns you need to convert.
cols
# Index(['B', 'D'], dtype='object')

df[cols] = df[cols].apply(pd.to_numeric, errors='coerce')
# Alternatively,
# for c in cols:
#     df[c] = pd.to_numeric(df[c], errors='coerce')

df

   A      B  C      D
0  5    1.0  9   23.0
1  0    NaN  3    1.0
2  3    NaN  5    NaN
3  3   50.0  2  268.0
4  7  234.0  4    NaN

Applying pd.to_numeric along the columns (i.e., axis=0, the default) should be slightly faster for long DataFrames.

How do I truncate a .NET string?

There is nothing in .net for this that I am aware of - here is my version which adds "...":

public static string truncateString(string originalString, int length) {
  if (string.IsNullOrEmpty(originalString)) {
   return originalString;
  }
  if (originalString.Length > length) {
   return originalString.Substring(0, length) + "...";
  }
  else {
   return originalString;
  }
}

Turn Pandas Multi-Index into column

There may be situations when df.reset_index() cannot be used (e.g., when you need the index, too). In this case, use index.get_level_values() to access index values directly:

df['Trial'] = df.index.get_level_values(0)
df['measurement'] = df.index.get_level_values(1)

This will assign index values to individual columns and keep the index.

See the docs for further info.

Right way to split an std::string into a vector<string>

If the string has both spaces and commas you can use the string class function

found_index = myString.find_first_of(delims_str, begin_index) 

in a loop. Checking for != npos and inserting into a vector. If you prefer old school you can also use C's

strtok() 

method.

How do I detect what .NET Framework versions and service packs are installed?

The registry is the official way to detect if a specific version of the Framework is installed.

enter image description here

Which registry keys are needed change depending on the Framework version you are looking for:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\.NETFramework\Policy\v1.0\3705 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\Install 
2.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Install 
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Setup\InstallSuccess 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Install
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Install

Generally you are looking for:

"Install"=dword:00000001

except for .NET 1.0, where the value is a string (REG_SZ) rather than a number (REG_DWORD).

Determining the service pack level follows a similar pattern:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 
1.0[1]             HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322\SP 
2.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\SP 
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\SP 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Client\Servicing
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full\Servicing

[1] Windows Media Center or Windows XP Tablet Edition

As you can see, determining the SP level for .NET 1.0 changes if you are running on Windows Media Center or Windows XP Tablet Edition. Again, .NET 1.0 uses a string value while all of the others use a DWORD.

For .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The last # is the Service Pack level.

While I didn't explicitly ask for this, if you want to know the exact version number of the Framework you would use these registry keys:

Framework Version  Registry Key
------------------------------------------------------------------------------------------
1.0                HKLM\Software\Microsoft\Active Setup\Installed Components\{78705f0d-e8db-4b2d-8193-982bdda15ecd}\Version 
1.0[1]             HKLM\Software\Microsoft\Active Setup\Installed Components\{FDC11A6F-17D1-48f9-9EA3-9051954BAA24}\Version 
1.1                HKLM\Software\Microsoft\NET Framework Setup\NDP\v1.1.4322 
2.0[2]             HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Version 
2.0[3]             HKLM\Software\Microsoft\NET Framework Setup\NDP\v2.0.50727\Increment
3.0                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.0\Version 
3.5                HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Version 
4.0 Client Profile HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 
4.0 Full Profile   HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Version 

[1] Windows Media Center or Windows XP Tablet Edition
[2] .NET 2.0 SP1
[3] .NET 2.0 Original Release (RTM)

Again, .NET 1.0 uses a string value while all of the others use a DWORD.

Additional Notes

  • for .NET 1.0 the string value at either of these keys has a format of #,#,####,#. The #,#,#### portion of the string is the Framework version.

  • for .NET 1.1, we use the name of the registry key itself, which represents the version number.

  • Finally, if you look at dependencies, .NET 3.0 adds additional functionality to .NET 2.0 so both .NET 2.0 and .NET 3.0 must both evaulate as being installed to correctly say that .NET 3.0 is installed. Likewise, .NET 3.5 adds additional functionality to .NET 2.0 and .NET 3.0, so .NET 2.0, .NET 3.0, and .NET 3. should all evaluate to being installed to correctly say that .NET 3.5 is installed.

  • .NET 4.0 installs a new version of the CLR (CLR version 4.0) which can run side-by-side with CLR 2.0.

Update for .NET 4.5

There won't be a v4.5 key in the registry if .NET 4.5 is installed. Instead you have to check if the HKLM\Software\Microsoft\NET Framework Setup\NDP\v4\Full key contains a value called Release. If this value is present, .NET 4.5 is installed, otherwise it is not. More details can be found here and here.

Defining arrays in Google Scripts

This may be of help to a few who are struggling like I was:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];

Confused about Service vs Factory

This is what helped me to understand the difference, thanks to a blog post by Pascal Precht.

A service is a method on a module that takes a name and a function that defines the service. You can inject and use that particular service in other components, like controllers, directives and filters. A factory is a method on a module and it also takes a name and a function, that defines the factory. We can also inject and use the it same way we did with the service.

Objects created with new use the value of the prototype property of their constructor function as their prototype, so I found the Angular code that calls Object.create(), that I believe is the service constructor function when it gets instantiated. However, a factory function is really just a function that gets called, which is why we have to return an object literal for the factory.

Here is the angular 1.5 code I found for factory:

var needsRecurse = false;
    var destination = copyType(source);

    if (destination === undefined) {
      destination = isArray(source) ? [] : Object.create(getPrototypeOf(source));
      needsRecurse = true;
    }

Angular source code snippet for the factory() function:

 function factory(name, factoryFn, enforce) {
    return provider(name, {
      $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
    });
  }

It takes the name and the factory function that is passed and returns a provider with the same name, that has a $get method which is our factory function. Whenever you ask the injector for a specific dependency, it basically asks the corresponding provider for an instance of that service, by calling the $get() method. That’s why $get() is required, when creating providers.

Here is the angular 1.5 code for service.

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
  }

It turns out that when we call service(), it actually calls factory()! However, it doesn’t just pass our service constructor function to the factory as is. It also passes a function that asks the injector to instantiate an object by the given constructor.

In other words, if we inject MyService somewhere, what happens in the code is:

MyServiceProvider.$get(); // return the instance of the service

To restate it again, a service calls a factory, which is a $get() method on the corresponding provider. Moreover, $injector.instantiate() is the method that ultimately calls Object.create() with the constructor function. That’s why we use "this" in services.

For ES5 it doesn't matter which we use: service() or factory(), it’s always a factory that is called which creates a provider for our service.

You can do the exact same thing with services as well though. A service is a constructor function, however, that doesn’t prevent us from returning object literals. So we can take our service code and write it in a way that it basically does the exact same thing as our factory or in other words, you can write a service as a factory to return an object.

Why do most people recommend to use factories over services? This is the best answer I've seen which comes from Pawel Kozlowski's book: Mastering Web Application Development with AngularJS.

The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate "private" variables. This is very useful as we can hide implementation details of a given service."

Bootstrap date time picker

All scripts should be imported in order:

  1. jQuery and Moment.js
  2. Bootstrap js file
  3. Bootstrap datepicker js file

Bootstrap-datetimepicker requires moment.js to be loaded before datepicker.js.

Working snippet:

_x000D_
_x000D_
$(function() {_x000D_
  $('#datetimepicker1').datetimepicker();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.7.14/css/bootstrap-datetimepicker.min.css">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class='col-sm-6'>_x000D_
      <div class="form-group">_x000D_
        <div class='input-group date' id='datetimepicker1'>_x000D_
          <input type='text' class="form-control" />_x000D_
          <span class="input-group-addon">_x000D_
            <span class="glyphicon glyphicon-calendar"></span>_x000D_
          </span>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTML5 and frameborder

How about using the same for technique for "fooling" the validator with Javascript by sticking a target attribute in XHTML <a onclick="this.target='_blank'">?

  • onsomething = " this.frameborder = '0' "

<iframe onload = " this.frameborder='0' " src="menu.html" id="menu"> </iframe>

Or getElementsByTagName]("iframe")1 adding this attribute for all iframes on the page?

Haven't tested this because I've done something which means that nothing is working in IE less than 9! :) So while I'm sorting that out ... :)

How do you add a JToken to an JObject?

Just adding .First to your bananaToken should do it:
foodJsonObj["food"]["fruit"]["orange"].Parent.AddAfterSelf(bananaToken .First);
.First basically moves past the { to make it a JProperty instead of a JToken.

@Brian Rogers, Thanks I forgot the .Parent. Edited

How to get std::vector pointer to the raw data?

&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken).

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via

  • &something[0] or &something.front() (the address of the element at index 0), or

  • &*something.begin() (the address of the element pointed to by the iterator returned by begin()).

In C++11, a new member function was added to std::vector: data(). This member function returns the address of the initial element in the container, just like &something.front(). The advantage of this member function is that it is okay to call it even if the container is empty.

How to create a file with a given size in Linux?

On OSX (and Solaris, apparently), the mkfile command is available as well:

mkfile 10g big_file

This makes a 10 GB file named "big_file". Found this approach here.

How do I fix MSB3073 error in my post-build event?

Prefer the MsBuild "Copy" task in an AfterBuild target over a post-build event.

Append this Target into your project file and remove the PostBuildEvent.

<Target Name="AfterBuild">
    <Copy SourceFiles="C:\Users\scogan\Documents\Visual Studio 2012\Projects\Organizr\Server\bin\Debug\Organizr.Services.*" 
          DestinationFolder="C:\inetpub\wwwroot\AppServer\bin\" 
          OverwriteReadOnlyFiles="true" 
          SkipUnchangedFiles="false" />
</Target>

how to change background image of button when clicked/focused?

Its very easy to implement . For that you need to create a one xml file(selector file) and put it in drawable folder in res. After that set xml file in button's background in your layout file.

button_background_selector.xml

<?xml version="1.0" encoding="UTF-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/your_hover_image" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/your_hover_image" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/your_hover_image"/>
    <item android:drawable="@drawable/your_simple_image" />
</selector>

Now set the above file in button's background.

<Button
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:textColor="@color/grey_text"
    android:background="@drawable/button_background_selector"/>

How to convert a date to milliseconds

tl;dr

LocalDateTime.parse(           // Parse into an object representing a date with a time-of-day but without time zone and without offset-from-UTC.
    "2014/10/29 18:10:45"      // Convert input string to comply with standard ISO 8601 format.
    .replace( " " , "T" )      // Replace SPACE in the middle with a `T`.
    .replace( "/" , "-" )      // Replace SLASH in the middle with a `-`.
)
.atZone(                       // Apply a time zone to provide the context needed to determine an actual moment.
    ZoneId.of( "Europe/Oslo" ) // Specify the time zone you are certain was intended for that input.
)                              // Returns a `ZonedDateTime` object.
.toInstant()                   // Adjust into UTC.
.toEpochMilli()                // Get the number of milliseconds since first moment of 1970 in UTC, 1970-01-01T00:00Z.

1414602645000

Time Zone

The accepted answer is correct, except that it ignores the crucial issue of time zone. Is your input string 6:10 PM in Paris or Montréal? Or UTC?

Use a proper time zone name. Usually a continent plus city/region. For example, "Europe/Oslo". Avoid the 3 or 4 letter codes which are neither standardized nor unique.

java.time

The modern approach uses the java.time classes.

Alter your input to conform with the ISO 8601 standard. Replace the SPACE in the middle with a T. And replace the slash characters with hyphens. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.

String input = "2014/10/29 18:10:45".replace( " " , "T" ).replace( "/" , "-" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;

A LocalDateTime, like your input string, lacks any concept of time zone or offset-from-UTC. Without the context of a zone/offset, a LocalDateTime has no real meaning. Is it 6:10 PM in India, Europe, or Canada? Each of those places experience 6:10 PM at different moments, at different points on the timeline. So you must specify which you have in mind if you want to determine a specific point on the timeline.

ZoneId z = ZoneId.of( "Europe/Oslo" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;  

Now we have a specific moment, in that ZonedDateTime. Convert to UTC by extracting a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = zdt.toInstant() ;

Now we can get your desired count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z.

long millisSinceEpoch = instant.toEpochMilli() ; 

Be aware of possible data loss. The Instant object is capable of carrying microseconds or nanoseconds, finer than milliseconds. That finer fractional part of a second will be ignored when getting a count of milliseconds.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.


Joda-Time

Update: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. I will leave this section intact for history.

Below is the same kind of code but using the Joda-Time 2.5 library and handling time zone.

The java.util.Date, .Calendar, and .SimpleDateFormat classes are notoriously troublesome, confusing, and flawed. Avoid them. Use either Joda-Time or the java.time package (inspired by Joda-Time) built into Java 8.

ISO 8601

Your string is almost in ISO 8601 format. The slashes need to be hyphens and the SPACE in middle should be replaced with a T. If we tweak that, then the resulting string can be fed directly into constructor without bothering to specify a formatter. Joda-Time uses ISO 8701 formats as it's defaults for parsing and generating strings.

Example Code

String inputRaw = "2014/10/29 18:10:45";
String input = inputRaw.replace( "/", "-" ).replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "Europe/Oslo" ); // Or DateTimeZone.UTC
DateTime dateTime = new DateTime( input, zone );
long millisecondsSinceUnixEpoch = dateTime.getMillis();

How to get database structure in MySQL via query

A variation of the first answer that I found useful

Open your command prompt and enter (you dont have to be logged into your mysql server)

mysqldump -hlocalhost -u<root> -p<password>  <dbname>  --compact --no-data > </path_to_mydump/>mysql.dmp

If a DOM Element is removed, are its listeners also removed from memory?

Yes, the garbage collector will remove them as well. Might not always be the case with legacy browsers though.

Best C/C++ Network Library

Aggregated List of Libraries

Append values to a set in Python

You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}

Or a shorter form using |=:

>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.

Spring MVC @PathVariable with dot (.) is getting truncated

In Spring Boot Rest Controller, I have resolved these by following Steps:

RestController :

@GetMapping("/statusByEmail/{email:.+}/")
public String statusByEmail(@PathVariable(value = "email") String email){
  //code
}

And From Rest Client:

Get http://mywebhook.com/statusByEmail/[email protected]/

How to represent a fix number of repeats in regular expression?

^\w{14}$ in Perl and any Perl-style regex.

If you want to learn more about regular expressions - or just need a handy reference - the Wikipedia Entry on Regular Expressions is actually pretty good.

VBA Public Array : how to?

Try this:

Dim colHeader(12)
colHeader = ("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L")

Unfortunately the code found online was VB.NET not VBA.

How to handle calendar TimeZones using Java?

Something that has worked for me in the past was to determine the offset (in milliseconds) between the user's timezone and GMT. Once you have the offset, you can simply add/subtract (depending on which way the conversion is going) to get the appropriate time in either timezone. I would usually accomplish this by setting the milliseconds field of a Calendar object, but I'm sure you could easily apply it to a timestamp object. Here's the code I use to get the offset

int offset = TimeZone.getTimeZone(timezoneId).getRawOffset();

timezoneId is the id of the user's timezone (such as EST).

Running Command Line in Java

what about

public class CmdExec {

public static Scanner s = null;


public static void main(String[] args) throws InterruptedException, IOException {
    s = new Scanner(System.in);
    System.out.print("$ ");
    String cmd = s.nextLine();
    final Process p = Runtime.getRuntime().exec(cmd);

    new Thread(new Runnable() {
        public void run() {
            BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = null; 

            try {
                while ((line = input.readLine()) != null) {
                    System.out.println(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    p.waitFor();
     }

 }

Why is it bad practice to call System.gc()?

This is a very bothersome question, and I feel contributes to many being opposed to Java despite how useful of a language it is.

The fact that you can't trust "System.gc" to do anything is incredibly daunting and can easily invoke "Fear, Uncertainty, Doubt" feel to the language.

In many cases, it is nice to deal with memory spikes that you cause on purpose before an important event occurs, which would cause users to think your program is badly designed/unresponsive.

Having ability to control the garbage collection would be very a great education tool, in turn improving people's understanding how the garbage collection works and how to make programs exploit it's default behavior as well as controlled behavior.

Let me review the arguments of this thread.

  1. It is inefficient:

Often, the program may not be doing anything and you know it's not doing anything because of the way it was designed. For instance, it might be doing some kind of long wait with a large wait message box, and at the end it may as well add a call to collect garbage because the time to run it will take a really small fraction of the time of the long wait but will avoid gc from acting up in the middle of a more important operation.

  1. It is always a bad practice and indicates broken code.

I disagree, it doesn't matter what garbage collector you have. Its' job is to track garbage and clean it.

By calling the gc during times where usage is less critical, you reduce odds of it running when your life relies on the specific code being run but instead it decides to collect garbage.

Sure, it might not behave the way you want or expect, but when you do want to call it, you know nothing is happening, and user is willing to tolerate slowness/downtime. If the System.gc works, great! If it doesn't, at least you tried. There's simply no down side unless the garbage collector has inherent side effects that do something horribly unexpected to how a garbage collector is suppose to behave if invoked manually, and this by itself causes distrust.

  1. It is not a common use case:

It is a use case that cannot be achieved reliably, but could be if the system was designed that way. It's like making a traffic light and making it so that some/all of the traffic lights' buttons don't do anything, it makes you question why the button is there to begin with, javascript doesn't have garbage collection function so we don't scrutinize it as much for it.

  1. The spec says that System.gc() is a hint that GC should run and the VM is free to ignore it.

what is a "hint"? what is "ignore"? a computer cannot simply take hints or ignore something, there are strict behavior paths it takes that may be dynamic that are guided by the intent of the system. A proper answer would include what the garbage collector is actually doing, at implementation level, that causes it to not perform collection when you request it. Is the feature simply a nop? Is there some kind of conditions that must me met? What are these conditions?

As it stands, Java's GC often seems like a monster that you just don't trust. You don't know when it's going to come or go, you don't know what it's going to do, how it's going to do it. I can imagine some experts having better idea of how their Garbage Collection works on per-instruction basis, but vast majority simply hopes it "just works", and having to trust an opaque-seeming algorithm to do work for you is frustrating.

There is a big gap between reading about something or being taught something, and actually seeing the implementation of it, the differences across systems, and being able to play with it without having to look at the source code. This creates confidence and feeling of mastery/understanding/control.

To summarize, there is an inherent problem with the answers "this feature might not do anything, and I won't go into details how to tell when it does do something and when it doesn't and why it won't or will, often implying that it is simply against the philosophy to try to do it, even if the intent behind it is reasonable".

It might be okay for Java GC to behave the way it does, or it might not, but to understand it, it is difficult to truly follow in which direction to go to get a comprehensive overview of what you can trust the GC to do and not to do, so it's too easy simply distrust the language, because the purpose of a language is to have controlled behavior up to philosophical extent(it's easy for a programmer, especially novices to fall into existential crisis from certain system/language behaviors) you are capable of tolerating(and if you can't, you just won't use the language until you have to), and more things you can't control for no known reason why you can't control them is inherently harmful.

Making a DateTime field in a database automatic?

You need to set the "default value" for the date field to getdate(). Any records inserted into the table will automatically have the insertion date as their value for this field.

The location of the "default value" property is dependent on the version of SQL Server Express you are running, but it should be visible if you select the date field of your table when editing the table.

Getting Keyboard Input

You can also make it with BufferedReader if you want to validate user input, like this:

import java.io.BufferedReader;
import java.io.InputStreamReader; 
class Areas {
    public static void main(String args[]){
        float PI = 3.1416f;
        int r=0;
        String rad; //We're going to read all user's text into a String and we try to convert it later
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //Here you declare your BufferedReader object and instance it.
        System.out.println("Radius?");
        try{
            rad = br.readLine(); //We read from user's input
            r = Integer.parseInt(rad); //We validate if "rad" is an integer (if so we skip catch call and continue on the next line, otherwise, we go to it (catch call))
            System.out.println("Circle area is: " + PI*r*r + " Perimeter: " +PI*2*r); //If all was right, we print this
        }
        catch(Exception e){
            System.out.println("Write an integer number"); //This is what user will see if he/she write other thing that is not an integer
            Areas a = new Areas(); //We call this class again, so user can try it again
           //You can also print exception in case you want to see it as follows:
           // e.printStackTrace();
        }
    }
}

Because Scanner class won't allow you to do it, or not that easy...

And to validate you use "try-catch" calls.

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

In kotlin, we can solve this by creating a custom widget inheriting the ViewPager class and adding a flag value for controlling swipe behavior.

NoSwipePager.kt

class NoSwipePager(context: Context, attrs: AttributeSet) : ViewPager(context, attrs) {

    var pagingEnabled: Boolean = false

    override fun onTouchEvent(event: MotionEvent): Boolean {
        return if (this.pagingEnabled) {
            super.onTouchEvent(event)
        } else false
    }

    override fun onInterceptTouchEvent(event: MotionEvent): Boolean {
        return if (this.pagingEnabled) {
            super.onInterceptTouchEvent(event)
        } else false
    }
}

In xml

<your.package.NoSwipePager
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@id/tab_layout" />

Disable swiping programmatically. If kotlin-android-extensions plugin is applied in build.gradle, swiping can be disabled by writing below code.

view_pager.pagingEnabled = false

Otherwise we can disable swiping using code below:

val viewPager : ViewPager = findViewById(R.id.view_pager)
viewPager.pagingEnabled = false