Programs & Examples On #J#

J# programming language is a discontinued transitional language for programmers of Java and Visual J++ languages, so they may use their existing knowledge and applications on .NET Framework.

Comparing two byte arrays in .NET

I did some measurements using attached program .net 4.7 release build without the debugger attached. I think people have been using the wrong metric since what you are about if you care about speed here is how long it takes to figure out if two byte arrays are equal. i.e. throughput in bytes.

StructuralComparison :              4.6 MiB/s
for                  :            274.5 MiB/s
ToUInt32             :            263.6 MiB/s
ToUInt64             :            474.9 MiB/s
memcmp               :           8500.8 MiB/s

As you can see, there's no better way than memcmp and it's orders of magnitude faster. A simple for loop is the second best option. And it still boggles my mind why Microsoft cannot simply include a Buffer.Compare method.

[Program.cs]:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace memcmp
{
    class Program
    {
        static byte[] TestVector(int size)
        {
            var data = new byte[size];
            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                rng.GetBytes(data);
            }
            return data;
        }

        static TimeSpan Measure(string testCase, TimeSpan offset, Action action, bool ignore = false)
        {
            var t = Stopwatch.StartNew();
            var n = 0L;
            while (t.Elapsed < TimeSpan.FromSeconds(10))
            {
                action();
                n++;
            }
            var elapsed = t.Elapsed - offset;
            if (!ignore)
            {
                Console.WriteLine($"{testCase,-16} : {n / elapsed.TotalSeconds,16:0.0} MiB/s");
            }
            return elapsed;
        }

        [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
        static extern int memcmp(byte[] b1, byte[] b2, long count);

        static void Main(string[] args)
        {
            // how quickly can we establish if two sequences of bytes are equal?

            // note that we are testing the speed of different comparsion methods

            var a = TestVector(1024 * 1024); // 1 MiB
            var b = (byte[])a.Clone();

            // was meant to offset the overhead of everything but copying but my attempt was a horrible mistake... should have reacted sooner due to the initially ridiculous throughput values...
            // Measure("offset", new TimeSpan(), () => { return; }, ignore: true);
            var offset = TimeZone.Zero

            Measure("StructuralComparison", offset, () =>
            {
                StructuralComparisons.StructuralEqualityComparer.Equals(a, b);
            });

            Measure("for", offset, () =>
            {
                for (int i = 0; i < a.Length; i++)
                {
                    if (a[i] != b[i]) break;
                }
            });

            Measure("ToUInt32", offset, () =>
            {
                for (int i = 0; i < a.Length; i += 4)
                {
                    if (BitConverter.ToUInt32(a, i) != BitConverter.ToUInt32(b, i)) break;
                }
            });

            Measure("ToUInt64", offset, () =>
            {
                for (int i = 0; i < a.Length; i += 8)
                {
                    if (BitConverter.ToUInt64(a, i) != BitConverter.ToUInt64(b, i)) break;
                }
            });

            Measure("memcmp", offset, () =>
            {
                memcmp(a, b, a.Length);
            });
        }
    }
}

C# '@' before a String

What is this for and why would I use @":\" instead of ":\"?

Because when you have a long string with many \ you don't need to escape them all and the \n, \r and \f won't work too.

Position a div container on the right side

This works for me.

<div style="position: relative;width:100%;">
    <div style="position:absolute;left:0px;background-color:red;width:25%;height:100px;">
      This will be on the left
    </div>

    <div style="position:absolute;right:0px;background-color:blue;width:25%;height:100px;">
      This will be on the right
    </div>
</div>

Playing Sound In Hidden Tag

Usually, what I do is put the normal audio tag, and then put autoplay="true" and I don't add: controls ="true" and that usually works for me

I put this in a snippet and also made a jsfiddel here

Hope this helps :)

_x000D_
_x000D_
<audio autoplay="true" _x000D_
src="https://res.cloudinary.com/foxyplays989/video/upload/v1558369838/LetsGo.mp3"> _x000D_
</audio>
_x000D_
_x000D_
_x000D_

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

how to customise input field width in bootstrap 3

i solved with a max-width in my main css-file.

/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
    max-width: 280px;
}

It's a simple solution with little "code"

Iterate a list with indexes in Python

Yep, that would be the enumerate function! Or more to the point, you need to do:

list(enumerate([3,7,19]))

[(0, 3), (1, 7), (2, 19)]

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

Why should C++ programmers minimize use of 'new'?

There are two widely-used memory allocation techniques: automatic allocation and dynamic allocation. Commonly, there is a corresponding region of memory for each: the stack and the heap.

Stack

The stack always allocates memory in a sequential fashion. It can do so because it requires you to release the memory in the reverse order (First-In, Last-Out: FILO). This is the memory allocation technique for local variables in many programming languages. It is very, very fast because it requires minimal bookkeeping and the next address to allocate is implicit.

In C++, this is called automatic storage because the storage is claimed automatically at the end of scope. As soon as execution of current code block (delimited using {}) is completed, memory for all variables in that block is automatically collected. This is also the moment where destructors are invoked to clean up resources.

Heap

The heap allows for a more flexible memory allocation mode. Bookkeeping is more complex and allocation is slower. Because there is no implicit release point, you must release the memory manually, using delete or delete[] (free in C). However, the absence of an implicit release point is the key to the heap's flexibility.

Reasons to use dynamic allocation

Even if using the heap is slower and potentially leads to memory leaks or memory fragmentation, there are perfectly good use cases for dynamic allocation, as it's less limited.

Two key reasons to use dynamic allocation:

  • You don't know how much memory you need at compile time. For instance, when reading a text file into a string, you usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program.

  • You want to allocate memory which will persist after leaving the current block. For instance, you may want to write a function string readfile(string path) that returns the contents of a file. In this case, even if the stack could hold the entire file contents, you could not return from a function and keep the allocated memory block.

Why dynamic allocation is often unnecessary

In C++ there's a neat construct called a destructor. This mechanism allows you to manage resources by aligning the lifetime of the resource with the lifetime of a variable. This technique is called RAII and is the distinguishing point of C++. It "wraps" resources into objects. std::string is a perfect example. This snippet:

int main ( int argc, char* argv[] )
{
    std::string program(argv[0]);
}

actually allocates a variable amount of memory. The std::string object allocates memory using the heap and releases it in its destructor. In this case, you did not need to manually manage any resources and still got the benefits of dynamic memory allocation.

In particular, it implies that in this snippet:

int main ( int argc, char* argv[] )
{
    std::string * program = new std::string(argv[0]);  // Bad!
    delete program;
}

there is unneeded dynamic memory allocation. The program requires more typing (!) and introduces the risk of forgetting to deallocate the memory. It does this with no apparent benefit.

Why you should use automatic storage as often as possible

Basically, the last paragraph sums it up. Using automatic storage as often as possible makes your programs:

  • faster to type;
  • faster when run;
  • less prone to memory/resource leaks.

Bonus points

In the referenced question, there are additional concerns. In particular, the following class:

class Line {
public:
    Line();
    ~Line();
    std::string* mString;
};

Line::Line() {
    mString = new std::string("foo_bar");
}

Line::~Line() {
    delete mString;
}

Is actually a lot more risky to use than the following one:

class Line {
public:
    Line();
    std::string mString;
};

Line::Line() {
    mString = "foo_bar";
    // note: there is a cleaner way to write this.
}

The reason is that std::string properly defines a copy constructor. Consider the following program:

int main ()
{
    Line l1;
    Line l2 = l1;
}

Using the original version, this program will likely crash, as it uses delete on the same string twice. Using the modified version, each Line instance will own its own string instance, each with its own memory and both will be released at the end of the program.

Other notes

Extensive use of RAII is considered a best practice in C++ because of all the reasons above. However, there is an additional benefit which is not immediately obvious. Basically, it's better than the sum of its parts. The whole mechanism composes. It scales.

If you use the Line class as a building block:

 class Table
 {
      Line borders[4];
 };

Then

 int main ()
 {
     Table table;
 }

allocates four std::string instances, four Line instances, one Table instance and all the string's contents and everything is freed automagically.

Need a query that returns every field that contains a specified letter

try this

Select * From Table
Where field like '%' + ltrValue1 + '%'
  And field like '%' + ltrValue2 + '%'
... etc.

and be prepared for a table scan as this functionality cannot use any existing indices

batch file - counting number of files in folder and storing in a variable

I'm going to assume you do not want to count hidden or system files.

There are many ways to do this. All of the methods that I will show involve some form of the FOR command. There are many variations of the FOR command that look almost the same, but they behave very differently. It can be confusing for a beginner.

You can get help by typing HELP FOR or FOR /? from the command line. But that help is a bit cryptic if you are not used to reading it.

1) The DIR command lists the number of files in the directory. You can pipe the results of DIR to FIND to get the relevant line and then use FOR /F to parse the desired value from the line. The problem with this technique is the string you search for has to change depending on the language used by the operating system.

@echo off
for /f %%A in ('dir ^| find "File(s)"') do set cnt=%%A
echo File count = %cnt%

2) You can use DIR /B /A-D-H-S to list the non-hidden/non-system files without other info, pipe the result to FIND to count the number of files, and use FOR /F to read the result.

@echo off
for /f %%A in ('dir /a-d-s-h /b ^| find /v /c ""') do set cnt=%%A
echo File count = %cnt%

3) You can use a simple FOR to enumerate all the files and SET /A to increment a counter for each file found.

@echo off
set cnt=0
for %%A in (*) do set /a cnt+=1
echo File count = %cnt%

Html table with button on each row

Pretty sure this solves what you're looking for:

HTML:

<table>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
    <tr><td><button class="editbtn">edit</button></td></tr>
</table>

Javascript (using jQuery):

$(document).ready(function(){
    $('.editbtn').click(function(){
        $(this).html($(this).html() == 'edit' ? 'modify' : 'edit');
    });
});

Edit:

Apparently I should have looked at your sample code first ;)

You need to change (at least) the ID attribute of each element. The ID is the unique identifier for each element on the page, meaning that if you have multiple items with the same ID, you'll get conflicts.

By using classes, you can apply the same logic to multiple elements without any conflicts.

JSFiddle sample

Tensorflow import error: No module named 'tensorflow'

The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.

One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder

conda create -n newenvt anaconda python=3.5
activate newenvt

and then install tensorflow into newenvt

I found this primer helpful

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

How to call getClass() from a static method in Java?

I wrestled with this myself. A nice trick is to use use the current thread to get a ClassLoader when in a static context. This will work in a Hadoop MapReduce as well. Other methods work when running locally, but return a null InputStream when used in a MapReduce.

public static InputStream getResource(String resource) throws Exception {
   ClassLoader cl = Thread.currentThread().getContextClassLoader();
   InputStream is = cl.getResourceAsStream(resource);
   return is;
}

How do I create a file and write to it?

Since the author did not specify whether they require a solution for Java versions that have been EoL'd (by both Sun and IBM, and these are technically the most widespread JVMs), and due to the fact that most people seem to have answered the author's question before it was specified that it is a text (non-binary) file, I have decided to provide my answer.


First of all, Java 6 has generally reached end of life, and since the author did not specify he needs legacy compatibility, I guess it automatically means Java 7 or above (Java 7 is not yet EoL'd by IBM). So, we can look right at the file I/O tutorial: https://docs.oracle.com/javase/tutorial/essential/io/legacy.html

Prior to the Java SE 7 release, the java.io.File class was the mechanism used for file I/O, but it had several drawbacks.

  • Many methods didn't throw exceptions when they failed, so it was impossible to obtain a useful error message. For example, if a file deletion failed, the program would receive a "delete fail" but wouldn't know if it was because the file didn't exist, the user didn't have permissions, or there was some other problem.
  • The rename method didn't work consistently across platforms.
  • There was no real support for symbolic links.
  • More support for metadata was desired, such as file permissions, file owner, and other security attributes. Accessing file metadata was inefficient.
  • Many of the File methods didn't scale. Requesting a large directory listing over a server could result in a hang. Large directories could also cause memory resource problems, resulting in a denial of service.
  • It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.

Oh well, that rules out java.io.File. If a file cannot be written/appended, you may not be able to even know why.


We can continue looking at the tutorial: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

If you have all lines you will write (append) to the text file in advance, the recommended approach is https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-

Here's an example (simplified):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);

Another example (append):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);

If you want to write file content as you go: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-

Simplified example (Java 8 or up):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
    writer.append("Zero header: ").append('0').write("\r\n");
    [...]
}

Another example (append):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
    writer.write("----------");
    [...]
}

These methods require minimal effort on the author's part and should be preferred to all others when writing to [text] files.

initialize a vector to zeros C++/C++11

You don't need initialization lists for that:

std::vector<int> vector1(length, 0);
std::vector<double> vector2(length, 0.0);

HTML meta tag for content language

<meta name="language" content="Spanish">

This isn't defined in any specification (including the HTML5 draft)

<meta http-equiv="content-language" content="es">

This is a poor man's version of a real HTTP header and should really be expressed in the headers. For example:

Content-language: es
Content-type: text/html;charset=UTF-8

It says that the document is intended for Spanish language speakers (it doesn't, however mean the document is written in Spanish; it could, for example, be written in English as part of a language course for Spanish speakers).

From the spec:

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

If you want to state that a document is written in Spanish then use:

<html lang="es">

How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?

I have placed the following script on my system & I call it as a bash alias for when I want to quickly grab the full path to a file in the current dir:

#!/bin/bash
/usr/bin/find "$PWD" -maxdepth 1 -mindepth 1 -name "$1"

I am not sure why, but, on OS X when called by a script "$PWD" expands to the absolute path. When the find command is called on the command line, it doesn't. But it does what I want... enjoy.

setContentView(R.layout.main); error

This problem usually happen if eclipse accidentally compile the main.xml incorrectly. The easiest solution is to delete R.java inside gen directory. Once we delete, than eclipse will generate the new R.java base on the latest main.xml

How to change Format of a Cell to Text using VBA

To answer your direct question, it is:

Range("A1").NumberFormat = "@"

Or

Cells(1,1).NumberFormat = "@"

However, I suggest making changing the format to what you actually want displayed. This allows you to retain the data type in the cell and easily use cell formulas to manipulate the data.

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

<ul>
  <li>this is my text</li>
  <li>this is my text</li>
  <li>this is my text</li>
  <li>this is my text</li>
  <li>this is my text</li>
</ul>

you can use this simple css style

ul {
     list-style-type: '\2713';
   }

Python Socket Multiple Clients

def get_clients():
    first_run = True
    startMainMenu = False

    while True:
        if first_run:
            global done
            done = False
            Thread(target=animate, args=("Waiting For Connection",)).start()

        Client, address = objSocket.accept()
        global menuIsOn
        if menuIsOn:
            menuIsOn = False  # will stop main menu
            startMainMenu = True

        done = True

        # Get Current Directory in Client Machine
        current_client_directory = Client.recv(1024).decode("utf-8", errors="ignore")

        # beep on connection
        beep()
        print(f"{bcolors.OKBLUE}\n***** Incoming Connection *****{bcolors.OKGREEN}")
        print('* Connected to: ' + address[0] + ':' + str(address[1]))
        try:
            get_client_info(Client, first_run)
        except Exception as e:
            print("Error data received is not a json!")
            print(e)
        now = datetime.now()
        current_time = now.strftime("%D %H:%M:%S")
        print("* Current Time =", current_time)

        print("* Current Folder in Client: " + current_client_directory + bcolors.WARNING)

        connections.append(Client)

        addresses.append(address)

        if first_run:
            Thread(target=threaded_main_menu, daemon=True).start()

            first_run = False
        else:
            print(f"{bcolors.OKBLUE}* Hit Enter To Continue.{bcolors.WARNING}\n#>", end="")
        if startMainMenu == True:
            Thread(target=threaded_main_menu, daemon=True).start()
            startMainMenu = False

How to trim a list in Python

You just subindex it with [:5] indicating that you want (up to) the first 5 elements.

>>> [1,2,3,4,5,6,7,8][:5]
[1, 2, 3, 4, 5]
>>> [1,2,3][:5]
[1, 2, 3]
>>> x = [6,7,8,9,10,11,12]
>>> x[:5]
[6, 7, 8, 9, 10]

Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!

>>> x[5:]
[11, 12]

How can you detect the version of a browser?

Detecting Browser and Its version

This code snippet is based on the article from MDN. Where they gave a brief hint about various keywords that can be used to detect the browser name.

reference

I have done few changes to detect browsers like Edge and UCBrowser

_x000D_
_x000D_
getBrowser = () => {
    const userAgent = navigator.userAgent;
    let browser = "unkown";
    // Detect browser name
    browser = (/ucbrowser/i).test(userAgent) ? 'UCBrowser' : browser;
    browser = (/edg/i).test(userAgent) ? 'Edge' : browser;
    browser = (/googlebot/i).test(userAgent) ? 'GoogleBot' : browser;
    browser = (/chromium/i).test(userAgent) ? 'Chromium' : browser;
    browser = (/firefox|fxios/i).test(userAgent) && !(/seamonkey/i).test(userAgent) ? 'Firefox' : browser;
    browser = (/; msie|trident/i).test(userAgent) && !(/ucbrowser/i).test(userAgent) ? 'IE' : browser;
    browser = (/chrome|crios/i).test(userAgent) && !(/opr|opera|chromium|edg|ucbrowser|googlebot/i).test(userAgent) ? 'Chrome' : browser;;
    browser = (/safari/i).test(userAgent) && !(/chromium|edg|ucbrowser|chrome|crios|opr|opera|fxios|firefox/i).test(userAgent) ? 'Safari' : browser;
    browser = (/opr|opera/i).test(userAgent) ? 'Opera' : browser;

    // detect browser version
    switch (browser) {
        case 'UCBrowser': return `${browser}/${browserVersion(userAgent,/(ucbrowser)\/([\d\.]+)/i)}`;
        case 'Edge': return `${browser}/${browserVersion(userAgent,/(edge|edga|edgios|edg)\/([\d\.]+)/i)}`;
        case 'GoogleBot': return `${browser}/${browserVersion(userAgent,/(googlebot)\/([\d\.]+)/i)}`;
        case 'Chromium': return `${browser}/${browserVersion(userAgent,/(chromium)\/([\d\.]+)/i)}`;
        case 'Firefox': return `${browser}/${browserVersion(userAgent,/(firefox|fxios)\/([\d\.]+)/i)}`;
        case 'Chrome': return `${browser}/${browserVersion(userAgent,/(chrome|crios)\/([\d\.]+)/i)}`;
        case 'Safari': return `${browser}/${browserVersion(userAgent,/(safari)\/([\d\.]+)/i)}`;
        case 'Opera': return `${browser}/${browserVersion(userAgent,/(opera|opr)\/([\d\.]+)/i)}`;
        case 'IE': const version = browserVersion(userAgent,/(trident)\/([\d\.]+)/i);
            // IE version is mapped using trident version 
            // IE/8.0 = Trident/4.0, IE/9.0 = Trident/5.0
            return version ? `${browser}/${parseFloat(version) + 4.0}` : `${browser}/7.0`;
        default: return `unknown/0.0.0.0`;
    }
}

browserVersion = (userAgent,regex) => {
    return userAgent.match(regex) ? userAgent.match(regex)[2] : null;
}

console.log(getBrowser());
_x000D_
_x000D_
_x000D_

What is the difference between single-quoted and double-quoted strings in PHP?

In PHP, single quote text is considered as string value and double quote text will parse the variables by replacing and processing their value.

$test = "variable";
echo "Hello Mr $test"; // the output would be: Hello Mr variable
echo 'Hello Mr $test'; // the output would be: Hello Mr $test

Here, double quote parse the value and single quote is considered as string value (without parsing the $test variable.)

Upload a file to Amazon S3 with NodeJS

var express = require('express')

app = module.exports = express();
var secureServer = require('http').createServer(app);
secureServer.listen(3001);

var aws = require('aws-sdk')
var multer = require('multer')
var multerS3 = require('multer-s3')

    aws.config.update({
    secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    accessKeyId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    region: 'us-east-1'
    });
    s3 = new aws.S3();

   var upload = multer({
   storage: multerS3({
    s3: s3,
    dirname: "uploads",
    bucket: "Your bucket name",
    key: function (req, file, cb) {
        console.log(file);
        cb(null, "uploads/profile_images/u_" + Date.now() + ".jpg"); //use  
     Date.now() for unique file keys
    }
  })
   });

 app.post('/upload', upload.single('photos'), function(req, res, next) {

 console.log('Successfully uploaded ', req.file)

 res.send('Successfully uploaded ' + req.file.length + ' files!')

})

Why does checking a variable against multiple values with `OR` only check the first value?

("Jesse" or "jesse")

The above expression tests whether or not "Jesse" evaluates to True. If it does, then the expression will return it; otherwise, it will return "jesse". The expression is equivalent to writing:

"Jesse" if "Jesse" else "jesse"

Because "Jesse" is a non-empty string though, it will always evaluate to True and thus be returned:

>>> bool("Jesse")  # Non-empty strings evaluate to True in Python
True
>>> bool("")  # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>

This means that the expression:

name == ("Jesse" or "jesse")

is basically equivalent to writing this:

name == "Jesse"

In order to fix your problem, you can use the in operator:

# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):

Or, you can lowercase the value of name with str.lower and then compare it to "jesse" directly:

# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":

HttpWebRequest-The remote server returned an error: (400) Bad Request

Are you sure you should be using POST not PUT?

POST is usually used with application/x-www-urlencoded formats. If you are using a REST API, you should maybe be using PUT? If you are uploading a file you probably need to use multipart/form-data. Not always, but usually, that is the right thing to do..

Also you don't seem to be using the credentials to log in - you need to use the Credentials property of the HttpWebRequest object to send the username and password.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

I was receiving the same error. You need to go increase the column length while importing the data for particular column. Choose a data source >> Advanced >> increase the column from default 50 to 200 or more.

It worked for me!

Best way to structure a tkinter application?

Probably the best way to learn how to structure your program is by reading other people's code, especially if it's a large program to which many people have contributed. After looking at the code of many projects, you should get an idea of what the consensus style should be.

Python, as a language, is special in that there are some strong guidelines as to how you should format your code. The first is the so-called "Zen of Python":

  • Beautiful is better than ugly.
  • Explicit is better than implicit.
  • Simple is better than complex.
  • Complex is better than complicated.
  • Flat is better than nested.
  • Sparse is better than dense.
  • Readability counts.
  • Special cases aren't special enough to break the rules.
  • Although practicality beats purity.
  • Errors should never pass silently.
  • Unless explicitly silenced.
  • In the face of ambiguity, refuse the temptation to guess.
  • There should be one-- and preferably only one --obvious way to do it.
  • Although that way may not be obvious at first unless you're Dutch.
  • Now is better than never.
  • Although never is often better than right now.
  • If the implementation is hard to explain, it's a bad idea.
  • If the implementation is easy to explain, it may be a good idea.
  • Namespaces are one honking great idea -- let's do more of those!

On a more practical level, there is PEP8, the style guide for Python.

With those in mind, I would say that your code style doesn't really fit, particularly the nested functions. Find a way to flatten those out, either by using classes or moving them into separate modules. This will make the structure of your program much easier to understand.

Where to place and how to read configuration resource files in servlet based application?

You can you with your source folder so whenever you build, those files are automatically copied to the classes directory.

Instead of using properties file, use XML file.

If the data is too small, you can even use web.xml for accessing the properties.

Please note that any of these approach will require app server restart for changes to be reflected.

XML Schema (XSD) validation tool?

I'm just learning Schema. I'm using RELAX NG and using xmllint to validate. I'm getting frustrated by the errors coming out of xmlllint. I wish they were a little more informative.

If there is a wrong attribute in the XML then xmllint tells you the name of the unsupported attribute. But if you are missing an attribute in the XML you just get a message saying the element can not be validated.

I'm working on some very complicated XML with very complicated rules, and I'm new to this so tracking down which attribute is missing is taking a long time.

Update: I just found a java tool I'm liking a lot. It can be run from the command line like xmllint and it supports RELAX NG: https://msv.dev.java.net/

Nested or Inner Class in PHP

I think I wrote an elegant solution to this problem by using namespaces. In my case, the inner class does not need to know his parent class (like the static inner class in Java). As an example I made a class called 'User' and a subclass called 'Type', used as a reference for the user types (ADMIN, OTHERS) in my example. Regards.

User.php (User class file)

<?php
namespace
{   
    class User
    {
        private $type;

        public function getType(){ return $this->type;}
        public function setType($type){ $this->type = $type;}
    }
}

namespace User
{
    class Type
    {
        const ADMIN = 0;
        const OTHERS = 1;
    }
}
?>

Using.php (An example of how to call the 'subclass')

<?php
    require_once("User.php");

    //calling a subclass reference:
    echo "Value of user type Admin: ".User\Type::ADMIN;
?>

How do I vertically align text in a paragraph?

In my case margin auto works fine.

p {
    font: 22px/24px Ubuntu;
    margin:auto 0px;
}

What is the use of DesiredCapabilities in Selenium WebDriver?

You should read the documentation about DesiredCapabilities. There is also a different page for the ChromeDriver. Javadoc from Capabilities:

Capabilities: Describes a series of key/value pairs that encapsulate aspects of a browser.

Basically, the DesiredCapabilities help to set properties for the WebDriver. A typical usecase would be to set the path for the FirefoxDriver if your local installation doesn't correspond to the default settings.

Making TextView scrollable on Android

If you don't want to use the EditText solution then you might have better luck with:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.yourLayout);
    (TextView)findViewById(R.id.yourTextViewId).setMovementMethod(ArrowKeyMovementMethod.getInstance());
}

