Programs & Examples On #Nonserializedattribute

Get jQuery version from inspecting the jQuery object

You can use either $().jquery; or $.fn.jquery which will return a string containing the version number, e.g. 1.6.2.

Difference between Return and Break statements

Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.

Break

for(int i=0;i<5;i++){
    print(i)
    if(i==2)
    {
      break;
    }
}

output: 0 1

return

for(int i=0;i<5;i++)
{
   print(i)
   if(i==2)
   {
    return;
   }
}

output: 0 1 3 4

REST API using POST instead of GET

If I understand the question correctly, he needs to perform a REST GET action, but wonders if it's OK to send in data via HTTP POST method.

As Scott had nicely laid out in his answer earlier, there are many good reasons to POST input data. IMHO it should be done this way, if quality of solution is the top priority.

A while back we created an REST API to authenticate users, taking username/password and returning an access token. The API is encrypted under TLS, but exposed to public internet. After evaluating different options, we chose HTTP POST for the REST method of "GET access token," because that's the only way to meet security standards.

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

What is the difference between UTF-8 and Unicode?

The existing answers already explain a lot of details, but here's a very short answer with the most direct explanation and example.

Unicode is the standard that maps characters to codepoints.
Each character has a unique codepoint (identification number), which is a number like 9731.

UTF-8 is an the encoding of the codepoints.
In order to store all characters on disk (in a file), UTF-8 splits characters into up to 4 octets (8-bit sequences) - bytes. UTF-8 is one of several encodings (methods of representing data). For example, in Unicode, the (decimal) codepoint 9731 represents a snowman (?), which consists of 3 bytes in UTF-8: E2 98 83

Here's a sorted list with some random examples.

Check whether a value exists in JSON object

Check for a value single level

const hasValue = Object.values(json).includes("bar");

Check for a value multi-level

function hasValueDeep(json, findValue) {
    const values = Object.values(json);
    let hasValue = values.includes(findValue);
    values.forEach(function(value) {
        if (typeof value === "object") {
            hasValue = hasValue || hasValueDeep(value, findValue);
        }
    })
    return hasValue;
}

Refresh image with a new one at the same url

Heavily based on Doin's #4 code, the below example simplifies that code a great bit utilising document.write instead of src in the iframe to support CORS. Also only focuses on busting the browser cache, not reloading every image on the page.

Below is written in typescript and uses the angular $q promise library, just fyi, but should be easy enough to port to vanilla javascript. Method is meant to live inside a typescript class.

Returns a promise that will be resolved when the iframe has completed reloading. Not heavily tested, but works well for us.

    mmForceImgReload(src: string): ng.IPromise<void> {
        var deferred = $q.defer<void>();
        var iframe = window.document.createElement("iframe");

        var firstLoad = true;
        var loadCallback = (e) => {
            if (firstLoad) {
                firstLoad = false;
                iframe.contentWindow.location.reload(true);
            } else {
                if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
                deferred.resolve();
            }
        }
        iframe.style.display = "none";
        window.parent.document.body.appendChild(iframe);
        iframe.addEventListener("load", loadCallback, false);
        iframe.addEventListener("error", loadCallback, false);
        var doc = iframe.contentWindow.document;
        doc.open();
        doc.write('<html><head><title></title></head><body><img src="' + src + '"></body></html>');
        doc.close();
        return deferred.promise;
    }

Save a subplot in matplotlib

Applying the full_extent() function in an answer by @Joe 3 years later from here, you can get exactly what the OP was looking for. Alternatively, you can use Axes.get_tightbbox() which gives a little tighter bounding box

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
from matplotlib.transforms import Bbox

def full_extent(ax, pad=0.0):
    """Get the full extent of an axes, including axes labels, tick labels, and
    titles."""
    # For text objects, we need to draw the figure first, otherwise the extents
    # are undefined.
    ax.figure.canvas.draw()
    items = ax.get_xticklabels() + ax.get_yticklabels() 
#    items += [ax, ax.title, ax.xaxis.label, ax.yaxis.label]
    items += [ax, ax.title]
    bbox = Bbox.union([item.get_window_extent() for item in items])

    return bbox.expanded(1.0 + pad, 1.0 + pad)

# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')

# Save the full figure...
fig.savefig('full_figure.png')

# Save just the portion _inside_ the second axis's boundaries
extent = full_extent(ax2).transformed(fig.dpi_scale_trans.inverted())
# Alternatively,
# extent = ax.get_tightbbox(fig.canvas.renderer).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)

I'd post a pic but I lack the reputation points

Read pdf files with php

You might want to also try this application http://pdfbox.apache.org/. A working example can be found at https://www.jinises.com

How do I replace part of a string in PHP?

You need first to cut the string in how many pieces you want. Then replace the part that you want:

 $text = 'this is the test for string.';
 $text = substr($text, 0, 10);
 echo $text = str_replace(" ", "_", $text);

This will output:

this_is_th

Batch file to map a drive when the folder name contains spaces

whenever you deal with spaces in filenames, use quotes

net use "m:\Server01\my folder" /USER:mynetwork\Administrator "Mypassword" /persistent:yes

What is the difference between user variables and system variables?

Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;

How to cache data in a MVC application

You can also try and use the caching built into ASP MVC:

Add the following attribute to the controller method you'd like to cache:

[OutputCache(Duration=10)]

In this case the ActionResult of this will be cached for 10 seconds.

More on this here

ORA-00054: resource busy and acquire with NOWAIT specified

When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.

If you absolutely must, you can kill the OS process as well (look up v$process.spid), which would release any locks it was holding on to.

See this for more detailed info.

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

Style child element when hover on parent

Yes, you can do this use this below code it may help you.

_x000D_
_x000D_
.parentDiv{_x000D_
margin : 25px;_x000D_
_x000D_
}_x000D_
.parentDiv span{_x000D_
  display : block;_x000D_
  padding : 10px;_x000D_
  text-align : center;_x000D_
  border: 5px solid #000;_x000D_
  margin : 5px;_x000D_
}_x000D_
_x000D_
.parentDiv div{_x000D_
padding:30px;_x000D_
border: 10px solid green;_x000D_
display : inline-block;_x000D_
align : cente;_x000D_
}_x000D_
_x000D_
.parentDiv:hover{_x000D_
  cursor: pointer;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv1{_x000D_
border: 10px solid red;_x000D_
}_x000D_
_x000D_
.parentDiv:hover .childDiv2{_x000D_
border: 10px solid yellow;_x000D_
} _x000D_
.parentDiv:hover .childDiv3{_x000D_
border: 10px solid orange;_x000D_
}
_x000D_
<div class="parentDiv">_x000D_
<span>Hover me to change Child Div colors</span>_x000D_
  <div class="childDiv1">_x000D_
    First Div Child_x000D_
  </div>_x000D_
  <div class="childDiv2">_x000D_
    Second Div Child_x000D_
  </div>_x000D_
  <div class="childDiv3">_x000D_
    Third Div Child_x000D_
  </div>_x000D_
  <div class="childDiv4">_x000D_
    Fourth Div Child_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Compute row average in pandas

We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965

df['mean'] = df.iloc[:, 0:4].mean(axis=1)

And if you want to select individual columns

df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)

How can I jump to class/method definition in Atom text editor?

To solve this, you'll need to install only 2 packages. Follow the steps below.

  1. Open atom, go to Packages(top bar) --> Settings View --> Install Packages/Themes.

  2. Type "goto" in the search field and click the packages button on the right.

  3. Install both "goto(1.8.3)" and "goto-definition(1.1.9)", or later versions. Make sure both of them are enabled after download.
  4. If necessary, you can restart atom (for some people).
  5. It should be able to work now. Right-Click on the method/attr/whatever, then select "Goto Definition"

Count how many files in directory PHP

You should have :

<div id="header">
<?php 
    // integer starts at 0 before counting
    $i = 0; 
    $dir = 'uploads/';
    if ($handle = opendir($dir)) {
        while (($file = readdir($handle)) !== false){
            if (!in_array($file, array('.', '..')) && !is_dir($dir.$file)) 
                $i++;
        }
    }
    // prints out how many were in the directory
    echo "There were $i files";
?>
</div>

Array Length in Java

Arrays are allocated memory at compile time in java, so they are static, the elements not explicitly set or modified are set with the default values. You could use some code like this, though it is not recommended as it does not count default values, even if you explicitly initialize them that way, it is also likely to cause bugs down the line. As others said, when looking for the actual size, ".length" must be used instead of ".length()".

public int logicalArrayLength(type[] passedArray) {
    int count = 0;
    for (int i = 0; i < passedArray.length; i++) {
        if (passedArray[i] != defaultValue) {
            count++;
        }
    }
    return count;
}

How do you disable browser Autocomplete on web form field / input tag?

The answer dsuess posted with the readonly was very clever and worked. But as I am using boostrap, the readonly input field was - until focused - marked with grey background. While the document loads, you can trick the browser by simply locking and unlocking the input.

So I had an idea to implement this into jQuery solution:

    jQuery(document).ready(function () {
        $("input").attr('readonly', true);
        $("input").removeAttr('readonly');
   });

Setting the height of a DIV dynamically

Simplest I could come up...

function resizeResizeableHeight() {
    $('.resizableHeight').each( function() {
        $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )
    });
}

Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).

PG::ConnectionBad - could not connect to server: Connection refused

I had to reinstall my postgres, great instructions outlined here: https://medium.com/@zowoodward/effectively-uninstall-and-reinstall-psql-with-homebrew-on-osx-fabbc45c5d9d

Then I had to create postgres user: /usr/local/opt/postgres/bin/createuser -s postgres

This approach will clobber all of your local data so please back up your data if needed.

Python: find position of element in array

Have you thought about using Python list's .index(value) method? It return the index in the list of where the first instance of the value passed in is found.

Better/Faster to Loop through set or list?

For simplicity's sake: newList = list(set(oldList))

But there are better options out there if you'd like to get speed/ordering/optimization instead: http://www.peterbe.com/plog/uniqifiers-benchmark

"Keep Me Logged In" - the best approach

Introduction

Your title “Keep Me Logged In” - the best approach make it difficult for me to know where to start because if you are looking at best approach then you would have to consideration the following :

  • Identification
  • Security

Cookies

Cookies are vulnerable, Between common browser cookie-theft vulnerabilities and cross-site scripting attacks we must accept that cookies are not safe. To help improve security you must note that php setcookies has additional functionality such as

bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

  • secure (Using HTTPS connection)
  • httponly (Reduce identity theft through XSS attack)

Definitions

  • Token ( Unpredictable random string of n length eg. /dev/urandom)
  • Reference ( Unpredictable random string of n length eg. /dev/urandom)
  • Signature (Generate a keyed hash value using the HMAC method)

Simple Approach

A simple solution would be :

  • User is logged on with Remember Me
  • Login Cookie issued with token & Signature
  • When is returning, Signature is checked
  • If Signature is ok .. then username & token is looked up in the database
  • if not valid .. return to login page
  • If valid automatically login

The above case study summarizes all example given on this page but they disadvantages is that

  • There is no way to know if the cookies was stolen
  • Attacker may be access sensitive operations such as change of password or data such as personal and baking information etc.
  • The compromised cookie would still be valid for the cookie life span

Better Solution

A better solution would be

  • User is logged in and remember me is selected
  • Generate Token & signature and store in cookie
  • The tokens are random and are only valid for single autentication
  • The token are replace on each visit to the site
  • When a non-logged user visit the site the signature, token and username are verified
  • Remember me login should have limited access and not allow modification of password, personal information etc.

Example Code

// Set privateKey
// This should be saved securely 
$key = 'fc4d57ed55a78de1a7b31e711866ef5a2848442349f52cd470008f6d30d47282';
$key = pack("H*", $key); // They key is used in binary form

// Am Using Memecahe as Sample Database
$db = new Memcache();
$db->addserver("127.0.0.1");

try {
    // Start Remember Me
    $rememberMe = new RememberMe($key);
    $rememberMe->setDB($db); // set example database

    // Check if remember me is present
    if ($data = $rememberMe->auth()) {
        printf("Returning User %s\n", $data['user']);

        // Limit Acces Level
        // Disable Change of password and private information etc

    } else {
        // Sample user
        $user = "baba";

        // Do normal login
        $rememberMe->remember($user);
        printf("New Account %s\n", $user);
    }
} catch (Exception $e) {
    printf("#Error  %s\n", $e->getMessage());
}

Class Used

class RememberMe {
    private $key = null;
    private $db;

    function __construct($privatekey) {
        $this->key = $privatekey;
    }

    public function setDB($db) {
        $this->db = $db;
    }

    public function auth() {

        // Check if remeber me cookie is present
        if (! isset($_COOKIE["auto"]) || empty($_COOKIE["auto"])) {
            return false;
        }

        // Decode cookie value
        if (! $cookie = @json_decode($_COOKIE["auto"], true)) {
            return false;
        }

        // Check all parameters
        if (! (isset($cookie['user']) || isset($cookie['token']) || isset($cookie['signature']))) {
            return false;
        }

        $var = $cookie['user'] . $cookie['token'];

        // Check Signature
        if (! $this->verify($var, $cookie['signature'])) {
            throw new Exception("Cokies has been tampared with");
        }

        // Check Database
        $info = $this->db->get($cookie['user']);
        if (! $info) {
            return false; // User must have deleted accout
        }

        // Check User Data
        if (! $info = json_decode($info, true)) {
            throw new Exception("User Data corrupted");
        }

        // Verify Token
        if ($info['token'] !== $cookie['token']) {
            throw new Exception("System Hijacked or User use another browser");
        }

        /**
         * Important
         * To make sure the cookie is always change
         * reset the Token information
         */

        $this->remember($info['user']);
        return $info;
    }

    public function remember($user) {
        $cookie = [
                "user" => $user,
                "token" => $this->getRand(64),
                "signature" => null
        ];
        $cookie['signature'] = $this->hash($cookie['user'] . $cookie['token']);
        $encoded = json_encode($cookie);

        // Add User to database
        $this->db->set($user, $encoded);

        /**
         * Set Cookies
         * In production enviroment Use
         * setcookie("auto", $encoded, time() + $expiration, "/~root/",
         * "example.com", 1, 1);
         */
        setcookie("auto", $encoded); // Sample
    }

    public function verify($data, $hash) {
        $rand = substr($hash, 0, 4);
        return $this->hash($data, $rand) === $hash;
    }

