Programs & Examples On #Createuser

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

Since the originating port 4200 is different than 8080,So before angular sends a create (PUT) request,it will send an OPTIONS request to the server to check what all methods and what all access-controls are in place. Server has to respond to that OPTIONS request with list of allowed methods and allowed origins.

Since you are using spring boot, the simple solution is to add ".allowedOrigins("http://localhost:4200");"

In your spring config,class

@Configuration
@EnableWebMvc
public class SpringConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("http://localhost:4200");
    }
}

However a better approach will be to write a Filter(interceptor) which adds the necessary headers to each response.

MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]

first create folder by command line mkdir C:\data\db (This is for database) then run command mongod --port 27018 by one command prompt(administration mode)- you can give name port number as your wish

Android Room - simple select query - Cannot access database on the main thread

You cannot run it on main thread instead use handlers, async or working threads . A sample code is available here and read article over room library here : Android's Room Library

/**
 *  Insert and get data using Database Async way
 */
AsyncTask.execute(new Runnable() {
    @Override
    public void run() {
        // Insert Data
        AppDatabase.getInstance(context).userDao().insert(new User(1,"James","Mathew"));

        // Get Data
        AppDatabase.getInstance(context).userDao().getAllUsers();
    }
});

If you want to run it on main thread which is not preferred way .

You can use this method to achieve on main thread Room.inMemoryDatabaseBuilder()

How to use addTarget method in swift 3

Try this with Swift 4

buttonSection.addTarget(self, action: #selector(actionWithParam(_:)), for: .touchUpInside)
@objc func actionWithParam(sender: UIButton){
    //...
}

buttonSection.addTarget(self, action: #selector(actionWithoutParam), for: .touchUpInside)
@objc func actionWithoutParam(){
    //...
}

Convert Promise to Observable

try this:

import 'rxjs/add/observable/fromPromise';
import { Observable } from "rxjs/Observable";

const subscription = Observable.fromPromise(
    firebase.auth().createUserWithEmailAndPassword(email, password)
);
subscription.subscribe(firebaseUser => /* Do anything with data received */,
                       error => /* Handle error here */);

you can find complete reference to fromPromise operator here.

disabling spring security in spring boot app

For me only excluding the following classes worked:

import org.springframework.boot.actuate.autoconfigure.security.servlet.ManagementWebSecurityAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class, ManagementWebSecurityAutoConfiguration.class}) {
  // ... 
}

How to handle errors with boto3?

  • Only one import needed.
  • No if statement needed.
  • Use the client built-in exception as intended.

Ex:

from boto3 import client

cli = client('iam')
try:
    cli.create_user(
        UserName = 'Brian'
    )
except cli.exceptions.EntityAlreadyExistsException:
    pass

a CloudWatch example:

cli = client('logs')
try:
    cli.create_log_group(
        logGroupName = 'MyLogGroup'
    )
except cli.exceptions.ResourceAlreadyExistsException:
    pass

Spring Boot Multiple Datasource

I think you can find it usefull

http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-two-datasources

It shows how to define multiple datasources & assign one of them as primary.

Here is a rather full example, also contains distributes transactions - if you need it.

http://fabiomaffioletti.me/blog/2014/04/15/distributed-transactions-multiple-databases-spring-boot-spring-data-jpa-atomikos/

What you need is to create 2 configuration classes, separate the model/repository packages etc to make the config easy.

Also, in above example, it creates the data sources manually. You can avoid this using the method on spring doc, with @ConfigurationProperties annotation. Here is an example of this:

http://xantorohara.blogspot.com.tr/2013/11/spring-boot-jdbc-with-multiple.html

Hope these helps.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

For me, it was just close the android studio and restart as Administrator.

How to create User/Database in script for Docker Postgres

EDIT - since Jul 23, 2015

The official postgres docker image will run .sql scripts found in the /docker-entrypoint-initdb.d/ folder.

So all you need is to create the following sql script:

init.sql

CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;

and add it in your Dockerfile:

Dockerfile

FROM library/postgres
COPY init.sql /docker-entrypoint-initdb.d/

But since July 8th, 2015, if all you need is to create a user and database, it is easier to just make use to the POSTGRES_USER, POSTGRES_PASSWORD and POSTGRES_DB environment variables:

docker run -e POSTGRES_USER=docker -e POSTGRES_PASSWORD=docker -e POSTGRES_DB=docker library/postgres

or with a Dockerfile:

FROM library/postgres
ENV POSTGRES_USER docker
ENV POSTGRES_PASSWORD docker
ENV POSTGRES_DB docker

for images older than Jul 23, 2015

From the documentation of the postgres Docker image, it is said that

[...] it will source any *.sh script found in that directory [/docker-entrypoint-initdb.d] to do further initialization before starting the service

What's important here is "before starting the service". This means your script make_db.sh will be executed before the postgres service would be started, hence the error message "could not connect to database postgres".

After that there is another useful piece of information:

If you need to execute SQL commands as part of your initialization, the use of Postgres single user mode is highly recommended.

Agreed this can be a bit mysterious at the first look. What it says is that your initialization script should start the postgres service in single mode before doing its actions. So you could change your make_db.ksh script as follows and it should get you closer to what you want:

NOTE, this has changed recently in the following commit. This will work with the latest change:

export PGUSER=postgres
psql <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Previously, the use of --single mode was required:

gosu postgres postgres --single <<- EOSQL
    CREATE USER docker;
    CREATE DATABASE docker;
    GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQL

Python: import module from another directory at the same level in project hierarchy

In the "root" __init__.py you can also do a

import sys
sys.path.insert(1, '.')

which should make both modules importable.

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

psql: FATAL: Peer authentication failed for user "dev"

pg_dump -h localhost -U postgres -F c -b -v -f mydb.backup mydb

Createuser: could not connect to database postgres: FATAL: role "tom" does not exist

Your error is posted in the official documentation. You can read this article.

I have copied the reason for you (and hyperlinked the URLs) from that article:

This will happen if the administrator has not created a PostgreSQL user account for you. (PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 20 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name

For your purposes, you can do:

1) Create a PostgreSQL user account:

sudo -u postgres createuser tom -d -P

(the -P option to set a password; the -d option for allowing the creation of database for your username 'tom'. Note that 'tom' is your operating system username. That way, you can execute PostgreSQL commands without sudoing.)

2) Now you should be able to execute createdb and other PostgreSQL commands.

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

If you really need to do it in separate transaction you need to use REQUIRES_NEW and live with the performance overhead. Watch out for dead locks.

I'd rather do it the other way:

  • Validate data on Java side.
  • Run everyting in one transaction.
  • If anything goes wrong on DB side -> it's a major error of DB or validation design. Rollback everything and throw critical top level error.
  • Write good unit tests.

PostgreSQL error: Fatal: role "username" does not exist

psql postgres

postgres=# CREATE ROLE username superuser;
postgres=# ALTER ROLE username WITH LOGIN;

PHP - Indirect modification of overloaded property

Nice you gave me something to play around with

Run

class Sample extends Creator {

}

$a = new Sample ();
$a->role->rolename = 'test';
echo  $a->role->rolename , PHP_EOL;
$a->role->rolename->am->love->php = 'w00';
echo  $a->role->rolename  , PHP_EOL;
echo  $a->role->rolename->am->love->php   , PHP_EOL;

Output

test
test
w00

Class Used

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        $this->{$name} = new Value ( $name, $value );
    }



}

class Value extends Creator {
    private $name;
    private $value;
    function __construct($name, $value) {
        $this->name = $name;
        $this->value = $value;
    }

    function __toString()
    {
        return (string) $this->value ;
    }
}      

Edit : New Array Support as requested

class Sample extends Creator {

}

$a = new Sample ();
$a->role = array (
        "A",
        "B",
        "C" 
);


$a->role[0]->nice = "OK" ;

print ($a->role[0]->nice  . PHP_EOL);

$a->role[1]->nice->ok = array("foo","bar","die");

print ($a->role[1]->nice->ok[2]  . PHP_EOL);


$a->role[2]->nice->raw = new stdClass();
$a->role[2]->nice->raw->name = "baba" ;

print ($a->role[2]->nice->raw->name. PHP_EOL);

Output

 Ok die baba

Modified Class

abstract class Creator {
    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }
        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;

    }

}

class Value {
    private $name ;
    function __construct($name, $value) {
        $this->{$name} = $value;
        $this->name = $value ;
    }

    public function __get($name) {
        if (! isset ( $this->{$name} )) {
            $this->{$name} = new Value ( $name, null );
        }

        if ($name == $this->name) {
            return $this->value;
        }

        return $this->{$name};
    }

    public function __set($name, $value) {
        if (is_array ( $value )) {
            array_walk ( $value, function (&$item, $key) {
                $item = new Value ( $key, $item );
            } );
        }
        $this->{$name} = $value;
    }

    public function __toString() {
        return (string) $this->name ;
    }   
}

How to create a user in Django?

Have you confirmed that you are passing actual values and not None?

from django.shortcuts import render

def createUser(request):
    userName = request.REQUEST.get('username', None)
    userPass = request.REQUEST.get('password', None)
    userMail = request.REQUEST.get('email', None)

    # TODO: check if already existed
    if userName and userPass and userMail:
       u,created = User.objects.get_or_create(userName, userMail)
       if created:
          # user was created
          # set the password here
       else:
          # user was retrieved
    else:
       # request was empty

    return render(request,'home.html')

PHP class not found but it's included

  1. Check File Permissions
  2. Check File size.

Sometimes an inaccessible or corrupted file would be the problem, as was in my case

Adding a column to an existing table in a Rails migration

Sometimes rails generate migration add_email_to_users email:string produces a migration like this

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
  end
end

In that case you have to manually an add_column to change:

class AddEmailToUsers < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :email, :string
  end
end

And then run rake db:migrate

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

For me I had all of the namespaces on the pages and none of the solutions above fixed it. My problem was in:

<%@ Page Language="C#" 
AutoEventWireup="true" 
CodeBehind="xxx.aspx.cs" 
Inherits="xxx.xxx.xxx" 
MasterPageFile="~masterurl/default.master" %>

Then in my aspx.cs file the namespace did not match the Inherits tag. So it needed

namespace xxx.xxx.xxx

In the .cs to match the Inherits.

How to configure postgresql for the first time?

