Programs & Examples On #Dci

Data, Context, Interactions (DCI) DCI was invented by Professor Trygve Reenskaug to solve a specific problem in OO code; it's very hard to read OO code for a specific use-case since it is often spread across many different classes, and the control flow between the methods of these classes depend on which objects are instantiated to which variables. With DCI Reenskaug proposed a new way of coding for use-cases where each use-case is implemented as a

How to use concerns in Rails 4

It's worth to mention that using concerns is considered bad idea by many.

  1. like this guy
  2. and this one

Some reasons:

  1. There is some dark magic happening behind the scenes - Concern is patching include method, there is a whole dependency handling system - way too much complexity for something that's trivial good old Ruby mixin pattern.
  2. Your classes are no less dry. If you stuff 50 public methods in various modules and include them, your class still has 50 public methods, it's just that you hide that code smell, sort of put your garbage in the drawers.
  3. Codebase is actually harder to navigate with all those concerns around.
  4. Are you sure all members of your team have same understanding what should really substitute concern?

Concerns are easy way to shoot yourself in the leg, be careful with them.

Set the value of a variable with the result of a command in a Windows batch file

The only way I've seen it done is if you do this:

for /f "delims=" %a in ('ver') do @set foobar=%a

ver is the version command for Windows and on my system it produces:

Microsoft Windows [Version 6.0.6001]

Source

WPF Binding StringFormat Short Date String

Be aware of the single quotes for the string format. This doesn't work:

    Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"

while this does:

    Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"

Rendering React Components from Array of Objects

There are couple of way which can be used.

const stations = [
  {call:'station one',frequency:'000'},
  {call:'station two',frequency:'001'}
];
const callList = stations.map(({call}) => call)

Solution 1

<p>{callList.join(', ')}</p>

Solution 2

<ol>    
  { callList && callList.map(item => <li>{item}</li>) }
</ol>

Edit kind-antonelli-z8372

Of course there are other ways also available.

Java: convert List<String> to a String

Java 8 does bring the

Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)

method, that is nullsafe by using prefix + suffix for null values.

It can be used in the following manner:

String s = stringList.stream().collect(Collectors.joining(" and ", "prefix_", "_suffix"))

The Collectors.joining(CharSequence delimiter) method just calls joining(delimiter, "", "") internally.

CORS - How do 'preflight' an httprequest?

Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:

  • jQuery sent its XHR request using only limited headers; only 'Origin' was sent.
  • No preflight request was needed.
  • The server only had to detect such a request, and add the "Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN'] header, after detecting that this was a cross-origin XHR.

PHP Code sample:

if (!empty($_SERVER['HTTP_ORIGIN'])) {
    // Uh oh, this XHR comes from outer space...
    // Use this opportunity to filter out referers that shouldn't be allowed to see this request
    if (!preg_match('@\.partner\.domain\.net$@'))
        die("End of the road if you're not my business partner.");

    // otherwise oblige
    header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
    // local request, no need to send a specific header for CORS
}

In particular, don't add an exit; as no preflight is needed.

Convert HTML + CSS to PDF

There's a tutorial on Zend's devzone on generating pdf from php (part 1, part 2) without any external libraries. I never implemented this sort of solution, but since it's all php, you might find it more flexible to implement and debug.

Update ViewPager dynamically?

I've gone through all the answers above and a number of others posts but still couldn't find something that worked for me (with different fragment types along with dynamically adding and removing tabs). FWIW following approach is what worked for me (in case anyone else has same issues).

public class MyFragmentStatePageAdapter extends FragmentStatePagerAdapter {
    private static final String TAB1_TITLE = "Tab 1";
    private static final String TAB2_TITLE = "Tab 2";
    private static final String TAB3_TITLE = "Tab 3";

    private ArrayList<String> titles = new ArrayList<>();
    private Map<Fragment, Integer> fragmentPositions = new HashMap<>();


    public MyFragmentStatePageAdapter(FragmentManager fm) {
        super(fm);
    }


    public void update(boolean showTab1, boolean showTab2, boolean showTab3) {
        titles.clear();

        if (showTab1) {
            titles.add(TAB1_TITLE);
        }
        if (showTab2) {
            titles.add(TAB2_TITLE);
        }
        if (showTab3) {
            titles.add(TAB3_TITLE);
        }
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return titles.size();
    }

    @Override
    public Fragment getItem(int position) {
        Fragment fragment = null;

        String tabName = titles.get(position);
        if (tabName.equals(TAB1_TITLE)) { 
            fragment =  Tab1Fragment.newInstance();
        } else if (tabName.equals(TAB2_TITLE)) {
            fragment =  Tab2Fragment.newInstance();
        } else if (tabName.equals(TAB3_TITLE)) {
            fragment =  Tab3Fragmen.newInstance();
        } 

        ((BaseFragment)fragment).setTitle(tabName);
        fragmentPositions.put(fragment, position);
        return fragment;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return titles.get(position);
    }

    @Override
    public int getItemPosition(Object item) {
        BaseFragment fragment = (BaseFragment)item;
        String title = fragment.getTitle();
        int position = titles.indexOf(title);

        Integer fragmentPosition = fragmentPositions.get(item);
        if (fragmentPosition != null && position == fragmentPosition) {
            return POSITION_UNCHANGED;
        } else {
            return POSITION_NONE;
        }
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
        fragmentPositions.remove(object);
    }
}

Select default option value from typescript angular 6

For reactive form, I managed to make it work by using the following example (47 can be replaced with other value or variable):

<div [formGroup]="form">
  <select formControlName="fieldName">
    <option
        *ngFor="let option of options; index as i"
        [selected]="option === 47"
    >
        {{ option }}
    </option>
  </select>
</div>

Import Excel Data into PostgreSQL 9.3

It is possible using ogr2ogr:

C:\Program Files\PostgreSQL\12\bin\ogr2ogr.exe -f "PostgreSQL" PG:"host=someip user=someuser dbname=somedb password=somepw" C:/folder/excelfile.xlsx -nln newtablenameinpostgres -oo AUTODETECT_TYPE=YES

(Not sure if ogr2ogr is included in postgres installation or if I got it with postgis extension.)

error: invalid type argument of ‘unary *’ (have ‘int’)

Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;. Finally, you declared c incorrectly. Since you assign it to be the address of a, where a is a pointer to int, you must declare it to be a pointer to a pointer to int.

#include <stdio.h>
int main(void)
{
    int b=10;
    int *a=&b;
    int **c=&a;
    printf("%d", **c);
    return 0;
} 

How to add new elements to an array?

If one really want to resize an array you could do something like this:

String[] arr = {"a", "b", "c"};
System.out.println(Arrays.toString(arr)); 
// Output is: [a, b, c]

arr = Arrays.copyOf(arr, 10); // new size will be 10 elements
arr[3] = "d";
arr[4] = "e";
arr[5] = "f";

System.out.println(Arrays.toString(arr));
// Output is: [a, b, c, d, e, f, null, null, null, null]

Django: Redirect to previous page after login

I encountered the same problem. This solution allows me to keep using the generic login view:

urlpatterns += patterns('django.views.generic.simple',
    (r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}),
)

Configure nginx with multiple locations with different root folders on subdomain

server {

    index index.html index.htm;
    server_name test.example.com;

    location / {
        root /web/test.example.com/www;
    }

    location /static {
        root /web/test.example.com;
    }
}

http://nginx.org/r/root

Retrieving subfolders names in S3 bucket from boto3

The big realisation with S3 is that there are no folders/directories just keys. The apparent folder structure is just prepended to the filename to become the 'Key', so to list the contents of myBucket's some/path/to/the/file/ you can try:

s3 = boto3.client('s3')
for obj in s3.list_objects_v2(Bucket="myBucket", Prefix="some/path/to/the/file/")['Contents']:
    print(obj['Key'])

which would give you something like:

some/path/to/the/file/yo.jpg
some/path/to/the/file/meAndYou.gif
...

How to convert List to Json in Java

Use GSON library for that. Here is the sample code

List<String> foo = new ArrayList<String>();
foo.add("A");
foo.add("B");
foo.add("C");

String json = new Gson().toJson(foo );

Here is the maven dependency for Gson

<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.2</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

Or you can directly download jar from here and put it in your class path

http://code.google.com/p/google-gson/downloads/detail?name=gson-1.0.jar&can=4&q=

To send Json to client you can use spring or in simple servlet add this code

response.getWriter().write(json);

I can't install python-ldap

For most systems, the build requirements are now mentioned in python-ldap's documentation, in the "Installing" section.

If anything is missing for your system (or your system is missing entirely), please let maintainer know! (As of 2018, I am the maintainer, so a comment here should be enough. Or you can send a pull request or mail.)

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

What is the string length of a GUID?

It depends on how you format the Guid:

  • Guid.NewGuid().ToString() => 36 characters (Hyphenated)
    outputs: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("D") => 36 characters (Hyphenated, same as ToString())
    outputs: 12345678-1234-1234-1234-123456789abc

  • Guid.NewGuid().ToString("N") => 32 characters (Digits only)
    outputs: 12345678123412341234123456789abc

  • Guid.NewGuid().ToString("B") => 38 characters (Braces)
    outputs: {12345678-1234-1234-1234-123456789abc}

  • Guid.NewGuid().ToString("P") => 38 characters (Parentheses)
    outputs: (12345678-1234-1234-1234-123456789abc)

  • Guid.NewGuid().ToString("X") => 68 characters (Hexadecimal)
    outputs: {0x12345678,0x1234,0x1234,{0x12,0x34,0x12,0x34,0x56,0x78,0x9a,0xbc}}

Is there a way to delete all the data from a topic or delete the topic before every run?

I use this script:

#!/bin/bash
topics=`kafka-topics --list --zookeeper zookeeper:2181`
for t in $topics; do 
    for p in retention.ms retention.bytes segment.ms segment.bytes; do
        kafka-topics --zookeeper zookeeper:2181 --alter --topic $t --config ${p}=100
    done
done
sleep 60
for t in $topics; do 
    for p in retention.ms retention.bytes segment.ms segment.bytes; do
        kafka-topics --zookeeper zookeeper:2181 --alter --topic $t --delete-config ${p}
    done
done

How to count string occurrence in string?

The parameters: ustring: the superset string countChar: the substring

A function to count substring occurrence in JavaScript:

_x000D_
_x000D_
function subStringCount(ustring, countChar){
  var correspCount = 0;
  var corresp = false;
  var amount = 0;
  var prevChar = null;
  
 for(var i=0; i!=ustring.length; i++){

     if(ustring.charAt(i) == countChar.charAt(0) && corresp == false){
       corresp = true;
       correspCount += 1;
       if(correspCount == countChar.length){
         amount+=1;
         corresp = false;
         correspCount = 0;
       }
       prevChar = 1;
     }
     else if(ustring.charAt(i) == countChar.charAt(prevChar) && corresp == true){
       correspCount += 1;
       if(correspCount == countChar.length){
         amount+=1;
         corresp = false;
         correspCount = 0;
         prevChar = null;
       }else{
         prevChar += 1 ;
       }
     }else{
       corresp = false;
       correspCount = 0;
     }
 } 
 return amount;
}

console.log(subStringCount('Hello World, Hello World', 'll'));
_x000D_
_x000D_
_x000D_

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