    private function hash($value, $rand = null) {
        $rand = $rand === null ? $this->getRand(4) : $rand;
        return $rand . bin2hex(hash_hmac('sha256', $value . $rand, $this->key, true));
    }

    private function getRand($length) {
        switch (true) {
            case function_exists("mcrypt_create_iv") :
                $r = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
                break;
            case function_exists("openssl_random_pseudo_bytes") :
                $r = openssl_random_pseudo_bytes($length);
                break;
            case is_readable('/dev/urandom') : // deceze
                $r = file_get_contents('/dev/urandom', false, null, 0, $length);
                break;
            default :
                $i = 0;
                $r = "";
                while($i ++ < $length) {
                    $r .= chr(mt_rand(0, 255));
                }
                break;
        }
        return substr(bin2hex($r), 0, $length);
    }
}

Testing in Firefox & Chrome

enter image description here

Advantage

  • Better Security
  • Limited access for attacker
  • When cookie is stolen its only valid for single access
  • When next the original user access the site you can automatically detect and notify the user of theft

Disadvantage

  • Does not support persistent connection via multiple browser (Mobile & Web)
  • The cookie can still be stolen because the user only gets the notification after the next login.

Quick Fix

  • Introduction of approval system for each system that must have persistent connection
  • Use multiple cookies for the authentication

Multiple Cookie Approach

When an attacker is about to steal cookies the only focus it on a particular website or domain eg. example.com

But really you can authenticate a user from 2 different domains (example.com & fakeaddsite.com) and make it look like "Advert Cookie"

  • User Logged on to example.com with remember me
  • Store username, token, reference in cookie
  • Store username, token, reference in Database eg. Memcache
  • Send refrence id via get and iframe to fakeaddsite.com
  • fakeaddsite.com uses the reference to fetch user & token from Database
  • fakeaddsite.com stores the signature
  • When a user is returning fetch signature information with iframe from fakeaddsite.com
  • Combine it data and do the validation
  • ..... you know the remaining

Some people might wonder how can you use 2 different cookies ? Well its possible, imagine example.com = localhost and fakeaddsite.com = 192.168.1.120. If you inspect the cookies it would look like this

enter image description here

From the image above

  • The current site visited is localhost
  • It also contains cookies set from 192.168.1.120

192.168.1.120

  • Only accepts defined HTTP_REFERER
  • Only accepts connection from specified REMOTE_ADDR
  • No JavaScript, No content but consist nothing rather than sign information and add or retrieve it from cookie

Advantage

  • 99% percent of the time you have tricked the attacker
  • You can easily lock the account in the attacker first attempt
  • Attack can be prevented even before the next login like the other methods

Disadvantage

  • Multiple Request to server just for a single login

Improvement

  • Done use iframe use ajax

"implements Runnable" vs "extends Thread" in Java

In the rare case you only run it once, you should extend Thread because of DRY. If you call it multiple times, you should implement Runnable because the same thread should not be restarted.

Convert multidimensional array into single array

For this particular case, this'll do:

$array = array_map('current', $array[0]);

It's basically the exact same question is this one, look at some answers there: PHP array merge from unknown number of parameters.

Adding days to $Date in PHP

All have to use bellow code:

$nday = time() + ( 24 * 60 * 60);    
echo 'Now:       '. date('Y-m-d') ."\n";    
echo 'Next Day: '. date('Y-m-d', $nday) ."\n";

MySQL: How to allow remote connection to mysql

If you installed MySQL from brew it really does only listen on the local interface by default. To fix that you need to edit /usr/local/etc/my.cnf and change the bind-address from 127.0.0.1 to *.

Then run brew services restart mysql.

iOS - UIImageView - how to handle UIImage image orientation

If I understand, what you want to do is disregard the orientation of the UIImage? If so then you could do this:

UIImage *originalImage = [... whatever ...];

UIImage *imageToDisplay =
     [UIImage imageWithCGImage:[originalImage CGImage]
              scale:[originalImage scale]
              orientation: UIImageOrientationUp];

So you're creating a new UIImage with the same pixel data as the original (referenced via its CGImage property) but you're specifying an orientation that doesn't rotate the data.

MySQL skip first 10 results

From the manual:

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

Obviously, you should replace 95 by 10. The large number they use is 2^64 - 1, by the way.

postgresql COUNT(DISTINCT ...) very slow

You can use this:

SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;

This is much faster than:

COUNT(DISTINCT column_name)

Abstract methods in Java

Abstract methods means there is no default implementation for it and an implementing class will provide the details.

Essentially, you would have

abstract class AbstractObject {
   public abstract void method();
}

class ImplementingObject extends AbstractObject {
  public void method() {
    doSomething();
  }
}

So, it's exactly as the error states: your abstract method can not have a body.

There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html

The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.

A very simple example would be shapes:

You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.

(This is taken from the site I linked above)

abstract class GraphicObject {
    int x, y;
    ...
    void moveTo(int newX, int newY) {
        ...
    }
    abstract void draw();
    abstract void resize();
}

class Circle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}
class Rectangle extends GraphicObject {
    void draw() {
        ...
    }
    void resize() {
        ...
    }
}

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

Common elements in two lists

Below code Remove common elements in the list

List<String> result =  list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());

Retrieve common elements

List<String> result = list1.stream()
                .distinct()
                .filter(list::contains)
                .collect(Collectors.toList());

Search File And Find Exact Match And Print Line?

It's very easy:

numb = raw_input('Input Line: ')
fiIn = open('file.txt').readlines()
for lines in fiIn:
   if numb == lines[0]:
      print lines

Generic List - moving an item within the list

Simplest way:

list[newIndex] = list[oldIndex];
list.RemoveAt(oldIndex);

EDIT

The question isn't very clear ... Since we don't care where the list[newIndex] item goes I think the simplest way of doing this is as follows (with or without an extension method):

    public static void Move<T>(this List<T> list, int oldIndex, int newIndex)
    {
        T aux = list[newIndex];
        list[newIndex] = list[oldIndex];
        list[oldIndex] = aux;
    }

This solution is the fastest because it doesn't involve list insertions/removals.

How to read and write to a text file in C++?

Look at this tutorial or this one, they are both pretty simple. If you are interested in an alternative this is how you do file I/O in C.

Some things to keep in mind, use single quotes ' when dealing with single characters, and double " for strings. Also it is a bad habit to use global variables when not necessary.

Have fun!

How to detect control+click in Javascript from an onclick div attribute?

When there is a mouse click ctrlKey is event attribute which can be accessed as e.ctrlKey. Look down for example

$("xyz").click(function(e)){
  if(e.ctrlKey){
    //if ctrl key is pressed
  }
  else{
    // if ctrl key is not pressed
  }
}

note: https://www.w3schools.com/jsref/event_key_keycode.asp

How to compile a static library in Linux?

Here a full makefile example:

makefile

TARGET = prog

$(TARGET): main.o lib.a
    gcc $^ -o $@

main.o: main.c
    gcc -c $< -o $@

lib.a: lib1.o lib2.o
    ar rcs $@ $^

lib1.o: lib1.c lib1.h
    gcc -c -o $@ $<

lib2.o: lib2.c lib2.h
    gcc -c -o $@ $<

clean:
    rm -f *.o *.a $(TARGET)

explaining the makefile:

  • target: prerequisites - the rule head
  • $@ - means the target
  • $^ - means all prerequisites
  • $< - means just the first prerequisite
  • ar - a Linux tool to create, modify, and extract from archives see the man pages for further information. The options in this case mean:
    • r - replace files existing inside the archive
    • c - create a archive if not already existent
    • s - create an object-file index into the archive

To conclude: The static library under Linux is nothing more than a archive of object files.

main.c using the lib

#include <stdio.h>

#include "lib.h"

int main ( void )
{
    fun1(10);
    fun2(10);
    return 0;
}

lib.h the libs main header

#ifndef LIB_H_INCLUDED
#define LIB_H_INCLUDED

#include "lib1.h"
#include "lib2.h"

#endif

lib1.c first lib source

#include "lib1.h"

#include <stdio.h>

void fun1 ( int x )
{
    printf("%i\n",x);
}

lib1.h the corresponding header

#ifndef LIB1_H_INCLUDED
#define LIB1_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun1 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB1_H_INCLUDED */

lib2.c second lib source

#include "lib2.h"

#include <stdio.h>

void fun2 ( int x )
{
    printf("%i\n",2*x);
}

lib2.h the corresponding header

#ifndef LIB2_H_INCLUDED
#define LIB2_H_INCLUDED

#ifdef __cplusplus
   extern “C” {
#endif

void fun2 ( int x );

#ifdef __cplusplus
   }
#endif

#endif /* LIB2_H_INCLUDED */

SQL Error: ORA-01861: literal does not match format string 01861

Try replacing the string literal for date '1989-12-09' with TO_DATE('1989-12-09','YYYY-MM-DD')

How do I run a Python script on my web server?

Very simply, you can rename your Python script to "pythonscript.cgi". Post that in your cgi-bin directory, add the appropriate permissions and browse to it.

This is a great link you can start with.

Here's another good one.

Hope that helps.


EDIT (09/12/2015): The second link has long been removed. Replaced it with one that provides information referenced from the original.

Bootstrap visible and hidden classes not working properly

Your mobile class Isn't correct:

.mobile {
  display: none !important;
  visibility: hidden !important; //This is what's keeping the div from showing, remove this.
}

editing PATH variable on mac

You could try this:

  1. Open the Terminal application. It can be found in the Utilities directory inside the Applications directory.
  2. Type the following: echo 'export PATH=YOURPATHHERE:$PATH' >> ~/.profile, replacing "YOURPATHHERE" with the name of the directory you want to add. Make certain that you use ">>" instead of one ">".
  3. Hit Enter.
  4. Close the Terminal and reopen. Your new Terminal session should now use the new PATH.

-> http://keito.me/tutorials/macosx_path

Hide password with "•••••••" in a textField

You can do this by using properties of textfield from Attribute inspector

Tap on Your Textfield from storyboard and go to Attribute inspector , and just check the checkbox of "Secure Text Entry" SS is added for graphical overview to achieve same

How do I run a PowerShell script when the computer starts?

I have a script that starts a file system watcher as well, but once the script window is closed the watcher dies. It will run all day if I start it from a powershell window and leave it open, but the minute I close it the script stops doing what it is supposed to.
You need to start the script and have it keep powershell open.
I tried numerous ways to do this, but the one that actually worked was from http://www.methos-it.com/blogs/keep-your-powershell-script-open-when-executed

param ( $Show )
if ( !$Show ) 
{
    PowerShell -NoExit -File $MyInvocation.MyCommand.Path 1
    return
}

Pasting that to the top of the script is what made it work.
I start the script from command line with

powershell.exe -noexit -command "& \path\to\script.ps1"

How would I get a cron job to run every 30 minutes?

You can use both of ',' OR divide '/' symbols.
But, '/' is better.
Suppose the case of 'every 5 minutes'. If you use ',', you have to write the cron job as following:

0,5,10,15,20,25,30,35,....    *      *     *   * your_command

It means run your_command in every hour in all of defined minutes: 0,5,10,...

However, if you use '/', you can write the following simple and short job:

*/5  *  *  *  *  your_command

It means run your_command in the minutes that are dividable by 5 or in the simpler words, '0,5,10,...'

So, dividable symbol '/' is the best choice always;

Where can I find php.ini?

On the command line execute:

php --ini

You will get something like:

Configuration File (php.ini) Path: /etc/php5/cli
Loaded Configuration File:         /etc/php5/cli/php.ini
Scan for additional .ini files in: /etc/php5/cli/conf.d
Additional .ini files parsed:      /etc/php5/cli/conf.d/curl.ini,
/etc/php5/cli/conf.d/pdo.ini,
/etc/php5/cli/conf.d/pdo_sqlite.ini,
/etc/php5/cli/conf.d/sqlite.ini,
/etc/php5/cli/conf.d/sqlite3.ini,
/etc/php5/cli/conf.d/xdebug.ini,
/etc/php5/cli/conf.d/xsl.ini

That's from my local dev-machine. However, the second line is the interesting one. If there is nothing mentioned, have a look at the first one. That is the path, where PHP looks for the php.ini.

You can grep the same information using phpinfo() in a script and call it with a browser. Its mentioned in the first block of the output. php -i does the same for the command line, but its quite uncomfortable.

How to disable textbox from editing?

        textBox1.Enabled = false;

"false" property will make the text box disable. and "true" will make it in regular form. Thanks.

MySQL: Check if the user exists and drop it

Found the answer to this from one of the MySQL forums. We’ll need to use a procedure to delete the user.

User here is “test” and “databaseName” the database name.


SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ANSI';
USE databaseName ;
DROP PROCEDURE IF EXISTS databaseName.drop_user_if_exists ;
DELIMITER $$
CREATE PROCEDURE databaseName.drop_user_if_exists()
BEGIN
  DECLARE foo BIGINT DEFAULT 0 ;
  SELECT COUNT(*)
  INTO foo
    FROM mysql.user
      WHERE User = 'test' and  Host = 'localhost';
   IF foo > 0 THEN
         DROP USER 'test'@'localhost' ;
  END IF;
END ;$$
DELIMITER ;
CALL databaseName.drop_user_if_exists() ;
DROP PROCEDURE IF EXISTS databaseName.drop_users_if_exists ;
SET SQL_MODE=@OLD_SQL_MODE ;

CREATE USER 'test'@'localhost' IDENTIFIED BY 'a'; GRANT ALL PRIVILEGES ON databaseName.* TO 'test'@'localhost' WITH GRANT OPTION

Show DataFrame as table in iPython Notebook

This answer is based on the 2nd tip from this blog post: 28 Jupyter Notebook tips, tricks and shortcuts

You can add the following code to the top of your notebook

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

This tells Jupyter to print the results for any variable or statement on it’s own line. So you can then execute a cell solely containing

df1
df2

and it will "print out the beautiful tables for both datasets".

How to find the process id of a running Java process on Windows? And how to kill the process alone?

This is specific to Windows. I was facing the same issue where I have to kill one specific java program using taskkill. When I run the java program, tasklist was showing the same program with Image name set as java.exe. But killing it using taskkill /F java.exe will stop all other java applications other than intended one which is not required.

So I run the same java program using:

start "MyProgramName" java java-program..

Here start command will open a new window and run the java program with window's title set to MyProgramName.

Now to kill this java-program use the following taskkill command:

taskkill /fi "MyProgramName"

Your Java program will be killed only. Rest will be unaffected.

AngularJS 1.2 $injector:modulerr

Its an injector error. You may have use lots of JavaScript files so the injector may be missing.

Some are here:

var app = angular.module('app', 
    ['ngSanitize', 'ui.router', 'pascalprecht.translate', 'ngResource', 
     'ngMaterial', 'angularMoment','md.data.table', 'angularFileUpload', 
     'ngMessages', 'ui.utils.masks', 'angular-sortable-view',          
     'mdPickers','ngDraggable','as.sortable', 'ngAnimate', 'ngTouch']
);

Please check the injector you need to insert in your app.js

How do I pass variables and data from PHP to JavaScript?

Here is is the trick:

  1. Here is your 'PHP' to use that variable:

    <?php
        $name = 'PHP variable';
        echo '<script>';
        echo 'var name = ' . json_encode($name) . ';';
        echo '</script>';
    ?>
    
  2. Now you have a JavaScript variable called 'name', and here is your JavaScript code to use that variable:

    <script>
         console.log("I am everywhere " + name);
    </script>
    

ionic build Android | error: No installed build tools found. Please install the Android build tools

I Search this problem for days.... I hope it will be usefull

FINAL SOLUTION: (I assume that you have installed Oracle-JDK and ANDROID)

open /etc/environment with

 sudo nano /etc/environment


PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/shoniisra/Android/Sdk/tools:/home/shoniisra/Android/Sdk/platform-tools:/home/shoniisra/Android/Sdk/build-tools:/home/shoniisra/Android/Sdk:/home/shoniisra/android-studio/bin"
JAVA_HOME="/home/shoniisra/java/jdk1.8.0_231"
ANDROID_HOME="/home/shoniisra/Android/Sdk/build-tools/29.0.2"
ANDROID_SDK_ROOT="/home/shoniisra/Android/Sdk"
ANT_HOME="/home/shoniisra/ant/apache-ant-1.9.14"

Save and exit (CTRL+o CTRL+X)

Reload file source /etc/environment

If you recently installed Android you should accept some licences

cd ~/Android/Sdk/tools/bin/

Execute sdkmanager:

./sdkmanager --licenses

Then Accept all, and Finally generate your APK

cd {yourproyect}
sudo ionic cordova build android

Remove border from buttons

Try using: border:0; or border:none;

Pass a String from one Activity to another Activity in Android

First Activity Code :

Intent mIntent = new Intent(ActivityA.this, ActivityB.class);
mIntent.putExtra("easyPuzzle", easyPuzzle);

Second Activity Code :

String easyPuzzle = getIntent().getStringExtra("easyPuzzle");

How to remove jar file from local maven repository which was added with install:install-file?

At least on the current maven version you need to add the switch -DreResolve=false if you intend to remove the dependencies from your local repo without re-downloading them.

mvn dependency:purge-local-repository -DreResolve=false

removes the dependencies without downloading them again.

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

how to initialize a char array?

This method uses the 'C' memset function, and is very fast (avoids a char-by-char loop).

const uint size = 65546;
char* msg = new char[size];
memset(reinterpret_cast<void*>(msg), 0, size);

Creating instance list of different objects

How can I create a list without defining a class type? (<Employee>)

If I'm reading this correctly, you just want to avoid having to specify the type, correct?

In Java 7, you can do

List<Employee> list = new ArrayList<>();

but any of the other alternatives being discussed are just going to sacrifice type safety.

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

Just iterate and add:

for(Map.Entry e : a.entrySet())
  if(!b.containsKey(e.getKey())
    b.put(e.getKey(), e.getValue());

Edit to add:

If you can make changes to a, you can also do:

a.putAll(b)

and a will have exactly what you need. (all the entries in b and all the entries in a that aren't in b)

Git refusing to merge unrelated histories on rebase

Firstly pull the remote changes to your local using the following command:

git pull origin branchname --allow-unrelated-histories

** branchname is master in my case.

When the pull command done, conflict occurs. You should solve the conflicts. I use Android Studio to solve conflicts. enter image description here

When conflicts solved, merge is done!

Now you can safely push.

How can I enable Assembly binding logging?

Per pierce.jason's answer above, I had luck with:

Just create a new DWORD(32) under the Fusion key. Name the DWORD to LogFailures, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.

How to reset a timer in C#?

You could write an extension method called Reset(), which

  • calls Stop()-Start() for Timers.Timer and Forms.Timer
  • calls Change for Threading.Timer

get the value of input type file , and alert if empty

There should be

$('.send_upload')

but not $('.upload')

How to calculate an age based on a birthday?

I do it like this:

(Shortened the code a bit)

public struct Age
{
    public readonly int Years;
    public readonly int Months;
    public readonly int Days;

}

public Age( int y, int m, int d ) : this()
{
    Years = y;
    Months = m;
    Days = d;
}

public static Age CalculateAge ( DateTime birthDate, DateTime anotherDate )
{
    if( startDate.Date > endDate.Date )
        {
            throw new ArgumentException ("startDate cannot be higher then endDate", "startDate");
        }

        int years = endDate.Year - startDate.Year;
        int months = 0;
        int days = 0;

        // Check if the last year, was a full year.
        if( endDate < startDate.AddYears (years) && years != 0 )
        {
            years--;
        }

        // Calculate the number of months.
        startDate = startDate.AddYears (years);

        if( startDate.Year == endDate.Year )
        {
            months = endDate.Month - startDate.Month;
        }
        else
        {
            months = ( 12 - startDate.Month ) + endDate.Month;
        }

        // Check if last month was a complete month.
        if( endDate < startDate.AddMonths (months) && months != 0 )
        {
            months--;
        }

        // Calculate the number of days.
        startDate = startDate.AddMonths (months);

        days = ( endDate - startDate ).Days;

        return new Age (years, months, days);
}

// Implement Equals, GetHashCode, etc... as well
// Overload equality and other operators, etc...

}

Extract hostname name from string

I personally researched a lot for this solution, and the best one I could find is actually from CloudFlare's "browser check":

function getHostname(){  
            secretDiv = document.createElement('div');
            secretDiv.innerHTML = "<a href='/'>x</a>";
            secretDiv = secretDiv.firstChild.href;
            var HasHTTPS = secretDiv.match(/https?:\/\//)[0];
            secretDiv = secretDiv.substr(HasHTTPS.length);
            secretDiv = secretDiv.substr(0, secretDiv.length - 1);
            return(secretDiv);  
}  

getHostname();

I rewritten variables so it is more "human" readable, but it does the job better than expected.

Server is already running in Rails

On Windows Rails 5.2, delete this file

c:/Sites/<your_folder>/tmp/pids/server.pid

and run

rails s

again.

What does LayoutInflater in Android do?

LayoutInflater is a fundamental component in Android. You must use it all the time to turn xml files into view hierarchies.

How do I make a JAR from a .java file?

This can be done without terminal, directly from IDE. Netbeans, for example.

  1. Create a separate project with packages (Create Project - Java - Java Class Library).
  2. Put your .java classes there.
  3. Build this project.
  4. Go to your project folder and find build and dist folders there.
  5. Find .jar file in your dist folder.
  6. Get your other project and add this .jar file to project libraries.
  7. You can now reference classes from this library and its methods directly from code, if import is automatically done for you.

Setting Curl's Timeout in PHP

See documentation: http://www.php.net/manual/en/function.curl-setopt.php

CURLOPT_CONNECTTIMEOUT - The number of seconds to wait while trying to connect. Use 0 to wait indefinitely.
CURLOPT_TIMEOUT - The maximum number of seconds to allow cURL functions to execute.

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0); 
curl_setopt($ch, CURLOPT_TIMEOUT, 400); //timeout in seconds

also don't forget to enlarge time execution of php script self:

set_time_limit(0);// to infinity for example

versionCode vs versionName in Android Manifest

Version Code Represent Version of Your code, android OS check for update by using this variable whether this code is old or new.

Version Name Represent name of version in the format-

(Major).(Minor).(point)

String, used for readable string only, functionally version code has been used by OS.

Correct way to select from two tables in SQL Server with no common field to join on

Cross join will help to join multiple tables with no common fields.But be careful while joining as this join will give cartesian resultset of two tables. QUERY:

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
CROSS JOIN table2

Alternative way to join on some condition that is always true like

SELECT 
   table1.columnA
 , table2,columnA
FROM table1 
INNER JOIN table2 ON 1=1

But this type of query should be avoided for performance as well as coding standards.

JPA or JDBC, how are they different?

JDBC is a much lower-level (and older) specification than JPA. In it's bare essentials, JDBC is an API for interacting with a database using pure SQL - sending queries and retrieving results. It has no notion of objects or hierarchies. When using JDBC, it's up to you to translate a result set (essentially a row/column matrix of values from one or more database tables, returned by your SQL query) into Java objects.

Now, to understand and use JDBC it's essential that you have some understanding and working knowledge of SQL. With that also comes a required insight into what a relational database is, how you work with it and concepts such as tables, columns, keys and relationships. Unless you have at least a basic understanding of databases, SQL and data modelling you will not be able to make much use of JDBC since it's really only a thin abstraction on top of these things.

How to convert numbers between hexadecimal and decimal

My version is I think a little more understandable because my C# knowledge is not so high. I'm using this algorithm: http://easyguyevo.hubpages.com/hub/Convert-Hex-to-Decimal (The Example 2)

using System;
using System.Collections.Generic;

static class Tool
{
    public static string DecToHex(int x)
    {
        string result = "";

        while (x != 0)
        {
            if ((x % 16) < 10)
                result = x % 16 + result;
            else
            {
                string temp = "";

                switch (x % 16)
                {
                    case 10: temp = "A"; break;
                    case 11: temp = "B"; break;
                    case 12: temp = "C"; break;
                    case 13: temp = "D"; break;
                    case 14: temp = "E"; break;
                    case 15: temp = "F"; break;
                }

                result = temp + result;
            }

            x /= 16;
        }

        return result;
    }

    public static int HexToDec(string x)
    {
        int result = 0;
        int count = x.Length - 1;
        for (int i = 0; i < x.Length; i++)
        {
            int temp = 0;
            switch (x[i])
            {
                case 'A': temp = 10; break;
                case 'B': temp = 11; break;
                case 'C': temp = 12; break;
                case 'D': temp = 13; break;
                case 'E': temp = 14; break;
                case 'F': temp = 15; break;
                default: temp = -48 + (int)x[i]; break; // -48 because of ASCII
            }

            result += temp * (int)(Math.Pow(16, count));
            count--;
        }

        return result;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter Decimal value: ");
        int decNum = int.Parse(Console.ReadLine());

        Console.WriteLine("Dec {0} is hex {1}", decNum, Tool.DecToHex(decNum));

        Console.Write("\nEnter Hexadecimal value: ");
        string hexNum = Console.ReadLine().ToUpper();

        Console.WriteLine("Hex {0} is dec {1}", hexNum, Tool.HexToDec(hexNum));

        Console.ReadKey();
    }
}

Matching an empty input box using CSS

If you're happy not not supporting IE or pre-Chromium Edge (which might be fine if you are using this for progressive enhancement), you can use :placeholder-shown as Berend has said. Note that for Chrome and Safari you actually need a non-empty placeholder for this to work, though a space works.

_x000D_
_x000D_
*,_x000D_
 ::after,_x000D_
 ::before {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
label.floating-label {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 2.2em;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input {_x000D_
  font-size: 1em;_x000D_
  height: 2.2em;_x000D_
  padding-top: 0.7em;_x000D_
  line-height: 1.5;_x000D_
  color: #495057;_x000D_
  background-color: #fff;_x000D_
  background-clip: padding-box;_x000D_
  border: 1px solid #ced4da;_x000D_
  border-radius: 0.25rem;_x000D_
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:focus {_x000D_
  color: #495057;_x000D_
  background-color: #fff;_x000D_
  border-color: #80bdff;_x000D_
  outline: 0;_x000D_
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);_x000D_
}_x000D_
_x000D_
label.floating-label input+span {_x000D_
  position: absolute;_x000D_
  top: 0em;_x000D_
  left: 0;_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  font-size: 0.66em;_x000D_
  line-height: 1.5;_x000D_
  color: #495057;_x000D_
  border: 1px solid transparent;_x000D_
  border-radius: 0.25rem;_x000D_
  transition: font-size 0.1s ease-in-out, top 0.1s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown {_x000D_
  padding-top: 0;_x000D_
  font-size: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown+span {_x000D_
  top: 0.3em;_x000D_
  font-size: 1em;_x000D_
}
_x000D_
<fieldset>_x000D_
  <legend>_x000D_
    Floating labels example (no-JS)_x000D_
  </legend>_x000D_
  <label class="floating-label">_x000D_
    <input type="text" placeholder=" ">_x000D_
    <span>Username</span>_x000D_
  </label>_x000D_
  <label class="floating-label">_x000D_
    <input type="Password" placeholder=" ">_x000D_
    <span>Password</span>_x000D_
  </label>_x000D_
</fieldset>_x000D_
<p>_x000D_
  Inspired by Bootstrap's <a href="https://getbootstrap.com/docs/4.0/examples/floating-labels/">floating labels</a>._x000D_
</p>
_x000D_
_x000D_
_x000D_

How to make a TextBox accept only alphabetic characters?

Here is my solution and it works as planned:

string errmsg = "ERROR : Wrong input";
ErrorLbl.Text = errmsg;

if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
  ErrorLbl.Text = "ERROR : Wrong input";
}
else ErrorLbl.Text = string.Empty;
if (ErrorLbl.Text == errmsg)
{
  Nametxt.Text = string.Empty;
}

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

Try loading the website in another web browser such as Safari. Recently had this problem and for some reason, it worked after loading in a different browser.

Java optional parameters

There are several ways to simulate optional parameters in Java:

  1. Method overloading.

    void foo(String a, Integer b) {
        //...
    }
    
    void foo(String a) {
        foo(a, 0); // here, 0 is a default value for b
    }
    
    foo("a", 2);
    foo("a");
    

    One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.

  2. Varargs.

    a) All optional parameters are of the same type:

    void foo(String a, Integer... b) {
        Integer b1 = b.length > 0 ? b[0] : 0;
        Integer b2 = b.length > 1 ? b[1] : 0;
        //...
    }
    
    foo("a");
    foo("a", 1, 2);
    

    b) Types of optional parameters may be different:

    void foo(String a, Object... b) {
        Integer b1 = 0;
        String b2 = "";
        if (b.length > 0) {
          if (!(b[0] instanceof Integer)) { 
              throw new IllegalArgumentException("...");
          }
          b1 = (Integer)b[0];
        }
        if (b.length > 1) {
            if (!(b[1] instanceof String)) { 
                throw new IllegalArgumentException("...");
            }
            b2 = (String)b[1];
            //...
        }
        //...
    }
    
    foo("a");
    foo("a", 1);
    foo("a", 1, "b2");
    

    The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has the different meaning you need some way to distinguish them.

  3. Nulls. To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body:

    void foo(String a, Integer b, Integer c) {
        b = b != null ? b : 0;
        c = c != null ? c : 0;
        //...
    }
    
    foo("a", null, 2);
    

    Now all arguments values must be provided, but the default ones may be null.

  4. Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:

    void foo(String a, Optional<Integer> bOpt) {
        Integer b = bOpt.isPresent() ? bOpt.get() : 0;
        //...
    }
    
    foo("a", Optional.of(2));
    foo("a", Optional.<Integer>absent());
    

    Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.

    Update: Java 8 includes the class java.util.Optional out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though.

  5. Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:

     class Foo {
         private final String a; 
         private final Integer b;
    
         Foo(String a, Integer b) {
           this.a = a;
           this.b = b;
         }
    
         //...
     }
    
     class FooBuilder {
       private String a = ""; 
       private Integer b = 0;
    
       FooBuilder setA(String a) {
         this.a = a;
         return this;
       }
    
       FooBuilder setB(Integer b) {
         this.b = b;
         return this;
       }
    
       Foo build() {
         return new Foo(a, b);
       }
     }
    
     Foo foo = new FooBuilder().setA("a").build();
    
  6. Maps. When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values:

    void foo(Map<String, Object> parameters) {
        String a = ""; 
        Integer b = 0;
        if (parameters.containsKey("a")) { 
            if (!(parameters.get("a") instanceof Integer)) { 
                throw new IllegalArgumentException("...");
            }
            a = (Integer)parameters.get("a");
        }
        if (parameters.containsKey("b")) { 
            //... 
        }
        //...
    }
    
    foo(ImmutableMap.<String, Object>of(
        "a", "a",
        "b", 2, 
        "d", "value")); 
    

    In Java 9, this approach became easier:

        @SuppressWarnings("unchecked")
        static <T> T getParm(Map<String, Object> map, String key, T defaultValue)
        {
            return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
        }
    
        void foo(Map<String, Object> parameters) {
            String a = getParm(parameters, "a", "");
            int b = getParm(parameters, "b", 0);
            // d = ...
        }
    
        foo(Map.of("a","a",  "b",2,  "d","value"));
    

Please note that you can combine any of these approaches to achieve a desirable result.

How to read a single character from the user?

The curses package in python can be used to enter "raw" mode for character input from the terminal with just a few statements. Curses' main use is to take over the screen for output, which may not be what you want. This code snippet uses print() statements instead, which are usable, but you must be aware of how curses changes line endings attached to output.

#!/usr/bin/python3
# Demo of single char terminal input in raw mode with the curses package.
import sys, curses

def run_one_char(dummy):
    'Run until a carriage return is entered'
    char = ' '
    print('Welcome to curses', flush=True)
    while ord(char) != 13:
        char = one_char()

def one_char():
    'Read one character from the keyboard'
    print('\r? ', flush= True, end = '')

    ## A blocking single char read in raw mode. 
    char = sys.stdin.read(1)
    print('You entered %s\r' % char)
    return char

## Must init curses before calling any functions
curses.initscr()
## To make sure the terminal returns to its initial settings,
## and to set raw mode and guarantee cleanup on exit. 
curses.wrapper(run_one_char)
print('Curses be gone!')

java.rmi.ConnectException: Connection refused to host: 127.0.1.1;

In my case I was unable to edit the hosts file because using a pc from the university.

I fixed the problem running rmiregistry in another port (instead of 1099) with:

rmiregistry <port>

and then running the server on that port.

It was basically an error caused by occupied port.

How to check whether a Storage item is set?

You can use hasOwnProperty method to check this

> localStorage.setItem('foo', 123)
undefined
> localStorage.hasOwnProperty('foo')
true
> localStorage.hasOwnProperty('bar')
false

Works in current versions of Chrome(Mac), Firefox(Mac) and Safari.

git push >> fatal: no configured push destination

I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.

git add .
git commit -m "some comments"
git push --set-upstream origin master

iOS - Dismiss keyboard when touching outside of UITextField

This is a good generic solution:

Objective-C:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];    
}