How to set Spring profile from system variable?

My solution is to set the environment variable as spring.profiles.active=development. So that all applications running in that machine will refer the variable and start the application. The order in which spring loads a properties as follows

application.properties
system properties
environment variable

Adding files to java classpath at runtime

yes, you can. it will need to be in its package structure in a separate directory from the rest of your compiled code if you want to isolate it. you will then just put its base dir in the front of the classpath on the command line.

How to pass multiple values through command argument in Asp.net?

Use OnCommand event of imagebutton. Within it do

<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>

Code-behind:

void CommandBtn_Click(Object sender, CommandEventArgs e) 
{    
    switch(e.CommandName)
    {
        case "Something":
            // Do your code
            break;
        default:              
            break; 

    }
}

What does elementFormDefault do in XSD?

Important to note with elementFormDefault is that it applies to locally defined elements, typically named elements inside a complexType block, as opposed to global elements defined on the top-level of the schema. With elementFormDefault="qualified" you can address local elements in the schema from within the xml document using the schema's target namespace as the document's default namespace.

In practice, use elementFormDefault="qualified" to be able to declare elements in nested blocks, otherwise you'll have to declare all elements on the top level and refer to them in the schema in nested elements using the ref attribute, resulting in a much less compact schema.

This bit in the XML Schema Primer talks about it: http://www.w3.org/TR/xmlschema-0/#NS

Remove space above and below <p> tag HTML

<p> tags have built in padding and margin. You could create a CSS selector combined with some javascript for instances when your <p> is empty. Probably overkill, but it should do what you need it to do.

CSS example: .NoPaddingOrMargin {padding: 0px; margin:0px}

How to test code dependent on environment variables using JUnit?

The usual solution is to create a class which manages the access to this environmental variable, which you can then mock in your test class.

public class Environment {
    public String getVariable() {
        return System.getenv(); // or whatever
    }
}

public class ServiceTest {
    private static class MockEnvironment {
        public String getVariable() {
           return "foobar";
        }
    }

    @Test public void testService() {
        service.doSomething(new MockEnvironment());
    }
}

The class under test then gets the environment variable using the Environment class, not directly from System.getenv().

How do I compare 2 rows from the same table (SQL Server)?

OK, after 2 years it's finally time to correct the syntax:

SELECT  t1.value, t2.value
FROM    MyTable t1
JOIN    MyTable t2
ON      t1.id = t2.id
WHERE   t1.id = @id
        AND t1.status = @status1
        AND t2.status = @status2

jQuery Datepicker close datepicker after selected date

This is my edited version : you just need to add an extra argument "autoClose".

example :

 $('input[name="fieldName"]').datepicker({ autoClose: true});

also you can specify a close callback if you want. :)

replace datepicker.js with this:

!function( $ ) {

// Picker object

var Datepicker = function(element, options , closeCallBack){
    this.element = $(element);
    this.format = DPGlobal.parseFormat(options.format||this.element.data('date-format')||'dd/mm/yyyy');
    this.autoClose = options.autoClose||this.element.data('date-autoClose')|| true;
    this.closeCallback = closeCallBack || function(){};
    this.picker = $(DPGlobal.template)
                        .appendTo('body')
                        .on({
                            click: $.proxy(this.click, this)//,
                            //mousedown: $.proxy(this.mousedown, this)
                        });
    this.isInput = this.element.is('input');
    this.component = this.element.is('.date') ? this.element.find('.add-on') : false;

    if (this.isInput) {
        this.element.on({
            focus: $.proxy(this.show, this),
            //blur: $.proxy(this.hide, this),
            keyup: $.proxy(this.update, this)
        });
    } else {
        if (this.component){
            this.component.on('click', $.proxy(this.show, this));
        } else {
            this.element.on('click', $.proxy(this.show, this));
        }
    }

    this.minViewMode = options.minViewMode||this.element.data('date-minviewmode')||0;
    if (typeof this.minViewMode === 'string') {
        switch (this.minViewMode) {
            case 'months':
                this.minViewMode = 1;
                break;
            case 'years':
                this.minViewMode = 2;
                break;
            default:
                this.minViewMode = 0;
                break;
        }
    }
    this.viewMode = options.viewMode||this.element.data('date-viewmode')||0;
    if (typeof this.viewMode === 'string') {
        switch (this.viewMode) {
            case 'months':
                this.viewMode = 1;
                break;
            case 'years':
                this.viewMode = 2;
                break;
            default:
                this.viewMode = 0;
                break;
        }
    }
    this.startViewMode = this.viewMode;
    this.weekStart = options.weekStart||this.element.data('date-weekstart')||0;
    this.weekEnd = this.weekStart === 0 ? 6 : this.weekStart - 1;
    this.onRender = options.onRender;
    this.fillDow();
    this.fillMonths();
    this.update();
    this.showMode();
};

Datepicker.prototype = {
    constructor: Datepicker,

    show: function(e) {
        this.picker.show();
        this.height = this.component ? this.component.outerHeight() : this.element.outerHeight();
        this.place();
        $(window).on('resize', $.proxy(this.place, this));
        if (e ) {
            e.stopPropagation();
            e.preventDefault();
        }
        if (!this.isInput) {
        }
        var that = this;
        $(document).on('mousedown', function(ev){
            if ($(ev.target).closest('.datepicker').length == 0) {
                that.hide();
            }
        });
        this.element.trigger({
            type: 'show',
            date: this.date
        });
    },

    hide: function(){
        this.picker.hide();
        $(window).off('resize', this.place);
        this.viewMode = this.startViewMode;
        this.showMode();
        if (!this.isInput) {
            $(document).off('mousedown', this.hide);
        }
        //this.set();
        this.element.trigger({
            type: 'hide',
            date: this.date
        });
    },

    set: function() {
        var formated = DPGlobal.formatDate(this.date, this.format);
        if (!this.isInput) {
            if (this.component){
                this.element.find('input').prop('value', formated);
            }
            this.element.data('date', formated);
        } else {
            this.element.prop('value', formated);
        }
    },

    setValue: function(newDate) {
        if (typeof newDate === 'string') {
            this.date = DPGlobal.parseDate(newDate, this.format);
        } else {
            this.date = new Date(newDate);
        }
        this.set();
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    place: function(){
        var offset = this.component ? this.component.offset() : this.element.offset();
        this.picker.css({
            top: offset.top + this.height,
            left: offset.left
        });
    },

    update: function(newDate){
        this.date = DPGlobal.parseDate(
            typeof newDate === 'string' ? newDate : (this.isInput ? this.element.prop('value') : this.element.data('date')),
            this.format
        );
        this.viewDate = new Date(this.date.getFullYear(), this.date.getMonth(), 1, 0, 0, 0, 0);
        this.fill();
    },

    fillDow: function(){
        var dowCnt = this.weekStart;
        var html = '<tr>';
        while (dowCnt < this.weekStart + 7) {
            html += '<th class="dow">'+DPGlobal.dates.daysMin[(dowCnt++)%7]+'</th>';
        }
        html += '</tr>';
        this.picker.find('.datepicker-days thead').append(html);
    },

    fillMonths: function(){
        var html = '';
        var i = 0
        while (i < 12) {
            html += '<span class="month">'+DPGlobal.dates.monthsShort[i++]+'</span>';
        }
        this.picker.find('.datepicker-months td').append(html);
    },

    fill: function() {
        var d = new Date(this.viewDate),
            year = d.getFullYear(),
            month = d.getMonth(),
            currentDate = this.date.valueOf();
        this.picker.find('.datepicker-days th:eq(1)')
                    .text(DPGlobal.dates.months[month]+' '+year);
        var prevMonth = new Date(year, month-1, 28,0,0,0,0),
            day = DPGlobal.getDaysInMonth(prevMonth.getFullYear(), prevMonth.getMonth());
        prevMonth.setDate(day);
        prevMonth.setDate(day - (prevMonth.getDay() - this.weekStart + 7)%7);
        var nextMonth = new Date(prevMonth);
        nextMonth.setDate(nextMonth.getDate() + 42);
        nextMonth = nextMonth.valueOf();
        var html = [];
        var clsName,
            prevY,
            prevM;
        while(prevMonth.valueOf() < nextMonth) {zs
            if (prevMonth.getDay() === this.weekStart) {
                html.push('<tr>');
            }
            clsName = this.onRender(prevMonth);
            prevY = prevMonth.getFullYear();
            prevM = prevMonth.getMonth();
            if ((prevM < month &&  prevY === year) ||  prevY < year) {
                clsName += ' old';
            } else if ((prevM > month && prevY === year) || prevY > year) {
                clsName += ' new';
            }
            if (prevMonth.valueOf() === currentDate) {
                clsName += ' active';
            }
            html.push('<td class="day '+clsName+'">'+prevMonth.getDate() + '</td>');
            if (prevMonth.getDay() === this.weekEnd) {
                html.push('</tr>');
            }
            prevMonth.setDate(prevMonth.getDate()+1);
        }
        this.picker.find('.datepicker-days tbody').empty().append(html.join(''));
        var currentYear = this.date.getFullYear();

        var months = this.picker.find('.datepicker-months')
                    .find('th:eq(1)')
                        .text(year)
                        .end()
                    .find('span').removeClass('active');
        if (currentYear === year) {
            months.eq(this.date.getMonth()).addClass('active');
        }

        html = '';
        year = parseInt(year/10, 10) * 10;
        var yearCont = this.picker.find('.datepicker-years')
                            .find('th:eq(1)')
                                .text(year + '-' + (year + 9))
                                .end()
                            .find('td');
        year -= 1;
        for (var i = -1; i < 11; i++) {
            html += '<span class="year'+(i === -1 || i === 10 ? ' old' : '')+(currentYear === year ? ' active' : '')+'">'+year+'</span>';
            year += 1;
        }
        yearCont.html(html);
    },

    click: function(e) {
        e.stopPropagation();
        e.preventDefault();
        var target = $(e.target).closest('span, td, th');
        if (target.length === 1) {
            switch(target[0].nodeName.toLowerCase()) {
                case 'th':
                    switch(target[0].className) {
                        case 'switch':
                            this.showMode(1);
                            break;
                        case 'prev':
                        case 'next':
                            this.viewDate['set'+DPGlobal.modes[this.viewMode].navFnc].call(
                                this.viewDate,
                                this.viewDate['get'+DPGlobal.modes[this.viewMode].navFnc].call(this.viewDate) + 
                                DPGlobal.modes[this.viewMode].navStep * (target[0].className === 'prev' ? -1 : 1)
                            );
                            this.fill();
                            this.set();
                            break;
                    }
                    break;
                case 'span':
                    if (target.is('.month')) {
                        var month = target.parent().find('span').index(target);
                        this.viewDate.setMonth(month);
                    } else {
                        var year = parseInt(target.text(), 10)||0;
                        this.viewDate.setFullYear(year);
                    }
                    if (this.viewMode !== 0) {
                        this.date = new Date(this.viewDate);
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                    }
                    this.showMode(-1);
                    this.fill();
                    this.set();
                    break;
                case 'td':
                    if (target.is('.day') && !target.is('.disabled')){
                        var day = parseInt(target.text(), 10)||1;
                        var month = this.viewDate.getMonth();
                        if (target.is('.old')) {
                            month -= 1;
                        } else if (target.is('.new')) {
                            month += 1;
                        }
                        var year = this.viewDate.getFullYear();
                        this.date = new Date(year, month, day,0,0,0,0);
                        this.viewDate = new Date(year, month, Math.min(28, day),0,0,0,0);
                        this.fill();
                        this.set();
                        this.element.trigger({
                            type: 'changeDate',
                            date: this.date,
                            viewMode: DPGlobal.modes[this.viewMode].clsName
                        });
                        if(this.autoClose === true){
                            this.hide();
                            this.closeCallback();
                        }

                    }
                    break;
            }
        }
    },

    mousedown: function(e){
        e.stopPropagation();
        e.preventDefault();
    },

    showMode: function(dir) {
        if (dir) {
            this.viewMode = Math.max(this.minViewMode, Math.min(2, this.viewMode + dir));
        }
        this.picker.find('>div').hide().filter('.datepicker-'+DPGlobal.modes[this.viewMode].clsName).show();
    }
};

$.fn.datepicker = function ( option, val ) {
    return this.each(function () {
        var $this = $(this);
        var datePicker = $this.data('datepicker');
        var options = typeof option === 'object' && option;
        if (!datePicker) {
            if (typeof val === 'function')
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options),val)));
            else{
                $this.data('datepicker', (datePicker = new Datepicker(this, $.extend({}, $.fn.datepicker.defaults,options))));
            }
        }
        if (typeof option === 'string') datePicker[option](val);

    });
};

$.fn.datepicker.defaults = {
    onRender: function(date) {
        return '';
    }
};
$.fn.datepicker.Constructor = Datepicker;