How to store phone numbers on MySQL databases?

  • All as varchar (they aren't numbers but "collections of digits")
  • Country + area + number separately
  • Not all countries have area code (eg Malta where I am)
  • Some countries drop the leading zero from the area code when dialling internal (eg UK)
  • Format in the client code

Unsuccessful append to an empty NumPy array

SO thread 'Multiply two arrays element wise, where one of the arrays has arrays as elements' has an example of constructing an array from arrays. If the subarrays are the same size, numpy makes a 2d array. But if they differ in length, it makes an array with dtype=object, and the subarrays retain their identity.

Following that, you could do something like this:

In [5]: result=np.array([np.zeros((1)),np.zeros((2))])

In [6]: result
Out[6]: array([array([ 0.]), array([ 0.,  0.])], dtype=object)

In [7]: np.append([result[0]],[1,2])
Out[7]: array([ 0.,  1.,  2.])

In [8]: result[0]
Out[8]: array([ 0.])

In [9]: result[0]=np.append([result[0]],[1,2])

In [10]: result
Out[10]: array([array([ 0.,  1.,  2.]), array([ 0.,  0.])], dtype=object)

However, I don't offhand see what advantages this has over a pure Python list or lists. It does not work like a 2d array. For example I have to use result[0][1], not result[0,1]. If the subarrays are all the same length, I have to use np.array(result.tolist()) to produce a 2d array.

GET parameters in the URL with CodeIgniter

Do this below. Worked for me. I took values from a select box and another textbox. Then on button click I took the entire data in Javascript function and redirected using javascript.

//Search Form
$(document).ready (function($){
    $("#searchbtn").click(function showAlert(e){
        e.preventDefault();
        var cat = $('#category').val();
        var srch = $('#srch').val();

        if(srch==""){
            alert("Search is empty :(");
        }
        else{
            var url = baseurl+'categories/search/'+cat+'/'+srch;            
            window.location.href=url;
        }
    });
});

The above code worked for me.

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Keys must be unique. Don't do that. Redesign as needed.

(if you are trying to insert, then delete, and the insert fails... just do the delete first. Rollback on error in either statement).

Open S3 object as a string with Boto3

read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

Plot different DataFrames in the same figure

Try:

ax = df1.plot()
df2.plot(ax=ax)

concatenate variables

If you need to concatenate paths with quotes, you can use = to replace quotes in a variable. This does not require you to know if the path already contains quotes or not. If there are no quotes, nothing is changed.

@echo off
rem Paths to combine
set DIRECTORY="C:\Directory with spaces"
set FILENAME="sub directory\filename.txt"

rem Combine two paths
set COMBINED="%DIRECTORY:"=%\%FILENAME:"=%"
echo %COMBINED%

rem This is just to illustrate how the = operator works
set DIR_WITHOUT_SPACES=%DIRECTORY:"=%
echo %DIR_WITHOUT_SPACES%

Clear icon inside input text

Using a jquery plugin I have adapted it to my needs adding customized options and creating a new plugin. You can find it here: https://github.com/david-dlc-cerezo/jquery-clearField

An example of a simple usage:

<script src='http://code.jquery.com/jquery-1.9.1.js'></script>
<script src='http://code.jquery.com/ui/1.10.3/jquery-ui.js'></script>
<script src='src/jquery.clearField.js'></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="css/jquery.clearField.css">

<table>
    <tr>
        <td><input name="test1" id="test1" clas="test" type='text'></td>
        <td>Empty</td>
    </tr>
    <tr>
        <td><input name="test2" id="test2" clas="test" type='text' value='abc'></td>
        <td>Not empty</td>
    </tr>
</table>

<script>
    $('.test').clearField();
</script>

Obtaining something like this:

enter image description here

Call An Asynchronous Javascript Function Synchronously

You can also convert it into callbacks.

function thirdPartyFoo(callback) {    
  callback("Hello World");    
}

function foo() {    
  var fooVariable;

  thirdPartyFoo(function(data) {
    fooVariable = data;
  });

  return fooVariable;
}

var temp = foo();  
console.log(temp);

Differences between SP initiated SSO and IDP initiated SSO

https://support.procore.com/faq/what-is-the-difference-between-sp-and-idp-initiated-sso

There is much more to this but this is a high level overview on which is which.

Procore supports both SP- and IdP-initiated SSO:

Identity Provider Initiated (IdP-initiated) SSO. With this option, your end users must log into your Identity Provider's SSO page (e.g., Okta, OneLogin, or Microsoft Azure AD) and then click an icon to log into and open the Procore web application. To configure this solution, see Configure IdP-Initiated SSO for Microsoft Azure AD, Configure Procore for IdP-Initated Okta SSO, or Configure IdP-Initiated SSO for OneLogin. OR Service Provider Initiated (SP-initiated) SSO. Referred to as Procore-initiated SSO, this option gives your end users the ability to sign into the Procore Login page and then sends an authorization request to the Identify Provider (e.g., Okta, OneLogin, or Microsoft Azure AD). Once the IdP authenticates the user's identify, the user is logged into Procore. To configure this solution, see Configure Procore-Initiated SSO for Microsoft Azure Active Directory, Configure Procore-Initiated SSO for Okta, or Configure Procore-Initiated SSO for OneLogin.

get current date and time in groovy?

Date has the time part, so we only need to extract it from Date

I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")

println "datePart : " + datePart + "\ttimePart : " + timePart

Detect iPhone/iPad purely by css

You might want to try the solution from this O'Reilly article.

The important part are these CSS media queries:

<link rel="stylesheet" media="all and (max-device-width: 480px)" href="iphone.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait)" href="ipad-portrait.css"> 
<link rel="stylesheet" media="all and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape)" href="ipad-landscape.css"> 
<link rel="stylesheet" media="all and (min-device-width: 1025px)" href="ipad-landscape.css"> 

CSS3 transition doesn't work with display property

I found a solution while tinkering around.

People who directly wanna see the results:

With click: https://jsfiddle.net/dt52jazg/

With Hover: https://jsfiddle.net/7gkufLsh/1/

Below is the code:

HTML

<ul class="list">
  <li>Hey</li>
  <li>This</li>
  <li>is</li>
  <li>just</li>
  <li>a</li>
  <li>test</li>
</ul>

<button class="click-me">
  Click me
</button>

CSS

.list li {
  min-height: 0;
  max-height: 0;
  opacity: 0;
  -webkit-transition: all .3s ease-in-out;
  transition: all .3s ease-in-out;
}

.active li {
  min-height: 20px;
  opacity: 1;
}

JS

(function() {
  $('.click-me').on('click', function() {
    $('.list').toggleClass('active');
  });
})();

Please let me know whether there is any problem with this solution 'coz I feel there would be no restriction of max-height with this solution.

How do you declare an object array in Java?

It's the other way round:

Vehicle[] car = new Vehicle[N];

This makes more sense, as the number of elements in the array isn't part of the type of car, but it is part of the initialization of the array whose reference you're initially assigning to car. You can then reassign it in another statement:

car = new Vehicle[10]; // Creates a new array

(Note that I've changed the type name to match Java naming conventions.)

For further information about arrays, see section 10 of the Java Language Specification.

Check if string ends with certain pattern

    String input1 = "This.is.a.great.place.too.work.";
    String input2 = "This/is/a/great/place/too/work/";
    String input3 = "This,is,a,great,place,too,work,";
    String input4 = "This.is.a.great.place.too.work.hahahah";
    String input5 = "This/is/a/great/place/too/work/hahaha";
    String input6 = "This,is,a,great,place,too,work,hahahha";
    
    String regEx = ".*work[.,/]";
    
    System.out.println(input1.matches(regEx)); // true
    System.out.println(input2.matches(regEx)); // true
    System.out.println(input3.matches(regEx)); // true
    System.out.println(input4.matches(regEx)); // false
    System.out.println(input5.matches(regEx)); // false
    System.out.println(input6.matches(regEx)); // false

Hash Map in Python

All you wanted (at the time the question was originally asked) was a hint. Here's a hint: In Python, you can use dictionaries.

Uploading Laravel Project onto Web Server

If you are trying to host your Laravel app on a shared hosting, this may help you.

Hosting Laravel on shared hosting #1

Hosting Laravel on shared hosting #2

If you want PHP 5.4 add this line to your .htaccess file or call your hosting provider.

AddType application/x-httpd-php54 .php

How to get build time stamp from Jenkins build variables?

I know its late replying to this question, but I have recently found a better solution to this problem without installing any plugin. We can create a formatted version number and can then use the variable created to display the build date/time. Steps to create: Build Environment --> Create a formatted version number:

  • Environment Variable Name: BUILD_DATE

  • Version Number Format String: ${BUILD_DATE_FORMATTED}

thats it. Just use the variable created above in the email subject line as ${ENV, var="BUILD_DATE"} and you will get the date/time of the current build.

Regex to extract URLs from href attribute in HTML with Python

The best answer is...

Don't use a regex

The expression in the accepted answer misses many cases. Among other things, URLs can have unicode characters in them. The regex you want is here, and after looking at it, you may conclude that you don't really want it after all. The most correct version is ten-thousand characters long.

Admittedly, if you were starting with plain, unstructured text with a bunch of URLs in it, then you might need that ten-thousand-character-long regex. But if your input is structured, use the structure. Your stated aim is to "extract the url, inside the anchor tag's href." Why use a ten-thousand-character-long regex when you can do something much simpler?

Parse the HTML instead

For many tasks, using Beautiful Soup will be far faster and easier to use:

>>> from bs4 import BeautifulSoup as Soup
>>> html = Soup(s, 'html.parser')           # Soup(s, 'lxml') if lxml is installed
>>> [a['href'] for a in html.find_all('a')]
['http://example.com', 'http://example2.com']

If you prefer not to use external tools, you can also directly use Python's own built-in HTML parsing library. Here's a really simple subclass of HTMLParser that does exactly what you want:

from html.parser import HTMLParser

class MyParser(HTMLParser):
    def __init__(self, output_list=None):
        HTMLParser.__init__(self)
        if output_list is None:
            self.output_list = []
        else:
            self.output_list = output_list
    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            self.output_list.append(dict(attrs).get('href'))

Test:

>>> p = MyParser()
>>> p.feed(s)
>>> p.output_list
['http://example.com', 'http://example2.com']

You could even create a new method that accepts a string, calls feed, and returns output_list. This is a vastly more powerful and extensible way than regular expressions to extract information from html.

mysql select from n last rows

Starting from the answer given by @chaos, but with a few modifications:

  • You should always use ORDER BY if you use LIMIT. There is no implicit order guaranteed for an RDBMS table. You may usually get rows in the order of the primary key, but you can't rely on this, nor is it portable.

  • If you order by in the descending order, you don't need to know the number of rows in the table beforehand.

  • You must give a correlation name (aka table alias) to a derived table.

Here's my version of the query:

SELECT `id`
FROM (
    SELECT `id`, `val`
    FROM `big_table`
    ORDER BY `id` DESC
    LIMIT $n
) AS t
WHERE t.`val` = $certain_number;

Getting parts of a URL (Regex)

regexp to get the URL path without the file.

url = 'http://domain/dir1/dir2/somefile' url.scan(/^(http://[^/]+)((?:/[^/]+)+(?=/))?/?(?:[^/]+)?$/i).to_s

It can be useful for adding a relative path to this url.

Laravel Controller Subfolder routing

In my case I had a prefix that had to be added for each route in the group, otherwise response would be that the UserController class was not found.

Route::prefix('/user')->group(function() {
    Route::post('/login', [UserController::class, 'login'])->prefix('/user');
    Route::post('/register', [UserController::class, 'register'])->prefix('/user');
});

Call a Javascript function every 5 seconds continuously

As best coding practices suggests, use setTimeout instead of setInterval.

function foo() {

    // your function code here

    setTimeout(foo, 5000);
}

foo();

Please note that this is NOT a recursive function. The function is not calling itself before it ends, it's calling a setTimeout function that will be later call the same function again.

Write a mode method in Java to find the most frequently occurring element in an array

THIS CODE CALCULATES MODE, MEDIAN, AND MEAN. IT IS TESTED AND IT DOES WORK. It is a complete program from start to finish and will compile.

import java.util.Arrays;
import java.util.Random;
import java.math.*;
/**
 *
 * @author Mason
 */
public class MODE{

    public static void main(String args[])
    {
        System.out.print("Enter the quantity of random numbers  ===>>  ");
        int listSize = Expo.enterInt();
        System.out.println();
        ArrayStats intStats = new ArrayStats(listSize);
        intStats.randomize();
        intStats.computeMean();
        intStats.computeMedian();
        intStats.computeMode();
        intStats.displayStats();
        System.out.println();
    }
}


class ArrayStats
{

    private int list[];
    private int size;
    private double mean;        
    private double median;      
    private int mode;           

    public ArrayStats(int s)//initializes class object
    {
        size = s;
        list = new int[size];
    }

    public void randomize()
    {
        //This will provide same numbers every time... If you want to randomize this, you can
        Random rand = new Random(555);
        for (int k = 0; k < size; k++)
            list[k] = rand.nextInt(11) + 10;  
    }

    public void computeMean()
    {
               double accumulator=0;
               for (int index=0;index<size;index++)
               accumulator+= list[index];

               mean = accumulator/size;
    }

        public void computeMedian()
{
        Arrays.sort(list);
                if((size%2!=0))
                    median = list[((size-1)/2)];
                else if(size!=1&&size%2==0)
                {
                    double a =(size)/2-0.5;
                    int a2 =  (int)Math.ceil(a);
                    double b =(size)/2-0.5;
                    int b2 = (int)Math.floor(b);
                    median = (double)(list[a2]+list[b2])/2;
                }
                else if (size ==1)
                    median = list[0];
        }

    public void computeMode()
    {
 int popularity1 = 0;
  int popularity2 = 0;
  int array_item; //Array contains integer value. Make it String if array contains string value.
  for(int i =0;i<list.length;i++){
      array_item = list[i];
      for(int j =0;j<list.length;j++){
          if(array_item == list[j])
             popularity1 ++;
      }
      if(popularity1 >= popularity2){
          mode = array_item;
          popularity2 = popularity1;
      }


      popularity1 = 0;
  }}

    public void displayStats()
    {
        System.out.println(Arrays.toString(list));
        System.out.println();
        System.out.println("Mean: " + mean);
        System.out.println("Median: " + median);
        System.out.println("Mode: " + mode);
        System.out.println();
    }

}

How do I define a method in Razor?

Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.

@functions {

    // Add code here.

}

100% width in React Native Flexbox

Noted: Try to fully understanding about flex concept.

       <View style={{
          flex: 2,
          justifyContent: 'center',
          alignItems: 'center'
        }}>
          <View style ={{
              flex: 1,
              alignItems: 'center, 
              height: 50, 
              borderWidth: 1, 
              borderColor: '#000' 
          }}>
               <Text>Welcome to React Nativ</Text>
           </View>
           <View style={{
              flex: 1,
              alignItems: 'center,
              borderWidth: 1, 
              borderColor: 'red ', 
              height: 50
            }}
            >
              <Text> line 1 </Text>
            </View>
          <View style={{
            flex: 1,
            alignItems: 'center, 
            height: 50, 
            borderWidth: 1,                     
            borderColor: '#000'
          }}>
             <Text>
              Press Cmd+R to reload,{'\n'}
              Cmd+D or shake for dev menu
             </Text>
           </View>
       </View>

Automatically plot different colored lines

You could use a colormap such as HSV to generate a set of colors. For example:

cc=hsv(12);
figure; 
hold on;
for i=1:12
    plot([0 1],[0 i],'color',cc(i,:));
end

MATLAB has 13 different named colormaps ('doc colormap' lists them all).

Another option for plotting lines in different colors is to use the LineStyleOrder property; see Defining the Color of Lines for Plotting in the MATLAB documentation for more information.

How to make rounded percentages add up to 100%

I'm not sure what level of accuracy you need, but what I would do is simply add 1 the first n numbers, n being the ceil of the total sum of decimals. In this case that is 3, so I would add 1 to the first 3 items and floor the rest. Of course this is not super accurate, some numbers might be rounded up or down when it shouldn't but it works okay and will always result in 100%.

So [ 13.626332, 47.989636, 9.596008, 28.788024 ] would be [14, 48, 10, 28] because Math.ceil(.626332+.989636+.596008+.788024) == 3

function evenRound( arr ) {
  var decimal = -~arr.map(function( a ){ return a % 1 })
    .reduce(function( a,b ){ return a + b }); // Ceil of total sum of decimals
  for ( var i = 0; i < decimal; ++i ) {
    arr[ i ] = ++arr[ i ]; // compensate error by adding 1 the the first n items
  }
  return arr.map(function( a ){ return ~~a }); // floor all other numbers
}

var nums = evenRound( [ 13.626332, 47.989636, 9.596008, 28.788024 ] );
var total = nums.reduce(function( a,b ){ return a + b }); //=> 100

You can always inform users that the numbers are rounded and may not be super-accurate...

Batch - Echo or Variable Not Working

Dont use spaces:

SET @var="GREG"
::instead of SET @var = "GREG"
ECHO %@var%
PAUSE

Is there a way to make a DIV unselectable?

As Johannes has already suggested, a background-image is probally the best way to achieve this in CSS alone.

A JavaScript solution would also have to affect "dragstart" to be effective across all popular browsers.

JavaScript:

<div onselectstart="return false;" ondragstart="return false;">your text</div>

jQuery:

var _preventDefault = function(evt) { evt.preventDefault(); };
$("div").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);

Rich

making a paragraph in html contain a text from a file

You can do something like that in pure html using an <object> tag:
<div><object data="file.txt"></object></div>

This method has some limitations though, like, it won't fit size of the block to the content - you have to specify width and height manually. And styles won't be applied to the text.

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

If you're on Linux, seriously consider just using the g_file_get_contents function from glib. It handles all the code for loading a file, allocating memory, and handling errors.

how to change language for DataTable

sorry to revive this thread, i know there is the solution, but it is easy to change the language with the datatables. Here, i leave you with my own datatable example.

$(document).ready(function ()
// DataTable
        var table = $('#tblUsuarios').DataTable({
            aoColumnDefs: [
                {"aTargets": [0], "bSortable": true},
                {"aTargets": [2], "asSorting": ["asc"], "bSortable": true},
            ],
            "language": {
                "url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
            }

    });

The language you get from the following link:

http://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n

Just replace the URL value in the language option with the one you like. Remember to always use the comma


Worked for me, hope it will work for anyone.

Best regards!

How to solve error message: "Failed to map the path '/'."

I also have same issue. In my case working on InstalledSheild / InstalledAware, to make setup of web service. After setup run the above error comes, while resolve issue when check, found that IIs default website path remove after setup run.

So I just add path as below step.

  1. Go to Command prompt -> type InetMgr
  2. Its open IIS, go to 'Default Web Site' -> Advanced Settings (at right side menu) enter image description here

  3. Go to Physical Path and paste this things - '%SystemDrive%\inetpub\wwwroot' as below enter image description here

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

I had similar issue when I was deploying my django application over elastic Beanstalk and what I found is when I was trying various methods somehow one eb-cli profile got created in config file in ~/.aws/ folder so once I got rid of that everything worked fine!!.

Passing an array of parameters to a stored procedure

I like this one, because it is suited to be passed as an XElement, which is suitable for SqlCommand

(Sorry it is VB.NET but you get the idea)

<Extension()>
Public Function ToXml(Of T)(array As IEnumerable(Of T)) As XElement
   Return XElement.Parse(
           String.Format("<doc>{0}</doc>", String.Join("", array.Select(Function(s) String.Concat("<d>", s.ToString(), "</d>")))), LoadOptions.None)
 End Function

This is the sql Stored proc, shortened, not complete!

CREATE PROCEDURE [dbo].[myproc] (@blah xml)
AS ... WHERE SomeID IN (SELECT doc.t.value('.','int') from @netwerkids.nodes(N'/doc/d') as doc(t))

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

Convert float to string with precision & number of decimal digits specified?

Another option is snprintf:

double pi = 3.1415926;

std::string s(16, '\0');
auto written = std::snprintf(&s[0], s.size(), "%.2f", pi);
s.resize(written);

Demo. Error handling should be added, i.e. checking for written < 0.

AngularJS not detecting Access-Control-Allow-Origin header?

I was sending requests from angularjs using $http service to bottle running on http://localhost:8090/ and I had to apply CORS otherwise I got request errors like "No 'Access-Control-Allow-Origin' header is present on the requested resource"

from bottle import hook, route, run, request, abort, response

#https://github.com/defnull/bottle/blob/master/docs/recipes.rst#using-the-hooks-plugin

@hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'

How to include js and CSS in JSP with spring MVC

You should put the folder containing css and js files into "webapp/resources". If you've put them in "src/main/java", you must change it. It worked for me.

Communication between multiple docker-compose projects

Since Compose 1.18 (spec 3.5), you can just override the default network using your own custom name for all Compose YAML files you need. It is as simple as appending the following to them:

networks:
  default:
    name: my-app

The above assumes you have version set to 3.5 (or above if they don't deprecate it in 4+).

Other answers have pointed the same; this is a simplified summary.

What does MissingManifestResourceException mean and how to fix it?

Recently ran into the same problem, struggled for a bit, found this topic but no answers were correct for me.

My issue was that when I removed main window from my WPF project (it does not have a main window), I forgot to remove StartupUri from App.xaml. I guess this exception can happen if you have a mistake in StartupUri, so in case if anybody is struggling with this - check your StartupUri in App.xaml.

Capture screenshot of active window?

KvanTTT's code worked great. I extended it a bit to allow a little more flexibility on save format, as well as the ability to save by hWnd, .NET Control/Form. You can get a bitmap or save to file, with a few options.

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace MosaiqPerformanceMonitor {
     public enum CaptureMode {
          Screen, Window
     }

     public static class ScreenCapturer {
          [DllImport("user32.dll")]
          private static extern IntPtr GetForegroundWindow();

          [DllImport("user32.dll")]
          private static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);

          [StructLayout(LayoutKind.Sequential)]
          private struct Rect {
                public int Left;
                public int Top;
                public int Right;
                public int Bottom;
          }

          [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
          public static extern IntPtr GetDesktopWindow();

          /// <summary> Capture Active Window, Desktop, Window or Control by hWnd or .NET Contro/Form and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, CaptureMode mode = CaptureMode.Window, ImageFormat format = null) {
                ImageSave(filename, format, Capture(mode));
          }

          /// <summary> Capture a specific window (or control) and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="handle">hWnd (handle) of the window to capture</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, IntPtr handle, ImageFormat format = null) {
                ImageSave(filename, format, Capture(handle));
          }

          /// <summary> Capture a specific window (or control) and save it to a specified file.  </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="c">Object to capture</param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          public static void CaptureAndSave(string filename, Control c, ImageFormat format = null) {
                ImageSave(filename, format, Capture(c));
          }
          /// <summary> Capture the active window (default) or the desktop and return it as a bitmap </summary>
          /// <param name="mode">Optional. The default value is CaptureMode.Window.</param>
          public static Bitmap Capture(CaptureMode mode = CaptureMode.Window) {
                return Capture(mode == CaptureMode.Screen ? GetDesktopWindow() : GetForegroundWindow());
          }

          /// <summary> Capture a .NET Control, Form, UserControl, etc. </summary>
          /// <param name="c">Object to capture</param>
          /// <returns> Bitmap of control's area </returns>
          public static Bitmap Capture(Control c) {
                return Capture(c.Handle);
          }


          /// <summary> Capture a specific window and return it as a bitmap </summary>
          /// <param name="handle">hWnd (handle) of the window to capture</param>
          public static Bitmap Capture(IntPtr handle) {
                Rectangle bounds;
                var rect = new Rect();
                GetWindowRect(handle, ref rect);
                bounds = new Rectangle(rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top);
                CursorPosition = new Point(Cursor.Position.X - rect.Left, Cursor.Position.Y - rect.Top);

                var result = new Bitmap(bounds.Width, bounds.Height);
                using (var g = Graphics.FromImage(result))
                     g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);

                return result;
          }

          /// <summary> Position of the cursor relative to the start of the capture </summary>
          public static Point CursorPosition;


          /// <summary> Save an image to a specific file </summary>
          /// <param name="filename">Filename.
          /// <para>* If extension is omitted, it's calculated from the type of file</para>
          /// <para>* If path is omitted, defaults to %TEMP%</para>
          /// <para>* Use %NOW% to put a timestamp in the filename</para></param>
          /// <param name="format">Optional file save mode.  Default is PNG</param>
          /// <param name="image">Image to save.  Usually a BitMap, but can be any
          /// Image.</param>
          static void ImageSave(string filename, ImageFormat format, Image image) {
                format = format ?? ImageFormat.Png;
                if (!filename.Contains("."))
                     filename = filename.Trim() + "." + format.ToString().ToLower();

                if (!filename.Contains(@"\"))
                     filename = Path.Combine(Environment.GetEnvironmentVariable("TEMP") ?? @"C:\Temp", filename);

                filename = filename.Replace("%NOW%", DateTime.Now.ToString("[email protected]"));
                image.Save(filename, format);
          }
     }
}

Java RegEx meta character (.) and ordinary dot?

Solutions proposed by the other members don't work for me.

But I found this :

to escape a dot in java regexp write [.]

When should I use a struct rather than a class in C#?

The C# struct is a lightweight alternative to a class. It can do almost the same as a class, but it's less "expensive" to use a struct rather than a class. The reason for this is a bit technical, but to sum up, new instances of a class is placed on the heap, where newly instantiated structs are placed on the stack. Furthermore, you are not dealing with references to structs, like with classes, but instead you are working directly with the struct instance. This also means that when you pass a struct to a function, it is by value, instead of as a reference. There is more about this in the chapter about function parameters.

So, you should use structs when you wish to represent more simple data structures, and especially if you know that you will be instantiating lots of them. There are lots of examples in the .NET framework, where Microsoft has used structs instead of classes, for instance the Point, Rectangle and Color struct.

CSS3 Transition not working

If you have a <script> tag anywhere on your page (even in the HTML, even if it is an empty tag with a src), then a transition must be activated by some event (it won't fire automatically when the page loads).

Docker-compose: node_modules not present in a volume after npm install succeeds

This happens because you have added your worker directory as a volume to your docker-compose.yml, as the volume is not mounted during the build.

When docker builds the image, the node_modules directory is created within the worker directory, and all the dependencies are installed there. Then on runtime the worker directory from outside docker is mounted into the docker instance (which does not have the installed node_modules), hiding the node_modules you just installed. You can verify this by removing the mounted volume from your docker-compose.yml.

A workaround is to use a data volume to store all the node_modules, as data volumes copy in the data from the built docker image before the worker directory is mounted. This can be done in the docker-compose.yml like this:

redis:
    image: redis
worker:
    build: ./worker
    command: npm start
    ports:
        - "9730:9730"
    volumes:
        - ./worker/:/worker/
        - /worker/node_modules
    links:
        - redis

I'm not entirely certain whether this imposes any issues for the portability of the image, but as it seems you are primarily using docker to provide a runtime environment, this should not be an issue.

If you want to read more about volumes, there is a nice user guide available here: https://docs.docker.com/userguide/dockervolumes/

EDIT: Docker has since changed it's syntax to require a leading ./ for mounting in files relative to the docker-compose.yml file.

Refreshing page on click of a button

<button type="button" onClick="refreshPage()">Close</button>

<script>
function refreshPage(){
    window.location.reload();
} 
</script>

or

<button type="button" onClick="window.location.reload();">Close</button>

Is it possible to make abstract classes in Python?

also this works and is simple:

class A_abstract(object):

    def __init__(self):
        # quite simple, old-school way.
        if self.__class__.__name__ == "A_abstract": 
            raise NotImplementedError("You can't instantiate this abstract class. Derive it, please.")

class B(A_abstract):

        pass

b = B()

# here an exception is raised:
a = A_abstract()

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

How to Validate a DateTime in C#?

Here's another variation of the solution that returns true if the string can be converted to a DateTime type, and false otherwise.

public static bool IsDateTime(string txtDate)
{
    DateTime tempDate;
    return DateTime.TryParse(txtDate, out tempDate);
}

How do I get the file name from a String containing the Absolute file path?

The other answers didn't quite work for my specific scenario, where I am reading paths that have originated from an OS different to my current one. To elaborate I am saving email attachments saved from a Windows platform on a Linux server. The filename returned from the JavaMail API is something like 'C:\temp\hello.xls'

The solution I ended up with:

String filenameWithPath = "C:\\temp\\hello.xls";
String[] tokens = filenameWithPath.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];

Use jQuery to hide a DIV when the user clicks outside of it

According to the docs, .blur() works for more than the <input> tag. For example:

$('.form_wrapper').blur(function(){
   $(this).hide();
});

MS Access DB Engine (32-bit) with Office 64-bit

Even tried all suggestions, in my case (Office x64 - Visual Studio 2017), the only way to have both access engines on a Office 64x installation so you can use it on Visual Studio and using a 2016+ version of Office, is to install the 2010 version of the Engine.

First install the x64 from this page

https://www.microsoft.com/en-us/download/details.aspx?id=54920

and then the x86 version from this one

https://www.microsoft.com/en-us/download/details.aspx?id=13255

as from this blog: http://dinesql.blogspot.com/2017/10/microsoft-access-database-engine-2016-Redistributable-Setup-you-cannot-install-the-32-bit-version-You-cannot-install-the-64-bit-version.html

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

How to split a data frame?

If you want to split a dataframe according to values of some variable, I'd suggest using daply() from the plyr package.

library(plyr)
x <- daply(df, .(splitting_variable), function(x)return(x))

Now, x is an array of dataframes. To access one of the dataframes, you can index it with the name of the level of the splitting variable.

x$Level1
#or
x[["Level1"]]

I'd be sure that there aren't other more clever ways to deal with your data before splitting it up into many dataframes though.

create array from mysql query php

THE CORRECT WAY ************************ THE CORRECT WAY

while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows);  // pop the last row off, which is an empty row

Java how to sort a Linked List?

In order to sort Strings alphabetically you will need to use a Collator, like:

 LinkedList<String> list = new LinkedList<String>();
 list.add("abc");
 list.add("Bcd");
 list.add("aAb");
 Collections.sort(list, new Comparator<String>() {
     @Override
     public int compare(String o1, String o2) {
         return Collator.getInstance().compare(o1, o2);
     }
 });

Because if you just call Collections.sort(list) you will have trouble with strings that contain uppercase characters.

For instance in the code I pasted, after the sorting the list will be: [aAb, abc, Bcd] but if you just call Collections.sort(list); you will get: [Bcd, aAb, abc]

Note: When using a Collator you can specify the locale Collator.getInstance(Locale.ENGLISH) this is usually pretty handy.

select count(*) from table of mysql in php

$num_result = mysql_query("SELECT count(*) as total_count from Students ") or exit(mysql_error());
$row = mysql_fetch_object($num_result);
echo $row->total_count;

How can I generate Unix timestamps?

In Linux or MacOS you can use:

date +%s

where

  • +%s, seconds since 1970-01-01 00:00:00 UTC. (GNU Coreutils 8.24 Date manual)

Example output now 1454000043.

Pass Additional ViewData to a Strongly-Typed Partial View

RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       new ViewDataDictionary { { "index", index } }
); 

Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.

HTML text input allow only numeric input

Use:

<script>
    function onlyNumber(id){ 
        var DataVal = document.getElementById(id).value;
        document.getElementById(id).value = DataVal.replace(/[^0-9]/g,'');
    }
</script>
<input type="text" id="1" name="1" onChange="onlyNumber(this.id);">

And if you want to update a value after press key, you can change onChange for onKeypress, onKeyDown or onKeyup. But event onKeypress doesn't running in any browsers.

Create database from command line

Try:

sudo -u postgres psql -c 'create database test;'

Define preprocessor macro through CMake?

For a long time, CMake had the add_definitions command for this purpose. However, recently the command has been superseded by a more fine grained approach (separate commands for compile definitions, include directories, and compiler options).

An example using the new add_compile_definitions:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
add_compile_definitions(WITH_OPENCV2)

Or:

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION} WITH_OPENCV2)