Swift:

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    self.view.endEditing(true)
}

Based on @icodebuster solution: https://stackoverflow.com/a/18756253/417652

Check if a file exists with wildcard in shell script

Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):

# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}

# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
   echo "No files not found"
elif [ $array_length -eq 1 ] ; then
   echo "File was found"
else
   echo "Files were found"
fi

for myfile in ${myarray[@]}
do
  echo "$myfile"
done

Yes, this does smell like Perl. Glad I didn't step in it ;)

CSS Flex Box Layout: full-width row and columns

You've almost done it. However setting flex: 0 0 <basis> declaration to the columns would prevent them from growing/shrinking; And the <basis> parameter would define the width of columns.

In addition, you could use CSS3 calc() expression to specify the height of columns with the respect to the height of the header.

#productShowcaseTitle {
  flex: 0 0 100%; /* Let it fill the entire space horizontally */
  height: 100px;
}

#productShowcaseDetail,
#productShowcaseThumbnailContainer {
  height: calc(100% - 100px); /* excluding the height of the header */
}

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 0 0 34%;  /* ~ 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
  <div id="productShowcaseDetail"></div>_x000D_
  <div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)


Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div> element, it would be achieved without using calc() as follows:

<div class="contentContainer"> <!-- Added wrapper -->
    <div id="productShowcaseDetail"></div>
    <div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
  display: flex;
  flex-direction: column;
  height: 600px; width: 580px;
}

.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 3;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
_x000D_
  <div class="contentContainer"> <!-- Added wrapper -->_x000D_
    <div id="productShowcaseDetail"></div>_x000D_
    <div id="productShowcaseThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)

MySQL: How to add one day to datetime field in query

You can try this:

SELECT DATE(DATE_ADD(m_inv_reqdate, INTERVAL + 1 DAY)) FROM  tr08_investment

Difference between try-catch and throw in java

try block contains set of statements where an exception can occur.

catch block will be used to used to handle the exception that occur with in try block. A try block is always followed by a catch block and we can have multiple catch blocks.

finally block is executed after catch block. We basically use it to put some common code when there are multiple catch blocks. Even if there is an exception or not finally block gets executed.

throw keyword will allow you to throw an exception and it is used to transfer control from try block to catch block.

throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself.

// Java program to demonstrate working of throws, throw, try, catch and finally.

 public class MyExample { 
      
        static void myMethod() throws IllegalAccessException 
        { 
            System.out.println("Inside myMethod()."); 
            throw new IllegalAccessException("demo"); 
        } 
      
        // This is a caller function  
        public static void main(String args[]) 
        { 
            try { 
                myMethod(); 
            } 
            catch (IllegalAccessException e) { 
                System.out.println("exception caught in main method."); 
            }
            finally(){
                System.out.println("I am in final block.");
            } 
        } 
    } 

Output:

Inside myMethod().
exception caught in main method.
I am in final block.

Who is listening on a given TCP port on Mac OS X?

On macOS, here's an easy way to get the process ID that's listening on a specific port with netstat. This example looks for a process serving content on port 80:

find server running on port 80

netstat -anv | egrep -w [.]80.*LISTEN

sample output

tcp4  0 0  *.80       *.*    LISTEN      131072 131072    715      0

The 2nd from the last column is the PID. In above, it's 715.

options

-a - show all ports, including those used by servers

-n - show numbers, don't look up names. This makes the command a lot faster

-v - verbose output, to get the process IDs

-w - search words. Otherwise the command will return info for ports 8000 and 8001, not just "80"

LISTEN - give info only for ports in LISTEN mode, i.e. servers

Laravel 5.1 API Enable Cors

For me i put this codes in public\index.php file. and it worked just fine for all CRUD operations.

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS, post, get');
header("Access-Control-Max-Age", "3600");
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Access-Control-Allow-Credentials", "true");

SeekBar and media player in android

I've used this tutorial with success, it's really simple to understand: www.androidhive.info/2012/03/android-building-audio-player-tutorial/

This is the interesting part:

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);
}  

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100);
       }
    };

/**
 *
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    mp.seekTo(currentPosition);

    // update timer progress again
    updateProgressBar();
}

Input and Output binary streams using JERSEY?

I have been composing my Jersey 1.17 services the following way:

FileStreamingOutput

public class FileStreamingOutput implements StreamingOutput {

    private File file;

    public FileStreamingOutput(File file) {
        this.file = file;
    }

    @Override
    public void write(OutputStream output)
            throws IOException, WebApplicationException {
        FileInputStream input = new FileInputStream(file);
        try {
            int bytes;
            while ((bytes = input.read()) != -1) {
                output.write(bytes);
            }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
            if (output != null) output.close();
            if (input != null) input.close();
        }
    }

}

GET

@GET
@Produces("application/pdf")
public StreamingOutput getPdf(@QueryParam(value="name") String pdfFileName) {
    if (pdfFileName == null)
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    if (!pdfFileName.endsWith(".pdf")) pdfFileName = pdfFileName + ".pdf";

    File pdf = new File(Settings.basePath, pdfFileName);
    if (!pdf.exists())
        throw new WebApplicationException(Response.Status.NOT_FOUND);

    return new FileStreamingOutput(pdf);
}

And the client, if you need it:

Client

private WebResource resource;

public InputStream getPDFStream(String filename) throws IOException {
    ClientResponse response = resource.path("pdf").queryParam("name", filename)
        .type("application/pdf").get(ClientResponse.class);
    return response.getEntityInputStream();
}

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

A date-time object is not a String

The java.sql.Timestamp class has no format. Its toString method generates a String with a format.

Do not conflate a date-time object with a String that may represent its value. A date-time object can parse strings and generate strings but is not itself a string.

java.time

First convert from the troubled old legacy date-time classes to java.time classes. Use the new methods added to the old classes.

Instant instant = mySqlDate.toInstant() ;

Lose the fraction of a second you don't want.

instant = instant.truncatedTo( ChronoUnit.Seconds );

Assign the time zone to adjust from UTC used by Instant.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
ZonedDateTime zdt = instant.atZone( z );

Generate a String close to your desired output. Replace its T in the middle with a SPACE.

DateTimeFormatter f = DateTimeFormatter.ISO_LOCAL_DATE_TIME ;
String output = zdt.format( f ).replace( "T" , " " );

How can I get a file's size in C++?

#include <stdio.h>

#define MAXNUMBER 1024

int main()
{
    int i;
    char a[MAXNUMBER];

    FILE *fp = popen("du -b  /bin/bash", "r");

    while((a[i++] = getc(fp))!= 9)
        ;

    a[i] ='\0';

    printf(" a is %s\n", a);

    pclose(fp);
    return 0;
}  

HTH

Dynamically adding properties to an ExpandoObject

Here is a sample helper class which converts an Object and returns an Expando with all public properties of the given object.


    public static class dynamicHelper
        {
            public static ExpandoObject convertToExpando(object obj)
            {
                //Get Properties Using Reflections
                BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
                PropertyInfo[] properties = obj.GetType().GetProperties(flags);

                //Add Them to a new Expando
                ExpandoObject expando = new ExpandoObject();
                foreach (PropertyInfo property in properties)
                {
                    AddProperty(expando, property.Name, property.GetValue(obj));
                }

                return expando;
            }

            public static void AddProperty(ExpandoObject expando, string propertyName, object propertyValue)
            {
                //Take use of the IDictionary implementation
                var expandoDict = expando as IDictionary;
                if (expandoDict.ContainsKey(propertyName))
                    expandoDict[propertyName] = propertyValue;
                else
                    expandoDict.Add(propertyName, propertyValue);
            }
        }

Usage:

//Create Dynamic Object
dynamic expandoObj= dynamicHelper.convertToExpando(myObject);

//Add Custom Properties
dynamicHelper.AddProperty(expandoObj, "dynamicKey", "Some Value");

Scanner only reads first word instead of line

The javadocs for Scanner answer your question

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

You might change the default whitespace pattern the Scanner is using by doing something like

Scanner s = new Scanner();
s.useDelimiter("\n");

Permission denied for relation

This frequently happens when you create a table as user postgres and then try to access it as an ordinary user. In this case it is best to log in as the postgres user and change the ownership of the table with the command:

alter table <TABLE> owner to <USER>;

What is a wrapper class?

There are several design patterns that can be called wrapper classes.

See my answer to "How do the Proxy, Decorator, Adaptor, and Bridge Patterns differ?"

What to do with branch after merge

If you DELETE the branch after merging it, just be aware that all hyperlinks, URLs, and references of your DELETED branch will be BROKEN.

What is the best way to find the users home directory in Java?

Alternative would be to use Apache CommonsIO FileUtils.getUserDirectory() instead of System.getProperty("user.home"). It will get you the same result and there is no chance to introduce a typo when specifying system property.

There is a big chance you already have Apache CommonsIO library in your project. Don't introduce it if you plan to use it only for getting user home directory.

Change Button color onClick

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

Hope this helps.

Set size of HTML page and browser window

You could try:

<html>
    <head>
        <style>
            #main {
                width: 500; /*Set to whatever*/
                height: 500;/*Set to whatever*/
            }
        </style>
    </head>
    <body id="main">
    </body>
</html>

How to parse string into date?

CONVERT(datetime, '24.04.2012', 104)

Should do the trick. See here for more info: CAST and CONVERT (Transact-SQL)

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

Handling a timeout error in python sockets

from foo import * 

adds all the names without leading underscores (or only the names defined in the modules __all__ attribute) in foo into your current module.

In the above code with from socket import * you just want to catch timeout as you've pulled timeout into your current namespace.