var DPGlobal = {
    modes: [
        {
            clsName: 'days',
            navFnc: 'Month',
            navStep: 1
        },
        {
            clsName: 'months',
            navFnc: 'FullYear',
            navStep: 1
        },
        {
            clsName: 'years',
            navFnc: 'FullYear',
            navStep: 10
    }],
    dates:{
        days: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi", "Dimanche"],
                    daysShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"],
                    daysMin: ["D", "L", "Ma", "Me", "J", "V", "S", "D"],
                    months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"],
                    monthsShort: ["Jan", "Fév", "Mar", "Avr", "Mai", "Jui", "Jul", "Aou", "Sep", "Oct", "Nov", "Déc"],
                    today: "Aujourd'hui",
                    clear: "Effacer",
                    weekStart: 1,
                    format: "dd/mm/yyyy"
    },
    isLeapYear: function (year) {
        return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0))
    },
    getDaysInMonth: function (year, month) {
        return [31, (DPGlobal.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
    },
    parseFormat: function(format){
        var separator = format.match(/[.\/\-\s].*?/),
            parts = format.split(/\W+/);
        if (!separator || !parts || parts.length === 0){
            throw new Error("Invalid date format.");
        }
        return {separator: separator, parts: parts};
    },
    parseDate: function(date, format) {
        var parts = date.split(format.separator),
            date = new Date(),
            val;
        date.setHours(0);
        date.setMinutes(0);
        date.setSeconds(0);
        date.setMilliseconds(0);
        if (parts.length === format.parts.length) {
            var year = date.getFullYear(), day = date.getDate(), month = date.getMonth();
            for (var i=0, cnt = format.parts.length; i < cnt; i++) {
                val = parseInt(parts[i], 10)||1;
                switch(format.parts[i]) {
                    case 'dd':
                    case 'd':
                        day = val;
                        date.setDate(val);
                        break;
                    case 'mm':
                    case 'm':
                        month = val - 1;
                        date.setMonth(val - 1);
                        break;
                    case 'yy':
                        year = 2000 + val;
                        date.setFullYear(2000 + val);
                        break;
                    case 'yyyy':
                        year = val;
                        date.setFullYear(val);
                        break;
                }
            }
            date = new Date(year, month, day, 0 ,0 ,0);
        }
        return date;
    },
    formatDate: function(date, format){
        var val = {
            d: date.getDate(),
            m: date.getMonth() + 1,
            yy: date.getFullYear().toString().substring(2),
            yyyy: date.getFullYear()
        };
        val.dd = (val.d < 10 ? '0' : '') + val.d;
        val.mm = (val.m < 10 ? '0' : '') + val.m;
        var date = [];
        for (var i=0, cnt = format.parts.length; i < cnt; i++) {
            date.push(val[format.parts[i]]);
        }
        return date.join(format.separator);
    },
    headTemplate: '<thead>'+
                        '<tr>'+
                            '<th class="prev">&lsaquo;</th>'+
                            '<th colspan="5" class="switch"></th>'+
                            '<th class="next">&rsaquo;</th>'+
                        '</tr>'+
                    '</thead>',
    contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>'
};
DPGlobal.template = '<div class="datepicker dropdown-menu">'+
                        '<div class="datepicker-days">'+
                            '<table class=" table-condensed">'+
                                DPGlobal.headTemplate+
                                '<tbody></tbody>'+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-months">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                        '<div class="datepicker-years">'+
                            '<table class="table-condensed">'+
                                DPGlobal.headTemplate+
                                DPGlobal.contTemplate+
                            '</table>'+
                        '</div>'+
                    '</div>';

}( window.jQuery );

Find the smallest positive integer that does not occur in a given sequence

For the space complexity of O(1) and time complexity of O(N) and if the array can be modified then it could be as follows:

public int getFirstSmallestPositiveNumber(int[] arr) {
    // set positions of non-positive or out of range elements as free (use 0 as marker)
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] <= 0 || arr[i] > arr.length) {
            arr[i] = 0;
        }
    }

    //iterate through the whole array again mapping elements [1,n] to positions [0, n-1]
    for (int i = 0; i < arr.length; i++) {
        int prev = arr[i];
        // while elements are not on their correct positions keep putting them there
        while (prev > 0 && arr[prev - 1] != prev) {
            int next = arr[prev - 1];
            arr[prev - 1] = prev;
            prev = next;
        }
    }

    // now, the first unmapped position is the smallest element
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] != i + 1) {
            return i + 1;
        }
    }
    return arr.length + 1;
}

@Test
public void testGetFirstSmallestPositiveNumber() {
    int[][] arrays = new int[][]{{1,-1,-5,-3,3,4,2,8},
      {5, 4, 3, 2, 1}, 
      {0, 3, -2, -1, 1}};

    for (int i = 0; i < arrays.length; i++) {
        System.out.println(getFirstSmallestPositiveNumber(arrays[i]));
    }
}  

Output:

5

6

2

Get installed applications in a system

I wanted to be able to extract a list of apps just as they appear in the start menu. Using the registry, I was getting entries that do not show up in the start menu.

I also wanted to find the exe path and to extract an icon to eventually make a nice looking launcher. Unfortunately, with the registry method this is kind of a hit and miss since my observations are that this information isn't reliably available.

My alternative is based around the shell:AppsFolder which you can access by running explorer.exe shell:appsFolder and which lists all apps, including store apps, currently installed and available through the start menu. The issue is that this is a virtual folder that can't be accessed with System.IO.Directory. Instead, you would have to use native shell32 commands. Fortunately, Microsoft published the Microsoft.WindowsAPICodePack-Shell on Nuget which is a wrapper for the aforementioned commands. Enough said, here's the code:

// GUID taken from https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid
var FOLDERID_AppsFolder = new Guid("{1e87508d-89c2-42f0-8a7e-645a0f50ca58}");
ShellObject appsFolder = (ShellObject)KnownFolderHelper.FromKnownFolderId(FOLDERID_AppsFolder);

foreach (var app in (IKnownFolder)appsFolder)
{
    // The friendly app name
    string name = app.Name;
    // The ParsingName property is the AppUserModelID
    string appUserModelID = app.ParsingName; // or app.Properties.System.AppUserModel.ID
    // You can even get the Jumbo icon in one shot
    ImageSource icon =  app.Thumbnail.ExtraLargeBitmapSource;
}

And that's all there is to it. You can also start the apps using

System.Diagnostics.Process.Start("explorer.exe", @" shell:appsFolder\" + appModelUserID);

This works for regular Win32 apps and UWP store apps. How about them apples.

Since you are interested in listing all installed apps, it is reasonable to expect that you might want to monitor for new apps or uninstalled apps as well, which you can do using the ShellObjectWatcher:

ShellObjectWatcher sow = new ShellObjectWatcher(appsFolder, false);
sow.AllEvents += (s, e) => DoWhatever();
sow.Start();

Edit: One might also be interested in knowing that the AppUserMoedlID mentioned above is the unique ID Windows uses to group windows in the taskbar.

What is the default access specifier in Java?

If no access specifier is given, it's package-level access (there is no explicit specifier for this) for classes and class members. Interface methods are implicitly public.

Maven skip tests

As you noted, -Dmaven.test.skip=true skips compiling the tests. More to the point, it skips building the test artifacts. A common practice for large projects is to have testing utilities and base classes shared among modules in the same project.

This is accomplished by having a module require a test-jar of a previously built module:

<dependency>
  <groupId>org.myproject.mygroup</groupId>
  <artifactId>common</artifactId>
  <version>1.0</version>
  <type>test-jar</type>
  <scope>test</scope>
</dependency>

If -Dmaven.test.skip=true (or simply -Dmaven.test.skip) is specified, the test-jars aren't built, and any module that relies on them will fail its build.

In contrast, when you use -DskipTests, Maven does not run the tests, but it does compile them and build the test-jar, making it available for the subsequent modules.

Sending the bearer token with axios

If you want to some data after passing token in header so that try this code

const api = 'your api'; 
const token = JSON.parse(sessionStorage.getItem('data'));
const token = user.data.id; /*take only token and save in token variable*/
axios.get(api , { headers: {"Authorization" : `Bearer ${token}`} })
.then(res => {
console.log(res.data);
.catch((error) => {
  console.log(error)
});

Differences between Ant and Maven

I can take a person that has never seen Ant - its build.xmls are reasonably well-written - and they can understand what is going on. I can take that same person and show them a Maven POM and they will not have any idea what is going on.

In an engineering organization that is huge, people write about Ant files becoming large and unmanageable. I've written those types and clean Ant scripts. It's really understanding upfront what you need to do going forward and designing a set of templates that can respond to change and scale over a 3+ year period.

Unless you have a simple project, learning the Maven conventions and the Maven way about getting things done is quite a bit of work.

At the end of the day you cannot consider project startup with Ant or Maven a factor: it's really the total cost of ownership. What it takes for the organization to maintain and extend its build system over a few years is one of the main factors that must be considered.

The most important aspects of a build system are dependency management and flexibility in expressing the build recipe. It must be somewhat intuitive when done well.

Java output formatting for Strings

EDIT: This is an extremely primitive answer but I can't delete it because it was accepted. See the answers below for a better solution though

Why not just generate a whitespace string dynamically to insert into the statement.

So if you want them all to start on the 50th character...

String key = "Name =";
String space = "";
for(int i; i<(50-key.length); i++)
{space = space + " ";}
String value = "Bob\n";
System.out.println(key+space+value);

Put all of that in a loop and initialize/set the "key" and "value" variables before each iteration and you're golden. I would also use the StringBuilder class too which is more efficient.

Reorder HTML table rows using drag-and-drop

I working well with it

<script>
    $(function () {

        $("#catalog tbody tr").draggable({
            appendTo:"body",
            helper:"clone"
        });
        $("#cart tbody").droppable({
            activeClass:"ui-state-default",
            hoverClass:"ui-state-hover",
            accept:":not(.ui-sortable-helper)",
            drop:function (event, ui) {
                $('.placeholder').remove();
                row = ui.draggable;
                $(this).append(row);
            }
        });
    });
</script>

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR is equivalent to wchar_t const *. It's a pointer to a wide character string that won't be modified by the function call.

You can assign to LPCWSTRs by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";

LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx is defined as FindWindowExA or FindWindowExW depending on this definition.

How to vertically align <li> elements in <ul>?

I had the same problem. Try this.

<nav>
    <ul>
        <li><a href="#">AnaSayfa</a></li>
        <li><a href="#">Hakkimizda</a></li>
        <li><a href="#">Iletisim</a></li>
    </ul>
</nav>
@charset "utf-8";

nav {
    background-color: #9900CC;
    height: 80px;
    width: 400px;
}

ul {
    list-style: none;
    float: right;
    margin: 0;
}

li {
    float: left;
    width: 100px;
    line-height: 80px;
    vertical-align: middle;
    text-align: center;
    margin: 0;
}

nav li a {
    width: 100px;
    text-decoration: none;
    color: #FFFFFF;
}

A TypeScript GUID class?

There is an implementation in my TypeScript utilities based on JavaScript GUID generators.

Here is the code:

_x000D_
_x000D_
class Guid {_x000D_
  static newGuid() {_x000D_
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {_x000D_
      var r = Math.random() * 16 | 0,_x000D_
        v = c == 'x' ? r : (r & 0x3 | 0x8);_x000D_
      return v.toString(16);_x000D_
    });_x000D_
  }_x000D_
}_x000D_
_x000D_
// Example of a bunch of GUIDs_x000D_
for (var i = 0; i < 100; i++) {_x000D_
  var id = Guid.newGuid();_x000D_
  console.log(id);_x000D_
}
_x000D_
_x000D_
_x000D_

Please note the following:

C# GUIDs are guaranteed to be unique. This solution is very likely to be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.

JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).

How do I center list items inside a UL element?

In Bootstrap (4) use display: inline-flex, like so:

li {
    display: inline-flex;
    /* ... */
}

"use database_name" command in PostgreSQL

The basic problem while migrating from MySQL I faced was, I thought of the term database to be same in PostgreSQL also, but it is not. So if we are going to switch the database from our application or pgAdmin, the result would not be as expected. As in my case, we have separate schemas (Considering PostgreSQL terminology here.) for each customer and separate admin schema. So in application, I have to switch between schemas.

For this, we can use the SET search_path command. This does switch the current schema to the specified schema name for the current session.

example:

SET search_path = different_schema_name;

This changes the current_schema to the specified schema for the session. To change it permanently, we have to make changes in postgresql.conf file.

Align div right in Bootstrap 3

The class pull-right is still there in Bootstrap 3 See the 'helper classes' here

pull-right is defined by

.pull-right {
  float: right !important;
}

without more info on styles and content, it's difficult to say.

It definitely pulls right in this JSBIN when the page is wider than 990px - which is when the col-md styling kicks in, Bootstrap 3 being mobile first and all.

Bootstrap 4

Note that for Bootstrap 4 .pull-right has been replaced with .float-right https://www.geeksforgeeks.org/pull-left-and-pull-right-classes-in-bootstrap-4/#:~:text=pull%2Dright%20classes%20have%20been,based%20on%20the%20Bootstrap%20Grid.

C# How to determine if a number is a multiple of another?

bool isMultiple = a % b == 0;

This will be true if a is a multiple of b

Android button onClickListener

This task can be accomplished using one of the android's main building block named as Intents and One of the methods public void startActivity (Intent intent) which belongs to your Activity class.

An intent is an abstract description of an operation to be performed. It can be used with startActivity to launch an Activity, broadcastIntent to send it to any interested BroadcastReceiver components, and startService(Intent) or bindService(Intent, ServiceConnection, int) to communicate with a background Service.

An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.

Refer the official docs -- http://developer.android.com/reference/android/content/Intent.html

public void startActivity (Intent intent) -- Used to launch a new activity.

So suppose you have two Activity class --

  1. PresentActivity -- This is your current activity from which you want to go the second activity.

  2. NextActivity -- This is your next Activity on which you want to move.

So the Intent would be like this

Intent(PresentActivity.this, NextActivity.class)

Finally this will be the complete code

public class PresentActivity extends Activity {
  protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    setContentView(R.layout.content_layout_id);

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
              // Perform action on click   
              Intent activityChangeIntent = new Intent(PresentActivity.this, NextActivity.class);

              // currentContext.startActivity(activityChangeIntent);

              PresentActivity.this.startActivity(activityChangeIntent);
            }
          });
  }
}

How to display raw html code in PRE or something like it but without escaping it

Essentially the original question can be broken down in 2 parts:

  • Main objective/challenge: embedding(/transporting) a raw formatted code-snippet (any kind of code) in a web-page's markup (for simple copy/paste/edit due to no encoding/escaping)
  • correctly displaying/rendering that code-snippet (possibly edit it) in the browser

The short (but) ambiguous answer is: you can't, ...but you can (get very close).
(I know, that are 3 contradicting answers, so read on...)

(polyglot)(x)(ht)ml Markup-languages rely on wrapping (almost) everything between begin/opening and end/closing tags/character(sequences).
So, to embed any kind of raw code/snippet inside your markup-language, one will always have to escape/encode every instance (inside that snippet) that resembles the character(-sequence) that would close the wrapping 'container' element in the markup. (During this post I'll refer to this as rule no 1.)
Think of "some "data" here" or <i>..close italics with '</i>'-tag</i>, where it is obvious one should escape/encode (something in) </i and " (or change container's quote-character from " to ').

So, because of rule no 1, you can't 'just' embed 'any' unknown raw code-snippet inside markup.
Because, if one has to escape/encode even one character inside the raw snippet, then that snippet would no longer be the same original 'pure raw code' that anyone can copy/paste/edit in the document's markup without further thought. It would lead to malformed/illegal markup and Mojibake (mainly) because of entities.
Also, should that snippet contain such characters, you'd still need some javascript to 'translate' that character(sequence) from (and to) it's escaped/encoded representation to display the snippet correctly in the 'webpage' (for copy/paste/edit).

That brings us to (some of) the datatypes that markup-languages specify. These datatypes essentially define what are considered 'valid characters' and their meaning (per tag, property, etc.):

  • PCDATA (Parsed Character DATA): will expand entities and one must escape <, & (and > depending on markup language/version).
    Most tags like body, div, pre, etc, but also textarea (until HTML5) fall under this type.
    So not only do you need to encode all the container's closing character-sequences inside the snippet, you also have to encode all <, & (,>) characters (at minimum).
    Needless to say, encoding/escaping this many characters falls outside this objective's scope of embedding a raw snippet in the markup.
    '..But a textarea seems to work...', yes, either because of the browsers error-engine trying to make something out of it, or because HTML5:

  • RCDATA (Replaceable Character DATA): will not not treat tags inside the text as markup (but are still governed by rule 1), so one doesn't need to encode < (>). BUT entities are still expanded, so they and 'ambiguous ampersands' (&) need special care.
    The current HTML5 spec says the textarea is now a RCDATA field and (quote):

    The text in raw text and RCDATA elements must not contain any occurrences of the string "</" (U+003C LESS-THAN SIGN, U+002F SOLIDUS) followed by characters that case-insensitively match the tag name of the element followed by one of U+0009 CHARACTER TABULATION (tab), U+000A LINE FEED (LF), U+000C FORM FEED (FF), U+000D CARRIAGE RETURN (CR), U+0020 SPACE, U+003E GREATER-THAN SIGN (>), or U+002F SOLIDUS (/).

    Thus no matter what, textarea needs a hefty entity translation handler or it will eventually Mojibake on entities!

  • CDATA (Character Data) will not treat tags inside the text as markup and will not expand entities.
    So as long as the raw snippet code does not violate rule 1 (that one can't have the containers closing character(sequence) inside the snippet), this requires no other escaping/encoding.

Clearly this boils down to: how can we minimize the number of characters/character-sequences that still need to be encoded in the snippet's raw source and the number of times that character(sequence) might appear in an average snippet; something that is also of importance for the javascript that handles the translation of these characters (if they occur).

So what 'containers' have this CDATA context?

Most value properties of tags are CDATA, so one could (ab)use a hidden input's value property (proof of concept jsfiddle here).
However (conform rule 1) this creates an encoding/escape problem with nested quotes (" and ') in the raw snippet and one needs some javascript to get/translate and set the snippet in another (visible) element (or simply setting it as a text-area's value). Somehow this gave me problems with entities in FF (just like in a textarea). But it doesn't really matter, since the 'price' of having to escape/encode nested quotes is higher then a (HTML5) textarea (quotes are quite common in source code..).

What about trying to (ab)use <![CDATA[<tag>bla & bla</tag>]]>?
As Jukka points out in his extended answer, this would only work in (rare) 'real xhtml'.
I thought of using a script-tag (with or without such a CDATA wrapper inside the script-tag) together with a multi-line comment /* */ that wraps the raw snippet (script-tags can have an id and you can access them by count). But since this obviously introduces a escaping problem with */, ]]> and </script in the raw snippet, this doesn't seem like a solution either.

Please post other viable 'containers' in the comments to this answer.

By the way, encoding or counting the number of - characters and balancing them out inside a comment tag <!-- --> is just insane for this purpose (apart from rule 1).


That leaves us with Jukka K. Korpela's excellent answer: the <xmp> tag seems the best option!

The 'forgotten' <xmp> holds CDATA, is intended for this purpose AND is indeed still in the current HTML 5 spec (and has been at least since HTML3.2); exactly what we need! It's also widely supported, even in IE6 (that is.. until it suffers from the same regression as the scrolling table-body).
Note: as Jukka pointed out, this will not work in true xhtml or polyglot (that will treat it as a pre) and the xmp tag must still adhere to rule no 1. But that's the 'only' rule.

Consider the following markup:

<!-- ATTENTION: replace any occurrence of &lt;/xmp with </xmp -->
<xmp id="snippet-container">
<div>
    <div>this is an example div &amp; holds an xmp tag:<br />
        <xmp> 
<html><head>  <!-- indentation col 0!! -->
    <title>My Title</title>
</head><body>
    <p>hello world !!</p>
</body></html>
        &lt;/xmp>  <!-- note this encoded/escaped tag -->
    </div>
    This line is also part of the snippet
</div>
</xmp>

The above codeblok illustrates a raw piece of markup where <xmp id="snippet-container"> contains an (almost raw) code-snippet (containing div>div>xmp>html-document).
Notice the encoded closing tag in this markup? To comply with rule no 1, this was encoded/escaped).

So embedding/transporting the (sometimes almost) raw code is/seems solved.