The good part about this is that it circumvents the shabby trickery CMake has in place for add_definitions. CMake is such a shabby system, but they are finally finding some sanity.

Find more explanation on which commands to use for compiler flags here: https://cmake.org/cmake/help/latest/command/add_definitions.html

Likewise, you can do this per-target as explained in Jim Hunziker's answer.

PHP: Inserting Values from the Form into MySQL

Try this:

dbConfig.php

<?php
$mysqli = new mysqli('localhost', 'root', 'pwd', 'yr db name');
    if($mysqli->connect_error)
        {
        echo $mysqli->connect_error;
        }
    ?>

Index.php

<html>
<head><title>Inserting data in database table </title>
</head>
<body>
<form action="control_table.php" method="post">
<table border="1" background="red" align="center">
<tr>
<td>Login Name</td>
<td><input type="text" name="txtname" /></td>
</tr>
<br>
<tr>
<td>Password</td>
<td><input type="text" name="txtpwd" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="txtbutton" value="SUBMIT" /></td>
</tr>
</table>
control_table.php
<?php include 'config.php'; ?>
<?php
$name=$pwd="";
    if(isset($_POST['txtbutton']))
        {
            $name = $_POST['txtname'];
            $pwd = $_POST['txtpwd'];
            $mysqli->query("insert into users(name,pwd) values('$name', '$pwd')");
        if(!$mysqli) 
        { echo mysqli_error(); }
    else
    {
        echo "Successfully Inserted <br />";
        echo "<a href='show.php'>View Result</a>";
    }

         }  

    ?>

