Programs & Examples On #Background application

Installing the Android USB Driver in Windows 7

Just download and install "Samsung Kies" from this link. and everything would work as required.

Before installing, uninstall the drivers you have installed for your device.

Update:

Two possible solutions:

  1. Try with the Google USB driver which comes with the SDK.
  2. Download and install the Samsung USB driver from this link as suggested by Mauricio Gracia Gutierrez

Postgresql, update if row with some unique value exists, else insert

This has been asked many times. A possible solution can be found here: https://stackoverflow.com/a/6527838/552671

This solution requires both an UPDATE and INSERT.

UPDATE table SET field='C', field2='Z' WHERE id=3;
INSERT INTO table (id, field, field2)
       SELECT 3, 'C', 'Z'
       WHERE NOT EXISTS (SELECT 1 FROM table WHERE id=3);

With Postgres 9.1 it is possible to do it with one query: https://stackoverflow.com/a/1109198/2873507

What's the best way to join on the same table twice?

You could use UNION to combine two joins:

SELECT Table1.PhoneNumber1 as PhoneNumber, Table2.SomeOtherField as OtherField
  FROM Table1
  JOIN Table2
    ON Table1.PhoneNumber1 = Table2.PhoneNumber
 UNION
SELECT Table1.PhoneNumber2 as PhoneNumber, Table2.SomeOtherField as OtherField
  FROM Table1
  JOIN Table2
    ON Table1.PhoneNumber2 = Table2.PhoneNumber

Best way to get hostname with php

I am running PHP version 5.4 on shared hosting and both of these both successfully return the same results:

php_uname('n');

gethostname();

How to change font in ipython notebook

The new location of the theme file is: ~/.jupyter/custom/custom.css

Ruby replace string with captured regex pattern

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"

How to determine the screen width in terms of dp or dip at runtime in Android?

Simplified for Kotlin:

val widthDp = resources.displayMetrics.run { widthPixels / density }
val heightDp = resources.displayMetrics.run { heightPixels / density }

How to hide a mobile browser's address bar?

You can go to fullscreen when user allows it :)

<button id="goFS">Go fullscreen</button>
<script>
  var goFS = document.getElementById("goFS");
  goFS.addEventListener("click", function() {
      
   const elem = document.documentElement;
   if (elem.requestFullscreen) {elem.requestFullscreen()}
   
  }, false);
</script>

Easy way to password-protect php page

This is a bit late but I wanted to reply in case anyone else came upon this page and found that the highest reply was a bit off. I have improved upon the system just a tad bit. Note, it is still not amazingly secure but it is an improvement.

First prepare your password salts file:

hash_generate.php:

 <?php

 $user = "Username"; // please replace with your user
 $pass = "Password"; // please replace with your passwd
 // two ; was missing

 $useroptions = ['cost' => 8,];
 $userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions);
 $pwoptions   = ['cost' => 8,];
 $passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);

 echo $userhash;
 echo "<br />";
 echo $passhash;

 ?>

Take your output $userhash and $passhash and put them in two text files: user.txt and pass.txt, respectively. Others have suggested putting these text files away above public_html, this is a good idea but I just used .htaccess and stored them in a folder called "stuff"

.htaccess

 deny from all

Now no one can peek into the hash. Next up is your index.php:

index.php:

<?php
$user = ""; //prevent the "no index" error from $_POST
$pass = "";
if (isset($_POST['user'])) { // check for them and set them so
    $user = $_POST['user'];
}
if (isset($_POST['pass'])) { // so that they don't return errors
    $pass = $_POST['pass'];
}    

$useroptions = ['cost' => 8,]; // all up to you
$pwoptions   = ['cost' => 8,]; // all up to you
$userhash    = password_hash($user, PASSWORD_BCRYPT, $useroptions); // hash entered user
$passhash    = password_hash($pass, PASSWORD_BCRYPT, $pwoptions);  // hash entered pw
$hasheduser  = file_get_contents("stuff/user.txt"); // this is our stored user
$hashedpass  = file_get_contents("stuff/pass.txt"); // and our stored password


if ((password_verify($user, $hasheduser)) && (password_verify($pass,$hashedpass))) {

    // the password verify is how we actually login here
    // the $userhash and $passhash are the hashed user-entered credentials
    // password verify now compares our stored user and pw with entered user and pw

    include "pass-protected.php";

} else { 
    // if it was invalid it'll just display the form, if there was never a $_POST
    // then it'll also display the form. that's why I set $user to "" instead of a $_POST
    // this is the right place for comments, not inside html
    ?>  
    <form method="POST" action="index.php">
    User <input type="text" name="user"></input><br/>
    Pass <input type="password" name="pass"></input><br/>
    <input type="submit" name="submit" value="Go"></input>
    </form>
    <?php 
} 

Add ArrayList to another ArrayList in java

Your Problem

Mainly, you've got 2 major problems:

You are using adding a List of Strings. You want a List containing Lists of Strings.

Note as well that when you invoke this:

NodeList.addAll(nodes);

... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList, which is using Objects and thus adds only the strings inside. Which leads me to the next point.

You seem to be confused between your nodes and NodeList. Your NodeList keeps growing over time, and that's what you add to your list.

So, even if doing things right, if we were to look at the end of each iteration at your nodes, nodeList and list, we'd see:

  • i = 0

    nodes: [PropertyStart,a,b,c,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd]]
    
  • i = 1

    nodes: [PropertyStart,d,e,f,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]
    
  • i = 2

    nodes: [PropertyStart,g,h,i,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]
    
  • and so on...

Some Other Corrections

Follow the Java Naming Conventions

Don't use variable names starting with uppercase letters. So here, replace NodeList with nodeList).

Learn a Bit More About Types

You say "I want the "list" array [...]". This is confusing for whoever you will be communicating with: It's not an array. It's an implementation of List backed by an array.

There's a difference between a type, an interface, and an implementation.

Use Generics for Stronger Typing in Collections

Use generic types, because static typing really helps with these errors. Also, use interfaces where possible, except if you have a good reason to use the concrete type.

So your code becomes:

List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();

Remove Unnecessary Code

You could do away with the nodeList entirely, and write the following once you've fixed your types:

list.add(nodes);

Use the Right Scope

Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.

Here you could then move List<String> nodes to be declared within the loop (and then forget the nodes.clear() invocation).

A reason not to do this could be performance, as you might want to avoid recreating an ArrayList on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code).

SSCCE

Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example.

Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list). And you confused a lot of people, as I think the output you give us is not what you actually got.

"Sources directory is already netbeans project" error when opening a project from existing sources

On Windows at least none of these answers work (for me anyway!). I have found the only way is to copy an existing netbeans project folder in to your new project and manually edit the xml project name.

I also opened the private/private.xml and removed the open files xml just incase these caused problems.

Once I'd done this the project works as normal.

is python capable of running on multiple cores?

Threads share a process and a process runs on a core, but you can use python's multiprocessing module to call your functions in separate processes and use other cores, or you can use the subprocess module, which can run your code and non-python code too.

How do I create a unique constraint that also allows nulls?

You can't do this with a UNIQUE constraint, but you can do this in a trigger.

    CREATE TRIGGER [dbo].[OnInsertMyTableTrigger]
   ON  [dbo].[MyTable]
   INSTEAD OF INSERT
AS 
BEGIN
    SET NOCOUNT ON;

    DECLARE @Column1 INT;
    DECLARE @Column2 INT; -- allow nulls on this column

    SELECT @Column1=Column1, @Column2=Column2 FROM inserted;

    -- Check if an existing record already exists, if not allow the insert.
    IF NOT EXISTS(SELECT * FROM dbo.MyTable WHERE Column1=@Column1 AND Column2=@Column2 @Column2 IS NOT NULL)
    BEGIN
        INSERT INTO dbo.MyTable (Column1, Column2)
            SELECT @Column2, @Column2;
    END
    ELSE
    BEGIN
        RAISERROR('The unique constraint applies on Column1 %d, AND Column2 %d, unless Column2 is NULL.', 16, 1, @Column1, @Column2);
        ROLLBACK TRANSACTION;   
    END

END

WCF named pipe minimal example

I just found this excellent little tutorial. broken link (Cached version)

I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.

As you can see, you don't need configuration files and all that messy stuff.

By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.

getting the ng-object selected with ng-change

If Divyesh Rupawala's answer doesn't work (passing the current item as the parameter), then please see the onChanged() function in this Plunker. It's using this:

http://plnkr.co/edit/B5TDQJ

How to remove the border highlight on an input text element

You can remove the orange or blue border (outline) around text/input boxes by using: outline:none

input {
    background-color: transparent;
    border: 0px solid;
    height: 20px;
    width: 160px;
    color: #CCC;
    outline:none !important;
}

push multiple elements to array

If you want an alternative to Array.concat in ECMAScript 2015 (a.k.a. ES6, ES2015) that, like it, does not modify the array but returns a new array you can use the spread operator like so:

_x000D_
_x000D_
var arr = [1];_x000D_
var newItems = [2, 3];_x000D_
var newerItems = [4, 5];_x000D_
var newArr = [...arr, ...newItems, ...newerItems];_x000D_
console.log(newArr);
_x000D_
_x000D_
_x000D_

Note this is different than the push method as the push method mutates/modifies the array.

If you want to see if certain ES2015 features work in your browser check Kangax's compatibility table.

You can also use Babel or a similar transpiler if you do not want to wait for browser support and want to use ES2015 in production.

React JS - Uncaught TypeError: this.props.data.map is not a function

You don't need an array to do it.

var ItemNode = this.state.data.map(function(itemData) {
return (
   <ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
 );
});

How to change the commit author for one specific commit?

SOLUTION

  1. Install git filter-repo (Git project recommends filter-repo over filter-branch)

    $ PACKAGE_TOOL install git-filter-repo
    
  2. Create a file .mailmap in the root of the git repository containing

    New Name <[email protected]> <[email protected]>
    
  3. Run git filter-repo --use-mailmap


MORE DETAILS

  • git-filter-repo lists this as an example in their docs
  • Instead of replacing both name and email based on email filter as in example above, take a look at additional examples in git mailmap documentation
  • Instead of using default .mailmap file you can specify your own by invoking git filter-repo with argument --mailmap <filename>.
  • Many more examples on how to further filter branch/tag/whatever can be found in git-filter-repo project's README.md.

how to check redis instance version?

To support the answers given above, The details of the redis instance can be obtained by

$ redis-cli
$ INFO

This gives all the info you may need

# Server
redis_version:5.0.5
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:da75abdfe06a50f8
redis_mode:standalone
os:Linux 5.3.0-51-generic x86_64
arch_bits:64
multiplexing_api:epoll
atomicvar_api:atomic-builtin
gcc_version:7.5.0
process_id:14126
run_id:adfaeec5683d7381a2a175a2111f6159b6342830
tcp_port:6379
uptime_in_seconds:16860
uptime_in_days:0
hz:10
configured_hz:10
lru_clock:15766886
executable:/tmp/redis-5.0.5/src/redis-server
config_file:

# Clients
connected_clients:22
....More Verbose

The version lies in the second line :)

Directory.GetFiles: how to get only filename, not full path?

Have a look at using FileInfo.Name Property

something like

string[] files = Directory.GetFiles(dir); 

for (int iFile = 0; iFile < files.Length; iFile++)
    string fn = new FileInfo(files[iFile]).Name;

Also have a look at using DirectoryInfo Class and FileInfo Class

ReactJS lifecycle method inside a function Component

You can use react-pure-lifecycle to add lifecycle functions to functional components.

Example:

import React, { Component } from 'react';
import lifecycle from 'react-pure-lifecycle';

const methods = {
  componentDidMount(props) {
    console.log('I mounted! Here are my props: ', props);
  }
};

const Channels = props => (
<h1>Hello</h1>
)

export default lifecycle(methods)(Channels);

Submit HTML form on self page

In 2013, with all the HTML5 stuff, you can just omit the 'action' attribute to self-submit a form

<form>

Actually, the Form Submission subsection of the current HTML5 draft does not allow action="" (empty attribute). It is against the specification.

From this other Stack Overflow answer.

Is it necessary to assign a string to a variable before comparing it to another?

Do I really have to create an NSString for "Wrong"?

No, why not just do:

if([statusString isEqualToString:@"Wrong"]){
    //doSomething;
}

Using @"" simply creates a string literal, which is a valid NSString.

Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?

Yes, you can do something like:

UILabel *label = ...;
if([someString isEqualToString:label.text]) {
    // Do stuff here 
}

Java says FileNotFoundException but file exists

I recently found interesting case that produces FileNotFoundExeption when file is obviously exists on the disk. In my program I read file path from another text file and create File object:

//String path was read from file
System.out.println(path); //file with exactly same visible path exists on disk
File file = new File(path); 
System.out.println(file.exists());  //false
System.out.println(file.canRead());  //false
FileInputStream fis = new FileInputStream(file);  // FileNotFoundExeption 