There are two methods you can use. Both require creating a user and a database.

  1. Using createuser and createdb,

    $ sudo -u postgres createuser --superuser $USER
    $ createdb mydatabase
    $ psql -d mydatabase
    
  2. Using the SQL administration commands, and connecting with a password over TCP

    $ sudo -u postgres psql postgres
    

    And, then in the psql shell

    CREATE ROLE myuser LOGIN PASSWORD 'mypass';
    CREATE DATABASE mydatabase WITH OWNER = myuser;
    

    Then you can login,

    $ psql -h localhost -d mydatabase -U myuser -p <port>
    

    If you don't know the port, you can always get it by running the following, as the postgres user,

    SHOW port;
    

    Or,

    $ grep "port =" /etc/postgresql/*/main/postgresql.conf
    

Sidenote: the postgres user

I suggest NOT modifying the postgres user.

  1. It's normally locked from the OS. No one is supposed to "log in" to the operating system as postgres. You're supposed to have root to get to authenticate as postgres.
  2. It's normally not password protected and delegates to the host operating system. This is a good thing. This normally means in order to log in as postgres which is the PostgreSQL equivalent of SQL Server's SA, you have to have write-access to the underlying data files. And, that means that you could normally wreck havoc anyway.
  3. By keeping this disabled, you remove the risk of a brute force attack through a named super-user. Concealing and obscuring the name of the superuser has advantages.

HTML5 Video // Completely Hide Controls

There are two ways to hide video tag controls

  1. Remove the controls attribute from the video tag.

  2. Add the css to the video tag

    video::-webkit-media-controls-panel {
    display: none !important;
    opacity: 1 !important;}
    

Which is a better way to check if an array has more than one element?

if (count($arr) >= 2)
{
  // array has at least 2 elements
}

sizeof() is an alias for count(). Both work with non-arrays too, but they will only return values greater than 1 if the argument is either an array or a Countable object, so you're pretty safe with this.

Apply style ONLY on IE

<!--[if !IE]><body<![endif]-->
<!--[if IE]><body class="ie"> <![endif]-->

body.ie .actual-form table {
    width: 100%
}

Remove a data connection from an Excel 2010 spreadsheet in compatibility mode

Select a cell in the cell range in which the data is imported, then Menu > Data > Properties > uncheck save query definition.

Properties will be greyed out unless a cell in the data import range is selected.

You can find out the range in which the data isimported by:

Menu > Data > Connections > (select connection) > Click here to see where the selected connections are used.

How to use goto statement correctly

There is not 'goto' in the Java world. The main reason was developers realized that complex codes which had goto would lead to making the code really pathetic and it would be almost impossible to enhance or maintain the code.

However this code could be modified a little and using the concept of continue and break we could make the code work.

    import java.util.*;

public class Factorial 
{
    public static void main(String[] args) 
    {
        int x = 1;
        int factValue = 1;
        Scanner userInput = new Scanner(System.in);
        restart: while(true){
        System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
        int factInput = userInput.nextInt();

        while(factInput<=0)
        {
            System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
            factInput = userInput.nextInt();
        }

        if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
        {
            System.out.println("The number you entered is not valid. Please try again.");
            continue restart;
        }
        while(x<=factInput)
        {
            factValue*=x;
            x++;
        }
        System.out.println(factInput+"! = "+factValue);
        userInput.close();
        break restart;
}
    }
}

How do I change the hover over color for a hover over table in Bootstrap?

Give this a try:

.table-hover tbody tr:hover td, .table-hover tbody tr:hover th {
  background-color: #color;
}

Intercept and override HTTP requests from WebView

Here is my solution I use for my app.

I have several asset folder with css / js / img anf font files.

The application gets all filenames and looks if a file with this name is requested. If yes, it loads it from asset folder.

//get list of files of specific asset folder
        private ArrayList listAssetFiles(String path) {

            List myArrayList = new ArrayList();
            String [] list;
            try {
                list = getAssets().list(path);
                for(String f1 : list){
                    myArrayList.add(f1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return (ArrayList) myArrayList;
        }

        //get mime type by url
        public String getMimeType(String url) {
            String type = null;
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            if (extension != null) {
                if (extension.equals("js")) {
                    return "text/javascript";
                }
                else if (extension.equals("woff")) {
                    return "application/font-woff";
                }
                else if (extension.equals("woff2")) {
                    return "application/font-woff2";
                }
                else if (extension.equals("ttf")) {
                    return "application/x-font-ttf";
                }
                else if (extension.equals("eot")) {
                    return "application/vnd.ms-fontobject";
                }
                else if (extension.equals("svg")) {
                    return "image/svg+xml";
                }
                type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
            }
            return type;
        }

        //return webresourceresponse
        public WebResourceResponse loadFilesFromAssetFolder (String folder, String url) {
            List myArrayList = listAssetFiles(folder);
            for (Object str : myArrayList) {
                if (url.contains((CharSequence) str)) {
                    try {
                        Log.i(TAG2, "File:" + str);
                        Log.i(TAG2, "MIME:" + getMimeType(url));
                        return new WebResourceResponse(getMimeType(url), "UTF-8", getAssets().open(String.valueOf(folder+"/" + str)));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        //@TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @SuppressLint("NewApi")
        @Override
        public WebResourceResponse shouldInterceptRequest(final WebView view, String url) {
            //Log.i(TAG2, "SHOULD OVERRIDE INIT");
            //String url = webResourceRequest.getUrl().toString();
            String extension = MimeTypeMap.getFileExtensionFromUrl(url);
            //I have some folders for files with the same extension
            if (extension.equals("css") || extension.equals("js") || extension.equals("img")) {
                return loadFilesFromAssetFolder(extension, url);
            }
            //more possible extensions for font folder
            if (extension.equals("woff") || extension.equals("woff2") || extension.equals("ttf") || extension.equals("svg") || extension.equals("eot")) {
                return loadFilesFromAssetFolder("font", url);
            }

            return null;
        }

How to use Selenium with Python?

You just need to get selenium package imported, that you can do from command prompt using the command

pip install selenium

When you have to use it in any IDE just import this package, no other documentation required to be imported

For Eg :

import selenium 
print(selenium.__filepath__)

This is just a general command you may use in starting to check the filepath of selenium

NoSql vs Relational database

If you need to process huge amount of data with high performance

OR

If data model is not predetermined

then

NoSQL database is a better choice.

Insert an item into sorted list in Python

I'm learning Algorithm right now, so i wonder how bisect module writes. Here is the code from bisect module about inserting an item into sorted list, which uses dichotomy:

def insort_right(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.
    If x is already in a, insert it to the right of the rightmost x.
    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """

    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x < a[mid]:
            hi = mid
        else:
            lo = mid+1
    a.insert(lo, x)

In Git, what is the difference between origin/master vs origin master?

origin is a name for remote git url. There can be many more remotes example below.

bangalore => bangalore.example.com:project.git

boston => boston.example.com:project.git

as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.

It is possible that remote bangalore has advanced since you have done "fetch" or "pull"

How to debug in Django, the good way?

I find Visual Studio Code is awesome for debugging Django apps. The standard python launch.json parameters run python manage.py with the debugger attached, so you can set breakpoints and step through your code as you like.

Parse String to Date with Different Format in Java

Check the javadocs for java.text.SimpleDateFormat It describes everything you need.

SSIS Excel Connection Manager failed to Connect to the Source

you can try this:

Uninstall office365

then install only Access Database Engine 2016 Redistributable 64 bit

Also set Project Configuration Properties for Debugging Run64BitRuntime = False

It should work.

How to find top three highest salary in emp table in oracle?

SELECT  *FROM 
    (
    SELECT *FROM emp 
    ORDER BY Salary desc
    )
WHERE rownum <= 3
ORDER BY Salary ;

Remove array element based on object property

var myArray = [
    {field: 'id', operator: 'eq', value: id}, 
    {field: 'cStatus', operator: 'eq', value: cStatus}, 
    {field: 'money', operator: 'eq', value: money}
];
console.log(myArray.length); //3
myArray = $.grep(myArray, function(element, index){return element.field == "money"}, true);
console.log(myArray.length); //2

Element is an object in the array. 3rd parameter true means will return an array of elements which fails your function logic, false means will return an array of elements which fails your function logic.

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

Post is rather old and not closely related to Chrome extensions development, but let it be here.

I had same problem when responding on message in callback. The solution is to return true in background message listener.

Here is simple example of background.js. It responses to any message from popup.js.

chrome.runtime.onMessage.addListener(function(rq, sender, sendResponse) {
    // setTimeout to simulate any callback (even from storage.sync)
    setTimeout(function() {
        sendResponse({status: true});
    }, 1);
    // return true;  // uncomment this line to fix error
});

Here is popup.js, which sends message on popup. You'll get exceptions until you un-comment "return true" line in background.js file.

document.addEventListener("DOMContentLoaded", () => {
    chrome.extension.sendMessage({action: "ping"}, function(resp) {
        console.log(JSON.stringify(resp));
    });
});

manifest.json, just in case :) Pay attention on alarm permissions section!

{
  "name": "TestMessages",
  "version": "0.1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "src/popup.html"
  },
  "background": {
    "scripts": ["src/background.js"],
    "persistent": false
  },
  "permissions": [
    "alarms"
  ]
}

jQuery Clone table row

Here you go:

$( table ).delegate( '.tr_clone_add', 'click', function () {
    var thisRow = $( this ).closest( 'tr' )[0];
    $( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});

Live demo: http://jsfiddle.net/RhjxK/4/


Update: The new way of delegating events in jQuery is

$(table).on('click', '.tr_clone_add', function () { … });

Python: How exactly can you take a string, split it, reverse it and join it back together again?

I was asked to do so without using any inbuilt function. So I wrote three functions for these tasks. Here is the code-

def string_to_list(string):
'''function takes actual string and put each word of string in a list'''
list_ = []
x = 0 #Here x tracks the starting of word while y look after the end of word.
for y in range(len(string)):
    if string[y]==" ":
        list_.append(string[x:y])
        x = y+1
    elif y==len(string)-1:
        list_.append(string[x:y+1])
return list_

def list_to_reverse(list_):
'''Function takes the list of words and reverses that list'''
reversed_list = []
for element in list_[::-1]:
    reversed_list.append(element)
return reversed_list

def list_to_string(list_):
'''This function takes the list and put all the elements of the list to a string with 
space as a separator'''
final_string = str()
for element in list_:
    final_string += str(element) + " "
return final_string

#Output
text = "I love India"
list_ = string_to_list(text)
reverse_list = list_to_reverse(list_)
final_string = list_to_string(reverse_list)
print("Input is - {}; Output is - {}".format(text, final_string))
#op= Input is - I love India; Output is - India love I 

Please remember, This is one of a simpler solution. This can be optimized so try that. Thank you!

Spring Boot application as a Service

If you want to use Spring Boot 1.2.5 with Spring Boot Maven Plugin 1.3.0.M2, here's out solution:

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

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <version>1.3.0.M2</version>
            <configuration>
                <executable>true</executable>
            </configuration>
        </plugin>
    </plugins>
</build>

<pluginRepositories>
    <pluginRepository>
        <id>spring-libs-milestones</id>
        <url>http://repo.spring.io/libs-milestone</url>
    </pluginRepository> 
</pluginRepositories>

Then compile as ususal: mvn clean package, make a symlink ln -s /.../myapp.jar /etc/init.d/myapp, make it executable chmod +x /etc/init.d/myapp and start it service myapp start (with Ubuntu Server)

Better naming in Tuple classes than "Item1", "Item2"

(double, int) t1 = (4.5, 3);
Console.WriteLine($"Tuple with elements {t1.Item1} and {t1.Item2}.");
// Output:
// Tuple with elements 4.5 and 3.

(double Sum, int Count) t2 = (4.5, 3);
Console.WriteLine($"Sum of {t2.Count} elements is {t2.Sum}.");
// Output:
// Sum of 3 elements is 4.5.
From Docs https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

An easy approach is to leverage this code:

<a href="javascript:void(0);">Link Title</a>

This approach doesn't force a page refresh, so the scrollbar stays in place. Also, it allows you to programmatically change the onclick event and handle client side event binding using jQuery.

For these reasons, the above solution is better than:

<a href="javascript:myClickHandler();">Link Title</a>
<a href="#" onclick="myClickHandler(); return false;">Link Title</a>

where the last solution will avoid the scroll-jump issue if and only if the myClickHandler method doesn't fail.

How do I kill the process currently using a port on localhost in Windows?

I was running zookeeper on Windows and wasn't able to stop ZooKeeper running at 2181 port using zookeeper-stop.sh, so tried this double slash "//" method to taskkill. It worked

     1. netstat -ano | findstr :2181
       TCP    0.0.0.0:2181           0.0.0.0:0              LISTENING       8876
       TCP    [::]:2181              [::]:0                 LISTENING       8876

     2.taskkill //PID 8876 //F
       SUCCESS: The process with PID 8876 has been terminated.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

It looks like a common gaps-and-islands problem. The difference between two sequences of row numbers rn1 and rn2 give the "group" number.

Run this query CTE-by-CTE and examine intermediate results to see how it works.

Sample data

I expanded sample data from the question a little.

DECLARE @Source TABLE
(
    EmployeeID int,
    DateStarted date,
    DepartmentID int
)

INSERT INTO @Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001),

(10005,'2013-05-01',001),
(10005,'2013-11-09',001),
(10005,'2013-12-01',002),
(10005,'2014-10-01',001),
(10005,'2016-12-01',001);

Query for SQL Server 2008

There is no LEAD function in SQL Server 2008, so I had to use self-join via OUTER APPLY to get the value of the "next" row for the DateEnd.

WITH
CTE
AS
(
    SELECT
        EmployeeID
        ,DateStarted
        ,DepartmentID
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
    FROM @Source
)
,CTE_Groups
AS
(
    SELECT
        EmployeeID
        ,MIN(DateStarted) AS DateStart
        ,DepartmentID
    FROM CTE
    GROUP BY
        EmployeeID
        ,DepartmentID
        ,rn1 - rn2
)
SELECT
    CTE_Groups.EmployeeID
    ,CTE_Groups.DepartmentID
    ,CTE_Groups.DateStart
    ,A.DateEnd
FROM
    CTE_Groups
    OUTER APPLY
    (
        SELECT TOP(1) G2.DateStart AS DateEnd
        FROM CTE_Groups AS G2
        WHERE
            G2.EmployeeID = CTE_Groups.EmployeeID
            AND G2.DateStart > CTE_Groups.DateStart
        ORDER BY G2.DateStart
    ) AS A
ORDER BY
    EmployeeID
    ,DateStart
;

Query for SQL Server 2012+

Starting with SQL Server 2012 there is a LEAD function that makes this task more efficient.

WITH
CTE
AS
(
    SELECT
        EmployeeID
        ,DateStarted
        ,DepartmentID
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
    FROM @Source
)
,CTE_Groups
AS
(
    SELECT
        EmployeeID
        ,MIN(DateStarted) AS DateStart
        ,DepartmentID
    FROM CTE
    GROUP BY
        EmployeeID
        ,DepartmentID
        ,rn1 - rn2
)
SELECT
    CTE_Groups.EmployeeID
    ,CTE_Groups.DepartmentID
    ,CTE_Groups.DateStart
    ,LEAD(CTE_Groups.DateStart) OVER (PARTITION BY CTE_Groups.EmployeeID ORDER BY CTE_Groups.DateStart) AS DateEnd
FROM
    CTE_Groups
ORDER BY
    EmployeeID
    ,DateStart
;

Result

+------------+--------------+------------+------------+
| EmployeeID | DepartmentID | DateStart  |  DateEnd   |
+------------+--------------+------------+------------+
|      10001 |            1 | 2013-01-01 | 2013-12-01 |
|      10001 |            2 | 2013-12-01 | 2014-10-01 |
|      10001 |            1 | 2014-10-01 | NULL       |
|      10005 |            1 | 2013-05-01 | 2013-12-01 |
|      10005 |            2 | 2013-12-01 | 2014-10-01 |
|      10005 |            1 | 2014-10-01 | NULL       |
+------------+--------------+------------+------------+

Bootstrap 3 truncate long text inside rows of a table in a responsive way

You need to use table-layout:fixed in order for CSS ellipsis to work on the table cells.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

demo: http://bootply.com/9njmoY2CmS

How do I validate a date in this format (yyyy-mm-dd) using jquery?

try this Here is working Demo:

$(function() {
    $('#btnSubmit').bind('click', function(){
        var txtVal =  $('#txtDate').val();
        if(isDate(txtVal))
            alert('Valid Date');
        else
            alert('Invalid Date');
    });

function isDate(txtDate)
{
    var currVal = txtDate;
    if(currVal == '')
        return false;

    var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex
    var dtArray = currVal.match(rxDatePattern); // is format OK?

    if (dtArray == null) 
        return false;

    //Checks for mm/dd/yyyy format.
    dtMonth = dtArray[3];
    dtDay= dtArray[5];
    dtYear = dtArray[1];        

    if (dtMonth < 1 || dtMonth > 12) 
        return false;
    else if (dtDay < 1 || dtDay> 31) 
        return false;
    else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) 
        return false;
    else if (dtMonth == 2) 
    {
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
        if (dtDay> 29 || (dtDay ==29 && !isleap)) 
                return false;
    }
    return true;
}

});

changed regex is:

var rxDatePattern = /^(\d{4})(\/|-)(\d{1,2})(\/|-)(\d{1,2})$/; //Declare Regex

Using global variables in a function

Use global keyword:

#Creating global variable
glob_var=0

def use():
    #Accessing global variable
    global glob_var
 
    #Changing value of global variable
    glob_var=2

def show():
    #Showing value of global variable
    print(glob_var)

if __name__=='__main__':
    use()
    show()

How can I detect if this dictionary key exists in C#?

What is the type of c.PhysicalAddresses? If it's Dictionary<TKey,TValue>, then you can use the ContainsKey method.

What is `git push origin master`? Help with git's refs, heads and remotes

Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

Commands

Make sure you're on your master branch with

1)git checkout master

then create the new branch with

2)git branch --track my_test origin/my_test

and check it out with

3)git checkout my_test.

You can then push and pull without specifying which local and remote.

However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config

The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

You can find something very similar to this in the config after running the commands above.

Some useful resources:

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

TL;DR: python -m pip install -U pip, then try again.


I was already using a venv (virtualenv) in PyCharm.

Creating it I clicked inherit global site packages checkbox, to allow packages installed via an installer to work. Now inside my venv there was no pip installed, so it would use the inherited global pip.

Here is how the error went:

(venv) D:\path\to\my\project> pip install certifi  # or any other package

Would fail with

PermissionError: [WinError 5] Access denied: 'c:\\program files\\python36\\Lib\\site-packages\\certifi'

Notice how that is the path of the system python, not the venv one. However we want it to execute in the right environment.

Here some more digging:

(venv) D:\path\to\my\project> which pip
/c/Program Files/Python36/Scripts/pip

(venv) D:\path\to\my\project> which python
/d/path/to/my/project/venv/Scripts/python

So python is using the correct path, but pip is not? Let's install pip here in the correct one as well:

(venv) D:\path\to\my\project> python -m pip install -U pip
... does stuff ...
Successfully installed pip

Now that's better. Running the original failing command again now works, as it is using the correct pip.

(venv) D:\path\to\my\project> pip install certifi  # or any other package
... install noise ...
Successfully installed certifi-2019.9.11 chardet-3.0.4 idna-2.8 requests-2.22.0 urllib3-1.25.7

CSS: Creating textured backgrounds

with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#

but it still limited on so many aspect. And browser support is also not so ready.

your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:

http://subtlepatterns.com

What is the simplest way to convert array to vector?

One simple way can be the use of assign() function that is pre-defined in vector class.

e.g.

array[5]={1,2,3,4,5};

vector<int> v;
v.assign(array, array+5); // 5 is size of array.

Using an integer as a key in an associative array in JavaScript

Get the value for an associative array property when the property name is an integer:

Starting with an associative array where the property names are integers:

var categories = [
    {"1": "Category 1"},
    {"2": "Category 2"},
    {"3": "Category 3"},
    {"4": "Category 4"}
];

Push items to the array:

categories.push({"2300": "Category 2300"});
categories.push({"2301": "Category 2301"});

Loop through the array and do something with the property value.

for (var i = 0; i < categories.length; i++) {
    for (var categoryid in categories[i]) {
        var category = categories[i][categoryid];
        // Log progress to the console
        console.log(categoryid + ": " + category);
        //  ... do something
    }
}

Console output should look like this:

1: Category 1
2: Category 2
3: Category 3
4: Category 4
2300: Category 2300
2301: Category 2301

As you can see, you can get around the associative array limitation and have a property name be an integer.

NOTE: The associative array in my example is the JSON content you would have if you serialized a Dictionary<string, string>[] object.

Calculate number of hours between 2 dates in PHP

Carbon could also be a nice way to go.

From their website:

A simple PHP API extension for DateTime. http://carbon.nesbot.com/

Example:

use Carbon\Carbon;

//...

$day1 = Carbon::createFromFormat('Y-m-d H:i:s', '2006-04-12 12:30:00');
$day2 = Carbon::createFromFormat('Y-m-d H:i:s', '2006-04-14 11:30:00');

echo $day1->diffInHours($day2); // 47

//...

Carbon extends the DateTime class to inherit methods including diff(). It adds nice sugars like diffInHours, diffInMintutes, diffInSeconds e.t.c.

node.js: read a text file into an array. (Each line an item in the array.)

Using the Node.js readline module.

var fs = require('fs');
var readline = require('readline');

var filename = process.argv[2];
readline.createInterface({
    input: fs.createReadStream(filename),
    terminal: false
}).on('line', function(line) {
   console.log('Line: ' + line);
});

Is CSS Turing complete?

CSS is not a programming language, so the question of turing-completeness is a meaningless one. If programming extensions are added to CSS such as was the case in IE6 then that new synthesis is a whole different thing.

CSS is merely a description of styles; it does not have any logic, and its structure is flat.

How to inflate one view with a layout

With Kotlin, you can use:

val content = LayoutInflater.from(context).inflate(R.layout.[custom_layout_name], null)

[your_main_layout].apply {
    //..
    addView(content)
}

Input and Output binary streams using JERSEY?

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

FileStreamingOutput

public class FileStreamingOutput implements StreamingOutput {

    private File file;

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

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

}

GET

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

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

    return new FileStreamingOutput(pdf);
}

And the client, if you need it:

Client

private WebResource resource;

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

Convert integer value to matching Java Enum

There is no way to elegantly handle integer-based enumerated types. You might think of using a string-based enumeration instead of your solution. Not a preferred way all the times, but it still exists.

public enum Port {
  /**
   * The default port for the push server.
   */
  DEFAULT("443"),

  /**
   * The alternative port that can be used to bypass firewall checks
   * made to the default <i>HTTPS</i> port.
   */
  ALTERNATIVE("2197");

  private final String portString;

  Port(final String portString) {
    this.portString = portString;
  }

  /**
   * Returns the port for given {@link Port} enumeration value.
   * @return The port of the push server host.
   */
  public Integer toInteger() {
    return Integer.parseInt(portString);
  }
}