How to obtain the last path segment of a URI

Here's a short method to do it:

public static String getLastBitFromUrl(final String url){
    // return url.replaceFirst("[^?]*/(.*?)(?:\\?.*)","$1);" <-- incorrect
    return url.replaceFirst(".*/([^/?]+).*", "$1");
}

Test Code:

public static void main(final String[] args){
    System.out.println(getLastBitFromUrl(
        "http://example.com/foo/bar/42?param=true"));
    System.out.println(getLastBitFromUrl("http://example.com/foo"));
    System.out.println(getLastBitFromUrl("http://example.com/bar/"));
}

Output:

42
foo
bar

Explanation:

.*/      // find anything up to the last / character
([^/?]+) // find (and capture) all following characters up to the next / or ?
         // the + makes sure that at least 1 character is matched
.*       // find all following characters


$1       // this variable references the saved second group from above
         // I.e. the entire string is replaces with just the portion
         // captured by the parentheses above

How to tell if a string is not defined in a Bash shell script

I think the answer you are after is implied (if not stated) by Vinko's answer, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:

if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "$VAR" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi

You probably can combine the two tests on the second line into one with:

if [ -z "$VAR" -a "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi

However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '-a' and do recommend using separate simple tests combined with &&. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).

You can find the details of these, and other related shell parameter expansions, the test or [ command and conditional expressions in the Bash manual.


I was recently asked by email about this answer with the question:

You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion

if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi

Wouldn't this accomplish the same?

if [ -z "${VAR}" ]; then echo VAR is not set at all; fi

Fair question - the answer is 'No, your simpler alternative does not do the same thing'.

Suppose I write this before your test:

VAR=

Your test will say "VAR is not set at all", but mine will say (by implication because it echoes nothing) "VAR is set but its value might be empty". Try this script:

(
unset VAR
if [ -z "${VAR+xxx}" ]; then echo JL:1 VAR is not set at all; fi
if [ -z "${VAR}" ];     then echo MP:1 VAR is not set at all; fi
VAR=
if [ -z "${VAR+xxx}" ]; then echo JL:2 VAR is not set at all; fi
if [ -z "${VAR}" ];     then echo MP:2 VAR is not set at all; fi
)

The output is:

JL:1 VAR is not set at all
MP:1 VAR is not set at all
MP:2 VAR is not set at all

In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the ${VAR=value} and ${VAR:=value} notations make. Ditto for ${VAR-value} and ${VAR:-value}, and ${VAR+value} and ${VAR:+value}, and so on.


As Gili points out in his answer, if you run bash with the set -o nounset option, then the basic answer above fails with unbound variable. It is easily remedied:

if [ -z "${VAR+xxx}" ]; then echo VAR is not set at all; fi
if [ -z "${VAR-}" ] && [ "${VAR+xxx}" = "xxx" ]; then echo VAR is set but empty; fi

Or you could cancel the set -o nounset option with set +u (set -u being equivalent to set -o nounset).

JQuery create a form and add elements to it programmatically

The tag is not closed:

$form.append("<input type=button value=button");

Should be:

$form.append('<input type="button" value="button">');

What is the volatile keyword useful for?

There are two different uses of volatile keyword.

  1. Prevents JVM from reading values from register (assume as cache), and forces its value to be read from memory.
  2. Reduces the risk of memory in-consistency errors.

Prevents JVM from reading values in register, and forces its value to be read from memory.

A busy flag is used to prevent a thread from continuing while the device is busy and the flag is not protected by a lock:

while (busy) {
    /* do something else */
}

The testing thread will continue when another thread turns off the busy flag:

busy = 0;

However, since busy is accessed frequently in the testing thread, the JVM may optimize the test by placing the value of busy in a register, then test the contents of the register without reading the value of busy in memory before every test. The testing thread would never see busy change and the other thread would only change the value of busy in memory, resulting in deadlock. Declaring the busy flag as volatile forces its value to be read before each test.

Reduces the risk of memory consistency errors.

Using volatile variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a "happens-before" relationship with subsequent reads of that same variable. This means that changes to a volatile variable are always visible to other threads.

The technique of reading, writing without memory consistency errors is called atomic action.

An atomic action is one that effectively happens all at once. An atomic action cannot stop in the middle: it either happens completely, or it doesn't happen at all. No side effects of an atomic action are visible until the action is complete.

Below are actions you can specify that are atomic:

  • Reads and writes are atomic for reference variables and for most primitive variables (all types except long and double).
  • Reads and writes are atomic for all variables declared volatile (including long and double variables).

Cheers!

AngularJs event to call after content is loaded

You can directly call it by adding {{YourFunction()}} after HTML element.

Here is a Plunker Link.

Passing parameters to click() & bind() event in jquery?

var someParam = xxxxxxx;

commentbtn.click(function(){

    alert(someParam );
});

Regex match entire words only

To match any whole word you would use the pattern (\w+)

Assuming you are using PCRE or something similar:

enter image description here

Above screenshot taken from this live example: http://regex101.com/r/cU5lC2

Matching any whole word on the commandline with (\w+)

I'll be using the phpsh interactive shell on Ubuntu 12.10 to demonstrate the PCRE regex engine through the method known as preg_match

Start phpsh, put some content into a variable, match on word.

el@apollo:~/foo$ phpsh

php> $content1 = 'badger'
php> $content2 = '1234'
php> $content3 = '$%^&'

php> echo preg_match('(\w+)', $content1);
1

php> echo preg_match('(\w+)', $content2);
1

php> echo preg_match('(\w+)', $content3);
0

The preg_match method used the PCRE engine within the PHP language to analyze variables: $content1, $content2 and $content3 with the (\w)+ pattern.

$content1 and $content2 contain at least one word, $content3 does not.

Match a number of literal words on the commandline with (dart|fart)

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(dart|fart)', $gun1);
1

php> echo preg_match('(dart|fart)', $gun2);
1

php> echo preg_match('(dart|fart)', $gun3);
1

php> echo preg_match('(dart|fart)', $gun4);
0

variables gun1 and gun2 contain the string dart or fart. gun4 does not. However it may be a problem that looking for word fart matches farty. To fix this, enforce word boundaries in regex.

Match literal words on the commandline with word boundaries.

el@apollo:~/foo$ phpsh

php> $gun1 = 'dart gun';
php> $gun2 = 'fart gun';
php> $gun3 = 'farty gun';
php> $gun4 = 'unicorn gun';

php> echo preg_match('(\bdart\b|\bfart\b)', $gun1);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun2);
1

php> echo preg_match('(\bdart\b|\bfart\b)', $gun3);
0

php> echo preg_match('(\bdart\b|\bfart\b)', $gun4);
0

So it's the same as the previous example except that the word fart with a \b word boundary does not exist in the content: farty.

Implementing Singleton with an Enum (in Java)

An enum type is a special type of class.

Your enum will actually be compiled to something like

public final class MySingleton {
    public final static MySingleton INSTANCE = new MySingleton();
    private MySingleton(){} 
}

When your code first accesses INSTANCE, the class MySingleton will be loaded and initialized by the JVM. This process initializes the static field above once (lazily).

How to get a key in a JavaScript object by its value?

I use this function:

Object.prototype.getKey = function(value){
  for(var key in this){
    if(this[key] == value){
      return key;
    }
  }
  return null;
};

Usage:

// ISO 639: 2-letter codes
var languageCodes = {
  DA: 'Danish',
  DE: 'German',
  DZ: 'Bhutani',
  EL: 'Greek',
  EN: 'English',
  EO: 'Esperanto',
  ES: 'Spanish'
};

var key = languageCodes.getKey('Greek');
console.log(key); // EL

How to exit git log or git diff

I wanted to give some kudos to the comment that mentioned CTRL + Z as an option. At the end of the day, it's going to depend on what system that you have Git installed on and what program is configured to open text files (e.g. less vs. vim). CTRL + Z works for vim on Windows.

If you're using Git in a Windows environment, there are some quirks. Just helps to know what they are. (i.e. Notepad vs. Nano, etc.).

Is it possible to force Excel recognize UTF-8 CSV files automatically?

In php you just prepend $bom to your $csv_string:

$bom = sprintf( "%c%c%c", 239, 187, 191); // EF BB BF
file_put_contents( $file_name, $bom . $csv_string );

Tested with MS Excel 2016, php 7.2.4

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Reinstalling Compass worked for me.. It's a magic!

sudo gem install -n /usr/local/bin compass

nginx missing sites-available directory

Well, I think nginx by itself doesn't have that in its setup, because the Ubuntu-maintained package does it as a convention to imitate Debian's apache setup. You could create it yourself if you wanted to emulate the same setup.

Create /etc/nginx/sites-available and /etc/nginx/sites-enabled and then edit the http block inside /etc/nginx/nginx.conf and add this line