The cause of the problem was that the path contained invisible \r\n characters at the end.

The fix in my case was:

File file = new File(path.trim()); 

To generalize a bit, the invisible / non-printing characters could have include space or tab characters, and possibly others, and they could have appeared at the beginning of the path, at the end, or embedded in the path. Trim will work in some cases but not all. There are a couple of things that you can help to spot this kind of problem:

  1. Output the pathname with quote characters around it; e.g.

      System.out.println("Check me! '" + path + "'");
    

    and carefully check the output for spaces and line breaks where they shouldn't be.

  2. Use a Java debugger to carefully examine the pathname string, character by character, looking for characters that shouldn't be there. (Also check for homoglyph characters!)

MySQL and PHP - insert NULL rather than empty string

For some reason, radhoo's solution wouldn't work for me. When I used the following expression:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')?"NULL":("'".$val1."'")) . ", ".
    (($val2=='')?"NULL":("'".$val2."'")) . 
    ")";

'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:

$query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
    (($val1=='')? :("'".$val1."'")) . ", ".
    (($val2=='')? :("'".$val2."'")) . 
    ")";

The blank resulted in the correct null (unquoted) being inserted into the query.

Why does typeof array with objects return "object" and not "array"?

One of the weird behaviour and spec in Javascript is the typeof Array is Object.

You can check if the variable is an array in couple of ways:

var isArr = data instanceof Array;
var isArr = Array.isArray(data);

But the most reliable way is:

isArr = Object.prototype.toString.call(data) == '[object Array]';

Since you tagged your question with jQuery, you can use jQuery isArray function:

var isArr = $.isArray(data);

How to run TypeScript files from command line?

This question was posted in 2015. In 2018, node recognizes both .js and .ts. So, running node file.ts will also run.

C# DataRow Empty-check

I did it like this:

var listOfRows = new List<DataRow>();
foreach (var row in resultTable.Rows.Cast<DataRow>())
{
    var isEmpty = row.ItemArray.All(x => x == null || (x!= null && string.IsNullOrWhiteSpace(x.ToString())));
    if (!isEmpty)
    {
        listOfRows.Add(row);
    }
}

How can I run an external command asynchronously from Python?

If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)

This has the advantage of servicing the early-finishing requests first. If you call communicate on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

How to run html file using node js

The simplest command by far:

npx http-server

This requires an existing index.html at the dir at where this command is being executed.

This was already mentioned by Vijaya Simha, but I thought using npx is way cleaner and shorter. I am running a webserver with this approach since months.

Docs: https://www.npmjs.com/package/http-server

Using generic std::function objects with member functions in one class

You can use functors if you want a less generic and more precise control under the hood. Example with my win32 api to forward api message from a class to another class.

IListener.h

#include <windows.h>
class IListener { 
    public:
    virtual ~IListener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) = 0;
};

Listener.h

#include "IListener.h"
template <typename D> class Listener : public IListener {
    public:
    typedef LRESULT (D::*WMFuncPtr)(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); 

    private:
    D* _instance;
    WMFuncPtr _wmFuncPtr; 

    public:
    virtual ~Listener() {}
    virtual LRESULT operator()(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) override {
        return (_instance->*_wmFuncPtr)(hWnd, uMsg, wParam, lParam);
    }

    Listener(D* instance, WMFuncPtr wmFuncPtr) {
        _instance = instance;
        _wmFuncPtr = wmFuncPtr;
    }
};

Dispatcher.h

#include <map>
#include "Listener.h"

class Dispatcher {
    private:
        //Storage map for message/pointers
        std::map<UINT /*WM_MESSAGE*/, IListener*> _listeners; 

    public:
        virtual ~Dispatcher() { //clear the map }

        //Return a previously registered callable funtion pointer for uMsg.
        IListener* get(UINT uMsg) {
            typename std::map<UINT, IListener*>::iterator itEvt;
            if((itEvt = _listeners.find(uMsg)) == _listeners.end()) {
                return NULL;
            }
            return itEvt->second;
        }

        //Set a member function to receive message. 
        //Example Button->add<MyClass>(WM_COMMAND, this, &MyClass::myfunc);
        template <typename D> void add(UINT uMsg, D* instance, typename Listener<D>::WMFuncPtr wmFuncPtr) {
            _listeners[uMsg] = new Listener<D>(instance, wmFuncPtr);
        }

};

Usage principles

class Button {
    public:
    Dispatcher _dispatcher;
    //button window forward all received message to a listener
    LRESULT onMessage(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        //to return a precise message like WM_CREATE, you have just
        //search it in the map.
        return _dispatcher[uMsg](hWnd, uMsg, w, l);
    }
};

class Myclass {
    Button _button;
    //the listener for Button messages
    LRESULT button_listener(HWND hWnd, UINT uMsg, WPARAM w, LPARAM l) {
        return 0;
    }

    //Register the listener for Button messages
    void initialize() {
        //now all message received from button are forwarded to button_listener function 
       _button._dispatcher.add(WM_CREATE, this, &Myclass::button_listener);
    }
};

Good luck and thank to all for sharing knowledge.

Build a simple HTTP server in C

Open a TCP socket on port 80, start listening for new connections, implement this. Depending on your purposes, you can ignore almost everything. At the easiest, you can send the same response for every request, which just involves writing text to the socket.

Using a scanner to accept String input and storing in a String Array

Would this work better?

import java.util.Scanner;

public class Work {

public static void main(String[] args){

    System.out.println("Please enter the following information");

    String name = "0";
    String num = "0";
    String address = "0";

    int i = 0;

    Scanner input = new Scanner(System.in);

    //The Arrays
    String [] contactName = new String [7];
    String [] contactNum = new String [7];
    String [] contactAdd = new String [7];

    //I set these as the Array titles
    contactName[0] = "Name";
    contactNum[0] = "Phone Number";
    contactAdd[0] = "Address";

    //This asks for the information and builds an Array for each
    //i -= i resets i back to 0 so the arrays are not 7,14,21+
    while (i < 6){

        i++;
        System.out.println("Enter contact name." + i);
        name = input.nextLine();
        contactName[i] = name;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact number." + i);
        num = input.nextLine();
        contactNum[i] = num;
    }

    i -= i;
    while (i < 6){
        i++;
        System.out.println("Enter contact address." + i);
        num = input.nextLine();
        contactAdd[i] = num;
    }


    //Now lets print out the Arrays
    i -= i;
    while(i < 6){
    i++;
    System.out.print( i + " " + contactName[i] + " / " );
    }

    //These are set to print the array on one line so println will skip a line
    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
    i++;

    System.out.print( i + " " + contactNum[i] + " / " );
    }

    System.out.println();
    i -= i;
    i -= 1;

    while(i < 6){
        i++;

    System.out.print( i + " " + contactAdd[i] + " / " );
    }

    System.out.println();

    System.out.println("End of program");

}

}

onClick not working on mobile (touch)

better to use touchstart event with .on() jQuery method:

$(window).load(function() { // better to use $(document).ready(function(){
    $('.List li').on('click touchstart', function() {
        $('.Div').slideDown('500');
    });
});

And i don't understand why you are using $(window).load() method because it waits for everything on a page to be loaded, this tend to be slow, while you can use $(document).ready() method which does not wait for each element on the page to be loaded first.

How to call a REST web service API from JavaScript?

Before we try to put anything on the front end of the website, let's open a connection the API. We'll do so using XMLHttpRequest objects, which is a way to open files and make an HTTP request.

We'll create a request variable and assign a new XMLHttpRequest object to it. Then we'll open a new connection with the open() method - in the arguments we'll specify the type of request as GET as well as the URL of the API endpoint. The request completes and we can access the data inside the onload function. When we're done, we'll send the request.
// Create a request variable and assign a new XMLHttpRequest object to it. var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)

request.onload = function () {
  // Begin accessing JSON data here
  }
}

// Send request
request.send()

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

How to make PopUp window in java

Hmm it has been a little while but from what I remember...
If you want a custom window you can just make a new frame and make it show up just like you would with the main window. Java also has a great dialog library that you can check out here:

How to Make Dialogs

That may be able to give you the functionality you are looking for with a whole lot less effort.

Object[] possibilities = {"ham", "spam", "yam"};
String s = (String)JOptionPane.showInputDialog(
                    frame,
                    "Complete the sentence:\n"
                    + "\"Green eggs and...\"",
                    "Customized Dialog",
                    JOptionPane.PLAIN_MESSAGE,
                    icon,
                    possibilities,
                    "ham");

//If a string was returned, say so.
if ((s != null) && (s.length() > 0)) {
    setLabel("Green eggs and... " + s + "!");
    return;
}

//If you're here, the return value was null/empty.
setLabel("Come on, finish the sentence!");

If you do not care to limit the user's choices, you can either use a form of the showInputDialog method that takes fewer arguments or specify null for the array of objects. In the Java look and feel, substituting null for possibilities results in a dialog that has a text field and looks like this:

How to map calculated properties with JPA and Hibernate

You have three options:

  • either you are calculating the attribute using a @Transient method
  • you can also use @PostLoad entity listener
  • or you can use the Hibernate specific @Formula annotation

While Hibernate allows you to use @Formula, with JPA, you can use the @PostLoad callback to populate a transient property with the result of some calculation:

@Column(name = "price")
private Double price;

@Column(name = "tax_percentage")
private Double taxes;

@Transient
private Double priceWithTaxes;

@PostLoad
private void onLoad() {
    this.priceWithTaxes = price * taxes;
}

So, you can use the Hibernate @Formula like this:

@Formula("""
    round(
       (interestRate::numeric / 100) *
       cents *
       date_part('month', age(now(), createdOn)
    )
    / 12)
    / 100::numeric
    """)
private double interestDollars;

define() vs. const

Yes, const are defined at compile-time and as nikic states cannot be assigned an expression, as define()'s can. But also const's cannot be conditionally declared (for the same reason). ie. You cannot do this:

if (/* some condition */) {
  const WHIZZ = true;  // CANNOT DO THIS!
}

Whereas you could with a define(). So, it doesn't really come down to personal preference, there is a correct and a wrong way to use both.

As an aside... I would like to see some kind of class const that can be assigned an expression, a sort of define() that can be isolated to classes?

Why are interface variables static and final by default?

Interface can be implemented by any classes and what if that value got changed by one of there implementing class then there will be mislead for other implementing classes. Interface is basically a reference to combine two corelated but different entity.so for that reason the declaring variable inside the interface will implicitly be final and also static because interface can not be instantiate.

Allowed memory size of 536870912 bytes exhausted in Laravel

I had also been through that problem. in my case, I was adding the data to the array and passing the array to the same array which brings the problem of memory limits. Some of the things you need to consider:

  1. Review our code, look if any loop is running infinity.

  2. Reduce the unwanted column if you are retrieving the data from the database.

  3. Maybe you can increase the memory limits in our XAMPP other any other software you are running.

Favorite Visual Studio keyboard shortcuts

Ctrl+I for incremental search

Android: How to rotate a bitmap on a center point

I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.

This is the method for rotating the Matrix:

this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 

(this.getCenterX() is basically the bitmaps X position + the bitmaps width / 2)

And the method for Drawing the bitmap (called via a RenderManager Class):

canvas.drawBitmap(this.bitmap, this.matrix, null);

So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate followed by postTranslate. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/

Anyways, thanks for your help!

How do I check if file exists in Makefile so I can delete it?

It may need a backslash on the end of the line for continuation (although perhaps that depends on the version of make):

if [ -a myApp ] ; \
then \
     rm myApp ; \
fi;

Catching exceptions from Guzzle

I was catching GuzzleHttp\Exception\BadResponseException as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException when DNS for domain wasn't available. So my suggestion is - catch GuzzleHttp\Exception\ConnectException to be safe about DNS errors as well.

How to generate classes from wsdl using Maven and wsimport?

Even though this is bit late response, may be helpful for someone. Look like you have used pluginManagement. If you use pluginManagement , it will not pick the plug-in execution.

It should be under

<build>
<plugins>           
        <plugin> 

Extracting .jar file with command line

To extract the jar into specified folder use this command via command prompt

C:\Java> jar xf myFile.jar -C "C:\tempfolder"

List of phone number country codes

Country Data NPM Package.

If you're using node or NPM in general, you should take a look at the thorough Country Data package.

Since you're trying to get the Country from a phone number, you face two major obstacles:

  1. Parsing the phone number to get the Country code.

  2. Handling situations where a Country code can belong to more than one Country. e.g. Country Code of "+1" belongs to the United States and Canada.

However, the Country Data package will allow you to do something like this:

var CountryDataLookup = require('country-data').lookup;

lookup.countries({countryCallingCodes: '+1'})

And these are the returning objects:

[ { alpha2: 'CA',
    alpha3: 'CAN',
    countryCallingCodes: [ '+1' ],
    currencies: [ 'CAD' ],
    ioc: 'CAN',
    languages: [ 'eng', 'fra' ],
    name: 'Canada',
    status: 'assigned' },
  { alpha2: 'UM',
    alpha3: 'UMI',
    countryCallingCodes: [ '+1' ],
    currencies: [ 'USD' ],
    ioc: '',
    languages: [ 'eng' ],
    name: 'United States Minor Outlying Islands',
    status: 'assigned' },
  { alpha2: 'US',
    alpha3: 'USA',
    countryCallingCodes: [ '+1' ],
    currencies: [ 'USD' ],
    ioc: 'USA',
    languages: [ 'eng' ],
    name: 'United States',
    status: 'assigned' } ]

SQL grouping by all the columns

nope. are you trying to do some aggregation? if so, you could do something like this to get what you need

;with a as
(
     select sum(IntField) as Total
     from Table
     group by CharField
)
select *, a.Total
from Table t
inner join a
on t.Field=a.Field

Query Mongodb on month, day, year... of a datetime

You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.

As an example if you want all the orders which are created in April 2016 you can use below query.

db.getCollection('orders').aggregate(
   [
     {
       $project:
         {
           doc: "$$ROOT",
           year: { $year: "$created" },
           month: { $month: "$created" },
           day: { $dayOfMonth: "$created" }
         }
     },
     { $match : { "month" : 4, "year": 2016 } }
   ]
)

Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.

You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.

Check if value is zero or not null in python

If number could be None or a number, and you wanted to include 0, filter on None instead:

if number is not None:

If number can be any number of types, test for the type; you can test for just int or a combination of types with a tuple:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimal and Fraction objects.

How to check Grants Permissions at Run-Time?

Try this for Check Run-Time Permission:

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

    checkRunTimePermission();
}

Check run time permission:

private void checkRunTimePermission() {
    String[] permissionArrays = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(permissionArrays, 11111);
    } else {
         // if already permition granted
        // PUT YOUR ACTION (Like Open cemara etc..)
    }
}

Handle Permission result:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == 11111) {
        for (int i = 0; i < grantResults.length; i++) {
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                // user rejected the permission
                boolean showRationale = shouldShowRequestPermissionRationale(permission);
                if (!showRationale) {
                    //execute when 'never Ask Again' tick and permission dialog not show
                } else {
                    if (openDialogOnce) {
                        alertView();
                    }
                }
            }
        }

        if (isPermitted)
            if (isPermissionFromGallery)
                openGalleryFragment();
    }
}

Set custom alert:

private void alertView() {
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);

    dialog.setTitle("Permission Denied")
            .setInverseBackgroundForced(true)
            //.setIcon(R.drawable.ic_info_black_24dp)
            .setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")

            .setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                }
            })
            .setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialoginterface, int i) {
                    dialoginterface.dismiss();
                    checkRunTimePermission();

                }
            }).show();
}

Preferred method to store PHP arrays (json_encode vs serialize)

JSON is simpler and faster than PHP's serialization format and should be used unless:

  • You're storing deeply nested arrays: json_decode(): "This function will return false if the JSON encoded data is deeper than 127 elements."
  • You're storing objects that need to be unserialized as the correct class
  • You're interacting with old PHP versions that don't support json_decode

round a single column in pandas

You are very close. You applied the round to the series of values given by df.value1. The return type is thus a Series. You need to assign that series back to the dataframe (or another dataframe with the same Index).

Also, there is a pandas.Series.round method which is basically a short hand for pandas.Series.apply(np.round).

In[2]: 
    df.value1 = df.value1.round()
    print df

Out[2]:
    item  value1  value2
    0    a       1     1.3
    1    a       2     2.5
    2    a       0     0.0
    3    b       3    -1.0
    4    b       5    -1.0

How to delete a specific file from folder using asp.net

Check the GridView1.SelectedRow is not null:

if (GridView1.SelectedRow == null) return;
string DeleteThis = GridView1.SelectedRow.Cells[0].Text;

How to convert upper case letters to lower case

To convert a string to lower case in Python, use something like this.

list.append(sentence.lower())

I found this in the first result after searching for "python upper to lower case".

How to get a value from a Pandas DataFrame and not the index and object type

import pandas as pd

dataset = pd.read_csv("data.csv")
values = list(x for x in dataset["column name"])

>>> values[0]
'item_0'

edit:

actually, you can just index the dataset like any old array.

import pandas as pd

dataset = pd.read_csv("data.csv")
first_value = dataset["column name"][0]

>>> print(first_value)
'item_0'

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Yes you can usually see what SOAP version is supported based on the WSDL.

Take a look at Demo web service WSDL. It has a reference to the soap12 namespace indicating it supports SOAP 1.2. If that was absent then you'd probably be safe assuming the service only supported SOAP 1.1.

Check if a div does NOT exist with javascript

I do below and check if id exist and execute function if exist.

var divIDVar = $('#divID').length;
if (divIDVar === 0){ 
    console.log('No DIV Exist'); 
} else{  
    FNCsomefunction(); 
}   

How do I define a method which takes a lambda as a parameter in Java 8?

Lambdas are purely a call-site construct: the recipient of the lambda does not need to know that a Lambda is involved, instead it accepts an Interface with the appropriate method.

In other words, you define or use a functional interface (i.e. an interface with a single method) that accepts and returns exactly what you want.

For this Java 8 comes with a set of commonly-used interface types in java.util.function (thanks to Maurice Naftalin for the hint about the JavaDoc).

For this specific use case there's java.util.function.IntBinaryOperator with a single int applyAsInt(int left, int right) method, so you could write your method like this:

static int method(IntBinaryOperator op){
    return op.applyAsInt(5, 10);
}

But you can just as well define your own interface and use it like this:

public interface TwoArgIntOperator {
    public int op(int a, int b);
}

//elsewhere:
static int method(TwoArgIntOperator operator) {
    return operator.op(5, 10);
}

Using your own interface has the advantage that you can have names that more clearly indicate the intent.

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

How can I configure my makefile for debug and release builds?

This question has appeared often when searching for a similar problem, so I feel a fully implemented solution is warranted. Especially since I (and I would assume others) have struggled piecing all the various answers together.

Below is a sample Makefile which supports multiple build types in separate directories. The example illustrated shows debug and release builds.

Supports ...

  • separate project directories for specific builds
  • easy selection of a default target build
  • silent prep target to create directories needed for building the project
  • build-specific compiler configuration flags
  • GNU Make's natural method of determining if project requires a rebuild
  • pattern rules rather than the obsolete suffix rules

#
# Compiler flags
#
CC     = gcc
CFLAGS = -Wall -Werror -Wextra

#
# Project files
#
SRCS = file1.c file2.c file3.c file4.c
OBJS = $(SRCS:.c=.o)
EXE  = exefile

#
# Debug build settings
#
DBGDIR = debug
DBGEXE = $(DBGDIR)/$(EXE)
DBGOBJS = $(addprefix $(DBGDIR)/, $(OBJS))
DBGCFLAGS = -g -O0 -DDEBUG

#
# Release build settings
#
RELDIR = release
RELEXE = $(RELDIR)/$(EXE)
RELOBJS = $(addprefix $(RELDIR)/, $(OBJS))
RELCFLAGS = -O3 -DNDEBUG

.PHONY: all clean debug prep release remake

# Default build
all: prep release

#
# Debug rules
#
debug: $(DBGEXE)

$(DBGEXE): $(DBGOBJS)
    $(CC) $(CFLAGS) $(DBGCFLAGS) -o $(DBGEXE) $^

$(DBGDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(DBGCFLAGS) -o $@ $<

#
# Release rules
#
release: $(RELEXE)

$(RELEXE): $(RELOBJS)
    $(CC) $(CFLAGS) $(RELCFLAGS) -o $(RELEXE) $^

$(RELDIR)/%.o: %.c
    $(CC) -c $(CFLAGS) $(RELCFLAGS) -o $@ $<

#
# Other rules
#
prep:
    @mkdir -p $(DBGDIR) $(RELDIR)

remake: clean all

clean:
    rm -f $(RELEXE) $(RELOBJS) $(DBGEXE) $(DBGOBJS)

How to use support FileProvider for sharing content to other apps?

Here is my blog post about why we need to use FileProvider and how to use it correctly. Fully updated to the latest versions of Android.

How to add new column to MYSQL table?

your table:

q1 | q2 | q3 | q4 | q5

you can also do

ALTER TABLE yourtable ADD q6 VARCHAR( 255 ) after q5

CSS / HTML Navigation and Logo on same line

Firstly, let's use some semantic HTML.

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Get in Touch</a></li>
    </ul>
</nav>

In fact, you can even get away with the more minimalist:

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <a href="#">Home</a>
    <a href="#">Projects</a>
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Get in Touch</a>
</nav>

Then add some CSS:

.navigation-bar {
    width: 100%;  /* i'm assuming full width */
    height: 80px; /* change it to desired width */
    background-color: red; /* change to desired color */
}
.logo {
    display: inline-block;
    vertical-align: top;
    width: 50px;
    height: 50px;
    margin-right: 20px;
    margin-top: 15px;    /* if you want it vertically middle of the navbar. */
}
.navigation-bar > a {
    display: inline-block;
    vertical-align: top;
    margin-right: 20px;
    height: 80px;        /* if you want it to take the full height of the bar */
    line-height: 80px;    /* if you want it vertically middle of the navbar */
}

Obviously, the actual margins, heights and line-heights etc. depend on your design.

Other options are to use tables or floats for layout, but these are generally frowned upon.

Last but not least, I hope you get cured of div-itis.

Persistent invalid graphics state error when using ggplot2

I solved this by clearing all the plots in the console and then making sure the plot area was large enough to accommodate what I was creating.

How can I do an UPDATE statement with JOIN in SQL Server?

And in MS ACCESS:

UPDATE ud 
INNER JOIN sale ON ud.id = sale.udid
SET ud.assid = sale.assid;

Best way to return a value from a python script

If you want your script to return values, just do return [1,2,3] from a function wrapping your code but then you'd have to import your script from another script to even have any use for that information:

Return values (from a wrapping-function)

(again, this would have to be run by a separate Python script and be imported in order to even do any good):

import ...
def main():
    # calculate stuff
    return [1,2,3]

Exit codes as indicators

(This is generally just good for when you want to indicate to a governor what went wrong or simply the number of bugs/rows counted or w/e. Normally 0 is a good exit and >=1 is a bad exit but you could inter-prate them in any way you want to get data out of it)

import sys
# calculate and stuff
sys.exit(100)

And exit with a specific exit code depending on what you want that to tell your governor. I used exit codes when running script by a scheduling and monitoring environment to indicate what has happened.

(os._exit(100) also works, and is a bit more forceful)

Stdout as your relay

If not you'd have to use stdout to communicate with the outside world (like you've described). But that's generally a bad idea unless it's a parser executing your script and can catch whatever it is you're reporting to.

import sys
# calculate stuff
sys.stdout.write('Bugs: 5|Other: 10\n')
sys.stdout.flush()
sys.exit(0)

Are you running your script in a controlled scheduling environment then exit codes are the best way to go.

Files as conveyors

There's also the option to simply write information to a file, and store the result there.

# calculate
with open('finish.txt', 'wb') as fh:
    fh.write(str(5)+'\n')

And pick up the value/result from there. You could even do it in a CSV format for others to read simplistically.

Sockets as conveyors

If none of the above work, you can also use network sockets locally *(unix sockets is a great way on nix systems). These are a bit more intricate and deserve their own post/answer. But editing to add it here as it's a good option to communicate between processes. Especially if they should run multiple tasks and return values.

ImageView - have height match width?

i did like this -

layout.setMinimumHeight(layout.getWidth());

Set custom attribute using JavaScript

Please use dataset

var article = document.querySelector('#electriccars'),
    data = article.dataset;

// data.columns -> "3"
// data.indexnumber -> "12314"
// data.parent -> "cars"

so in your case for setting data:

getElementById('item1').dataset.icon = "base2.gif";

How many threads can a Java VM support?

The absolute theoretical maximum is generally a process's user address space divided by the thread stack size (though in reality, if all your memory is reserved for thread stacks, you won't have a working program...).

So under 32-bit Windows, for example, where each process has a user address space of 2GB, giving each thread a 128K stack size, you'd expect an absolute maximum of 16384 threads (=2*1024*1024 / 128). In practice, I find I can start up about 13,000 under XP.

Then, I think you're essentially into whether (a) you can manage juggling that many threads in your code and not do obviously silly things (such as making them all wait on the same object then calling notifyAll()...), and (b) whether the operating system can. In principle, the answer to (b) is "yes" if the answer to (a) is also "yes".

Incidentally, you can specify the stack size in the constructor of the Thread; you don't need to (and probably shouldn't) mess about with VM parameters for this.

Clean up a fork and restart it from the upstream

The simplest solution would be (using 'upstream' as the remote name referencing the original repo forked):