What about displaying/rendering the snippet (and that encoded &lt;/xmp>)?

The browser will (or it should) render the snippet (the contents inside snippet-container) exactly the way you see it in the codeblock above (with some discrepancy amongst browsers whether or not the snippet starts with a blank line).
That includes the formatting/indentation, entities (like the string &amp;), full tags, comments AND the encoded closing tag &lt;/xmp> (just like it was encoded in the markup). And depending on browser(version) one could even try use the property contenteditable="true" to edit this snippet (all that without javascript enabled). Doing something like textarea.value=xmp.innerHTML is also a breeze.

So you can... if the snippet doesn't contain the containers closing character-sequence.

However, should a raw snippet contain the closing character-sequence </xmp (because it is an example of xmp itself or it contains some regex, etc), you must accept that you have to encode/escape that sequence in the raw snippet AND need a javascript handler to translate that encoding to display/render the encoded &lt;/xmp> like </xmp> inside a textarea (for editing/posting) or (for example) a pre just to correctly render the snippet's code (or so it seems).

A very rudimentary jsfiddle example of this here. Note that getting/embedding/displaying/retrieving-to-textarea worked perfect even in IE6. But setting the xmp's innerHTML revealed some interesting 'would-be-intelligent' behavior on IE's part. There is a more extensive note and workaround on that in the fiddle.

But now comes the important kicker (another reason why you only get very close): Just as an over-simplified example, imagine this rabbit-hole:

Intended raw code-snippet:

<!-- remember to translate between </xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Well, to comply with rule 1, we 'only' need to encode those </xmp[> \n\r\t\f\/] sequences, right?

So that gives us the following markup (using just a possible encoding):

<xmp id="container">
<!-- remember to translate between &lt;/xmp> and &lt;/xmp> -->
<xmp>
<p>a paragraph</p>
&lt;/xmp>
</xmp>

Hmm.. shalt I get my crystal ball or flip a coin? No, let the computer look at its system-clock and state that a derived number is 'random'. Yes, that should do it..

Using a regex like: xmp.innerHTML.replace(/&lt;(?=\/xmp[> \n\r\t\f\/])/gi, '<');, would translate 'back' to this:

<!-- remember to translate between </xmp> and </xmp> -->
<xmp>
<p>a paragraph</p>
</xmp>

Hmm.. seems this random generator is broken... Houston..?
Should you have missed the joke/problem, read again starting at the 'intended raw code-snippet'.

Wait, I know, we (also) need to encode .... to ....
Ok, rewind to 'intended raw code-snippet' and read again.
Somehow this all begins to smell like the famous hilarious-but-true rexgex-answer on SO, a good read for people fluent in mojibake.

Maybe someone knows a clever algorithm or solution to fix this problem, but I assume that the embedded raw code will get more and more obscure to the point where you'd be better of properly escaping/encoding just your <, & (and >), just like the rest of the world.

Conclusion: (using the xmp tag)

  • it can be done with known snippets that do not contain the container's closing character-sequence,
  • we can get very close to the original objective with known snippets that only use 'basic first-level' escaping/encoding so we don't fall in the rabbithole,
  • but ultimately it seems that one can't do this reliably in a 'production-environment' where people can/should copy/paste/edit 'any unknown' raw snippets while not knowing/understanding the implications/rules/rabbithole (depending on your implementation of handling/translating for rule 1 and the rabbit-hole).

Hope this helps!

PS: Whilst I would appreciate an upvote if you find this explanation useful, I kind of think Jukka's answer should be the accepted answer (should no better option/answer come along), since he was the one who remembered the xmp tag (that I forgot about over the years and got 'distracted' by the commonly advocated PCDATA elements like pre, textarea, etc.).
This answer originated in explaining why you can't do it (with any unknown raw snippet) and explain some obvious pitfalls that some other (now deleted) answers overlooked when advising a textarea for embedding/transport. I've expanded my existing explanation to also support and further explain Jukka's answer (since all that entity and *CDATA stuff is almost harder than code-pages).

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Setting a divs background image to fit its size?

Use background-size for that purpose:

background-size: 100% 100%;

More on:

http://www.w3schools.com/cssref/css3_pr_background-size.asp

How can I install Visual Studio Code extensions offline?

I've stored a script in my gist to download an extension from the marketplace using a PowerShell script. Feel free to comment of share it.

https://gist.github.com/azurekid/ca641c47981cf8074aeaf6218bb9eb58

[CmdletBinding()]
param
(
    [Parameter(Mandatory = $true)]
    [string] $Publisher,

    [Parameter(Mandatory = $true)]
    [string] $ExtensionName,

    [Parameter(Mandatory = $true)]
    [ValidateScript( {
            If ($_ -match "^([0-9].[0-9].[0-9])") {
                $True
            }
            else {
                Throw "$_ is not a valid version number. Version can only contain digits"
            }
        })]
    [string] $Version,

    [Parameter(Mandatory = $true)]
    [string] $OutputLocation
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

Write-Output "Publisher:        $($Publisher)"
Write-Output "Extension name:   $($ExtensionName)"
Write-Output "Version:          $($Version)"
Write-Output "Output location   $($OutputLocation)"

$baseUrl = "https://$($Publisher).gallery.vsassets.io/_apis/public/gallery/publisher/$($Publisher)/extension/$($ExtensionName)/$($Version)/assetbyname/Microsoft.VisualStudio.Services.VSIXPackage"
$outputFile = "$($Publisher)-$($ExtensionName)-$($Version).visx"

if (Test-Path $OutputLocation) {
    try {
        Write-Output "Retrieving extension..."
        [uri]::EscapeUriString($baseUrl) | Out-Null
        Invoke-WebRequest -Uri $baseUrl -OutFile "$OutputLocation\$outputFile"
    }
    catch {
        Write-Error "Unable to find the extension in the marketplace"
    }
}
else {
    Write-Output "The Path $($OutputLocation) does not exist"
}

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

The difference between "require(x)" and "import x"

Not an answer here and more like a comment, sorry but I can't comment.

In node V10, you can use the flag --experimental-modules to tell Nodejs you want to use import. But your entry script should end with .mjs.

Note this is still an experimental thing and should not be used in production.

// main.mjs
import utils from './utils.js'
utils.print();
// utils.js
module.exports={
    print:function(){console.log('print called')}
}

Ref 1 - Nodejs Doc

Ref 2 - github issue

Get original URL referer with PHP?

Store it in a cookie that only lasts for the current browsing session

How to declare a variable in MySQL?

SET

SET @var_name = value 

OR

SET @var := value

both operators = and := are accepted


SELECT

SELECT col1, @var_name := col2 from tb_name WHERE "conditon";

if multiple record sets found only the last value in col2 is keep (override);

SELECT col1, col2 INTO @var_name, col3 FROM .....

in this case the result of select is not containing col2 values


Ex both methods used

-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations

...
SELECT count(*) INTO @NR FROM a_table WHERE a_condition;
SET NEW.ord_col =  IFNULL( @NR, 0 ) + 1;
...

Take a screenshot via a Python script on Linux

There is a python package for this Autopy

The bitmap module can to screen grabbing (bitmap.capture_screen) It is multiplateform (Windows, Linux, Osx).

XML Parsing - Read a Simple XML File and Retrieve Values

Easy way to parse the xml is to use the LINQ to XML

for example you have the following xml file

<library>
    <track id="1" genre="Rap" time="3:24">
        <name>Who We Be RMX (feat. 2Pac)</name>
        <artist>DMX</artist>
        <album>The Dogz Mixtape: Who's Next?!</album>
    </track>
    <track id="2" genre="Rap" time="5:06">
        <name>Angel (ft. Regina Bell)</name>
        <artist>DMX</artist>
        <album>...And Then There Was X</album>
    </track>
    <track id="3" genre="Break Beat" time="6:16">
        <name>Dreaming Your Dreams</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
    <track id="4" genre="Break Beat" time="9:38">
        <name>Finished Symphony</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
<library>

For reading this file, you can use the following code:

public void Read(string  fileName)
{
    XDocument doc = XDocument.Load(fileName);

    foreach (XElement el in doc.Root.Elements())
    {
        Console.WriteLine("{0} {1}", el.Name, el.Attribute("id").Value);
        Console.WriteLine("  Attributes:");
        foreach (XAttribute attr in el.Attributes())
            Console.WriteLine("    {0}", attr);
        Console.WriteLine("  Elements:");

        foreach (XElement element in el.Elements())
            Console.WriteLine("    {0}: {1}", element.Name, element.Value);
    }
}

How to highlight text using javascript

function stylizeHighlightedString() {

    var text = window.getSelection();

    // For diagnostics
    var start = text.anchorOffset;
    var end = text.focusOffset - text.anchorOffset;

    range = window.getSelection().getRangeAt(0);

    var selectionContents = range.extractContents();
    var span = document.createElement("span");

    span.appendChild(selectionContents);

    span.style.backgroundColor = "yellow";
    span.style.color = "black";

    range.insertNode(span);
}

Testing Spring's @RequestBody using Spring MockMVC

I have encountered a similar problem with a more recent version of Spring. I tried to use a new ObjectMapper().writeValueAsString(...) but it would not work in my case.

I actually had a String in a JSON format, but I feel like it is literally transforming the toString() method of every field into JSON. In my case, a date LocalDate field would end up as:

"date":{"year":2021,"month":"JANUARY","monthValue":1,"dayOfMonth":1,"chronology":{"id":"ISO","calendarType":"iso8601"},"dayOfWeek":"FRIDAY","leapYear":false,"dayOfYear":1,"era":"CE"}

which is not the best date format to send in a request ...

In the end, the simplest solution in my case is to use the Spring ObjectMapper. Its behaviour is better since it uses Jackson to build your JSON with complex types.

@Autowired
private ObjectMapper objectMapper;

and I simply used it in mytest:

mockMvc.perform(post("/api/")
                .content(objectMapper.writeValueAsString(...))
                .contentType(MediaType.APPLICATION_JSON)
);

How to get a list of sub-folders and their files, ordered by folder-names

How about using sort?

dir /b /s | sort

Here's an example I tested with:


dir /s /b /o:gn

d:\root0
d:\root0\root1
d:\root0\root1\folderA
d:\root0\root1\folderB
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt

dir /s /b | sort

d:\root0
d:\root0\root1
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt

To just get directories, use the /A:D parameter:

dir /a:d /s /b | sort

text flowing out of div

If it is just one instance that needs to be wrapped over 2 or 3 lines I would just use a few <wbr> in the string. It will treat those just like <br> but it wont insert the line break if it isn't necessary.

<div id="w74" class="dpinfo">
adsfadsadsads<wbr>fadsadsadsfadsadsa<wbr>dsfadsadsadsfadsadsads<wbr>fadsadsadsfadsadsadsfa<wbr>dsadsadsfadsadsadsfadsad<wbr>sadsfadsadsads<wbr>fadsadsadsfadsads adsfadsads
</div>

Here is a fiddle.

http://jsfiddle.net/gaby_de_wilde/UJ6zG/37/

How to trim a string to N chars in Javascript?

    let trimString = function (string, length) {
      return string.length > length ? 
             string.substring(0, length) + '...' :
             string;
    };

Use Case,

let string = 'How to trim a string to N chars in Javascript';

trimString(string, 20);

//How to trim a string...

IndentationError: unexpected unindent WHY?

@MaxPython The answer above is missing ":"

try:
   #do something
except:
  # print 'error/exception'

def printError(e): print e

Custom "confirm" dialog in JavaScript?

_x000D_
_x000D_
var confirmBox = '<div class="modal fade confirm-modal">' +_x000D_
    '<div class="modal-dialog modal-sm" role="document">' +_x000D_
    '<div class="modal-content">' +_x000D_
    '<button type="button" class="close m-4 c-pointer" data-dismiss="modal" aria-label="Close">' +_x000D_
    '<span aria-hidden="true">&times;</span>' +_x000D_
    '</button>' +_x000D_
    '<div class="modal-body pb-5"></div>' +_x000D_
    '<div class="modal-footer pt-3 pb-3">' +_x000D_
    '<a href="#" class="btn btn-primary yesBtn btn-sm">OK</a>' +_x000D_
    '<button type="button" class="btn btn-secondary abortBtn btn-sm" data-dismiss="modal">Abbrechen</button>' +_x000D_
    '</div>' +_x000D_
    '</div>' +_x000D_
    '</div>' +_x000D_
    '</div>';_x000D_
_x000D_
var dialog = function(el, text, trueCallback, abortCallback) {_x000D_
_x000D_
    el.click(function(e) {_x000D_
_x000D_
        var thisConfirm = $(confirmBox).clone();_x000D_
_x000D_
        thisConfirm.find('.modal-body').text(text);_x000D_
_x000D_
        e.preventDefault();_x000D_
        $('body').append(thisConfirm);_x000D_
        $(thisConfirm).modal('show');_x000D_
_x000D_
        if (abortCallback) {_x000D_
            $(thisConfirm).find('.abortBtn').click(function(e) {_x000D_
                e.preventDefault();_x000D_
                abortCallback();_x000D_
                $(thisConfirm).modal('hide');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        if (trueCallback) {_x000D_
            $(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
                e.preventDefault();_x000D_
                trueCallback();_x000D_
                $(thisConfirm).modal('hide');_x000D_
            });_x000D_
        } else {_x000D_
_x000D_
            if (el.prop('nodeName') == 'A') {_x000D_
                $(thisConfirm).find('.yesBtn').attr('href', el.attr('href'));_x000D_
            }_x000D_
_x000D_
            if (el.attr('type') == 'submit') {_x000D_
                $(thisConfirm).find('.yesBtn').click(function(e) {_x000D_
                    e.preventDefault();_x000D_
                    el.off().click();_x000D_
                });_x000D_
            }_x000D_
        }_x000D_
_x000D_
        $(thisConfirm).on('hidden.bs.modal', function(e) {_x000D_
            $(this).remove();_x000D_
        });_x000D_
_x000D_
    });_x000D_
}_x000D_
_x000D_
// custom confirm_x000D_
$(function() {_x000D_
    $('[data-confirm]').each(function() {_x000D_
        dialog($(this), $(this).attr('data-confirm'));_x000D_
    });_x000D_
_x000D_
    dialog($('#customCallback'), "dialog with custom callback", function() {_x000D_
_x000D_
        alert("hi there");_x000D_
_x000D_
    });_x000D_
_x000D_
});
_x000D_
.test {_x000D_
  display:block;_x000D_
  padding: 5p 10px;_x000D_
  background:orange;_x000D_
  color:white;_x000D_
  border-radius:4px;_x000D_
  margin:0;_x000D_
  border:0;_x000D_
  width:150px;_x000D_
  text-align:center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
example 1_x000D_
<a class="test" href="http://example" data-confirm="do you want really leave the website?">leave website</a><br><br>_x000D_
_x000D_
_x000D_
example 2_x000D_
<form action="">_x000D_
<button class="test" type="submit" data-confirm="send form to delete some files?">delete some files</button>_x000D_
</form><br><br>_x000D_
_x000D_
example 3_x000D_
<span class="test"  id="customCallback">with callback</span>
_x000D_
_x000D_
_x000D_

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

How to rename a table column in Oracle 10g

alter table table_name rename column oldColumn to newColumn;

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Order discrete x scale by frequency/value

You can use reorder:

qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar")

Edit:

To have the tallest bar at the left, you have to use a bit of a kludge:

qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1),
   data=mtcars,geom="bar")

I would expect this to also have negative heights, but it doesn't, so it works!

PHP: Inserting Values from the Form into MySQL

<?php
    $username="root";
    $password="";
    $database="test";

    #get the data from form fields
    $Id=$_POST['Id'];
    $P_name=$_POST['P_name'];
    $address1=$_POST['address1'];
    $address2=$_POST['address2'];
    $email=$_POST['email'];

    mysql_connect(localhost,$username,$password);
    @mysql_select_db($database) or die("unable to select database");

    if($_POST['insertrecord']=="insert"){
        $query="insert into person values('$Id','$P_name','$address1','$address2','$email')";
        echo "inside";
        mysql_query($query);
        $query1="select * from person";
        $result=mysql_query($query1);
        $num= mysql_numrows($result);

        #echo"<b>output</b>";
        print"<table border size=1 > 
        <tr><th>Id</th>
        <th>P_name</th>
        <th>address1</th>
        <th>address2</th>
        <th>email</th>
        </tr>";
        $i=0;
        while($i<$num)
        {
            $Id=mysql_result($result,$i,"Id");
            $P_name=mysql_result($result,$i,"P_name");
            $address1=mysql_result($result,$i,"address1");
            $address2=mysql_result($result,$i,"address2");
            $email=mysql_result($result,$i,"email");
            echo"<tr><td>$Id</td>
            <td>$P_name</td>
            <td>$address1</td>
            <td>$address2</td>
            <td>$email</td>
            </tr>";
            $i++;
        }
        print"</table>";
    }

    if($_POST['searchdata']=="Search")
    {
        $P_name=$_POST['name'];
        $query="select * from person where P_name='$P_name'";
        $result=mysql_query($query);
        print"<table border size=1><tr><th>Id</th>
        <th>P_name</th>
        <th>address1</th>
        <th>address2</th>
        <th>email</th>
        </tr>";
        while($row=mysql_fetch_array($result))
        {
            $Id=$row[Id];
            $P_name=$row[P_name];
            $address1=$row[address1];
            $address2=$row[address2];
            $email=$row[email];
            echo"<tr><td>$Id</td>
            <td>$P_name</td>
            <td>$address1</td>
            <td>$address2</td>
            <td>$email</td>
            </tr>";
        }
        echo"</table>";
    }
    echo"<a href=lab2.html> Back </a>";
?>

How do I uninstall a package installed using npm link?

If you've done something like accidentally npm link generator-webapp after you've changed it, you can fix it by cloning the right generator and linking that.

git clone https://github.com/yeoman/generator-webapp.git;
# for fixing generator-webapp, replace with your required repository
cd generator-webapp;
npm link;

How can I make a countdown with NSTimer?

Make Countdown app Xcode 8.1, Swift 3

import UIKit
import Foundation

class ViewController: UIViewController, UITextFieldDelegate {

    var timerCount = 0
    var timerRunning = false

    @IBOutlet weak var timerLabel: UILabel! //ADD Label
    @IBOutlet weak var textField: UITextField! //Add TextField /Enter any number to Countdown

    override func viewDidLoad() {
        super.viewDidLoad()

        //Reset
        timerLabel.text = ""
        if timerCount == 0 {
            timerRunning = false
        }
}

       //Figure out Count method
    func Counting() {
        if timerCount > 0 {
        timerLabel.text = "\(timerCount)"
            timerCount -= 1
        } else {
            timerLabel.text = "GO!"

        }

    }

    //ADD Action Button
    @IBAction func startButton(sender: UIButton) {

        //Figure out timer
        if timerRunning == false {
         _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.Counting), userInfo: nil, repeats: true)
            timerRunning = true
        }

        //unwrap textField and Display result
        if let countebleNumber = Int(textField.text!) {
            timerCount = countebleNumber
            textField.text = "" //Clean Up TextField
        } else {
            timerCount = 3 //Defoult Number to Countdown if TextField is nil
            textField.text = "" //Clean Up TextField
        }

    }

    //Dismiss keyboard
    func keyboardDismiss() {
        textField.resignFirstResponder()
    }

    //ADD Gesture Recignizer to Dismiss keyboard then view tapped
    @IBAction func viewTapped(_ sender: AnyObject) {
        keyboardDismiss()
    }

    //Dismiss keyboard using Return Key (Done) Button
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        keyboardDismiss()

        return true
    }

}