include /etc/nginx/sites-enabled/*;

Of course, all the files will be inside sites-available, and you'd create a symlink for them inside sites-enabled for those you want enabled.

add an element to int [] array in java

try this

public static void main(String[] args) {
    int[] series = {4,2};
    series = addElement(series, 3);
    series = addElement(series, 1);
}

static int[] addElement(int[] a, int e) {
    a  = Arrays.copyOf(a, a.length + 1);
    a[a.length - 1] = e;
    return a;
}

How to determine device screen size category (small, normal, large, xlarge) using code?

Here is a Xamarin.Android version of Tom McFarlin's answer

        //Determine screen size
        if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeLarge) {
            Toast.MakeText (this, "Large screen", ToastLength.Short).Show ();
        } else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeNormal) {
            Toast.MakeText (this, "Normal screen", ToastLength.Short).Show ();
        } else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeSmall) {
            Toast.MakeText (this, "Small screen", ToastLength.Short).Show ();
        } else if ((Application.Context.Resources.Configuration.ScreenLayout & ScreenLayout.SizeMask) == ScreenLayout.SizeXlarge) {
            Toast.MakeText (this, "XLarge screen", ToastLength.Short).Show ();
        } else {
            Toast.MakeText (this, "Screen size is neither large, normal or small", ToastLength.Short).Show ();
        }
        //Determine density
        DisplayMetrics metrics = new DisplayMetrics();
        WindowManager.DefaultDisplay.GetMetrics (metrics);
        var density = metrics.DensityDpi;
        if (density == DisplayMetricsDensity.High) {
            Toast.MakeText (this, "DENSITY_HIGH... Density is " + density, ToastLength.Long).Show ();
        } else if (density == DisplayMetricsDensity.Medium) {
            Toast.MakeText (this, "DENSITY_MEDIUM... Density is " + density, ToastLength.Long).Show ();
        } else if (density == DisplayMetricsDensity.Low) {
            Toast.MakeText (this, "DENSITY_LOW... Density is " + density, ToastLength.Long).Show ();
        } else if (density == DisplayMetricsDensity.Xhigh) {
            Toast.MakeText (this, "DENSITY_XHIGH... Density is " + density, ToastLength.Long).Show ();
        } else if (density == DisplayMetricsDensity.Xxhigh) {
            Toast.MakeText (this, "DENSITY_XXHIGH... Density is " + density, ToastLength.Long).Show ();
        } else if (density == DisplayMetricsDensity.Xxxhigh) {
            Toast.MakeText (this, "DENSITY_XXXHIGH... Density is " + density, ToastLength.Long).Show ();
        } else {
            Toast.MakeText (this, "Density is neither HIGH, MEDIUM OR LOW.  Density is " + density, ToastLength.Long).Show ();
        }

how do you filter pandas dataframes by multiple columns

In case somebody wonders what is the faster way to filter (the accepted answer or the one from @redreamality):

import pandas as pd
import numpy as np

length = 100_000
df = pd.DataFrame()
df['Year'] = np.random.randint(1950, 2019, size=length)
df['Gender'] = np.random.choice(['Male', 'Female'], length)

%timeit df.query('Gender=="Male" & Year=="2014" ')
%timeit df[(df['Gender']=='Male') & (df['Year']==2014)]

Results for 100,000 rows:

6.67 ms ± 557 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
5.54 ms ± 536 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Results for 10,000,000 rows:

326 ms ± 6.52 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
472 ms ± 25.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So results depend on the size and the data. On my laptop, query() gets faster after 500k rows. Further, the string search in Year=="2014" has an unnecessary overhead (Year==2014 is faster).

Display help message with python argparse when script is called without any arguments

parser.print_help()
parser.exit()

The parser.exit method also accept a status (returncode), and a message value (include a trailing newline yourself!).

an opinionated example, :)

#!/usr/bin/env python3

""" Example argparser based python file
"""

import argparse

ARGP = argparse.ArgumentParser(
    description=__doc__,
    formatter_class=argparse.RawTextHelpFormatter,
)
ARGP.add_argument('--example', action='store_true', help='Example Argument')


def main(argp=None):
    if argp is None:
        argp = ARGP.parse_args()  # pragma: no cover

    if 'soemthing_went_wrong' and not argp.example:
        ARGP.print_help()
        ARGP.exit(status=64, message="\nSomething went wrong, --example condition was not set\n")


if __name__ == '__main__':
    main()  # pragma: no cover

Example calls:

$ python3 ~/helloworld.py; echo $?
usage: helloworld.py [-h] [--example]

 Example argparser based python file

optional arguments:
  -h, --help  show this help message and exit
  --example   Example Argument

Something went wrong, --example condition was not set
64
$ python3 ~/helloworld.py --example; echo $?
0

How to set "value" to input web element using selenium?

As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");

Difference between TCP and UDP?

From the Skullbox article:

TCP (Transmission Control Protocol) is the most commonly used protocol on the Internet. The reason for this is because TCP offers error correction. When the TCP protocol is used there is a "guaranteed delivery." This is due largely in part to a method called "flow control." Flow control determines when data needs to be re-sent, and stops the flow of data until previous packets are successfully transferred. This works because if a packet of data is sent, a collision may occur. When this happens, the client re-requests the packet from the server until the whole packet is complete and is identical to its original.

UDP (User Datagram Protocol) is anther commonly used protocol on the Internet. However, UDP is never used to send important data such as webpages, database information, etc; UDP is commonly used for streaming audio and video. Streaming media such as Windows Media audio files (.WMA) , Real Player (.RM), and others use UDP because it offers speed! The reason UDP is faster than TCP is because there is no form of flow control or error correction. The data sent over the Internet is affected by collisions, and errors will be present. Remember that UDP is only concerned with speed. This is the main reason why streaming media is not high quality.

1) TCP is connection oriented and reliable where as UDP is connection less and unreliable.

2) TCP needs more processing at network interface level where as in UDP it’s not.

3) TCP uses, 3 way handshake, congestion control, flow control and other mechanism to make sure the reliable transmission.

4) UDP is mostly used in cases where the packet delay is more serious than packet loss.

JavaScript DOM: Find Element Index In Container

You can use this to find the index of an element:

Array.prototype.indexOf.call(yourUl, yourLi)

This for example logs all indices:

var lis = yourList.getElementsByTagName('li');
for(var i = 0; i < lis.length; i++) {
    console.log(Array.prototype.indexOf.call(lis, lis[i]));
}?

JSFIDDLE

Right align text in android TextView

I also faced the same problem and figured the problem was happening as the layout_width of the TextView was having wrap_content. You need to have layout_width as match_parent and the android:gravity = "gravity"

Using a .php file to generate a MySQL dump

As long as you are allowed to use exec(), you can execute shell commands through your PHP code.

So assuming you know how to write the mysqldump in the command line, i.e.

mysqldump -u [username] -p [database] > [database].sql

then you can use this as the parameter to exec() function.

exec("mysqldump -u mysqluser -p my_database > my_database_dump.sql");

jQuery: get the file name selected from <input type="file" />

It is just such simple as writing:

$('input[type=file]').val()

Anyway, I suggest using name or ID attribute to select your input. And with event, it should look like this:

$('input[type=file]').change(function(e){
  $in=$(this);
  $in.next().html($in.val());
});

Preferred way to create a Scala list

As a new scala developer i wrote small test to check list creation time with suggested methods above. It looks like (for ( p <- ( 0 to x ) ) yield p) toList the fastest approach.

import java.util.Date
object Listbm {

  final val listSize = 1048576
  final val iterationCounts = 5
  def getCurrentTime: BigInt = (new Date) getTime

  def createList[T] ( f : Int => T )( size : Int ): T = f ( size )

  // returns function time execution
  def experiment[T] ( f : Int => T ) ( iterations: Int ) ( size :Int ) : Int  = {

    val start_time = getCurrentTime
    for ( p <- 0 to iterations )  createList ( f ) ( size )
    return (getCurrentTime - start_time) toInt

  }

  def printResult ( f:  => Int ) : Unit = println ( "execution time " + f  )

  def main( args : Array[String] ) {


    args(0) match {

      case "for" =>  printResult ( experiment ( x => (for ( p <- ( 0 to x ) ) yield p) toList  ) ( iterationCounts ) ( listSize ) )
      case "range"  =>  printResult ( experiment ( x => ( 0 to x ) toList ) ( iterationCounts ) ( listSize ) )
      case "::" => printResult ( experiment ( x => ((0 to x) :\ List[Int]())(_ :: _) ) ( iterationCounts ) ( listSize ) )
      case _ => println ( "please use: for, range or ::\n")
    }
  }
}

Android load from URL to Bitmap

Its Working in Pie OS Use this

    @Override
    protected void onCreate() {
        super.onCreate();
        //setNotificationBadge();

        if (android.os.Build.VERSION.SDK_INT >= 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

    }

        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        Menu menu = bottomNavigationView.getMenu();
        MenuItem userImage = menu.findItem(R.id.navigation_download);
        userImage.setTitle("Login");

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {

                    URL url = new URL("https://rukminim1.flixcart.com/image/832/832/jmux18w0/mobile/b/g/n/mi-redmi-6-mzb6387in-original-imaf9z8eheryfbsu.jpeg?q=70");
                    Bitmap myBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());

                    Log.e("keshav", "Bitmap " + myBitmap);
                    userImage.setIcon(new BitmapDrawable(getResources(), myBitmap));

                } catch (IOException e) {
                    Log.e("keshav", "Exception " + e.getMessage());
                }
            }
        });

How to remove the Flutter debug banner?

MaterialApp( debugShowCheckedModeBanner: false, )

Twitter bootstrap 3 two columns full height

If there will be no content after the row (whole screen height is taken), the trick with using position: fixed; height: 100% for .col:before element may work well:

_x000D_
_x000D_
header {_x000D_
  background: green;_x000D_
  height: 50px;_x000D_
}_x000D_
.col-xs-3 {_x000D_
  background: pink;_x000D_
}_x000D_
.col-xs-3:before {_x000D_
  background: pink;_x000D_
  content: ' ';_x000D_
  height: 100%;_x000D_
  margin-left: -15px; /* compensates column's padding */_x000D_
  position: fixed;_x000D_
  width: inherit; /* bootstrap column's width */_x000D_
  z-index: -1; /* puts behind content */_x000D_
}_x000D_
.col-xs-9 {_x000D_
  background: yellow;_x000D_
}_x000D_
.col-xs-9:before {_x000D_
  background: yellow;_x000D_
  content: ' ';_x000D_
  height: 100%;_x000D_
  margin-left: -15px; /* compensates column's padding */_x000D_
  position: fixed;_x000D_
  width: inherit; /* bootstrap column's width */_x000D_
  z-index: -1; /* puts behind content */_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<header>Header</header>_x000D_
<div class="container-fluid">_x000D_
    <div class="row">_x000D_
        <div class="col-xs-3">Navigation</div>_x000D_
        <div class="col-xs-9">Content</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where is the list of predefined Maven properties

I got tired of seeing this page with its by-now stale references to defunct Codehaus pages so I asked on the Maven Users mailing list and got some more up-to-date answers.

I would say that the best (and most authoritative) answer contained in my link above is the one contributed by Hervé BOUTEMY:

here is the core reference: http://maven.apache.org/ref/3-LATEST/maven-model-builder/

it does not explain everyting that can be found in POM or in settings, since there are so much info available but it points to POM and settings descriptors and explains everything that is not POM or settings

How do I remove javascript validation from my eclipse project?

I removed the tag in the .project .

    <buildCommand>
        <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
        <arguments>
        </arguments>
    </buildCommand>

It's worked very well for me.

Open directory dialog

For Directory Dialog to get the Directory Path, First Add reference System.Windows.Forms, and then Resolve, and then put this code in a button click.

    var dialog = new FolderBrowserDialog();
    dialog.ShowDialog();
    folderpathTB.Text = dialog.SelectedPath;

(folderpathTB is name of TextBox where I wana put the folder path, OR u can assign it to a string variable too i.e.)

    string folder = dialog.SelectedPath;

And if you wana get FileName/path, Simply do this on Button Click

    FileDialog fileDialog = new OpenFileDialog();
    fileDialog.ShowDialog();
    folderpathTB.Text = fileDialog.FileName;

(folderpathTB is name of TextBox where I wana put the file path, OR u can assign it to a string variable too)

Note: For Folder Dialog, the System.Windows.Forms.dll must be added to the project, otherwise it wouldn't work.

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

jquery: get id from class selector

As of jQuery 1.6, you could (and some would say should) use .prop instead of .attr

$('.test').click(function(){
    alert($(this).prop('id'));
});

It is discussed further in this post: .prop() vs .attr()

Angular cookies

Yeah, here is one ng2-cookies

Usage:

import { Cookie } from 'ng2-cookies/ng2-cookies';

Cookie.setCookie('cookieName', 'cookieValue');
Cookie.setCookie('cookieName', 'cookieValue', 10 /*days from now*/);
Cookie.setCookie('cookieName', 'cookieValue', 10, '/myapp/', 'mydomain.com');

let myCookie = Cookie.getCookie('cookieName');

Cookie.deleteCookie('cookieName');

Capitalize the first letter of string in AngularJs

If you use Bootstrap, you can simply add the text-capitalize helper class:

<p class="text-capitalize">CapiTaliZed text.</p>

EDIT: just in case the link dies again:

Text Transform

Transform text in components with text capitalization classes.

lowercased text.
UPPERCASED TEXT.
CapiTaliZed Text.

<p class="text-lowercase">Lowercased text.</p>
<p class="text-uppercase">Uppercased text.</p>
<p class="text-capitalize">CapiTaliZed text.</p>

Note how text-capitalize only changes the first letter of each word, leaving the case of any other letters unaffected.

How to restart tomcat 6 in ubuntu

if you are using extracted tomcat then,

startup.sh and shutdown.sh are two script located in TOMCAT/bin/ to start and shutdown tomcat, You could use that

if tomcat is installed then

/etc/init.d/tomcat5.5 start
/etc/init.d/tomcat5.5 stop
/etc/init.d/tomcat5.5 restart

What's the difference between HEAD, working tree and index, in Git?

A few other good references on those topics:

workflow

I use the index as a checkpoint.

When I'm about to make a change that might go awry — when I want to explore some direction that I'm not sure if I can follow through on or even whether it's a good idea, such as a conceptually demanding refactoring or changing a representation type — I checkpoint my work into the index.

If this is the first change I've made since my last commit, then I can use the local repository as a checkpoint, but often I've got one conceptual change that I'm implementing as a set of little steps.
I want to checkpoint after each step, but save the commit until I've gotten back to working, tested code.

Notes:

  1. the workspace is the directory tree of (source) files that you see and edit.

  2. The index is a single, large, binary file in <baseOfRepo>/.git/index, which lists all files in the current branch, their sha1 checksums, time stamps and the file name -- it is not another directory with a copy of files in it.

  3. The local repository is a hidden directory (.git) including an objects directory containing all versions of every file in the repo (local branches and copies of remote branches) as a compressed "blob" file.

Don't think of the four 'disks' represented in the image above as separate copies of the repo files.

3 states

They are basically named references for Git commits. There are two major types of refs: tags and heads.

  • Tags are fixed references that mark a specific point in history, for example v2.6.29.
  • On the contrary, heads are always moved to reflect the current position of project development.

commits

(note: as commented by Timo Huovinen, those arrows are not what the commits point to, it's the workflow order, basically showing arrows as 1 -> 2 -> 3 -> 4 where 1 is the first commit and 4 is the last)

Now we know what is happening in the project.
But to know what is happening right here, right now there is a special reference called HEAD. It serves two major purposes:

  • it tells Git which commit to take files from when you checkout, and
  • it tells Git where to put new commits when you commit.

When you run git checkout ref it points HEAD to the ref you’ve designated and extracts files from it. When you run git commit it creates a new commit object, which becomes a child of current HEAD. Normally HEAD points to one of the heads, so everything works out just fine.

checkout

How to set up devices for VS Code for a Flutter emulator

From version 2.13.0 of Dart Code, emulators can be launched directly from within Code but This feature relies on support from the Flutter tools which means it will only show emulators when using a very recent Flutter SDK. Flutter’s master channel already has this change, but it may take a little longer to filter through to the dev and beta channels.

I tested this feature and worked very well on flutter version 0.5.6-pre.61 (master channel)

enter image description here

How to set Meld as git mergetool

None of the other answers here worked for me, possibly from trying a combination of all of them. I was able to adapt this accepted answer to work with meld. This is now working for me with git 1.9.4, meld 3.14.0, and windows 8.1.

Edit ~/.gitconfig to look like:

[diff]
    tool = meld
    guitool = meld
[mergetool "meld"]
    path = c:/Program Files (x86)/Meld/Meld.exe
[difftool "meld"]
    path = c:/Program Files (x86)/Meld/Meld.exe

how to fetch data from database in Hibernate

Let me quote this:

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

As far as I can see you are using the table name.

So it should be like this:

Query query = session.createQuery("from Employee");

Why is vertical-align:text-top; not working in CSS

You can use margin-top: -50% to move the text all the way to the top of the div.

margin-top: -50%;

General error: 1364 Field 'user_id' doesn't have a default value

There are two solutions for this issue.

First, is to create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.

Second, if you started to get this error just recently, after MySQL/MariaDB upgrade, like I did, and in case you already have large project with a lot to fix, all you need to do is to edit MySQL/MariaDB configuration file (for example /etc/my.cnf) and disable strict mode for tables:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

This error started to happen quite recently, due to new strict mode enabled by default. Removing STRICT_TRANS_TABLES from sql_mode configuration key, makes it work as before.

Why doesn't catching Exception catch RuntimeException?

Catching Exception will catch a RuntimeException

Print ArrayList

This helped to me:

System.out.println(Arrays.toString(codeLangArray.toArray()));

how to delete installed library form react native project

If you want to unlink already installed packages in react native

  1. $ react-native unlink package_name
  2. $ yarn remove package_name (if it is npm then npm uninstall --save)

If you execute 2nd step before 1st step you need to install relevant package back and execute 2nd step

Export data from R to Excel

Another option is the openxlsx-package. It doesn't depend on and can read, edit and write Excel-files. From the description from the package:

openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java

Example usage:

library(openxlsx)

# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')

# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')

Besides these two basic functions, the openxlsx-package has a host of other functions for manipulating Excel-files.

For example, with the writeDataTable-function you can create formatted tables in an Excel-file.

How to Add Incremental Numbers to a New Column Using Pandas

You can also simply set your pandas column as list of id values with length same as of dataframe.

df['New_ID'] = range(880, 880+len(df))

Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

Javascript Audio Play on click

HTML:

<button onclick="play()">Play File</button>
<audio id="audio" src="https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"></audio>

JavaScript:

let play = function(){document.getElementById("audio").play()}

Should you use .htm or .html file extension? What is the difference, and which file is correct?

Same thing.. makes no difference at all... htm was used in the days where only 3 letter extensions were common.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

mysql->SHOW PROCESSLIST;
kill xxxx; 

and then kill which one in sleep. In my case it is 2456.

enter image description here

Remove characters except digits from string using Python?

You can use filter:

filter(lambda x: x.isdigit(), "dasdasd2313dsa")

On python3.0 you have to join this (kinda ugly :( )

''.join(filter(lambda x: x.isdigit(), "dasdasd2313dsa"))

Swift Set to Array

I created a simple extension that gives you an unsorted Array as a property of Set in Swift 4.0.

extension Set {
    var array: [Element] {
        return Array(self)
    }
}

If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.

To use this, just call

let array = set.array

What is the best way to detect a mobile device?

You can use media query to be able to handle it easily.

isMobile = function(){
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");
    return isMobile.matches ? true : false
}

How do I limit the number of returned items?

For some reason I could not get this to work with the proposed answers, but I found another variation, using select, that worked for me:

models.Post.find().sort('-date').limit(10).select('published').exec(function(e, data){
        ...
});

Has the api perhaps changed? I am using version 3.8.19

Need a good hex editor for Linux

wxHexEditor is the only GUI disk editor for linux. to google "wxhexeditor site:archive.getdeb.net" and download the .deb file to install

Sort objects in an array alphabetically on one property of the array

Here is a simple function you can use to sort array of objects through their properties; it doesn't matter if the property is a type of string or integer, it will work.

_x000D_
_x000D_
    var cars = [_x000D_
        {make:"AMC",        model:"Pacer",  year:1978},_x000D_
        {make:"Koenigsegg", model:"CCGT",   year:2011},_x000D_
        {make:"Pagani",     model:"Zonda",  year:2006},_x000D_
    ];_x000D_
_x000D_
    function sortObjectsByProp(objectsArr, prop, ascending = true) {_x000D_
        let objectsHaveProp = objectsArr.every(object => object.hasOwnProperty(prop));_x000D_
        if(objectsHaveProp)    {_x000D_
            let newObjectsArr = objectsArr.slice();_x000D_
            newObjectsArr.sort((a, b) => {_x000D_
                if(isNaN(Number(a[prop])))  {_x000D_
                    let textA = a[prop].toUpperCase(),_x000D_
                        textB = b[prop].toUpperCase();_x000D_
                    if(ascending)   {_x000D_
                        return textA < textB ? -1 : textA > textB ? 1 : 0;_x000D_
                    } else {_x000D_
                        return textB < textA ? -1 : textB > textA ? 1 : 0;_x000D_
                    }_x000D_
                } else {_x000D_
                    return ascending ? a[prop] - b[prop] : b[prop] - a[prop];_x000D_
                }_x000D_
            });_x000D_
            return newObjectsArr;_x000D_
        }_x000D_
        return objectsArr;_x000D_
    }_x000D_
_x000D_
    let sortedByMake = sortObjectsByProp(cars, "make"); // returns ascending order by its make;_x000D_
    let sortedByYear = sortObjectsByProp(cars, "year", false); // returns descending order by its year,since we put false as a third argument;_x000D_
    console.log(sortedByMake);_x000D_
    console.log(sortedByYear);
_x000D_
_x000D_
_x000D_

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

Underline text in UIlabel

I've combined some of provided answers, to create better (at least for my requirements) UILabel subclass, which supports:

  • multiline text with various label bounds (text can be in the middle of label frame, or accurate size)
  • underline
  • strikeout
  • underline/strikeout line offset
  • text alignment
  • different font sizes

https://github.com/GuntisTreulands/UnderLineLabel

SSRS Field Expression to change the background color of the Cell

=IIF(fields!column.value =Condition,"Red","Black")

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])

Similarly,

>>> test[1,:]
array([3, 4])

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

Shell command to sum integers, one per line?

Plain bash one liner

$ cat > /tmp/test
1 
2 
3 
4 
5
^D

$ echo $(( $(cat /tmp/test | tr "\n" "+" ) 0 ))

How to view kafka message

On server where your admin run kafka find kafka-console-consumer.sh by command find . -name kafka-console-consumer.sh then go to that directory and run for read message from your topic

./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning --max-messages 10

note that in topic may be many messages in that case I use --max-messages key

How to check if input is numeric in C++

The problem with the usage of

cin>>number_variable;

is that when you input 123abc value, it will pass and your variable will contain 123.

You can use regex, something like this

double inputNumber()
{
    string str;
    regex regex_pattern("-?[0-9]+.?[0-9]+");
    do
    {
        cout << "Input a positive number: ";
        cin >> str;
    }while(!regex_match(str,regex_pattern));

    return stod(str);
}

Or you can change the regex_pattern to validate anything that you would like.

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The COLLATE keyword specify what kind of character set and rules (order, confrontation rules) you are using for string values.

For example in your case you are using Latin rules with case insensitive (CI) and accent sensitive (AS)

You can refer to this Documentation

Output (echo/print) everything from a PHP Array

I think you are looking for print_r which will print out the array as text. You can't control the formatting though, it's more for debugging. If you want cool formatting you'll need to do it manually.

static constructors in C++? I need to initialize private static objects

How about creating a template to mimic the behavior of C#.

template<class T> class StaticConstructor
{
    bool m_StaticsInitialised = false;

public:
    typedef void (*StaticCallback)(void);

    StaticConstructor(StaticCallback callback)
    {
        if (m_StaticsInitialised)
            return;

        callback();

        m_StaticsInitialised = true;
    }
}

template<class T> bool StaticConstructor<T>::m_StaticsInitialised;

class Test : public StaticConstructor<Test>
{
    static std::vector<char> letters_;

    static void _Test()
    {
        for (char c = 'a'; c <= 'z'; c++)
            letters_.push_back(c);
    }

public:
    Test() : StaticConstructor<Test>(&_Test)
    {
        // non static stuff
    };
};

Using Regular Expressions to Extract a Value in Java

This function collect all matching sequences from string. In this example it takes all email addresses from string.

static final String EMAIL_PATTERN = "[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})";

public List<String> getAllEmails(String message) {      
    List<String> result = null;
    Matcher matcher = Pattern.compile(EMAIL_PATTERN).matcher(message);

    if (matcher.find()) {
        result = new ArrayList<String>();
        result.add(matcher.group());

        while (matcher.find()) {
            result.add(matcher.group());
        }
    }

    return result;
}

For message = "[email protected], <[email protected]>>>> [email protected]" it will create List of 3 elements.

Easiest way to convert month name to month number in JS ? (Jan = 01)

If you don't want an array then how about an object?

var months = {
    'Jan' : '01',
    'Feb' : '02',
    'Mar' : '03',
    'Apr' : '04',
    'May' : '05',
    'Jun' : '06',
    'Jul' : '07',
    'Aug' : '08',
    'Sep' : '09',
    'Oct' : '10',
    'Nov' : '11',
    'Dec' : '12'
}

React fetch data in server before render

I've just stumbled upon this problem too, learning React, and solved it by showing spinner until the data is ready.

    render() {
    if (this.state.data === null) {
        return (
            <div className="MyView">
                <Spinner/>
            </div>
        );
    }
    else {
        return(
            <div className="MyView">
                <ReactJson src={this.state.data}/>
            </div>
        );
    }
}

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

The C# summarized descendant.

More reading: http://blogs.msdn.com/b/nathannesbit/archive/2009/04/20/addrange-and-observablecollection.aspx

public sealed class ObservableCollectionEx<T> : ObservableCollection<T>
{
    #region Ctor

    public ObservableCollectionEx()
    {
    }

    public ObservableCollectionEx(List<T> list) : base(list)
    {
    }

    public ObservableCollectionEx(IEnumerable<T> collection) : base(collection)
    {
    }

    #endregion

    /// <summary> 
    /// Adds the elements of the specified collection to the end of the ObservableCollection(Of T). 
    /// </summary> 
    public void AddRange(
        IEnumerable<T> itemsToAdd,
        ECollectionChangeNotificationMode notificationMode = ECollectionChangeNotificationMode.Add)
    {
        if (itemsToAdd == null)
        {
            throw new ArgumentNullException("itemsToAdd");
        }
        CheckReentrancy();

        if (notificationMode == ECollectionChangeNotificationMode.Reset)
        {
            foreach (var i in itemsToAdd)
            {
                Items.Add(i);
            }

            OnPropertyChanged(new PropertyChangedEventArgs("Count"));
            OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));

            return;
        }

        int startIndex = Count;
        var changedItems = itemsToAdd is List<T> ? (List<T>) itemsToAdd : new List<T>(itemsToAdd);
        foreach (var i in changedItems)
        {
            Items.Add(i);
        }

        OnPropertyChanged(new PropertyChangedEventArgs("Count"));
        OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
        OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, changedItems, startIndex));
    }

    public enum ECollectionChangeNotificationMode
    {
        /// <summary>
        /// Notifies that only a portion of data was changed and supplies the changed items (not supported by some elements,
        /// like CollectionView class).
        /// </summary>
        Add,

        /// <summary>
        /// Notifies that the entire collection was changed, does not supply the changed items (may be inneficient with large
        /// collections as requires the full update even if a small portion of items was added).
        /// </summary>
        Reset
    }
}