git remote add upstream /url/to/original/repo
git fetch upstream
git checkout master
git reset --hard upstream/master  
git push origin master --force 

(Similar to this GitHub page, section "What should I do if I’m in a bad situation?")

Be aware that you can lose changes done on the master branch (both locally, because of the reset --hard, and on the remote side, because of the push --force).

An alternative would be, if you want to preserve your commits on master, to replay those commits on top of the current upstream/master.
Replace the reset part by a git rebase upstream/master. You will then still need to force push.
See also "What should I do if I’m in a bad situation?"


A more complete solution, backing up your current work (just in case) is detailed in "Cleanup git master branch and move some commit to new branch".

See also "Pull new updates from original GitHub repository into forked GitHub repository" for illustrating what "upstream" is.

upstream


Note: recent GitHub repos do protect the master branch against push --force.
So you will have to un-protect master first (see picture below), and then re-protect it after force-pushing).

enter image description here


Note: on GitHub specifically, there is now (February 2019) a shortcut to delete forked repos for pull requests that have been merged upstream.

Programmatically get own phone number in iOS

AppStore will reject it, as it's reaching outside of application container.

Apps should be self-contained in their bundles, and may not read or write data outside the designated container area

Section 2.5.2 : https://developer.apple.com/app-store/review/guidelines/#software-requirements

Invariant Violation: _registerComponent(...): Target container is not a DOM element

If you use webpack for rendering your react and use HtmlWebpackPlugin in your react,this plugin builds its blank index.html by itself and injects js file in it,so it does not contain div element,as HtmlWebpackPlugin docs you can build your own index.html and give its address to this plugin, in my webpack.config.js

plugins: [            
    new HtmlWebpackPlugin({
        title: 'dev',
        template: 'dist/index.html'
    })
],

and this is my index.html file

<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="shortcut icon" href="">
    <meta name="viewport" content="width=device-width">
    <title>Epos report</title>
</head>
<body>
   <div id="app"></div>
   <script src="./bundle.js"></script>
</body>
</html>

Display Bootstrap Modal using javascript onClick

You don't need an onclick. Assuming you're using Bootstrap 3 Bootstrap 3 Documentation

<div class="span4 proj-div" data-toggle="modal" data-target="#GSCCModal">Clickable content, graphics, whatever</div>

<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
 <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

If you're using Bootstrap 2, you'd follow the markup here: http://getbootstrap.com/2.3.2/javascript.html#modals

Split string, convert ToList<int>() in one line

My problem was similar but with the inconvenience that sometimes the string contains letters (sometimes empty).

string sNumbers = "1,2,hh,3,4,x,5";

Trying to follow Pcode Xonos Extension Method:

public static List<int> SplitToIntList(this string list, char separator = ',')
{
      int result = 0;
      return (from s in list.Split(',')
              let isint = int.TryParse(s, out result)
              let val = result
              where isint
              select val).ToList(); 
}

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

I had the same error, and I found out that the cause was because my computer disk was full. After deleting some unnecessary files, the error went away.

AngularJS access parent scope from child controller

From a child component you can access the properties and methods of the parent component with 'require'. Here is an example:

Parent:

.component('myParent', mymodule.MyParentComponent)
...
controllerAs: 'vm',
...
var vm = this;
vm.parentProperty = 'hello from parent';

Child:

require: {
    myParentCtrl: '^myParent'
},
controllerAs: 'vm',
...
var vm = this;
vm.myParentCtrl.parentProperty = 'hello from child';

Android XML Percent Symbol

In your strings.xml file you can use any Unicode sign you want.

For example, the Unicode number for percent sign is 0025:

<string name="percent_sign">&#x0025;</string>

You can see a comprehensive list of Unicode signs here

Plain Old CLR Object vs Data Transfer Object

Don't even call them DTOs. They're called Models....Period. Models never have behavior. I don't know who came up with this dumb term DTO but it must be a .NET thing is all I can figure. Think of view models in MVC, same dam** thing, models are used to transfer state between layers server side or over the wire period, they are all models. Properties with data. These are models you pass ove the wire. Models, Models Models. That's it.

I wish the stupid term DTO would go away from our vocabulary.

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

Hibernate SessionFactory vs. JPA EntityManagerFactory

Prefer EntityManagerFactory and EntityManager. They are defined by the JPA standard.

SessionFactory and Session are hibernate-specific. The EntityManager invokes the hibernate session under the hood. And if you need some specific features that are not available in the EntityManager, you can obtain the session by calling:

Session session = entityManager.unwrap(Session.class);

Hibernate: ids for this class must be manually assigned before calling save()

Assign primary key in hibernate

Make sure that the attribute is primary key and Auto Incrementable in the database. Then map it into the data class with the annotation with @GeneratedValue annotation using IDENTITY.

@Entity
@Table(name = "client")
data class Client(
        @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private val id: Int? = null
)

GL

Source

create table with sequence.nextval in oracle

Oracle 12c

We now finally have IDENTITY columns like many other databases, in case of which a sequence is auto-generated behind the scenes. This solution is much faster than a trigger-based one as can be seen in this blog post.

So, your table creation would look like this:

CREATE TABLE qname
(
    qname_id integer GENERATED BY DEFAULT AS IDENTITY (START WITH 1) NOT NULL PRIMARY KEY,
    qname    VARCHAR2(4000) NOT NULL -- CONSTRAINT qname_uk UNIQUE
);

Oracle 11g and below

According to the documentation, you cannot do that:

Restriction on Default Column Values A DEFAULT expression cannot contain references to PL/SQL functions or to other columns, the pseudocolumns CURRVAL, NEXTVAL, LEVEL, PRIOR, and ROWNUM, or date constants that are not fully specified.

The standard way to have "auto increment" columns in Oracle is to use triggers, e.g.

CREATE OR REPLACE TRIGGER my_trigger
  BEFORE INSERT 
  ON qname
  FOR EACH ROW
  -- Optionally restrict this trigger to fire only when really needed
  WHEN (new.qname_id is null)
DECLARE
  v_id qname.qname_id%TYPE;
BEGIN
  -- Select a new value from the sequence into a local variable. As David
  -- commented, this step is optional. You can directly select into :new.qname_id
  SELECT qname_id_seq.nextval INTO v_id FROM DUAL;

  -- :new references the record that you are about to insert into qname. Hence,
  -- you can overwrite the value of :new.qname_id (qname.qname_id) with the value
  -- obtained from your sequence, before inserting
  :new.qname_id := v_id;
END my_trigger;

Read more about Oracle TRIGGERs in the documentation

Generating Random Passwords

validChars can be any construct, but I decided to select based on ascii code ranges removing control chars. In this example, it is a 12 character string.

string validChars = String.Join("", Enumerable.Range(33, (126 - 33)).Where(i => !(new int[] { 34, 38, 39, 44, 60, 62, 96 }).Contains(i)).Select(i => { return (char)i; }));
string.Join("", Enumerable.Range(1, 12).Select(i => { return validChars[(new Random(Guid.NewGuid().GetHashCode())).Next(0, validChars.Length - 1)]; }))

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

try to adding -Xmx512m in Android Studio->Settings->Compiler->VM Options , it's working thanks..

"google is not defined" when using Google Maps V3 in Firefox remotely

Changed the

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"> 
      function(){
            myMap()
                }
</script>

and made it

<script type="text/javascript">
      function(){
            myMap()
                }
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=API"></script>

It worked :)

Global environment variables in a shell script

Run your script with .

. myscript.sh

This will run the script in the current shell environment.

export governs which variables will be available to new processes, so if you say

FOO=1
export BAR=2
./runScript.sh

then $BAR will be available in the environment of runScript.sh, but $FOO will not.

insert echo into the specific html element like div which has an id or class

The only things I can think of are

  1. including files
  2. replacing elements within files using preg_match_all
  3. using assigned variables

I have recently been using str_replace and setting text in the HTML portion like so

{{TEXT_TO_REPLACE}}

using file_get_contents() you can grab html data and then organise it how you like.

here is a demo

myReplacementCodeFunction(){
  $text = '<img src="'.$row['name'].'" />'; 
  $text .= "<div>".$row['name']."</div>";
  $text .= "<div>".$row['title']."</div>";
  $text .= "<div>".$row['description']."</div>";
  $text .= "<div>".$row['link']."</div>";
  $text .= "<br />";
  return $text;
}

$htmlContents = file_get_contents("myhtmlfile.html");
$htmlContents = str_replace("{{TEXT_TO_REPLACE}}", myReplacementCodeFunction(), $htmlContents);
echo $htmlContents;

and now a demo html file:

<html>
<head>
   <style type="text/css">
      body{background:#666666;}
      div{border:1px solid red;}
   </style>
  </head>
  <body>
    {{TEXT_TO_REPLACE}}
  </body>
</html>

Python popen command. Wait until the command is finished

I think process.communicate() would be suitable for output having small size. For larger output it would not be the best approach.

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Convert python datetime to epoch with strftime

This works in Python 2 and 3:

>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998

Just following the official docs... https://docs.python.org/2/library/time.html#module-time

How to Truncate a string in PHP to the word closest to a certain number of characters?

While this is a rather old question, I figured I would provide an alternative, as it was not mentioned and valid for PHP 4.3+.

You can use the sprintf family of functions to truncate text, by using the %.Ns precision modifier.

A period . followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string

Simple Truncation https://3v4l.org/QJDJU

$string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var_dump(sprintf('%.10s', $string));

Result

string(10) "0123456789"

Expanded Truncation https://3v4l.org/FCD21

Since sprintf functions similarly to substr and will partially cut off words. The below approach will ensure words are not cutoff by using strpos(wordwrap(..., '[break]'), '[break]') with a special delimiter. This allows us to retrieve the position and ensure we do not match on standard sentence structures.

Returning a string without partially cutting off words and that does not exceed the specified width, while preserving line-breaks if desired.

function truncate($string, $width, $on = '[break]') {
    if (strlen($string) > $width && false !== ($p = strpos(wordwrap($string, $width, $on), $on))) {
        $string = sprintf('%.'. $p . 's', $string);
    }
    return $string;
}
var_dump(truncate('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ', 20));

var_dump(truncate("Lorem Ipsum is simply dummy text of the printing and typesetting industry.", 20));

var_dump(truncate("Lorem Ipsum\nis simply dummy text of the printing and typesetting industry.", 20));

Result

/* 
string(36) "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"  
string(14) "Lorem Ipsum is" 
string(14) "Lorem Ipsum
is" 
*/

Results using wordwrap($string, $width) or strtok(wordwrap($string, $width), "\n")

/*
string(14) "Lorem Ipsum is"
string(11) "Lorem Ipsum"
*/

How to add a single item to a Pandas Series

  • ser1 = pd.Sereis(np.linspace(1, 10, 2))
  • element = np.nan
  • ser1 = ser1.append(pd.Series(element))

Node.js + Nginx - What now?

Nginx can act as a reverse proxy server which works just like a project manager. When it gets a request it analyses it and forwards the request to upstream(project members) or handles itself. Nginx has two ways of handling a request based on how its configured.

  • serve the request
  • forward the request to another server

    server{
     server_name mydomain.com sub.mydomain.com;
    
     location /{ 
      proxy_pass http://127.0.0.1:8000;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }
    
     location /static/{
       alias /my/static/files/path;
     }
    

    }

Server the request

With this configuration, when the request url is mydomain.com/static/myjs.js it returns the myjs.js file in /my/static/files/path folder. When you configure nginx to serve static files, it handles the request itself.

forward the request to another server

When the request url is mydomain.com/dothis nginx will forwards the request to http://127.0.0.1:8000. The service which is running on the localhost 8000 port will receive the request and returns the response to nginx and nginx returns the response to the client.

When you run node.js server on the port 8000 nginx will forward the request to node.js. Write node.js logic and handle the request. That's it you have your nodejs server running behind the nginx server.

If you wish to run any other services other than nodejs just run another service like Django, flask, php on different ports and config it in nginx.

Move the most recent commit(s) to a new branch with Git

Most of the solutions here count the amount of commits you'd like to go back. I think this is an error prone methodology. Counting would require recounting.

You can simply pass the commit hash of the commit you want to be at HEAD or in other words, the commit you'd like to be the last commit via:

(Notice see commit hash)

To avoid this:

1) git checkout master

2) git branch <feature branch> master

3) git reset --hard <commit hash>

4) git push -f origin master

Show/Hide Multiple Divs with Jquery

If you want to be able to show / hide singular divs and / or groups of divs with less code, just apply several classes to them, to insert them into groups if needed.

Example :

.group1 {}
.group2 {}
.group3 {}

<div class="group3"></div>
<div class="group1 group2"></div>
<div class="group1 group3 group2"></div>

Then you just need to use an identifier to link the action to he target, and with 5,6 lines of jquery code you have everything you need.

No mapping found for HTTP request with URI [/WEB-INF/pages/apiForm.jsp]