Spring MVC + JSON = 406 Not Acceptable

One more way you can get this error is to create a class with no public members. 406 unacceptable is a pretty useless error message in this scenario.

Check if string contains only digits

Here is a solution without using regular expressions:

function onlyDigits(s) {
  for (let i = s.length - 1; i >= 0; i--) {
    const d = s.charCodeAt(i);
    if (d < 48 || d > 57) return false
  }
  return true
}

where 48 and 57 are the char codes for "0" and "9", respectively.

WhatsApp API (java/python)

Yowsup provide best solution with example.you can download api from https://github.com/tgalal/yowsup let me know if you have any issue.

Access parent's parent from javascript object

I used something that resembles singleton pattern:

function myclass() = {
    var instance = this;

    this.Days = function() {
        var days = ["Piatek", "Sobota", "Niedziela"];
        return days;
    }

    this.EventTime = function(day, hours, minutes) {
        this.Day = instance.Days()[day];
        this.Hours = hours;
        this.minutes = minutes;
        this.TotalMinutes = day*24*60 + 60*hours + minutes;
    }
}

SQL Server Operating system error 5: "5(Access is denied.)"

In linux, I went to /var/opt/mssql/data/ folder and opened a terminal with sudo then, changed my *.mdf and *.ldf file permissions as below in which you replace yourDB with your Database file name and myUser to currently logged username:

chmod 755 yourDB.mdf
chown myUser yourDB.mdf

chmod 755 yourDB.ldf
chown myUser yourDB.ldf

After that, it was reconnected without any issue.

How to get the current URL within a Django template?

In Django 3, you want to use url template tag:

{% url 'name-of-your-user-profile-url' possible_context_variable_parameter %}

For an example, see the documentation

Get Absolute Position of element within the window in wpf

Add this method to a static class:

 public static Rect GetAbsolutePlacement(this FrameworkElement element, bool relativeToScreen = false)
    {
        var absolutePos = element.PointToScreen(new System.Windows.Point(0, 0));
        if (relativeToScreen)
        {
            return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
        }
        var posMW = Application.Current.MainWindow.PointToScreen(new System.Windows.Point(0, 0));
        absolutePos = new System.Windows.Point(absolutePos.X - posMW.X, absolutePos.Y - posMW.Y);
        return new Rect(absolutePos.X, absolutePos.Y, element.ActualWidth, element.ActualHeight);
    }

Set relativeToScreen paramater to true for placement from top left corner of whole screen or to false for placement from top left corner of application window.

How to load URL in UIWebView in Swift?

UIWebView loadRequest: Create NSURLRequest using NSURL object, then passing the request to uiwebview it will load the requested URL into the web view.

 override func viewDidLoad() {
     super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.
     let url = NSURL (string: "http://www.google.com");
     let requestObj = NSURLRequest(URL: url!);
     myWebView.loadRequest(requestObj);
     self.view.addSubview(myWebView)
  }

For more reference:

http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/

PHP: Best way to check if input is a valid number?

return ctype_digit($num) && (int) $num > 0

PHP: How to remove all non printable characters in a string?

All of the solutions work partially, and even below probably does not cover all of the cases. My issue was in trying to insert a string into a utf8 mysql table. The string (and its bytes) all conformed to utf8, but had several bad sequences. I assume that most of them were control or formatting.

function clean_string($string) {
  $s = trim($string);
  $s = iconv("UTF-8", "UTF-8//IGNORE", $s); // drop all non utf-8 characters

  // this is some bad utf-8 byte sequence that makes mysql complain - control and formatting i think
  $s = preg_replace('/(?>[\x00-\x1F]|\xC2[\x80-\x9F]|\xE2[\x80-\x8F]{2}|\xE2\x80[\xA4-\xA8]|\xE2\x81[\x9F-\xAF])/', ' ', $s);

  $s = preg_replace('/\s+/', ' ', $s); // reduce all multiple whitespace to a single space

  return $s;
}

To further exacerbate the problem is the table vs. server vs. connection vs. rendering of the content, as talked about a little here

How to add composite primary key to table

You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:

This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.

CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)

If you don't have a table that we can reference, add one like this so that the example will work:

CREATE TABLE Codes (
    Code [varchar](2) PRIMARY KEY   
    )

NOTE: you must have a table to reference before creating the foreign key.

Convert one date format into another in PHP

Try this:

$tempDate = explode('-','03-23-15');
$date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1];

How to remove a package in sublime text 2

Sublime Text 3

Procedure


Run Sublime Text.


Select Preferences ? Package Control.

Or

Use ctrl+shift+p shortcut for (Win, Linux) or cmd+shift+p for (OS X).


Select Remove Package. Package Control: Remove Package


Start typing name of the package you want to remove and select it from the list of installed packages.


Wait for the uninstallation to complete.

Make Div Draggable using CSS

You can do it now by using the CSS property -webkit-user-drag:

_x000D_
_x000D_
#drag_me {_x000D_
  -webkit-user-drag: element;_x000D_
}
_x000D_
<div draggable="true" id="drag_me">_x000D_
  Your draggable content here_x000D_
</div>
_x000D_
_x000D_
_x000D_

This property is only supported by webkit browsers, such as Safari or Chrome, but it is a nice approach to get it working using only CSS.

The HTML5 draggable attribute is only set to ensure dragging works for other browsers.

You can find more information here: http://help.dottoro.com/lcbixvwm.php

How to copy a directory structure but only include certain files (using windows batch files)

For those using Altap Salamander (2 panels file manager) : in the Options of the Copy popup, just specify the file names or masks. Easy.

Initializing C# auto-properties

This will be possible in C# 6.0:

public int Y { get; } = 2;

Django URL Redirect

You can try the Class Based View called RedirectView

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

Notice how as url in the <url_to_home_view> you need to actually specify the url.

permanent=False will return HTTP 302, while permanent=True will return HTTP 301.

Alternatively you can use django.shortcuts.redirect

Update for Django 2+ versions

With Django 2+, url() is deprecated and replaced by re_path(). Usage is exactly the same as url() with regular expressions. For replacements without the need of regular expression, use path().

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')

C++ Double Address Operator? (&&)

As other answers have mentioned, the && token in this context is new to C++0x (the next C++ standard) and represent an "rvalue reference".

Rvalue references are one of the more important new things in the upcoming standard; they enable support for 'move' semantics on objects and permit perfect forwarding of function calls.

It's a rather complex topic - one of the best introductions (that's not merely cursory) is an article by Stephan T. Lavavej, "Rvalue References: C++0x Features in VC10, Part 2"

Note that the article is still quite heavy reading, but well worthwhile. And even though it's on a Microsoft VC++ Blog, all (or nearly all) the information is applicable to any C++0x compiler.

How to start a Process as administrator mode in C#

Here is an example of run process as administrator without Windows Prompt

  Process p = new Process();
  p.StartInfo.FileName = Server.MapPath("process.exe");
  p.StartInfo.Arguments = "";
  p.StartInfo.UseShellExecute = false;
  p.StartInfo.CreateNoWindow = true;
  p.StartInfo.RedirectStandardOutput = true;
  p.StartInfo.Verb = "runas";
  p.Start();
  p.WaitForExit();

How to update a record using sequelize for node?

hi to update the record it very simple

  1. sequelize find the record by ID (or by what you want)
  2. then you pass the params with result.feild = updatedField
  3. if the record doesn'texist in database sequelize create a new record with the params
  4. watch the exemple for more understand Code #1 test that code for all version under V4
const sequelizeModel = require("../models/sequelizeModel");
    const id = req.params.id;
            sequelizeModel.findAll(id)
            .then((result)=>{
                result.name = updatedName;
                result.lastname = updatedLastname;
                result.price = updatedPrice;
                result.tele = updatedTele;
                return result.save()
            })
            .then((result)=>{
                    console.log("the data was Updated");
                })
            .catch((err)=>{
                console.log("Error : ",err)
            });

Code for V5

const id = req.params.id;
            const name = req.body.name;
            const lastname = req.body.lastname;
            const tele = req.body.tele;
            const price = req.body.price;
    StudentWork.update(
        {
            name        : name,
            lastname    : lastname,
            tele        : tele,
            price       : price
        },
        {returning: true, where: {id: id} }
      )
            .then((result)=>{
                console.log("data was Updated");
                res.redirect('/');
            })
    .catch((err)=>{
        console.log("Error : ",err)
    });