XMLHttpRequest (Ajax) Error

The problem is likely to lie with the line:

window.onload = onPageLoad();

By including the brackets you are saying onload should equal the return value of onPageLoad(). For example:

/*Example function*/
function onPageLoad()
{
    return "science";
}
/*Set on load*/
window.onload = onPageLoad()

If you print out the value of window.onload to the console it will be:

science

The solution is remove the brackets:

window.onload = onPageLoad;

So, you're using onPageLoad as a reference to the so-named function.

Finally, in order to get the response value you'll need a readystatechange listener for your XMLHttpRequest object, since it's asynchronous:

xmlDoc = xmlhttp.responseXML;
parser = new DOMParser(); // This code is untested as it doesn't run this far.

Here you add the listener:

xmlHttp.onreadystatechange = function() {
    if(this.readyState == 4) {
        // Do something
    }
}

Is it better to use "is" or "==" for number comparison in Python?

== is what you want, "is" just happens to work on your examples.

Return a value of '1' a referenced cell is empty

You can use:

=IF(ISBLANK(A1),1,0)

but you should be careful what you mean by empty cell. I've been caught out by this before. If you want to know if a cell is truly blank, isblank, as above, will work. Unfortunately, you sometimes also need to know if it just contains no useful data.

The expression:

=IF(ISBLANK(A1),TRUE,(TRIM(A1)=""))

