Programs & Examples On #Import hooks

Firing a Keyboard Event in Safari, using JavaScript

The Mozilla Developer Network provides the following explanation:

  1. Create an event using event = document.createEvent("KeyboardEvent")
  2. Init the keyevent


event.initKeyEvent (type, bubbles, cancelable, viewArg, 
       ctrlKeyArg, altKeyArg, shiftKeyArg, metaKeyArg, 
           keyCodeArg, charCodeArg)
  1. Dispatch the event using yourElement.dispatchEvent(event)

I don't see the last one in your code, maybe that's what you're missing. I hope this works in IE as well...

Instagram: Share photo from webpage

The short answer is: No. The only way to post images is through the mobile app.

From the Instagram API documentation:

At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:

  • Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
  • We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.

All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.

push() a two-dimensional array

Iterating over two dimensions means you'll need to check over two dimensions.

assuming you're starting with:

var myArray = [
]; //don't forget your semi-colons

You want to expand this two-dimensional array to become:

var myArray = [

Which means you need to understand what the difference is.

Start with the outer array:

var myArray = [

If you want to make this array longer, you need to check that it's the correct length, and add more inner arrays to make up the difference:

var i,
rows = 8;
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill

The next step requires iterating over every column in every array, we'll build on the original code:

var i,
rows = 8;
cols = 7; //adding columns in this time
myArray = [...]; //see first example above
for (i = 0; i < rows; i += 1) {
    //check if the index exists in the outer array (row)
    if (!(i in myArray)) {
        //if it doesn't exist, we need another array to fill
        myArray[i] = [];
    row = myArray[i];
    for (j = 0; j < cols; j += 1) {
        //check if the index exists in the inner array (column)
        if (!(i in row)) {
            //if it doesn't exist, we need to fill it with `0`
            row[j] = 0;

jQuery .load() call doesn't execute JavaScript in loaded HTML file

I was able to fix this issue by changing $(document).ready() to window.onLoad().

How does `scp` differ from `rsync`?

The major difference between these tools is how they copy files.

scp basically reads the source file and writes it to the destination. It performs a plain linear copy, locally, or over a network.

rsync also copies files locally or over a network. But it employs a special delta transfer algorithm and a few optimizations to make the operation a lot faster. Consider the call.

rsync A host:B
  • rsync will check files sizes and modification timestamps of both A and B, and skip any further processing if they match.

  • If the destination file B already exists, the delta transfer algorithm will make sure only differences between A and B are sent over the wire.

  • rsync will write data to a temporary file T, and then replace the destination file B with T to make the update look "atomic" to processes that might be using B.

Another difference between them concerns invocation. rsync has a plethora of command line options, allowing the user to fine tune its behavior. It supports complex filter rules, runs in batch mode, daemon mode, etc. scp has only a few switches.

In summary, use scp for your day to day tasks. Commands that you type once in a while on your interactive shell. It's simpler to use, and in those cases rsync optimizations won't help much.

For recurring tasks, like cron jobs, use rsync. As mentioned, on multiple invocations it will take advantage of data already transferred, performing very quickly and saving on resources. It is an excellent tool to keep two directories synchronized over a network.

Also, when dealing with large files, use rsync with the -P option. If the transfer is interrupted, you can resume it where it stopped by reissuing the command. See Sid Kshatriya's answer.

The infamous java.sql.SQLException: No suitable driver found

I've forgot to add the PostgreSQL JDBC Driver into my project (Mvnrepository).


compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'



You can also download the JAR and import to your project manually.

Why does the C++ STL not provide any "tree" containers?

Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.

Some issues to consider:

  • Are the number of children for a node fixed or variable?
  • How much overhead per node? - ie, do you need parent pointers, sibling pointers, etc.
  • What algorithms to provide? - different iterators, search algorithms, etc.

In the end, the problem ends up being that a tree container that would be useful enough to everyone, would be too heavyweight to satisfy most of the people using it. If you are looking for something powerful, Boost Graph Library is essentially a superset of what a tree library could be used for.

Here are some other generic tree implementations:

Last segment of URL in jquery

If you aren't worried about generating the extra elements using the split then filter could handle the issue you mention of the trailing slash (Assuming you have browser support for filter).

url.split('/').filter(function (s) { return !!s }).pop()

How do I install PIL/Pillow for Python 3.6?

You can download the wheel corresponding to your configuration here ("Pillow-4.1.1-cp36-cp36m-win_amd64.whl" in your case) and install it with:

pip install some-package.whl

If you have problem to install the wheel read this answer

Best way to split string into lines

Update: See here for an alternative/async solution.

This works great and is faster than Regex:

input.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None)

It is important to have "\r\n" first in the array so that it's taken as one line break. The above gives the same results as either of these Regex solutions:

Regex.Split(input, "\r\n|\r|\n")

Regex.Split(input, "\r?\n|\r")

Except that Regex turns out to be about 10 times slower. Here's my test:

Action<Action> measure = (Action func) => {
    var start = DateTime.Now;
    for (int i = 0; i < 100000; i++) {
    var duration = DateTime.Now - start;

var input = "";
for (int i = 0; i < 100; i++)
    input += "1 \r2\r\n3\n4\n\r5 \r\n\r\n 6\r7\r 8\r\n";

measure(() =>
    input.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.None)

measure(() =>
    Regex.Split(input, "\r\n|\r|\n")

measure(() =>
    Regex.Split(input, "\r?\n|\r")





and here's the Extension Method:

public static class StringExtensionMethods
    public static IEnumerable<string> GetLines(this string str, bool removeEmptyLines = false)
        return str.Split(new[] { "\r\n", "\r", "\n" },
            removeEmptyLines ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);


input.GetLines()      // keeps empty lines

input.GetLines(true)  // removes empty lines

batch file Copy files with certain extensions from multiple directories into one directory

In a batch file solution

for /R c:\source %%f in (*.xml) do copy %%f x:\destination\

The code works as such;

for each file for in directory c:\source and subdirectories /R that match pattern (\*.xml) put the file name in variable %%f, then for each file do copy file copy %%f to destination x:\\destination\\

Just tested it here on my Windows XP computer and it worked like a treat for me. But I typed it into command prompt so I used the single %f variable name version, as described in the linked question above.

Generating a random hex color code with PHP

Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.

See Wikipedia for more info.

In other words, use any colour from #000000 to #FFFFFF.

edit: Dear downvoters. Check the edit history for the question first.

When is the @JsonProperty property used and what is it used for?

Adding the JsonProperty also ensures safety in case someone decides they want to change one of the property names not realizing the class in question will be serialized to a Json object. If they change the property name the JsonProperty ensures it will be used in the Json object, and not the property name.

How do I extract data from a DataTable?

  var table = Tables[0]; //get first table from Dataset
  foreach (DataRow row in table.Rows)
       foreach (var item in row.ItemArray)

How to fast get Hardware-ID in C#?

The following approach was inspired by this answer to a related (more general) question.

The approach is to read the MachineGuid value in registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography. This value is generated during OS installation.

There are few ways around the uniqueness of the Hardware-ID per machine using this approach. One method is editing the registry value, but this would cause complications on the user's machine afterwards. Another method is to clone a drive image which would copy the MachineGuid value.

However, no approach is hack-proof and this will certainly be good enough for normal users. On the plus side, this approach is quick performance-wise and simple to implement.

public string GetMachineGuid()
   string location = @"SOFTWARE\Microsoft\Cryptography";
   string name = "MachineGuid";

   using (RegistryKey localMachineX64View = 
       RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
       using (RegistryKey rk = localMachineX64View.OpenSubKey(location))
           if (rk == null)
               throw new KeyNotFoundException(
                   string.Format("Key Not Found: {0}", location));

           object machineGuid = rk.GetValue(name);
           if (machineGuid == null)
               throw new IndexOutOfRangeException(
                   string.Format("Index Not Found: {0}", name));

           return machineGuid.ToString();

Remove the string on the beginning of an URL

Another way:

Regex.Replace(urlString, "www.(.+)", "$1");

Python list sort in descending order

You can simply do this:


Retrofit 2 - URL Query Parameter

I am new to retrofit and I am enjoying it. So here is a simple way to understand it for those that might want to query with more than one query: The ? and & are automatically added for you.


 public interface IService {

      String BASE_URL = "";
      String API_KEY = "SFSDF24242353434";

      @GET("Search") //i.e
      Call<Products> getProducts(@Query("one") String one, @Query("two") String two,    
                                @Query("key") String key)

It will be called this way. Considering you did the rest of the code already.

  Call<Results> call = service.productList("Whatever", "here", IService.API_KEY);

For example, when a query is returned, it will look like this.


Link to full project: Please star etc:

If you found this useful, don't forget to star it please. :)

Convert a string to a double - is this possible?

Use doubleval(). But be very careful about using decimals in financial transactions, and validate that user input very carefully.

PHP: Possible to automatically get all POSTed data?

Sure. Just walk through the $_POST array:

foreach ($_POST as $key => $value) {
    echo "Field ".htmlspecialchars($key)." is ".htmlspecialchars($value)."<br>";

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

How to measure time in milliseconds using ANSI C?

I always use the clock_gettime() function, returning time from the CLOCK_MONOTONIC clock. The time returned is the amount of time, in seconds and nanoseconds, since some unspecified point in the past, such as system startup of the epoch.

#include <stdio.h>
#include <stdint.h>
#include <time.h>

int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
  return ((timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
           ((timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);

int main(int argc, char **argv)
  struct timespec start, end;
  clock_gettime(CLOCK_MONOTONIC, &start);

  // Some code I am interested in measuring 

  clock_gettime(CLOCK_MONOTONIC, &end);

  uint64_t timeElapsed = timespecDiff(&end, &start);

C# RSA encryption/decryption with transmission

public static string Encryption(string strText)
            var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
                    // client encrypting data with public key issued by server                    

                    var encryptedData = rsa.Encrypt(testData, true);

                    var base64Encrypted = Convert.ToBase64String(encryptedData);

                    return base64Encrypted;
                    rsa.PersistKeyInCsp = false;

        public static string Decryption(string strText)
            var privateKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent><P>/aULPE6jd5IkwtWXmReyMUhmI/nfwfkQSyl7tsg2PKdpcxk4mpPZUdEQhHQLvE84w2DhTyYkPHCtq/mMKE3MHw==</P><Q>3WV46X9Arg2l9cxb67KVlNVXyCqc/w+LWt/tbhLJvV2xCF/0rWKPsBJ9MC6cquaqNPxWWEav8RAVbmmGrJt51Q==</Q><DP>8TuZFgBMpBoQcGUoS2goB4st6aVq1FcG0hVgHhUI0GMAfYFNPmbDV3cY2IBt8Oj/uYJYhyhlaj5YTqmGTYbATQ==</DP><DQ>FIoVbZQgrAUYIHWVEYi/187zFd7eMct/Yi7kGBImJStMATrluDAspGkStCWe4zwDDmdam1XzfKnBUzz3AYxrAQ==</DQ><InverseQ>QPU3Tmt8nznSgYZ+5jUo9E0SfjiTu435ihANiHqqjasaUNvOHKumqzuBZ8NRtkUhS6dsOEb8A2ODvy7KswUxyA==</InverseQ><D>cgoRoAUpSVfHMdYXW9nA3dfX75dIamZnwPtFHq80ttagbIe4ToYYCcyUz5NElhiNQSESgS5uCgNWqWXt5PnPu4XmCXx6utco1UVH8HGLahzbAnSy6Cj3iUIQ7Gj+9gQ7PkC434HTtHazmxVgIR5l56ZjoQ8yGNCPZnsdYEmhJWk=</D></RSAKeyValue>";

            var testData = Encoding.UTF8.GetBytes(strText);

            using (var rsa = new RSACryptoServiceProvider(1024))
                    var base64Encrypted = strText;

                    // server decrypting data with private key                    

                    var resultBytes = Convert.FromBase64String(base64Encrypted);
                    var decryptedBytes = rsa.Decrypt(resultBytes, true);
                    var decryptedData = Encoding.UTF8.GetString(decryptedBytes);
                    return decryptedData.ToString();
                    rsa.PersistKeyInCsp = false;

How to make a <div> or <a href="#"> to align center

You can use css like below;

 <a href="contact.html" style="margin:auto; text-align:center; display:block;" class="button large hpbottom">Get Started</a>

Transposing a 1D NumPy array

instead use arr[:,None] to create column vector

Best Practices for securing a REST API / web service

Thanks for the excellent advice. We ended up using a custom HTTP header to pass an identity token from the client to the service, in preparation for integrating our RESTful API with the the upcoming Zermatt Identity framework from Microsoft. I have described the problem here and our solution here. I also took tweakt's advice and bought RESTful Web Services - a very good book if you're building a RESTful API of any kind.

Rollback one specific migration in Laravel

Laravel 5.3+

Rollback one step. Natively.

php artisan migrate:rollback --step=1

And here's the manual page: docs.

Laravel 5.2 and before

No way to do without some hassle. For details, check Martin Bean's answer.

IE and Edge fix for object-fit: cover;

There is no rule to achieve that using CSS only, besides the object-fit (that you are currently using), which has partial support in EDGE1 so if you want to use this in IE, you have to use a object-fit polyfill in case you want to use just the element img, otherwise you have to do some workarounds.

You can see the the object-fit support here


You can use a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

//ES6 version
if ('objectFit' in === false) {
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('img[data-object-fit]').forEach(image => {
            (image.runtimeStyle || = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
            image.src = `data:image/svg+xml,%3Csvg xmlns='' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`

//ES5 version transpiled from code above with BabelJS
if ('objectFit' in === false) {
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
            (image.runtimeStyle || = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
            image.src = "data:image/svg+xml,%3Csvg xmlns='' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
img {
  display: inline-flex;
  width: 175px;
  height: 175px;
  margin-right: 10px;
  border: 1px solid red

[data-object-fit='cover'] {
  object-fit: cover

[data-object-fit='contain'] {
  object-fit: contain
<img data-object-fit='cover' src='//' />
<img data-object-fit='contain' src='//' />
<img src='//' />


1 - EDGE has now partial support for object-fit since version 16, and by partial, it means only works in img element (future version 18 still has only partial support)


how do you view macro code in access?

You can try the following VBA code to export Macro contents directly without converting them to VBA first. Unlike Tables, Forms, Reports, and Modules, the Macros are in a container called Scripts. But they are there and can be exported and imported using SaveAsText and LoadFromText

Option Compare Database

Option Explicit

Public Sub ExportDatabaseObjects()
On Error GoTo Err_ExportDatabaseObjects

    Dim db As Database
    Dim d As Document
    Dim c As Container
    Dim sExportLocation As String

    Set db = CurrentDb()

    sExportLocation = "C:\SomeFolder\"
    Set c = db.Containers("Scripts")
    For Each d In c.Documents
        Application.SaveAsText acMacro, d.Name, sExportLocation & "Macro_" & d.Name & ".txt"
    Next d

An alternative object to use is as follows:

  For Each obj In Access.Application.CurrentProject.AllMacros
    Access.Application.SaveAsText acMacro, obj.Name, strFilePath & "\Macro_" & obj.Name & ".txt"

Permission denied error while writing to a file in Python

If you are executing the python script via terminal pass --user to provide admin permissions.

Worked for me!

If you are using windows run the file as admin.

If you are executing via cmd, run cmd as admin and execute the python script.

How to set the component size with GridLayout? Is there a better way?

In my project I managed to use GridLayout and results are very stable, with no flickering and with a perfectly working vertical scrollbar.

First I created a JPanel for the settings; in my case it is a grid with a row for each parameter and two columns: left column is for labels and right column is for components. I believe your case is similar.

JPanel yourSettingsPanel = new JPanel();
yourSettingsPanel.setLayout(new GridLayout(numberOfParams, 2));

I then populate this panel by iterating on my parameters and alternating between adding a JLabel and adding a component.

for (int i = 0; i < numberOfParams; ++i) {

To prevent yourSettingsPanel from extending to the entire container I first wrap it in the north region of a dummy panel, that I called northOnlyPanel.

JPanel northOnlyPanel = new JPanel();
northOnlyPanel.setLayout(new BorderLayout());
northOnlyPanel.add(yourSettingsPanel, BorderLayout.NORTH);

Finally I wrap the northOnlyPanel in a JScrollPane, which should behave nicely pretty much anywhere.

JScrollPane scroll = new JScrollPane(northOnlyPanel,

Most likely you want to display this JScrollPane extended inside a JFrame; you can add it to a BorderLayout JFrame, in the CENTER region:

window.add(scroll, BorderLayout.CENTER);

In my case I put it on the left column of a GridLayout(1, 2) panel, and I use the right column to display contextual help for each parameter.

JTextArea help = new JTextArea();

JPanel split = new JPanel();
split.setLayout(new GridLayout(1, 2));

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

After snooping around all day, I figured out the answer thanks to this guide:

Basically under Eclipse -> Windows -> Preferences -> PHP Executables, there is a section on where the .exe and .ini is referenced. The defaulted ones were in the Eclipse directory when you install the PHP Development Tools SDK Feature from Eclipses Install New Software in the Help menu.

So instead of that, I added a new executable called PHP 5.3.5 (CGI) and referenced the cgi.exe and .ini from xampp's php folder.

Thank you webarto for giving your time to help me out.

How can I delete derived data in Xcode 8?

In Xcode 8, all the derived data is automatically cleaned. If you want to do it by hand, go to Locations tab from the Preferences, locate project's derived data folder, and delete files related to the project.

In macOS 10.12 and later, Xcode cleans up stale derived data, precompiled headers, and module caches. (23282174)

Xcode 8.0 Release Notes

Credits to @charmingToad

But from what I observed, the same behaviour is typical when using Xcode 8 on OS X 10.11.5/6

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

var str = 'Dude, he totally said that "You Rock!"';
var var1 = str.replace(/\"/g,"\\\"");

How to run .sh on Windows Command Prompt?

On Windows 10 Anniversary Update, it's even easier to run shell commands in/with bash on ubuntu on windows

I was trying to set my region for my x-wrt r7000 netgear router, I found the following worked for me, using bash on ubuntu on windows, you do have to enable subsystem found in windows features, and dev mode on

ssh [email protected] < /mnt/c/

How to make a function wait until a callback has been called using node.js

supposing you have a function:

var fetchPage(page, callback) {
   request(uri, function (error, response, body) {
        if (something_good) {
          callback(true, page+1);
        } else {


you can make use of callbacks like this:

fetchPage(1, x = function(next, page) {
if (next) {
    console.log("^^^ CALLBACK -->  fetchPage: " + page);
    fetchPage(page, x);

Interface or an Abstract Class: which one to use?

From a phylosophic point of view :

  • An abstract class represents an "is a" relationship. Lets say I have fruits, well I would have a Fruit abstract class that shares common responsabilities and common behavior.

  • An interface represents a "should do" relationship. An interface, in my opinion (which is the opinion of a junior dev), should be named by an action, or something close to an action, (Sorry, can't find the word, I'm not an english native speaker) lets say IEatable. You know it can be eaten, but you don't know what you eat.

From a coding point of view :

  • If your objects have duplicated code, it is an indication that they have common behavior, which means you might need an abstract class to reuse the code, which you cannot do with an interface.

  • Another difference is that an object can implement as many interfaces as you need, but you can only have one abstract class because of the "diamond problem" (check out here to know why!

I probably forget some points, but I hope it can clarify things.

PS : The "is a"/"should do" is brought by Vivek Vermani's answer, I didn't mean to steal his answer, just to reuse the terms because I liked them!

Hidden Features of Xcode

?` to properly format (reindent) your code

EDIT: Apparently re-indent feature (Edit > Format > Reindent) has no default shortcut. I guess I assigned one (in Preferences > Key bindings) a long time ago and don't even remember about that. Sorry for misleading you.

How to check if a column is empty or null using SQL query select statement?

Here is my preferred way to check for "if null or empty":

FROM UserProfile 
WHERE PropertydefinitionID in (40, 53) 
AND NULLIF(PropertyValue, '') is null

Since it modifies the search argument (SARG) it might have performance issues because it might not use an existing index on the PropertyValue column.

List all kafka topics

Kafka is a distributed system and needs Zookeeper. you have to start zookeeper too. Follow "Quick Start" here :

How to count TRUE values in a logical vector

There's also a package called bit that is specifically designed for fast boolean operations. It's especially useful if you have large vectors or need to do many boolean operations.

z <- sample(c(TRUE, FALSE), 1e8, rep = TRUE)

  sum(z) # 0.170s

  bit::sum.bit(z) # 0.021s, ~10x improvement in speed

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]


data[data$Var1>10, ]


subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars


mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Java - Getting Data from MySQL database

Here you go :

Connection con = DriverManager.getConnection("jdbc:mysql://localhost/t", "", "");

Statement st = con.createStatement();
String sql = ("SELECT * FROM posts ORDER BY id DESC LIMIT 1;");
ResultSet rs = st.executeQuery(sql);
if( { 
 int id = rs.getInt("first_column_name"); 
 String str1 = rs.getString("second_column_name");


In rs.getInt or rs.getString you can pass column_id starting from 1, but i prefer to pass column_name as its more informative as you don't have to look at database table for which index is what column.


boolean next() throws SQLException

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If the result set type is TYPE_FORWARD_ONLY, it is vendor specified whether their JDBC driver implementation will return false or throw an SQLException on a subsequent call to next.

If an input stream is open for the current row, a call to the method next will implicitly close it. A ResultSet object's warning chain is cleared when a new row is read.

Returns: true if the new current row is valid; false if there are no more rows Throws: SQLException - if a database access error occurs or this method is called on a closed result set


Using multiple case statements in select query

There are two ways to write case statements, you seem to be using a combination of the two

case a.updatedDate
    when 1760 then 'Entered on' + a.updatedDate
    when 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate


    when a.updatedDate = 1760 then 'Entered on' + a.updatedDate
    when a.updatedDate = 1710 then 'Viewed on' + a.updatedDate
    else 'Last Updated on' + a.updateDate

are equivalent. They may not work because you may need to convert date types to varchars to append them to other varchars.

IIS: Display all sites and bindings in PowerShell

The most easy way as I saw:

Foreach ($Site in get-website) { Foreach ($Bind in $Site.bindings.collection) {[pscustomobject]@{name=$;Protocol=$Bind.Protocol;Bindings=$Bind.BindingInformation}}}

AngularJS does not send hidden field value

In the controller:

$scope.entityId = $routeParams.entityId;

In the view:

<input type="hidden" name="entityId" ng-model="entity.entityId" ng-init="entity.entityId = entityId" />

Remove ALL styling/formatting from hyperlinks

You can just use an a selector in your stylesheet to define all states of an anchor/hyperlink. For example:

a {
    color: blue;

Would override all link styles and make all the states the colour blue.

How to get the currently logged in user's user id in Django?


This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user}} </p>
<p>Your User Id is  : {{}} </p>

"unrecognized import path" with go get

I had exactly the same issue, after moving from old go version (installed from old PPA) to newer (1.2.1) default packages in ubuntu 14.04.

The first step was to purge existing go:

sudo apt-get purge golang*

Which outputs following warnings:

dpkg: warning: while removing golang-go, directory '/usr/lib/go/src' not empty so not removed
dpkg: warning: while removing, directory '/usr/lib/go' not empty so not removed

It looks like removing go leaves some files behind, which in turn can confuse newer install. More precisely, installation itself will complete fine, but afterwards any go command, like "go get something" gives those "unrecognized import path" errors.

All I had to do was to remove those dirs first, reinstall golang, and all works like a charm (assuming you also set GOPATH)

# careful!
sudo rm -rf /usr/lib/go /usr/lib/go/src
sudo apt-get install golang-go

Java Could not reserve enough space for object heap error

to make sure it runs the 64 bit version of java have it like this:

"c:\Program Files\Java\jre7\bin\java.exe" -Xmx1536M -Xms1536M -XX:MaxPermSize=256M -jar forge-1.6.4-

take a look at what jre version you have installed just in case.. x64 should be in program files while x32 resides in Program Files (x86)

Unix command to check the filesize

ls -l --block-size=M 

will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB. If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.


ls -lah 

-h When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to three or less using base 2 for sizes.

man ls

How to exit from the application and show the home screen?

Here's what i did:

    public void onBackPressed() {
            Intent newIntent = new Intent(this,QuitAppActivity.class);

protected void onCreate(Bundle savedInstanceState) {

Basically what you did is cleared all activities from the stack and launch QuitAppActivity, that will finish the task.

Update label from another thread

You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.

 private void AggiornaContatore()
         this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});    
         this.lblCounter.Text = this.index.ToString(); ;

Please go through this chapter and more from this book to get a clear picture about threading:

Which are more performant, CTE or temporary tables?

Temp tables are always on disk - so as long as your CTE can be held in memory, it would most likely be faster (like a table variable, too).

But then again, if the data load of your CTE (or temp table variable) gets too big, it'll be stored on disk, too, so there's no big benefit.

In general, I prefer a CTE over a temp table since it's gone after I used it. I don't need to think about dropping it explicitly or anything.

So, no clear answer in the end, but personally, I would prefer CTE over temp tables.

Eclipse Bug: Unhandled event loop exception No more handles

If you have a fresh Windows 7, force a Windows Update. That will make the problem go away. It's a shot in the dark, but solved my problem. I struggled with it for a day until I realized that newer eclipse releases give the above error with older .net Framework: everything went fine until a driver installed .net 4.0, and from that point Eclipse editor gave the unhandled event loop exception.

Validating an XML against referenced XSD in C#

I had do this kind of automatic validation in VB and this is how I did it (converted to C#):

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags = settings.ValidationFlags |
XmlReader XMLvalidator = XmlReader.Create(reader, settings);

Then I subscribed to the settings.ValidationEventHandler event while reading the file.

How to set aliases in the Git Bash for Windows?

  • Go to: C:\Users\ [youruserdirectory] \bash_profile

  • In your bash_profile file type - alias desk='cd " [DIRECTORY LOCATION] "'

  • Refresh your User directory where the bash_profile file exists then reopen your CMD or Git Bash window

Type in desk to see if you get to the Desktop location or the location you want in the "DIRECTORY LOCATION" area above

Note: [ desk ] can be what ever name that you choose and should get you to the location you want to get to when typed in the CMD window.

Pythonic way to check if a file exists?

To check if a path is an existing file:


Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

How to get all checked checkboxes

A simple for loop which tests the checked property and appends the checked ones to a separate array. From there, you can process the array of checkboxesChecked further if needed.

// Pass the checkbox name to the function
function getCheckedBoxes(chkboxName) {
  var checkboxes = document.getElementsByName(chkboxName);
  var checkboxesChecked = [];
  // loop over them all
  for (var i=0; i<checkboxes.length; i++) {
     // And stick the checked ones onto an array...
     if (checkboxes[i].checked) {
  // Return the array if it is non-empty, or null
  return checkboxesChecked.length > 0 ? checkboxesChecked : null;

// Call as
var checkedBoxes = getCheckedBoxes("mycheckboxes");

Display the current date and time using HTML and Javascript with scrollable effects in hta application

This will help you.


var today = new Date();
document.getElementById('date').innerHTML = today

Fiddle Demo

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

I was looking for the same behavior using jdbi's BindBeanList and found the syntax is exactly the same as Peter Lang's answer above. In case anybody is running into this question, here's my code:

  @SqlUpdate("INSERT INTO table_one (col_one, col_two) VALUES <beans> ON DUPLICATE KEY UPDATE col_one=VALUES(col_one), col_two=VALUES(col_two)")
void insertBeans(@BindBeanList(value = "beans", propertyNames = {"colOne", "colTwo"}) List<Beans> beans);

One key detail to note is that the propertyName you specify within @BindBeanList annotation is not same as the column name you pass into the VALUES() call on update.

Check if number is prime number

Try this code.

bool isPrimeNubmer(int n)
    if (n == 2 || n == 3) //2, 3 are prime numbers
        return true;
    else if (n % 2 == 0) //even numbers are not prime numbers
        return false;
        int j = 3;
        int k = (n + 1) / 2 ;

        while (j <= k)
            if (n % j == 0)
                return false;
            j = j + 2;
        return true;

Code-first vs Model/Database-first

I use EF database first in order to provide more flexibility and control over the database configuration.

EF code first and model first seemed cool at first, and provides database independence, however in doing this it does not allow you to specify what I consider very basic and common database configuration information. For example table indexes, security metadata, or have a primary key containing more than one column. I find I want to use these and other common database features and therefore have to do some database configuration directly anyway.

I find the default POCO classes generated during DB first are very clean, however lack the very useful data annotation attributes, or mappings to stored procedures. I used the T4 templates to overcome some of these limitations. T4 templates are awesome, especially when combined with your own metadata and partial classes.

Model first seems to have lots of potential, but is giving me lots of bugs during complex database schema refactoring. Not sure why.

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:


PowerShell : retrieve JSON object by field value

This is my json data:


Powershell script:

$data = Get-Content "Path to json file" | Out-String | ConvertFrom-Json

foreach ($line in $data) {

Placing border inside of div and not on its edge

Yahoo! This is really possible. I found it.

For Bottom Border:

div {box-shadow: 0px -3px 0px red inset; }

For Top Border:

div {box-shadow: 0px 3px 0px red inset; }

ArrayList - How to modify a member of an object?

Well u have used Pojo Entity so u can do this. u need to get object of that and have to set data.


that way u can do that. or u can set other param too.

trim left characters in sql server?

You can use LEN in combination with SUBSTRING:

SELECT SUBSTRING(myColumn, 7, LEN(myColumn)) from myTable

How to install pandas from pip on windows cmd?

Please Ensure you are using a virtualEnv this is how :

virtualenv -p python3 envname

source env/bin/activate
pip install pandas

on windows you have to add scripts exe in the CLASSPATH in order to use pip command


i suggest you to use MINGW he can gives you a better environment to work with python

How to change font size in a textbox in html

To actually do it in HTML with inline CSS (not with an external CSS style sheet)

<input type="text" style="font-size: 44pt">

A lot of people would consider putting the style right into the html like this to be poor form. However, I frequently make extreeemly simple web pages for my own use that don't even have a <html> or <body> tag, and such is appropriate there.

How to specify the download location with wget?

Make sure you have the URL correct for whatever you are downloading. First of all, URLs with characters like ? and such cannot be parsed and resolved. This will confuse the cmd line and accept any characters that aren't resolved into the source URL name as the file name you are downloading into.

For example:

wget ""

will download into a file named, ?source=typ_redirect.

As you can see, knowing a thing or two about URLs helps to understand wget.

I am booting from a hirens disk and only had Linux 2.6.1 as a resource (import os is unavailable). The correct syntax that solved my problem downloading an ISO onto the physical hard drive was:

wget "(source url)" -O (directory where HD was mounted)/isofile.iso" 

One could figure the correct URL by finding at what point wget downloads into a file named index.html (the default file), and has the correct size/other attributes of the file you need shown by the following command:

wget "(source url)"

Once that URL and source file is correct and it is downloading into index.html, you can stop the download (ctrl + z) and change the output file by using:

-O "<specified download directory>/filename.extension"

after the source url.

In my case this results in downloading an ISO and storing it as a binary file under isofile.iso, which hopefully mounts.

How to get source code of a Windows executable?

There's nothing you can do about it i'm afraid as you won't be able to view it in a readable format, it's pretty much intentional and it'll show the interpreted machine code, there would be no formatting or comments as you normally get in .cs/.c files.

It's pretty much a hit and miss scenario.

Someone has already asked about it on another website

What is the C# equivalent of friend?

The closet equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:

class Outer
    class Inner
       // This class can access Outer's private members

or if you prefer to put the Inner class in another file:

partial class Outer

partial class Outer
    class Inner
       // This class can access Outer's private members

Android Min SDK Version vs. Target SDK Version

android:minSdkVersion and android:targetSdkVersion both are Integer value we need to declare in android manifest file but both are having different properties.

android:minSdkVersion: This is minimum required API level to run an android app. If we will install the same app on lower API version the parser error will be appear, and application not support problem will appear.

android:targetSdkVersion: Target sdk version is to set the Target API level of app. if this attribute not declared in manifest, minSdk version will be your TargetSdk Version. This is always true that "app support installation on all higher version of API we declared as TargetSdk Version". To make app limited target we need to declare maxSdkVersion in our manifest file...

Stopping a CSS3 Animation on last frame

The best way seems to put the final state at the main part of css. Like here, i put width to 220px, so that it finally becomes 220px. But starting to 0px; {
  font-size: 20px;
  border: 2px solid #fff;
  width: 220px;
  animation: slide 1s;
  -webkit-animation: slide 1s; /* Safari and Chrome */
@-webkit-keyframes slide { /* Safari and Chrome */
  from {width:0px;}
  to {width:220px;}

How do I import a .bak file into Microsoft SQL Server 2012?

For SQL Server 2008, I would imagine the procedure is similar...?

  • open SQL Server Management Studio
  • log in to a SQL Server instance, right click on "Databases", select "Restore Database"
  • wizard appears, you want "from device" which allows you to select a .bak file

Visual Studio: How to show Overloads in IntelliSense?

Try the keyboard shortcut Ctrl-Shift-Space. This corresponds to Edit.ParameterInfo, in case you've changed the default.


descriptive screenshot, by jp2code

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

In my case I had inherited from the IdentityDbContext correctly (with my own custom types and key defined) but had inadvertantly removed the call to the base class's OnModelCreating:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    base.OnModelCreating(modelBuilder); // I had removed this
    /// Rest of on model creating here.

Which then fixed up my missing indexes from the identity classes and I could then generate migrations and enable migrations appropriately.

How to return a file (FileContentResult) in ASP.NET WebAPI

If you want to return IHttpActionResult you can do it like this:

public IHttpActionResult Test()
    var stream = new MemoryStream();

    var result = new HttpResponseMessage(HttpStatusCode.OK)
        Content = new ByteArrayContent(stream.GetBuffer())
    result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
        FileName = "test.pdf"
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

    var response = ResponseMessage(result);

    return response;

Classes vs. Modules in VB.NET

I think it's a good idea to keep avoiding modules unless you stick them into separate namespaces. Because in Intellisense methods in modules will be visible from everywhere in that namespace.

So instead of ModuleName.MyMethod() you end up with MyMethod() popups in anywhere and this kind of invalidates the encapsulation. (at least in the programming level).

That's why I always try to create Class with shared methods, seems so much better.

Unable to open project... cannot be opened because the project file cannot be parsed

In case if you did not find in Text === or <<< or >>>> like was for me problem was really simple and fun... I change name of App in Xcode, but not change it in UnityProjectSettings before build - that was the problem...

Use Mockito to mock some methods but not others

According to docs :

Foo mock = mock(Foo.class, CALLS_REAL_METHODS);

// this calls the real implementation of Foo.getSomething()
value = mock.getSomething();


// now fakeValue is returned
value = mock.getSomething();

in_array() and multidimensional array

It works too creating first a new unidimensional Array from the original one.

$arr = array("key1"=>"value1","key2"=>"value2","key3"=>"value3");

foreach ($arr as $row)  $vector[] = $row['key1'];


Difference between View and table in sql

Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.

View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are

  • We can combine columns/rows from multiple table or another view and have a consolidated view.
  • Views can be used as security mechanisms by letting users access data through the view, without granting the users permissions to directly access the underlying base tables of the view
  • It acts as abstract layer to downstream systems, so any change in schema is not exposed and hence the downstream systems doesn't get affected.

How to get value of Radio Buttons?

To Get the Value when the radio button is checked

if (rdbtnSN06.IsChecked == true)
string RadiobuttonContent =Convert.ToString(rdbtnSN06.Content.ToString());
string RadiobuttonContent =Convert.ToString(rdbtnSN07.Content.ToString());

jQuery: serialize() form and other parameters

I dont know but none of the above worked for me, Then i used this and it worked :

In form's serialized array it is stored as key value pair

We pushed the new value or values here in form variable and then we can pass this variable directly now.

var form = $('form.sigPad').serializeArray();
var uniquekey = {
      name: "uniquekey",
      value: $('#UniqueKey').val()

How to resize image automatically on browser width resize but keep same height?

Since you are having trouble adjusting the height you might be able to use this.

width: 100%;
height: 100%;
max-height: 300px;

I'm not sure exactly what size or location you are putting your images but maybe this will help!

How to Query an NTP Server using C#? is going to work well for Windows Phone .

Adding the relevant code

/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the 
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
    /// <summary>
    /// Contains the time returned from the Ntp request
    /// </summary>
    public class TimeReceivedEventArgs : EventArgs
        public DateTime CurrentTime { get; internal set; }

    /// <summary>
    /// Subscribe to this event to receive the time acquired by the NTP requests
    /// </summary>
    public event EventHandler<TimeReceivedEventArgs> TimeReceived;

    protected void OnTimeReceived(DateTime time)
        if (TimeReceived != null)
            TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });

    /// <summary>
    /// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
    /// information later and will provide method to allow some one to choose an NTP server.
    /// </summary>
    public string[] NtpServerList = new string[]
        " ",

    string _serverName;
    private Socket _socket;

    /// <summary>
    /// Constructor allowing an NTP server to be specified
    /// </summary>
    /// <param name="serverName">the name of the NTP server to be used</param>
    public NtpClient(string serverName)
        _serverName = serverName;

    /// <summary>
    /// </summary>
    public NtpClient()
        : this("")
    { }

    /// <summary>
    /// Begins the network communication required to retrieve the time from the NTP server
    /// </summary>
    public void RequestTime()
        byte[] buffer = new byte[48];
        buffer[0] = 0x1B;
        for (var i = 1; i < buffer.Length; ++i)
            buffer[i] = 0;
        DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);

        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
        sArgsConnect.Completed += (o, e) =>
            if (e.SocketError == SocketError.Success)
                SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
                sArgs.Completed +=
                    new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
                sArgs.SetBuffer(buffer, 0, buffer.Length);
                sArgs.UserToken = buffer;


    void sArgs_Completed(object sender, SocketAsyncEventArgs e)
        if (e.SocketError == SocketError.Success)
            byte[] buffer = (byte[])e.Buffer;
            SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
            sArgs.RemoteEndPoint = e.RemoteEndPoint;

            sArgs.SetBuffer(buffer, 0, buffer.Length);
            sArgs.Completed += (o, a) =>
                if (a.SocketError == SocketError.Success)
                    byte[] timeData = a.Buffer;

                    ulong hTime = 0;
                    ulong lTime = 0;

                    for (var i = 40; i <= 43; ++i)
                        hTime = hTime << 8 | buffer[i];
                    for (var i = 44; i <= 47; ++i)
                        lTime = lTime << 8 | buffer[i];
                    ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);

                    TimeSpan timeSpan =
                        TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    var currentTime = new DateTime(1900, 1, 1) + timeSpan;


Usage :

public partial class MainPage : PhoneApplicationPage
    private NtpClient _ntpClient;
    public MainPage()
        _ntpClient = new NtpClient();
        _ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);

    void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
        this.Dispatcher.BeginInvoke(() =>
                                            txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
                                            txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();

    private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)

How do you make Git work with IntelliJ?

On Window machine install any version of Git. I installed


. Got to search program and search for git.exe. The file can be located under



Open Intelli IDEA>Settings>Version Control>Git. On Path To Git executable add the path. Click on Test button. It will show a message as

Git executed successfully

Now click on Apply and Save. This will solve the issue. .

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

How do I parse JSON from a Java HTTPResponse?

Jackson appears to support some amount of JSON parsing straight from an InputStream. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.

Why does my sorting loop seem to append an element where it shouldn't?

Your output is correct. Denote the white characters of " Hello" and " This" at the beginning.

Another issue is with your methodology. Use the Arrays.sort() method:

String[] strings = { " Hello ", " This ", "Is ", "Sorting ", "Example" };



Here the third element of the array "is" should be "Is", otherwise it will come in last after sorting. Because the sort method internally uses the ASCII value to sort elements.

Checking the form field values before submitting that page

use return before calling the function, while you click the submit button, two events(form posting as you used submit button and function call for onclick) will happen, to prevent form posting you have to return false, you have did it, also you have to specify the return i.e, to expect a value from the function,

this is a code:

input type="submit" name="continue" value="submit" onClick="**return** checkform();"

What is the correct value for the disabled attribute?

HTML5 spec: :

The checked content attribute is a boolean attribute :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.


The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />


If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

error C2220: warning treated as error - no 'object' file generated

The error says that a warning was treated as an error, therefore your problem is a warning message! The object file is then not created because there was an error. So you need to check your warnings and fix them.

In case you don't know how to find them: Open the Error List (View > Error List) and click on Warning.

How to do something to each file in a directory with a batch script

Command line usage:

for /f %f in ('dir /b c:\') do echo %f

Batch file usage:

for /f %%f in ('dir /b c:\') do echo %%f

Update: if the directory contains files with space in the names, you need to change the delimiter the for /f command is using. for example, you can use the pipe char.

for /f "delims=|" %%f in ('dir /b c:\') do echo %%f

Update 2: (quick one year and a half after the original answer :-)) If the directory name itself has a space in the name, you can use the usebackq option on the for:

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files"`) do echo %%f

And if you need to use output redirection or command piping, use the escape char (^):

for /f "usebackq delims=|" %%f in (`dir /b "c:\program files" ^| findstr /i microsoft`) do echo %%f

C# getting the path of %AppData%

This is working for me in a console application -

string appData = System.Environment.GetEnvironmentVariable("APPDATA");

Append an empty row in dataframe using pandas

Add a new pandas.Series using pandas.DataFrame.append().

If you wish to specify the name (AKA the "index") of the new row, use:


If you don't wish to name the new row, use:

df.append(pandas.Series(), ignore_index=True)

where df is your pandas.DataFrame.

Global variables in header file

Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol :

This type of code create problem while porting.

Python: PIP install path, what is the correct location for this and other addons?

Modules go in site-packages and executables go in your system's executable path. For your environment, this path is /usr/local/bin/.

To avoid having to deal with this, simply use easy_install, distribute or pip. These tools know which files need to go where.

What are projection and selection?

Simply PROJECTION deals with elimination or selection of columns, while SELECTION deals with elimination or selection of rows.

Smooth scrolling when clicking an anchor link

Adding this:

function () {
    window.location.hash = href;

is somehow nullifying the vertical offset

top - 72

in Firefox and IE, ut not in Chrome. Basically, the page scrolls smoothly to the point at which it should stop based upon the offset, but then jumps down to where the page would go without the offset.

It does add the hash to the end of the url, but pressing back does not take you back to the top, it just removes the hash from the url and leaves the viewing window where it sits.

Here is the full js I am using:

var $root = $('html, body');
$('a').click(function() {
    var href = $.attr(this, 'href');
        scrollTop: $(href).offset().top - 120
    }, 500, function () {
        window.location.hash = href;
    return false;

How can I create an object based on an interface file definition in TypeScript?

If you are creating the "modal" variable elsewhere, and want to tell TypeScript it will all be done, you would use:

declare const modal: IModal;

If you want to create a variable that will actually be an instance of IModal in TypeScript you will need to define it fully.

const modal: IModal = {
    content: '',
    form: '',
    href: '',
    $form: null,
    $message: null,
    $modal: null,
    $submits: null

Or lie, with a type assertion, but you'll lost type safety as you will now get undefined in unexpected places, and possibly runtime errors, when accessing modal.content and so on (properties that the contract says will be there).

const modal = {} as IModal;

Example Class

class Modal implements IModal {
    content: string;
    form: string;
    href: string;
    $form: JQuery;
    $message: JQuery;
    $modal: JQuery;
    $submits: JQuery;

const modal = new Modal();

You may think "hey that's really a duplication of the interface" - and you are correct. If the Modal class is the only implementation of the IModal interface you may want to delete the interface altogether and use...

const modal: Modal = new Modal();

Rather than

const modal: IModal = new Modal();

Convert to/from DateTime and Time in Ruby

require 'time'
require 'date'

t =
d =

dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)

SQL Server: Difference between PARTITION BY and GROUP BY

It has really different usage scenarios. When you use GROUP BY you merge some of the records for the columns that are same and you have an aggregation of the result set.

However when you use PARTITION BY your result set is same but you just have an aggregation over the window functions and you don't merge the records, you will still have the same count of records.

Here is a rally helpful article explaining the difference:

How is a tag different from a branch in Git? Which should I use, here?

Tags can be either signed or unsigned; branches are never signed.

Signed tags can never move because they are cryptographically bound (with a signature) to a particular commit. Unsigned tags are not bound and it is possible to move them (but moving tags is not a normal use case).

Branches can not only move to a different commit but are expected to do so. You should use a branch for your local development project. It doesn't quite make sense to commit work to a Git repository "on a tag".

How do I use IValidatableObject?

The problem with the accepted answer is that it now depends on the caller for the object to be properly validated. I would either remove the RangeAttribute and do the range validation inside the Validate method or I would create a custom attribute subclassing RangeAttribute that takes the name of the required property as an argument on the constructor.

For example:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class RangeIfTrueAttribute : RangeAttribute
    private readonly string _NameOfBoolProp;

    public RangeIfTrueAttribute(string nameOfBoolProp, int min, int max) : base(min, max)
        _NameOfBoolProp = nameOfBoolProp;

    public RangeIfTrueAttribute(string nameOfBoolProp, double min, double max) : base(min, max)
        _NameOfBoolProp = nameOfBoolProp;

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        var property = validationContext.ObjectType.GetProperty(_NameOfBoolProp);
        if (property == null)
            return new ValidationResult($"{_NameOfBoolProp} not found");

        var boolVal = property.GetValue(validationContext.ObjectInstance, null);

        if (boolVal == null || boolVal.GetType() != typeof(bool))
            return new ValidationResult($"{_NameOfBoolProp} not boolean");

        if ((bool)boolVal)
            return base.IsValid(value, validationContext);
        return null;

What does "The code generator has deoptimised the styling of [some file] as it exceeds the max of "100KB"" mean?

I tried Ricardo Stuven's way but it didn't work for me. What worked in the end was adding "compact": false to my .babelrc file:

    "compact": false,
    "presets": ["latest", "react", "stage-0"]

Programmatically navigate using react router V4

As sometimes I prefer to switch routes by Application then by buttons, this is a minimal working example what works for me:

import { Component } from 'react'
import { BrowserRouter as Router, Link } from 'react-router-dom'

class App extends Component {
  constructor(props) {

    /** @type BrowserRouter */
    this.router = undefined

  async handleSignFormSubmit() {
    await magic()

  render() {
    return (
      <Router ref={ el => this.router = el }>
        <Link to="/signin">Sign in</Link>
        <Route path="/signin" exact={true} render={() => (
          <SignPage onFormSubmit={ this.handleSignFormSubmit } />
        )} />

Maven: How do I activate a profile from command line?

Both commands are correct :

mvn clean install -Pdev1
mvn clean install -P dev1

The problem is most likely not profile activation, but the profile not accomplishing what you expect it to.

It is normal that the command :

mvn help:active-profiles

does not display the profile, because is does not contain -Pdev1. You could add it to make the profile appear, but it would be pointless because you would be testing maven itself.

What you should do is check the profile behavior by doing the following :

  1. set activeByDefault to true in the profile configuration,
  2. run mvn help:active-profiles (to make sure it is effectively activated even without -Pdev1),
  3. run mvn install.

It should give the same results as before, and therefore confirm that the problem is the profile not doing what you expect.

how to set auto increment column with sql developer

@tom-studee you were right, it's possible to do it in the data modeler.

Double click your table, then go to the column section. Here double click on the column which will have the auto increment. In the general section there is a checkbox "autoincrement", just tick it.

After that you can also go to the "autoincrement" section to customize it.

When you save it and ask the data modeler to generate the SQL script, you will see the sequence and trigger which represent your autoincrement.

SELECTING with multiple WHERE conditions on same column

You can either use GROUP BY and HAVING COUNT(*) = _:

SELECT contact_id
FROM your_table
WHERE flag IN ('Volunteer', 'Uploaded', ...)
GROUP BY contact_id
HAVING COUNT(*) = 2 -- // must match number in the WHERE flag IN (...) list

(assuming contact_id, flag is unique).

Or use joins:

SELECT T1.contact_id
FROM your_table T1
JOIN your_table T2 ON T1.contact_id = T2.contact_id AND T2.flag = 'Uploaded'
-- // more joins if necessary
WHERE T1.flag = 'Volunteer'

If the list of flags is very long and there are lots of matches the first is probably faster. If the list of flags is short and there are few matches, you will probably find that the second is faster. If performance is a concern try testing both on your data to see which works best.

What is the command to truncate a SQL Server log file?

Another option altogether is to detach the database via Management Studio. Then simply delete the log file, or rename it and delete later.

Back in Management Studio attach the database again. In the attach window remove the log file from list of files.

The DB attaches and creates a new empty log file. After you check everything is all right, you can delete the renamed log file.

You probably ought not use this for production databases.

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

I fixed this error on my RDS instance by rebooting it from the AWS management console. HTH

[edit: lol downvotes]

format a Date column in a Data Frame

The data.table package has its IDate class and functionalities similar to lubridate or the zoo package. You could do:

dt = data.table(
  Name = c('Joe', 'Amy', 'John'),
  JoiningDate = c('12/31/09', '10/28/09', '05/06/10'),
  AmtPaid = c(1000, 100, 200)

dt[ , JoiningDate := as.IDate(JoiningDate, '%m/%d/%y') ]

How do I run a batch script from within a batch script?

Here is example:

You have a.bat:

@echo off
if exist b.bat goto RUNB
goto END

and b.bat called conditionally from a.bat:

@echo off 
echo "This is b.bat"

C++ correct way to return pointer to array from function

Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.

In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.

You can define a pointer to an array, for example this:

double (*p)[42];

defines p as a pointer to a 42-element array of doubles. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.

A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator [] to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.

If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.

Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.

But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector> and <array>, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.

EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.

Observable.of is not a function

Patching wasn't working for me, for whatever reason, so I had to resort to this method:

import { of } from 'rxjs/observable/of'

// ...

return of(res)

python inserting variable string as file name

Even better are f-strings in python 3!

f = open(f'{name}.csv', 'wb')

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

What I did was creating my own Window and Style. Because I like to have control over everything and I didn't want some external libraries just to use a Window from it. I looked at already mentioned MahApps.Metro on GitHub


and also very nice Modern UI on GitHub. (.NET4.5 only)

Modern UI

There is one more it's Elysium but I really didn't try this one.


The style I did was really easy when I looked how it's done in these. Now I have my own Window and I can do whatever I want with xaml... for me it's the main reason why I did my own. And I made one more for you too :) I should probably say that I wouldn't be able to do it without exploring Modern UI it was great help. I tried to make it look like VS2012 Window. It looks like this.


Here is code (please note that it's targeting .NET4.5)

public class MyWindow : Window

    public MyWindow()
        this.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, this.OnCloseWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, this.OnMaximizeWindow, this.OnCanResizeWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, this.OnMinimizeWindow, this.OnCanMinimizeWindow));
        this.CommandBindings.Add(new CommandBinding(SystemCommands.RestoreWindowCommand, this.OnRestoreWindow, this.OnCanResizeWindow));

    private void OnCanResizeWindow(object sender, CanExecuteRoutedEventArgs e)
        e.CanExecute = this.ResizeMode == ResizeMode.CanResize || this.ResizeMode == ResizeMode.CanResizeWithGrip;

    private void OnCanMinimizeWindow(object sender, CanExecuteRoutedEventArgs e)
        e.CanExecute = this.ResizeMode != ResizeMode.NoResize;

    private void OnCloseWindow(object target, ExecutedRoutedEventArgs e)

    private void OnMaximizeWindow(object target, ExecutedRoutedEventArgs e)

    private void OnMinimizeWindow(object target, ExecutedRoutedEventArgs e)

    private void OnRestoreWindow(object target, ExecutedRoutedEventArgs e)

And here resources:

<BooleanToVisibilityConverter x:Key="bool2VisibilityConverter" />

<Color x:Key="WindowBackgroundColor">#FF2D2D30</Color>
<Color x:Key="HighlightColor">#FF3F3F41</Color>
<Color x:Key="BlueColor">#FF007ACC</Color>
<Color x:Key="ForegroundColor">#FFF4F4F5</Color>

<SolidColorBrush x:Key="WindowBackgroundColorBrush" Color="{StaticResource WindowBackgroundColor}"/>
<SolidColorBrush x:Key="HighlightColorBrush" Color="{StaticResource HighlightColor}"/>
<SolidColorBrush x:Key="BlueColorBrush" Color="{StaticResource BlueColor}"/>
<SolidColorBrush x:Key="ForegroundColorBrush" Color="{StaticResource ForegroundColor}"/>

<Style x:Key="WindowButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
    <Setter Property="Background" Value="Transparent" />
    <Setter Property="HorizontalContentAlignment" Value="Center" />
    <Setter Property="VerticalContentAlignment" Value="Center" />
    <Setter Property="Padding" Value="1" />
    <Setter Property="Template">
            <ControlTemplate TargetType="{x:Type Button}">
                <Grid Background="{TemplateBinding Background}">
                    <ContentPresenter x:Name="contentPresenter"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                          Margin="{TemplateBinding Padding}"
                          RecognizesAccessKey="True" />
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="{StaticResource HighlightColorBrush}" />
                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="{DynamicResource BlueColorBrush}" />
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter TargetName="contentPresenter" Property="Opacity" Value=".5" />

<Style x:Key="MyWindowStyle" TargetType="local:MyWindow">
    <Setter Property="Foreground" Value="{DynamicResource ForegroundColorBrush}" />
    <Setter Property="Background" Value="{DynamicResource WindowBackgroundBrush}"/>
    <Setter Property="ResizeMode" Value="CanResizeWithGrip" />
    <Setter Property="UseLayoutRounding" Value="True" />
    <Setter Property="TextOptions.TextFormattingMode" Value="Display" />
    <Setter Property="Template">
            <ControlTemplate TargetType="local:MyWindow">
                <Border x:Name="WindowBorder" Margin="{Binding Source={x:Static SystemParameters.WindowNonClientFrameThickness}}" Background="{StaticResource WindowBackgroundColorBrush}">
                        <Border BorderThickness="1">
                                <Grid x:Name="LayoutRoot">
                                        <RowDefinition Height="25" />
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="15" />
                                    <ContentPresenter Grid.Row="1" Grid.RowSpan="2" Margin="7"/>
                                    <Rectangle x:Name="HeaderBackground" Height="25" Fill="{DynamicResource WindowBackgroundColorBrush}" VerticalAlignment="Top" Grid.Row="0"/>
                                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" WindowChrome.IsHitTestVisibleInChrome="True" Grid.Row="0">
                                        <Button Command="{Binding Source={x:Static SystemCommands.MinimizeWindowCommand}}" ToolTip="minimize" Style="{StaticResource WindowButtonStyle}">
                                                <Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
                                                    <Path Data="M0,6 L8,6 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                        Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2"  />
                                        <Grid Margin="1,0,1,0">
                                            <Button x:Name="Restore" Command="{Binding Source={x:Static SystemCommands.RestoreWindowCommand}}" ToolTip="restore" Visibility="Collapsed" Style="{StaticResource WindowButtonStyle}">
                                                    <Grid Width="30" Height="25" UseLayoutRounding="True" RenderTransform="1,0,0,1,.5,.5">
                                                        <Path Data="M2,0 L8,0 L8,6 M0,3 L6,3 M0,2 L6,2 L6,8 L0,8 Z" Width="8" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                            Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1"  />
                                            <Button x:Name="Maximize" Command="{Binding Source={x:Static SystemCommands.MaximizeWindowCommand}}" ToolTip="maximize" Style="{StaticResource WindowButtonStyle}">
                                                    <Grid Width="31" Height="25">
                                                        <Path Data="M0,1 L9,1 L9,8 L0,8 Z" Width="9" Height="8" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                            Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="2"  />
                                        <Button Command="{Binding Source={x:Static SystemCommands.CloseWindowCommand}}" ToolTip="close"  Style="{StaticResource WindowButtonStyle}">
                                                <Grid Width="30" Height="25" RenderTransform="1,0,0,1,0,1">
                                                    <Path Data="M0,0 L8,7 M8,0 L0,7 Z" Width="8" Height="7" VerticalAlignment="Center" HorizontalAlignment="Center"
                                                        Stroke="{Binding Foreground, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" StrokeThickness="1.5"  />
                                    <TextBlock x:Name="WindowTitleTextBlock" Grid.Row="0" Text="{TemplateBinding Title}" HorizontalAlignment="Left" TextTrimming="CharacterEllipsis" VerticalAlignment="Center"  Margin="8 -1 0 0"  FontSize="16"  Foreground="{TemplateBinding Foreground}"/>
                                    <Grid Grid.Row="2">
                                        <Path x:Name="ResizeGrip" Visibility="Collapsed" Width="12" Height="12" Margin="1" HorizontalAlignment="Right"
                                        Stroke="{StaticResource BlueColorBrush}" StrokeThickness="1" Stretch="None" Data="F1 M1,10 L3,10 M5,10 L7,10 M9,10 L11,10 M2,9 L2,11 M6,9 L6,11 M10,9 L10,11 M5,6 L7,6 M9,6 L11,6 M6,5 L6,7 M10,5 L10,7 M9,2 L11,2 M10,1 L10,3" />
                        <Border BorderBrush="{StaticResource BlueColorBrush}" BorderThickness="1" Visibility="{Binding IsActive, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource bool2VisibilityConverter}}" />
                    <Trigger Property="WindowState" Value="Maximized">
                        <Setter TargetName="Maximize" Property="Visibility" Value="Collapsed" />
                        <Setter TargetName="Restore" Property="Visibility" Value="Visible" />
                        <Setter TargetName="LayoutRoot" Property="Margin" Value="7" />
                    <Trigger Property="WindowState" Value="Normal">
                        <Setter TargetName="Maximize" Property="Visibility" Value="Visible" />
                        <Setter TargetName="Restore" Property="Visibility" Value="Collapsed" />
                            <Condition Property="ResizeMode" Value="CanResizeWithGrip" />
                            <Condition Property="WindowState" Value="Normal" />
                        <Setter TargetName="ResizeGrip" Property="Visibility" Value="Visible" />
    <Setter Property="WindowChrome.WindowChrome">
            <WindowChrome CornerRadius="0" GlassFrameThickness="1" UseAeroCaptionButtons="False" />

Python ImportError: No module named wx

If you do not have wx installed on windows you can use :

 pip install wx

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

I had the same problem, by accident mistake. I'll share it here, in case someone may have made the same mistake.

Basic steps, as others described.

  1. Download putty and puttygen, or the putty package and install it.
  2. Get the .pem file from your AWS EC2 instance.
  3. Use puttygen to convert the .pem file so that you'll have a private key --- mistake happened here. I chose "Conversions" tab from PuttyGen, and load my .pem file. After loading pem file, here DO NOT hit "Generate", instead directly "Save private key". That's the key you need. If you click Generate, you'll have a totally different pair of keys.
  4. In putty, use [email protected], and load the private key at SSH/Auth

Good luck!

SSH SCP Local file to Remote in Terminal Mac Os X

Watch that your file name doesn't have : in them either. I found that I had to mv blah-07-08-17-02:69.txt no_colons.txt and then scp no-colons.txt server: then don't forget to mv back on the server. Just in case this was an issue.

how to get list of port which are in use on the server

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.

Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

According to this thread in MSDN forums: VS2012 RC installation breaks VS2010 C++ projects, simply, take cvtres.exe from VS2010 SP1

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe

or from VS2012

C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\bin\cvtres.exe

and copy it over the cvtres.exe in VS2010 RTM installation (the one without SP1)

C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe

This way, you will effectively use the corrected version of cvtres.exe which is 11.0.51106.1.

Repeat the same steps for 64-bit version of the tool in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64\cvtres.exe.

This solution is an alternative to installation of SP1 for VS2010 - in some cases you simply can't install SP1 (i.e. if you need to support pre-SP1 builds).

How to disable text selection using jQuery?

Here's a more comprehensive solution to the disconnect selection, and the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)


  $.fn.ctrlCmd = function(key) {

    var allowDefault = true;

    if (!$.isArray(key)) {
       key = [key];

    return this.keydown(function(e) {
        for (var i = 0, l = key.length; i < l; i++) {
            if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
                allowDefault = false;
        return allowDefault;

$.fn.disableSelection = function() {

    this.ctrlCmd(['a', 'c']);

    return this.attr('unselectable', 'on')
               .bind('selectstart', false);


and call example:


This could be also not enough for old versions of FireFox (I can't tell which). If all this does not work, add the following:

.on('mousedown', false)

Timing a command's execution in PowerShell


Measure-Command { .\do_something.ps1 }

Note that one minor downside of Measure-Command is that you see no stdout output.

[Update, thanks to @JasonMArcher] You can fix that by piping the command output to some commandlet that writes to the host, e.g. Out-Default so it becomes:

Measure-Command { .\do_something.ps1 | Out-Default }

Another way to see the output would be to use the .NET Stopwatch class like this:

$sw = [Diagnostics.Stopwatch]::StartNew()

Set bootstrap modal body height by percentage

This worked for me

.modal-content {
    /* 80% of window height */
    height: 80%;

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;


Mongoose.js: Find user by username LIKE value

This is what I'm using.

module.exports.getBookByName = function(name,callback){
    var query = {
            name: {$regex : name}

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Port 80 is being used by SYSTEM (PID 4), what is that?

This Process works for me:

  1. Right click on My Computer.
  2. Select Manage.
  3. Double click Services and Applications.
  4. Then double-click Services.
  5. Right click on "World Wide Web Publishing Service".
  6. Select Stop
  7. Restart XAMPP

Using with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(, space, txt);

Example gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

  onClick={ this.props.onClick } 

onClick(e) {


JavaScript: SyntaxError: missing ) after argument list

You got an extra } to many as seen below:

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
        } // <-- REMOVE THIS :)
    }, false);

A very good tool for those things is jsFiddle. I have created a fiddle with your invalid code and when clicking the TidyUp button it formats your code which makes it clearer if there are any possible mistakes with missing braces.

DEMO - Your code in a fiddle, have a play :)

Unable to open a file with fopen()

Try using an absolute path for the filename. And if you are using Windows, use getlasterror() to see the actual error message.

retrieve links from web page using python and BeautifulSoup

There can be many duplicate links together with both external and internal links. To differentiate between the two and just get unique links using sets:

# Python 3.
import urllib    
from bs4 import BeautifulSoup

url = ""
resp = urllib.request.urlopen(url)
# Get server encoding per recommendation of Martijn Pieters.
soup = BeautifulSoup(resp,'charset'))  
external_links = set()
internal_links = set()
for line in soup.find_all('a'):
    link = line.get('href')
    if not link:
    if link.startswith('http'):

# Depending on usage, full internal links may be preferred.
full_internal_links = {
    urllib.parse.urljoin(url, internal_link) 
    for internal_link in internal_links

# Print all unique external and full internal links.
for link in external_links.union(full_internal_links):

Python: How to keep repeating a program until a specific input is obtained?

There are two ways to do this. First is like this:

while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

The second is like this:

inp = raw_input()       # Get the input
while inp != "":        # Loop until it is a blank line
    inp = raw_input()   # Get the input again

Note that if you are on Python 3.x, you will need to replace raw_input with input.

Get all files that have been modified in git branch

For some reason no one mentioned git-tree. See

git-tree is preferred because it's a plumbing command; meant to be programmatic (and, presumably, faster)

(assuming base branch is master)

git diff-tree --no-commit-id --name-only -r master..branch-name

However this will show you all files which were affected in the branch, if you want to see explicitly modified files only, you can use --diff-filter:

git diff-tree --no-commit-id --name-only -r master..branch-name --diff-filter=M

Also one can use --name-status instead of --name-only to see the status of the files (A/M/D and so on)

export html table to csv

Used the answer above, but altered it for my needs.

I used the following function and imported to my REACT file where I needed to download the csv file.

I had a span tag within my th elements. Added comments to what most functions/methods do.

import { tableToCSV, downloadCSV } from './../Helpers/exportToCSV';

export function tableToCSV(){
  let tableHeaders = Array.from(document.querySelectorAll('th'))
    .map(item => {
      // title = splits elem tags on '\n',
      // then filter out blank "" that appears in array.
      // ex ["Timestamp", "[Full time]", ""]
      let title = item.innerText.split("\n").filter(str => (str !== 0)).join(" ")
      return title

  const rows = Array.from(document.querySelectorAll('tr'))
  .reduce((arr, currRow) => {
    // if tr tag contains th tag.
    // if null return array.
    if (currRow.querySelector('th')) return arr

    // concats individual cells into csv format row.
    const cells = Array.from(currRow.querySelectorAll('td'))
      .map(item => item.innerText)
    return arr.concat([cells])
  }, [])

return tableHeaders + '\n' + rows.join('\n')

export function downloadCSV(csv){
  const csvFile = new Blob([csv], { type: 'text/csv' })
  const downloadLink =  document.createElement('a')
  // sets the name for the download file = `CSV-${currentDateUSWritten()}.csv`
  // sets the url to the window URL created from csv file above
  downloadLink.href = window.URL.createObjectURL(csvFile)
  // creates link, but does not display it. = 'none'
  // add link to body so click function below works

When user click export to csv it trigger the following function in react.

  handleExport = (e) => {
    const csv = tableToCSV()
    return downloadCSV(csv)

Example html table elems.

  <table id="datatable">
          <tr id="tableHeader" className="t-header">
              <span className="block">full time</span></th>
            <th>current rate
              <span className="block">alt view</span>
            <th>Battery Voltage
              <span className="block">current voltage
            <th>Temperature 1
              <span className="block">[C]</span>
            <th>Temperature 2
              <span className="block">[C]</span>
            <th>Time & Date </th>


how to display none through code behind

I believe this should work:


get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and, that reference the services you might use in a controller.

How to enable assembly bind failure logging (Fusion) in .NET

For those who are a bit lazy, I recommend running this as a bat file for when ever you want to enable it:

reg add "HKLM\Software\Microsoft\Fusion" /v EnableLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v ForceLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogFailures /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogResourceBinds /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogPath /t REG_SZ /d C:\FusionLog\

if not exist "C:\FusionLog\" mkdir C:\FusionLog

How do you tell if a string contains another string in POSIX sh?

#!/usr/bin/env sh

# Searches a subset string in a string:
# 1st arg:reference string
# 2nd arg:subset string to be matched

if echo "$1" | grep -q "$2"
    echo "$2 is in $1"
    echo "$2 is not in $1"

ssl.SSLError: tlsv1 alert protocol version

I believe TLSV1_ALERT_PROTOCOL_VERSION is alerting you that the server doesn't want to talk TLS v1.0 to you. Try to specify TLS v1.2 only by sticking in these lines:

import ssl
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)

# Create HTTPS connection
c = HTTPSConnection("", context=context)

Note, you may need sufficiently new versions of Python (2.7.9+ perhaps?) and possibly OpenSSL (I have "OpenSSL 1.0.2k 26 Jan 2017" and the above seems to work, YMMV)

How do I wrap text in a span?

I've got a solution that should work in IE6 (and definitely works in 7+ & FireFox/Chrome).
You were on the right track using a span, but the use of a ul was wrong and the css wasn't right.

Try this

<a class="htooltip" href="#">

        Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci.
.htooltip, .htooltip:visited, .tooltip:active {
    color: #0077AA;
    text-decoration: none;

.htooltip:hover {
    color: #0099CC;

.htooltip span {
    display : none;
    position: absolute;
    background-color: black;
    color: #fff;
    padding: 5px 10px 5px 40px;
    text-decoration: none;
    width: 350px;
    z-index: 10;

.htooltip:hover span {
    display: block;

Everyone was going about this the wrong way. The code isn't valid, ul's cant go in a's, p's can't go in a's, div's cant go in a's, just use a span (remembering to make it display as a block so it will wrap as if it were a div/p etc).

OSError: [WinError 193] %1 is not a valid Win32 application

Uninstalling numpy from command line / terminal through pip fixed the error for me:

pip uninstall numpy

how to programmatically fake a touch event to a UIButton?

If you want to do this kind of testing, you’ll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.

Can I restore a single table from a full mysql mysqldump file?

Back in '08 I had a need to do this too. I wrote a Perl script that'll do it, and it's now my method of choice. Also summarized how to do it in awk or how to restore elsewhere and extract. Recently I added this sed method to the list as well. You can find the script and the other methods here:

Redis connection to failed - connect ECONNREFUSED

I'm on windows, and had to install Redis from here and then run redis-server.exe.

From the top of this SO question.

How to set character limit on the_content() and the_excerpt() in wordpress

For Using the_content() functions (for displaying the main content of the page)

$content = get_the_content();

echo substr($content, 0, 100);

For Using the_excerpt() functions (for displaying the excerpt-short content of the page)

$excerpt= get_the_excerpt();

echo substr($excerpt, 0, 100);

How do I get to IIS Manager?

First of all, you need to check that the IIS is installed in your machine, for that you can go to:

Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'

If not, check it, and Press Accept to install it.

Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).

Edit: You should have something like this: enter image description here

Unit tests vs Functional tests

Unit testing is usually done by developers. The objective of doing the same is to make sure their code works properly. General rule of thumb is to cover all the paths in code using unit testing.

Functional Testing: This is a good reference. Functional Testing Explanation

SVN checkout the contents of a folder, not the folder itself

Just add a . to it:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

That means: check out to current directory.

Selenium Webdriver move mouse to Point

IMHO you should pay your attention to Robot.class

Still if you want to move the mouse pointer physically, you need to take different approach using Robot class

  Point coordinates = driver.findElement("ctl00_portalmaster_txtUserName")).getLocation();
  Robot robot = new Robot();

Webdriver provide document coordinates, where as Robot class is based on Screen coordinates, so I have added +120 to compensate the browser header.
Screen Coordinates: These are coordinates measured from the top left corner of the user's computer screen. You'd rarely get coordinates (0,0) because that is usually outside the browser window. About the only time you'd want these coordinates is if you want to position a newly created browser window at the point where the user clicked. In all browsers these are in event.screenX and event.screenY.
Window Coordinates: These are coordinates measured from the top left corner of the browser's content area. If the window is scrolled, vertically or horizontally, this will be different from the top left corner of the document. This is rarely what you want. In all browsers these are in event.clientX and event.clientY.
Document Coordinates: These are coordinates measured from the top left corner of the HTML Document. These are the coordinates that you most frequently want, since that is the coordinate system in which the document is defined.

More details you can get here

Hope this be helpful to you.

What exactly does stringstream do?

Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream is similar to the usage of iostream, so it is not a burden to learn.

Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.

The basic member functions of stringstream class are

  • str(), which returns the contents of its buffer in string type.

  • str(string), which set the contents of the buffer to the string argument.

Here is an example of how to use string streams.

ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;

The result is dec: 15 hex: f.

istringstream is of more or less the same usage.

To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.

FYI, the inheritance relationships between the classes are:

string stream classes

This action could not be completed. Try Again (-22421)

When above problem exists and you have Two Factor Authentication enabled, just do the following:

  1. go to and then create your App-Specific Password

enter image description here

  1. Inside Application Loader login with your apple id and App Specific Password you just created.

  2. Upload your ipa to itunesconnect.

Should I use 'has_key()' or 'in' on Python dicts?

Expanding on Alex Martelli's performance tests with Adam Parkin's comments...

$ python3.5 -mtimeit -s'd=dict.fromkeys(range( 99))' 'd.has_key(12)'
Traceback (most recent call last):
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/", line 301, in main
    x = t.timeit(number)
  File "/usr/local/Cellar/python3/3.5.2_3/Frameworks/Python.framework/Versions/3.5/lib/python3.5/", line 178, in timeit
    timing = self.inner(it, self.timer)
  File "<timeit-src>", line 6, in inner
AttributeError: 'dict' object has no attribute 'has_key'

$ python2.7 -mtimeit -s'd=dict.fromkeys(range(  99))' 'd.has_key(12)'
10000000 loops, best of 3: 0.0872 usec per loop

$ python2.7 -mtimeit -s'd=dict.fromkeys(range(1999))' 'd.has_key(12)'
10000000 loops, best of 3: 0.0858 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(  99))' '12 in d'
10000000 loops, best of 3: 0.031 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d'
10000000 loops, best of 3: 0.033 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(  99))' '12 in d.keys()'
10000000 loops, best of 3: 0.115 usec per loop

$ python3.5 -mtimeit -s'd=dict.fromkeys(range(1999))' '12 in d.keys()'
10000000 loops, best of 3: 0.117 usec per loop

Manually type in a value in a "Select" / Drop-down HTML list?

ExtJS has a ComboBox control that can do this (and a whole host of other cool stuff!!)

EDIT: Browse all controls etc, here:

java.lang.ClassNotFoundException on working app

Had this sort of problem today after upgrading to latest ADT/SDK. Took me quite a while. Checked that i used google-apis (for maps), uses-library, cleaned the project etc.

Deleting the .project and adding a fresh one (create new android project) finally solved it.

Difference between Git and GitHub

In simple:

Git - is local repository.

GitHub - is central repository.

Hope below image will help to understand: Git and GitHub Difference

Git and GitHub Difference more details

How to reject in async/await syntax?

Your best bet is to throw an Error wrapping the value, which results in a rejected promise with an Error wrapping the value:

} catch (error) {
    throw new Error(400);

You can also just throw the value, but then there's no stack trace information:

} catch (error) {
    throw 400;

Alternately, return a rejected promise with an Error wrapping the value, but it's not idiomatic:

} catch (error) {
    return Promise.reject(new Error(400));

(Or just return Promise.reject(400);, but again, then there's no context information.)

In your case, as you're using TypeScript and foo's return value is Promise<A>, you'd use this:

return Promise.reject<A>(400 /*or Error*/ );

In an async/await situation, that last is probably a bit of a semantic mis-match, but it does work.

If you throw an Error, that plays well with anything consuming your foo's result with await syntax:

try {
    await foo();
} catch (error) {
    // Here, `error` would be an `Error` (with stack trace, etc.).
    // Whereas if you used `throw 400`, it would just be `400`.

Returning JSON object from an ASP.NET page

no problem doing it with asp.... it's most natural to do so with MVC, but can be done with standard asp as well.

The MVC framework has all sorts of helper classes for JSON, if you can, I'd suggest sussing in some MVC-love, if not, you can probably easily just get the JSON helper classes used by MVC in and use them in the context of


here's an example of how to return JSON data with MVC. This would be in your controller class. This is out of the box functionality with MVC--when you crate a new MVC project this stuff gets auto-created so it's nothing special. The only thing that I"m doing is returning an actionResult that is JSON. The JSON method I'm calling is a method on the Controller class. This is all very basic, default MVC stuff:

public ActionResult GetData()
    var data = new { Name="kevin", Age=40 };
    return Json(data, JsonRequestBehavior.AllowGet);

This return data could be called via JQuery as an ajax call thusly:

$.get("/Reader/GetData/", function(data) { someJavacriptMethodOnData(data); });

How to add a linked source folder in Android Studio?

The right answer is:

android {

    sourceSets { += 'src/main/<YOUR DIRECTORY>'

Furthermore, if your external source directory is not under src/main, you could use a relative path like this:

sourceSets { += 'src/main/../../../<YOUR DIRECTORY>'

Converting user input string to regular expression

Thanks to earlier answers, this blocks serves well as a general purpose solution for applying a configurable string into a RegEx .. for filtering text:

var permittedChars = '^a-z0-9 _,.?!@+<>';
permittedChars = '[' + permittedChars + ']';

var flags = 'gi';
var strFilterRegEx = new RegExp(permittedChars, flags);

log.debug ('strFilterRegEx: ' + strFilterRegEx);

strVal = strVal.replace(strFilterRegEx, '');
// this replaces hard code solt:
// strVal = strVal.replace(/[^a-z0-9 _,.?!@+]/ig, '');

When creating a service with sc.exe how to pass in context parameters?

I had issues getting this to work on Windows 7. It seemed to ignore the first argument I passed in so I used binPath= "C:\path\to\service.exe -bogusarg -realarg1 -realarg2" and it worked.

Cursor adapter and sqlite example

Really simple example.

Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.

There are two main parts to using a Cursor Adapter with SQLite:

  1. Create a proper Cursor from the Database.

  2. Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.

1. Create a proper Cursor from the Database.

In your Activity:

SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper( 
        context, DATABASE_NAME, null, DATABASE_VERSION);

SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();

String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'

Cursor cursor = sqLiteDatabase.rawQuery(query, null); 

ClientCursorAdapter adapter = new ClientCursorAdapter(
        this, R.layout.clients_listview_row, cursor, 0 );


2. Create a Custom Cursor Adapter.

Note: Extending from ResourceCursorAdapter assumes you use XML to create your views.

public class ClientCursorAdapter extends ResourceCursorAdapter {

    public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
        super(context, layout, cursor, flags);

    public void bindView(View view, Context context, Cursor cursor) {
        TextView name = (TextView) view.findViewById(;

        TextView phone = (TextView) view.findViewById(;

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

Go to "Window -> Preferences -> General -> C/C++ -> Code analysis" and disable "Syntax and Semantics Errors -> Abstract class cannot be instantiated"

How do I sum values in a column that match a given condition using pandas?

You can also do this without using groupby or loc. By simply including the condition in code. Let the name of dataframe be df. Then you can try :


or you can also try :


Another way could be to use the numpy library of python :

import numpy as np
print(np.where(df['a']==1, df['b'],0).sum())

Difference between map and collect in Ruby?

I've been told they are the same.

Actually they are documented in the same place under

  • ary.collect {|item| block } ? new_ary
  • {|item| block } ? new_ary
  • ary.collect ? an_enumerator
  • ? an_enumerator

Invokes block once for each element of self. Creates a new array containing the values returned by the block. See also Enumerable#collect.
If no block is given, an enumerator is returned instead.

a = [ "a", "b", "c", "d" ]
a.collect {|x| x + "!" }   #=> ["a!", "b!", "c!", "d!"]
a                          #=> ["a", "b", "c", "d"]

Docker: Multiple Dockerfiles in project

Add an abstraction layer, for example, a YAML file like in this project which looks like

    base: centos:centos7
    packager: rpm
      - $build_essential_centos 
      - rpm-build
      - $get_release
      - $environment_vars

A short Python script/make can generate all Dockerfiles from the configuration file.

How to add percent sign to NSString

The code for percent sign in NSString format is %%. This is also true for NSLog() and printf() formats.

error: use of deleted function

Switching from gcc 4.6 to gcc 4.8 resolved this for me.

How does String substring work in Swift

I'm quite mechanical thinking. Here are the basics...

Swift 4 Swift 5

  let t = "abracadabra"

  let start1 = t.index(t.startIndex, offsetBy:0)
  let   end1 = t.index(t.endIndex, offsetBy:-5)
  let start2 = t.index(t.endIndex, offsetBy:-5)
  let   end2 = t.index(t.endIndex, offsetBy:0)

  let t2 = t[start1 ..< end1]
  let t3 = t[start2 ..< end2]                

  //or a shorter form 

  let t4 = t[..<end1]
  let t5 = t[start2...]

  print("\(t2) \(t3) \(t)")
  print("\(t4) \(t5) \(t)")

  // result:
  // abraca dabra abracadabra

The result is a substring, meaning that it is a part of the original string. To get a full blown separate string just use e.g.


This is what I use:

    let mid = t.index(t.endIndex, offsetBy:-5)
    let firstHalf = t[..<mid]
    let secondHalf = t[mid...]

Could not load file or assembly "System.Net.Http, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

How to set page content to the middle of screen?


<!DOCTYPE html>
        <div id="main_body">
          some text


   width: 100%;
   Height: 100%;
    background: #ff3333;
    width: 200px;
    position: absolute;

JS ( jQuery )

    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

Why not use Double or Float to represent currency?

To add on previous answers, there is also option of implementing Joda-Money in Java, besides BigDecimal, when dealing with the problem addressed in the question. Java modul name is

It requires Java SE 8 or later and has no dependencies.

To be more precise, there is compile-time dependency but it is not required.


Examples of using Joda Money:

  // create a monetary value
  Money money = Money.parse("USD 23.87");

  // add another amount with safe double conversion
  CurrencyUnit usd = CurrencyUnit.of("USD");
  money =, 12.43d));

  // subtracts an amount in dollars
  money = money.minusMajor(2);

  // multiplies by 3.5 with rounding
  money = money.multipliedBy(3.5d, RoundingMode.DOWN);

  // compare two amounts
  boolean bigAmount = money.isGreaterThan(dailyWage);

  // convert to GBP using a supplied rate
  BigDecimal conversionRate = ...;  // obtained from code outside Joda-Money
  Money moneyGBP = money.convertedTo(CurrencyUnit.GBP, conversionRate, RoundingMode.HALF_UP);

  // use a BigMoney for more complex calculations where scale matters
  BigMoney moneyCalc = money.toBigMoney();


Implementation examples:

Found shared references to a collection org.hibernate.HibernateException

Explanation on practice. If you try to save your object, e.g.:

Set<Folder> folders = message.getFolders();

you don't need to set updated object to a parent object:


Simple save your parent object like:

Set<Folder> folders = message.getFolders();
   // Not set updated object here

Hibernate Delete query

The reason is that for deleting an object, Hibernate requires that the object is in persistent state. Thus, Hibernate first fetches the object (SELECT) and then removes it (DELETE).

Why Hibernate needs to fetch the object first? The reason is that Hibernate interceptors might be enabled (, and the object must be passed through these interceptors to complete its lifecycle. If rows are delete directly in the database, the interceptor won't run.

On the other hand, it's possible to delete entities in one single SQL DELETE statement using bulk operations:

Query q = session.createQuery("delete Entity where id = X");

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.


The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.


However, using a token Without SSL is still vulnerable to an attack called 'sidejacking':

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

Output PowerShell variables to a text file

The simple solution is to avoid creating an array before piping to Out-File. Rule #1 of PowerShell is that the comma is a special delimiter, and the default behavior is to create an array. Concatenation is done like this.

$computer + "," + $Speed + "," + $Regcheck | out-file -filepath C:\temp\scripts\pshell\dump.txt -append -width 200

This creates an array of three items.


vs. concatenation of three items separated by commas.

$computer + "," + $Speed + "," + $Regcheck

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

Difference between $(this) and

this is a reference for the DOM element for which the event is being handled (the current target). refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.

You can get a good sense of this by reviewing the jQuery event docs, but in summary:


The current DOM element within the event bubbling phase.


The element where the currently-called jQuery event handler was attached.


The other DOM element involved in the event, if any.

The DOM element that initiated the event.

To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this) or $(

The .attr() method only works on a jQuery object, not on a DOM element. $('href') or simply will give you what you want.

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

With Xiaomi Redmi note 8 pro (MIUI 10.4.4), Android 9 -

While connecting to Vysor (2.1.2) from Windows PC (via USB cable), received the error message:

"Error installing APK: Failure [INSTALL_FAILED_USER_RESTRICTED]"

even after turning "USB Debugging" On.

So the following settings were required -

  • Developer options (On)
  • USB debugging (On)
  • Install via USB (On)

Leave the following,

  • Turn on MIUI optimization (On)
  • Verify apps over USB (On)

Is there a better way to compare dictionary values

If your dictionaries are deeply nested and if they contain different types of collections, you could convert them to json string and compare.

import json
match = (json.dumps(dict1) == json.dumps(dict2))

caveat- this solution may not work if your dictionaries have binary strings in the values as this is not json serializable

How to stash my previous commit?

If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only.

Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following:

git rebase -i HEAD~2

This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example

pick 222 commit to be stashed
pick 111 commit to be pushed to remote

# Rebase 111..222 onto 333
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
# These lines can be re-ordered; they are executed from top to bottom.
# If you remove a line here THAT COMMIT WILL BE LOST.
# However, if you remove everything, the rebase will be aborted.
# Note that empty commits are commented out

Reorder the two commits (they are listed oldest => newest) like this:

pick 111 commit to be pushed to remote
pick 222 commit to be stashed

Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5 which will output newest-first.

At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes:

git reset --soft HEAD~1
git stash

It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.

How to implode array with key and value without foreach in PHP

There is also var_export and print_r more commonly known for printing debug output but both functions can take an optional argument to return a string instead.

Using the example from the question as data.

$array = ["item1"=>"object1", "item2"=>"object2","item-n"=>"object-n"];

Using print_r to turn the array into a string

This will output a human readable representation of the variable.

$string = print_r($array, true);
echo $string;

Will output:

    [item1] => object1
    [item2] => object2
    [item-n] => object-n

Using var_export to turn the array into a string

Which will output a php string representation of the variable.

$string = var_export($array, true);
echo $string;

Will output:

array (
  'item1' => 'object1',
  'item2' => 'object2',
  'item-n' => 'object-n',

Because it is valid php we can evaluate it.

eval('$array2 = ' . var_export($array, true) . ';');
var_dump($array2 === $array);



What is the difference between include and require in Ruby?

  • Ruby require is more like "include" in other languages (such as C). It tells Ruby that you want to bring in the contents of another file. Similar mechanisms in other languages are:

  • Ruby include is an object-oriented inheritance mechanism used for mixins.

There is a good explanation here:

[The] simple answer is that require and include are essentially unrelated.

"require" is similar to the C include, which may cause newbie confusion. (One notable difference is that locals inside the required file "evaporate" when the require is done.)

The Ruby include is nothing like the C include. The include statement "mixes in" a module into a class. It's a limited form of multiple inheritance. An included module literally bestows an "is-a" relationship on the thing including it.

Emphasis added.

Binding select element to object in Angular

In app.component.html:

 <select type="number" [(ngModel)]="selectedLevel">
          <option *ngFor="let level of levels" [ngValue]="level">{{}}</option>

And app.component.ts:

import { Component } from '@angular/core';

  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
export class AppComponent  {
  levels:Array<Object> = [
      {num: 0, name: "AA"},
      {num: 1, name: "BB"}

    this.levelNum = +this.levelNum;

  selectedLevel = this.levels[0];

  selectedLevelCustomCompare = {num: 1, name: "BB"}

  compareFn(a, b) {
    console.log(a, b, a && b && a.num == b.num);
    return a && b && a.num == b.num;

How do you validate a URL with a regular expression in Python? gives regular expressions for consistency with the rules in RFC 3986 and RFC 3987 (that is, not with scheme-specific rules).

A regexp for IRI_reference is:


In one line:


JUnit 4 compare Sets

Using Hamcrest:

assertThat( set1, both(everyItem(isIn(set2))).and(containsInAnyOrder(set1)));

This works also when the sets have different datatypes, and reports on the difference instead of just failing.

Unicode character for "X" cancel / close?

As @Haza pointed out the times symbol can be used. Twitter Bootstrap maps this to a close icon for dismissing content like modals and alerts.

<button class="close">&times;</button>

make an ID in a mysql table auto_increment (after the fact)




But none of these will work if your bar_id is a foreign key in another table: you'll be getting

an error 1068: Multiple primary key defined

To solve this, temporary disable foreign key constraint checks by

set foreign_key_checks = 0;

and after running the statements above, enable them back again.

set foreign_key_checks = 1;

Adding a custom header to HTTP request using angular.js

Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is by design.

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted. It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

Ref: AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Python creating a dictionary of lists

Your question has already been answered, but IIRC you can replace lines like:

if d.has_key(scope_item):


if scope_item in d:

That is, d references d.keys() in that construction. Sometimes defaultdict isn't the best option (for example, if you want to execute multiple lines of code after the else associated with the above if), and I find the in syntax easier to read.

How do you divide each element in a list by an int?

>>> myList = [10,20,30,40,50,60,70,80,90]
>>> myInt = 10
>>> newList = map(lambda x: x/myInt, myList)
>>> newList
[1, 2, 3, 4, 5, 6, 7, 8, 9]

How to iterate through table in Lua?

To iterate over all the key-value pairs in a table you can use pairs:

for k, v in pairs(arr) do
  print(k, v[1], v[2], v[3])


pears   2   p   green
apples  0   a   red
oranges 1   o   orange

Edit: Note that Lua doesn't guarantee any iteration order for the associative part of the table. If you want to access the items in a specific order, retrieve the keys from arr and sort it. Then access arr through the sorted keys:

local ordered_keys = {}

for k in pairs(arr) do
    table.insert(ordered_keys, k)

for i = 1, #ordered_keys do
    local k, v = ordered_keys[i], arr[ ordered_keys[i] ]
    print(k, v[1], v[2], v[3])


  apples  a   red     5
  oranges o   orange  12
  pears   p   green   7