How to make the Facebook Like Box responsive?

As of August 4 2015, the native facebook like box have a responsive code snippet available at Facebook Developers page.

You can generate your responsive Facebook likebox here

https://developers.facebook.com/docs/plugins/page-plugin

This is the best solution ever rather than hacking CSS.

Change the mouse pointer using JavaScript

With regards to @CrazyJugglerDrummer second method it would be:

elementsToChange.style.cursor = "http://wiki-devel.sugarlabs.org/images/e/e2/Arrow.cur";

wordpress contactform7 textarea cols and rows change in smaller screens

I know this post is old, sorry for that.

You can also type 10x for cols and x2 for rows, if you want to have only one attribute.

[textarea* your-message x3 class:form-control] <!-- only rows -->
[textarea* your-message 10x class:form-control] <!-- only columns -->
[textarea* your-message 10x3 class:form-control] <!-- both -->

google-services.json for different productFlavors

Inspired by @ahmed_khan_89 answer above. We can directly keep like this in gradle file.

android{

// set build flavor here to get the right Google-services configuration(Google Analytics).
    def currentFlavor = "free" //This should match with Build Variant selection. free/paidFull/paidBasic

    println "--> $currentFlavor copy!"
    copy {
        from "src/$currentFlavor/"
        include 'google-services.json'
        into '.'
    }
//other stuff
}

How do I write to a Python subprocess' stdin?

To clarify some points:

As jro has mentioned, the right way is to use subprocess.communicate.

Yet, when feeding the stdin using subprocess.communicate with input, you need to initiate the subprocess with stdin=subprocess.PIPE according to the docs.

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Also qed has mentioned in the comments that for Python 3.4 you need to encode the string, meaning you need to pass Bytes to the input rather than a string. This is not entirely true. According to the docs, if the streams were opened in text mode, the input should be a string (source is the same page).

If streams were opened in text mode, input must be a string. Otherwise, it must be bytes.

So, if the streams were not opened explicitly in text mode, then something like below should work:

import subprocess
command = ['myapp', '--arg1', 'value_for_arg1']
p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate(input='some data'.encode())[0]

I've left the stderr value above deliberately as STDOUT as an example.

That being said, sometimes you might want the output of another process rather than building it up from scratch. Let's say you want to run the equivalent of echo -n 'CATCH\nme' | grep -i catch | wc -m. This should normally return the number characters in 'CATCH' plus a newline character, which results in 6. The point of the echo here is to feed the CATCH\nme data to grep. So we can feed the data to grep with stdin in the Python subprocess chain as a variable, and then pass the stdout as a PIPE to the wc process' stdin (in the meantime, get rid of the extra newline character):

import subprocess

what_to_catch = 'catch'
what_to_feed = 'CATCH\nme'

# We create the first subprocess, note that we need stdin=PIPE and stdout=PIPE
p1 = subprocess.Popen(['grep', '-i', what_to_catch], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We immediately run the first subprocess and get the result
# Note that we encode the data, otherwise we'd get a TypeError
p1_out = p1.communicate(input=what_to_feed.encode())[0]

# Well the result includes an '\n' at the end, 
# if we want to get rid of it in a VERY hacky way
p1_out = p1_out.decode().strip().encode()

# We create the second subprocess, note that we need stdin=PIPE
p2 = subprocess.Popen(['wc', '-m'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# We run the second subprocess feeding it with the first subprocess' output.
# We decode the output to convert to a string
# We still have a '\n', so we strip that out
output = p2.communicate(input=p1_out)[0].decode().strip()

This is somewhat different than the response here, where you pipe two processes directly without adding data directly in Python.

Hope that helps someone out.

How to get a specific output iterating a hash in Ruby?

You can also refine Hash::each so it will support recursive enumeration. Here is my version of Hash::each(Hash::each_pair) with block and enumerator support:

module HashRecursive
    refine Hash do
        def each(recursive=false, &block)
            if recursive
                Enumerator.new do |yielder|
                    self.map do |key, value|
                        value.each(recursive=true).map{ |key_next, value_next| yielder << [[key, key_next].flatten, value_next] } if value.is_a?(Hash)
                        yielder << [[key], value]
                    end
                end.entries.each(&block)
            else
                super(&block)
            end
        end
        alias_method(:each_pair, :each)
    end
end

using HashRecursive

Here are usage examples of Hash::each with and without recursive flag:

hash = {
    :a => {
        :b => {
            :c => 1,
            :d => [2, 3, 4]
        },
        :e => 5
    },
    :f => 6
}

p hash.each, hash.each {}, hash.each.size
# #<Enumerator: {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}:each>
# {:a=>{:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}, :f=>6}
# 2

p hash.each(true), hash.each(true) {}, hash.each(true).size
# #<Enumerator: [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]:each>
# [[[:a, :b, :c], 1], [[:a, :b, :d], [2, 3, 4]], [[:a, :b], {:c=>1, :d=>[2, 3, 4]}], [[:a, :e], 5], [[:a], {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}], [[:f], 6]]
# 6

hash.each do |key, value|
    puts "#{key} => #{value}"
end
# a => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# f => 6

hash.each(true) do |key, value|
    puts "#{key} => #{value}"
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :b] => {:c=>1, :d=>[2, 3, 4]}
# [:a, :e] => 5
# [:a] => {:b=>{:c=>1, :d=>[2, 3, 4]}, :e=>5}
# [:f] => 6

hash.each_pair(recursive=true) do |key, value|
    puts "#{key} => #{value}" unless value.is_a?(Hash)
end
# [:a, :b, :c] => 1
# [:a, :b, :d] => [2, 3, 4]
# [:a, :e] => 5
# [:f] => 6

Here is example from the question itself:

hash = {
    1   =>  ["a", "b"], 
    2   =>  ["c"], 
    3   =>  ["a", "d", "f", "g"], 
    4   =>  ["q"]
}

hash.each(recursive=false) do |key, value|
    puts "#{key} => #{value}"
end
# 1 => ["a", "b"]
# 2 => ["c"]
# 3 => ["a", "d", "f", "g"]
# 4 => ["q"]

Also take a look at my recursive version of Hash::merge(Hash::merge!) here.

Completely removing phpMyAdmin

I had same problem. Try the following command. This solved my problem.

sudo apt-get install libapache2-mod-php5

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !

How to sort a list of lists by a specific index of the inner list?

Make sure that you do not have any null or NaN values in the list you want to sort. If there are NaN values, then your sort will be off, impacting the sorting of the non-null values.

Check out Python: sort function breaks in the presence of nan

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

This question helped me.

So, try this:

Controller code:

[HttpGet]
public HttpResponseMessage Test()
{
    var path = System.Web.HttpContext.Current.Server.MapPath("~/Content/test.docx");;
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    result.Content.Headers.ContentLength = stream.Length;
    return result;          
}

View Html markup (with click event and simple url):

<script type="text/javascript">
    $(document).ready(function () {
        $("#btn").click(function () {
            // httproute = "" - using this to construct proper web api links.
            window.location.href = "@Url.Action("GetFile", "Data", new { httproute = "" })";
        });
    });
</script>


<button id="btn">
    Button text
</button>

<a href=" @Url.Action("GetFile", "Data", new { httproute = "" }) ">Data</a>

How to get time difference in minutes in PHP

<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>

Error: fix the version conflict (google-services plugin)

I think you change

compile 'com.google.firebase:firebase-messaging:11.0.4'

Python xticks in subplots

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

  • If you want to set the xticklabels:

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

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

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

How do I use the Simple HTTP client in Android?

You can use this code:

int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.setConnectTimeout(TIME_OUT);
                conection.connect();
                // Getting file length
                int lenghtOfFile = conection.getContentLength();
                // Create a Input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);
                // Output stream to write file
                OutputStream output = new FileOutputStream(
                        "/sdcard/9androidnet.jpg");

                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (SocketTimeoutException e) {
                connectionTimeout=true;
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

jQuery check if it is clicked or not

Alright, before I go into the solution, lets be on the same line about this one fact: Javascript is Event Based. So you'll usually have to setup callbacks to be able to do procedures.

Based on your comment I assumed you have a trigger that will do the logic that launched the function depending if the element is clicked; for sake of demonstration I made it a "submit button"; but this can be a timer or something else.

var the_action = function(type) {
    switch(type) {
        case 'a':
            console.log('Case A');
            break;
         case 'b':
            console.log('Case B');
            break;
    }
};

$('.clickme').click(function() { 
    console.log('Clicked');
    $(this).data('clicked', true);
});

$('.submit').click(function() {
    // All your logic can go here if you want.
    if($('.clickme').data('clicked') == true) {
        the_action('a');
    } else {
        the_action('b');
    }
});

Live Example: http://jsfiddle.net/kuroir/6MCVJ/

Mapping object to dictionary and vice versa

Using some reflection and generics in two extension methods you can achieve that.

Right, others did mostly the same solution, but this uses less reflection which is more performance-wise and way more readable:

public static class ObjectExtensions
{
    public static T ToObject<T>(this IDictionary<string, object> source)
        where T : class, new()
    {
            var someObject = new T();
            var someObjectType = someObject.GetType();

            foreach (var item in source)
            {
                someObjectType
                         .GetProperty(item.Key)
                         .SetValue(someObject, item.Value, null);
            }

            return someObject;
    }

    public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    {
        return source.GetType().GetProperties(bindingAttr).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null)
        );

    }
}

class A
{
    public string Prop1
    {
        get;
        set;
    }

    public int Prop2
    {
        get;
        set;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        dictionary.Add("Prop1", "hello world!");
        dictionary.Add("Prop2", 3893);
        A someObject = dictionary.ToObject<A>();

        IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
    }
}

Add a scrollbar to a <textarea>

HTML:

<textarea rows="10" cols="20" id="text"></textarea>

CSS:

#text
{
    overflow-y:scroll;
}

Static methods in Python?

Static methods in Python?

Is it possible to have static methods in Python so I can call them without initializing a class, like:

ClassName.StaticMethod()

Yes, static methods can be created like this (although it's a bit more Pythonic to use underscores instead of CamelCase for methods):

class ClassName(object):

    @staticmethod
    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

The above uses the decorator syntax. This syntax is equivalent to

class ClassName(object):

    def static_method(kwarg1=None):
        '''return a value that is a function of kwarg1'''

    static_method = staticmethod(static_method)

This can be used just as you described:

ClassName.static_method()

A builtin example of a static method is str.maketrans() in Python 3, which was a function in the string module in Python 2.


Another option that can be used as you describe is the classmethod, the difference is that the classmethod gets the class as an implicit first argument, and if subclassed, then it gets the subclass as the implicit first argument.

class ClassName(object):

    @classmethod
    def class_method(cls, kwarg1=None):
        '''return a value that is a function of the class and kwarg1'''

Note that cls is not a required name for the first argument, but most experienced Python coders will consider it badly done if you use anything else.

These are typically used as alternative constructors.

new_instance = ClassName.class_method()

A builtin example is dict.fromkeys():

new_dict = dict.fromkeys(['key1', 'key2'])

Angular 2 http post params and body

And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

The JDK has switched locations of java.exe between 1.6 and 1.7!!!

In my case I found that the JAVA_HOME for the JDK had to add the \jre on the end. The mvn bat file is looking for java.exe and it looks for it in JAVA_HOME\bin. Its not there for JDK 1.7; it is in JAVA_HOME\jre\bin. In JDK 1.6 such it IS in JAVA_HOME\bin.

Hope this helps somebody.

How do I print colored output to the terminal in Python?

You can try this with python 3:

from termcolor import colored
print(colored('Hello, World!', 'green', 'on_red'))

If you are using windows operating system, the above code may not work for you. Then you can try this code:

from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

Hope that helps.

Correct way to initialize empty slice

As an addition to @ANisus' answer...

below is some information from the "Go in action" book, which I think is worth mentioning:

Difference between nil & empty slices

If we think of a slice like this:

[pointer] [length] [capacity]

then:

nil slice:   [nil][0][0]
empty slice: [addr][0][0] // points to an address

nil slice

They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.

// Create a nil slice of integers.
var slice []int

empty slice

Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.

// Use make to create an empty slice of integers.
slice := make([]int, 0)

// Use a slice literal to create an empty slice of integers.
slice := []int{}

Regardless of whether you’re using a nil slice or an empty slice, the built-in functions append, len, and cap work the same.


Go playground example:

package main

import (
    "fmt"
)

func main() {

    var nil_slice []int
    var empty_slice = []int{}

    fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
    fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))

}

prints:

true 0 0
false 0 0

What is the difference between a .cpp file and a .h file?

A header (.h, .hpp, ...) file contains

  • Class definitions ( class X { ... }; )
  • Inline function definitions ( inline int get_cpus() { ... } )
  • Function declarations ( void help(); )
  • Object declarations ( extern int debug_enabled; )

A source file (.c, .cpp, .cxx) contains

  • Function definitions ( void help() { ... } or void X::f() { ... } )
  • Object definitions ( int debug_enabled = 1; )

However, the convention that headers are named with a .h suffix and source files are named with a .cpp suffix is not really required. One can always tell a good compiler how to treat some file, irrespective of its file-name suffix ( -x <file-type> for gcc. Like -x c++ ).

Source files will contain definitions that must be present only once in the whole program. So if you include a source file somewhere and then link the result of compilation of that file and then the one of the source file itself together, then of course you will get linker errors, because you have those definitions now appear twice: Once in the included source file, and then in the file that included it. That's why you had problems with including the .cpp file.

How to check if a variable is empty in python?

See also this previous answer which recommends the not keyword

How to check if a list is empty in Python?

It generalizes to more than just lists:

>>> a = ""
>>> not a
True

>>> a = []
>>> not a
True

>>> a = 0
>>> not a
True