What you need is to have a controller that responds to the url first which then renders your jsp. See this link for a solution.

Handling data in a PHP JSON Object

You mean something like this?

<?php

$jsonurl = "http://search.twitter.com/trends.json";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

foreach ( $json_output->trends as $trend )
{
    echo "{$trend->name}\n";
}

How to parse JSON in Java

You could use Google Gson.

Using this library you only need to create a model with the same JSON structure. Then the model is automatically filled in. You have to call your variables as your JSON keys, or use @SerializedName if you want to use different names.

JSON

From your example:

{
    "pageInfo": {
        "pageName": "abc",
        "pagePic": "http://example.com/content.jpg"
    }
    "posts": [
        {
            "post_id": "123456789012_123456789012",
            "actor_id": "1234567890",
            "picOfPersonWhoPosted": "http://example.com/photo.jpg",
            "nameOfPersonWhoPosted": "Jane Doe",
            "message": "Sounds cool. Can't wait to see it!",
            "likesCount": "2",
            "comments": [],
            "timeOfPost": "1234567890"
        }
    ]
}

Model

class MyModel {

    private PageInfo pageInfo;
    private ArrayList<Post> posts = new ArrayList<>();
}

class PageInfo {

    private String pageName;
    private String pagePic;
}

class Post {

    private String post_id;

    @SerializedName("actor_id") // <- example SerializedName
    private String actorId;

    private String picOfPersonWhoPosted;
    private String nameOfPersonWhoPosted;
    private String message;
    private String likesCount;
    private ArrayList<String> comments;
    private String timeOfPost;
}

Parsing

Now you can parse using Gson library:

MyModel model = gson.fromJson(jsonString, MyModel.class);

Gradle import

Remember to import the library in the app Gradle file

implementation 'com.google.code.gson:gson:2.8.6' // or earlier versions

Automatic model generation

You can generate model from JSON automatically using online tools like this.

- java.lang.NullPointerException - setText on null object reference

Here lies your problem:

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text); // tv is null
}

--> (TextView) findViewById(id); // returns null But from your code, I can't find why this method returns null. Try to track down, what id you give as a parameter and if this view with the specified id exists.

The error message is very clear and even tells you at what method. From the documentation:

public final View findViewById (int id)
    Look for a child view with the given id. If this view has the given id, return this view.
    Parameters
        id  The id to search for.
    Returns
        The view that has the given id in the hierarchy or null

http://developer.android.com/reference/android/view/View.html#findViewById%28int%29

In other words: You have no view with the id you give as a parameter.

Where is the Keytool application?

If you have Android installed in windows, you will also find it here: C:\Program Files\Android\jdk\microsoft_dist_openjdk_1.8.0.25\jre\bin

How to write log base(2) in c/c++

Consult your basic mathematics course, log n / log 2. It doesn't matter whether you choose log or log10in this case, dividing by the log of the new base does the trick.

How to include External CSS and JS file in Laravel 5

At first, you have to put your .css or .js files in the public folder of your project. You may create subfolders to it and move the files into the subfolder. Then you have to do the followings

<link rel="stylesheet" href="{{asset('css/your_css_file.css')}}">
<script src="{{asset('js/your_js_file.js')}}"></script>

In my example, I have created two subfolders called css and js. I put all of the .css and .js files in corresponding folders and use them where ever I want them. Thank you and hope this helps you.

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

How can I remove punctuation from input text in Java?

This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:

String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");

Spaces are initially left in the input so the split will still work.

By removing the rubbish characters before splitting, you avoid having to loop through the elements.

How to cancel a Task in await?

I just want to add to the already accepted answer. I was stuck on this, but I was going a different route on handling the complete event. Rather than running await, I add a completed handler to the task.

Comments.AsAsyncAction().Completed += new AsyncActionCompletedHandler(CommentLoadComplete);

Where the event handler looks like this

private void CommentLoadComplete(IAsyncAction sender, AsyncStatus status )
{
    if (status == AsyncStatus.Canceled)
    {
        return;
    }
    CommentsItemsControl.ItemsSource = Comments.Result;
    CommentScrollViewer.ScrollToVerticalOffset(0);
    CommentScrollViewer.Visibility = Visibility.Visible;
    CommentProgressRing.Visibility = Visibility.Collapsed;
}

With this route, all the handling is already done for you, when the task is cancelled it just triggers the event handler and you can see if it was cancelled there.

how to remove new lines and returns from php string?

you can pass an array of strings to str_replace, so you can do all in a single statement:

$content = str_replace(["\r\n", "\n", "\r"], "", $content);

postgresql duplicate key violates unique constraint

Intro

I also encountered this problem and the solution proposed by @adamo was basically the right solution. However, I had to invest a lot of time in the details, which is why I am now writing a new answer in order to save this time for others.

Case

My case was as follows: There was a table that was filled with data using an app. Now a new entry had to be inserted manually via SQL. After that the sequence was out of sync and no more records could be inserted via the app.

Solution

As mentioned in the answer from @adamo, the sequence must be synchronized manually. For this purpose the name of the sequence is needed. For Postgres, the name of the sequence can be determined with the command PG_GET_SERIAL_SEQUENCE. Most examples use lower case table names. In my case the tables were created by an ORM middleware (like Hibernate or Entity Framework Core etc.) and their names all started with a capital letter.

In an e-mail from 2004 (link) I got the right hint.

(Let's assume for all examples, that Foo is the table's name and Foo_id the related column.)

Command to get the sequence name:

SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id');

So, the table name must be in double quotes, surrounded by single quotes.

1. Validate, that the sequence is out-of-sync

SELECT CURRVAL(PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')) AS "Current Value", MAX("Foo_id") AS "Max Value" FROM "Foo";

When the Current Value is less than Max Value, your sequence is out-of-sync.

2. Correction

SELECT SETVAL((SELECT PG_GET_SERIAL_SEQUENCE('"Foo"', 'Foo_id')), (SELECT (MAX("Foo_id") + 1) FROM "Foo"), FALSE);

How to get directory size in PHP

There are several things you could do to optimise the script - but maximum success would make it IO-bound rather than CPU-bound:

  1. Calculate rtrim($path, '/') outside the loop.
  2. make if ($t<>"." && $t<>"..") the outer test - it doesn't need to stat the path
  3. Calculate rtrim($path, '/') . '/' . $t once per loop - inside 2) and taking 1) into account.
  4. Calculate explode(' ','B KB MB GB TB PB'); once rather than each call?

Hide particular div onload and then show div after click

This is an easier way to do it. Hope this helps...

<script type="text/javascript">
$(document).ready(function () {
    $("#preview").toggle(function() {
        $("#div1").hide();
        $("#div2").show();
    }, function() {
        $("#div1").show();
        $("#div2").hide();
    });
});

<div id="div1">
This is preview Div1. This is preview Div1.
</div>

<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>

<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
  • If you want the div to be hidden on load, make the style display:none
  • Use toggle rather than click function.


Links:

JQuery Tutorials

JQuery References

System.web.mvc missing

I have the same situation: Visual Studio 2010, no NuGet installed, and an ASP.NET application using System.Web.Mvc version 3.

What worked for me, was to set each C# project that uses System.Web.Mvc, to go to References in the Solution Explorer, and set properties on System.Web.Mvc, with Copy Local to true, and Specific Version to false - the last one caused the Version field to show the current version on that machine.

Gradle, Android and the ANDROID_HOME SDK location

I came across the same problem when opening a cloned git repository. The local.properties file is automatically added to the .gitignore file as it is specific to the build environment of each machine and is therefore not part of the repo.

The solution is to import the project instead of just opening it after you have cloned it from git, this forces android studio to create the local.properties file specific to your machine:

File >> Import Project >>

jQuery: how to change title of document during .ready()?

This works fine in all browser...

$(document).attr("title", "New Title");

Works in IE too

Python Script Uploading files via FTP

To avoid getting the encryption error you can also try out below commands

ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()

ftp.prot_p() ensure that your connections are encrypted

Uncaught SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode

This means that you must declare strict mode by writing "use strict" at the beginning of the file or the function to use block-scope declarations.

EX:

function test(){
    "use strict";
    let a = 1;
} 

How to use multiprocessing queue in Python?

I had a look at multiple answers across stack overflow and the web while trying to set-up a way of doing multiprocessing using queues for passing around large pandas dataframes. It seemed to me that every answer was re-iterating the same kind of solutions without any consideration of the multitude of edge cases one will definitely come across when setting up calculations like these. The problem is that there is many things at play at the same time. The number of tasks, the number of workers, the duration of each task and possible exceptions during task execution. All of these make synchronization tricky and most answers do not address how you can go about it. So this is my take after fiddling around for a few hours, hopefully this will be generic enough for most people to find it useful.

Some thoughts before any coding examples. Since queue.Empty or queue.qsize() or any other similar method is unreliable for flow control, any code of the like

while True:
    try:
        task = pending_queue.get_nowait()
    except queue.Empty:
        break

is bogus. This will kill the worker even if milliseconds later another task turns up in the queue. The worker will not recover and after a while ALL the workers will disappear as they randomly find the queue momentarily empty. The end result will be that the main multiprocessing function (the one with the join() on the processes) will return without all the tasks having completed. Nice. Good luck debugging through that if you have thousands of tasks and a few are missing.

The other issue is the use of sentinel values. Many people have suggested adding a sentinel value in the queue to flag the end of the queue. But to flag it to whom exactly? If there is N workers, assuming N is the number of cores available give or take, then a single sentinel value will only flag the end of the queue to one worker. All the other workers will sit waiting for more work when there is none left. Typical examples I've seen are

while True:
    task = pending_queue.get()
    if task == SOME_SENTINEL_VALUE:
        break

One worker will get the sentinel value while the rest will wait indefinitely. No post I came across mentioned that you need to submit the sentinel value to the queue AT LEAST as many times as you have workers so that ALL of them get it.

The other issue is the handling of exceptions during task execution. Again these should be caught and managed. Moreover, if you have a completed_tasks queue you should independently count in a deterministic way how many items are in the queue before you decide that the job is done. Again relying on queue sizes is bound to fail and returns unexpected results.

In the example below, the par_proc() function will receive a list of tasks including the functions with which these tasks should be executed alongside any named arguments and values.

import multiprocessing as mp
import dill as pickle
import queue
import time
import psutil

SENTINEL = None


def do_work(tasks_pending, tasks_completed):
    # Get the current worker's name
    worker_name = mp.current_process().name

    while True:
        try:
            task = tasks_pending.get_nowait()
        except queue.Empty:
            print(worker_name + ' found an empty queue. Sleeping for a while before checking again...')
            time.sleep(0.01)
        else:
            try:
                if task == SENTINEL:
                    print(worker_name + ' no more work left to be done. Exiting...')
                    break

                print(worker_name + ' received some work... ')
                time_start = time.perf_counter()
                work_func = pickle.loads(task['func'])
                result = work_func(**task['task'])
                tasks_completed.put({work_func.__name__: result})
                time_end = time.perf_counter() - time_start
                print(worker_name + ' done in {} seconds'.format(round(time_end, 5)))
            except Exception as e:
                print(worker_name + ' task failed. ' + str(e))
                tasks_completed.put({work_func.__name__: None})


def par_proc(job_list, num_cpus=None):

    # Get the number of cores
    if not num_cpus:
        num_cpus = psutil.cpu_count(logical=False)

    print('* Parallel processing')
    print('* Running on {} cores'.format(num_cpus))

    # Set-up the queues for sending and receiving data to/from the workers
    tasks_pending = mp.Queue()
    tasks_completed = mp.Queue()

    # Gather processes and results here
    processes = []
    results = []

    # Count tasks
    num_tasks = 0

    # Add the tasks to the queue
    for job in job_list:
        for task in job['tasks']:
            expanded_job = {}
            num_tasks = num_tasks + 1
            expanded_job.update({'func': pickle.dumps(job['func'])})
            expanded_job.update({'task': task})
            tasks_pending.put(expanded_job)

    # Use as many workers as there are cores (usually chokes the system so better use less)
    num_workers = num_cpus

    # We need as many sentinels as there are worker processes so that ALL processes exit when there is no more
    # work left to be done.
    for c in range(num_workers):
        tasks_pending.put(SENTINEL)

    print('* Number of tasks: {}'.format(num_tasks))

    # Set-up and start the workers
    for c in range(num_workers):
        p = mp.Process(target=do_work, args=(tasks_pending, tasks_completed))
        p.name = 'worker' + str(c)
        processes.append(p)
        p.start()

    # Gather the results
    completed_tasks_counter = 0
    while completed_tasks_counter < num_tasks:
        results.append(tasks_completed.get())
        completed_tasks_counter = completed_tasks_counter + 1

    for p in processes:
        p.join()

    return results

And here is a test to run the above code against