https://github.com/nikae/CountDown-

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

Generate a random number in a certain range in MATLAB

if you are looking to generate all the number within a specific rang randomly then you can try

r = randi([a b],1,d)

a = start point

b = end point

d = how many number you want to generate but keep in mind that d should be less than or equal to b-a

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

CSS div 100% height

I have another suggestion. When you want myDiv to have a height of 100%, use these extra 3 attributes on your div:

myDiv {
    min-height: 100%;
    overflow-y: hidden;
    position: relative;
}

That should do the job!

Convert string to number and add one

Parse the Id as it would be string and then add.

e.g.

$('.load_more').live("click",function() { //When user clicks
    var newcurrentpageTemp = parseInt($(this).attr("id")) + 1;//Get the id from the hyperlink
    alert(newcurrentpageTemp);
    dosomething();
});

The openssl extension is required for SSL/TLS protection

After trying everything, I finally managed to get this sorted. None of the above suggested solutions worked for me. My system is A PC Windows 10. In order to get this sorted I had to change the config.json file located here C:\Users\[Your User]\AppData\Roaming\Composer\. In there, you will find:

{
    "config": {
        "disable-tls": true},
    "repositories": {
        "packagist": {
            "type": "composer",
            "url": "http://repo.packagist.org" // this needs to change to 'https'
        }
    }
}

where you need to update the packagist repo url to point to the 'https' url version.

I am aware that the above selected solution will work for 95% of the cases, but as I said, that did not work for me. Hope this helps someone.

Happy coding!

replace NULL with Blank value or Zero in sql server

You can use the COALESCE function to automatically return null values as 0. Syntax is as shown below:

SELECT COALESCE(total_amount, 0) from #Temp1

How do I determine height and scrolling position of window in jQuery?

Pure JS

window.innerHeight
window.scrollY

is more than 10x faster than jquery (and code has similar size):

enter image description here

Here you can perform test on your machine: https://jsperf.com/window-height-width

gradlew: Permission Denied

Could also be fixed with

git update-index --chmod=+x gradlew

HTML5 textarea placeholder not appearing

I know this post has been (very well) answered by Aquarelle but just in case somebody is having this issue with other tag forms with no text such as inputs i'll leave this here:

If you have an input in your form and placeholder is not showing because a white space at the beginning, this may be caused for you "value" attribute. In case you are using variables to fill the value of an input check that there are no white spaces between the commas and the variables.

example using twig for php framework symfony :

<input type="text" name="subject" value="{{ subject }}" placeholder="hello" />       <-- this is ok
<input type="text" name="subject" value" {{ subject }} " placeholder="hello" />      <-- this will not show placeholder 

In this case the tag between {{ }} is the variable, just make sure you are not leaving spaces between the commas because white space is also a valid character.

What is the difference between HTTP 1.1 and HTTP 2.0?

HTTP 2.0 is a binary protocol that multiplexes numerous streams going over a single (normally TLS-encrypted) TCP connection.

The contents of each stream are HTTP 1.1 requests and responses, just encoded and packed up differently. HTTP2 adds a number of features to manage the streams, but leaves old semantics untouched.

Java - Convert String to valid URI object

You can use the multi-argument constructors of the URI class. From the URI javadoc:

The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.

So if you use

URI uri = new URI("http", "www.google.com?q=a b");

Then you get http:www.google.com?q=a%20b which isn't quite right, but it's a little closer.

If you know that your string will not have URL fragments (e.g. http://example.com/page#anchor), then you can use the following code to get what you want:

String s = "http://www.google.com?q=a b";
String[] parts = s.split(":",2);
URI uri = new URI(parts[0], parts[1], null);

To be safe, you should scan the string for # characters, but this should get you started.

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

Hiding elements in responsive layout?

For Bootstrap 4.0 beta (and I assume this will stay for final) there is a change - be aware that the hidden classes were removed.

See the docs: https://getbootstrap.com/docs/4.0/utilities/display/

In order to hide the content on mobile and display on the bigger devices you have to use the following classes:

d-none d-sm-block

The first class set display none all across devices and the second one display it for devices "sm" up (you could use md, lg, etc. instead of sm if you want to show on different devices.

I suggest to read about that before migration:

https://getbootstrap.com/docs/4.0/migration/#responsive-utilities

How do I set the default font size in Vim?

For the first one remove the spaces. Whitespace matters for the set command.

set guifont=Monaco:h20

For the second one it should be (the h specifies the height)

set guifont=Monospace:h20

My recommendation for setting the font is to do (if your version supports it)

set guifont=*

This will pop up a menu that allows you to select the font. After selecting the font, type

set guifont?

To show what the current guifont is set to. After that copy that line into your vimrc or gvimrc. If there are spaces in the font add a \ to escape the space.

set guifont=Monospace\ 20

Save and load MemoryStream to/from a file

Save into a file

Car car = new Car();
car.Name = "Some fancy car";
MemoryStream stream = Serializer.SerializeToStream(car);
System.IO.File.WriteAllBytes(fileName, stream.ToArray());

Load from a file

using (var stream = new MemoryStream(System.IO.File.ReadAllBytes(fileName)))
{
    Car car = (Car)Serializer.DeserializeFromStream(stream);
}

where

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Serialization
{
    public class Serializer
    {
        public static MemoryStream SerializeToStream(object o)
        {
            MemoryStream stream = new MemoryStream();
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, o);
            return stream;
        }

        public static object DeserializeFromStream(MemoryStream stream)
        {
            IFormatter formatter = new BinaryFormatter();
            stream.Seek(0, SeekOrigin.Begin);
            object o = formatter.Deserialize(stream);
            return o;
        }
    }
}

Originally the implementation of this class has been posted here

and

[Serializable]
public class Car
{
    public string Name;
}

Most Pythonic way to provide global configuration variables in config.py?

Similar to blubb's answer. I suggest building them with lambda functions to reduce code. Like this:

User = lambda passwd, hair, name: {'password':passwd, 'hair':hair, 'name':name}

#Col      Username       Password      Hair Color  Real Name
config = {'st3v3' : User('password',   'blonde',   'Steve Booker'),
          'blubb' : User('12345678',   'black',    'Bubb Ohaal'),
          'suprM' : User('kryptonite', 'black',    'Clark Kent'),
          #...
         }
#...

config['st3v3']['password']  #> password
config['blubb']['hair']      #> black

This does smell like you may want to make a class, though.

Or, as MarkM noted, you could use namedtuple

from collections import namedtuple
#...

User = namedtuple('User', ['password', 'hair', 'name']}

#Col      Username       Password      Hair Color  Real Name
config = {'st3v3' : User('password',   'blonde',   'Steve Booker'),
          'blubb' : User('12345678',   'black',    'Bubb Ohaal'),
          'suprM' : User('kryptonite', 'black',    'Clark Kent'),
          #...
         }
#...

config['st3v3'].password   #> passwd
config['blubb'].hair       #> black

Verify ImageMagick installation

Try this:

<?php
//This function prints a text array as an html list.
function alist ($array) {  
  $alist = "<ul>";
  for ($i = 0; $i < sizeof($array); $i++) {
    $alist .= "<li>$array[$i]";
  }
  $alist .= "</ul>";
  return $alist;
}
//Try to get ImageMagick "convert" program version number.
exec("convert -version", $out, $rcode);
//Print the return code: 0 if OK, nonzero if error. 
echo "Version return code is $rcode <br>"; 
//Print the output of "convert -version"    
echo alist($out); 
?>

How to get cumulative sum

Above (Pre-SQL12) we see examples like this:-

SELECT
    T1.id, SUM(T2.id) AS CumSum
FROM 
    #TMP T1
    JOIN #TMP T2 ON T2.id < = T1.id
GROUP BY
    T1.id

More efficient...

SELECT
    T1.id, SUM(T2.id) + T1.id AS CumSum
FROM 
    #TMP T1
    JOIN #TMP T2 ON T2.id < T1.id
GROUP BY
    T1.id

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

Batch command date and time in file name

I found the best solution for me, after reading all your answers:

set t=%date%_%time%
set d=%t:~10,4%%t:~7,2%%t:~4,2%_%t:~15,2%%t:~18,2%%t:~21,2%
echo hello>"Archive_%d%"

If AM I get 20160915_ 150101 (with a leading space and time).

If PM I get 20160915_2150101.

Get The Current Domain Name With Javascript (Not the path, etc.)

If you wish a full domain origin, you can use this:

document.location.origin

And if you wish to get only the domain, use can you just this:

document.location.hostname

But you have other options, take a look at the properties in:

document.location

How to pass a callback as a parameter into another function

You can use JavaScript CallBak like this:

var a;

function function1(callback) {
 console.log("First comeplete");
 a = "Some value";
 callback();
}
function function2(){
 console.log("Second comeplete:", a);
}


function1(function2);

Or Java Script Promise:

let promise = new Promise(function(resolve, reject) { 
  // do function1 job
  let a = "Your assign value"
  resolve(a);
});

promise.then(             

function(a) {
 // do function2 job with function1 return value;
 console.log("Second comeplete:", a);
},
function(error) { 
 console.log("Error found");
});

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

For people who find this old posting on the web by searching for the error message, there is another possible cause of the problem.

You could just have a typo in your call to the script, even if you have already done the things described in the other excellent answer. So check to make sure you can used the right spelling in your script tags.

TypeScript: casting HTMLElement

This seems to solve the problem, using the [index: TYPE] array access type, cheers.

interface ScriptNodeList extends NodeList {
    [index: number]: HTMLScriptElement;
}

var script = ( <ScriptNodeList>document.getElementsByName('foo') )[0];

How do I dynamically assign properties to an object in TypeScript?

Extending @jmvtrinidad solution for Angular,

When working with a already existing typed object, this is how to add new property.

let user: User = new User();
(user as any).otherProperty = 'hello';
//user did not lose its type here.

Now if you want to use otherProperty in html side, this is what you'd need:

<div *ngIf="$any(user).otherProperty">
   ...
   ...
</div>

Angular compiler treats $any() as a cast to the any type just like in TypeScript when a <any> or as any cast is used.

Change text color with Javascript?

<div id="about">About Snakelane</div>

<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
<script>
var about;   
function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

If you are getting an error with the other MemoryStream examples here, then you need to set the Position to 0.

public static Stream ToStream(this bytes[] bytes) 
{
    return new MemoryStream(bytes) 
    {
        Position = 0
    };
}

Check whether a table contains rows or not sql server 2005

FOR the best performance, use specific column name instead of * - for example:

SELECT TOP 1 <columnName> 
FROM <tableName> 

This is optimal because, instead of returning the whole list of columns, it is returning just one. That can save some time.

Also, returning just first row if there are any values, makes it even faster. Actually you got just one value as the result - if there are any rows, or no value if there is no rows.

If you use the table in distributed manner, which is most probably the case, than transporting just one value from the server to the client is much faster.

You also should choose wisely among all the columns to get data from a column which can take as less resource as possible.

How do I export a project in the Android studio?

From the menu:

Build|Generate Signed APK

or

Build|Build APK

(the latter if you don't need a signed one to publish to the Play Store)

UEFA/FIFA scores API

UEFA or FIFA don't seem to provide any API to get the information you want. However, there are some third-party services which support that:

  • OPTA - Both commercial and free. They have incredible database about matches. Whoscored.com currently uses it.

  • Others: livescoreboards, xmlsoccer, ...

Inline SVG in CSS

Yes, it is possible. Try this:

body { background-image: 
        url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='%23F00'/><stop offset='90%' stop-color='%23fcc'/> </linearGradient><rect fill='url(%23gradient)' x='0' y='0' width='100%' height='100%'/></svg>");
      }

(Note that the SVG content needs to be url-escaped for this to work, e.g. # gets replaced with %23.)

This works in IE 9 (which supports SVG). Data-URLs work in older versions of IE too (with limitations), but they don’t natively support SVG.

How to put multiple statements in one line?

Here is an example:

for i in range(80, 90): print(i, end=" ") if (i!=89) else print(i)

Output:

80 81 82 83 84 85 86 87 88 89
>>>

Get first line of a shell command's output

I would use:

awk 'FNR <= 1' file_*.txt

As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1 may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i' to 'FNR <= i' allows to obtain the first i lines.

For example, if you have n files named file_1.txt, ... file_n.txt:

awk 'FNR <= 1' file_*.txt

hello
...
bye

But with head wildcards print the name of the file:

head -1 file_*.txt

==> file_1.csv <==
hello
...
==> file_n.csv <==
bye

Cannot create SSPI context

I had the same issue after changing the user which was running the MSSQLSERVER-Service

To solve incorrect SPNs with SQL Server I used this tool

http://www.microsoft.com/en-us/download/details.aspx?id=39046 - Microsoft® Kerberos Configuration Manager for SQL Server

In my case it worked pretty well.

How to save data in an android app

Use SharedPreferences, http://developer.android.com/reference/android/content/SharedPreferences.html

Here's a sample: http://developer.android.com/guide/topics/data/data-storage.html#pref

If the data structure is more complex or the data is large, use an Sqlite database; but for small amount of data and with a very simple data structure, I'd say, SharedPrefs will do and a DB might be overhead.

Column/Vertical selection with Keyboard in SublimeText 3

The reason why the sublime documented shortcuts for Mac does not work are they are linked to the shortcuts of other Mac functionalities such as Mission Control, Application Windows, etc. Solution: Go to System Preferences -> Keyboard -> Shortcuts and then un-check the options for Mission Control and Application Windows. Now try "Control + Shift [+ Arrow keys]" for selecting the required text and then move the cursor to the required location without any mouse click, so that the selection can be pasted with the correct indentation at the required location.

Select2 doesn't work when embedded in a bootstrap modal

According to the official select2 documentation this issue occurs because Bootstrap modals tend to steal focus from other elements outside of the modal.

By default Select2 attaches the dropdown menu to the element and it is considered "outside of the modal".

Instead attach the dropdown to the modal itself with the dropdownParent setting:

$('#myModal').select2({
   dropdownParent: $('#myModal')
});

See reference: https://select2.org/troubleshooting/common-problems

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

If it helps anyone, I just appended the contents of the below output file to the existing org.apache.catalina.startup.TldConfig.jarsToSkip= entry.

Note that /var/log/tomcat7/catalina.out is the location of your tomcat log.

egrep "No TLD files were found in \[file:[^\]+\]" /var/log/tomcat7/catalina.out -o | egrep "[^]/]+.jar" -o | sort | uniq | sed -e 's/.jar/.jar,\\/g' > skips.txt

Hope that helps.

Standard deviation of a list

pure python code:

from math import sqrt

def stddev(lst):
    mean = float(sum(lst)) / len(lst)
    return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, lst))) / len(lst))

Oracle PL Sql Developer cannot find my tnsnames.ora file

Which Oracle client are you using?

Oracle 64bit 11g client isn't support in PLSQL Developer. Try to install 32bits client.

Pyspark: Exception: Java gateway process exited before sending the driver its port number

The error occured since JAVA is not installed on machine. Spark is developed in scala which usually runs on JAVA.

Try to install JAVA and execute the pyspark statements. It will works

How to disable button in React.js

just Add:

<button disabled={this.input.value?"true":""} className="add-item__button" onClick={this.add.bind(this)}>Add</button>

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

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

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

as per this answer.

How do you set, clear, and toggle a single bit?

Here are some macros I use:

SET_FLAG(Status, Flag)            ((Status) |= (Flag))
CLEAR_FLAG(Status, Flag)          ((Status) &= ~(Flag))
INVALID_FLAGS(ulFlags, ulAllowed) ((ulFlags) & ~(ulAllowed))
TEST_FLAGS(t,ulMask, ulBit)       (((t)&(ulMask)) == (ulBit))
IS_FLAG_SET(t,ulMask)             TEST_FLAGS(t,ulMask,ulMask)
IS_FLAG_CLEAR(t,ulMask)           TEST_FLAGS(t,ulMask,0)

How to convert answer into two decimal point

Try using the Format function:

Private Sub btncalc_Click(ByVal sender As System.Object,
                          ByVal e As System.EventArgs) Handles btncalc.Click
  txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) * 
                     Val(txtF.Text) / Val(txtE.Text), "0.00")
  txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00")
End Sub

How do I get the current absolute URL in Ruby on Rails?

This works for Ruby on Rails 3.0 and should be supported by most versions of Ruby on Rails:

request.env['REQUEST_URI']

Where and why do I have to put the "template" and "typename" keywords?

Preface

This post is meant to be an easy-to-read alternative to litb's post.

The underlying purpose is the same; an explanation to "When?" and "Why?" typename and template must be applied.


What's the purpose of typename and template?

typename and template are usable in circumstances other than when declaring a template.

There are certain contexts in C++ where the compiler must explicitly be told how to treat a name, and all these contexts have one thing in common; they depend on at least one template-parameter.

We refer to such names, where there can be an ambiguity in interpretation, as; "dependent names".

This post will offer an explanation to the relationship between dependent-names, and the two keywords.


A snippet says more than 1000 words

Try to explain what is going on in the following function-template, either to yourself, a friend, or perhaps your cat; what is happening in the statement marked (A)?

template<class T> void f_tmpl () { T::foo * x; /* <-- (A) */ }


It might not be as easy as one thinks, more specifically the result of evaluating (A) heavily depends on the definition of the type passed as template-parameter T.

Different Ts can drastically change the semantics involved.

struct X { typedef int       foo;       }; /* (C) --> */ f_tmpl<X> ();
struct Y { static  int const foo = 123; }; /* (D) --> */ f_tmpl<Y> ();


The two different scenarios:

  • If we instantiate the function-template with type X, as in (C), we will have a declaration of a pointer-to int named x, but;

  • if we instantiate the template with type Y, as in (D), (A) would instead consist of an expression that calculates the product of 123 multiplied with some already declared variable x.



The Rationale

The C++ Standard cares about our safety and well-being, at least in this case.

To prevent an implementation from potentially suffering from nasty surprises, the Standard mandates that we sort out the ambiguity of a dependent-name by explicitly stating the intent anywhere we'd like to treat the name as either a type-name, or a template-id.

If nothing is stated, the dependent-name will be considered to be either a variable, or a function.



How to handle dependent names?

If this was a Hollywood film, dependent-names would be the disease that spreads through body contact, instantly affects its host to make it confused. Confusion that could, possibly, lead to an ill-formed perso-, erhm.. program.

A dependent-name is any name that directly, or indirectly, depends on a template-parameter.

template<class T> void g_tmpl () {
   SomeTrait<T>::type                   foo; // (E), ill-formed
   SomeTrait<T>::NestedTrait<int>::type bar; // (F), ill-formed
   foo.data<int> ();                         // (G), ill-formed    
}

We have four dependent names in the above snippet:

  • E)
    • "type" depends on the instantiation of SomeTrait<T>, which include T, and;
  • F)
    • "NestedTrait", which is a template-id, depends on SomeTrait<T>, and;
    • "type" at the end of (F) depends on NestedTrait, which depends on SomeTrait<T>, and;
  • G)
    • "data", which looks like a member-function template, is indirectly a dependent-name since the type of foo depends on the instantiation of SomeTrait<T>.