>>> a = 0.0
>>> not a
True

>>> a = numpy.array([])
>>> not a
True

Notably, it will not work for "0" as a string because the string does in fact contain something - a character containing "0". For that you have to convert it to an int:

>>> a = "0"
>>> not a
False

>>> a = '0'
>>> not int(a)
True

VBA - Select columns using numbers?

no need for loops or such.. try this..

dim startColumnas integer

dim endColumn as integer

startColumn = 7

endColumn = 24

Range(Cells(, startColumn), Cells(, endColumn)).ColumnWidth = 3.8 ' <~~ whatever width you want to set..* 

How to get input from user at runtime

you can try this too And it will work:

DECLARE
  a NUMBER;
  b NUMBER;
BEGIN
  a :=: a; --this will take input from user
  b :=: b;
  DBMS_OUTPUT.PUT_LINE('a = '|| a);
  DBMS_OUTPUT.PUT_LINE('b = '|| b);
END;

Rethrowing exceptions in Java without losing the stack trace

In Java is almost the same:

try
{
   ...
}
catch (Exception e)
{
   if (e instanceof FooException)
     throw e;
}

MVC controller : get JSON object from HTTP body?

Once you define a class (MyDTOClass) indicating what you expect to receive it should be as simple as...

public ActionResult Post([FromBody]MyDTOClass inputData){
 ... do something with input data ...
}

Thx to Julias:

Parsing Json .Net Web Api

Make sure your request is sent with the http header:

Content-Type: application/json

This Handler class should be static or leaks might occur: IncomingHandler

I am not sure but you can try intialising handler to null in onDestroy()

Create a Bitmap/Drawable from file path

Create bitmap from file path:

File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);

If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.

I think you are giving the wrong file path. :) Hope this helps.

How to use an array list in Java?

A List is an ordered Collection of elements. You can add them with the add method, and retrieve them with the get(int index) method. You can also iterate over a List, remove elements, etc. Here are some basic examples of using a List:

List<String> names = new ArrayList<String>(3); // 3 because we expect the list 
    // to have 3 entries.  If we didn't know how many entries we expected, we
    // could leave this empty or use a LinkedList instead
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.get(2)); // prints "Charlie"
System.out.println(names); // prints the whole list
for (String name: names) {
    System.out.println(name);  // prints the names in turn.
}

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

Sample Code: To set Footer text programatically

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      if (e.Row.RowType == DataControlRowType.Footer)
      {
         Label lbl = (Label)e.Row.FindControl("lblTotal");
         lbl.Text = grdTotal.ToString("c");
      }
   }

UPDATED CODE:

  decimal sumFooterValue = 0;
  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
         string sponsorBonus = ((Label)e.Row.FindControl("Label2")).Text;
         string pairingBonus = ((Label)e.Row.FindControl("Label3")).Text;
         string staticBonus = ((Label)e.Row.FindControl("Label4")).Text;
         string leftBonus = ((Label)e.Row.FindControl("Label5")).Text;
         string rightBonus = ((Label)e.Row.FindControl("Label6")).Text;
         decimal totalvalue = Convert.ToDecimal(sponsorBonus) + Convert.ToDecimal(pairingBonus) + Convert.ToDecimal(staticBonus) + Convert.ToDecimal(leftBonus) + Convert.ToDecimal(rightBonus);
         e.Row.Cells[6].Text = totalvalue.ToString();
         sumFooterValue += totalvalue; 
        }

    if (e.Row.RowType == DataControlRowType.Footer)
        {
           Label lbl = (Label)e.Row.FindControl("lblTotal");
           lbl.Text = sumFooterValue.ToString();
        }

   }

In .aspx Page

 <asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" 
        AutoGenerateColumns="False" DataKeyNames="ID" CellPadding="4" 
        ForeColor="#333333" GridLines="None" ShowFooter="True" 
                onrowdatabound="GridView1_RowDataBound">
        <RowStyle BackColor="#EFF3FB" />
        <Columns>
            <asp:TemplateField HeaderText="Report Date" SortExpression="reportDate">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("reportDate") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" 
                        Text='<%# Bind("reportDate", "{0:dd MMMM yyyy}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Sponsor Bonus" SortExpression="sponsorBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("sponsorBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" 
                        Text='<%# Bind("sponsorBonus", "{0:0.00}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Pairing Bonus" SortExpression="pairingBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("pairingBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label3" runat="server" 
                        Text='<%# Bind("pairingBonus", "{0:c}") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Static Bonus" SortExpression="staticBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label4" runat="server" Text='<%# Bind("staticBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Left Bonus" SortExpression="leftBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label5" runat="server" Text='<%# Bind("leftBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Right Bonus" SortExpression="rightBonus">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label6" runat="server" Text='<%# Bind("rightBonus") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Total" SortExpression="total">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox7" runat="server"></asp:TextBox>
                </EditItemTemplate>
                <FooterTemplate>
                    <asp:Label ID="lbltotal" runat="server" Text="Label"></asp:Label>
                </FooterTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label7" runat="server"></asp:Label>
                </ItemTemplate>
                <ItemStyle Width="100px" />

            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#2461BF" />
        <AlternatingRowStyle BackColor="White" />            
    </asp:GridView>

My Blog - Asp.net Gridview Article

failed to push some refs to [email protected]

It would appear that you are not fully up-to-date. You would need to do a git pull and either "--rebase" or let it merge into your set.

After this, you should then be able to push, since it would be a 'fast-forward' change that wouldn't remove history.

Edit: example command list

git pull
git push

LINQ query on a DataTable