from socket import * pulls in the definitions of everything inside of socket but doesn't add socket itself.

try:
    # socketstuff
except timeout:
    print 'caught a timeout'

Many people consider import * problematic and try to avoid it. This is because common variable names in 2 or more modules that are imported in this way will clobber one another.

For example, consider the following three python files:

# a.py
def foo():
    print "this is a's foo function"

# b.py
def foo():
    print "this is b's foo function"

# yourcode.py
from a import *
from b import *
foo()

If you run yourcode.py you'll see just the output "this is b's foo function".

For this reason I'd suggest either importing the module and using it or importing specific names from the module:

For example, your code would look like this with explicit imports:

import socket
from socket import AF_INET, SOCK_DGRAM

def main():
    client_socket = socket.socket(AF_INET, SOCK_DGRAM)
    client_socket.settimeout(1)
    server_host = 'localhost'
    server_port = 1234
    while(True):
        client_socket.sendto('Message', (server_host, server_port))
        try:
            reply, server_address_info = client_socket.recvfrom(1024)
            print reply
        except socket.timeout:
            #more code

Just a tiny bit more typing but everything's explicit and it's pretty obvious to the reader where everything comes from.

Best way to access a control on another form in Windows Forms?

@Lars, good call on the passing around of Form references, seen it as well myself. Nasty. Never seen them passed them down to the BLL layer though! That doesn't even make sense! That could have seriously impacted performance right? If somewhere in the BLL the reference was kept, the form would stay in memory right?

You have my sympathy! ;)


@Ed, RE your comment about making the Forms UserControls. Dylan has already pointed out that the root form instantiates many child forms, giving the impression of an MDI application (where I am assuming users may want to close various Forms). If I am correct in this assumption, I would think they would be best kept as forms. Certainly open to correction though :)

How to export table as CSV with headings on Postgresql?

COPY products_273 TO '/tmp/products_199.csv' WITH (FORMAT CSV, HEADER);

as described in the manual.

Android change SDK version in Eclipse? Unable to resolve target android-x

I faced the same issue and got it working.

I think it is because when you import a project, build target is not set in the project properties which then default to the value used in manifest file. Most likely, you already have installed a later android API with your SDK.

The solution is to enable build target toward your installed API level (but keep the minimum api support as specified in the manifest file). TO do this, in project properties, go to android, and from "Project Build Target", pick a target name.

Calling JavaScript Function From CodeBehind

Working Example :_

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage2.Master" AutoEventWireup="true" CodeBehind="History.aspx.cs" Inherits="NAMESPACE_Web.History1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
    <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>


 <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> 

        <script type="text/javascript">

            function helloFromCodeBehind() {
                alert("hello!")
            }


        </script>

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

 <div id="container"  ></div>

</asp:Content>

Code Behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace NAMESPACE_Web
{
    public partial class History1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "helloFromCodeBehind()", true);
        }

    }
}

Possible pitfalls:-

  1. Code and HTML might not be in same namespace
  2. CodeBehind="History.aspx.cs" is pointing to wrong page
  3. JS function is having some error

How to add a char/int to an char array in C?

The error is due the fact that you are passing a wrong to strcat(). Look at strcat()'s prototype:

   char *strcat(char *dest, const char *src);

But you pass char as the second argument, which is obviously wrong.

Use snprintf() instead.

char str[1024] = "Hello World";
char tmp = '.';
size_t len = strlen(str);

snprintf(str + len, sizeof str - len, "%c", tmp);

As commented by OP:

That was just a example with Hello World to describe the Problem. It must be empty as first in my real program. Program will fill it later. The problem just contains to add a char/int to an char Array

In that case, snprintf() can handle it easily to "append" integer types to a char buffer too. The advantage of snprintf() is that it's more flexible to concatenate various types of data into a char buffer.

For example to concatenate a string, char and an int:

char str[1024];
ch tmp = '.';
int i = 5;

// Fill str here

snprintf(str + len, sizeof str - len, "%c%d", str, tmp, i);

How in node to split string by newline ('\n')?

It looks like regex /\r\n|\r|\n/ handles CR, LF, and CRLF line endings, their mixed sequences, and keeps all the empty lines inbetween. Try that!

_x000D_
_x000D_
    function splitLines(t) { return t.split(/\r\n|\r|\n/); }

    // single newlines
    console.log(splitLines("AAA\rBBB\nCCC\r\nDDD"));
    // double newlines
    console.log(splitLines("EEE\r\rFFF\n\nGGG\r\n\r\nHHH"));
    // mixed sequences
    console.log(splitLines("III\n\r\nJJJ\r\r\nKKK\r\n\nLLL\r\n\rMMM"));
_x000D_
_x000D_
_x000D_

You should get these arrays as a result:

[ "AAA", "BBB", "CCC", "DDD" ]
[ "EEE", "", "FFF", "", "GGG", "", "HHH" ]
[ "III", "", "JJJ", "", "KKK", "", "LLL", "", "MMM" ]

You can also teach that regex to recognize other legit Unicode line terminators by adding |\xHH or |\uHHHH parts, where H's are hexadecimal digits of the additional terminator character codepoint (as seen in Wikipedia article as U+HHHH).

Detect when a window is resized using JavaScript ?

This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:

window.onresize = functionRef;

The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)

_x000D_
_x000D_
function resize() {_x000D_
  console.log("height: ", window.innerHeight, "px");_x000D_
  console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
_x000D_
_x000D_

Sum of values in an array using jQuery

In http://bugs.jquery.com/ticket/1886 it becomes obvious that the jQuery devs have serious mental issues reg. functional programming inspired additions. Somehow it's good to have some fundamental things (like map) but not others (like reduce), unless it reduces jQuery's overall filesize. Go figure.

Helpfully, someone placed code to use the normal reduce function for jQuery arrays:

$.fn.reduce = [].reduce;

Now we can use a simple reduce function to create a summation:

//where X is a jQuery array
X.reduce(function(a,b){ return a + b; });
// (change "a" into parseFloat("a") if the first a is a string)

Lastly, as some older browsers hadn't yet implemented reduce, a polyfill can be taken from MDN (it's big but I guess it has the exact same behavior, which is desirable):

if ( 'function' !== typeof Array.prototype.reduce ) {
    Array.prototype.reduce = function( callback /*, initialValue*/ ) {
        'use strict';
        if ( null === this || 'undefined' === typeof this ) {
          throw new TypeError(
             'Array.prototype.reduce called on null or undefined' );
        }
        if ( 'function' !== typeof callback ) {
          throw new TypeError( callback + ' is not a function' );
        }
        var t = Object( this ), len = t.length >>> 0, k = 0, value;
        if ( arguments.length >= 2 ) {
          value = arguments[1];
        } else {
          while ( k < len && ! k in t ) k++; 
          if ( k >= len )
            throw new TypeError('Reduce of empty array with no initial value');
          value = t[ k++ ];
        }
        for ( ; k < len ; k++ ) {
          if ( k in t ) {
             value = callback( value, t[k], k, t );
          }
        }
        return value;
      };
    }

Load local HTML file in a C# WebBrowser

Note that the file:/// scheme does not work on the compact framework, at least it doesn't with 5.0.

You will need to use the following:

string appDir = Path.GetDirectoryName(
    Assembly.GetExecutingAssembly().GetName().CodeBase);
webBrowser1.Url = new Uri(Path.Combine(appDir, @"Documentation\index.html"));

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

This happened to me when I registered a new domain name, e.g., "new" for example.com (new.example.com). The name could not be resolved temporarily in my location for a couple of hours, while it could be resolved abroad. So I used a proxy to test the website where I saw net::ERR_HTTP2_PROTOCOL_ERROR in chrome console for some AJAX posts. Hours later, when the name could be resloved locally, those error just dissappeared.

I think the reason for that error is those AJAX requests were not redirected by my proxy, it just visit a website which had not been resolved by my local DNS resolver.

Laravel Eloquent update just if changes have been made

You can use getChanges() on Eloquent model even after persisting.

Difference between DataFrame, Dataset, and RDD in Spark

Apache Spark provide three type of APIs

  1. RDD
  2. DataFrame
  3. Dataset

Comparing RDD, Dataframe and Dataset APIs

Here is the APIs comparison between RDD, Dataframe and Dataset.

RDD

The main abstraction Spark provides is a resilient distributed dataset (RDD), which is a collection of elements partitioned across the nodes of the cluster that can be operated on in parallel.

RDD Features:-

  • Distributed collection:
    RDD uses MapReduce operations which is widely adopted for processing and generating large datasets with a parallel, distributed algorithm on a cluster. It allows users to write parallel computations, using a set of high-level operators, without having to worry about work distribution and fault tolerance.

  • Immutable: RDDs composed of a collection of records which are partitioned. A partition is a basic unit of parallelism in an RDD, and each partition is one logical division of data which is immutable and created through some transformations on existing partitions.Immutability helps to achieve consistency in computations.

  • Fault tolerant: In a case of we lose some partition of RDD , we can replay the transformation on that partition in lineage to achieve the same computation, rather than doing data replication across multiple nodes.This characteristic is the biggest benefit of RDD because it saves a lot of efforts in data management and replication and thus achieves faster computations.

  • Lazy evaluations: All transformations in Spark are lazy, in that they do not compute their results right away. Instead, they just remember the transformations applied to some base dataset . The transformations are only computed when an action requires a result to be returned to the driver program.

  • Functional transformations: RDDs support two types of operations: transformations, which create a new dataset from an existing one, and actions, which return a value to the driver program after running a computation on the dataset.

  • Data processing formats:
    It can easily and efficiently process data which is structured as well as unstructured data.

  • Programming Languages supported:
    RDD API is available in Java, Scala, Python and R.

RDD Limitations:-

  • No inbuilt optimization engine: When working with structured data, RDDs cannot take advantages of Spark’s advanced optimizers including catalyst optimizer and Tungsten execution engine. Developers need to optimize each RDD based on its attributes.

  • Handling structured data: Unlike Dataframe and datasets, RDDs don’t infer the schema of the ingested data and requires the user to specify it.

Dataframes

Spark introduced Dataframes in Spark 1.3 release. Dataframe overcomes the key challenges that RDDs had.

A DataFrame is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database or a R/Python Dataframe. Along with Dataframe, Spark also introduced catalyst optimizer, which leverages advanced programming features to build an extensible query optimizer.

Dataframe Features:-

  • Distributed collection of Row Object: A DataFrame is a distributed collection of data organized into named columns. It is conceptually equivalent to a table in a relational database, but with richer optimizations under the hood.

  • Data Processing: Processing structured and unstructured data formats (Avro, CSV, elastic search, and Cassandra) and storage systems (HDFS, HIVE tables, MySQL, etc). It can read and write from all these various datasources.

  • Optimization using catalyst optimizer: It powers both SQL queries and the DataFrame API. Dataframe use catalyst tree transformation framework in four phases,

     1.Analyzing a logical plan to resolve references
     2.Logical plan optimization
     3.Physical planning
     4.Code generation to compile parts of the query to Java bytecode.
    
  • Hive Compatibility: Using Spark SQL, you can run unmodified Hive queries on your existing Hive warehouses. It reuses Hive frontend and MetaStore and gives you full compatibility with existing Hive data, queries, and UDFs.

  • Tungsten: Tungsten provides a physical execution backend whichexplicitly manages memory and dynamically generates bytecode for expression evaluation.

  • Programming Languages supported:
    Dataframe API is available in Java, Scala, Python, and R.

Dataframe Limitations:-

  • Compile-time type safety: As discussed, Dataframe API does not support compile time safety which limits you from manipulating data when the structure is not know. The following example works during compile time. However, you will get a Runtime exception when executing this code.

Example:

case class Person(name : String , age : Int) 
val dataframe = sqlContext.read.json("people.json") 
dataframe.filter("salary > 10000").show 
=> throws Exception : cannot resolve 'salary' given input age , name

This is challenging specially when you are working with several transformation and aggregation steps.

  • Cannot operate on domain Object (lost domain object): Once you have transformed a domain object into dataframe, you cannot regenerate it from it. In the following example, once we have create personDF from personRDD, we won’t be recover the original RDD of Person class (RDD[Person]).

Example:

case class Person(name : String , age : Int)
val personRDD = sc.makeRDD(Seq(Person("A",10),Person("B",20)))
val personDF = sqlContext.createDataframe(personRDD)
personDF.rdd // returns RDD[Row] , does not returns RDD[Person]

Datasets API

Dataset API is an extension to DataFrames that provides a type-safe, object-oriented programming interface. It is a strongly-typed, immutable collection of objects that are mapped to a relational schema.

At the core of the Dataset, API is a new concept called an encoder, which is responsible for converting between JVM objects and tabular representation. The tabular representation is stored using Spark internal Tungsten binary format, allowing for operations on serialized data and improved memory utilization. Spark 1.6 comes with support for automatically generating encoders for a wide variety of types, including primitive types (e.g. String, Integer, Long), Scala case classes, and Java Beans.

Dataset Features:-

  • Provides best of both RDD and Dataframe: RDD(functional programming, type safe), DataFrame (relational model, Query optimazation , Tungsten execution, sorting and shuffling)

  • Encoders: With the use of Encoders, it is easy to convert any JVM object into a Dataset, allowing users to work with both structured and unstructured data unlike Dataframe.

  • Programming Languages supported: Datasets API is currently only available in Scala and Java. Python and R are currently not supported in version 1.6. Python support is slated for version 2.0.

  • Type Safety: Datasets API provides compile time safety which was not available in Dataframes. In the example below, we can see how Dataset can operate on domain objects with compile lambda functions.

Example:

case class Person(name : String , age : Int)
val personRDD = sc.makeRDD(Seq(Person("A",10),Person("B",20)))
val personDF = sqlContext.createDataframe(personRDD)
val ds:Dataset[Person] = personDF.as[Person]
ds.filter(p => p.age > 25)
ds.filter(p => p.salary > 25)
 // error : value salary is not a member of person
ds.rdd // returns RDD[Person]
  • Interoperable: Datasets allows you to easily convert your existing RDDs and Dataframes into datasets without boilerplate code.

Datasets API Limitation:-

  • Requires type casting to String: Querying the data from datasets currently requires us to specify the fields in the class as a string. Once we have queried the data, we are forced to cast column to the required data type. On the other hand, if we use map operation on Datasets, it will not use Catalyst optimizer.