Neither of statement (E), (F) or (G) is valid if the compiler would interpret the dependent-names as variables/functions (which as stated earlier is what happens if we don't explicitly say otherwise).

The solution

To make g_tmpl have a valid definition we must explicitly tell the compiler that we expect a type in (E), a template-id and a type in (F), and a template-id in (G).

template<class T> void g_tmpl () {
   typename SomeTrait<T>::type foo;                            // (G), legal
   typename SomeTrait<T>::template NestedTrait<int>::type bar; // (H), legal
   foo.template data<int> ();                                  // (I), legal
}

Every time a name denotes a type, all names involved must be either type-names or namespaces, with this in mind it's quite easy to see that we apply typename at the beginning of our fully qualified name.

template however, is different in this regard, since there's no way of coming to a conclusion such as; "oh, this is a template, then this other thing must also be a template". This means that we apply template directly in front of any name that we'd like to treat as such.



Can I just stick the keywords in front of any name?

"Can I just stick typename and template in front of any name? I don't want to worry about the context in which they appear..." - Some C++ Developer

The rules in the Standard states that you may apply the keywords as long as you are dealing with a qualified-name (K), but if the name isn't qualified the application is ill-formed (L).

namespace N {
  template<class T>
  struct X { };
}

         N::         X<int> a; // ...  legal
typename N::template X<int> b; // (K), legal
typename template    X<int> c; // (L), ill-formed

Note: Applying typename or template in a context where it is not required is not considered good practice; just because you can do something, doesn't mean that you should.


Additionally there are contexts where typename and template are explicitly disallowed:

  • When specifying the bases of which a class inherits

    Every name written in a derived class's base-specifier-list is already treated as a type-name, explicitly specifying typename is both ill-formed, and redundant.

                        // .------- the base-specifier-list
      template<class T> // v
      struct Derived      : typename SomeTrait<T>::type /* <- ill-formed */ {
        ...
      };
    

  • When the template-id is the one being referred to in a derived class's using-directive

      struct Base {
        template<class T>
        struct type { };
      };
    
      struct Derived : Base {
        using Base::template type; // ill-formed
        using Base::type;          // legal
      };
    

Accessing member of base class

Working example. Notes below.

class Animal {
    constructor(public name) {
    }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

class Snake extends Animal {
    move() {
        alert(this.name + " is Slithering...");
        super.move(5);
    }
}

class Horse extends Animal {
    move() {
        alert(this.name + " is Galloping...");
        super.move(45);
    }
}

var sam = new Snake("Sammy the Python");
var tom: Animal = new Horse("Tommy the Palomino");

sam.move();
tom.move(34);
  1. You don't need to manually assign the name to a public variable. Using public name in the constructor definition does this for you.

  2. You don't need to call super(name) from the specialised classes.

  3. Using this.name works.

Notes on use of super.

This is covered in more detail in section 4.9.2 of the language specification.

The behaviour of the classes inheriting from Animal is not dissimilar to the behaviour in other languages. You need to specify the super keyword in order to avoid confusion between a specialised function and the base class function. For example, if you called move() or this.move() you would be dealing with the specialised Snake or Horse function, so using super.move() explicitly calls the base class function.

There is no confusion of properties, as they are the properties of the instance. There is no difference between super.name and this.name - there is simply this.name. Otherwise you could create a Horse that had different names depending on whether you were in the specialized class or the base class.

How do I protect javascript files?

As I said in the comment I left on gion_13 answer before (please read), you really can't. Not with javascript.

If you don't want the code to be available client-side (= stealable without great efforts), my suggestion would be to make use of PHP (ASP,Python,Perl,Ruby,JSP + Java-Servlets) that is processed server-side and only the results of the computation/code execution are served to the user. Or, if you prefer, even Flash or a Java-Applet that let client-side computation/code execution but are compiled and thus harder to reverse-engine (not impossible thus).

Just my 2 cents.

EditorFor() and html properties

This is the cleanest and most elegant/simple way to get a solution here.

Brilliant blog post and no messy overkill in writing custom extension/helper methods like a mad professor.

http://geekswithblogs.net/michelotti/archive/2010/02/05/mvc-2-editor-template-with-datetime.aspx

Move branch pointer to different commit without checkout

If you want to move a non-checked out branch to another commit, the easiest way is running the git branch command with -f option, which determines where the branch HEAD should be pointing to:

git branch -f

Be careful as this won't work if the branch you are trying to move is your current branch. To move a branch pointer, run the following command: git update-ref -m "reset: Reset to " refs/heads/

The git update-ref command updates the object name stored in a ref safely.

Hope, my answer helped you.The source of information is this snippet.

How do I read the first line of a file using cat?

There are many different ways:

sed -n 1p file
head -n 1 file
awk 'NR==1' file

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Did you use the webpack... if yes please install

angular2-template-loader

and put it

test: /\.ts$/,
   loaders: ['awesome-typescript-loader', 'angular2-template-loader']

Explicitly set column value to null SQL Developer

Use Shift+Del.

More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.

Batch files - number of command line arguments

The function :getargc below may be what you're looking for.

@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof

:getargc
    set getargc_v0=%1
    set /a "%getargc_v0% = 0"
:getargc_l0
    if not x%2x==xx (
        shift
        set /a "%getargc_v0% = %getargc_v0% + 1"
        goto :getargc_l0
    )
    set getargc_v0=
    goto :eof

It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.

It also uses a nifty trick, passing the name of the return variable to be set by the function.

The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:

C:\Here> xx.cmd 1 2 3 4 5
    Count is 5
    Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
    Count is 11
    Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
    Count is 1
    Args are 1
C:\Here> xx.cmd
    Count is 0
    Args are
C:\Here> xx.cmd 1 2 "3 4 5"
    Count is 3
    Args are 1 2 "3 4 5"

Get the first key name of a JavaScript object

You can query the content of an object, per its array position.
For instance:

 let obj = {plainKey: 'plain value'};

 let firstKey = Object.keys(obj)[0]; // "plainKey"
 let firstValue = Object.values(obj)[0]; // "plain value"

 /* or */

 let [key, value] = Object.entries(obj)[0]; // ["plainKey", "plain value"]

 console.log(key); // "plainKey"
 console.log(value); // "plain value"

How to print number with commas as thousands separators?

Slightly expanding the answer of Ian Schneider:

If you want to use a custom thousands separator, the simplest solution is:

'{:,}'.format(value).replace(',', your_custom_thousands_separator)

Examples

'{:,.2f}'.format(123456789.012345).replace(',', ' ')

If you want the German representation like this, it gets a bit more complicated:

('{:,.2f}'.format(123456789.012345)
          .replace(',', ' ')  # 'save' the thousands separators 
          .replace('.', ',')  # dot to comma
          .replace(' ', '.')) # thousand separators to dot

Get class list for element with jQuery

You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.

Then you can iterate and find the one you want.

var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
    if (classList[i] === 'someClass') {
        //do something
    }
}

jQuery does not really help you here...

var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
    if (item === 'someClass') {
        //do something
    }
});

What does += mean in Python?

+= is the in-place addition operator.

It's the same as doing cnt = cnt + 1. For example:

>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44

The operator is often used in a similar fashion to the ++ operator in C-ish languages, to increment a variable by one in a loop (i += 1)

There are similar operator for subtraction/multiplication/division/power and others:

i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4

The += operator also works on strings, for example:

>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there

People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:

  1. If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

The str.join() method refers to doing the following:

mysentence = []
for x in range(100):
    mysentence.append("test")
" ".join(mysentence)

..instead of the more obvious:

mysentence = ""
for x in range(100):
    mysentence += " test"

The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)

If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()'ing it.

The APK file does not exist on disk

If you just want to know the conclusion, please go to the last section. Thanks.

Usually when building project fails, some common tricks you could try:

  • Build -> Clean Project
  • Check Build Variants
  • Restart Android Studio (as you mentioned)

But to be more specific to your problem - when Android Studio could not find the APK file on disk. It means that Android Studio has actually successfully built the project, and also generated the APK, however, for some reason, Android Studio is not able to find the file.

In this case, please check the printed directory according to the log. It's helpful.

For example:

With Android Studio 2.0 Preview (build 143.2443734).

  1. Checkout to a specific commit (so that it's detached from head): git checkout [commit_hash]
  2. Run project
  3. Android Studio tells: The APK file /Users/MyApplicationName/app/build/outputs/apk/app-debug-HEAD.apk does not exist on disk
  4. Go to the directory, there is a file actually named: app-debug-(HEAD.apk (with an extra parenthesis)
  5. Run git branch

    *(HEAD detached at 1a2bfff)

So here you could see, due to my gradle build script's mistake, file naming is somehow wrong.

Above example is just one scenario which could lead to the same issue, but not necessary to be the same root cause as yours.

As a result, I strongly recommend you to check the directory (to find the difference), and check your build.gradle script (you may change the apk name there, something like below):

applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def newFileName = "whatever you want to name it";
            def apk = output.outputFile;
            output.outputFile = new File(apk.parentFile, newFileName);
        }
    }

What is correct media query for IPad Pro?

I tried several of the proposed answers but the problem is that the media queries conflicted with other queries and instead of displaying the mobile CSS on the iPad Pro, it was displaying the desktop CSS. So instead of using max and min for dimensions, I used the EXACT VALUES and it works because on the iPad pro you can't resize the browser.

Note that I added a query for mobile CSS that I use for devices with less than 900px width; feel free to remove it if needed.

This is the query, it combines both landscape and portrait, it works for the 12.9" and if you need to target the 10.5" you can simply add the queries for these dimensions:

@media only screen and (max-width: 900px), 
(height: 1024px) and (width: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: landscape), 
(width: 1024px) and (height: 1366px) and (-webkit-min-device-pixel-ratio: 1.5) and (orientation: portrait)  {

     // insert mobile and iPad Pro 12.9" CSS here    
}

select into in mysql

Use the CREATE TABLE SELECT syntax.

http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html

CREATE TABLE new_tbl SELECT * FROM orig_tbl;

Determine a user's timezone

First, understand that time zone detection in JavaScript is imperfect. You can get the local time zone offset for a particular date and time using getTimezoneOffset on an instance of the Date object, but that's not quite the same as a full IANA time zone like America/Los_Angeles.

There are some options that can work though:

_x000D_
_x000D_
const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(tzid);
_x000D_
_x000D_
_x000D_

The result is a string containing the IANA time zone setting of the computer where the code is running.

Supported environments are listed in the Intl compatibility table. Expand the DateTimeFormat section, and look at the feature named resolvedOptions().timeZone defaults to the host environment.

  • Some libraries, such as Luxon use this API to determine the time zone through functions like luxon.Settings.defaultZoneName.

  • If you need to support an wider set of environments, such as older web browsers, you can use a library to make an educated guess at the time zone. They work by first trying the Intl API if it's available, and when it's not available, they interrogate the getTimezoneOffset function of the Date object, for several different points in time, using the results to choose an appropriate time zone from an internal data set.

    Both jsTimezoneDetect and moment-timezone have this functionality.

      // using jsTimeZoneDetect
      var tzid = jstz.determine().name();
    
      // using moment-timezone
      var tzid = moment.tz.guess();
    

    In both cases, the result can only be thought of as a guess. The guess may be correct in many cases, but not all of them.

    Additionally, these libraries have to be periodically updated to counteract the fact that many older JavaScript implementations are only aware of the current daylight saving time rule for their local time zone. More details on that here.

Ultimately, a better approach is to actually ask your user for their time zone. Provide a setting that they can change. You can use one of the above options to choose a default setting, but don't make it impossible to deviate from that in your app.

There's also the entirely different approach of not relying on the time zone setting of the user's computer at all. Instead, if you can gather latitude and longitude coordinates, you can resolve those to a time zone using one of these methods. This works well on mobile devices.

g++ undefined reference to typeinfo

Similarly to the RTTI, NO-RTTI discussion above, this problem can also occur if you use dynamic_cast and fail to include the object code containing the class implementation.

I ran into this problem building on Cygwin and then porting code to Linux. The make files, directory structure and even the gcc versions (4.8.2) were identical in both cases, but the code linked and operated correctly on Cygwin but failed to link on Linux. Red Hat Cygwin has apparently made compiler/linker modifications that avoid the object code linking requirement.

The Linux linker error message properly directed me to the dynamic_cast line, but earlier messages in this forum had me looking for missing function implementations rather than the actual problem: missing object code. My workaround was to substitute a virtual type function in the base and derived class, e.g. virtual int isSpecialType(), rather than use dynamic_cast. This technique avoids the requirement to link object implementation code just to get dynamic_cast to work properly.

Bash: Syntax error: redirection unexpected

do it the simpler way,

direc=$(basename `pwd`)

Or use the shell