will return true for cells that are either truly blank, or contain nothing but white space.

Here's the results when column A contains varying amounts of spaces, column B contains the length (so you know how many spaces) and column C contains the result of the above expression:

<-A-> <-B-> <-C->
        0   TRUE
        1   TRUE
        2   TRUE
        3   TRUE
        4   TRUE
        5   TRUE
  a     1   FALSE
<-A-> <-B-> <-C->

To return 1 if the cell is blank or white space and 0 otherwise:

=IF(ISBLANK(A1),1,if(TRIM(A1)="",1,0))

will do the trick.

This trick comes in handy when the cell that you're checking is actually the result of an Excel function. Many Excel functions (such as trim) will return an empty string rather than a blank cell.

You can see this in action with a new sheet. Leave cell A1 as-is and set A2 to =trim(a1).

Then set B1 to =isblank(a1) and B2 to isblank(a2). You'll see that the former is true while the latter is false.

How to communicate between Docker containers via "hostname"

Edit: After Docker 1.9, the docker network command (see below https://stackoverflow.com/a/35184695/977939) is the recommended way to achieve this.


My solution is to set up a dnsmasq on the host to have DNS record automatically updated: "A" records have the names of containers and point to the IP addresses of the containers automatically (every 10 sec). The automatic updating script is pasted here:

#!/bin/bash

# 10 seconds interval time by default
INTERVAL=${INTERVAL:-10}

# dnsmasq config directory
DNSMASQ_CONFIG=${DNSMASQ_CONFIG:-.}

# commands used in this script
DOCKER=${DOCKER:-docker}
SLEEP=${SLEEP:-sleep}
TAIL=${TAIL:-tail}

declare -A service_map

while true
do
    changed=false
    while read line
    do
        name=${line##* }
        ip=$(${DOCKER} inspect --format '{{.NetworkSettings.IPAddress}}' $name)
        if [ -z ${service_map[$name]} ] || [ ${service_map[$name]} != $ip ] # IP addr changed
        then
            service_map[$name]=$ip
            # write to file
            echo $name has a new IP Address $ip >&2
            echo "host-record=$name,$ip"  > "${DNSMASQ_CONFIG}/docker-$name"
            changed=true
        fi
    done < <(${DOCKER} ps | ${TAIL} -n +2)

    # a change of IP address occured, restart dnsmasq
    if [ $changed = true ]
    then
        systemctl restart dnsmasq
    fi

    ${SLEEP} $INTERVAL
done

Make sure your dnsmasq service is available on docker0. Then, start your container with --dns HOST_ADDRESS to use this mini dns service.

Reference: http://docs.blowb.org/setup-host/dnsmasq.html

How to: Create trigger for auto update modified date with SQL Server 2008

My approach:

  • define a default constraint on the ModDate column with a value of GETDATE() - this handles the INSERT case

  • have a AFTER UPDATE trigger to update the ModDate column

Something like:

CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
    UPDATE dbo.TimeEntry
    SET ModDate = GETDATE()
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

Use .corr to get the correlation between two columns

changing 'Citable docs per Capita' to numeric before correlation will solve the problem.

    Top15['Citable docs per Capita'] = pd.to_numeric(Top15['Citable docs per Capita'])
    data = Top15[['Citable docs per Capita','Energy Supply per Capita']]
    correlation = data.corr(method='pearson')

here-document gives 'unexpected end of file' error

The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat:

cat -A myfile.sh

Once you see the output from cat -A the solution will be obvious: remove the offending characters.

What is the current directory in a batch file?

In a batch file, %cd% is the most commonly used command for the current directory, although you can set your own variable:

set mypath=%cd%
echo %mypath% (where %mypath% is the current directory that the batch file is sitting in)

So say you were wanting to open Myprog.exe. If it was in the same folder, you would use the command:

start %mypath%\Myprog.exe

That would open Myprog from the current folder.

The other option is to make a directory in C: called AutomatePrograms. Then, you transfer your files to that folder then you can open them using the following command:

start "" "C:\AutomatePrograms\Myprog1.exe"
start "" "C:\AutomatePrograms\Myprog2.exe"
start "" "C:\AutomatePrograms\Myprog3.exe"

Embed YouTube Video with No Ads

If you play the video as a playlist and then single out that video you can get it without ads. Here is what I have done: https://www.youtube.com/v/VIDEO_ID?playlist=VIDEO_ID&autoplay=1&rel=0

adb uninstall failed

Mine was on samsung j7 pro, issue was simple.

j7y17lte:/system $ pm list packages|grep airtel                                                                                                                                                                                            
package:com.samsung.android.airtel.stubapp

j7y17lte:/system $ pm uninstall -k --user 0 com.samsung.android.airtel.stubapp

DO NO-NOT include the word package in the unistall command

Capture keyboardinterrupt in Python without try-except

You can prevent printing a stack trace for KeyboardInterrupt, without try: ... except KeyboardInterrupt: pass (the most obvious and propably "best" solution, but you already know it and asked for something else) by replacing sys.excepthook. Something like

def custom_excepthook(type, value, traceback):
    if type is KeyboardInterrupt:
        return # do nothing
    else:
        sys.__excepthook__(type, value, traceback)

Simplest way to throw an error/exception with a custom message in Swift 2?

In case you don't need to catch the error and you want to immediately stop the application you can use a fatalError: fatalError ("Custom message here")

Build android release apk on Phonegap 3.x CLI

You could try this command, it should build and run the app (so .apk should be created) :

phonegap local run android

What is the difference between Document style and RPC style communication?

In WSDL definition, bindings contain operations, here comes style for each operation.

Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.

  • Advantage:
    • Using this Document style, we can validate SOAP messages against predefined schema. It supports xml datatypes and patterns.
    • loosely coupled.
  • Disadvantage: It is a little bit hard to get understand.

In WSDL types element looks as follows:

<types>
 <xsd:schema>
  <xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace="http://ws.peter.com/"/>
 </xsd:schema>
</types>

The schema is importing from external reference.

RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.

<types/>  
<message name="getHelloWorldAsString">  
<part name="arg0" type="xsd:string"/>  
</message>  
<message name="getHelloWorldAsStringResponse">  
<part name="return" type="xsd:string"/>  
</message>  
  • Advantage: Easy to understand.
  • Disadvantage:
    • we can not validate SOAP messages.
    • tightly coupled

RPC : No types in WSDL
Document: Types section would be available in WSDL

C++: constructor initializer for arrays

You can use C++0x auto keyword together with template specialization on for example a function named boost::make_array() (similar to make_pair()). For the case of where N is either 1 or 2 arguments we can then write variant A as

namespace boost
{
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    return boost::array<T,2> ({{ a }});
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    return boost::array<T,2> ({{ a, b }});
}
}

and variant B as

namespace boost {
/*! Construct Array from @p a. */
template <typename T>
boost::array<T,1> make_array(const T & a)
{
    boost::array<T,1> x;
    x[0] = a;
    return x;
}
/*! Construct Array from @p a, @p b. */
template <typename T>
boost::array<T,2> make_array(const T & a, const T & b)
{
    boost::array<T,2> x;
    x[0] = a;
    x[1] = b;
    return x;
}
}

GCC-4.6 with -std=gnu++0x and -O3 generates the exact same binary code for

auto x = boost::make_array(1,2);

using both A and B as it does for

boost::array<int, 2> x = {{1,2}};

For user defined types (UDT), though, variant B results in an extra copy constructor, which usually slow things down, and should therefore be avoided.

Note that boost::make_array errors when calling it with explicit char array literals as in the following case

auto x = boost::make_array("a","b");

I believe this is a good thing as const char* literals can be deceptive in their use.

Variadic templates, available in GCC since 4.5, can further be used reduce all template specialization boiler-plate code for each N into a single template definition of boost::make_array() defined as

/*! Construct Array from @p a, @p b. */
template <typename T, typename ... R>
boost::array<T,1+sizeof...(R)> make_array(T a, const R & ... b)
{
    return boost::array<T,1+sizeof...(R)>({{ a, b... }});
}

This works pretty much as we expect. The first argument determines boost::array template argument T and all other arguments gets converted into T. For some cases this may undesirable, but I'm not sure how if this is possible to specify using variadic templates.

Perhaps boost::make_array() should go into the Boost Libraries?

How I can check if an object is null in ruby on rails 2?

You can use the simple not flag to validate that. Example

if !@objectname

This will return true if @objectname is nil. You should not use dot operator or a nil value, else it will throw

*** NoMethodError Exception: undefined method `isNil?' for nil:NilClass

An ideal nil check would be like:

!@objectname || @objectname.nil? || @objectname.empty?

How to detect when facebook's FB.init is complete

Actually Facebook has already provided a mechanism to subscribe to authentication events.

In your case you are using "status: true" which means that FB object will request Facebook for user's login status.

FB.init({
    appId  : '<?php echo $conf['fb']['appid']; ?>',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true  // parse XFBML
});

By calling "FB.getLoginStatus()" you are running the same request again.

Instead you could use FB.Event.subscribe to subscribe to auth.statusChange or auth.authResponseChange event BEFORE you call FB.init

FB.Event.subscribe('auth.statusChange', function(response) {
    if(response.status == 'connected') {
        runFbInitCriticalCode();
    }
});

FB.init({
    appId  : '<?php echo $conf['fb']['appid']; ?>',
    status : true, // check login status
    cookie : true, // enable cookies to allow the server to access the session
    xfbml  : true  // parse XFBML
});

Most likely, when using "status: false" you can run any code right after FB.init, because there will be no asynchronous calls.

Getting HTML elements by their attribute names

I think you want to take a look at jQuery since that Javascript library provides a lot of functionality you might want to use in this kind of cases. In your case you could write (or find one on the internet) a hasAttribute method, like so (not tested):

$.fn.hasAttribute = function(tagName, attrName){
  var result = [];
  $.each($(tagName), function(index, value) { 
     var attr = $(this).attr(attrName); 
     if (typeof attr !== 'undefined' && attr !== false)
        result.push($(this));
  });
  return result;
}

Generic type conversion FROM string

Yet another variation. Handles Nullables, as well as situations where the string is null and T is not nullable.

public class TypedProperty<T> : Property where T : IConvertible
{
    public T TypedValue
    {
        get
        {
            if (base.Value == null) return default(T);
            var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
            return (T)Convert.ChangeType(base.Value, type);
        }
        set { base.Value = value.ToString(); }
    }
}

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

I ran into this issue while making REST calls from my app server running in AWS EC2. The following Steps fixed the issue for me.

  1. curl -vs https://your_rest_path
  2. echo | openssl s_client -connect your_domain:443
  3. sudo apt-get install ca-certificates

curl -vs https://your_rest_path will now work!

Python find min max and average of a list (array)

Only a teacher would ask you to do something silly like this. You could provide an expected answer. Or a unique solution, while the rest of the class will be (yawn) the same...

from operator import lt, gt
def ultimate (l,op,c=1,u=0):
    try:
        if op(l[c],l[u]): 
            u = c
        c += 1
        return ultimate(l,op,c,u)
    except IndexError:
        return l[u]
def minimum (l):
    return ultimate(l,lt)
def maximum (l):
    return ultimate(l,gt)

The solution is simple. Use this to set yourself apart from obvious choices.

JSON parsing using Gson for Java

This is simple code to do it, I avoided all checks but this is the main idea.

 public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").getAsString();
    return result;
}

To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.

Convert PDF to image with high resolution

It's actually pretty easy to do with Preview on a mac. All you have to do is open the file in Preview and save-as (or export) a png or jpeg but make sure that you use at least 300 dpi at the bottom of the window to get a high quality image.

Where is Developer Command Prompt for VS2013?

From VS2013 Menu Select "Tools", then Select "External Tools". Enter as below:

  • Title: "VS2013 Native Tools-Command Prompt" would be good
  • Command: C:\Windows\System32\cmd.exe
  • Arguments: /k "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat"
  • Initial Directory: Select as suits your needs.

Click OK. Now you have command prompt access under the Tools Menu.

Cache an HTTP 'Get' service response in AngularJS?

As AngularJS factories are singletons, you can simply store the result of the http request and retrieve it next time your service is injected into something.

angular.module('myApp', ['ngResource']).factory('myService',
  function($resource) {
    var cache = false;
    return {
      query: function() {
        if(!cache) {
          cache = $resource('http://example.com/api').query();
        }
        return cache;
      }
    };
  }
);

How to write a Python module/package?

I created a project to easily initiate a project skeleton from scratch. https://github.com/MacHu-GWU/pygitrepo-project.

And you can create a test project, let's say, learn_creating_py_package.

You can learn what component you should have for different purpose like:

  • create virtualenv
  • install itself
  • run unittest
  • run code coverage
  • build document
  • deploy document
  • run unittest in different python version
  • deploy to PYPI

The advantage of using pygitrepo is that those tedious are automatically created itself and adapt your package_name, project_name, github_account, document host service, windows or macos or linux.

It is a good place to learn develop a python project like a pro.

Hope this could help.

Thank you.

How to update (append to) an href in jquery?

Here is what i tried to do to add parameter in the url which contain the specific character in the url.

jQuery('a[href*="google.com"]').attr('href', function(i,href) {
        //jquery date addition
        var requiredDate = new Date();
        var numberOfDaysToAdd = 60;
        requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd); 
        //var convertedDate  = requiredDate.format('d-M-Y');
        //var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
        //console.log(requiredDate);

        var month   = requiredDate.getMonth()+1;
        var day     = requiredDate.getDate();

        var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
        //

Working Example Click

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

Use Libre Office API Here is an example

libreoffice --headless --convert-to html docx-file-path --outdir html-dir-path

MySQL: How to reset or change the MySQL root password?

I faced problems with ubuntu 18.04 and mysql 5.7, this is the solution

Try restart mysql-server before execution the comands

sudo service mysql restart

MYSQL-SERVER >= 5.7

sudo mysql -uroot -p
USE mysql;
UPDATE user SET authentication_string=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;

MYSQL-SERVER < 5.7

sudo mysql -uroot -p
USE mysql;
UPDATE user SET password=PASSWORD('YOUR_PASSWORD') WHERE User='root';
UPDATE user SET plugin="mysql_native_password";
FLUSH PRIVILEGES;
quit;

How to convert enum names to string in c

I found a C preprocessor trick that is doing the same job without declaring a dedicated array string (Source: http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/c_preprocessor_applications_en).

Sequential enums

Following the invention of Stefan Ram, sequential enums (without explicitely stating the index, e.g. enum {foo=-1, foo1 = 1}) can be realized like this genius trick:

#include <stdio.h>

#define NAMES C(RED)C(GREEN)C(BLUE)
#define C(x) x,
enum color { NAMES TOP };
#undef C

#define C(x) #x,    
const char * const color_name[] = { NAMES };

This gives the following result:

int main( void )  { 
    printf( "The color is %s.\n", color_name[ RED ]);  
    printf( "There are %d colors.\n", TOP ); 
}

The color is RED.
There are 3 colors.

Non-Sequential enums

Since I wanted to map error codes definitions to are array string, so that I can append the raw error definition to the error code (e.g. "The error is 3 (LC_FT_DEVICE_NOT_OPENED)."), I extended the code in that way that you can easily determine the required index for the respective enum values:

#define LOOPN(n,a) LOOP##n(a)
#define LOOPF ,
#define LOOP2(a) a LOOPF a LOOPF
#define LOOP3(a) a LOOPF a LOOPF a LOOPF
#define LOOP4(a) a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP5(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP6(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP7(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP8(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF
#define LOOP9(a) a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF a LOOPF


#define LC_ERRORS_NAMES \
    Cn(LC_RESPONSE_PLUGIN_OK, -10) \
    Cw(8) \
    Cn(LC_RESPONSE_GENERIC_ERROR, -1) \
    Cn(LC_FT_OK, 0) \
    Ci(LC_FT_INVALID_HANDLE) \
    Ci(LC_FT_DEVICE_NOT_FOUND) \
    Ci(LC_FT_DEVICE_NOT_OPENED) \
    Ci(LC_FT_IO_ERROR) \
    Ci(LC_FT_INSUFFICIENT_RESOURCES) \
    Ci(LC_FT_INVALID_PARAMETER) \
    Ci(LC_FT_INVALID_BAUD_RATE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_ERASE) \
    Ci(LC_FT_DEVICE_NOT_OPENED_FOR_WRITE) \
    Ci(LC_FT_FAILED_TO_WRITE_DEVICE) \
    Ci(LC_FT_EEPROM_READ_FAILED) \
    Ci(LC_FT_EEPROM_WRITE_FAILED) \
    Ci(LC_FT_EEPROM_ERASE_FAILED) \
    Ci(LC_FT_EEPROM_NOT_PRESENT) \
    Ci(LC_FT_EEPROM_NOT_PROGRAMMED) \
    Ci(LC_FT_INVALID_ARGS) \
    Ci(LC_FT_NOT_SUPPORTED) \
    Ci(LC_FT_OTHER_ERROR) \
    Ci(LC_FT_DEVICE_LIST_NOT_READY)


#define Cn(x,y) x=y,
#define Ci(x) x,
#define Cw(x)
enum LC_errors { LC_ERRORS_NAMES TOP };
#undef Cn
#undef Ci
#undef Cw
#define Cn(x,y) #x,
#define Ci(x) #x,
#define Cw(x) LOOPN(x,"")
static const char* __LC_errors__strings[] = { LC_ERRORS_NAMES };
static const char** LC_errors__strings = &__LC_errors__strings[10];

In this example, the C preprocessor will generate the following code:

enum LC_errors { LC_RESPONSE_PLUGIN_OK=-10,  LC_RESPONSE_GENERIC_ERROR=-1, LC_FT_OK=0, LC_FT_INVALID_HANDLE, LC_FT_DEVICE_NOT_FOUND, LC_FT_DEVICE_NOT_OPENED, LC_FT_IO_ERROR, LC_FT_INSUFFICIENT_RESOURCES, LC_FT_INVALID_PARAMETER, LC_FT_INVALID_BAUD_RATE, LC_FT_DEVICE_NOT_OPENED_FOR_ERASE, LC_FT_DEVICE_NOT_OPENED_FOR_WRITE, LC_FT_FAILED_TO_WRITE_DEVICE, LC_FT_EEPROM_READ_FAILED, LC_FT_EEPROM_WRITE_FAILED, LC_FT_EEPROM_ERASE_FAILED, LC_FT_EEPROM_NOT_PRESENT, LC_FT_EEPROM_NOT_PROGRAMMED, LC_FT_INVALID_ARGS, LC_FT_NOT_SUPPORTED, LC_FT_OTHER_ERROR, LC_FT_DEVICE_LIST_NOT_READY, TOP };

static const char* __LC_errors__strings[] = { "LC_RESPONSE_PLUGIN_OK", "" , "" , "" , "" , "" , "" , "" , "" "LC_RESPONSE_GENERIC_ERROR", "LC_FT_OK", "LC_FT_INVALID_HANDLE", "LC_FT_DEVICE_NOT_FOUND", "LC_FT_DEVICE_NOT_OPENED", "LC_FT_IO_ERROR", "LC_FT_INSUFFICIENT_RESOURCES", "LC_FT_INVALID_PARAMETER", "LC_FT_INVALID_BAUD_RATE", "LC_FT_DEVICE_NOT_OPENED_FOR_ERASE", "LC_FT_DEVICE_NOT_OPENED_FOR_WRITE", "LC_FT_FAILED_TO_WRITE_DEVICE", "LC_FT_EEPROM_READ_FAILED", "LC_FT_EEPROM_WRITE_FAILED", "LC_FT_EEPROM_ERASE_FAILED", "LC_FT_EEPROM_NOT_PRESENT", "LC_FT_EEPROM_NOT_PROGRAMMED", "LC_FT_INVALID_ARGS", "LC_FT_NOT_SUPPORTED", "LC_FT_OTHER_ERROR", "LC_FT_DEVICE_LIST_NOT_READY", };

This results to the following implementation capabilities:

LC_errors__strings[-1] ==> LC_errors__strings[LC_RESPONSE_GENERIC_ERROR] ==> "LC_RESPONSE_GENERIC_ERROR"

How do I comment on the Windows command line?

: this is one way to comment

As a result:

:: this will also work
:; so will this
:! and this

Above styles work outside codeblocks, otherwise:

REM is another way to comment.

How to ignore ansible SSH authenticity checking?

Ignoring checking is a bad idea as it makes you susceptible to Man-in-the-middle attacks.

I took the freedom to improve nikobelia's answer by only adding each machine's key once and actually setting ok/changed status in Ansible:

- name: Accept EC2 SSH host keys
  connection: local
  become: false
  shell: |
    ssh-keygen -F {{ inventory_hostname }} || 
      ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
  register: known_hosts_script
  changed_when: "'found' not in known_hosts_script.stdout"

However, Ansible starts gathering facts before the script runs, which requires an SSH connection, so we have to either disable this task or manually move it to later:

- name: Example play
  hosts: all
  gather_facts: no  # gather facts AFTER the host key has been accepted instead

  tasks:

  # https://stackoverflow.com/questions/32297456/
  - name: Accept EC2 SSH host keys
    connection: local
    become: false
    shell: |
      ssh-keygen -F {{ inventory_hostname }} ||
        ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts
    register: known_hosts_script
    changed_when: "'found' not in known_hosts_script.stdout"
  
  - name: Gathering Facts
    setup:

One kink I haven't been able to work out is that it marks all as changed even if it only adds a single key. If anyone could contribute a fix that would be great!

How can I add raw data body to an axios request?

The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.

    axios.request({
        method: 'post',
        url: 'http://foo.bar/',
        data: {},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        transformRequest: [(data, header) => {
            data = 'grant_type=client_credentials'
            return data
        }]
    })

Application Installation Failed in Android Studio

Your APK file is missing . So , Clean Project >> Build APK >> Run the project .

In C#, what's the difference between \n and \r\n?

The Difference

There are a few characters which can indicate a new line. The usual ones are these two:

* '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF).
* '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).

Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:

* DOS and Windows

They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).

* Unix (and hence Linux as well)

Unix uses a single '\n' to indicate a new line.

* Mac

Macs use a single '\r'.

Taken from Here

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

.btn is the best way, in modern website, it's not good while using anchor element without href so make the anchor tag to button is better.

Invoke-customs are only supported starting with android 0 --min-api 26

In my case the error was still there, because my system used upgraded Java. If you are using Java 10, modify the compileOptions:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_10
    targetCompatibility JavaVersion.VERSION_1_10

}

Django: multiple models in one template using forms

"I want to hide some of the fields and do some complex validation."

I start with the built-in admin interface.

  1. Build the ModelForm to show the desired fields.

  2. Extend the Form with the validation rules within the form. Usually this is a clean method.

    Be sure this part works reasonably well.

Once this is done, you can move away from the built-in admin interface.

Then you can fool around with multiple, partially related forms on a single web page. This is a bunch of template stuff to present all the forms on a single page.

Then you have to write the view function to read and validated the various form things and do the various object saves().

"Is it a design issue if I break down and hand-code everything?" No, it's just a lot of time for not much benefit.

Send text to specific contact programmatically (whatsapp)

This approach works with WhatsApp Business app as well!

Change package name as sendIntent.setPackage("com.whatsapp.w4b"); for WhatsApp Business.

Great hack Rishabh, thanks a lot, I was looking for this solution since last 3 years.

As per the Rishabh Maurya's answer above, I have implemented this code which is working fine for both text and image sharing on WhatsApp.

Note that in both the cases it opens a whatsapp conversation (if toNumber exists in users whatsapp contact list), but user have to click send button to complete the action. That means it helps in skipping contact selection step.

For text messages

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("text/plain");
startActivity(sendIntent);

For sharing images

String toNumber = "+91 98765 43210"; // contains spaces.
toNumber = toNumber.replace("+", "").replace(" ", "");

Intent sendIntent = new Intent("android.intent.action.MAIN");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
sendIntent.putExtra("jid", toNumber + "@s.whatsapp.net");
sendIntent.putExtra(Intent.EXTRA_TEXT, message);
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.setPackage("com.whatsapp");
sendIntent.setType("image/png");
context.startActivity(sendIntent);

Enjoy WhatsApping!