In my application I found that using LINQ to Datasets with the AsEnumerable() extension for DataTable as suggested in the answer was extremely slow. If you're interested in optimizing for speed, use James Newtonking's Json.Net library (http://james.newtonking.com/json/help/index.html)

// Serialize the DataTable to a json string
string serializedTable = JsonConvert.SerializeObject(myDataTable);    
Jarray dataRows = Jarray.Parse(serializedTable);

// Run the LINQ query
List<JToken> results = (from row in dataRows
                    where (int) row["ans_key"] == 42
                    select row).ToList();

// If you need the results to be in a DataTable
string jsonResults = JsonConvert.SerializeObject(results);
DataTable resultsTable = JsonConvert.DeserializeObject<DataTable>(jsonResults);

Excel formula to remove space between words in a cell

It is SUBSTITUTE(B1," ",""), not REPLACE(xx;xx;xx).

Hiding the R code in Rmarkdown/knit and just showing the results

Might also be interesting for you to know that you can use:

{r echo=FALSE, results='hide',message=FALSE}
a<-as.numeric(rnorm(100))
hist(a, breaks=24)

to exclude all the commands you give, all the results it spits out and all message info being spit out by R (eg. after library(ggplot) or something)

Using module 'subprocess' with timeout

The solution I use is to prefix the shell command with timelimit. If the comand takes too long, timelimit will stop it and Popen will have a returncode set by timelimit. If it is > 128, it means timelimit killed the process.

See also python subprocess with timeout and large output (>64K)

Determine if JavaScript value is an "integer"?

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

If you want to change a foreign key without dropping it you can do:

ALTER TABLE child_table_name  WITH CHECK ADD FOREIGN KEY(child_column_name)
REFERENCES parent_table_name (parent_column_name) ON DELETE CASCADE

UTF-8, UTF-16, and UTF-32

  • UTF-8 is variable 1 to 4 bytes.

  • UTF-16 is variable 2 or 4 bytes.

  • UTF-32 is fixed 4 bytes.

Note: UTF-8 can take 1 to 6 bytes with latest convention: https://lists.gnu.org/archive/html/help-flex/2005-01/msg00030.html

Uncaught TypeError: Cannot read property 'value' of undefined

Try this, It always works, and you will get NO TypeError:

try{

    var i1 = document.getElementById('i1');
    var i2 = document.getElementById('i2');
    var __i = {'user' : document.getElementsByName("username")[0], 'pass' : document.getElementsByName("password")[0] };
    if(  __i.user.value.length >= 1 ) { i1.value = ''; } else { i1.value = 'Acc'; }
    if(  __i.pass.value.length >= 1 ) { i2.value = ''; } else { i2.value = 'Pwd'; }

}catch(e){
    if(e){
    // If fails, Do something else
    }
}

How to resolve "Waiting for Debugger" message?

My solution is to use the Dalvik Debug Monitor. Sometimes there is a red or green bug beside a process. Click on the device you're trying to load to. Select the Actions tab and reset adb. This usually attaches the debugger for me. I find that doing debugging through this Monitor works better for me than using the Android Eclipse plugin Logcat.

What online brokers offer APIs?

Ameritrade also offers an API, as long as you have an Ameritrade account: http://www.tdameritrade.com/tradingtools/partnertools/api_dev.html

$(this).attr("id") not working

What are you expecting $(this) to refer to?

Do you mean sel.attr("id"); perhaps?

Create Windows service from executable

Same as Sergii Pozharov's answer, but with a PowerShell cmdlet:

New-Service -Name "MyService" -BinaryPathName "C:\Path\to\myservice.exe"

See New-Service for more customization.

This will only work for executables that already implement the Windows Services API.

Allowed characters in filename

Here is the code to clean file name in python.

import unicodedata

def clean_name(name, replace_space_with=None):
    """
    Remove invalid file name chars from the specified name

    :param name: the file name
    :param replace_space_with: if not none replace space with this string
    :return: a valid name for Win/Mac/Linux
    """

    # ref: https://en.wikipedia.org/wiki/Filename
    # ref: https://stackoverflow.com/questions/4814040/allowed-characters-in-filename
    # No control chars, no: /, \, ?, %, *, :, |, ", <, >

    # remove control chars
    name = ''.join(ch for ch in name if unicodedata.category(ch)[0] != 'C')

    cleaned_name = re.sub(r'[/\\?%*:|"<>]', '', name)
    if replace_space_with is not None:
        return cleaned_name.replace(' ', replace_space_with)
    return cleaned_name

How can I add reflection to a C++ application?

Reflection is not supported by C++ out of the box. This is sad because it makes defensive testing a pain.

There are several approaches to doing reflection:

  1. use the debug information (non portable).
  2. Sprinkle your code with macro's/templates or some other source approach (looks ugly)
  3. Modify a compiler such as clang/gcc to produce a database.
  4. Use Qt moc approach
  5. Boost Reflect
  6. Precise and Flat Reflection

The first link looks the most promising (uses mod's to clang), the second discusses a number of techniques, the third is a different approach using gcc:

  1. http://www.donw.org/rfl/

  2. https://bitbucket.org/dwilliamson/clreflect

  3. https://root.cern.ch/how/how-use-reflex

There is now a working group for C++ reflection. See the news for C++14 @ CERN:

Edit 13/08/17:

Since the original post there have been a number of potential advancements on the reflection. The following provides more detail and a discussion on the various techniques and status:

  1. Static Reflection in a Nutshell
  2. Static Reflection
  3. A design for static reflection

However it does not look promising on a standardised reflections approach in C++ in the near future unless there is a lot more interest from the community in support for reflection in C++.

The following details the current status based on feedback from the last C++ standards meeting:

Edit 13/12/2017

Reflection looks to be moving towards C++ 20 or more probably a TSR. Movement is however slow.

Edit 15/09/2018

A draft TS has been sent out to the national bodies for ballot.

The text can be found here: https://github.com/cplusplus/reflection-ts

Edit 11/07/2019

The reflection TS is feature complete and is out for comment and vote over the summer (2019).

The meta-template programing approach is to be replaced with a simplier compile time code approach (not reflected in the TS).

Edit 10/02/2020

There is a request to support the reflection TS in Visual Studio here:

Talk on the TS by the author David Sankel:

Edit 17 March 2020

Progress on reflection is being made. A report from '2020-02 Prague ISO C++ Committee Trip Report' can be found here:

Details on what is being considered for C++23 can be found here (includes short section on Reflection):

Edit 4th June 2020

A new framework has been released by Jeff Preshing called 'Plywood' that contains a mechanism for runtime reflection. More details can be found here:

The tools and approach look to be the most polished and easiest to use so far.

Edit July 12 2020

Clang experimental reflection fork : https://github.com/lock3/meta/wiki

Interesting reflection library that uses clang tooling library to extract information for simple reflection with no need to add macro's: https://github.com/chakaz/reflang

Edit Feb 24 2021

Some additional clang tooling approaches:

How to program a fractal?

I think you might not see fractals as an algorithm or something to program. Fractals is a concept! It is a mathematical concept of detailed pattern repeating itself.

Therefore you can create a fractal in many ways, using different approaches, as shown in the image below.

enter image description here

Choose an approach and then investigate how to implement it. These four examples were implemented using Marvin Framework. The source codes are available here

Subtracting 2 lists in Python

The combination of map and lambda functions in Python is a good solution for this kind of problem:

a = [2,2,2]
b = [1,1,1]
map(lambda x,y: x-y, a,b)

zip function is another good choice, as demonstrated by @UncleZeiv

How to Get a Sublist in C#

Would it be as easy as running a LINQ query on your List?

List<string> mylist = new List<string>{ "hello","world","foo","bar"};
List<string> listContainingLetterO = mylist.Where(x=>x.Contains("o")).ToList();

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

how to convert numeric to nvarchar in sql command

If the culture of the result doesn't matters or we're only talking of integer values, CONVERT or CAST will be fine.

However, if the result must match a specific culture, FORMAT might be the function to go:

DECLARE @value DECIMAL(19,4) = 1505.5698
SELECT CONVERT(NVARCHAR, @value)        -->  1505.5698
SELECT FORMAT(@value, 'N2', 'en-us')    --> 1,505.57
SELECT FORMAT(@value, 'N2', 'de-de')    --> 1.505,57

For more information on FORMAT see here.

Of course, formatting the result should be a matter of the UI layer of the software.

VideoView Full screen in android application

I achieved it by switching to landscape orientation and setting layout params to MATCH_PARENT. Just before switching to fullscreen mode, we need to store current orientation mode and VideoView params indefaultScreenOrientationMode and defaultVideoViewParams variables correspondingly. So that we can use them when we exit from video fullscreen mode. Thus, when you want to open video in fullscreen mode, use makeVideoFullScreen() method, to exit - exitVideoFullScreen().

Please, note I used RelativeLayout for my VideoView, in your case it can be another layout type.

private RelativeLayout.LayoutParams defaultVideoViewParams;
private int defaultScreenOrientationMode;

// play video in fullscreen mode
private void makeVideoFullScreen() {

    defaultScreenOrientationMode = getResources().getConfiguration().orientation;
    defaultVideoViewParams = (LayoutParams) videoView.getLayoutParams();

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

    videoView.postDelayed(new Runnable() {

        @Override
        public void run() {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.MATCH_PARENT);

            videoView.setLayoutParams(params);
            videoView.layout(10, 10, 10, 10);
        }
    }, 700);
}


// close fullscreen mode
private void exitVideoFullScreen() {
    setRequestedOrientation(defaultScreenOrientationMode);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

    videoView.postDelayed(new Runnable() {

        @Override
        public void run() {
            videoView.setLayoutParams(defaultVideoViewParams);
            videoView.layout(10, 10, 10, 10);
        }
    }, 700);
}

How do I correct the character encoding of a file?

I found this question when searching for a solution to a code page issue i had with Chinese characters, but in the end my problem was just an issue with Windows not displaying them correctly in the UI.

In case anyone else has that same issue, you can fix it simply by changing the local in windows to China and then back again.

I found the solution here:

http://answers.microsoft.com/en-us/windows/forum/windows_7-desktop/how-can-i-get-chinesejapanese-characters-to/fdb1f1da-b868-40d1-a4a4-7acadff4aafa?page=2&auth=1

Also upvoted Gabriel's answer as looking at the data in notepad++ was what tipped me off about windows.

Simple Vim commands you wish you'd known earlier

gi switches to insertion mode, placing the cursor at the same location it was previously.

C# equivalent of C++ map<string,double>

Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection

Python integer incrementing with ++

You can do:

number += 1

compare two list and return not matching items using linq

The naive approach:

MsgList.Where(x => !SentList.Any(y => y.MsgID == x.MsgID))

Be aware this will take up to m*n operations as it compares every MsgID in SentList to each in MsgList ("up to" because it will short-circuit when it does happen to match).

Undefined index error PHP

Hey this is happening because u r trying to display value before assignnig it U just fill in the values and submit form it will display correct output Or u can write ur php code below form tags It ll run without any errors

Why is my method undefined for the type object?

Change your main to:

public static void main(String[] args) {
    EchoServer echoServer = new EchoServer();
    echoServer.listen();
}

When you declare Object EchoServer0; you have a few mistakes.

  1. EchoServer0 is of type Object, therefore it doesn't have the method listen().
  2. You will also need to create an instance of it with new.
  3. Another problem, this is only regarding naming conventions, you should call your variables starting by lower case letters, echoServer0 instead of EchoServer0. Uppercase names are usually for class names.
  4. You should not create a variable with the same name as its class. It is confusing.

Can anyone explain what JSONP is, in layman terms?

Say you had some URL that gave you JSON data like:

{'field': 'value'}

...and you had a similar URL except it used JSONP, to which you passed the callback function name 'myCallback' (usually done by giving it a query parameter called 'callback', e.g. http://example.com/dataSource?callback=myCallback). Then it would return:

myCallback({'field':'value'})

...which is not just an object, but is actually code that can be executed. So if you define a function elsewhere in your page called myFunction and execute this script, it will be called with the data from the URL.

The cool thing about this is: you can create a script tag and use your URL (complete with callback parameter) as the src attribute, and the browser will run it. That means you can get around the 'same-origin' security policy (because browsers allow you to run script tags from sources other than the domain of the page).

This is what jQuery does when you make an ajax request (using .ajax with 'jsonp' as the value for the dataType property). E.g.

$.ajax({
  url: 'http://example.com/datasource',
  dataType: 'jsonp',
  success: function(data) {
    // your code to handle data here
  }
});

Here, jQuery takes care of the callback function name and query parameter - making the API identical to other ajax calls. But unlike other types of ajax requests, as mentioned, you're not restricted to getting data from the same origin as your page.

Android splash screen image sizes to fit all devices

Density buckets

LDPI    120dpi    .75x
MDPI    160dpi    1x
HDPI    240dpi    1.5x
XHDPI   320dpi    2x
XXHDPI  480dpi    3x
XXXHDPI 640dpi    4x

px / dp = dpi / 160 dpi

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

After trying all these solutions (and a lot more), I found that the problem lies somewhere else. For people that go through the same misery as me after buying a certificate, I'll share the solution for my problem.

Behavior

I understand that 'sign' applies a strong name and not an authenticode to a DLL or EXE. This is why signtool will work in this case, but 'sign' in Visual studio will not work.

Reason

In the past I've had experience with certificates from Verisign. They have a KeySpec=2 in the certificate - which is used with the 'sign' functionality in Visual Studio. These certificates work fine for both Visual Studio and signtool.

I now bought certificates from Comodo, which have an incorrect KeySpec=1 in the code signing certificates. That means these certificates work fine with signtool (authenticode) but not with strong naming (the sign drop-down).

Solution

There are two ways to solve this issue:

  1. Create a separate certificate for your strong name using sn -k [name].snk. Sign the assembly using the snk and afterwards use signtool with your code signing certificate to do sign the DLL/EXE with the authenticode signature. While this seems strange, from what I understand this is a correct way to deal with certificates, because strong names have a different purpose than authenticode (see also this link for details on how this works).
  2. Import your certificate as KeySpec=2. The procedure for this is detailed here.

Because I want to use multiple strong names, I currently use option (1), although option (2) also works.


To ensure this solution will never get lost in the future, here's the procedure of solution 2:

  1. Using the "Certifiates" MMC export the existing keyset (KeySpec=1) to a PFX file. Note: Please backup this file to a safe location and test if the file can be imported ok on another machine if you really want to play it safe!
  2. Delete the existing certificate from the crypto store (stlll using the MMC).
  3. Open a CMD prompt.
  4. Import the PFX file using this command:
    1. certutil -importPFX -user <pfxfilename> AT_SIGNATURE
    2. Enter the passphrase for the pfx when prompted.

You now should have a keyset/certificate with KeySpec=2. If needed you can now export this into another PFX file using the MMC again.

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

What does "<>" mean in Oracle

It means not equal to, this is a good method to exclude certain elements from your query. For example lets say you have an orders tables and then you have OrderStatusID column within that table.

You also have a status table where

0 = OnHold, 
1 = Processing, 
2 = WaitingPayment, 
3 = Shipped, 
4 = Canceled.

You can run a query where

Select * From [Orders] where OrderStatusID <> 4

this should give you all the orders except those that have been canceled! :D

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

Is there a default password to connect to vagrant when using `homestead ssh` for the first time?

By default Vagrant uses a generated private key to login, you can try this:

ssh -l ubuntu -p 2222 -i .vagrant/machines/default/virtualbox/private_key 127.0.0.1

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

Example of multipart/form-data

EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245

To see exactly what is happening, use nc -l or an ECHO server and an user agent like a browser or cURL.

Save the form to an .html file:

<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
  <p><input type="text" name="text" value="text default">
  <p><input type="file" name="file1">
  <p><input type="file" name="file2">
  <p><button type="submit">Submit</button>
</form>

Create files to upload:

echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html

Run:

nc -l localhost 8000

Open the HTML on your browser, select the files and click on submit and check the terminal.

nc prints the request received. Firefox sent:

POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"

text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain

Content of a.txt.

-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html

<!DOCTYPE html><title>Content of a.html.</title>

-----------------------------9051914041544843365972754266--

Aternativelly, cURL should send the same POST request as your a browser form:

nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000

You can do multiple tests with:

while true; do printf '' | nc -l localhost 8000; done

member names cannot be the same as their enclosing type C#

The problem is with the method:

private void Flow()
{
    X = x;
    Y = y;
}

Your class is named Flow so this method can't also be named Flow. You will have to change the name of the Flow method to something else to make this code compile.

Or did you mean to create a private constructor to initialize your class? If that's the case, you will have to remove the void keyword to let the compiler know that your declaring a constructor.

Finding all possible combinations of numbers to reach a given sum

function solve(n){
    let DP = [];

     DP[0] = DP[1] = DP[2] = 1;
     DP[3] = 2;

    for (let i = 4; i <= n; i++) {
      DP[i] = DP[i-1] + DP[i-3] + DP[i-4];
    }
    return DP[n]
}

console.log(solve(5))

This is a Dynamic Solution for JS to tell how many ways anyone can get the certain sum. This can be the right solution if you think about time and space complexity.

How to load property file from classpath?

final Properties properties = new Properties();
try (final InputStream stream =
           this.getClass().getResourceAsStream("foo.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

(How) can I count the items in an enum?

There's not really a good way to do this, usually you see an extra item in the enum, i.e.

enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};

So then you can do:

int fuz[FOOBAR_NR_ITEMS];

Still not very nice though.

But of course you do realize that just the number of items in an enum is not safe, given e.g.

enum foobar {foo, bar = 5, baz, quz = 20};

the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.

edit: as requested, made the special entry stick out more.

Unsigned keyword in C++

Integer Types:

short            -> signed short
signed short
unsigned short
int              -> signed int
signed int
unsigned int
signed           -> signed int
unsigned         -> unsigned int
long             -> signed long
signed long
unsigned long

Be careful of char:

char  (is signed or unsigned depending on the implmentation)
signed char
unsigned char

If Else in LINQ

my example:

 companyNamesFirst = this.model.CustomerDisplayList.Where(a => a.CompanyFirst != null ? a.CompanyFirst.StartsWith(typedChars.ToLower())) : false).Select(b => b.CompanyFirst).Distinct().ToList();

vim - How to delete a large block of text without counting the lines?

You can also enter a very large number, and then press dd if you wish to delete all the lines below the cursor.

Fully change package name including company domain

I have not changed any package name. The following two steps worked for me. After doing the following, the application was installed as a NEW one , eventhough there was two applications with the same package name.

1) In the build.gradle

applicationId "mynew.mynewpackage.com"

2) In the AndroidManifest.xml android:authorities="mynew.mynewpackage.com.fileprovider"

.Net: How do I find the .NET version?

Per Microsoft in powershell:

Get-ChildItem "hklm:SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\" | Get-ItemPropertyValue -Name Release | % { $_ -ge 394802 }

See the table at this link to get the DWORD value to search for specific versions:

https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed#ps_a

ImportError: No module named win32com.client

Had the exact same problem and none of the answers here helped me. Till I find this thread and post

Short: win32 modules are not guaranted to install correctly with pip. Install them directly from packages provided by developpers on github. It works like a charm.

What is the use of BindingResult interface in spring MVC?

Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.

Then, you can check this object looking for validation errors:

validator.validate(modelObject, bindingResult);  
if (bindingResult.hasErrors()) {  
    // do something  
}

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

You're not adding columns to your DataGridView

DataGridView dataGridView1 = new DataGridView();//Create new grid

dataGridView1.Columns[0].Name = "ItemID";// refer to column which is not there 

Is it clear now why you get an exception?

Add this line before you use columns to fix the error

dataGridView1.ColumnCount = 5;

Grep regex NOT containing string

grep matches, grep -v does the inverse. If you need to "match A but not B" you usually use pipes:

grep "${PATT}" file | grep -v "${NOTPATT}"

xcopy file, rename, suppress "Does xxx specify a file name..." message

I met same issue when try to copy file with new name only if file does not exist in destination or exist (with new name), but is older. The solution is to add * char at end of destination file name. Example:

xcopy "C:\src\whee.config.txt" "C:\dest\bee.config.txt*" /D /Y

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

Google Apps Script to open a URL

Building of off an earlier example, I think there is a cleaner way of doing this. Create an index.html file in your project and using Stephen's code from above, just convert it into an HTML doc.

<!DOCTYPE html>
<html>
  <base target="_top">
  <script>
    function onSuccess(url) {
      var a = document.createElement("a"); 
      a.href = url;
      a.target = "_blank";
      window.close = function () {
        window.setTimeout(function() {
          google.script.host.close();
        }, 9);
      };
      if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        if (navigator.userAgent.toLowerCase().indexOf("firefox") > -1) {
          window.document.body.append(a);
        }                        
        event.initEvent("click", true, true); 
        a.dispatchEvent(event);
      } else {
        a.click();
      }
      close();
    }

    function onFailure(url) {
      var div = document.getElementById('failureContent');
      var link = '<a href="' + url + '" target="_blank">Process</a>';
      div.innerHtml = "Failure to open automatically: " + link;
    }

    google.script.run.withSuccessHandler(onSuccess).withFailureHandler(onFailure).getUrl();
  </script>
  <body>
    <div id="failureContent"></div>
  </body>
  <script>
    google.script.host.setHeight(40);
    google.script.host.setWidth(410);
  </script>
</html>

Then, in your Code.gs script, you can have something like the following,

function getUrl() {
  return 'http://whatever.com';
}

function openUrl() {
  var html = HtmlService.createHtmlOutputFromFile("index");
  html.setWidth(90).setHeight(1);
  var ui = SpreadsheetApp.getUi().showModalDialog(html, "Opening ..." );
}

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

Try this

SELECT CONVERT(varchar(11),getdate(),101) -- Converts to 'mm/dd/yyyy'

SELECT CONVERT(varchar(11),getdate(),103) -- Converts to 'dd/mm/yyyy'

More info here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

How to run a SQL query on an Excel table?

I might be misunderstanding me, but isn't this exactly what a pivot table does? Do you have the data in a table or just a filtered list? If its not a table make it one (ctrl+l) if it is, then simply activate any cell in the table and insert a pivot table on another sheet. Then Add the columns lastname, firstname, phonenumber to the rows section. Then Add Phone number to the filter section and filter out the null values. Now Sort like normal.