$ direc=${PWD##*/}

Error: allowDefinition='MachineToApplication' beyond application level

I added to my website publish script. At the end, delete the obj folder from your website folder.

mkdir -p functionality in Python

mkdir -p gives you an error if the file already exists:

$ touch /tmp/foo
$ mkdir -p /tmp/foo
mkdir: cannot create directory `/tmp/foo': File exists

So a refinement to the previous suggestions would be to re-raise the exception if os.path.isdir returns False (when checking for errno.EEXIST).

(Update) See also this highly similar question; I agree with the accepted answer (and caveats) except I would recommend os.path.isdir instead of os.path.exists.

(Update) Per a suggestion in the comments, the full function would look like:

import os
def mkdirp(directory):
    if not os.path.isdir(directory):
        os.makedirs(directory) 

How to avoid the "divide by zero" error in SQL?

In case you want to return zero, in case a zero devision would happen, you can use:

SELECT COALESCE(dividend / NULLIF(divisor,0), 0) FROM sometable

For every divisor that is zero, you will get a zero in the result set.

How to trigger jQuery change event in code

for me $('#element').val('...').change() is the best way.

possibly undefined macro: AC_MSG_ERROR

There are two possible reasons for that problem:

  1. did not install aclocal.
    solution:install libtool

    • For ubuntu: sudo apt-get install libtool
    • For centos: sudo yum install libtool
  2. the path to LIBTOOL.m4 is error.
    solution:

    1. use aclocal --print-ac-dir to check current path to aclocal.(It's usually should be "/usr/share/aclocal" or "/usr/share/aclocal")
    2. Then check if there are *.m4 files.
    3. If not, cp corresponding *.m4 files to this path.( Maybe cp /usr/share/aclocal/*.m4 /usr/local/share/aclocal/ or cp /usr/local/share/aclocal/*.m4 /usr/share/aclocal/)

Hope it helps

How to get the selected radio button value using js

var mailcopy = document.getElementById('mailCopy').checked; 

if(mailcopy==true)
{
  alert("Radio Button Checked");
}
else
{
  alert("Radio Button un-Checked");
}

When to use the different log levels

G'day,

As a corollary to this question, communicate your interpretations of the log levels and make sure that all people on a project are aligned in their interpretation of the levels.

It's painful to see a vast variety of log messages where the severities and the selected log levels are inconsistent.

Provide examples if possible of the different logging levels. And be consistent in the info to be logged in a message.

HTH

Python Binomial Coefficient

What about this one? :) It uses correct formula, avoids math.factorial and takes less multiplication operations:

import math
import operator
product = lambda m,n: reduce(operator.mul, xrange(m, n+1), 1)
x = max(0, int(input("Enter a value for x: ")))
y = max(0, int(input("Enter a value for y: ")))
print product(y+1, x) / product(1, x-y)

Also, in order to avoid big-integer arithmetics you may use floating point numbers, convert product(a[i])/product(b[i]) to product(a[i]/b[i]) and rewrite the above program as:

import math
import operator
product = lambda iterable: reduce(operator.mul, iterable, 1)
x = max(0, int(input("Enter a value for x: ")))
y = max(0, int(input("Enter a value for y: ")))
print product(map(operator.truediv, xrange(y+1, x+1), xrange(1, x-y+1)))

How to go from Blob to ArrayBuffer

Or you can use the fetch API

fetch(URL.createObjectURL(myBlob)).then(res => res.arrayBuffer())

I don't know what the performance difference is, and this will show up on your network tab in DevTools as well.

Download multiple files with a single action

To solve this, I created a JS library to stream multiple files directly into a zip on the client-side. The main unique feature is that it has no size limits from memory (everything is streamed) nor zip format (it uses zip64 if the contents are more than 4GB).

Since it doesn't do compression, it is also very performant.

Find "downzip" it on npm or github!

What is phtml, and when should I use a .phtml extension rather than .php?

To give an example to what Alex said, if you're using Magento, for example, .phtml files are only to be found in the /design area as template files, and contain both HTML and PHP lines. Meanwhile the PHP files are pure code and don't have any lines of HTML in them.

Fastest way to convert a dict's keys & values from `unicode` to `str`?

I know I'm late on this one:

def convert_keys_to_string(dictionary):
    """Recursively converts dictionary keys to strings."""
    if not isinstance(dictionary, dict):
        return dictionary
    return dict((str(k), convert_keys_to_string(v)) 
        for k, v in dictionary.items())

Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

Thanks, riaraos, uninstalling KB952241 was the solution for me, too. Before doing that I tried to run the installer from "Programs and Features" and from the installation DVD without success. I did not want to completely remove the VS 2008 installation but only add a few components.

Notes on my system:

Windows 7 Beta 1 Visual Studio 2008 SP1

How to set page content to the middle of screen?

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>Center</title>        
    </head>
    <body>
        <div id="main_body">
          some text
        </div>
    </body>
</html>

CSS

body
{
   width: 100%;
   Height: 100%;
}
#main_body
{
    background: #ff3333;
    width: 200px;
    position: absolute;
}?

JS ( jQuery )

$(function(){
    var windowHeight = $(window).height();
    var windowWidth = $(window).width();
    var main = $("#main_body");    
    $("#main_body").css({ top: ((windowHeight / 2) - (main.height() / 2)) + "px",
                          left:((windowWidth / 2) - (main.width() / 2)) + "px" });
});

See example here

How to override the path of PHP to use the MAMP path?

Probably too late to comment but here's what I did when I ran into issues with setting php PATH for my XAMPP installation on Mac OSX

  1. Open up the file .bash_profile (found under current user folder) using the available text editor.
  2. Add the path as below:

export PATH=/path/to/your/php/installation/bin:leave/rest/of/the/stuff/untouched/:$PATH

  1. Save your .bash_profile and re-start your Mac.

Explanation: Terminal / Mac tries to run a search on the PATHS it knows about, in a hope of finding the program, when user initiates a program from the "Terminal", hence the trick here is to make the terminal find the php, the user intends to, by pointing it to the user's version of PHP at some bin folder, installed by the user.

Worked for me :)

P.S I'm still a lost sheep around my new Computer ;)

How to create a temporary directory and get the path / file name in Python

If I get your question correctly, you want to also know the names of the files generated inside the temporary directory? If so, try this:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

YES, you can Update and Insert into view and that edit will be reflected on the original table....
BUT
1-the view should have all the NOT NULL values on the table
2-the update should have the same rules as table... "updating primary key related to other foreign key.. etc"...

Read files from a Folder present in project

below code should work:

string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\Names.txt");
string[] files = File.ReadAllLines(path);

How to stretch div height to fill parent div - CSS

Simply add height: 100%; onto the #B2 styling. min-height shouldn't be necessary.

How can I test an AngularJS service from the console?

@JustGoscha's answer is spot on, but that's a lot to type when I want access, so I added this to the bottom of my app.js. Then all I have to type is x = getSrv('$http') to get the http service.

// @if DEBUG
function getSrv(name, element) {
    element = element || '*[ng-app]';
    return angular.element(element).injector().get(name);
}
// @endif

It adds it to the global scope but only in debug mode. I put it inside the @if DEBUG so that I don't end up with it in the production code. I use this method to remove debug code from prouduction builds.

How to automate drag & drop functionality using Selenium WebDriver Java

Selenium has pretty good documentation. Here is a link to the specific part of the API you are looking for.

WebElement element = driver.findElement(By.name("source")); 

WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();

Calculate the date yesterday in JavaScript

This will produce yesterday at 00:00 with minutes precision

var d = new Date();
d.setDate(d.getDate() - 1);
d.setTime(d.getTime()-d.getHours()*3600*1000-d.getMinutes()*60*1000);

I need an unordered list without any bullets

 <div class="custom-control custom-checkbox left">
    <ul class="list-unstyled">
        <li>
         <label class="btn btn-secondary text-left" style="width:100%;text-align:left;padding:2px;">
           <input type="checkbox" style="zoom:1.7;vertical-align:bottom;" asp-for="@Model[i].IsChecked" class="custom-control-input" /> @Model[i].Title
         </label>
        </li>
     </ul>
</div>

CR LF notepad++ removal

Goto View -> Show Symbol -> Show All Characters. Uncheck it. There you go.!!

enter image description here

Error when using scp command "bash: scp: command not found"

Check if scp is installed or not on from where you want want to copy check using which scp

If it's already installed, it will print you a path like /usr/bin/scp Else, install scp using:

yum -y install openssh-clients

Then copy command

scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql  /var/www/html/db_bkp/

How to utilize date add function in Google spreadsheet?

Using pretty much the same approach as used by Burnash, for the final result you can use ...

=regexextract(A1,"[0-9]+")+A2

where A1 houses the string with text and number and A2 houses the date of interest

How to instantiate, initialize and populate an array in TypeScript?

There isn't a field initialization syntax like that for objects in JavaScript or TypeScript.

Option 1:

class bar {
    // Makes a public field called 'length'
    constructor(public length: number) { }
}

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

Understanding dict.copy() - shallow or deep?

Take this example:

original = dict(a=1, b=2, c=dict(d=4, e=5))
new = original.copy()

Now let's change a value in the 'shallow' (first) level:

new['a'] = 10
# new = {'a': 10, 'b': 2, 'c': {'d': 4, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 4, 'e': 5}}
# no change in original, since ['a'] is an immutable integer

Now let's change a value one level deeper:

new['c']['d'] = 40
# new = {'a': 10, 'b': 2, 'c': {'d': 40, 'e': 5}}
# original = {'a': 1, 'b': 2, 'c': {'d': 40, 'e': 5}}
# new['c'] points to the same original['d'] mutable dictionary, so it will be changed

mysql -> insert into tbl (select from another table) and some default values

If you want to insert all the columns then

insert into def select * from abc;

here the number of columns in def should be equal to abc.

if you want to insert the subsets of columns then

insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc; 

if you want to insert some hardcorded values then

insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;

Skipping every other element after the first

def skip_elements(elements):
    # Initialize variables
    new_list = []
    i = 0

    # Iterate through the list
    for words in elements:
        # Does this element belong in the resulting list?
        if i <= len(elements):
            # Add this element to the resulting list
            new_list.insert(i,elements[i])
        # Increment i
        i += 2

    return new_list

How to read line by line or a whole text file at once?

you can also use this to read all the lines in the file one by one then print i

#include <iostream>
#include <fstream>

using namespace std;



bool check_file_is_empty ( ifstream& file){
    return file.peek() == EOF ;
}

int main (){


    string text[256];
    int lineno ;
    ifstream file("text.txt");
    int num = 0;

    while (!check_file_is_empty(file))
    {    
        getline(file , text[num]);
        num++;
    }
    for (int i = 0; i < num ; i++)
    {
        cout << "\nthis is the text in " <<  "line " << i+1 << " :: " << text[i] << endl ;


    }
    
    system("pause");

    return 0;
}

hope this could help you :)

How to change the font color of a disabled TextBox?

hi set the readonly attribute to true from the code side or run time not from the design time

txtFingerPrints.BackColor = System.Drawing.SystemColors.Info;
txtFingerPrints.ReadOnly = true;

What is the difference between Cloud Computing and Grid Computing?

Grid computing is where more than one computer coordinates to solve a problem together. Often used for problems involving a lot of number crunching, which can be easily parallelisable.

Cloud computing is where an application doesn't access resources it requires directly, rather it accesses them through something like a service. So instead of talking to a specific hard drive for storage, and a specific CPU for computation, etc. it talks to some service that provides these resources. The service then maps any requests for resources to its physical resources, in order to provide for the application. Usually the service has access to a large amount of physical resources, and can dynamically allocate them as they are needed.

In this way, if an application requires only a small amount of some resource, say computation, then the service only allocates a small amount, say on a single physical CPU (that may be shared with some other application using the service). If the application requires a large amount of some resource, then the service allocates that large amount, say a grid of CPUs. The application is relatively oblivious to this, and all the complex handling and coordination is performed by the service, not the application. In this way the application can scale well.

For example a web site written "on the cloud" may share a server with many other web sites while it has a low amount of traffic, but may be moved to its own dedicated server, or grid of servers, if it ever has massive amounts of traffic. This is all handled by the cloud service, so the application shouldn't have to be modified drastically to cope.

A cloud would usually use a grid. A grid is not necessarily a cloud or part of a cloud.

Wikipedia articles: Grid computing, Cloud computing.

Why should I use an IDE?

It definitely leads to an improvement in productivity for me. To the point where I even code Linux applications in Visual Studio on Vista and then use a Linux virtual machine to build them.

You don't have to memorize all of the arguments to a function or method call, once you start typing it the IDE will show you what arguments are needed. You get wizards to set project properties, compiler options, etc. You can search for things throughout the entire project instead of just the current document or files in a folder. If you get a compiler error, double-click it and it takes you right to the offending line.

Integration of tools like model editors, connecting to and browsing external databases, managing collections of code "snippets", GUI modeling tools, etc. All of these things could be had separately, but having them all within the same development environment saves a lot of time and keeps the development process flowing more efficiently.

How to use pip with Python 3.x alongside Python 2.x

In Windows, first installed Python 3.7 and then Python 2.7. Then, use command prompt:

pip install python2-module-name

pip3 install python3-module-name

That's all

Get current cursor position in a textbox

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

_x000D_
_x000D_
function textbox()_x000D_
{_x000D_
        var ctl = document.getElementById('Javascript_example');_x000D_
        var startPos = ctl.selectionStart;_x000D_
        var endPos = ctl.selectionEnd;_x000D_
        alert(startPos + ", " + endPos);_x000D_
}
_x000D_
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">
_x000D_
_x000D_
_x000D_

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

Show Current Location and Update Location in MKMapView in Swift

Hi Sometimes setting the showsUserLocation in code doesn't work for some weird reason.

So try a combination of the following.

In viewDidLoad()

  self.mapView.showsUserLocation = true

Go to your storyboard in Xcode, on the right panel's attribute inspector tick the User location check box, like in the attached image. run your app and you should be able to see the User location

enter image description here

Return multiple values from a SQL Server function

Another option would be to use a procedure with output parameters - Using a Stored Procedure with Output Parameters

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

Get Locale Short Date Format using javascript

Short date patterns:

const shortDatePatterns = {
'aa-DJ': "dd/MM/yyyy",
'aa-ER': "dd/MM/yyyy",
'aa-ET': "dd/MM/yyyy",
'af': "yyyy-MM-dd",
'af-NA': "yyyy-MM-dd",
'af-ZA': "yyyy-MM-dd",
'agq-CM': "d/M/yyyy",
'ak-GH': "yyyy/MM/dd",
'am': "dd/MM/yyyy",
'am-ET': "dd/MM/yyyy",
'ar': "dd/MM/yy",
'ar-001': "d/M/yyyy",
'ar-AE': "dd/MM/yyyy",
'ar-BH': "dd/MM/yyyy",
'ar-DJ': "d/M/yyyy",
'ar-DZ': "dd-MM-yyyy",
'ar-EG': "dd/MM/yyyy",
'ar-ER': "d/M/yyyy",
'ar-IL': "d/M/yyyy",
'ar-IQ': "dd/MM/yyyy",
'ar-JO': "dd/MM/yyyy",
'ar-KM': "d/M/yyyy",
'ar-KW': "dd/MM/yyyy",
'ar-LB': "dd/MM/yyyy",
'ar-LY': "dd/MM/yyyy",
'ar-MA': "dd-MM-yyyy",
'ar-MR': "d/M/yyyy",
'ar-OM': "dd/MM/yyyy",
'ar-PS': "d/M/yyyy",
'ar-QA': "dd/MM/yyyy",
'ar-SA': "dd/MM/yy",
'ar-SD': "d/M/yyyy",
'ar-SO': "d/M/yyyy",
'ar-SS': "d/M/yyyy",
'ar-SY': "dd/MM/yyyy",
'ar-TD': "d/M/yyyy",
'ar-TN': "dd-MM-yyyy",
'ar-YE': "dd/MM/yyyy",
'arn-CL': "dd-MM-yyyy",
'as': "dd-MM-yyyy",
'as-IN': "dd-MM-yyyy",
'asa-TZ': "dd/MM/yyyy",
'ast-ES': "d/M/yyyy",
'az': "dd.MM.yyyy",
'az-Cyrl-AZ': "dd.MM.yyyy",
'az-Latn-AZ': "dd.MM.yyyy",
'ba': "dd.MM.yy",
'ba-RU': "dd.MM.yy",
'bas-CM': "d/M/yyyy",
'be': "dd.MM.yy",
'be-BY': "dd.MM.yy",
'bem-ZM': "dd/MM/yyyy",
'bez-TZ': "dd/MM/yyyy",
'bg': "d.M.yyyy '?.'",
'bg-BG': "d.M.yyyy '?.'",
'bin-NG': "d/M/yyyy",
'bm': "d/M/yyyy",
'bm-Latn-ML': "d/M/yyyy",
'bn': "d/M/yyyy",
'bn-BD': "d/M/yyyy",
'bn-IN': "dd-MM-yy",
'bo': "yyyy/M/d",
'bo-CN': "yyyy/M/d",
'bo-IN': "yyyy-MM-dd",
'br': "dd/MM/yyyy",
'br-FR': "dd/MM/yyyy",
'brx-IN': "M/d/yyyy",
'bs': "d.M.yyyy.",
'bs-Cyrl-BA': "d.M.yyyy",
'bs-Latn-BA': "d.M.yyyy.",
'byn-ER': "dd/MM/yyyy",
'ca': "d/M/yyyy",
'ca-AD': "d/M/yyyy",
'ca-ES': "d/M/yyyy",
'ca-ES-valencia': "d/M/yyyy",
'ca-FR': "d/M/yyyy",
'ca-IT': "d/M/yyyy",
'ce-RU': "yyyy-MM-dd",
'cgg-UG': "dd/MM/yyyy",
'chr-Cher-US': "M/d/yyyy",
'co': "dd/MM/yyyy",
'co-FR': "dd/MM/yyyy",
'cs-CZ': "dd.MM.yyyy",
'cu': "yyyy.MM.dd",
'cu-RU': "yyyy.MM.dd",
'cy': "dd/MM/yyyy",
'cy-GB': "dd/MM/yyyy",
'da-DK': "dd-MM-yyyy",
'da-GL': "dd/MM/yyyy",
'dav-KE': "dd/MM/yyyy",
'de': "dd.MM.yyyy",
'de-AT': "dd.MM.yyyy",
'de-BE': "dd.MM.yyyy",
'de-CH': "dd.MM.yyyy",
'de-DE': "dd.MM.yyyy",
'de-IT': "dd.MM.yyyy",
'de-LI': "dd.MM.yyyy",
'de-LU': "dd.MM.yyyy",
'dje-NE': "d/M/yyyy",
'dsb-DE': "d. M. yyyy",
'dua-CM': "d/M/yyyy",
'dv-MV': "dd/MM/yy",
'dyo-SN': "d/M/yyyy",
'dz': "yyyy-MM-dd",
'dz-BT': "yyyy-MM-dd",
'ebu-KE': "dd/MM/yyyy",
'ee': "M/d/yyyy",
'ee-GH': "M/d/yyyy",
'ee-TG': "M/d/yyyy",
'el-CY': "d/M/yyyy",
'el-GR': "d/M/yyyy",
'en-001': "dd/MM/yyyy",
'en-029': "dd/MM/yyyy",
'en-150': "dd/MM/yyyy",
'en-AG': "dd/MM/yyyy",
'en-AI': "dd/MM/yyyy",
'en-AS': "M/d/yyyy",
'en-AT': "dd/MM/yyyy",
'en-AU': "d/MM/yyyy",
'en-BB': "dd/MM/yyyy",
'en-BE': "dd/MM/yyyy",
'en-BI': "M/d/yyyy",
'en-BM': "dd/MM/yyyy",
'en-BS': "dd/MM/yyyy",
'en-BW': "dd/MM/yyyy",
'en-BZ': "dd/MM/yyyy",
'en-CA': "yyyy-MM-dd",
'en-CC': "dd/MM/yyyy",
'en-CH': "dd/MM/yyyy",
'en-CK': "dd/MM/yyyy",
'en-CM': "dd/MM/yyyy",
'en-CX': "dd/MM/yyyy",
'en-CY': "dd/MM/yyyy",
'en-DE': "dd/MM/yyyy",
'en-DK': "dd/MM/yyyy",
'en-DM': "dd/MM/yyyy",
'en-ER': "dd/MM/yyyy",
'en-FI': "dd/MM/yyyy",
'en-FJ': "dd/MM/yyyy",
'en-FK': "dd/MM/yyyy",
'en-FM': "dd/MM/yyyy",
'en-GB': "dd/MM/yyyy",
'en-GD': "dd/MM/yyyy",
'en-GG': "dd/MM/yyyy",
'en-GH': "dd/MM/yyyy",
'en-GI': "dd/MM/yyyy",
'en-GM': "dd/MM/yyyy",
'en-GU': "M/d/yyyy",
'en-GY': "dd/MM/yyyy",
'en-HK': "d/M/yyyy",
'en-ID': "dd/MM/yyyy",
'en-IE': "dd/MM/yyyy",
'en-IL': "dd/MM/yyyy",
'en-IM': "dd/MM/yyyy",
'en-IN': "dd-MM-yyyy",
'en-IO': "dd/MM/yyyy",
'en-JE': "dd/MM/yyyy",
'en-JM': "d/M/yyyy",
'en-KE': "dd/MM/yyyy",
'en-KI': "dd/MM/yyyy",
'en-KN': "dd/MM/yyyy",
'en-KY': "dd/MM/yyyy",
'en-LC': "dd/MM/yyyy",
'en-LR': "dd/MM/yyyy",
'en-LS': "dd/MM/yyyy",
'en-MG': "dd/MM/yyyy",
'en-MH': "M/d/yyyy",
'en-MO': "dd/MM/yyyy",
'en-MP': "M/d/yyyy",
'en-MS': "dd/MM/yyyy",
'en-MT': "dd/MM/yyyy",
'en-MU': "dd/MM/yyyy",
'en-MW': "dd/MM/yyyy",
'en-MY': "d/M/yyyy",
'en-NA': "dd/MM/yyyy",
'en-NF': "dd/MM/yyyy",
'en-NG': "dd/MM/yyyy",
'en-NL': "dd/MM/yyyy",
'en-NR': "dd/MM/yyyy",
'en-NU': "dd/MM/yyyy",
'en-NZ': "d/MM/yyyy",
'en-PG': "dd/MM/yyyy",
'en-PH': "dd/MM/yyyy",
'en-PK': "dd/MM/yyyy",
'en-PN': "dd/MM/yyyy",
'en-PR': "M/d/yyyy",
'en-PW': "dd/MM/yyyy",
'en-RW': "dd/MM/yyyy",
'en-SB': "dd/MM/yyyy",
'en-SC': "dd/MM/yyyy",
'en-SD': "dd/MM/yyyy",
'en-SE': "yyyy-MM-dd",
'en-SG': "d/M/yyyy",
'en-SH': "dd/MM/yyyy",
'en-SI': "dd/MM/yyyy",
'en-SL': "dd/MM/yyyy",
'en-SS': "dd/MM/yyyy",
'en-SX': "dd/MM/yyyy",
'en-SZ': "dd/MM/yyyy",
'en-TC': "dd/MM/yyyy",
'en-TK': "dd/MM/yyyy",
'en-TO': "dd/MM/yyyy",
'en-TT': "dd/MM/yyyy",
'en-TV': "dd/MM/yyyy",
'en-TZ': "dd/MM/yyyy",
'en-UG': "dd/MM/yyyy",
'en-UM': "M/d/yyyy",
'en-US': "M/d/yyyy",
'en-VC': "dd/MM/yyyy",
'en-VG': "dd/MM/yyyy",
'en-VI': "M/d/yyyy",
'en-VU': "dd/MM/yyyy",
'en-WS': "dd/MM/yyyy",
'en-ZA': "yyyy/MM/dd",
'en-ZM': "dd/MM/yyyy",
'en-ZW': "d/M/yyyy",
'eo-001': "yyyy-MM-dd",
'es': "dd/MM/yyyy",
'es-419': "d/M/yyyy",
'es-AR': "d/M/yyyy",
'es-BO': "d/M/yyyy",
'es-BR': "d/M/yyyy",
'es-BZ': "d/M/yyyy",
'es-CL': "dd-MM-yyyy",
'es-CO': "d/MM/yyyy",
'es-CR': "d/M/yyyy",
'es-CU': "d/M/yyyy",
'es-DO': "d/M/yyyy",
'es-EC': "d/M/yyyy",
'es-ES': "dd/MM/yyyy",
'es-GQ': "d/M/yyyy",
'es-GT': "d/MM/yyyy",
'es-HN': "d/M/yyyy",
'es-MX': "dd/MM/yyyy",
'es-NI': "d/M/yyyy",
'es-PA': "MM/dd/yyyy",
'es-PE': "d/MM/yyyy",
'es-PH': "d/M/yyyy",
'es-PR': "MM/dd/yyyy",
'es-PY': "d/M/yyyy",
'es-SV': "d/M/yyyy",
'es-US': "M/d/yyyy",
'es-UY': "d/M/yyyy",
'es-VE': "d/M/yyyy",
'et': "dd.MM.yyyy",
'et-EE': "dd.MM.yyyy",
'eu-ES': "yyyy/M/d",
'ewo-CM': "d/M/yyyy",
'fa-IR': "dd/MM/yyyy",
'ff-CM': "d/M/yyyy",
'ff-GN': "d/M/yyyy",
'ff-Latn-SN': "dd/MM/yyyy",
'ff-MR': "d/M/yyyy",
'ff-NG': "d/M/yyyy",
'fi': "d.M.yyyy",
'fi-FI': "d.M.yyyy",
'fil-PH': "M/d/yyyy",
'fo': "dd.MM.yyyy",
'fo-DK': "dd.MM.yyyy",
'fo-FO': "dd.MM.yyyy",
'fr': "dd/MM/yyyy",
'fr-029': "dd/MM/yyyy",
'fr-BE': "dd-MM-yy",
'fr-BF': "dd/MM/yyyy",
'fr-BI': "dd/MM/yyyy",
'fr-BJ': "dd/MM/yyyy",
'fr-BL': "dd/MM/yyyy",
'fr-CA': "yyyy-MM-dd",
'fr-CD': "dd/MM/yyyy",
'fr-CF': "dd/MM/yyyy",
'fr-CG': "dd/MM/yyyy",
'fr-CH': "dd.MM.yyyy",
'fr-CI': "dd/MM/yyyy",
'fr-CM': "dd/MM/yyyy",
'fr-DJ': "dd/MM/yyyy",
'fr-DZ': "dd/MM/yyyy",
'fr-FR': "dd/MM/yyyy",
'fr-GA': "dd/MM/yyyy",
'fr-GF': "dd/MM/yyyy",
'fr-GN': "dd/MM/yyyy",
'fr-GP': "dd/MM/yyyy",
'fr-GQ': "dd/MM/yyyy",
'fr-HT': "dd/MM/yyyy",
'fr-KM': "dd/MM/yyyy",
'fr-LU': "dd/MM/yyyy",
'fr-MA': "dd/MM/yyyy",
'fr-MC': "dd/MM/yyyy",
'fr-MF': "dd/MM/yyyy",
'fr-MG': "dd/MM/yyyy",
'fr-ML': "dd/MM/yyyy",
'fr-MQ': "dd/MM/yyyy",
'fr-MR': "dd/MM/yyyy",
'fr-MU': "dd/MM/yyyy",
'fr-NC': "dd/MM/yyyy",
'fr-NE': "dd/MM/yyyy",
'fr-PF': "dd/MM/yyyy",
'fr-PM': "dd/MM/yyyy",
'fr-RE': "dd/MM/yyyy",
'fr-RW': "dd/MM/yyyy",
'fr-SC': "dd/MM/yyyy",
'fr-SN': "dd/MM/yyyy",
'fr-SY': "dd/MM/yyyy",
'fr-TD': "dd/MM/yyyy",
'fr-TG': "dd/MM/yyyy",
'fr-TN': "dd/MM/yyyy",
'fr-VU': "dd/MM/yyyy",
'fr-WF': "dd/MM/yyyy",
'fr-YT': "dd/MM/yyyy",
'fur-IT': "dd/MM/yyyy",
'fy-NL': "dd-MM-yyyy",
'ga': "dd/MM/yyyy",
'ga-IE': "dd/MM/yyyy",
'gd': "dd/MM/yyyy",
'gd-GB': "dd/MM/yyyy",
'gl': "dd/MM/yyyy",
'gl-ES': "dd/MM/yyyy",
'gn': "dd/MM/yyyy",
'gn-PY': "dd/MM/yyyy",
'gsw-CH': "dd.MM.yyyy",
'gsw-FR': "dd/MM/yyyy",
'gsw-LI': "dd.MM.yyyy",
'gu': "dd-MM-yy",
'gu-IN': "dd-MM-yy",
'guz-KE': "dd/MM/yyyy",
'gv-IM': "dd/MM/yyyy",
'ha-Latn-GH': "d/M/yyyy",
'ha-Latn-NE': "d/M/yyyy",
'ha-Latn-NG': "d/M/yyyy",
'haw-US': "d/M/yyyy",
'he-IL': "dd/MM/yyyy",
'hi-IN': "dd-MM-yyyy",
'hr': "d.M.yyyy.",
'hr-BA': "d. M. yyyy.",
'hr-HR': "d.M.yyyy.",
'hsb-DE': "d.M.yyyy",
'hu': "yyyy. MM. dd.",
'hu-HU': "yyyy. MM. dd.",
'hy-AM': "dd.MM.yyyy",
'ia-001': "yyyy/MM/dd",
'ia-FR': "yyyy/MM/dd",
'ibb-NG': "d/M/yyyy",
'id': "dd/MM/yyyy",
'id-ID': "dd/MM/yyyy",
'ig-NG': "dd/MM/yyyy",
'ii-CN': "yyyy/M/d",
'is': "d.M.yyyy",
'is-IS': "d.M.yyyy",
'it': "dd/MM/yyyy",
'it-CH': "dd.MM.yyyy",
'it-IT': "dd/MM/yyyy",
'it-SM': "dd/MM/yyyy",
'it-VA': "dd/MM/yyyy",
'iu-Cans-CA': "d/M/yyyy",
'iu-Latn-CA': "d/MM/yyyy",
'ja-JP': "yyyy/MM/dd",
'jgo-CM': "yyyy-MM-dd",
'jmc-TZ': "dd/MM/yyyy",
'jv-Java-ID': "dd/MM/yyyy",
'jv-Latn-ID': "dd/MM/yyyy",
'ka-GE': "dd.MM.yyyy",
'kab-DZ': "d/M/yyyy",
'kam-KE': "dd/MM/yyyy",
'kde-TZ': "dd/MM/yyyy",
'kea-CV': "d/M/yyyy",
'khq-ML': "d/M/yyyy",
'ki': "dd/MM/yyyy",
'ki-KE': "dd/MM/yyyy",
'kk-KZ': "dd.MM.yyyy",
'kkj-CM': "dd/MM yyyy",
'kl-GL': "dd-MM-yyyy",
'kln-KE': "dd/MM/yyyy",
'km': "dd/MM/yy",
'km-KH': "dd/MM/yy",
'kn': "dd-MM-yy",
'kn-IN': "dd-MM-yy",
'ko-KP': "yyyy. M. d.",
'ko-KR': "yyyy-MM-dd",
'kok-IN': "dd-MM-yyyy",
'kr': "d/M/yyyy",
'kr-NG': "d/M/yyyy",
'ks-Arab-IN': "M/d/yyyy",
'ks-Deva-IN': "dd-MM-yyyy",
'ksb-TZ': "dd/MM/yyyy",
'ksf-CM': "d/M/yyyy",
'ksh-DE': "d. M. yyyy",
'ku-Arab-IQ': "yyyy/MM/dd",
'ku-Arab-IR': "dd/MM/yyyy",
'kw': "dd/MM/yyyy",
'kw-GB': "dd/MM/yyyy",
'ky': "d-MMM yy",
'ky-KG': "d-MMM yy",
'la': "dd/MM/yyyy",
'la-001': "dd/MM/yyyy",
'lag-TZ': "dd/MM/yyyy",
'lb': "dd.MM.yy",
'lb-LU': "dd.MM.yy",
'lg-UG': "dd/MM/yyyy",
'lkt-US': "M/d/yyyy",
'ln-AO': "d/M/yyyy",
'ln-CD': "d/M/yyyy",
'ln-CF': "d/M/yyyy",
'ln-CG': "d/M/yyyy",
'lo-LA': "d/M/yyyy",
'lrc-IQ': "yyyy-MM-dd",
'lrc-IR': "dd/MM/yyyy",
'lt': "yyyy-MM-dd",
'lt-LT': "yyyy-MM-dd",
'lu': "d/M/yyyy",
'lu-CD': "d/M/yyyy",
'luo-KE': "dd/MM/yyyy",
'luy-KE': "dd/MM/yyyy",
'lv': "dd.MM.yyyy",
'lv-LV': "dd.MM.yyyy",
'mas-KE': "dd/MM/yyyy",
'mas-TZ': "dd/MM/yyyy",
'mer-KE': "dd/MM/yyyy",
'mfe-MU': "d/M/yyyy",
'mg': "yyyy-MM-dd",
'mg-MG': "yyyy-MM-dd",
'mgh-MZ': "dd/MM/yyyy",
'mgo-CM': "yyyy-MM-dd",
'mi-NZ': "dd/MM/yyyy",
'mk': "dd.M.yyyy",
'mk-MK': "dd.M.yyyy",
'ml': "d/M/yyyy",
'ml-IN': "d/M/yyyy",
'mn': "yyyy.MM.dd",
'mn-MN': "yyyy.MM.dd",
'mn-Mong-CN': "yyyy/M/d",
'mn-Mong-MN': "yyyy/M/d",
'mni-IN': "dd/MM/yyyy",
'moh-CA': "M/d/yyyy",
'mr': "dd-MM-yyyy",
'mr-IN': "dd-MM-yyyy",
'ms': "d/MM/yyyy",
'ms-BN': "d/MM/yyyy",
'ms-MY': "d/MM/yyyy",
'ms-SG': "d/MM/yyyy",
'mt': "dd/MM/yyyy",
'mt-MT': "dd/MM/yyyy",
'mua-CM': "d/M/yyyy",
'my': "dd-MM-yyyy",
'my-MM': "dd-MM-yyyy",
'mzn-IR': "dd/MM/yyyy",
'naq-NA': "dd/MM/yyyy",
'nb-NO': "dd.MM.yyyy",
'nb-SJ': "dd.MM.yyyy",
'nd-ZW': "dd/MM/yyyy",
'nds-DE': "d.MM.yyyy",
'nds-NL': "d.MM.yyyy",
'ne': "M/d/yyyy",
'ne-IN': "yyyy/M/d",
'ne-NP': "M/d/yyyy",
'nl': "d-M-yyyy",
'nl-AW': "dd-MM-yyyy",
'nl-BE': "d/MM/yyyy",
'nl-BQ': "dd-MM-yyyy",
'nl-CW': "dd-MM-yyyy",
'nl-NL': "d-M-yyyy",
'nl-SR': "dd-MM-yyyy",
'nl-SX': "dd-MM-yyyy",
'nmg-CM': "d/M/yyyy",
'nn-NO': "dd.MM.yyyy",
'nnh-CM': "dd/MM/yyyy",
'no': "dd.MM.yyyy",
'nqo-GN': "dd/MM/yyyy",
'nr': "yyyy-MM-dd",
'nr-ZA': "yyyy-MM-dd",
'nso-ZA': "yyyy-MM-dd",
'nus-SS': "d/MM/yyyy",
'nyn-UG': "dd/MM/yyyy",
'oc-FR': "dd/MM/yyyy",
'om': "dd/MM/yyyy",
'om-ET': "dd/MM/yyyy",
'om-KE': "dd/MM/yyyy",
'or-IN': "dd-MM-yy",
'os-GE': "dd.MM.yyyy",
'os-RU': "dd.MM.yyyy",
'pa': "dd-MM-yy",
'pa-Arab-PK': "dd-MM-yy",
'pa-IN': "dd-MM-yy",
'pap-029': "d-M-yyyy",
'pl': "dd.MM.yyyy",
'pl-PL': "dd.MM.yyyy",
'prg-001': "dd.MM.yyyy",
'prs-AF': "yyyy/M/d",
'ps': "yyyy/M/d",
'ps-AF': "yyyy/M/d",
'pt': "dd/MM/yyyy",
'pt-AO': "dd/MM/yyyy",
'pt-BR': "dd/MM/yyyy",
'pt-CH': "dd/MM/yyyy",
'pt-CV': "dd/MM/yyyy",
'pt-GQ': "dd/MM/yyyy",
'pt-GW': "dd/MM/yyyy",
'pt-LU': "dd/MM/yyyy",
'pt-MO': "dd/MM/yyyy",
'pt-MZ': "dd/MM/yyyy",
'pt-PT': "dd/MM/yyyy",
'pt-ST': "dd/MM/yyyy",
'pt-TL': "dd/MM/yyyy",
'quc-Latn-GT': "dd/MM/yyyy",
'quz-BO': "dd/MM/yyyy",
'quz-EC': "dd/MM/yyyy",
'quz-PE': "dd/MM/yyyy",
'rm-CH': "dd-MM-yyyy",
'rn-BI': "d/M/yyyy",
'ro': "dd.MM.yyyy",
'ro-MD': "dd.MM.yyyy",
'ro-RO': "dd.MM.yyyy",
'rof-TZ': "dd/MM/yyyy",
'ru': "dd.MM.yyyy",
'ru-BY': "dd.MM.yyyy",
'ru-KG': "dd.MM.yyyy",
'ru-KZ': "dd.MM.yyyy",
'ru-MD': "dd.MM.yyyy",
'ru-RU': "dd.MM.yyyy",
'ru-UA': "dd.MM.yyyy",
'rw': "yyyy-MM-dd",
'rw-RW': "yyyy-MM-dd",
'rwk-TZ': "dd/MM/yyyy",
'sa': "dd-MM-yyyy",
'sa-IN': "dd-MM-yyyy",
'sah-RU': "dd.MM.yyyy",
'saq-KE': "dd/MM/yyyy",
'sbp-TZ': "dd/MM/yyyy",
'sd': "dd/MM/yyyy",
'sd-Arab-PK': "dd/MM/yyyy",
'sd-Deva-IN': "dd/MM/yyyy",
'se': "yyyy-MM-dd",
'se-FI': "d.M.yyyy",
'se-NO': "yyyy-MM-dd",
'se-SE': "yyyy-MM-dd",
'seh-MZ': "d/M/yyyy",
'ses-ML': "d/M/yyyy",
'sg': "d/M/yyyy",
'sg-CF': "d/M/yyyy",
'shi-Latn-MA': "d/M/yyyy",
'shi-Tfng-MA': "d/M/yyyy",
'si': "yyyy-MM-dd",
'si-LK': "yyyy-MM-dd",
'sk': "d. M. yyyy",
'sk-SK': "d. M. yyyy",
'sl': "d. MM. yyyy",
'sl-SI': "d. MM. yyyy",
'sma-NO': "dd.MM.yyyy",
'sma-SE': "yyyy-MM-dd",
'smj-NO': "dd.MM.yyyy",
'smj-SE': "yyyy-MM-dd",
'smn-FI': "d.M.yyyy",
'sms-FI': "d.M.yyyy",
'sn': "yyyy-MM-dd",
'sn-Latn-ZW': "yyyy-MM-dd",
'so': "dd/MM/yyyy",
'so-DJ': "dd/MM/yyyy",
'so-ET': "dd/MM/yyyy",
'so-KE': "dd/MM/yyyy",
'so-SO': "dd/MM/yyyy",
'sq-AL': "d.M.yyyy",
'sq-MK': "d.M.yyyy",
'sq-XK': "d.M.yyyy",
'sr': "d.M.yyyy.",
'sr-Cyrl-BA': "d.M.yyyy.",
'sr-Cyrl-ME': "d.M.yyyy.",
'sr-Cyrl-RS': "dd.MM.yyyy.",
'sr-Cyrl-XK': "d.M.yyyy.",
'sr-Latn-BA': "d.M.yyyy.",
'sr-Latn-ME': "d.M.yyyy.",
'sr-Latn-RS': "d.M.yyyy.",
'sr-Latn-XK': "d.M.yyyy.",
'ss': "yyyy-MM-dd",
'ss-SZ': "yyyy-MM-dd",
'ss-ZA': "yyyy-MM-dd",
'ssy-ER': "dd/MM/yyyy",
'st': "yyyy-MM-dd",
'st-LS': "yyyy-MM-dd",
'st-ZA': "yyyy-MM-dd",
'sv': "yyyy-MM-dd",
'sv-AX': "yyyy-MM-dd",
'sv-FI': "dd-MM-yyyy",
'sv-SE': "yyyy-MM-dd",
'sw-CD': "dd/MM/yyyy",
'sw-KE': "dd/MM/yyyy",
'sw-TZ': "dd/MM/yyyy",
'sw-UG': "dd/MM/yyyy",
'syr-SY': "dd/MM/yyyy",
'ta-IN': "dd-MM-yyyy",
'ta-LK': "d/M/yyyy",
'ta-MY': "d/M/yyyy",
'ta-SG': "d/M/yyyy",
'te-IN': "dd-MM-yy",
'teo-KE': "dd/MM/yyyy",
'teo-UG': "dd/MM/yyyy",
'tg': "dd.MM.yyyy",
'tg-Cyrl-TJ': "dd.MM.yyyy",
'th': "d/M/yyyy",
'th-TH': "d/M/yyyy",
'ti-ER': "dd/MM/yyyy",
'ti-ET': "dd/MM/yyyy",
'tig-ER': "dd/MM/yyyy",
'tk': "dd.MM.yy 'ý.'",
'tk-TM': "dd.MM.yy 'ý.'",
'tn': "yyyy-MM-dd",
'tn-BW': "yyyy-MM-dd",
'tn-ZA': "yyyy-MM-dd",
'to': "d/M/yyyy",
'to-TO': "d/M/yyyy",
'tr': "d.MM.yyyy",
'tr-CY': "d.MM.yyyy",
'tr-TR': "d.MM.yyyy",
'ts-ZA': "yyyy-MM-dd",
'tt': "dd.MM.yyyy",
'tt-RU': "dd.MM.yyyy",
'twq-NE': "d/M/yyyy",
'tzm-Arab-MA': "d/M/yyyy",
'tzm-Latn-DZ': "dd-MM-yyyy",
'tzm-Latn-MA': "dd/MM/yyyy",
'tzm-Tfng-MA': "dd-MM-yyyy",
'ug': "yyyy-M-d",
'ug-CN': "yyyy-M-d",
'uk-UA': "dd.MM.yyyy",
'ur-IN': "d/M/yy",
'ur-PK': "dd/MM/yyyy",
'uz': "dd/MM/yyyy",
'uz-Arab-AF': "dd/MM yyyy",
'uz-Cyrl-UZ': "dd/MM/yyyy",
'uz-Latn-UZ': "dd/MM/yyyy",
'vai-Latn-LR': "dd/MM/yyyy",
'vai-Vaii-LR': "dd/MM/yyyy",
've': "yyyy-MM-dd",
've-ZA': "yyyy-MM-dd",
'vi': "dd/MM/yyyy",
'vi-VN': "dd/MM/yyyy",
'vo-001': "yyyy-MM-dd",
'vun-TZ': "dd/MM/yyyy",
'wae-CH': "yyyy-MM-dd",
'wal-ET': "dd/MM/yyyy",
'wo-SN': "dd/MM/yyyy",
'xh-ZA': "yyyy-MM-dd",
'xog-UG': "dd/MM/yyyy",
'yav-CM': "d/M/yyyy",
'yi-001': "dd/MM/yyyy",
'yo-BJ': "dd/MM/yyyy",
'yo-NG': "dd/MM/yyyy",
'zgh-Tfng-MA': "d/M/yyyy",
'zh-CN': "yyyy/M/d",
'zh-Hans-HK': "d/M/yyyy",
'zh-Hans-MO': "d/M/yyyy",
'zh-HK': "d/M/yyyy",
'zh-MO': "d/M/yyyy",
'zh-SG': "d/M/yyyy",
'zh-TW': "yyyy/M/d",
'zu-ZA': "M/d/yyyy",
};

Check if enum exists in Java

Just use valueOf() method. If the value doesn't exist, it throws IllegalArgumentException and you can catch it like that:

      boolean isSettingCodeValid = true;

       try {
            SettingCode.valueOf(settingCode.toUpperCase());
        } catch (IllegalArgumentException e) {
            // throw custom exception or change the isSettingCodeValid value
            isSettingCodeValid = false;
        }

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

Use docker start <your_container_name>

Then connect to database by using mssql -u <yourUsername> -p <yourPassword>

If you get an error in the first step then the docker is running and go with the second step.

Note: I use Mac as my primary OS and this might be the same answer for Unix based OSs. If not! Sorry in advance.

Convert object array to hash map, indexed by an attribute value of the Object

If you want to convert to the new ES6 Map do this:

var kvArray = [['key1', 'value1'], ['key2', 'value2']];
var myMap = new Map(kvArray);

Why should you use this type of Map? Well that is up to you. Take a look at this.

How to use Collections.sort() in Java?

Use this method Collections.sort(List,Comparator) . Implement a Comparator and pass it to Collections.sort().

class RecipeCompare implements Comparator<Recipe> {

    @Override
    public int compare(Recipe o1, Recipe o2) {
        // write comparison logic here like below , it's just a sample
        return o1.getID().compareTo(o2.getID());
    }
}

Then use the Comparator as

Collections.sort(recipes,new RecipeCompare());

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

The main difference is GIF is patented and a bit more widely supported. PNG is an open specification and alpha transparency is not supported in IE6. Support was improved in IE7, but not completely fixed.

As far as file sizes go, GIF has a smaller default color pallet, so they tend to be smaller file sizes at first glance. PNG files have a larger default pallet, however you can shrink their color pallet so that, when you do, they result in a smaller file size than GIF. The issue again is that this feature isn't as supported in Internet Explorer.

Also, because PNGs can support alpha transparency, they're the only option if you want a variation of transparency other than binary transparency.

How to escape the % (percent) sign in C's printf?

The backslash in C is used to escape characters in strings. Strings would not recognize % as a special character, and therefore no escape would be necessary. printf is another matter: use %% to print one %.