def test_parallel_processing():
    def heavy_duty1(arg1, arg2, arg3):
        return arg1 + arg2 + arg3

    def heavy_duty2(arg1, arg2, arg3):
        return arg1 * arg2 * arg3

    task_list = [
        {'func': heavy_duty1, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
        {'func': heavy_duty2, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
    ]

    results = par_proc(task_list)

    job1 = sum([y for x in results if 'heavy_duty1' in x.keys() for y in list(x.values())])
    job2 = sum([y for x in results if 'heavy_duty2' in x.keys() for y in list(x.values())])

    assert job1 == 15
    assert job2 == 21

plus another one with some exceptions

def test_parallel_processing_exceptions():
    def heavy_duty1_raises(arg1, arg2, arg3):
        raise ValueError('Exception raised')
        return arg1 + arg2 + arg3

    def heavy_duty2(arg1, arg2, arg3):
        return arg1 * arg2 * arg3

    task_list = [
        {'func': heavy_duty1_raises, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
        {'func': heavy_duty2, 'tasks': [{'arg1': 1, 'arg2': 2, 'arg3': 3}, {'arg1': 1, 'arg2': 3, 'arg3': 5}]},
    ]

    results = par_proc(task_list)

    job1 = sum([y for x in results if 'heavy_duty1' in x.keys() for y in list(x.values())])
    job2 = sum([y for x in results if 'heavy_duty2' in x.keys() for y in list(x.values())])

    assert not job1
    assert job2 == 21

Hope that is helpful.

Test or check if sheet exists

In case anyone wants to avoid VBA and test if a worksheet exists purely within a cell formula, it is possible using the ISREF and INDIRECT functions:

=ISREF(INDIRECT("SheetName!A1"))

This will return TRUE if the workbook contains a sheet called SheetName and FALSE otherwise.

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

AngularJS relies on input names to expose validation errors.

Unfortunately, as of today, it is not possible (without using a custom directive) to dynamically generate a name of an input. Indeed, checking input docs we can see that the name attribute accepts a string only.

To solve the 'dynamic name' problem you need to create an inner form (see ng-form):

<div ng-repeat="social in formData.socials">
      <ng-form name="urlForm">
            <input type="url" name="socialUrl" ng-model="social.url">
            <span class="alert error" ng-show="urlForm.socialUrl.$error.url">URL error</span>
      </ng-form>
  </div>

The other alternative would be to write a custom directive for this.

Here is the jsFiddle showing the usage of the ngForm: http://jsfiddle.net/pkozlowski_opensource/XK2ZT/2/

How to get the browser language using JavaScript

The "JavaScript" way:

var lang = navigator.language || navigator.userLanguage; //no ?s necessary

Really you should be doing language detection on the server, but if it's absolutely necessary to know/use via JavaScript, it can be gotten.

Converting file size in bytes to human-readable string

Solution as ReactJS Component

Bytes = React.createClass({
    formatBytes() {
        var i = Math.floor(Math.log(this.props.bytes) / Math.log(1024));
        return !this.props.bytes && '0 Bytes' || (this.props.bytes / Math.pow(1024, i)).toFixed(2) + " " + ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][i]
    },
    render () {
        return (
            <span>{ this.formatBytes() }</span>
        );
    }
});

UPDATE For those using es6 here is a stateless version of this same component

const sufixes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const getBytes = (bytes) => {
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return !bytes && '0 Bytes' || (bytes / Math.pow(1024, i)).toFixed(2) + " " + sufixes[i];
};

const Bytes = ({ bytes }) => (<span>{ getBytes(bytes) }</span>);

Bytes.propTypes = {
  bytes: React.PropTypes.number,
};

How to get current user who's accessing an ASP.NET application?

Using System.Web.HttpContext.Current.User.Identity.Name should work. Please check the IIS Site settings on the server that is hosting your site by doing the following:

  1. Go to IIS ? Sites ? Your Site ? Authentication

    IIS Settings

  2. Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.

    Authentication

  3. Now System.Web.HttpContext.Current.User.Identity.Name should return something like this:

    domain\username

Why do we not have a virtual constructor in C++?

A virtual-table(vtable) is made for each Class having one or more 'virtual-functions'. Whenever an Object is created of such class, it contains a 'virtual-pointer' which points to the base of corresponding vtable. Whenever there is a virtual function call, the vtable is used to resolve to the function address. Constructor can not be virtual, because when constructor of a class is executed there is no vtable in the memory, means no virtual pointer defined yet. Hence the constructor should always be non-virtual.

How to connect to a docker container from outside the host (same network) [Windows]

This is the most common issue faced by Windows users for running Docker Containers. IMO this is the "million dollar question on Docker"; @"Rocco Smit" has rightly pointed out "inbound traffic for it was disabled by default on my host machine's firewall"; in my case, my McAfee Anti Virus software. I added additional ports to be allowed for inbound traffic from other computers on the same Wifi LAN in the Firewall Settings of McAfee; then it was magic. I had struggled for more than a week browsing all over internet, SO, Docker documentations, Tutorials after Tutorials related to the Networking of Docker, and the many illustrations of "not supported on Windows" for "macvlan", "ipvlan", "user defined bridge" and even this same SO thread couple of times. I even started browsing google with "anybody using Docker in Production?", (yes I know Linux is more popular for Prod workloads compared to Windows servers) as I was not able to access (from my mobile in the same Home wifi) an nginx app deployed in Docker Container on Windows. After all, what good it is, if you cannot access the application (deployed on a Docker Container) from other computers / devices in the same LAN at-least; Ultimately in my case, the issue was just with a firewall blocking inbound traffic;

How to check if a string contains only digits in Java

According to Oracle's Java Documentation:

private static final Pattern NUMBER_PATTERN = Pattern.compile(
        "[\\x00-\\x20]*[+-]?(NaN|Infinity|((((\\p{Digit}+)(\\.)?((\\p{Digit}+)?)" +
        "([eE][+-]?(\\p{Digit}+))?)|(\\.((\\p{Digit}+))([eE][+-]?(\\p{Digit}+))?)|" +
        "(((0[xX](\\p{XDigit}+)(\\.)?)|(0[xX](\\p{XDigit}+)?(\\.)(\\p{XDigit}+)))" +
        "[pP][+-]?(\\p{Digit}+)))[fFdD]?))[\\x00-\\x20]*");
boolean isNumber(String s){
return NUMBER_PATTERN.matcher(s).matches()
}

Format date as dd/MM/yyyy using pipes

I think that it's because the locale is hardcoded into the DatePipe. See this link:

And there is no way to update this locale by configuration right now.

Java: how to initialize String[]?

I believe you just migrated from C++, Well in java you have to initialize a data type(other then primitive types and String is not a considered as a primitive type in java ) to use them as according to their specifications if you don't then its just like an empty reference variable (much like a pointer in the context of C++).

public class StringTest {
    public static void main(String[] args) {
        String[] errorSoon = new String[100];
        errorSoon[0] = "Error, why?";
        //another approach would be direct initialization
        String[] errorsoon = {"Error , why?"};   
    }
}

Best practice for partial updates in a RESTful service

You should use PATCH for partial updates - either using json-patch documents (see http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-08 or http://www.mnot.net/blog/2012/09/05/patch) or the XML patch framework (see http://tools.ietf.org/html/rfc5261). In my opinion though, json-patch is the best fit for your kind of business data.

PATCH with JSON/XML patch documents has very strait forward semantics for partial updates. If you start using POST, with modified copies of the original document, for partial updates you soon run into problems where you want missing values (or, rather, null values) to represent either "ignore this property" or "set this property to the empty value" - and that leads down a rabbit hole of hacked solutions that in the end will result in your own kind of patch format.

You can find a more in-depth answer here: http://soabits.blogspot.dk/2013/01/http-put-patch-or-post-partial-updates.html.

How to properly add 1 month from now to current date in moment.js

var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');

if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
    futureMonth = futureMonth.add(1, 'd');
}

console.log(currentDate);
console.log(futureMonth);

DEMO

EDIT

moment.addRealMonth = function addRealMonth(d) {
  var fm = moment(d).add(1, 'M');
  var fmEnd = moment(fm).endOf('month');
  return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;  
}

var nextMonth = moment.addRealMonth(moment());

DEMO

What does the regex \S mean in JavaScript?

/\S/.test(string) returns true if and only if there's a non-space character in string. Tab and newline count as spaces.

Notepad++: Multiple words search in a file (may be in different lines)?

Possible solution

  1. In Notepad++ , click search menu, the click Find
  2. in FIND WHAT : enter this ==> cat|town
  3. Select REGULAR EXPRESSION radiobutton
  4. click FIND IN CURRENT DOCUMENT

Screenshot

How should I resolve java.lang.IllegalArgumentException: protocol = https host = null Exception?

This code seems completely unnecessary:

String serverURLS = getRecipientURL(message);

serverURLS = "https:\\\\abc.my.domain.com:55555\\update";

if (serverURLS != null){
    serverURL = new URL(serverURLS);
}
  1. serverURLS is assigned the result of getRecipientURL(message)
  2. Then immediately you overwrite the value of serverURLS, making the previous statement a dead store
  3. Then, because if (serverURLS != null) evaluates to true, since you just assigned the variable a value in the preceding statement, you assign a value to serverURL. It is impossible for if (serverURLS != null) to evaluate to false!
  4. You never actually use the variable serverURLS beyond the previous line of code.

You could replace all of this with just:

serverURL = new URL("https:\\\\abc.my.domain.com:55555\\update");

Preloading CSS Images

http://css-tricks.com/snippets/css/css-only-image-preloading/

Technique #1

Load the image on the element's regular state, only shift it away with background position. Then move the background position to display it on hover.

#grass { background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background-position: bottom left; }

Technique #2

If the element in question already has a background-image applied and you need to change that image, the above won't work. Typically you would go for a sprite here (a combined background image) and just shift the background position. But if that isn't possible, try this. Apply the background image to another page element that is already in use, but doesn't have a background image.

#random-unsuspecting-element { background: url(images/grass.png) no-repeat -9999px -9999px; }
#grass:hover { background: url(images/grass.png) no-repeat; }

Check if multiple strings exist in another string

a = ['a', 'b', 'c']
str =  "a123"

a_match = [True for match in a if match in str]

if True in a_match:
  print "some of the strings found in str"
else:
  print "no strings found in str"

How do I access previous promise results in a .then() chain?

Break the chain

When you need to access the intermediate values in your chain, you should split your chain apart in those single pieces that you need. Instead of attaching one callback and somehow trying to use its parameter multiple times, attach multiple callbacks to the same promise - wherever you need the result value. Don't forget, a promise just represents (proxies) a future value! Next to deriving one promise from the other in a linear chain, use the promise combinators that are given to you by your library to build the result value.

This will result in a very straightforward control flow, clear composition of functionalities and therefore easy modularisation.

function getExample() {
    var a = promiseA(…);
    var b = a.then(function(resultA) {
        // some processing
        return promiseB(…);
    });
    return Promise.all([a, b]).then(function([resultA, resultB]) {
        // more processing
        return // something using both resultA and resultB
    });
}

Instead of the parameter destructuring in the callback after Promise.all that only became avail­able with ES6, in ES5 the then call would be replaced by a nifty helper method that was provided by many promise libraries (Q, Bluebird, when, …): .spread(function(resultA, resultB) { ….

Bluebird also features a dedicated join function to replace that Promise.all+spread combination with a simpler (and more efficient) construct:

…
return Promise.join(a, b, function(resultA, resultB) { … });

Sorting an array of objects by property values

Descending order of price:

homes.sort((x,y) => {return y.price - x.price})

Ascending order of price:

homes.sort((x,y) => {return x.price - y.price})

PHP post_max_size overrides upload_max_filesize

The normal method to send a file upload is POST, thus also post_max_size should be 16 Mb or more.

Incidentally, also memory_limit plays a role. It should be bigger than 16Mb, but since the default value is 128Mb, you won't see this problem. Example php.ini configuration:

post_max_size = 16M
upload_max_filesize = 16M
memory_limit = 128M

Change these value in php.ini if you've access to it, otherwise you can try to change them in an .htaccess file.

php_value upload_max_filesize 16M
php_value post_max_size 16M 

This will work only if the AllowOverride settings permit it. Otherwise, you've to ask to your hosting company.

What is the best way to implement nested dictionaries?

You could create a YAML file and read it in using PyYaml.

Step 1: Create a YAML file, "employment.yml":

new jersey:
  mercer county:
    pumbers: 3
    programmers: 81
  middlesex county:
    salesmen: 62
    programmers: 81
new york:
  queens county:
    plumbers: 9
    salesmen: 36

Step 2: Read it in Python

import yaml
file_handle = open("employment.yml")
my_shnazzy_dictionary = yaml.safe_load(file_handle)
file_handle.close()

and now my_shnazzy_dictionary has all your values. If you needed to do this on the fly, you can create the YAML as a string and feed that into yaml.safe_load(...).

Get the name of a pandas DataFrame

From here what I understand DataFrames are:

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

And Series are:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).

Series have a name attribute which can be accessed like so:

 In [27]: s = pd.Series(np.random.randn(5), name='something')

 In [28]: s
 Out[28]: 
 0    0.541
 1   -1.175
 2    0.129
 3    0.043
 4   -0.429
 Name: something, dtype: float64

 In [29]: s.name
 Out[29]: 'something'

EDIT: Based on OP's comments, I think OP was looking for something like:

 >>> df = pd.DataFrame(...)
 >>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
 >>> print(df.name)
 'df'

Current timestamp as filename in Java

You can get the current timestamp appended with a file extension in the following way:

String fileName = new Date().getTime() + ".txt";

How to display raw JSON data on a HTML page

I think all you need to display the data on an HTML page is JSON.stringify.

For example, if your JSON is stored like this:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

Of course you will probably want to replace body with some other element via getElementById.

As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.

var jsonVar = {
        text: "example",
        number: 1,
        obj: {
            "more text": "another example"
        },
        obj2: {
             "yet more text": "yet another example"
        }
    }, // THE RAW OBJECT
    jsonStr = JSON.stringify(jsonVar),  // THE OBJECT STRINGIFIED
    regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
    f = {
            brace: 0
        }; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
           // IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)

regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
        return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
    },
    rtnStr = 0;
    if (p1.lastIndexOf('{') === (p1.length - 1)) {
        rtnStr = rtnFn();
        f['brace'] += 1;
    } else if (p1.indexOf('}') === 0) {
         f['brace'] -= 1;
        rtnStr = rtnFn();
    } else {
        rtnStr = rtnFn();
    }
    return rtnStr;
});