Remove HTML tags from a String

Here is one more variant of how to replace all(HTML Tags | HTML Entities | Empty Space in HTML content)

content.replaceAll("(<.*?>)|(&.*?;)|([ ]{2,})", ""); where content is a String.

Bootstrap how to get text to vertical align in a div container

h2.text-left{
  position:relative;
  top:50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Explanation:

The top:50% style essentially pushes the header element down 50% from the top of the parent element. The translateY stylings also act in a similar manner by moving then element down 50% from the top.

Please note that this works well for headers with 1 (maybe 2) lines of text as this simply moves the top of the header element down 50% and then the rest of the content fills in below that, which means that with multiple lines of text it would appear to be slightly below vertically aligned.

A possible fix for multiple lines would be to use a percentage slightly less than 50%.

Where is database .bak file saved from SQL Server Management Studio?

Use the script below, and switch the DatabaseName with then name of the database that you've backed up. On the column physical_device_name, you'll have the full path of your backed-up database:

select a.backup_set_id, a.server_name, a.database_name, a.name, a.user_name, a.position, a.software_major_version, a.backup_start_date, backup_finish_date, a.backup_size, a.recovery_model, b.physical_device_name
from msdb.dbo.backupset a join msdb.dbo.backupmediafamily b
  on a.media_set_id = b.media_set_id
where a.database_name = 'DatabaseName'
order by a.backup_finish_date desc

How to use BigInteger?

BigInteger is an immutable class. So whenever you do any arithmetic, you have to reassign the output to a variable.

Bootstrap: How do I identify the Bootstrap version?

An easy way to do this, without searching files or folders would be:

  • Open your web page on browser
  • press ctrl+U
  • search boostrap.min.js or boostrap.min.css, then click it (it would open source file)
  • at first line(commented) you should see boostrap version

XOR operation with two strings in java

Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.

I would do an XOR each charAt() to create a new String. Like

String s, key;

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
    sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();

In response to @user467257's comment

If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).

It is the char values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.

public static void main(String... args) throws UnsupportedEncodingException {
    char ch1 = 'a';
    char ch2 = 'æ';
    char ch3 = (char) (ch1 ^ ch2);
    System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}

prints

135 UTF-8 encoded is [-62, -121]

Java optional parameters

Short version :

Using three dots:

public void foo(Object... x) {
    String first    =  x.length > 0 ? (String)x[0]  : "Hello";
    int duration    =  x.length > 1 ? Integer.parseInt((String) x[1])     : 888;
}   
foo("Hii", ); 
foo("Hii", 146); 

(based on @VitaliiFedorenko's answer)

YouTube API to fetch all videos on a channel

Here is a video from Google Developers showing how to list all videos in a channel in v3 of the YouTube API.

There are two steps:

  1. Query Channels to get the "uploads" Id. eg https://www.googleapis.com/youtube/v3/channels?id={channel Id}&key={API key}&part=contentDetails

  2. Use this "uploads" Id to query PlaylistItems to get the list of videos. eg https://www.googleapis.com/youtube/v3/playlistItems?playlistId={"uploads" Id}&key={API key}&part=snippet&maxResults=50

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

peerDependencies didn't quite make sense for me until I read this snippet from a blog post on the topic Ciro mentioned above:

What [plugins] need is a way of expressing these “dependencies” between plugins and their host package. Some way of saying, “I only work when plugged in to version 1.2.x of my host package, so if you install me, be sure that it’s alongside a compatible host.” We call this relationship a peer dependency.

The plugin does expect a specific version of the host...

peerDependencies are for plugins, libraries that require a "host" library to perform their function, but may have been written at a time before the latest version of the host was released.

That is, if I write PluginX v1 for HostLibraryX v3 and walk away, there's no guarantee PluginX v1 will work when HostLibraryX v4 (or even HostLibraryX v3.0.1) is released.

... but the plugin doesn't depend on the host...

From the point of view of the plugin, it only adds functions to the host library. I don't really "need" the host to add a dependency to a plugin, and plugins often don't literally depend on their host. If you don't have the host, the plugin harmlessly does nothing.

This means dependencies isn't really the right concept for plugins.

Even worse, if my host was treated like a dependency, we'd end up in this situation that the same blog post mentions (edited a little to use this answer's made up host & plugin):

But now, [if we treat the contemporary version of HostLibraryX as a dependency for PluginX,] running npm install results in the unexpected dependency graph of

+-- [email protected]
+-- [email protected]
  +-- [email protected]

I’ll leave the subtle failures that come from the plugin using a different [HostLibraryX] API than the main application to your imagination.

... and the host obviously doesn't depend on the plugin...

... that's the whole point of plugins. Now if the host was nice enough to include dependency information for all of its plugins, that'd solve the problem, but that'd also introduce a huge new cultural problem: plugin management!

The whole point of plugins is that they can pair up anonymously. In a perfect world, having the host manage 'em all would be neat & tidy, but we're not going to require libraries herd cats.

If we're not hierarchically dependent, maybe we're intradependent peers...

Instead, we have the concept of being peers. Neither host nor plugin sits in the other's dependency bucket. Both live at the same level of the dependency graph.


... but this is not an automatable relationship. <<< Moneyball!!!

If I'm PluginX v1 and expect a peer of (that is, have a peerDependency of) HostLibraryX v3, I'll say so. If you've auto-upgraded to the latest HostLibraryX v4 (note that's version 4) AND have Plugin v1 installed, you need to know, right?

npm can't manage this situation for me --

"Hey, I see you're using PluginX v1! I'm automatically downgrading HostLibraryX from v4 to v3, kk?"

... or...

"Hey I see you're using PluginX v1. That expects HostLibraryX v3, which you've left in the dust during your last update. To be safe, I'm automatically uninstalling Plugin v1!!1!

How about no, npm?!

So npm doesn't. It alerts you to the situation, and lets you figure out if HostLibraryX v4 is a suitable peer for Plugin v1.


Coda

Good peerDependency management in plugins will make this concept work more intuitively in practice. From the blog post, yet again...

One piece of advice: peer dependency requirements, unlike those for regular dependencies, should be lenient. You should not lock your peer dependencies down to specific patch versions. It would be really annoying if one Chai plugin peer-depended on Chai 1.4.1, while another depended on Chai 1.5.0, simply because the authors were lazy and didn’t spend the time figuring out the actual minimum version of Chai they are compatible with.

How to set the title text color of UIButton?

Swift UI solution

Button(action: {}) {
            Text("Button")
        }.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))

Swift 3, Swift 4, Swift 5

to improve comments. This should work:

button.setTitleColor(.red, for: .normal)

default select option as blank

<select required>
  <option value="" disabled selected>None</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You can avoid custom validation in this case.

Difference between UTF-8 and UTF-16?

This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.

static byte[] toBytes(String s){
        byte[] b=new byte[s.length()*2];
        ByteBuffer.wrap(b).asCharBuffer().put(s);
        return b;
    }

How to sum the values of one column of a dataframe in spark/scala

Not sure this was around when this question was asked but:

df.describe().show("columnName")

gives mean, count, stdtev stats on a column. I think it returns on all columns if you just do .show()

How to handle iframe in Selenium WebDriver using java

WebDriver driver=new FirefoxDriver();
driver.get("http://www.java-examples.com/java-string-examples");
Thread.sleep(3000);
//Switch to nested frame
driver.switchTo().frame("aswift_2").switchTo().frame("google_ads_frame3");

Laravel Fluent Query Builder Join with subquery

I am on Laravel 7.25 and I don't know if it supports on previous versions or not but Its pretty good.

Syntax for the function:

public function joinSub($query, $as, $first, $operator = null, $second = null, $type = 'inner', $where = false)

Example:

Showing/Getting the user ID and the total number of posts by them left joining two tables users and posts.

        return DB::table('users')
            ->joinSub('select user_id,count(id) noOfPosts from posts group by user_id', 'totalPosts', 'users.id', '=', 'totalPosts.user_id', 'left')
            ->select('users.name', 'totalPosts.noOfPosts')
            ->get();

Alternative:

If you don't wanna mention 'left' for leftjoin then you can use another prebuilt function

    public function leftJoinSub($query, $as, $first, $operator = null, $second = null)
    {
        return $this->joinSub($query, $as, $first, $operator, $second, 'left');
    }

And yeah, it actually calls the same function but it passes the join type itself. You can apply the same logic for other joins i.e. righJoinSub(...) etc.

Generate random numbers uniformly over an entire range

Why rand is a bad idea

Most of the answers you got here make use of the rand function and the modulus operator. That method may not generate numbers uniformly (it depends on the range and the value of RAND_MAX), and is therefore discouraged.

C++11 and generation over a range

With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: std::uniform_int_distribution. Here's an example:

const int range_from  = 0;
const int range_to    = 10;
std::random_device                  rand_dev;
std::mt19937                        generator(rand_dev());
std::uniform_int_distribution<int>  distr(range_from, range_to);

std::cout << distr(generator) << '\n';

And here's the running example.

Template function may help some:

template<typename T>
T random(T range_from, T range_to) {
    std::random_device                  rand_dev;
    std::mt19937                        generator(rand_dev());
    std::uniform_int_distribution<T>    distr(range_from, range_to);
    return distr(generator);
}

Other random generators

The <random> header offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.

How can I shuffle a container?

The standard provides std::shuffle, which can be used as follows:

std::vector<int> vec = {4, 8, 15, 16, 23, 42};

std::random_device random_dev;
std::mt19937       generator(random_dev());

std::shuffle(vec.begin(), vec.end(), generator);

The algorithm will reorder the elements randomly, with a linear complexity.

Boost.Random

Another alternative, in case you don't have access to a C++11+ compiler, is to use Boost.Random. Its interface is very similar to the C++11 one.

How to upload folders on GitHub

You can also use the command line, Change directory where your folder is located then type the following :

     git init
     git add <folder1> <folder2> <etc.>
     git commit -m "Your message about the commit"
     git remote add origin https://github.com/yourUsername/yourRepository.git
     git push -u origin master
     git push origin master  

How to use PDO to fetch results array in PHP?

There are three ways to fetch multiple rows returned by PDO statement.

The simplest one is just to iterate over PDOStatement itself:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// iterating over a statement
foreach($stmt as $row) {
    echo $row['name'];
}

another one is to fetch rows using fetch() method inside a familiar while statement:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    echo $row['name'];
}

but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// fetching rows into array
$data = $stmt->fetchAll();

or, if you need to preprocess some data first, use the while loop and collect the data into array manually

$result = [];
$stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
$stmt->execute(array("%$query%"));
// using while
while($row = $stmt->fetch()) {
    $result[] = [
        'newname' => $row['oldname'],
        // etc
    ];
}

and then output them in a template:

<ul>
<?php foreach($data as $row): ?>
    <li><?=$row['name']?></li>
<?php endforeach ?>
</ul>

Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:

^\d{1,45}$

where \d is the same like [0-9].

Show ImageView programmatically

After submitting a POST form open a new window showing the result

Add

<form target="_blank" ...></form>

or

form.setAttribute("target", "_blank");

to your form's definition.

How to add favicon.ico in ASP.NET site

resolve the url like this href="<%=ResolveUrl("~/favicon.ico")%>"

Java, How do I get current index/key in "for each" loop

Not possible in Java.


Here's the Scala way:

val m = List(5, 4, 2, 89)

for((el, i) <- m.zipWithIndex)
  println(el +" "+ i)

How do I add comments to package.json for npm install?

I ended up with a scripts like that:

  "scripts": {
    "//-1a": "---------------------------------------------------------------",
    "//-1b": "---------------------- from node_modules ----------------------",
    "//-1c": "---------------------------------------------------------------",
    "ng": "ng",
    "prettier": "prettier",
    "tslint": "tslint",
    "//-2a": "---------------------------------------------------------------",
    "//-2b": "--------------------------- backend ---------------------------",
    "//-2c": "---------------------------------------------------------------",
    "back:start": "node backend/index.js",
    "back:start:watch": "nodemon",
    "back:build:prod": "tsc -p backend/tsconfig.json",
    "back:serve:prod": "NODE_ENV=production node backend/dist/main.js",
    "back:lint:check": "tslint -c ./backend/tslint.json './backend/src/**/*.ts'",
    "back:lint:fix": "yarn run back:lint:check --fix",
    "back:check": "yarn run back:lint:check && yarn run back:prettier:check",
    "back:check:fix": "yarn run back:lint:fix; yarn run back:prettier:fix",
    "back:prettier:base-files": "yarn run prettier './backend/**/*.ts'",
    "back:prettier:fix": "yarn run back:prettier:base-files --write",
    "back:prettier:check": "yarn run back:prettier:base-files -l",
    "back:test": "ts-node --project backend/tsconfig.json node_modules/jasmine/bin/jasmine ./backend/**/*spec.ts",
    "back:test:watch": "watch 'yarn run back:test' backend",
    "back:test:coverage": "echo TODO",
    "//-3a": "---------------------------------------------------------------",
    "//-3b": "-------------------------- frontend ---------------------------",
    "//-3c": "---------------------------------------------------------------",
    "front:start": "yarn run ng serve",
    "front:test": "yarn run ng test",
    "front:test:ci": "yarn run front:test --single-run --progress=false",
    "front:e2e": "yarn run ng e2e",
    "front:e2e:ci": "yarn run ng e2e --prod --progress=false",
    "front:build:prod": "yarn run ng build --prod --e=prod --no-sourcemap --build-optimizer",
    "front:lint:check": "yarn run ng lint --type-check",
    "front:lint:fix": "yarn run front:lint:check --fix",
    "front:check": "yarn run front:lint:check && yarn run front:prettier:check",
    "front:check:fix": "yarn run front:lint:fix; yarn run front:prettier:fix",
    "front:prettier:base-files": "yarn run prettier \"./frontend/{e2e,src}/**/*.{scss,ts}\"",
    "front:prettier:fix": "yarn run front:prettier:base-files --write",
    "front:prettier:check": "yarn run front:prettier:base-files -l",
    "front:postbuild": "gulp compress",
    "//-4a": "---------------------------------------------------------------",
    "//-4b": "--------------------------- cypress ---------------------------",
    "//-4c": "---------------------------------------------------------------",
    "cy:open": "cypress open",
    "cy:headless": "cypress run",
    "cy:prettier:base-files": "yarn run prettier \"./cypress/**/*.{js,ts}\"",
    "cy:prettier:fix": "yarn run front:prettier:base-files --write",
    "cy:prettier:check": "yarn run front:prettier:base-files -l",
    "//-5a": "---------------------------------------------------------------",
    "//-5b": "--------------------------- common ----------------------------",
    "//-5c": "---------------------------------------------------------------",
    "all:check": "yarn run back:check && yarn run front:check && yarn run cy:prettier:check",
    "all:check:fix": "yarn run back:check:fix && yarn run front:check:fix && yarn run cy:prettier:fix",
    "//-6a": "---------------------------------------------------------------",
    "//-6b": "--------------------------- hooks -----------------------------",
    "//-6c": "---------------------------------------------------------------",
    "precommit": "lint-staged",
    "prepush": "yarn run back:lint:check && yarn run front:lint:check"
  },