Example:

ds.select(col("name").as[String], $"age".as[Int]).collect()

No support for Python and R: As of release 1.6, Datasets only support Scala and Java. Python support will be introduced in Spark 2.0.

The Datasets API brings in several advantages over the existing RDD and Dataframe API with better type safety and functional programming.With the challenge of type casting requirements in the API, you would still not the required type safety and will make your code brittle.

make sounds (beep) with c++

The ASCII bell character might be what you are looking for. Number 7 in this table.

Two Divs on the same row and center align both of them

Please take a look on flex it will help you make things right,

on the main div set css display :flex

the div's that inside set css: flex:1 1 auto;

attached jsfiddle link as example enjoy :)

https://jsfiddle.net/hodca/v1uLsxbg/

jQuery callback for multiple ajax calls

Here is a callback object I wrote where you can either set a single callback to fire once all complete or let each have their own callback and fire them all once all complete:

NOTICE

Since jQuery 1.5+ you can use the deferred method as described in another answer:

  $.when($.ajax(), [...]).then(function(results){},[...]);

Example of deferred here

for jQuery < 1.5 the following will work or if you need to have your ajax calls fired at unknown times as shown here with two buttons: fired after both buttons are clicked

[usage]

for single callback once complete: Working Example

// initialize here
var requestCallback = new MyRequestsCompleted({
    numRequest: 3,
    singleCallback: function(){
        alert( "I'm the callback");
    }
});

//usage in request
$.ajax({
    url: '/echo/html/',
    success: function(data) {
        requestCallback.requestComplete(true);
    }
});
$.ajax({
    url: '/echo/html/',
    success: function(data) {
        requestCallback.requestComplete(true);
    }
});
$.ajax({
    url: '/echo/html/',
    success: function(data) {
        requestCallback.requestComplete(true);
    }
});

each having their own callback when all complete: Working Example

//initialize 
var requestCallback = new MyRequestsCompleted({
    numRequest: 3
});

//usage in request
$.ajax({
    url: '/echo/html/',
    success: function(data) {
        requestCallback.addCallbackToQueue(true, function() {
            alert('Im the first callback');
        });
    }
});
$.ajax({
    url: '/echo/html/',
    success: function(data) {
        requestCallback.addCallbackToQueue(true, function() {
            alert('Im the second callback');
        });
    }
});
$.ajax({
    url: '/echo/html/',
    success: function(data) {
        requestCallback.addCallbackToQueue(true, function() {
            alert('Im the third callback');
        });
    }
});

[The Code]

var MyRequestsCompleted = (function() {
    var numRequestToComplete, requestsCompleted, callBacks, singleCallBack;

    return function(options) {
        if (!options) options = {};

        numRequestToComplete = options.numRequest || 0;
        requestsCompleted = options.requestsCompleted || 0;
        callBacks = [];
        var fireCallbacks = function() {
            alert("we're all complete");
            for (var i = 0; i < callBacks.length; i++) callBacks[i]();
        };
        if (options.singleCallback) callBacks.push(options.singleCallback);

        this.addCallbackToQueue = function(isComplete, callback) {
            if (isComplete) requestsCompleted++;
            if (callback) callBacks.push(callback);
            if (requestsCompleted == numRequestToComplete) fireCallbacks();
        };
        this.requestComplete = function(isComplete) {
            if (isComplete) requestsCompleted++;
            if (requestsCompleted == numRequestToComplete) fireCallbacks();
        };
        this.setCallback = function(callback) {
            callBacks.push(callBack);
        };
    };
})();

Pinging servers in Python

#!/usr/bin/python3

import subprocess as sp

ip = "192.168.122.60"
status,result = sp.getstatusoutput("ping -c1 -w2 " + ip)

if status == 0: 
    print("System " + ip + " is UP !")
else:
    print("System " + ip + " is DOWN !")

Terminating a Java Program

What does return; mean?

return; really means it returns nothing void. That's it.

why return; or other codes can write below the statement of System.exit(0);

It is allowed since compiler doesn't know calling System.exit(0) will terminate the JVM. The compiler will just give a warning - unnecessary return statement

This IP, site or mobile application is not authorized to use this API key

  url = https://maps.googleapis.com/maps/api/directions/json?origin=19.0176147,72.8561644&destination=28.65381,77.22897&mode=driving&key=AIzaSyATaUNPUjc5rs0lVp2Z_spnJle-AvhKLHY

add only in AppDelegate like

            GMSServices.provideAPIKey("AIzaSyATaUNPUjc5rs0lVp2Z_spnJle-AvhKLHY")

and remove the key in this url.

now url is

https://maps.googleapis.com/maps/api/directions/json?origin=19.0176147,72.8561644&destination=28.65381,77.22897&mode=driving

Iterate through dictionary values?

Create the opposite dictionary:

PIX1 = {}
for key in PIX0.keys():
    PIX1[PIX0.get(key)] = key

Then run the same code on this dictionary instead (using PIX1 instead of PIX0).

BTW, I'm not sure about Python 3, but in Python 2 you need to use raw_input instead of input.

How to add font-awesome to Angular 2 + CLI project

UPDATE Feb 2020:
fortawesome package now supports ng add but it is available only for angular 9:

ng add @fortawesome/angular-fontawesome

UPDATE 8 Oct 2019:

You can use a new package https://www.npmjs.com/package/@fortawesome/angular-fontawesome

npm install @fortawesome/angular-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons

Add FontAwesomeModule to imports in src/app/app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
 