document.body.innerHTML += regeStr; // appends the result to the body of the HTML document

This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.

jQuery .slideRight effect

Another solution is by using .animate() and appropriate CSS.

e.g.

   $('#mydiv').animate({ marginLeft: "100%"} , 4000);

JS Fiddle

Mongoose and multiple database in single node.js project

According to the fine manual, createConnection() can be used to connect to multiple databases.

However, you need to create separate models for each connection/database:

var conn      = mongoose.createConnection('mongodb://localhost/testA');
var conn2     = mongoose.createConnection('mongodb://localhost/testB');

// stored in 'testA' database
var ModelA    = conn.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testA database' }
}));

// stored in 'testB' database
var ModelB    = conn2.model('Model', new mongoose.Schema({
  title : { type : String, default : 'model in testB database' }
}));

I'm pretty sure that you can share the schema between them, but you have to check to make sure.

Get webpage contents with Python?

Because you're using Python 3.1, you need to use the new Python 3.1 APIs.

Try:

urllib.request.urlopen('http://www.python.org/')

Alternately, it looks like you're working from Python 2 examples. Write it in Python 2, then use the 2to3 tool to convert it. On Windows, 2to3.py is in \python31\tools\scripts. Can someone else point out where to find 2to3.py on other platforms?

Edit

These days, I write Python 2 and 3 compatible code by using six.

from six.moves import urllib
urllib.request.urlopen('http://www.python.org')

Assuming you have six installed, that runs on both Python 2 and Python 3.

How to get the current user's Active Directory details in C#

The "pre Windows 2000" name i.e. DOMAIN\SomeBody, the Somebody portion is known as sAMAccountName.

So try:

using(DirectoryEntry de = new DirectoryEntry("LDAP://MyDomainController"))
{
   using(DirectorySearcher adSearch = new DirectorySearcher(de))
   {
     adSearch.Filter = "(sAMAccountName=someuser)";
     SearchResult adSearchResult = adSearch.FindOne();
   }
}

[email protected] is the UserPrincipalName, but it isn't a required field.

Spring mvc @PathVariable

Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.

@RequestMapping(value = "/download/{documentId}", method = RequestMethod.GET)
public ModelAndView download(@PathVariable int documentId) {
    ModelAndView mav = new ModelAndView();
    Document document =  documentService.fileDownload(documentId);

    mav.addObject("downloadDocument", document);
    mav.setViewName("download");

    return mav;
}

Multi-dimensional arraylist or list in C#?

Not exactly. But you can create a list of lists:

var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
    var l = new List<int>();
    ll.Add(l);
}

ListBox with ItemTemplate (and ScrollBar!)

Thnaks for answer. I tried it myself too to an Empty Project and - lo behold allmighty creator of heaven and seven seas - it worked. I originally had ListBox inside which was inside of root . For some reason ListBox doesn't like being inside of StackPanel, at all! =)

-pom-

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');

Change class on mouseover in directive

I have run into problems in the past with IE and the css:hover selector so the approach that I have taken, is to use a custom directive.

.directive('hoverClass', function () {
    return {
        restrict: 'A',
        scope: {
            hoverClass: '@'
        },
        link: function (scope, element) {
            element.on('mouseenter', function() {
                element.addClass(scope.hoverClass);
            });
            element.on('mouseleave', function() {
                element.removeClass(scope.hoverClass);
            });
        }
    };
})

then on the element itself you can add the directive with the class names that you want enabled when the mouse is over the the element for example:

<li data-ng-repeat="item in social" hover-class="hover tint" class="social-{{item.name}}" ng-mouseover="hoverItem(true);" ng-mouseout="hoverItem(false);"
                index="{{$index}}"><i class="{{item.icon}}"
                box="course-{{$index}}"></i></li>

This should add the class hover and tint when the mouse is over the element and doesn't run the risk of a scope variable name collision. I haven't tested but the mouseenter and mouseleave events should still bubble up to the containing element so in the given scenario the following should still work

<div hover-class="hover" data-courseoverview data-ng-repeat="course in courses | orderBy:sortOrder | filter:search"
 data-ng-controller ="CourseItemController"
 data-ng-class="{ selected: isSelected }">

providing of course that the li's are infact children of the parent div

the MySQL service on local computer started and then stopped

mysqld --initialize

Run the above after the install command. Then try to start the service - that should work.

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

What values for checked and selected are false?

The checked and selected attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.

If you don't want to set the attribute, then the entire attribute must be omitted.

Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).

Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:

<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ...          checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked          > <!-- Only HTML 5 and later -->
<input ... checked=""       > <!-- Only HTML 5 and later -->

Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true", checked="yes", and checked="false" will all trigger the checked state.

I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.

(And all the above applies equally to selected as it does to checked.)

How to find path of active app.config file?

Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell

How do I set up IntelliJ IDEA for Android applications?

I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.