My intent here is not to clarify one line, just to have some sort of delimiters between my scripts for backend, frontend, all, etc.

I'm not a huge fan of 1a, 1b, 1c, 2a, ... but the keys are different and I do not have any problem at all like that.

What is unit testing and how do you do it?

What exactly IS unit testing? Is it built into code or run as separate programs? Or something else?

From MSDN: The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.

Essentially, you are writing small bits of code to test the individual bits of your code. In the .net world, you would run these small bits of code using something like NUnit or MBunit or even the built in testing tools in visual studio. In Java you might use JUnit. Essentially the test runners will build your project, load and execute the unit tests and then let you know if they pass or fail.

How do you do it?

Well it's easier said than done to unit test. It takes quite a bit of practice to get good at it. You need to structure your code in a way that makes it easy to unit test to make your tests effective.

When should it be done? Are there times or projects not to do it? Is everything unit-testable?

You should do it where it makes sense. Not everything is suited to unit testing. For example UI code is very hard to unit test and you often get little benefit from doing so. Business Layer code however is often very suitable for tests and that is where most unit testing is focused.

Unit testing is a massive topic and to fully get an understanding of how it can best benefit you I'd recommend getting hold of a book on unit testing such as "Test Driven Development by Example" which will give you a good grasp on the concepts and how you can apply them to your code.

How to use fetch in typescript

If you take a look at @types/node-fetch you will see the body definition

export class Body {
    bodyUsed: boolean;
    body: NodeJS.ReadableStream;
    json(): Promise<any>;
    json<T>(): Promise<T>;
    text(): Promise<string>;
    buffer(): Promise<Buffer>;
}

That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:

import { Actor } from './models/actor';

fetch(`http://swapi.co/api/people/1/`)
      .then(res => res.json<Actor>())
      .then(res => {
          let b:Actor = res;
      });

Center a H1 tag inside a DIV

You could add padding to the h1:

#AlertDiv h1 {
  padding:15px 18px;
}

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

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

Option 1:

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

bars = [ new bar(1) ];

Option 2:

interface bar {
    length: number;
}

bars = [ {length: 1} ];

How to find out if a Python object is a string?

You can test it by concatenating with an empty string:

def is_string(s):
  try:
    s += ''
  except:
    return False
  return True

Edit:

Correcting my answer after comments pointing out that this fails with lists

def is_string(s):
  return isinstance(s, basestring)

Angular - How to apply [ngStyle] conditions

<ion-col size="12">
  <ion-card class="box-shadow ion-text-center background-size"
  *ngIf="data != null"
  [ngStyle]="{'background-image': 'url(' + data.headerImage + ')'}">

  </ion-card>

php refresh current page?

Another elegant one is

header("Location: http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
exit;

Set up a scheduled job?

Yes, the method above is so great. And I tried some of them. At last, I found a method like this:

    from threading import Timer

    def sync():

        do something...

        sync_timer = Timer(self.interval, sync, ())
        sync_timer.start()

Just like Recursive.

Ok, I hope this method can meet your requirement. :)

How to Change color of Button in Android when Clicked?

Refer this,

boolean check = false;
Button backward_img;
Button backward_img1;
backward_img = (Button) findViewById(R.id.bars_footer_backward);
backward_img1 = (Button) findViewById(R.id.bars_footer_backward1);
backward_img.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        check = true;
        backward_img.setBackgroundColor(Color.BLUE);
    }
});

if (check == true) {
    backward_img1.setBackgroundColor(Color.RED);
    backward_img.setBackgroundColor(Color.BLUE);
}

Differences between arm64 and aarch64

It seems that ARM64 was created by Apple and AARCH64 by the others, most notably GNU/GCC guys.

After some googling I found this link:

The LLVM 64-bit ARM64/AArch64 Back-Ends Have Merged

So it makes sense, iPad calls itself ARM64, as Apple is using LLVM, and Edge uses AARCH64, as Android is using GNU GCC toolchain.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

How can I set a cookie in react?

Use vanilla js, example

document.cookie = `referral_key=hello;max-age=604800;domain=example.com`

Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

Create a directory if it doesn't exist

You can use cstdlib

Although- http://www.cplusplus.com/articles/j3wTURfi/

#include <cstdlib>

const int dir= system("mkdir -p foo");
if (dir< 0)
{
     return;
}

you can also check if the directory exists already by using

#include <dirent.h>

JSON Invalid UTF-8 middle byte

This awnser solved my problem. Below is a copy of it:

Make sure to start you JVM with -Dfile.encoding=UTF-8. You JVM defaults to the operating system charset

This is a JVM argument which could be added, for example, either to JBoss standalone or JBoss running from Eclipse.

In my case, this problem happened isolatelly on only one of my team people's computer. All the others was working without this problem.

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

If you are using rbenv then make sure that you run the "rbenv rehash" command after you set local or global ruby version. It solved the issue for me.

rbenv rehash

How do I force a DIV block to extend to the bottom of a page even if it has no content?

Try http://mystrd.at/modern-clean-css-sticky-footer/

The link above is down, but this link https://stackoverflow.com/a/18066619/1944643 is ok. :D

Demo:

<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <meta name="author" content="http://mystrd.at">
    <meta name="robots" content="noindex, nofollow">
    <title>James Dean CSS Sticky Footer</title>
    <style type="text/css">
        html {
            position: relative;
            min-height: 100%;
        }
        body {
            margin: 0 0 100px;
            /* bottom = footer height */
            padding: 25px;
        }
        footer {
            background-color: orange;
            position: absolute;
            left: 0;
            bottom: 0;
            height: 100px;
            width: 100%;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <article>
        <!-- or <div class="container">, etc. -->
        <h1>James Dean CSS Sticky Footer</h1>

        <p>Blah blah blah blah</p>
        <p>More blah blah blah</p>
    </article>
    <footer>
        <h1>Footer Content</h1>
    </footer>
</body>

</html>

Mongoose and multiple database in single node.js project

As an alternative approach, Mongoose does export a constructor for a new instance on the default instance. So something like this is possible.

var Mongoose = require('mongoose').Mongoose;

var instance1 = new Mongoose();
instance1.connect('foo');

var instance2 = new Mongoose();
instance2.connect('bar');

This is very useful when working with separate data sources, and also when you want to have a separate database context for each user or request. You will need to be careful, as it is possible to create a LOT of connections when doing this. Make sure to call disconnect() when instances are not needed, and also to limit the pool size created by each instance.

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

In case if we have multiple docker files in our environment just Dockerfile wont suffice our requirement.

docker build -t ihub -f Dockerfile.ihub .

So use the file (-f argument) command to specify your docker file(Dockerfile.ihub)

Replace string in text file using PHP

Thanks to your comments. I've made a function that give an error message when it happens:

/**
 * Replaces a string in a file
 *
 * @param string $FilePath
 * @param string $OldText text to be replaced
 * @param string $NewText new text
 * @return array $Result status (success | error) & message (file exist, file permissions)
 */
function replace_in_file($FilePath, $OldText, $NewText)
{
    $Result = array('status' => 'error', 'message' => '');
    if(file_exists($FilePath)===TRUE)
    {
        if(is_writeable($FilePath))
        {
            try
            {
                $FileContent = file_get_contents($FilePath);
                $FileContent = str_replace($OldText, $NewText, $FileContent);
                if(file_put_contents($FilePath, $FileContent) > 0)
                {
                    $Result["status"] = 'success';
                }
                else
                {
                   $Result["message"] = 'Error while writing file';
                }
            }
            catch(Exception $e)
            {
                $Result["message"] = 'Error : '.$e;
            }
        }
        else
        {
            $Result["message"] = 'File '.$FilePath.' is not writable !';
        }
    }
    else
    {
        $Result["message"] = 'File '.$FilePath.' does not exist !';
    }
    return $Result;
}

Adding a user on .htpasswd

Exact same thing, just omit the -c option. Apache's docs on it here.

htpasswd /etc/apache2/.htpasswd newuser

Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).

Change header text of columns in a GridView

protected void grdDis_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            #region Dynamically Show gridView header From data base
            getAllheaderName();/*To get all Allowences master headerName*/

            TextBox txt_Days = (TextBox)grdDis.HeaderRow.FindControl("txtDays");
            txt_Days.Text = hidMonthsDays.Value;
            #endregion
        }
    }

How to generate an MD5 file hash in JavaScript?

You can use a lightweight library pure-md5. Just a 4.7kb.

_x000D_
_x000D_
$("#file-dialog").change(function() {_x000D_
  handleFiles(this.files);_x000D_
});_x000D_
_x000D_
function handleFiles(files) {_x000D_
  for (var index = 0; index < files.length; index++) {_x000D_
    var file = files[index];_x000D_
    var fileReader = new FileReader();_x000D_
    fileReader.onload = function(e) {_x000D_
      $('body').append(`_x000D_
        <div style="margin-top: 2rem;">_x000D_
          <span>${file.name}: </span>_x000D_
          <span>${(md5(e.target.result))}</span>_x000D_
        </div>_x000D_
      `);_x000D_
    }_x000D_
_x000D_
    fileReader.readAsText(file, 'utf-8');_x000D_
  }_x000D_
_x000D_
}
_x000D_
body {_x000D_
  font-family: sans-serif;_x000D_
}
_x000D_
<script src="https://unpkg.com/[email protected]/lib/index.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="file" id="file-dialog" multiple="true" accept="image/*">
_x000D_
_x000D_
_x000D_

How to use npm with ASP.NET Core

Shawn Wildermuth has a nice guide here: https://wildermuth.com/2017/11/19/ASP-NET-Core-2-0-and-the-End-of-Bower

The article links to the gulpfile on GitHub where he's implemented the strategy in the article. You could just copy and paste most of the gulpfile contents into yours, but be sure to add the appropriate packages in package.json under devDependencies: gulp gulp-uglify gulp-concat rimraf merge-stream

Convert float to double without losing precision

Floats, by nature, are imprecise and always have neat rounding "issues". If precision is important then you might consider refactoring your application to use Decimal or BigDecimal.

Yes, floats are computationally faster than decimals because of the on processor support. However, do you want fast or accurate?

Best way to store passwords in MYSQL database

You should use one way encryption (which is a way to encrypt a value so that is very hard to revers it). I'm not familiar with MySQL, but a quick search shows that it has a password() function that does exactly this kind of encryption. In the DB you will store the encrypted value and when the user wants to authenticate you take the password he provided, you encrypt it using the same algorithm/function and then you check that the value is the same with the password stored in the database for that user. This assumes that the communication between the browser and your server is secure, namely that you use https.

getDate with Jquery Datepicker

I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle

$(document).ready(function(){
    // Datepicker
    $('#datepicker').datepicker({
        dateFormat: 'yy-mm-dd',
        inline: true,
        minDate: new Date(2010, 1 - 1, 1),
        maxDate:new Date(2010, 12 - 1, 31),
        altField: '#datepicker_value',
        onSelect: function(){
            var day1 = $("#datepicker").datepicker('getDate').getDate();                 
            var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;             
            var year1 = $("#datepicker").datepicker('getDate').getFullYear();
            var fullDate = year1 + "-" + month1 + "-" + day1;
            var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
            $('#page_output').html(str_output);
        }
    });
});

PIG how to count a number of rows in alias

What you want is to count all the lines in a relation (dataset in Pig Latin)

This is very easy following the next steps:

logs = LOAD 'log'; --relation called logs, using PigStorage with tab as field delimiter
logs_grouped = GROUP logs ALL;--gives a relation with one row with logs as a bag
number = FOREACH LOGS_GROUP GENERATE COUNT_STAR(logs);--show me the number

I have to say it is important Kevin's point as using COUNT instead of COUNT_STAR we would have only the number of lines which first field is not null.

Also I like Jerome's one line syntax it is more concise but in order to be didactic I prefer to divide it in two and add some comment.

In general I prefer:

numerito = FOREACH (GROUP CARGADOS3 ALL) GENERATE COUNT_STAR(CARGADOS3);

over

name = GROUP CARGADOS3 ALL
number = FOREACH name GENERATE COUNT_STAR(CARGADOS3);

Bootstrap 4 dropdown with search

As of 10. July 2017, the issue of Bootstrap 4 support with bootstrap-select is still open. In the open issue, there are some ad-hoc solutions which you could try with your project.

Or you could use a library like Select2 and add a theme to match Bootstrap 4. Here is an example: Select 2 with Bootstrap 4 (disclaimer: I'm not the author of this blog post and I haven't verified if this still works with the all versions of Bootstrap 4).