@NgModule({
  imports: [
    BrowserModule,
    FontAwesomeModule
  ],
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule { }

Tie the icon to the property in your component src/app/app.component.ts:

import { Component } from '@angular/core';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  faCoffee = faCoffee;
}

Use the icon in the template src/app/app.component.html:

<fa-icon [icon]="faCoffee"></fa-icon>

ORIGINAL ANSWER:

Option 1:

You can use angular-font-awesome npm module

npm install --save font-awesome angular-font-awesome

Import the module:

...
//
import { AngularFontAwesomeModule } from 'angular-font-awesome';
@NgModule({
  //...
  imports: [
    //...
    AngularFontAwesomeModule
  ],
  //...
})
export class AppModule { }

If you're using Angular CLI, add the font-awesome CSS to styles inside the angular-cli.json

"styles": [
    "styles.css",
    "../node_modules/font-awesome/css/font-awesome.css"
],

NOTE: If using SCSS preprocessor just change the css for scss

Example Use:

<fa name="cog" animation="spin"></fa>

Option 2:

There is an official story for that now

Install the font-awesome library and add the dependency to package.json

npm install --save font-awesome

Using CSS

To add Font Awesome CSS icons to your app...

// in .angular-cli.json

"styles": [
  "styles.css",
  "../node_modules/font-awesome/css/font-awesome.css"
]

Using SASS

Create an empty file _variables.scss in src/.

Add the following to _variables.scss:

$fa-font-path : '../node_modules/font-awesome/fonts'; In styles.scss add the following:

@import 'variables';
@import '../node_modules/font-awesome/scss/font-awesome';

Test

Run ng serve to run your application in develop mode, and navigate to http://localhost:4200.

To verify Font Awesome has been set up correctly, change src/app/app.component.html to the following...

<h1>
  {{title}} <i class="fa fa-check"></i>
</h1>

After saving this file, return to the browser to see the Font Awesome icon next to the app title.

Also there is a related question Angular CLI outputs the font-awesome font files the dist root as by default angular cli outputs the fonts in to the dist root, which is by the way not an issue at all.

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

What is the use of verbose in Keras while validating the model?

verbose: Integer. 0, 1, or 2. Verbosity mode.

Verbose=0 (silent)

Verbose=1 (progress bar)

Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc: 
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc: 
0.8071 - val_loss: 0.4617 - val_acc: 0.8168

Verbose=2 (one line per epoch)

Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
 - 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046

How do I configure the proxy settings so that Eclipse can download new plugins?

Manual + disable SOCKS didn't work for me (still tried to use SOCKS and my company proxy refused it),
Native + changed eclipse.ini worked for me

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient
-Dhttp.proxyHost=myproxy
-Dhttp.proxyPort=8080
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1

These settings require IDE restart (sometimes with -clean -refresh command line options).
https://bugs.eclipse.org/bugs/show_bug.cgi?id=281472


Java8, Eclipse Neon3, slow proxy server:

-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4
-Dhttp.proxyHost=<proxy>
-Dhttp.proxyPort=8080
-Dhttps.proxyHost=<proxy>
-Dhttps.proxyPort=8080
-DsocksProxyHost=
-DsocksProxyPort=
-Dhttp.proxyUser=<user>
-Dhttp.proxyPassword=<pass>
-Dhttp.nonProxyHosts=localhost|127.0.0.1
-Dorg.eclipse.equinox.p2.transport.ecf.retry=5
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.connectTimeout=15000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.readTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.retryAttempts=20
-Dorg.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout=1000
-Dorg.eclipse.ecf.provider.filetransfer.browse.connectTimeout=3000
-Dorg.eclipse.ecf.provider.filetransfer.browse.readTimeout=1000

How to display the first few characters of a string in Python?

You can 'slice' a string very easily, just like you'd pull items from a list:

a_string = 'This is a string'

To get the first 4 letters:

first_four_letters = a_string[:4]
>>> 'This'

Or the last 5:

last_five_letters = a_string[-5:]
>>> 'string'

So applying that logic to your problem:

the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe

Difference between Interceptor and Filter in Spring MVC

A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.

Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.

Reference: http://static.springframework.org/sp...ng-interceptor

Change name of folder when cloning from GitHub?

Here is one more answer from @Marged in comments

  1. Create a folder with the name you want
  2. Run the command below from the folder you created

    git clone <path to your online repo> .
    

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

Create Windows service from executable

To create a Windows Service from an executable, you can use sc.exe:

sc.exe create <new_service_name> binPath= "<path_to_the_service_executable>"

You must have quotation marks around the actual exe path, and a space after the binPath=.

More information on the sc command can be found in Microsoft KB251192.

Note that it will not work for just any executable: the executable must be a Windows Service (i.e. implement ServiceMain). When registering a non-service executable as a service, you'll get the following error upon trying to start the service:

Error 1053: The service did not respond to the start or control request in a timely fashion.

There are tools that can create a Windows Service from arbitrary, non-service executables, see the other answers for examples of such tools.

How do I execute code AFTER a form has loaded?

You can close your form after some execution..

//YourForm.ActiveForm.Close();

    LoadingForm.ActiveForm.Close();

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

How to check if a String is numeric in Java

I have illustrated some conditions to check numbers and decimals without using any API,

Check Fix Length 1 digit number

Character.isDigit(char)

Check Fix Length number (Assume length is 6)

String number = "132452";
if(number.matches("([0-9]{6})"))
System.out.println("6 digits number identified");

Check Varying Length number between (Assume 4 to 6 length)

//  {n,m}  n <= length <= m
String number = "132452";
if(number.matches("([0-9]{4,6})"))
System.out.println("Number Identified between 4 to 6 length");

String number = "132";
if(!number.matches("([0-9]{4,6})"))
System.out.println("Number not in length range or different format");

Check Varying Length decimal number between (Assume 4 to 7 length)

//  It will not count the '.' (Period) in length
String decimal = "132.45";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1.12";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "1234";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "-10.123";
if(decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Numbers Identified between 4 to 7");

String decimal = "123..4";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "132";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

String decimal = "1.1";
if(!decimal.matches("(-?[0-9]+(\.)?[0-9]*){4,6}"))
System.out.println("Decimal not in range or different format");

Hope it will help manyone.

Oracle Differences between NVL and Coalesce

NVL will do an implicit conversion to the datatype of the first parameter, so the following does not error

select nvl('a',sysdate) from dual;

COALESCE expects consistent datatypes.

select coalesce('a',sysdate) from dual;

will throw a 'inconsistent datatype error'

Automatic exit from Bash shell script on error

Here is how to do it:

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE *** 
************
'

join on multiple columns

Below is the structure of SQL that you may write. You can do multiple joins by using "AND" or "OR".

Select TableA.Col1, TableA.Col2, TableB.Val
FROM TableA, 
INNER JOIN TableB
 ON TableA.Col1 = TableB.Col1 OR TableA.Col2 = TableB.Col2

How do I tell Python to convert integers into words

This does the job without any library. Used recursion and it is Indian style. -- Ravi.

def spellNumber(no):
    # str(no) will result in  56.9 for 56.90 so we used the method which is given below.
    strNo = "%.2f" %no
    n = strNo.split(".")
    rs = numberToText(int(n[0])).strip()
    ps =""
    if(len(n)>=2):
        ps = numberToText(int(n[1])).strip()
        rs = "" + ps+ " paise"  if(rs.strip()=="") else  (rs + " and " + ps+ " paise").strip()
    return rs
print(spellNumber(0.67))
print(spellNumber(5858.099))
print(spellNumber(5083754857380.50))    

def numberToText(no):
    ones = " ,one,two,three,four,five,six,seven,eight,nine,ten,eleven,tweleve,thirteen,fourteen,fifteen,sixteen,seventeen,eighteen,nineteen,twenty".split(',')
    tens = "ten,twenty,thirty,fourty,fifty,sixty,seventy,eighty,ninety".split(',')
    text = ""
    if len(str(no))<=2:
        if(no<20):
            text = ones[no]
        else:
            text = tens[no//10-1] +" " + ones[(no %10)]
    elif len(str(no))==3:
        text = ones[no//100] +" hundred " + numberToText(no- ((no//100)* 100))
    elif len(str(no))<=5:
        text = numberToText(no//1000) +" thousand " + numberToText(no- ((no//1000)* 1000))
    elif len(str(no))<=7:
        text = numberToText(no//100000) +" lakh " + numberToText(no- ((no//100000)* 100000))
    else:
        text = numberToText(no//10000000) +" crores " + numberToText(no- ((no//10000000)* 10000000))
    return text

makefile execute another target

Actually you are right: it runs another instance of make. A possible solution would be:

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : clean clearscr all

clearscr:
    clear

By calling make fresh you get first the clean target, then the clearscreen which runs clear and finally all which does the job.

EDIT Aug 4

What happens in the case of parallel builds with make’s -j option? There's a way of fixing the order. From the make manual, section 4.2:

Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites

The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).

Hence the makefile becomes

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : | clean clearscr all

clearscr:
    clear

EDIT Dec 5

It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.

log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)

install:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  command1  # this line will be a subshell
  command2  # this line will be another subshell
  @command3  # Use `@` to hide the command line
  $(call log_error, "It works, yey!")

uninstall:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  ....
  $(call log_error, "Nuked!")

Android Studio - Importing external Library/Jar

you export the project from Eclipse and then import the project from Android Studio, this should solve your problem, open a eclipse project without importing it from Android Studio you can cause problems, look at: (Excuse my language, I speak Spanish.) http://developer.android.com/intl/es/sdk/installing/migrate.html

How to initialize private static members in C++?

Also working in privateStatic.cpp file :

#include <iostream>

using namespace std;

class A
{
private:
  static int v;
};

int A::v = 10; // possible initializing

int main()
{
A a;
//cout << A::v << endl; // no access because of private scope
return 0;
}

// g++ privateStatic.cpp -o privateStatic && ./privateStatic

Bootstrap 4 dropdown with search

As of version 1.13.1 there is support for Bootstrap 4: https://developer.snapappointments.com/bootstrap-select/

The implementation remains exactly the same as it was in Bootstrap 3:

  • add class="selectpicker" and data-live-search="true"to your select
  • add data-tokens to your options. The live search will look into these data-token element when performing the search.

This is an example, taken from the site of the link above:

<select class="selectpicker" data-live-search="true">
  <option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
  <option data-tokens="mustard">Burger, Shake and a Smile</option>
  <option data-tokens="frosting">Sugar, Spice and all things nice</option>
</select>

Live search for the search term 'fro' will only leave the third option visible (because of the data-tokens "frosting").

Don't forget to include the bootstrap-select CDN .css and .js in your project. I am very glad to see this live search become available again, because it comes in very handy when presenting large dropdown lists to the user.

How do you iterate through every file/directory recursively in standard C++?

You need to call OS-specific functions for filesystem traversal, like open() and readdir(). The C standard does not specify any filesystem-related functions.

Aligning textviews on the left and right edges in Android layout

enter image description here

This Code will Divide the control into two equal sides.

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
    <TextView
        android:text = "Left Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtLeft"/>

    <TextView android:text = "Right Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtRight"/>
    </LinearLayout>

Getting list of items inside div using Selenium Webdriver

You're asking for all the elements of class facetContainerDiv, of which there is only one (your outer-most div). Why not do

List<WebElement> checks =  driver.findElements(By.class("facetCheck"));
// click the 3rd checkbox
checks.get(2).click();

How to pass prepareForSegue: an object

I've implemented a library with a category on UIViewController that simplifies this operation. Basically, you set the parameters you want to pass over in a NSDictionary associated to the UI item that is performing the segue. It works with manual segues too.

For example, you can do

[self performSegueWithIdentifier:@"yourIdentifier" parameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

for a manual segue or create a button with a segue and use

[button setSegueParameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

If destination view controller is not key-value coding compliant for a key, nothing happens. It works with key-values too (useful for unwind segues). Check it out here https://github.com/stefanomondino/SMQuickSegue

placeholder for select tag

<select>

    <option selected="selected" class="Country">Country Name</option>

    <option value="1">India</option>

    <option value="2">us</option>

</select>

.country
{


    display:none;
}

</style>

ASP MVC href to a controller/view

how about

<li>
<a href="@Url.Action("Index", "Users")" class="elements"><span>Clients</span></a>
</li>

How to obtain a Thread id in Python?

The thread.get_ident() function returns a long integer on Linux. It's not really a thread id.

I use this method to really get the thread id on Linux:

import ctypes
libc = ctypes.cdll.LoadLibrary('libc.so.6')

# System dependent, see e.g. /usr/include/x86_64-linux-gnu/asm/unistd_64.h
SYS_gettid = 186

def getThreadId():
   """Returns OS thread id - Specific to Linux"""
   return libc.syscall(SYS_gettid)

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

I can confirm that in Android Studio 1.x (here AS) on Windows also the right sequence is:

  • File -> New
  • AS opens a list where you must click on Image Asset
  • AS opens a dialog where the app\src\main\res Directory Structure is automatically selected (the right choice)
  • Clicking on the OK button, AS opens the Asset Studio dialog where you can find all the tools and options we had on the past Eclipse ADT

This can be done absolutely in any moments after creation of the project.

Android Studio warns you that it will overwrite the current ic_launcer, but this is exactly what we expect to do.

Regular expressions in C: examples?

This is an example of using REG_EXTENDED. This regular expression

"^(-)?([0-9]+)((,|.)([0-9]+))?\n$"

Allows you to catch decimal numbers in Spanish system and international. :)

#include <regex.h>
#include <stdlib.h>
#include <stdio.h>
regex_t regex;
int reti;
char msgbuf[100];

int main(int argc, char const *argv[])
{
    while(1){
        fgets( msgbuf, 100, stdin );
        reti = regcomp(&regex, "^(-)?([0-9]+)((,|.)([0-9]+))?\n$", REG_EXTENDED);
        if (reti) {
            fprintf(stderr, "Could not compile regex\n");
            exit(1);
        }

        /* Execute regular expression */
        printf("%s\n", msgbuf);
        reti = regexec(&regex, msgbuf, 0, NULL, 0);
        if (!reti) {
            puts("Match");
        }
        else if (reti == REG_NOMATCH) {
            puts("No match");
        }
        else {
            regerror(reti, &regex, msgbuf, sizeof(msgbuf));
            fprintf(stderr, "Regex match failed: %s\n", msgbuf);
            exit(1);
        }

        /* Free memory allocated to the pattern buffer by regcomp() */
        regfree(&regex);
    }

}

Export/import jobs in Jenkins

Jenkins has a rather good wiki, albeit hard to read when you're new to CI software...

They offer a simple solution for moving jobs between servers

The trick probably was the need to reload config from the Jenkins Configuration Page.

Update 2020.03.10

The JenkinsCI landscape has changed a lot... I've been using Job DSL for a while now. We have a SEED Job that generates the rest of the jobs.

This helps us both recreate or move for the Jenkins server whenever needed :) You could also version those files for even more maintainability!

How do I use FileSystemObject in VBA?

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

Understanding REST: Verbs, error codes, and authentication

Simply put, you are doing this completely backward.

You should not be approaching this from what URLs you should be using. The URLs will effectively come "for free" once you've decided upon what resources are necessary for your system AND how you will represent those resources, and the interactions between the resources and application state.

To quote Roy Fielding

A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]

Folks always start with the URIs and think this is the solution, and then they tend to miss a key concept in REST architecture, notably, as quoted above, "Failure here implies that out-of-band information is driving interaction instead of hypertext."

To be honest, many see a bunch of URIs and some GETs and PUTs and POSTs and think REST is easy. REST is not easy. RPC over HTTP is easy, moving blobs of data back and forth proxied through HTTP payloads is easy. REST, however, goes beyond that. REST is protocol agnostic. HTTP is just very popular and apt for REST systems.

REST lives in the media types, their definitions, and how the application drives the actions available to those resources via hypertext (links, effectively).

There are different view about media types in REST systems. Some favor application specific payloads, while others like uplifting existing media types in to roles that are appropriate for the application. For example, on the one hand you have specific XML schemas designed suited to your application versus using something like XHTML as your representation, perhaps through microformats and other mechanisms.

Both approaches have their place, I think, the XHTML working very well in scenarios that overlap both the human driven and machine driven web, whereas the former, more specific data types I feel better facilitate machine to machine interactions. I find the uplifting of commodity formats can make content negotiation potentially difficult. "application/xml+yourresource" is much more specific as a media type than "application/xhtml+xml", as the latter can apply to many payloads which may or may not be something a machine client is actually interested in, nor can it determine without introspection.

However, XHTML works very well (obviously) in the human web where web browsers and rendering is very important.

You application will guide you in those kinds of decisions.

Part of the process of designing a REST system is discovering the first class resources in your system, along with the derivative, support resources necessary to support the operations on the primary resources. Once the resources are discovered, then the representation of those resources, as well as the state diagrams showing resource flow via hypertext within the representations because the next challenge.

Recall that each representation of a resource, in a hypertext system, combines both the actual resource representation along with the state transitions available to the resource. Consider each resource a node in a graph, with the links being the lines leaving that node to other states. These links inform clients not only what can be done, but what is required for them to be done (as a good link combines the URI and the media type required).

For example, you may have:

<link href="http://example.com/users" rel="users" type="application/xml+usercollection"/>
<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>

Your documentation will talk about the rel field named "users", and the media type of "application/xml+youruser".

These links may seem redundant, they're all talking to the same URI, pretty much. But they're not.

This is because for the "users" relation, that link is talking about the collection of users, and you can use the uniform interface to work with the collection (GET to retrieve all of them, DELETE to delete all of them, etc.)

If you POST to this URL, you will need to pass a "application/xml+usercollection" document, which will probably only contain a single user instance within the document so you can add the user, or not, perhaps, to add several at once. Perhaps your documentation will suggest that you can simply pass a single user type, instead of the collection.

You can see what the application requires in order to perform a search, as defined by the "search" link and it's mediatype. The documentation for the search media type will tell you how this behaves, and what to expect as results.

The takeaway here, though, is the URIs themselves are basically unimportant. The application is in control of the URIs, not the clients. Beyond a few 'entry points', your clients should rely on the URIs provided by the application for its work.

The client needs to know how to manipulate and interpret the media types, but doesn't much need to care where it goes.

These two links are semantically identical in a clients eyes:

<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>
<link href="http://example.com/AW163FH87SGV" rel="search" type="application/xml+usersearchcriteria"/>

So, focus on your resources. Focus on their state transitions in the application and how that's best achieved.

Why would you use String.Equals over ==?

It's entirely likely that a large portion of the developer base comes from a Java background where using == to compare strings is wrong and doesn't work.

In C# there's no (practical) difference (for strings) as long as they are typed as string.

If they are typed as object or T then see other answers here that talk about generic methods or operator overloading as there you definitely want to use the Equals method.

List all of the possible goals in Maven 2?

Is it possible to list all of the possible goals (including, say, all the plugins) that it is possible to run?

Maven doesn't have anything built-in for that, although the list of phases is finite (the list of plugin goals isn't since the list of plugins isn't).

But you can make things easier and leverage the power of bash completion (using cygwin if you're under Windows) as described in the Guide to Maven 2.x auto completion using BASH (but before to choose the script from this guide, read further).

To get things working, first follow this guide to setup bash completion on your computer. Then, it's time to get a script for Maven2 and:

  • While you could use the one from the mini guide
  • While you use an improved version attached to MNG-3928
  • While you could use a random scripts found around the net (see the resources if you're curious)
  • I personally use the Bash Completion script from Ludovic Claude's PPA (which is bundled into the packaged version of maven in Ubuntu) that you can download from the HEAD. It's simply the best one.

Below, here is what I get just to illustrate the result:

$ mvn [tab][tab]
Display all 377 possibilities? (y or n)
ant:ant 
ant:clean 
ant:help 
antrun:help 
antrun:run 
archetype:crawl 
archetype:create 
archetype:create-from-project 
archetype:generate 
archetype:help 
assembly:assembly 
assembly:directory 
assembly:directory-single 
assembly:help 
assembly:single  
... 

Of course, I never browse the 377 possibilities, I use completion. But this gives you an idea about the size of "a" list :)

Resources

java get file size efficiently

In response to rgrig's benchmark, the time taken to open/close the FileChannel & RandomAccessFile instances also needs to be taken into account, as these classes will open a stream for reading the file.

After modifying the benchmark, I got these results for 1 iterations on a 85MB file:

file totalTime: 48000 (48 us)
raf totalTime: 261000 (261 us)
channel totalTime: 7020000 (7 ms)

For 10000 iterations on same file:

file totalTime: 80074000 (80 ms)
raf totalTime: 295417000 (295 ms)
channel totalTime: 368239000 (368 ms)

If all you need is the file size, file.length() is the fastest way to do it. If you plan to use the file for other purposes like reading/writing, then RAF seems to be a better bet. Just don't forget to close the file connection :-)

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;

public class FileSizeBench
{    
    public static void main(String[] args) throws Exception
    {
        int iterations = 1;
        String fileEntry = args[0];

        Map<String, Long> times = new HashMap<String, Long>();
        times.put("file", 0L);
        times.put("channel", 0L);
        times.put("raf", 0L);

        long fileSize;
        long start;
        long end;
        File f1;
        FileChannel channel;
        RandomAccessFile raf;

        for (int i = 0; i < iterations; i++)
        {
            // file.length()
            start = System.nanoTime();
            f1 = new File(fileEntry);
            fileSize = f1.length();
            end = System.nanoTime();
            times.put("file", times.get("file") + end - start);

            // channel.size()
            start = System.nanoTime();
            channel = new FileInputStream(fileEntry).getChannel();
            fileSize = channel.size();
            channel.close();
            end = System.nanoTime();
            times.put("channel", times.get("channel") + end - start);

            // raf.length()
            start = System.nanoTime();
            raf = new RandomAccessFile(fileEntry, "r");
            fileSize = raf.length();
            raf.close();
            end = System.nanoTime();
            times.put("raf", times.get("raf") + end - start);
        }

        for (Map.Entry<String, Long> entry : times.entrySet()) {
            System.out.println(entry.getKey() + " totalTime: " + entry.getValue() + " (" + getTime(entry.getValue()) + ")");
        }
    }

    public static String getTime(Long timeTaken)
    {
        if (timeTaken < 1000) {
            return timeTaken + " ns";
        } else if (timeTaken < (1000*1000)) {
            return timeTaken/1000 + " us"; 
        } else {
            return timeTaken/(1000*1000) + " ms";
        } 
    }
}

How to solve the memory error in Python

Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:

In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75

Doing some rough math:

75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB

So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.

If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.

Evaluate empty or null JSTL c tags

This code is correct but if you entered a lot of space (' ') instead of null or empty string return false.

To correct this use regular expresion (this code below check if the variable is null or empty or blank the same as org.apache.commons.lang.StringUtils.isNotBlank) :

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
        <c:if test="${not empty description}">
            <c:set var="description" value="${fn:replace(description, ' ', '')}" />
            <c:if test="${not empty description}">
                  The description is not blank.
            </c:if>
        </c:if>

Multiple "order by" in LINQ

I have created some extension methods (below) so you don't have to worry if an IQueryable is already ordered or not. If you want to order by multiple properties just do it as follows:

// We do not have to care if the queryable is already sorted or not. 
// The order of the Smart* calls defines the order priority
queryable.SmartOrderBy(i => i.Property1).SmartOrderByDescending(i => i.Property2);

This is especially helpful if you create the ordering dynamically, f.e. from a list of properties to sort.

public static class IQueryableExtension
{
    public static bool IsOrdered<T>(this IQueryable<T> queryable) {
        if(queryable == null) {
            throw new ArgumentNullException("queryable");
        }

        return queryable.Expression.Type == typeof(IOrderedQueryable<T>);
    }

    public static IQueryable<T> SmartOrderBy<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenBy(keySelector);
        } else {
            return queryable.OrderBy(keySelector);
        }
    }

    public static IQueryable<T> SmartOrderByDescending<T, TKey>(this IQueryable<T> queryable, Expression<Func<T, TKey>> keySelector) {
        if(queryable.IsOrdered()) {
            var orderedQuery = queryable as IOrderedQueryable<T>;
            return orderedQuery.ThenByDescending(keySelector);
        } else {
            return queryable.OrderByDescending(keySelector);
        }
    }
}

How to len(generator())

You can combine the benefits of generators with the certainty of len(), by creating your own iterable object:

class MyIterable(object):
    def __init__(self, n):
        self.n = n

    def __len__(self):
        return self.n

    def __iter__(self):
        self._gen = self._generator()
        return self

    def _generator(self):
        # Put your generator code here
        i = 0
        while i < self.n:
            yield i
            i += 1

    def next(self):
        return next(self._gen)

mi = MyIterable(100)
print len(mi)
for i in mi:
    print i,

This is basically a simple implementation of xrange, which returns an object you can take the len of, but doesn't create an explicit list.

How to make Apache serve index.php instead of index.html?

PHP will work only on the .php file extension.

If you are on Apache you can also set, in your httpd.conf file, the extensions for PHP. You'll have to find the line:

AddType application/x-httpd-php .php .html
                                     ^^^^^

and add how many extensions, that should be read with the PHP interpreter, as you want.

Compile c++14-code with g++

For gcc 4.8.4 you need to use -std=c++1y in later versions, looks like starting with 5.2 you can use -std=c++14.

If we look at the gcc online documents we can find the manuals for each version of gcc and we can see by going to Dialect options for 4.9.3 under the GCC 4.9.3 manual it says:

‘c++1y’

The next revision of the ISO C++ standard, tentatively planned for 2014. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.

So up till 4.9.3 you had to use -std=c++1y while the gcc 5.2 options say:

‘c++14’ ‘c++1y’

The 2014 ISO C++ standard plus amendments. The name ‘c++1y’ is deprecated.

It is not clear to me why this is listed under Options Controlling C Dialect but that is how the documents are currently organized.

Map and Reduce in .NET

The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

var wordOccurrences = words
                .GroupBy(w => w)
                .Select(intermediate => new
                {
                    Word = intermediate.Key,
                    Frequency = intermediate.Sum(w => 1)
                })
                .Where(w => w.Frequency > 10)
                .OrderBy(w => w.Frequency);

For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

How do I install a plugin for vim?

Make sure that the actual .vim file is in ~/.vim/plugin/

How do I get a TextBox to only accept numeric input in WPF?

We can do validation on text box changed event. The following implementation prevents keypress input other than numeric and one decimal point.

private void textBoxNumeric_TextChanged(object sender, TextChangedEventArgs e) 
{         
      TextBox textBox = sender as TextBox;         
      Int32 selectionStart = textBox.SelectionStart;         
      Int32 selectionLength = textBox.SelectionLength;         
      String newText = String.Empty;         
      int count = 0;         
      foreach (Char c in textBox.Text.ToCharArray())         
      {             
         if (Char.IsDigit(c) || Char.IsControl(c) || (c == '.' && count == 0))             
         {                 
            newText += c;                 
            if (c == '.')                     
              count += 1;             
         }         
     }         
     textBox.Text = newText;         
     textBox.SelectionStart = selectionStart <= textBox.Text.Length ? selectionStart :        textBox.Text.Length;     
} 

Checking whether a variable is an integer or not

It is very simple to check in python. You can do like this:

Suppose you want to check a variable is integer or not!

## For checking a variable is integer or not in python

if type(variable) is int:
     print("This line will be executed")
else:
     print("Not an integer")

Postgresql tables exists, but getting "relation does not exist" when querying

I had to include double quotes with the table name.

db=> \d
                           List of relations
 Schema |                     Name                      | Type  | Owner 
--------+-----------------------------------------------+-------+-------
 public | COMMONDATA_NWCG_AGENCIES                      | table | dan
 ...

db=> \d COMMONDATA_NWCG_AGENCIES
Did not find any relation named "COMMONDATA_NWCG_AGENCIES".

???

Double quotes:

db=> \d "COMMONDATA_NWCG_AGENCIES"
                         Table "public.COMMONDATA_NWCG_AGENCIES"
          Column          |            Type             | Collation | Nullable | Default 
--------------------------+-----------------------------+-----------+----------+---------
 ID                       | integer                     |           | not null | 
 ...

Lots and lots of double quotes:

db=> select ID from COMMONDATA_NWCG_AGENCIES limit 1;
ERROR:  relation "commondata_nwcg_agencies" does not exist
LINE 1: select ID from COMMONDATA_NWCG_AGENCIES limit 1;
                       ^
db=> select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
ERROR:  column "id" does not exist
LINE 1: select ID from "COMMONDATA_NWCG_AGENCIES" limit 1;
               ^
db=> select "ID" from "COMMONDATA_NWCG_AGENCIES" limit 1;
 ID 
----
  1
(1 row)

This is postgres 11. The CREATE TABLE statements from this dump had double quotes as well:

DROP TABLE IF EXISTS "COMMONDATA_NWCG_AGENCIES";

CREATE TABLE "COMMONDATA_NWCG_AGENCIES" (
...

How do I replace multiple spaces with a single space in C#?

try this method

private string removeNestedWhitespaces(char[] st)
{
    StringBuilder sb = new StringBuilder();
    int indx = 0, length = st.Length;
    while (indx < length)
    {
        sb.Append(st[indx]);
        indx++;
        while (indx < length && st[indx] == ' ')
            indx++;
        if(sb.Length > 1  && sb[0] != ' ')
            sb.Append(' ');
    }
    return sb.ToString();
}

use it like this:

string test = removeNestedWhitespaces("1 2 3  4    5".toCharArray());

How to POST a FORM from HTML to ASPX page

The Request.Form.Keys collection will be empty if none of your html inputs have NAMEs. It's easy to forget to put them there after you've been doing .NET for a while. Just name them and you'll be good to go.

Launch Pycharm from command line (terminal)

Easy solution without need for pathes:

open -b com.jetbrains.pycharm



You can set it as alias for every-day easier usage (put to your .bash_rc etc.):

alias pycharm='open -b com.jetbrains.pycharm'

Usage:

pycharm .
pycharm file.py

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If you are using windows just go to control panel, click on automatic updates then click on Windows Update Web Site link. Just follow the step. At least this works for me, no more certificates issue i.e whenever I go to https://www.dropbox.com as before.

Convert array of indices to 1-hot encoded numpy array

I am adding for completion a simple function, using only numpy operators:

   def probs_to_onehot(output_probabilities):
        argmax_indices_array = np.argmax(output_probabilities, axis=1)
        onehot_output_array = np.eye(np.unique(argmax_indices_array).shape[0])[argmax_indices_array.reshape(-1)]
        return onehot_output_array

It takes as input a probability matrix: e.g.:

[[0.03038822 0.65810204 0.16549407 0.3797123 ] ... [0.02771272 0.2760752 0.3280924 0.33458805]]

And it will return

[[0 1 0 0] ... [0 0 0 1]]

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Forward host port to docker container

If MongoDB and RabbitMQ are running on the Host, then the port should already exposed as it is not within Docker.

You do not need the -p option in order to expose ports from container to host. By default, all port are exposed. The -p option allows you to expose a port from the container to the outside of the host.

So, my guess is that you do not need -p at all and it should be working fine :)

Selecting element by data attribute with jQuery

To select all anchors with the data attribute data-customerID==22, you should include the a to limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.

$('a[data-customerID="22"]');

Javascript to open popup window and disable parent window

var popupWindow=null;

function popup()
{
    popupWindow = window.open('child_page.html','name','width=200,height=200');
}

function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}

and then declare these functions in the body tag of parent window

<body onFocus="parent_disable();" onclick="parent_disable();">

As you requested here is the complete html code of the parent window

<html>
<head>
<script type="text/javascript">

var popupWindow=null;

function child_open()
{ 

popupWindow =window.open('new.jsp',"_blank","directories=no, status=no, menubar=no, scrollbars=yes, resizable=no,width=600, height=280,top=200,left=200");

}
function parent_disable() {
if(popupWindow && !popupWindow.closed)
popupWindow.focus();
}
</script>
</head>
<body onFocus="parent_disable();" onclick="parent_disable();">
    <a href="javascript:child_open()">Click me</a>
</body>    
</html>

Content of new.jsp below

<html>
<body>
I am child
</body>
</html>

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

SPA best practices for authentication and session management

You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.

The Basic Auth / Session ID can be stolen via:

  • MITM attack (Man-In-The-Middle) - without SSL/HTTPS
  • An intruder gaining access to a user's computer
  • XSS

By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.

The new (more secure) flow would be:

Login

  • User logs in and sends login credentials to API (over SSL/HTTPS)
  • API receives login credentials
  • If valid:
    • Register a new session in the database Read update
    • Encrypt User ID, Session ID, IP address, timestamp, etc. in a JWT with a private key.
  • API sends the JWT token back to the client (over SSL/HTTPS)
  • Client receives the JWT token and stores in localStorage/cookie

Every request to API

  • User sends a HTTP request to API (over SSL/HTTPS) with the stored JWT token in the HTTP header
  • API reads HTTP header and decrypts JWT token with its private key
  • API validates the JWT token, matches the IP address from the HTTP request with the one in the JWT token and checks if session has expired
  • If valid:
    • Return response with requested content
  • If invalid:
    • Throw exception (403 / 401)
    • Flag intrusion in the system
    • Send a warning email to the user.

Updated 30.07.15:

JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).

I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).