So here's the full guide:

  1. Download and install Java JDK (Choose the Java platform)
  2. Download and install Android SDK (Installer is recommended)
  3. After android SD finishes installing, open SDK Manager under Android SDK Tools (sometimes needs to be opened under admin's privileges)
  4. Choose everything and mark Accept All and install.
  5. Download and install IntelliJ IDEA (The community edition is free)
  6. Wait for all downloads and installations and stuff to finish.

New Project:

  1. Run IntelliJ
  2. Create a new project (there's a tutorial here)
  3. Enter the name, choose Android type.
  4. There's a step missing in the tutorial, when you are asked to choose the JDK (before choosing the SDK) you need to choose the Java JDK you've installed earlier. Should be under C:\Program Files\Java\jdk{version}
  5. Choose a New platform ( if there's not one selected ) , the SDK platform is the android platform at C:\Program Files\Android\android-sdk-windows.
  6. Choose the android version.
  7. Now you can write your program.

Compiling:

  1. Near the Run button you need to select the drop-down-list, choose Edit Configurations
  2. In the Prefer Android Virtual device select the ... button
  3. Click on create, give it a name, press OK.
  4. Double click the new device to choose it.
  5. Press OK.
  6. You're ready to run the program.

How to check for an empty object in an AngularJS view

Use json filter and compare with '{}' string.

<div>
    My object is {{ (myObject | json) == '{}' ? 'Empty' : 'Not Empty' }}
</div>

ng-show example:

<div ng-show="(myObject | json) != '{}'"></div>

How do I make a delay in Java?

Using TimeUnit.SECONDS.sleep(1); or Thread.sleep(1000); Is acceptable way to do it. In both cases you have to catch InterruptedExceptionwhich makes your code Bulky.There is an Open Source java library called MgntUtils (written by me) that provides utility that already deals with InterruptedException inside. So your code would just include one line:

TimeUtils.sleepFor(1, TimeUnit.SECONDS);

See the javadoc here. You can access library from Maven Central or from Github. The article explaining about the library could be found here

Get Time from Getdate()

Did you try to make a cast from date to time?

select cast(getdate() as time)

Reviewing the question, I saw the 'AM/PM' at end. So, my answer for this question is:

select format(getdate(), 'hh:mm:ss tt')

Run on Microsoft SQL Server 2012 and Later.

What should be the values of GOPATH and GOROOT?

Regarding GOROOT specifically, Go 1.9 will set it automatically to its installation path.
Even if you have multiple Go installed, calling the 1.9.x one will set GOROOT to /path/to/go/1.9 (before, if not set, it assumed a default path like /usr/local/go or c:\Go).

See CL Go Review 53370:

The go tool will now use the path from which it was invoked to attempt to locate the root of the Go install tree.
This means that if the entire Go installation is moved to a new location, the go tool should continue to work as usual.

This may be overriden by setting GOROOT in the environment, which should only be done in unusual circumstances.
Note that this does not affect the result of the runtime.GOROOT() function, which will continue to report the original installation location; this may be fixed in later releases.

Get item in the list in Scala?

Use parentheses:

data(2)

But you don't really want to do that with lists very often, since linked lists take time to traverse. If you want to index into a collection, use Vector (immutable) or ArrayBuffer (mutable) or possibly Array (which is just a Java array, except again you index into it with (i) instead of [i]).

Get ID from URL with jQuery

var full_url = document.URL; // Get current url
var url_array = full_url.split('/') // Split the string into an array with / as separator
var last_segment = url_array[url_array.length-1];  // Get the last part of the array (-1)
alert( last_segment ); // Alert last segment

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

In jQuery, a new element can be created by passing a HTML string to the constructor, as shown below:

var img = $('<img id="dynamic">'); //Equivalent: $(document.createElement('img'))
img.attr('src', responseObject.imgurl);
img.appendTo('#imagediv');

How do format a phone number as a String in Java?

The worst possible solution would be:

StringBuilder sb = new StringBuilder();
long tmp = phoneFmt;
sb.append("(");
sb.append(tmp / 10000000);
tmp = tmp % 10000000;
sb.append(")-");
sb.apppend(tmp / 10000);
tmp = tmp % 10000000;
sb.append("-");
sb.append(tmp);

Git error: "Please make sure you have the correct access rights and the repository exists"

I had this problem, and i discover that my system was with wrong dns address. Verify your network and test with

ssh -vvv [email protected]

And read the output messages. If you see "You can use git or hg to connect to Bitbucket." , everything is ok.

How to compare two floating point numbers in Bash?

beware when comparing numbers that are package versions, like checking if grep 2.20 is greater than version 2.6:

$ awk 'BEGIN { print (2.20 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.2 >= 2.6) ? "YES" : "NO" }'
NO

$ awk 'BEGIN { print (2.60 == 2.6) ? "YES" : "NO" }'
YES

I solved such problem with such shell/awk function:

# get version of GNU tool
toolversion() {
    local prog="$1" operator="$2" value="$3" version

    version=$($prog --version | awk '{print $NF; exit}')

    awk -vv1="$version" -vv2="$value" 'BEGIN {
        split(v1, a, /\./); split(v2, b, /\./);
        if (a[1] == b[1]) {
            exit (a[2] '$operator' b[2]) ? 0 : 1
        }
        else {
            exit (a[1] '$operator' b[1]) ? 0 : 1
        }
    }'
}

if toolversion grep '>=' 2.6; then
   # do something awesome
fi

Unexpected token ILLEGAL in webkit

Delete all invisible characters (whitespace) around that area, then give it another try.

I've seen that error in Safari when copy/pasting code. You can pick up some invalid (and unfortunately invisible) characters.

Used to happen to me a lot when copying from jsFiddle.

CRC32 C or C++ implementation

using zlib.h (http://refspecs.linuxbase.org/LSB_3.0.0/LSB-Core-generic/LSB-Core-generic/zlib-crc32-1.html):

#include <zlib.h>
unsigned long  crc = crc32(0L, Z_NULL, 0);
crc = crc32(crc, (const unsigned char*)data_address, data_len);

How to declare array of zeros in python (or an array of a certain size)

use numpy

import numpy
zarray = numpy.zeros(100)

And then use the Histogram library function

How to format font style and color in echo

echo '< span style = "font-color: #ff0000"> Movie List for {$key} 2013 </span>';

How can I get javascript to read from a .json file?

Actually, you are looking for the AJAX CALL, in which you will replace the URL parameter value with the link of the JSON file to get the JSON values.

$.ajax({
    url: "File.json", //the path of the file is replaced by File.json
    dataType: "json",
    success: function (response) {
        console.log(response); //it will return the json array
    }
});

URL rewriting with PHP

Although already answered, and author's intent is to create a front controller type app but I am posting literal rule for problem asked. if someone having the problem for same.

RewriteEngine On
RewriteRule ^([^/]+)/([^/]+)/([\d]+)$ $1?id=$3 [L]

Above should work for url picture.php/Some-text-goes-here/51. without using a index.php as a redirect app.

Parse JSON in JavaScript?

The following example will make it clear:

let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);

// Output: John Doe, 11

Line Break in XML formatting?

Take note: I have seen other posts that say &#xA; will give you a paragraph break, which oddly enough works in the Android xml String.xml file, but will NOT show up in a device when testing (no breaks at all show up). Therefore, the \n shows up on both.

What is the difference between JSF, Servlet and JSP?

The basic difference between Servlets and JSP is that in Servlets we write java code and in that we embed HTML code and there is just reverse case with JSP . In JSP we write HTML code and in that we embed java code using tags provided by JSP.

How to open a local disk file with JavaScript?

Consider reformatting your file into javascript. Then you can simply load it using good old...

<script src="thefileIwantToLoad.js" defer></script>

How can I brew link a specific version?

I asked in #machomebrew and learned that you can switch between versions using brew switch.

$ brew switch libfoo mycopy 

to get version mycopy of libfoo.

Unit Testing C Code

Minunit is an incredibly simple unit testing framework. I'm using it to unit test c microcontroller code for avr.

What is Haskell used for in the real world?

I think people in this post are missing the most important point for anyone who has never used a functional programming language: expanding your mind. If you are new to functional programming then Haskell will make you think in ways you've never thought before. As a result your programming in other areas and other languages will improve. How much? Hard to quantify.

copy all files and folders from one drive to another drive using DOS (command prompt)

xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y

Use the above command. It will definitely work.

In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:

  • /h copies hidden and system files also
  • /i if destination does not exist and copying more than one file, assume that destination must be a directory
  • /c continue copying even if error occurs
  • /k copies attributes
  • /e copies directories and subdirectories, including empty ones
  • /r overwrites read-only files
  • /y suppress prompting to confirm whether you want to overwrite a file

NULL value for int in Update statement

Assuming the column is set to support NULL as a value:

UPDATE YOUR_TABLE
   SET column = NULL

Be aware of the database NULL handling - by default in SQL Server, NULL is an INT. So if the column is a different data type you need to CAST/CONVERT NULL to the proper data type:

UPDATE YOUR_TABLE
   SET column = CAST(NULL AS DATETIME)

...assuming column is a DATETIME data type in the example above.

Find index of last occurrence of a substring in a string

Use the str.rindex method.

>>> 'hello'.rindex('l')
3
>>> 'hello'.index('l')
2

When can I use a forward declaration?

None of the answers so far describe when one can use a forward declaration of a class template. So, here it goes.

A class template can be forwarded declared as:

template <typename> struct X;

Following the structure of the accepted answer,

Here's what you can and cannot do.

What you can do with an incomplete type:

  • Declare a member to be a pointer or a reference to the incomplete type in another class template:

    template <typename T>
    class Foo {
        X<T>* ptr;
        X<T>& ref;
    };
    
  • Declare a member to be a pointer or a reference to one of its incomplete instantiations:

    class Foo {
        X<int>* ptr;
        X<int>& ref;
    };
    
  • Declare function templates or member function templates which accept/return incomplete types:

    template <typename T>
       void      f1(X<T>);
    template <typename T>
       X<T>    f2();
    
  • Declare functions or member functions which accept/return one of its incomplete instantiations:

    void      f1(X<int>);
    X<int>    f2();
    
  • Define function templates or member function templates which accept/return pointers/references to the incomplete type (but without using its members):

    template <typename T>
       void      f3(X<T>*, X<T>&) {}
    template <typename T>
       X<T>&   f4(X<T>& in) { return in; }
    template <typename T>
       X<T>*   f5(X<T>* in) { return in; }
    
  • Define functions or methods which accept/return pointers/references to one of its incomplete instantiations (but without using its members):

    void      f3(X<int>*, X<int>&) {}
    X<int>&   f4(X<int>& in) { return in; }
    X<int>*   f5(X<int>* in) { return in; }
    
  • Use it as a base class of another template class

    template <typename T>
    class Foo : X<T> {} // OK as long as X is defined before
                        // Foo is instantiated.
    
    Foo<int> a1; // Compiler error.
    
    template <typename T> struct X {};
    Foo<int> a2; // OK since X is now defined.
    
  • Use it to declare a member of another class template:

    template <typename T>
    class Foo {
        X<T> m; // OK as long as X is defined before
                // Foo is instantiated. 
    };
    
    Foo<int> a1; // Compiler error.
    
    template <typename T> struct X {};
    Foo<int> a2; // OK since X is now defined.
    
  • Define function templates or methods using this type

    template <typename T>
      void    f1(X<T> x) {}    // OK if X is defined before calling f1
    template <typename T>
      X<T>    f2(){return X<T>(); }  // OK if X is defined before calling f2
    
    void test1()
    {
       f1(X<int>());  // Compiler error
       f2<int>();     // Compiler error
    }
    
    template <typename T> struct X {};
    
    void test2()
    {
       f1(X<int>());  // OK since X is defined now
       f2<int>();     // OK since X is defined now
    }
    

What you cannot do with an incomplete type:

  • Use one of its instantiations as a base class

    class Foo : X<int> {} // compiler error!
    
  • Use one of its instantiations to declare a member:

    class Foo {
        X<int> m; // compiler error!
    };
    
  • Define functions or methods using one of its instantiations

    void      f1(X<int> x) {}            // compiler error!
    X<int>    f2() {return X<int>(); }   // compiler error!
    
  • Use the methods or fields of one of its instantiations, in fact trying to dereference a variable with incomplete type

    class Foo {
        X<int>* m;            
        void method()            
        {
            m->someMethod();      // compiler error!
            int i = m->someField; // compiler error!
        }
    };
    
  • Create explicit instantiations of the class template

    template struct X<int>;
    

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Simply just append your fields and their values to the elements:

$user->roles()->sync([
   1 => ['F1' => 'F1 Updated']
]);

What are the rules about using an underscore in a C++ identifier?

Yes, underscores may be used anywhere in an identifier. I believe the rules are: any of a-z, A-Z, _ in the first character and those +0-9 for the following characters.

Underscore prefixes are common in C code -- a single underscore means "private", and double underscores are usually reserved for use by the compiler.

Hide Command Window of .BAT file that Executes Another .EXE File

Using start works for me:

@echo off
copy "C:\Remoting.config-Training" "C:\Remoting.config"
start C:\ThirdParty.exe

EDIT: Ok, looking more closely, start seems to interpret the first parameter as the new window title if quoted. So, if you need to quote the path to your ThirdParty.exe you must supply a title string as well.

Examples:

:: Title not needed:
start C:\ThirdParty.exe

:: Title needed
start "Third Party App" "C:\Program Files\Vendor\ThirdParty.exe"

How to overlay image with color in CSS?

You could use the hue-rotate function in the filter property. It's quite an obscure measurement though, you'd need to know how many degrees round the colour wheel you need to move in order to arrive at your desired hue, for example:

header {
    filter: hue-rotate(90deg);
}

Once you'd found the correct hue, you could combine the brightness and either grayscale or saturate functions to find the correct shade, for example:

header {
    filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}

The filter property has a vendor prefix in Webkit, so the final code would be:

header {
  -webkit-filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
          filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}

How to integrate sourcetree for gitlab

Using the SSH URL from GitLab:

Step 1: Generate an SSH Key with default values from GitLab.

GitLab provides the commands to generate it. Just copy them, edit the email, and paste it in the terminal. Using the default values is important. Else SourceTree will not be able to access the SSH key without additional configuration.

STEP 2: Add the SSH key to your keychain using the command ssh-add -K.

Open the terminal and paste the above command in it. This will add the key to your keychain.

STEP 3: Restart SourceTree and clone remote repo using URL.

Restarting SourceTree is needed so that SourceTree picks the new key.

enter image description here

STEP 4: Copy the SSH URL provided by GitLab.

enter image description here

STEP 5: Paste the SSH URL into the Source URL field of SourceTree.

enter image description here

These steps were successfully performed on Mac OS 10.13.2 using SourceTree 2.7.1.

enter image description hereenter image description here

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

Java simple code: java.net.SocketException: Unexpected end of file from server

"Unexpected end of file" implies that the remote server accepted and closed the connection without sending a response. It's possible that the remote system is too busy to handle the request, or that there's a network bug that randomly drops connections.

It's also possible there is a bug in the server: something in the request causes an internal error, and the server simply closes the connection instead of sending a HTTP error response like it should. Several people suggest this is caused by missing headers or invalid header values in the request.

With the information available it's impossible to say what's going wrong. If you have access to the servers in question you can use packet sniffing tools to find what exactly is sent and received, and look at logs to of the server process to see if there are any error messages.

HTML5 image icon to input placeholder

`CSS:

input#search{
 background-image: url(bg.jpg);
 background-repeat: no-repeat;
 text-indent: 20px;
}

input#search:focus{
 background-image:none;
}

HTML:

<input type="text" id="search" name="search" value="search" />`

What is the simplest way to swap each pair of adjoining chars in a string with Python?

A bit late to the party, but there is actually a pretty simple way to do this:

The index sequence you are looking for can be expressed as the sum of two sequences:

 0  1  2  3 ...
+1 -1 +1 -1 ...

Both are easy to express. The first one is just range(N). A sequence that toggles for each i in that range is i % 2. You can adjust the toggle by scaling and offsetting it:

         i % 2      ->  0  1  0  1 ...
     1 - i % 2      ->  1  0  1  0 ...
2 * (1 - i % 2)     ->  2  0  2  0 ...
2 * (1 - i % 2) - 1 -> +1 -1 +1 -1 ...

The entire expression simplifies to i + 1 - 2 * (i % 2), which you can use to join the string almost directly:

result = ''.join(string[i + 1 - 2 * (i % 2)] for i in range(len(string)))

This will work only for an even-length string, so you can check for overruns using min:

N = len(string)
result = ''.join(string[min(i + 1 - 2 * (i % 2), N - 1)] for i in range(N))

Basically a one-liner, doesn't require any iterators beyond a range over the indices, and some very simple integer math.

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0

In STL maps, is it better to use map::insert than []?

When you write

map[key] = value;

there's no way to tell if you replaced the value for key, or if you created a new key with value.

map::insert() will only create:

using std::cout; using std::endl;
typedef std::map<int, std::string> MyMap;
MyMap map;
// ...
std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value));
if ( ! res.second ) {
    cout << "key " <<  key << " already exists "
         << " with value " << (res.first)->second << endl;
} else {
    cout << "created key " << key << " with value " << value << endl;
}

For most of my apps, I usually don't care if I'm creating or replacing, so I use the easier to read map[key] = value.

What are the differences between a HashMap and a Hashtable in Java?

HashMap and Hashtable both are used to store data in key and value form. Both are using hashing technique to store unique keys. ut there are many differences between HashMap and Hashtable classes that are given below.

enter image description here

How to get thread id of a pthread in linux c program?

I think not only is the question not clear but most people also are not cognizant of the difference. Examine the following saying,

POSIX thread IDs are not the same as the thread IDs returned by the Linux specific gettid() system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned by gettid() is a number (similar to a process ID) that is assigned by the kernel. Although each POSIX thread has a unique kernel thread ID in the Linux NPTL threading implementation, an application generally doesn’t need to know about the kernel IDs (and won’t be portable if it depends on knowing them).

Excerpted from: The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Michael Kerrisk

IMHO, there is only one portable way that pass a structure in which define a variable holding numbers in an ascending manner e.g. 1,2,3... to per thread. By doing this, threads' id can be kept track. Nonetheless, int pthread_equal(tid1, tid2) function should be used.

if (pthread_equal(tid1, tid2)) printf("Thread 2 is same as thread 1.\n");
else printf("Thread 2 is NOT same as thread 1.\n");

Difference between an API and SDK

API is specifications on how to do something, an interface, such as "The railroad tracks are four feet apart, and the metal bar is 1 inch wide" Now that you have the API you can now build a train that will fit on those railroad tracks if you want to go anywhere. API is just information on how to build your code, it doesn't do anything.

SDK is some package of actual tools that already worried about the specifications. "Here's a train, some coal, and a maintenance man. Use it to go from place to place" With the SDK you don't worry about specifics. An SDK is actual code, it can be used by itself to do something, but of course, the train won't start up spontaneously, you still have to get a conductor to control the train.

SDKs also have their own APIs. "If you want to power the train put coal in it", "Pull the blue lever to move the train.", "If the train starts acting funny, call the maintenance man" etc.