Updated 17.07.16:

JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.

Add an element to an array in Swift

Here is a small extension if you wish to insert at the beginning of the array without loosing the item at the first position

extension Array{
    mutating func appendAtBeginning(newItem : Element){
        let copy = self
        self = []
        self.append(newItem)
        self.appendContentsOf(copy)
    }
}

How to do parallel programming in Python?

CPython uses the Global Interpreter Lock which makes parallel programing a bit more interesting than C++

This topic has several useful examples and descriptions of the challenge:

Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?

CSS scrollbar style cross browser

As of IE6 I believe you cannot customize the scroll bar using those properties. The Chris Coyier article linked to above goes into nice detail about the options for webkit proprietary css for customizing the scroll bar.

If you really want a cross browser solution that you can fully customize you're going to have to use some JS. Here is a link to a nice plugin for it called FaceScroll: http://www.dynamicdrive.com/dynamicindex11/facescroll/index.htm

Java ArrayList replace at specific index

We can replace element in arraylist using ArrayList Set() method.We are a example for this as below.

Create Arraylist

 ArrayList<String> arr = new ArrayList<String>();
 arr.add("c");
 arr.add("php");
 arr.add("html");
 arr.add("java");

Now replcae Element on index 2

 arr.set(2,"Mysql");
 System.out.println("after replace arrayList is = " + arr);

OutPut :

 after replace arrayList is = [c, php, Mysql, java]

Reference :

Replace element in ArrayList

Referring to a Column Alias in a WHERE Clause

HAVING works in MySQL according to documentation:

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

SVN Commit specific files

Use changelists. The advantage over specifying files is that you can visualize and confirm everything you wanted is actually included before you commit.

$ svn changelist fix-issue-237 foo.c 
Path 'foo.c' is now a member of changelist 'fix-issue-237'.

That done, svn now keeps things separate for you. This helps when you're juggling multiple changes

$ svn status
A       bar.c
A       baz.c

--- Changelist 'fix-issue-237':
A       foo.c

Finally, tell it to commit what you wanted changed.

$ svn commit --changelist fix-issue-237 -m "Issue 237"

ImportError: No module named tensorflow

Try installing tensorflow again with the whatever version you want and with option --ignore-installed like:

pip install tensorflow==1.2.0 --ignore-installed

I solved same issue using this command.

How to upload a file from Windows machine to Linux machine using command lines via PuTTy?

Pscp.exe is painfully slow.

Uploading files using WinSCP is like 10 times faster.

So, to do that from command line, first you got to add the winscp.com file to your %PATH%. It's not a top-level domain, but an executable .com file, which is located in your WinSCP installation directory.

Then just issue a simple command and your file will be uploaded much faster putty ever could:

WinSCP.com /command "open sftp://username:[email protected]:22" "put your_large_file.zip /var/www/somedirectory/" "exit"

And make sure your check the synchronize folders feature, which is basically what rsync does, so you won't ever want to use pscp.exe again.

WinSCP.com /command "help synchronize"

DateTime's representation in milliseconds?

You're probably trying to convert to a UNIX-like timestamp, which are in UTC:

yourDateTime.ToUniversalTime().Subtract(
    new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    ).TotalMilliseconds

This also avoids summertime issues, since UTC doesn't have those.

A Java collection of value pairs? (tuples?)

The preferred solution as you've described it is a List of Pairs (i.e. List).

To accomplish this you would create a Pair class for use in your collection. This is a useful utility class to add to your code base.

The closest class in the Sun JDK providing functionality similar to a typical Pair class is AbstractMap.SimpleEntry. You could use this class rather than creating your own Pair class, though you would have to live with some awkward restrictions and I think most people would frown on this as not really the intended role of SimpleEntry. For example SimpleEntry has no "setKey()" method and no default constructor, so you may find it too limiting.

Bear in mind that Collections are designed to contain elements of a single type. Related utility interfaces such as Map are not actually Collections (i.e. Map does not implement the Collection interface). A Pair would not implement the Collection interface either but is obviously a useful class in building larger data structures.

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

How do I compare strings in GoLang?

The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like \n, \r, spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.