Programs & Examples On #Bcd

A binary-coded decimal (BCD) is a method of representing each decimal digit of a number with a fixed number of bits.

Get current url in Angular

You can make use of location service available in @angular/common and via this below code you can get the location or current URL

import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';

@Component({
  selector: 'app-top-nav',
  templateUrl: './top-nav.component.html',
  styleUrls: ['./top-nav.component.scss']
})
export class TopNavComponent implements OnInit {

  route: string;

  constructor(location: Location, router: Router) {
    router.events.subscribe((val) => {
      if(location.path() != ''){
        this.route = location.path();
      } else {
        this.route = 'Home'
      }
    });
  }

  ngOnInit() {
  }

}

here is the reference link from where I have copied thing to get location for my project. https://github.com/elliotforbes/angular-2-admin/blob/master/src/app/common/top-nav/top-nav.component.ts

Kubernetes Pod fails with CrashLoopBackOff

Pod is not started due to problem coming after initialization of POD.

Check and use command to get docker container of pod

docker ps -a | grep private-reg

Output will be information of docker container with id.

See docker logs:

docker logs -f <container id>

Python Pandas iterate over rows and access column names

This was not as straightforward as I would have hoped. You need to use enumerate to keep track of how many columns you have. Then use that counter to look up the name of the column. The accepted answer does not show you how to access the column names dynamically.

for row in df.itertuples(index=False, name=None):
    for k,v in enumerate(row):
        print("column: {0}".format(df.columns.values[k]))
        print("value: {0}".format(v)

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

In my case I got this error when trying to make Proguard + Spring Boot 2 work.

Adding -dontusemixedcaseclassnames to proguard.conf fixes it.

How to embed new Youtube's live video permanent URL?

Have you tried plugin called " Youtube Live Stream Auto Embed"

Its seems to be working. Check it once.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.

I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.

.includes() not working in Internet Explorer

It works for me:

function stringIncludes(a, b) {
      return a.indexOf(b) !== -1;
}

How do I turn off the mysql password validation?

On some installations, you cannot execute this command until you have reset the root password. You cannot reset the root password, until you execute this command. Classic Catch-22.

One solution not mention by other responders is to temporarily disable the plugin via mysql configuration. In any my.cnf, in the [mysqld] section, add:

skip-validate_password=1

and restart the server. Change the password, and set the value back to 0, and restart again.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AllowAllS3ActionsInUserFolder",
            "Effect": "Allow",
            "Action": [
                "s3:*"
            ],
            "Resource": [
                "arn:aws:s3:::your_bucket_name",
                "arn:aws:s3:::your_bucket_name/*"
            ]
        }
    ]
}

Adding both "arn:aws:s3:::your_bucket_name" and "arn:aws:s3:::your_bucket_name/*" to policy congiguration fixed the issue for me.

Connecting to Microsoft SQL server using Python

Try using pytds, it works throughout more complexity environment than pyodbc and more easier to setup.

I made it work on Ubuntu 18.04

Ref: https://github.com/denisenkom/pytds

Example code in documentation:

import pytds
with pytds.connect('server', 'database', 'user', 'password') as conn:
    with conn.cursor() as cur:
        cur.execute("select 1")
        cur.fetchall()

How to create a DataFrame of random integers with Pandas?

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .


Demo -

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which produces:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

How to printf a 64-bit integer as hex?

Edit: Use printf("val = 0x%" PRIx64 "\n", val); instead.

Try printf("val = 0x%llx\n", val);. See the printf manpage:

ll (ell-ell). A following integer conversion corresponds to a long long int or unsigned long long int argument, or a following n conversion corresponds to a pointer to a long long int argument.

Edit: Even better is what @M_Oehm wrote: There is a specific macro for that, because unit64_t is not always a unsigned long long: PRIx64 see also this stackoverflow answer

Remove Duplicates from range of cells in excel vba

If you got only one column in the range to clean, just add "(1)" to the end. It indicates in wich column of the range Excel will remove the duplicates. Something like:

 Sub norepeat()

    Range("C8:C16").RemoveDuplicates (1)

End Sub

Regards

Print "\n" or newline characters as part of the output on terminal

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'

How to select all columns, except one column in pandas?

When the columns are not a MultiIndex, df.columns is just an array of column names so you can do:

df.loc[:, df.columns != 'b']

          a         c         d
0  0.561196  0.013768  0.772827
1  0.882641  0.615396  0.075381
2  0.368824  0.651378  0.397203
3  0.788730  0.568099  0.869127

Why does git status show branch is up-to-date when changes exist upstream?

This is because your local repo hasn't checked in with the upstream remotes. To have this work as you're expecting it to, use git fetch then run a git status again.

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

How to scanf only integer?

Try using the following pattern in scanf. It will read until the end of the line:

scanf("%d\n", &n)

You won't need the getchar() inside the loop since scanf will read the whole line. The floats won't match the scanf pattern and the prompt will ask for an integer again.

Multipart File upload Spring Boot

@RequestBody MultipartFile[] submissions

should be

@RequestParam("file") MultipartFile[] submissions

The files are not the request body, they are part of it and there is no built-in HttpMessageConverter that can convert the request to an array of MultiPartFile.

You can also replace HttpServletRequest with MultipartHttpServletRequest, which gives you access to the headers of the individual parts.

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

For those using Microsoft products with a web.config file:

Merge this with your web.config.

To allow on any domain replace value="domain" with value="*"

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.webserver>
    <httpprotocol>
      <customheaders>
        <add name="Access-Control-Allow-Origin" value="domain" />
      </customheaders>
    </httpprotocol>
  </system.webserver>
</configuration>

If you don't have permission to edit web.config, then add this line in your server-side code.

Response.AppendHeader("Access-Control-Allow-Origin", "domain");

How to get a specific column value from a DataTable in c#

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);

Oracle query to identify columns having special characters

I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.

Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition

SELECT * FROM test WHERE REGEXP_LIKE(sampletext,  '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

Controller not a function, got undefined, while defining controllers globally

I got this problem because I had wrapped a controller-definition file in a closure:

(function() {
   ...stuff...
});

But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:

(function() {
   ...stuff...
})();

Note the () at the end.

How to download image from url

Depending whether or not you know the image format, here are ways you can do it :

Download Image to a file, knowing the image format

using (WebClient webClient = new WebClient()) 
{
   webClient.DownloadFile("http://yoururl.com/image.png", "image.png") ; 
}

Download Image to a file without knowing the image format

You can use Image.FromStream to load any kind of usual bitmaps (jpg, png, bmp, gif, ... ), it will detect automaticaly the file type and you don't even need to check the url extension (which is not a very good practice). E.g:

using (WebClient webClient = new WebClient()) 
{
    byte [] data = webClient.DownloadData("https://fbcdn-sphotos-h-a.akamaihd.net/hphotos-ak-xpf1/v/t34.0-12/10555140_10201501435212873_1318258071_n.jpg?oh=97ebc03895b7acee9aebbde7d6b002bf&oe=53C9ABB0&__gda__=1405685729_110e04e71d9");

   using (MemoryStream mem = new MemoryStream(data)) 
   {
       using (var yourImage = Image.FromStream(mem)) 
       { 
          // If you want it as Png
           yourImage.Save("path_to_your_file.png", ImageFormat.Png) ; 

          // If you want it as Jpeg
           yourImage.Save("path_to_your_file.jpg", ImageFormat.Jpeg) ; 
       }
   } 

}

Note : ArgumentException may be thrown by Image.FromStream if the downloaded content is not a known image type.

Check this reference on MSDN to find all format available. Here are reference to WebClient and Bitmap.

Find elements inside forms and iframe using Java and Selenium WebDriver

When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe

You can do it using:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

In case if your frameId is dynamic, and you only have one iframe, you can use something like:

driver.switchTo().frame(driver.findElement(By.tagName("iframe")));

How to Batch Rename Files in a macOS Terminal?

Using mmv

mmv '*_*_*' '#1_#3' *.png

Finding index of character in Swift String

You can also find indexes of a character in a single string like this,

extension String {

  func indexes(of character: String) -> [Int] {

    precondition(character.count == 1, "Must be single character")

    return self.enumerated().reduce([]) { partial, element  in
      if String(element.element) == character {
        return partial + [element.offset]
      }
      return partial
    }
  }

}

Which gives the result in [String.Distance] ie. [Int], like

"apple".indexes(of: "p") // [1, 2]
"element".indexes(of: "e") // [0, 2, 4]
"swift".indexes(of: "j") // []

How to create XML file with specific structure in Java

Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

How to generate unique ID with node.js

More easy and without addition modules

Math.random().toString(26).slice(2)

How to set up datasource with Spring for HikariCP?

May this also can help using configuration file like java class way.

@Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfig {
    @Autowired
    JdbcConfigProperties jdbc;


    @Bean(name = "hikariDataSource")
    public DataSource hikariDataSource() {
        HikariConfig config = new HikariConfig();
        HikariDataSource dataSource;

        config.setJdbcUrl(jdbc.getUrl());
        config.setUsername(jdbc.getUser());
        config.setPassword(jdbc.getPassword());
        // optional: Property setting depends on database vendor
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        dataSource = new HikariDataSource(config);

        return dataSource;
    }
}

How to use it:

@Component
public class Car implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(AptSommering.class);


    @Autowired
    @Qualifier("hikariDataSource")
    private DataSource hikariDataSource;


}

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

Setup:

My OS windows 8 64bit
Eclipse version Standard/SDK Kepler Service Release 2
My JDK is jdk-8u5-windows-i586
My JRE is jre-8u5-windows-i586

This how I overcome my error.

At the very first my Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") also didn't work. Then I login to this website and downloaded the UCanAccess 2.0.8 zip (as Mr.Gord Thompson said) file and unzip it.

Then you will also able to find these *.jar files in that unzip folder:

ucanaccess-2.0.8.jar
commons-lang-2.6.jar
commons-logging-1.1.1.jar
hsqldb.jar
jackcess-2.0.4.jar

Then what I did was I copied all these 5 files and paste them in these 2 locations:

C:\Program Files (x86)\eclipse\lib
C:\Program Files (x86)\eclipse\lib\ext

(I did that funny thing becoz I was unable to import these libraries to my project)

Then I reopen the eclipse with my project.then I see all that *.jar files in my project's JRE System Library folder.

Finally my code works.

public static void main(String[] args) 
{

    try
    {

        Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\Hasith\\Documents\\JavaDatabase1.mdb");
        Statement stment = conn.createStatement();
        String qry = "SELECT * FROM Table1";

        ResultSet rs = stment.executeQuery(qry);
        while(rs.next())
        {
            String id    = rs.getString("ID") ;
            String fname = rs.getString("Nama");

            System.out.println(id + fname);
        }
    }
    catch(Exception err)
    {
        System.out.println(err);
    }


    //System.out.println("Hasith Sithila");

}

LINQ select one field from list of DTO objects to array

This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.

var mySkus = myLines.Select(x => x.Sku);

Or if you want it as an Array just do...

var mySkus = myLines.Select(x => x.Sku).ToArray();

Insert multiple lines into a file after specified pattern using shell script

sed '/^cdef$/r'<(
    echo "line1"
    echo "line2"
    echo "line3"
    echo "line4"
) -i -- input.txt

Object of class mysqli_result could not be converted to string in

Before using the $result variable, you should use $row = mysqli_fetch_array($result) or mysqli_fetch_assoc() functions.

Like this:

$row = mysqli_fetch_array($result);

and use the $row array as you need.

Locking pattern for proper use of .NET MemoryCache

Console example of MemoryCache, "How to save/get simple class objects"

Output after launching and pressing Any key except Esc :

Saving to cache!
Getting from cache!
Some1
Some2

    class Some
    {
        public String text { get; set; }

        public Some(String text)
        {
            this.text = text;
        }

        public override string ToString()
        {
            return text;
        }
    }

    public static MemoryCache cache = new MemoryCache("cache");

    public static string cache_name = "mycache";

    static void Main(string[] args)
    {

        Some some1 = new Some("some1");
        Some some2 = new Some("some2");

        List<Some> list = new List<Some>();
        list.Add(some1);
        list.Add(some2);

        do {

            if (cache.Contains(cache_name))
            {
                Console.WriteLine("Getting from cache!");
                List<Some> list_c = cache.Get(cache_name) as List<Some>;
                foreach (Some s in list_c) Console.WriteLine(s);
            }
            else
            {
                Console.WriteLine("Saving to cache!");
                cache.Set(cache_name, list, DateTime.Now.AddMinutes(10));                   
            }

        } while (Console.ReadKey(true).Key != ConsoleKey.Escape);

    }

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

How to deal with SettingWithCopyWarning in Pandas

You could avoid the whole problem like this, I believe:

return (
    pd.read_csv(StringIO(str_of_all), sep=',', names=list('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefg')) #dtype={'A': object, 'B': object, 'C': np.float64}
    .rename(columns={'A':'STK', 'B':'TOpen', 'C':'TPCLOSE', 'D':'TPrice', 'E':'THigh', 'F':'TLow', 'I':'TVol', 'J':'TAmt', 'e':'TDate', 'f':'TTime'}, inplace=True)
    .ix[:,[0,3,2,1,4,5,8,9,30,31]]
    .assign(
        TClose=lambda df: df['TPrice'],
        RT=lambda df: 100 * (df['TPrice']/quote_df['TPCLOSE'] - 1),
        TVol=lambda df: df['TVol']/TVOL_SCALE,
        TAmt=lambda df: df['TAmt']/TAMT_SCALE,
        STK_ID=lambda df: df['STK'].str.slice(13,19),
        STK_Name=lambda df: df['STK'].str.slice(21,30)#.decode('gb2312'),
        TDate=lambda df: df.TDate.map(lambda x: x[0:4]+x[5:7]+x[8:10]),
    )
)

Using Assign. From the documentation: Assign new columns to a DataFrame, returning a new object (a copy) with all the original columns in addition to the new ones.

See Tom Augspurger's article on method chaining in pandas: https://tomaugspurger.github.io/method-chaining

git status shows fatal: bad object HEAD

This happened because by mistake I removed some core file of GIT. Try this its worked for me.

re-initialize git

git init

fetch data from remote

git fetch

Now check all your changes and git status by

git status

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Python convert tuple to string

Use str.join:

>>> tup = ('a', 'b', 'c', 'd', 'g', 'x', 'r', 'e')
>>> ''.join(tup)
'abcdgxre'
>>>
>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

>>>

Failure [INSTALL_FAILED_INVALID_APK]

Uninstall the previous version if installed already and try again.It might help

Select query to remove non-numeric characters

You can use stuff and patindex.

stuff(Col, 1, patindex('%[0-9]%', Col)-1, '')

SQL Fiddle

Pretty Printing a pandas dataframe

You can use prettytable to render the table as text. The trick is to convert the data_frame to an in-memory csv file and have prettytable read it. Here's the code:

from StringIO import StringIO
import prettytable    

output = StringIO()
data_frame.to_csv(output)
output.seek(0)
pt = prettytable.from_csv(output)
print pt

Loop through columns and add string lengths as new columns

You can use lapply to pass each column to str_length, then cbind it to your original data.frame...

library(stringr)

out <- lapply( df , str_length )    
df <- cbind( df , out )

#     col1     col2 col1 col2
#1     abc adf qqwe    3    8
#2    abcd        d    4    1
#3       a        e    1    1
#4 abcdefg        f    7    1

How to trim a string after a specific character in java

Use regex:

result = result.replaceAll("\n.*", "");

replaceAll() uses regex to find its target, which I have replaced with "nothing" - effectively deleting the target.

The target I've specified by the regex \n.* means "the newline char and everything after"

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

Cut Java String at a number of character

You can use String#substring()

if(str != null && str.length() > 8) {
    return str.substring(0, 8) + "...";
} else {
    return str;
}

You could however make a function where you pass the maximum number of characters that can be displayed. The ellipsis would then cut in only if the width specified isn't enough for the string.

public String getShortString(String input, int width) {
  if(str != null && str.length() > width) {
      return str.substring(0, width - 3) + "...";
  } else {
      return str;
  }
}

// abcdefgh...
System.out.println(getShortString("abcdefghijklmnopqrstuvwxyz", 11));

// abcdefghijk
System.out.println(getShortString("abcdefghijk", 11)); // no need to trim

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

Get values from an object in JavaScript

If you want to do this in a single line, try:

Object.keys(a).map(function(key){return a[key]})

How to get the last character of a string in a shell?

Every answer so far implies the word "shell" in the question equates to Bash.

This is how one could do that in a standard Bourne shell:

printf $str | tail -c 1

Java ByteBuffer to String

Just wanted to point out, it's not safe to assume ByteBuffer.array() will always work.

byte[] bytes;
if(buffer.hasArray()) {
    bytes = buffer.array();
} else {
    bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
}
String v = new String(bytes, charset);

Usually buffer.hasArray() will always be true or false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need. But the rest of the answers may not work with a ByteBuffer that's been created through ByteBuffer.allocateDirect().

How to search and replace text in a file?

As Jack Aidley had posted and J.F. Sebastian pointed out, this code will not work:

 # Read in the file
filedata = None
with file = open('file.txt', 'r') :
  filedata = file.read()

# Replace the target string
filedata.replace('ram', 'abcd')

# Write the file out again
with file = open('file.txt', 'w') :
  file.write(filedata)`

But this code WILL work (I've tested it):

f = open(filein,'r')
filedata = f.read()
f.close()

newdata = filedata.replace("old data","new data")

f = open(fileout,'w')
f.write(newdata)
f.close()

Using this method, filein and fileout can be the same file, because Python 3.3 will overwrite the file upon opening for write.

Fit Image into PictureBox

Imam Mahdi aj SizeMode Change in properties

You can use the properties section

Reading file line by line (with space) in Unix Shell scripting - Issue

Try this,

IFS=''
while read line
do
    echo $line
done < file.txt

EDIT:

From man bash

IFS - The Internal Field Separator that is used for word
splitting after expansion and to split lines into words
with  the  read  builtin  command. The default value is
``<space><tab><newline>''

How to replace a substring of a string

You are probably not assigning it after doing the replacement or replacing the wrong thing. Try :

String haystack = "abcd=0; efgh=1";
String result = haystack.replaceAll("abcd","dddd");

How to copy a char array in C?

You cannot assign arrays to copy them. How you can copy the contents of one into another depends on multiple factors:

For char arrays, if you know the source array is null terminated and destination array is large enough for the string in the source array, including the null terminator, use strcpy():

#include <string.h>

char array1[18] = "abcdefg";
char array2[18];

...

strcpy(array2, array1);

If you do not know if the destination array is large enough, but the source is a C string, and you want the destination to be a proper C string, use snprinf():

#include <stdio.h>

char array1[] = "a longer string that might not fit";
char array2[18];

...

snprintf(array2, sizeof array2, "%s", array1);

If the source array is not necessarily null terminated, but you know both arrays have the same size, you can use memcpy:

#include <string.h>

char array1[28] = "a non null terminated string";
char array2[28];

...

memcpy(array2, array1, sizeof array2);

How to convert QString to int?

Use .toInt() for int .toFloat() for float and .toDouble() for double

toInt();

How do you Encrypt and Decrypt a PHP String?

These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:

function encryptString($plaintext, $password, $encoding = null) {
    $iv = openssl_random_pseudo_bytes(16);
    $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
    return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}

function decryptString($ciphertext, $password, $encoding = null) {
    $ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
    if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
    return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}

Usage:

$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");

regular expression for finding 'href' value of a <a> link

Try this regex:

"href\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))"

You will get more help from discussions over:

Regular expression to extract URL from an HTML link

and

Regex to get the link in href. [asp.net]

Hope its helpful.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

phpmailer - The following SMTP Error: Data not accepted

I was using just

$mail->Body    = $message;

and for some sumbited forms the PHP was returning the error:

SMTP Error: data not accepted.SMTP server error: DATA END command failed Detail: This message was classified as SPAM and may not be delivered SMTP code: 550

I got it fixed adding this code after $mail->Body=$message :

$mail->MsgHTML = $message;
$mail->AltBody = $message;

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

Remove the last three characters from a string

The new C# 8.0 range operator can be a great shortcut to achieve this.

Example #1 (to answer the question):

string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd

Example #2 (to show you how awesome range operators are):

string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98

How can I check if character in a string is a letter? (Python)

data = "abcdefg hi j 12345"

digits_count = 0
letters_count = 0
others_count = 0

for i in userinput:

    if i.isdigit():
        digits_count += 1 
    elif i.isalpha():
        letters_count += 1
    else:
        others_count += 1

print("Result:")        
print("Letters=", letters_count)
print("Digits=", digits_count)

Output:

Please Enter Letters with Numbers:
abcdefg hi j 12345
Result:
Letters = 10
Digits = 5

By using str.isalpha() you can check if it is a letter.

Remove final character from string

Simple:

st =  "abcdefghij"
st = st[:-1]

There is also another way that shows how it is done with steps:

list1 = "abcdefghij"
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

This is also a way with user input:

list1 = input ("Enter :")
list2 = list(list1)
print(list2)
list3 = list2[:-1]
print(list3)

To make it take away the last word in a list:

list1 = input("Enter :")
list2 = list1.split()
print(list2)
list3 = list2[:-1]
print(list3)

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

Selecting/excluding sets of columns in pandas

You just need to convert your set to a list

import pandas as pd
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
my_cols = set(df.columns)
my_cols.remove('B')
my_cols.remove('D')
my_cols = list(my_cols)
df2 = df[my_cols]

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

Moving x-axis to the top of a plot in matplotlib

tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)

Heatmap in matplotlib with pcolor?

This is late, but here is my python implementation of the flowingdata NBA heatmap.

updated:1/4/2014: thanks everyone

# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# ------------------------------------------------------------------------
# Filename   : heatmap.py
# Date       : 2013-04-19
# Updated    : 2014-01-04
# Author     : @LotzJoe >> Joe Lotz
# Description: My attempt at reproducing the FlowingData graphic in Python
# Source     : http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/
#
# Other Links:
#     http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor
#
# ------------------------------------------------------------------------

import matplotlib.pyplot as plt
import pandas as pd
from urllib2 import urlopen
import numpy as np
%pylab inline

page = urlopen("http://datasets.flowingdata.com/ppg2008.csv")
nba = pd.read_csv(page, index_col=0)

# Normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())

# Sort data according to Points, lowest to highest
# This was just a design choice made by Yau
# inplace=False (default) ->thanks SO user d1337
nba_sort = nba_norm.sort('PTS', ascending=True)

nba_sort['PTS'].head(10)

# Plot it out
fig, ax = plt.subplots()
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)

# Format
fig = plt.gcf()
fig.set_size_inches(8, 11)

# turn off the frame
ax.set_frame_on(False)

# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(nba_sort.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(nba_sort.shape[1]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

# Set the labels

# label source:https://en.wikipedia.org/wiki/Basketball_statistics
labels = [
    'Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 'Free throws attempts', 'Free throws percentage',
    'Three-pointers made', 'Three-point attempt', 'Three-point percentage', 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']

# note I could have used nba_sort.columns but made "labels" instead
ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(nba_sort.index, minor=False)

# rotate the
plt.xticks(rotation=90)

ax.grid(False)

# Turn off all the ticks
ax = plt.gca()

for t in ax.xaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False
for t in ax.yaxis.get_major_ticks():
    t.tick1On = False
    t.tick2On = False

The output looks like this: flowingdata-like nba heatmap

There's an ipython notebook with all this code here. I've learned a lot from 'overflow so hopefully someone will find this useful.

Best /Fastest way to read an Excel Sheet into a DataTable?

I have always used OLEDB for this, something like...

    Dim sSheetName As String
    Dim sConnection As String
    Dim dtTablesList As DataTable
    Dim oleExcelCommand As OleDbCommand
    Dim oleExcelReader As OleDbDataReader
    Dim oleExcelConnection As OleDbConnection

    sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""

    oleExcelConnection = New OleDbConnection(sConnection)
    oleExcelConnection.Open()

    dtTablesList = oleExcelConnection.GetSchema("Tables")

    If dtTablesList.Rows.Count > 0 Then
        sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
    End If

    dtTablesList.Clear()
    dtTablesList.Dispose()

    If sSheetName <> "" Then

        oleExcelCommand = oleExcelConnection.CreateCommand()
        oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
        oleExcelCommand.CommandType = CommandType.Text

        oleExcelReader = oleExcelCommand.ExecuteReader

        nOutputRow = 0

        While oleExcelReader.Read

        End While

        oleExcelReader.Close()

    End If

    oleExcelConnection.Close()

The ACE.OLEDB provider will read both .xls and .xlsx files and I have always found the speed quite good.

How to remove element from ArrayList by checking its value?

Snippet to remove a element from any arraylist based on the matching condition is as follows:

List<String> nameList = new ArrayList<>();
        nameList.add("Arafath");
        nameList.add("Anjani");
        nameList.add("Rakesh");

Iterator<String> myItr = nameList.iterator();

    while (myItr.hasNext()) {
        String name = myItr.next();
        System.out.println("Next name is: " + name);
        if (name.equalsIgnoreCase("rakesh")) {
            myItr.remove();
        }
    }

String contains - ignore case

Try this

public static void main(String[] args)
{

    String original = "ABCDEFGHIJKLMNOPQ";
    String tobeChecked = "GHi";

    System.out.println(containsString(original, tobeChecked, true));        
    System.out.println(containsString(original, tobeChecked, false));

}

public static boolean containsString(String original, String tobeChecked, boolean caseSensitive)
{
    if (caseSensitive)
    {
        return original.contains(tobeChecked);

    }
    else
    {
        return original.toLowerCase().contains(tobeChecked.toLowerCase());
    }

}

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

List of all unique characters in a string?

The simplest solution is probably:

In [10]: ''.join(set('aaabcabccd'))
Out[10]: 'acbd'

Note that this doesn't guarantee the order in which the letters appear in the output, even though the example might suggest otherwise.

You refer to the output as a "list". If a list is what you really want, replace ''.join with list:

In [1]: list(set('aaabcabccd'))
Out[1]: ['a', 'c', 'b', 'd']

As far as performance goes, worrying about it at this stage sounds like premature optimization.

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

Adding image inside table cell in HTML

Try using "/" instead of "\" for the path to your image. Some comments here seem to come from people that do not understand some of us are simply learning web development which in many cases is best done locally. So instead of using src=C:\Pics\H.gif use src="C:/Pics/H.gif" for an absolute path or just src="Pics/H.gif" for a relative path if your Pics are in a sub-directory of your html page's location). Note also, it is good practice to surround your path with quotes. otherwise you will have problems with paths that include spaces and other odd characters.

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

How to Populate a DataTable from a Stored Procedure

You can use a SqlDataAdapter:

    SqlDataAdapter adapter = new SqlDataAdapter();
    SqlCommand cmd = new SqlCommand("usp_GetABCD", sqlcon);
    cmd.CommandType = CommandType.StoredProcedure;
    adapter.SelectCommand = cmd;
    DataTable dt = new DataTable();
    adapter.Fill(dt);

Declare a constant array

There is no such thing as array constant in Go.

Quoting from the Go Language Specification: Constants:

There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.

A Constant expression (which is used to initialize a constant) may contain only constant operands and are evaluated at compile time.

The specification lists the different types of constants. Note that you can create and initialize constants with constant expressions of types having one of the allowed types as the underlying type. For example this is valid:

func main() {
    type Myint int
    const i1 Myint = 1
    const i2 = Myint(2)
    fmt.Printf("%T %v\n", i1, i1)
    fmt.Printf("%T %v\n", i2, i2)
}

Output (try it on the Go Playground):

main.Myint 1
main.Myint 2

If you need an array, it can only be a variable, but not a constant.

I recommend this great blog article about constants: Constants

Windows service with timer

You need to put your main code on the OnStart method.

This other SO answer of mine might help.

You will need to put some code to enable debugging within visual-studio while maintaining your application valid as a windows-service. This other SO thread cover the issue of debugging a windows-service.

EDIT:

Please see also the documentation available here for the OnStart method at the MSDN where one can read this:

Do not use the constructor to perform processing that should be in OnStart. Use OnStart to handle all initialization of your service. The constructor is called when the application's executable runs, not when the service runs. The executable runs before OnStart. When you continue, for example, the constructor is not called again because the SCM already holds the object in memory. If OnStop releases resources allocated in the constructor rather than in OnStart, the needed resources would not be created again the second time the service is called.

Why do we assign a parent reference to the child object in Java?

Let's say you'd like to have an array of instances of Parent class, and a set of child classes Child1, Child2, Child3 extending Parent. There're situations when you're only interested with the parent class implementation, which is more general, and do not care about more specific stuff introduced by child classes.

Python Brute Force algorithm

Try this:

import os
import sys

Zeichen=["a","b","c","d","e","f","g","h"­,"i","j","k","l","m","n","o","p","q­","r","s","­;t","u","v","w","x","y","z"]
def start(): input("Enter to start")
def Gen(stellen): if stellen==1: for i in Zeichen: print(i) elif stellen==2: for i in Zeichen:    for r in Zeichen: print(i+r) elif stellen==3: for i in Zeichen: for r in Zeichen: for t in Zeichen:     print(i+r+t) elif stellen==4: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in Zeichen:    print(i+r+t+u) elif stellen==5: for i in Zeichen: for r in Zeichen: for t in Zeichen: for u in    Zeichen: for o in Zeichen: print(i+r+t+u+o) else: print("done")

#*********************
start()
Gen(1)
Gen(2)
Gen(3)
Gen(4)
Gen(5)

You have not concluded your merge (MERGE_HEAD exists)

OK. The problem is your previous pull failed to merge automatically and went to conflict state. And the conflict wasn't resolved properly before the next pull.

  1. Undo the merge and pull again.

    To undo a merge:

    git merge --abort [Since git version 1.7.4]

    git reset --merge [prior git versions]

  2. Resolve the conflict.

  3. Don't forget to add and commit the merge.

  4. git pull now should work fine.

Python: convert string to byte array

An alternative to get a byte array is to encode the string in ascii: b=s.encode('ascii').

Decoding a Base64 string in Java

If you don't want to use apache, you can use Java8:

byte[] decodedBytes = Base64.getDecoder().decode("YWJjZGVmZw=="); 
System.out.println(new String(decodedBytes) + "\n");

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

If you are using eclipse, you should modify the context.xml, from the server project created in your eclipse package explorer. When using tomcat in eclipse it is the only one valid, the others are ignored or overwriten

Find if value in column A contains value from column B?

You can use VLOOKUP, but this requires a wrapper function to return True or False. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.

Fill down this formula in column K next to the existing values in column I (from I1 to I2691):

=COUNTIF(<entire column E range>,<single column I value>)>0
=COUNTIF($E$1:$E$99504,$I1)>0

You can also use MATCH:

=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))
=NOT(ISNA(MATCH($I1,$E$1:$E$99504,0)))

bitwise XOR of hex numbers in python

For performance purpose, here's a little code to benchmark these two alternatives:

#!/bin/python

def hexxorA(a, b):
    if len(a) > len(b):
        return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a[:len(b)], b)])
    else:
        return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b[:len(a)])])

def hexxorB(a, b):
    if len(a) > len(b):
        return '%x' % (int(a[:len(b)],16)^int(b,16))
    else:
        return '%x' % (int(a,16)^int(b[:len(a)],16))

def testA():
    strstr = hexxorA("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
    if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
        raise KeyError
    return strstr

def testB():
    strstr = hexxorB("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")
    if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):
        raise KeyError
    return strstr

if __name__ == '__main__':
    import timeit
    print("Time-it 100k iterations :")
    print("\thexxorA: ", end='')
    print(timeit.timeit("testA()", setup="from __main__ import testA", number=100000), end='s\n')
    print("\thexxorB: ", end='')
    print(timeit.timeit("testB()", setup="from __main__ import testB", number=100000), end='s\n')

Here are the results :

Time-it 100k iterations :
    hexxorA: 8.139988073991844s
    hexxorB: 0.240523161992314s

Seems like '%x' % (int(a,16)^int(b,16)) is faster then the zip version.

How do I convert a number to a letter in Java?

Personally, I prefer

return "ABCDEFGHIJKLMNOPQRSTUVWXYZ".substring(i, i+1);

which shares the backing char[]. Alternately, I think the next-most-readable approach is

return Character.toString((char) (i + 'A'));

which doesn't depend on remembering ASCII tables. It doesn't do validation, but if you want to, I'd prefer to write

char c = (char) (i + 'A');
return Character.isUpperCase(c) ? Character.toString(c) : null;

just to make it obvious that you're checking that it's an alphabetic character.

Sending HTTP Post request with SOAP action using org.apache.http

The soapAction must passed as a http-header parameter - when used, it's not part of the http-body/payload.

Look here for an example with apache httpclient: http://svn.apache.org/repos/asf/httpcomponents/oac.hc3x/trunk/src/examples/PostSOAP.java

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

How to take column-slices of dataframe in pandas

Here's how you could use different methods to do selective column slicing, including selective label based, index based and the selective ranges based column slicing.

In [37]: import pandas as pd    
In [38]: import numpy as np
In [43]: df = pd.DataFrame(np.random.rand(4,7), columns = list('abcdefg'))

In [44]: df
Out[44]: 
          a         b         c         d         e         f         g
0  0.409038  0.745497  0.890767  0.945890  0.014655  0.458070  0.786633
1  0.570642  0.181552  0.794599  0.036340  0.907011  0.655237  0.735268
2  0.568440  0.501638  0.186635  0.441445  0.703312  0.187447  0.604305
3  0.679125  0.642817  0.697628  0.391686  0.698381  0.936899  0.101806

In [45]: df.loc[:, ["a", "b", "c"]] ## label based selective column slicing 
Out[45]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

In [46]: df.loc[:, "a":"c"] ## label based column ranges slicing 
Out[46]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

In [47]: df.iloc[:, 0:3] ## index based column ranges slicing 
Out[47]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

### with 2 different column ranges, index based slicing: 
In [49]: df[df.columns[0:1].tolist() + df.columns[1:3].tolist()]
Out[49]: 
          a         b         c
0  0.409038  0.745497  0.890767
1  0.570642  0.181552  0.794599
2  0.568440  0.501638  0.186635
3  0.679125  0.642817  0.697628

How to sort an array based on the length of each element?

If you want to preserve the order of the element with the same length as the original array, use bubble sort.

Input = ["ab","cdc","abcd","de"];

Output  = ["ab","cd","cdc","abcd"]

Function:

function bubbleSort(strArray){
  const arrayLength = Object.keys(strArray).length;
    var swapp;
    var newLen = arrayLength-1;
    var sortedStrArrByLenght=strArray;
    do {
        swapp = false;
        for (var i=0; i < newLen; i++)
        {
            if (sortedStrArrByLenght[i].length > sortedStrArrByLenght[i+1].length)
            {
               var temp = sortedStrArrByLenght[i];
               sortedStrArrByLenght[i] = sortedStrArrByLenght[i+1];
               sortedStrArrByLenght[i+1] = temp;
               swapp = true;
            }
        }
        newLen--;
    } while (swap);
  return sortedStrArrByLenght;
}

Autowiring two beans implementing same interface - how to set default bean to autowire?

For Spring 2.5, there's no @Primary. The only way is to use @Qualifier.

How to split one string into multiple variables in bash shell?

Using bash regex capabilities:

re="^([^-]+)-(.*)$"
[[ "ABCDE-123456" =~ $re ]] && var1="${BASH_REMATCH[1]}" && var2="${BASH_REMATCH[2]}"
echo $var1
echo $var2

OUTPUT

ABCDE
123456

Server returned HTTP response code: 401 for URL: https

Try This. You need pass the authentication to let the server know its a valid user. You need to import these two packages and has to include a jersy jar. If you dont want to include jersy jar then import this package

import sun.misc.BASE64Encoder;

import com.sun.jersey.core.util.Base64;
import sun.net.www.protocol.http.HttpURLConnection;

and then,

String encodedAuthorizedUser = getAuthantication("username", "password");
URL url = new URL("Your Valid Jira URL");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setRequestProperty ("Authorization", "Basic " + encodedAuthorizedUser );

 public String getAuthantication(String username, String password) {
   String auth = new String(Base64.encode(username + ":" + password));
   return auth;
 }

Converting ArrayList to Array in java

List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki"); 
String names[]=list.toArray(new String[0]);

if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.

JPA - Returning an auto generated id after persist()

@Entity
public class ABC implements Serializable {
     @Id
     @GeneratedValue(strategy=GenerationType.IDENTITY)
     private int id;   
}

check that @GeneratedValue notation is there in your entity class.This tells JPA about your entity property auto-generated behavior

Generate random password string with requirements in javascript

In case you need a password generated with at least 1 number, 1 upper case character, and 1 lower case character:

function generatePassword(passwordLength) {
  var numberChars = "0123456789";
  var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var lowerChars = "abcdefghijklmnopqrstuvwxyz";
  var allChars = numberChars + upperChars + lowerChars;
  var randPasswordArray = Array(passwordLength);
  randPasswordArray[0] = numberChars;
  randPasswordArray[1] = upperChars;
  randPasswordArray[2] = lowerChars;
  randPasswordArray = randPasswordArray.fill(allChars, 3);
  return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(Math.random() * x.length)] })).join('');
}

function shuffleArray(array) {
  for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
  return array;
}

alert(generatePassword(12));

Here's the fiddle if you want to play/test: http://jsfiddle.net/sJGW4/155/

Props to @mwag for giving me the start to create this.

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool

Trim a string based on the string length

str==null ? str : str.substring(0, Math.min(str.length(), 10))

or,

str==null ? "" : str.substring(0, Math.min(str.length(), 10))

Works with null.

How to print a string at a fixed width?

EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.

You can use string formatting like this:

>>> print '%5s' % 'aa'
   aa
>>> print '%5s' % 'aaa'
  aaa
>>> print '%5s' % 'aaaa'
 aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

Basically:

  • the % character informs python it will have to substitute something to a token
  • the s character informs python the token will be a string
  • the 5 (or whatever number you wish) informs python to pad the string with spaces up to 5 characters.

In your specific case a possible implementation could look like:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
...     print 'value %3s - num of occurances = %d' % item # %d is the token of integers
... 
value   a - num of occurances = 1
value  ab - num of occurances = 1
value abc - num of occurances = 1

SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

and you could get the number of occurrences by using combinations in conjunction with count().

How to find a string inside a entire database?

Here is an easy and convenient cursor based solution

DECLARE
@search_string  VARCHAR(100),
@table_name     SYSNAME,
@table_id       INT,
@column_name    SYSNAME,
@sql_string     VARCHAR(2000)

SET @search_string = 'StringtoSearch'

DECLARE tables_cur CURSOR FOR SELECT name, object_id FROM sys.objects WHERE  type = 'U'

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id 
        AND system_type_id IN (167, 175, 231, 239)

    OPEN columns_cur

    FETCH NEXT FROM columns_cur INTO @column_name
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + '] 
            LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''

            EXECUTE(@sql_string)

        FETCH NEXT FROM columns_cur INTO @column_name
        END

    CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END

CLOSE tables_cur
DEALLOCATE tables_cur

How to split a string between letters and digits (or between digits and letters)?

If you are looking for solution without using Java String functionality (i.e. split, match, etc.) then the following should help:

List<String> splitString(String string) {
        List<String> list = new ArrayList<String>();
        String token = "";
        char curr;
        for (int e = 0; e < string.length() + 1; e++) {
            if (e == 0)
                curr = string.charAt(0);
            else {
                curr = string.charAt(--e);
            }

            if (isNumber(curr)) {
                while (e < string.length() && isNumber(string.charAt(e))) {
                    token += string.charAt(e++);
                }
                list.add(token);
                token = "";
            } else {
                while (e < string.length() && !isNumber(string.charAt(e))) {
                    token += string.charAt(e++);
                }
                list.add(token);
                token = "";
            }

        }

        return list;
    }

boolean isNumber(char c) {
        return c >= '0' && c <= '9';
    }

This solution will split numbers and 'words', where 'words' are strings that don't contain numbers. However, if you like to have only 'words' containing English letters then you can easily modify it by adding more conditions (like isNumber method call) depending on your requirements (for example you may wish to skip words that contain non English letters). Also note that the splitString method returns ArrayList which later can be converted to String array.

How to determine if a String has non-alphanumeric characters?

One approach is to do that using the String class itself. Let's say that your string is something like that:

String s = "some text";
boolean hasNonAlpha = s.matches("^.*[^a-zA-Z0-9 ].*$");

one other is to use an external library, such as Apache commons:

String s = "some text";
boolean hasNonAlpha = !StringUtils.isAlphanumeric(s);

Search and replace a particular string in a file using Perl

You could also do this:

#!/usr/bin/perl

use strict;
use warnings;

$^I = '.bak'; # create a backup copy 

while (<>) {
   s/<PREF>/ABCD/g; # do the replacement
   print; # print to the modified file
}

Invoke the script with by

./script.pl input_file

You will get a file named input_file, containing your changes, and a file named input_file.bak, which is simply a copy of the original file.

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

First create table without auto_increment,

CREATE TABLE `members`(
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL
    PRIMARY KEY (memberid) 
) ENGINE = MYISAM;

after set id as index,

ALTER TABLE `members` ADD INDEX(`id`);

after set id as auto_increment,

ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;

Or

CREATE TABLE IF NOT EXISTS `members` (
    `id` int(11) NOT NULL,
    `memberid` VARCHAR( 30 ) NOT NULL ,
    `Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
    `firstname` VARCHAR( 50 ) NULL ,
    `lastname` VARCHAR( 50 ) NULL,
      PRIMARY KEY (`memberid`),
      KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Get the POST request body from HttpServletRequest

In Java 8, you can do it in a simpler and clean way :

if ("POST".equalsIgnoreCase(request.getMethod())) 
{
   test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}

how to access downloads folder in android?

For your first question try

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 

(available since API 8)

To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Gwerder's solution wont work because hash = hmac.read(); happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write statement is un-necessary in this example.

Instead do this:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash = hmac.read();
    //...do something with the hash...
});

More formally, if you wish, the line

hmac.end(text, function () {

could be written

hmac.end(text, 'utf8', function () {

because in this example text is a utf string

Find the index of a char in string?

Contanis occur if using the method of the present letter, and store the corresponding number using the IndexOf method, see example below.

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains("d") Then
        numberString = myString.IndexOf("d")
    End If
End Sub

Another sample with TextBox

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim myString As String = "abcdef"
    Dim numberString As String = String.Empty

    If myString.Contains(me.TextBox1.Text) Then
        numberString = myString.IndexOf(Me.TextBox1.Text)
    End If
End Sub

Regards

Batch file: Find if substring is in string (not in a file)

To find a text in the Var, Example:

var_text="demo string test"
Echo.%var_text% | findstr /C:"test">nul && (
    echo "found test" 
    ) || Echo.%var_text% | findstr /C:"String">nul && (
             echo "found String with S uppercase letter" 
    ) || (
             echo "Not Found " 
    )

LEGEND:

  1. & Execute_that AND execute_this
  2. || Ex: Execute_that IF_FAIL execute this
  3. && Ex: Execute_that IF_SUCCESSFUL execute this
  4. >nul no echo result of command
  5. findstr
  6. /C: Use string as a literal search string

Splitting on first occurrence

>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'

What is the Windows equivalent of the diff command?

If you have installed git on your machine, you can open a git terminal and just use the Linux diff command as normal.

generate random string for div id

Based on HTML 4, the id should start from letter:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

So, one of the solutions could be (alphanumeric):

  var length = 9;
  var prefix = 'my-awesome-prefix-'; // To be 100% sure id starts with letter

  // Convert it to base 36 (numbers + letters), and grab the first 9 characters
  // after the decimal.
  var id = prefix + Math.random().toString(36).substr(2, length);

Another solution - generate string with letters only:

  var length = 9;
  var id = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, length);

Passing route control with optional parameter after root in express?

Express version:

"dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1"
  }

Optional parameter are very much handy, you can declare and use them easily using express:

app.get('/api/v1/tours/:cId/:pId/:batchNo?', (req, res)=>{
    console.log("category Id: "+req.params.cId);
    console.log("product ID: "+req.params.pId);
    if (req.params.batchNo){
        console.log("Batch No: "+req.params.batchNo);
    }
});

In the above code batchNo is optional. Express will count it optional because after in URL construction, I gave a '?' symbol after batchNo '/:batchNo?'

Now I can call with only categoryId and productId or with all three-parameter.

http://127.0.0.1:3000/api/v1/tours/5/10
//or
http://127.0.0.1:3000/api/v1/tours/5/10/8987

enter image description here enter image description here

how to parse json using groovy

That response is a Map, with a single element with key '212315952136472'. There's no 'data' key in the Map. If you want to loop through all entries, use something like this:

JSONObject userJson = JSON.parse(jsonResponse)
userJson.each { id, data -> println data.link }

If you know it's a single-element Map then you can directly access the link:

def data = userJson.values().iterator().next()
String link = data.link

And if you knew the id (e.g. if you used it to make the request) then you can access the value more concisely:

String id = '212315952136472'
...
String link = userJson[id].link

javascript regular expression to not match a word

if (!s.match(/abc|def/g)) {
    alert("match");
}
else {
    alert("no match");
}

Configuration System Failed to Initialize

In my case, within my .edmx file I had run the 'Update Model From Database' command. This command added an unnecessary connection string to my app.config file. I deleted that connection string and all was good again.

.NET - How do I retrieve specific items out of a Dataset?

The DataSet object has a Tables array. If you know the table you want, it will have a Row array, each object of which has an ItemArray array. In your case the code would most likely be

int var1 = int.Parse(ds.Tables[0].Rows[0].ItemArray[4].ToString());

and so forth. This would give you the 4th item in the first row. You can also use Columns instead of ItemArray and specify the column name as a string instead of remembering it's index. That approach can be easier to keep up with if the table structure changes. So that would be

int var1 = int.Parse(ds.Tables[0].Rows[0]["MyColumnName"].ToString());

Using an array as needles in strpos

You can iterate through the array and set a "flag" value if strpos returns false.

$flag = false;
foreach ($find_letters as $letter)
{
    if (strpos($string, $letter) === false)
    {
        $flag = true;
    }
}

Then check the value of $flag.

How can I split a string into segments of n characters?

Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.

// substring + array push + end precalc
var chunks = [];

for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
    chunks.push(str.substring(i, e));
}

Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.

You can try it here

With CSS, use "..." for overflowed block of multi-lines

a pure css method base on -webkit-line-clamp:

_x000D_
_x000D_
@-webkit-keyframes ellipsis {/*for test*/_x000D_
    0% { width: 622px }_x000D_
    50% { width: 311px }_x000D_
    100% { width: 622px }_x000D_
}_x000D_
.ellipsis {_x000D_
    max-height: 40px;/* h*n */_x000D_
    overflow: hidden;_x000D_
    background: #eee;_x000D_
_x000D_
    -webkit-animation: ellipsis ease 5s infinite;/*for test*/_x000D_
    /**_x000D_
    overflow: visible;_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .content {_x000D_
    position: relative;_x000D_
    display: -webkit-box;_x000D_
    -webkit-box-orient: vertical;_x000D_
    -webkit-box-pack: center;_x000D_
    font-size: 50px;/* w */_x000D_
    line-height: 20px;/* line-height h */_x000D_
    color: transparent;_x000D_
    -webkit-line-clamp: 2;/* max row number n */_x000D_
    vertical-align: top;_x000D_
}_x000D_
.ellipsis .text {_x000D_
    display: inline;_x000D_
    vertical-align: top;_x000D_
    font-size: 14px;_x000D_
    color: #000;_x000D_
}_x000D_
.ellipsis .overlay {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 50%;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    overflow: hidden;_x000D_
_x000D_
    /**_x000D_
    overflow: visible;_x000D_
    left: 0;_x000D_
    background: rgba(0,0,0,.5);_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .overlay:before {_x000D_
    content: "";_x000D_
    display: block;_x000D_
    float: left;_x000D_
    width: 50%;_x000D_
    height: 100%;_x000D_
_x000D_
    /**_x000D_
    background: lightgreen;_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .placeholder {_x000D_
    float: left;_x000D_
    width: 50%;_x000D_
    height: 40px;/* h*n */_x000D_
_x000D_
    /**_x000D_
    background: lightblue;_x000D_
    /**/_x000D_
}_x000D_
.ellipsis .more {_x000D_
    position: relative;_x000D_
    top: -20px;/* -h */_x000D_
    left: -50px;/* -w */_x000D_
    float: left;_x000D_
    color: #000;_x000D_
    width: 50px;/* width of the .more w */_x000D_
    height: 20px;/* h */_x000D_
    font-size: 14px;_x000D_
_x000D_
    /**_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    background: orange;_x000D_
    /**/_x000D_
}
_x000D_
<div class='ellipsis'>_x000D_
    <div class='content'>_x000D_
        <div class='text'>text text text text text text text text text text text text text text text text text text text text text </div>_x000D_
        <div class='overlay'>_x000D_
            <div class='placeholder'></div>_x000D_
            <div class='more'>...more</div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

SQL 'like' vs '=' performance

A personal example using mysql 5.5: I had an inner join between 2 tables, one of 3 million rows and one of 10 thousand rows.

When using a like on an index as below(no wildcards), it took about 30 seconds:

where login like '12345678'

using 'explain' I get:

enter image description here

When using an '=' on the same query, it took about 0.1 seconds:

where login ='600009'

Using 'explain' I get:

enter image description here

As you can see, the like completely cancelled the index seek, so query took 300 times more time.

Generating a random password in php

I know you are trying to generate your password in a specific way, but you might want to look at this method as well...

$bytes = openssl_random_pseudo_bytes(2);

$pwd = bin2hex($bytes);

It's taken from the php.net site and it creates a string which is twice the length of the number you put in the openssl_random_pseudo_bytes function. So the above would create a password 4 characters long.

In short...

$pwd = bin2hex(openssl_random_pseudo_bytes(4));

Would create a password 8 characters long.

Note however that the password only contains numbers 0-9 and small cap letters a-f!

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

paste below two jar in your /WEB-INF/lib folder and then go to project properties and go to add jar and select these two jars then click Ok, Ok

standard.jar, jstl-1.0.2.jar

Is there a difference between /\s/g and /\s+/g?

\s means "one space", and \s+ means "one or more spaces".

But, because you're using the /g flag (replace all occurrences) and replacing with the empty string, your two expressions have the same effect.

Joining pairs of elements of a list

Well I would do it this way as I am no good with Regs..

CODE

t = '1. eat, food\n\
7am\n\
2. brush, teeth\n\
8am\n\
3. crack, eggs\n\
1pm'.splitlines()

print [i+j for i,j in zip(t[::2],t[1::2])]

output:

['1. eat, food   7am', '2. brush, teeth   8am', '3. crack, eggs   1pm']  

Hope this helps :)

How do you get the string length in a batch file?

If you are on Windows Vista +, then try this Powershell method:

For /F %%L in ('Powershell $Env:MY_STRING.Length') do (
    Set MY_STRING_LEN=%%L
)

or alternatively:

Powershell $Env:MY_STRING.Length > %Temp%\TmpFile.txt
Set /p MY_STRING_LEN = < %Temp%\TmpFile.txt
Del %Temp%\TmpFile.txt

I'm on Windows 7 x64 and this is working for me.

How can I check if an element exists in the visible DOM?

Use getElementById() if it's available.

Also, here's an easy way to do it with jQuery:

if ($('#elementId').length > 0) {
  // Exists.
}

And if you can't use third-party libraries, just stick to base JavaScript:

var element =  document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
  // Exists.
}

Write a file on iOS

Swift

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding, error: nil)
}

func loadFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] as! String
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String = String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding, error: nil)!
    println(content)
}

Swift 2

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.writeToFile(fileName, atomically: false, encoding: NSUTF8StringEncoding)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0] 
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
       content = try String(contentsOfFile: fileName, encoding: NSUTF8StringEncoding)
    }catch _{
        content=""
    }
    return content;
}

Swift 3

func saveFile() {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content = "Hello World"
    do{
        try content.write(toFile: fileName, atomically: false, encoding: String.Encoding.utf8)
    }catch _ {

    }

}

func loadFile()->String {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    let fileName = "\(documentsDirectory)/textFile.txt"
    let content: String
    do{
        content = try String(contentsOfFile: fileName, encoding: String.Encoding.utf8)
    } catch _{
        content=""
    }
    return content;
}

How to set column widths to a jQuery datatable?

Configuration Options:

$(document).ready(function () {

  $("#companiesTable").dataTable({
    "sPaginationType": "full_numbers",
    "bJQueryUI": true,
    "bAutoWidth": false, // Disable the auto width calculation 
    "aoColumns": [
      { "sWidth": "30%" }, // 1st column width 
      { "sWidth": "30%" }, // 2nd column width 
      { "sWidth": "40%" } // 3rd column width and so on 
    ]
  });
});

Specify the css for the table:

table.display {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed;         // add this 
  word-wrap:break-word;        // add this 
}

HTML:

<table id="companiesTable" class="display"> 
  <thead>
    <tr>
      <th>Company name</th>
      <th>Address</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>

    <% for(Company c: DataRepository.GetCompanies()){ %>
      <tr>  
        <td><%=c.getName()%></td>
        <td><%=c.getAddress()%></td>
        <td><%=c.getTown()%></td>
      </tr>
    <% } %>

  </tbody>
</table>

It works for me!

Turning a Comma Separated string into individual rows

I know it has a lot of answers, but I want to write my version of split function like others and like string_split SQL Server 2016 native function.

create function [dbo].[Split]
(
    @Value nvarchar(max),
    @Delimiter nvarchar(50)
)
returns @tbl table
(
    Seq int primary key identity(1, 1),
    Value nvarchar(max)
)
as begin
    declare @Xml xml = cast('<d>' + replace(@Value, @Delimiter, '</d><d>') + '</d>' as xml)

    insert into @tbl
            (Value)
    select  a.split.value('.', 'nvarchar(max)') as Value
    from    @Xml.nodes('/d') a(split)
    
    return
end
  • Seq column is primary key to support fast join with other real table or Split function returned table.
  • Used XML function to support large data (looping version will slow down significantly when you have large data)

Here's a answer to question.

CREATE TABLE Testdata
(
    SomeID INT,
    OtherID INT,
    String VARCHAR(MAX)
)

INSERT Testdata SELECT 1,  9, '18,20,22'
INSERT Testdata SELECT 2,  8, '17,19'
INSERT Testdata SELECT 3,  7, '13,19,20'
INSERT Testdata SELECT 4,  6, ''
INSERT Testdata SELECT 9, 11, '1,2,3,4'


select  t.SomeID, t.OtherID, s.Value
from    Testdata t
        cross apply dbo.Split(t.String, ',') s

--Output
SomeID  OtherID Value
1       9       18
1       9       20
1       9       22
2       8       17
2       8       19
3       7       13
3       7       19
3       7       20
4       6       
9       11      1
9       11      2
9       11      3
9       11      4

Joining Split with other split

declare @Names nvarchar(max) = 'a,b,c,d'
declare @Codes nvarchar(max) = '10,20,30,40'

select  n.Seq, n.Value Name, c.Value Code
from    dbo.Split(@Names, ',') n
        inner join dbo.Split(@Codes, ',') c on n.Seq = c.Seq

--Output
Seq Name    Code
1   a       10
2   b       20
3   c       30
4   d       40

Split two times

declare @NationLocSex nvarchar(max) = 'Korea,Seoul,1;Vietnam,Kiengiang,0;China,Xian,0'

; with rows as
(
    select  Value
    from    dbo.Split(@NationLocSex, ';')
)
select  rw.Value r, cl.Value c
from    rows rw
        cross apply dbo.Split(rw.Value, ',') cl

--Output
r                       c
Korea,Seoul,1           Korea
Korea,Seoul,1           Seoul
Korea,Seoul,1           1
Vietnam,Kiengiang,0     Vietnam
Vietnam,Kiengiang,0     Kiengiang
Vietnam,Kiengiang,0     0
China,Xian,0            China
China,Xian,0            Xian
China,Xian,0            0

Split to columns

declare @Numbers nvarchar(50) = 'First,Second,Third'

; with t as
(
    select  case when Seq = 1 then Value end f1,
            case when Seq = 2 then Value end f2,
            case when Seq = 3 then Value end f3
    from    dbo.Split(@Numbers, ',')
)
select  min(f1) f1, min(f2) f2, min(f3) f3
from    t

--Output
f1      f2      f3
First   Second  Third

Generate rows by range


declare @Ranges nvarchar(50) = '1-2,4-6'

declare @Numbers table (Num int)
insert into @Numbers values (1),(2),(3),(4),(5),(6),(7),(8)

; with t as
(
    select  r.Seq, r.Value,
            min(case when ft.Seq = 1 then ft.Value end) ValueFrom,
            min(case when ft.Seq = 2 then ft.Value end) ValueTo
    from    dbo.Split(@Ranges, ',') r
            cross apply dbo.Split(r.Value, '-') ft
    group by r.Seq, r.Value
)
select  t.Seq, t.Value, t.ValueFrom, t.ValueTo, n.Num
from    t
        inner join @Numbers n on n.Num between t.ValueFrom and t.ValueTo

--Output
Seq Value   ValueFrom   ValueTo Num
1   1-2     1           2       1
1   1-2     1           2       2
2   4-6     4           6       4
2   4-6     4           6       5
2   4-6     4           6       6

Test a string for a substring

if "ABCD" in "xxxxABCDyyyy":
    # whatever

How to remove the character at a given index from a string in C?

this is how I implemented the same in c++.

#include <iostream>
#include <cstring>

using namespace std;

int leng;
char ch;
string str, cpy;

int main() {
    cout << "Enter a string: ";
    getline(cin, str);
    leng = str.length();
    cout << endl << "Enter the character to delete: ";
    cin >> ch;
    for (int i=0; i<leng; i++) {
        if (str[i] != ch)
        cpy += str[i];
    }
    cout << endl << "String after removal: " << cpy;
    return 0;
}

Hashcode and Equals for Hashset

I think your questions will all be answered if you understand how Sets, and in particular HashSets work. A set is a collection of unique objects, with Java defining uniqueness in that it doesn't equal anything else (equals returns false).

The HashSet takes advantage of hashcodes to speed things up. It assumes that two objects that equal eachother will have the same hash code. However it does not assume that two objects with the same hash code mean they are equal. This is why when it detects a colliding hash code, it only compares with other objects (in your case one) in the set with the same hash code.

Index (zero based) must be greater than or equal to zero

String.Format must start with zero index "{0}" like this:

Aboutme.Text = String.Format("{0}", reader.GetString(0));

Configure hibernate to connect to database via JNDI Datasource

Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">



  <jee:jndi-lookup id="dataSource"
                 jndi-name="Give_DataSource_Path_From_Your_Server"
                 expected-type="javax.sql.DataSource" />


Hope It will help someone.Thanks!

How can I compare two strings in java and define which of them is smaller than the other alphabetically?

You can use

str1.compareTo(str2);

If str1 is lexicographically less than str2, a negative number will be returned, 0 if equal or a positive number if str1 is greater.

E.g.,

"a".compareTo("b"); // returns a negative number, here -1
"a".compareTo("a"); // returns  0
"b".compareTo("a"); // returns a positive number, here 1
"b".compareTo(null); // throws java.lang.NullPointerException

How to convert a String to JsonObject using gson library

To do it in a simpler way, consider below:

JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();

How to split a single column values to multiple column values?

;WITH Split_Names (Name, xmlname)
AS
(
    SELECT 
    Name,
    CONVERT(XML,'<Names><name>'  
    + REPLACE(Name,' ', '</name><name>') + '</name></Names>') AS xmlname
      FROM somenames
)

 SELECT       
 xmlname.value('/Names[1]/name[1]','varchar(100)') AS first_name,    
 xmlname.value('/Names[1]/name[2]','varchar(100)') AS last_name
 FROM Split_Names

and also check the link below for reference

http://jahaines.blogspot.in/2009/06/converting-delimited-string-of-values.html

warning: assignment makes integer from pointer without a cast

The expression *src refers to the first character in the string, not the whole string. To reassign src to point to a different string tgt, use src = tgt;.

How to replace part of string by position?

I believe the simplest way would be this:(without stringbuilder)

string myString = "ABCDEFGHIJ";
char[] replacementChars = {'Z', 'X'};
byte j = 0;

for (byte i = 3; i <= 4; i++, j++)  
{                   
myString = myString.Replace(myString[i], replacementChars[j]);  
}

This works because a variable of type string can be treated as an array of char variables. You can, for example refer to the second character of a string variable with name "myString" as myString[1]

Removing duplicates from a String in Java

public class StringTest {

    public static String dupRemove(String str) {

        Set<Character> s1 = new HashSet<Character>();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); i++) {

            Character c = str.charAt(i);

            if (!s1.contains(c)) {
                s1.add(c);
                sb.append(c);
            }


        }

        System.out.println(sb.toString());

        return sb.toString();

    }

    public static void main(String[] args) {

        dupRemove("AAAAAAAAAAAAAAAAA BBBBBBBB");
    }

}

Regular expression to return text between parenthesis

Building on tkerwin's answer, if you happen to have nested parentheses like in

st = "sum((a+b)/(c+d))"

his answer will not work if you need to take everything between the first opening parenthesis and the last closing parenthesis to get (a+b)/(c+d), because find searches from the left of the string, and would stop at the first closing parenthesis.

To fix that, you need to use rfind for the second part of the operation, so it would become

st[st.find("(")+1:st.rfind(")")]

Java JDBC - How to connect to Oracle using Service Name instead of SID

So there are two easy ways to make this work. The solution posted by Bert F works fine if you don't need to supply any other special Oracle-specific connection properties. The format for that is:

jdbc:oracle:thin:@//HOSTNAME:PORT/SERVICENAME

However, if you need to supply other Oracle-specific connection properties then you need to use the long TNSNAMES style. I had to do this recently to enable Oracle shared connections (where the server does its own connection pooling). The TNS format is:

jdbc:oracle:thin:@(description=(address=(host=HOSTNAME)(protocol=tcp)(port=PORT))(connect_data=(service_name=SERVICENAME)(server=SHARED)))

If you're familiar with the Oracle TNSNAMES file format, then this should look familiar to you. If not then just Google it for the details.

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

To swap characters in a string a of position l and r

def swap(a, l, r):
    a = a[0:l] + a[r] + a[l+1:r] + a[l] + a[r+1:]
    return a

Example: swap("aaabcccdeee", 3, 7) returns "aaadcccbeee"

Convert a list of characters into a string

besides str.join which is the most natural way, a possibility is to use io.StringIO and abusing writelines to write all elements in one go:

import io

a = ['a','b','c','d']

out = io.StringIO()
out.writelines(a)
print(out.getvalue())

prints:

abcd

When using this approach with a generator function or an iterable which isn't a tuple or a list, it saves the temporary list creation that join does to allocate the right size in one go (and a list of 1-character strings is very expensive memory-wise).

If you're low in memory and you have a lazily-evaluated object as input, this approach is the best solution.

PHP random string generator

Here's my simple one line solution to generate a use friendly random password, excluding the characters that lookalike such as "1" and "l", "O" and "0", etc... here it is 5 characters but you can easily change it of course:

$user_password = substr(str_shuffle('abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789'),0,5);

Generating all permutations of a given string

Based on Mark Byers' answer i came up with this solution:

JAVA

public class Main {

    public static void main(String[] args) {
        myPerm("ABCD", 0);
    }

    private static void myPerm(String str, int index)
    {
        if (index == str.length()) System.out.println(str);

        for (int i = index; i < str.length(); i++)
        {
            char prefix = str.charAt(i);
            String suffix = str.substring(0,i) + str.substring(i+1);

            myPerm(prefix + suffix, index + 1);
        }
    }
}

C#

I also wrote the function in C# using the new C# 8.0 range operator

    class Program
    {
        static void Main(string[] args)
        {
            myPerm("ABCD", 0);
        }

        private static void myPerm(string str, int index)
        {
            if (index == str.Length) Console.WriteLine(str);

            for (int i = index; i < str.Length; i++)
            {
                char prefix = str[i];
                string suffix = str[0..i] + str[(i + 1)..];

                myPerm(prefix + suffix, index + 1);
            }
        }
    

We just put every letter at the beginning and then permute.
The first iteration looks like this:

/*
myPerm("ABCD",0)  
  prefix = "A"  
  suffix = "BCD"  
  myPerm("ABCD",1)  
    prefix = "B"  
    suffix = "ACD"  
    myPerm("BACD",2)  
      prefix = "C"  
      suffix = "BAD"  
      myPerm("CBAD",3)  
        prefix = "D"  
        suffix = "CBA"  
        myPerm("DCBA",4)  
          Console.WriteLine("DCBA")
*/

Remove .php extension with .htaccess

After changing the parameter AllowOverride from None to All in /etc/apache2/apache2.conf (Debian 8), following this, the .htaccess file just must contain:

Options +MultiViews
AddHandler php5-script php
AddType text/html php

And it was enough to hide .php extension from files

Finding the path of the program that will execute from the command line in Windows

Use the where command. The first result in the list is the one that will execute.

C:\> where notepad
C:\Windows\System32\notepad.exe
C:\Windows\notepad.exe

According to this blog post, where.exe is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.

On Linux, the equivalent is the which command, e.g. which ssh.

org.hibernate.MappingException: Unknown entity

In hibernate.cfg.xml , please put following code

<mapping class="class/bo name"/>

C# adding a character in a string

string alpha = "abcdefghijklmnopqrstuvwxyz";
string newAlpha = "";
for (int i = 5; i < alpha.Length; i += 6)
{
  newAlpha = alpha.Insert(i, "-");
  alpha = newAlpha;
}

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

JQuery string contains check

Please try:

str1.contains(str2)

Send email using java

The short answer - No.

The long answer - no, since the code relies on the presence of a SMTP server running on the local machine, and listening on port 25. The SMTP server (technically the MTA or Mail Transfer Agent) is responsible for communicating with the Mail User Agent (MUA, which in this case is the Java process) to receive outgoing emails.

Now, MTAs are typically responsible for receiving mails from users for a particular domain. So, for the domain gmail.com, it would be the Google mail servers that are responsible for authenticating mail user agents and hence transferring of mails to inboxes on the GMail servers. I'm not sure if GMail trusts open mail relay servers, but it is certainly not an easy task to perform authentication on behalf on Google, and then relay mail to the GMail servers.

If you read the JavaMail FAQ on using JavaMail to accessing GMail, you'll notice that the hostname and the port happen to be pointing to the GMail servers, and certainly not to localhost. If you intend to use your local machine, you'll need to perform either relaying or forwarding.

You'll probably need to understand the SMTP protocol in depth if you intend to get anywhere when it comes to SMTP. You can start with the Wikipedia article on SMTP, but any further progress will actually necessitate programming against a SMTP server.

What is the boundary in multipart/form-data?

multipart/form-data contains boundary to separate name/value pairs. The boundary acts like a marker of each chunk of name/value pairs passed when a form gets submitted. The boundary is automatically added to a content-type of a request header.

The form with enctype="multipart/form-data" attribute will have a request header Content-Type : multipart/form-data; boundary --- WebKit193844043-h (browser generated vaue).

The payload passed looks something like this:

Content-Type: multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”file”; filename=”captcha”
    Content-Type:

    -----WebKitFormBoundary7MA4YWxkTrZu0gW
    Content-Disposition: form-data; name=”action”

    submit
    -----WebKitFormBoundary7MA4YWxkTrZu0gW--

On the webservice side, it's consumed in @Consumes("multipart/form-data") form.

Beware, when testing your webservice using chrome postman, you need to check the form data option(radio button) and File menu from the dropdown box to send attachment. Explicit provision of content-type as multipart/form-data throws an error. Because boundary is missing as it overrides the curl request of post man to server with content-type by appending the boundary which works fine.

See RFC1341 sec7.2 The Multipart Content-Type

Getting the "real" Facebook profile picture URL from graph API

For Android:

According to latest Facebook SDK,

First you need to call GraphRequest API for getting all the details of user in which API also gives URL of current Profile Picture.

Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,picture.type(large)");
new GraphRequest(token, "me", params, HttpMethod.GET,
        new GraphRequest.Callback() {
            @Override
            public void onCompleted(GraphResponse response) {
                if (response != null) {
                    try {
                        JSONObject data = response.getJSONObject();
                        if (data.has("picture")) {
                            String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
}).executeAsync();

Short rot13 function - Python

As of Python 3.1, string.translate and string.maketrans no longer exist. However, these methods can be used with bytes instead.

Thus, an up-to-date solution directly inspired from Paul Rubel's one, is:

rot13 = bytes.maketrans(
    b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
    b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM")
b'Hello world!'.translate(rot13)

Conversion from string to bytes and vice-versa can be done with the encode and decode built-in functions.

How to get the last characters in a String in Java, regardless of String size

org.apache.commons.lang3.StringUtils.substring(s, -7) 

gives you the answer. It returns the input if it is shorter than 7, and null if s == null. It never throws an exception.

See https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#substring-java.lang.String-int-int-

Adding quotes to a string in VBScript

You can do like:

a="""xyz"""  
g="abcd " & a  

Or:

a=chr(34) & "xyz" & chr(34)
g="abcd " & a  

How to match "any character" in regular expression?

[^] should match any character, including newline. [^CHARS] matches all characters except for those in CHARS. If CHARS is empty, it matches all characters.

JavaScript example:

/a[^]*Z/.test("abcxyz \0\r\n\t012789ABCXYZ") // Returns ‘true’.

How to make Regular expression into non-greedy?

You are right that greediness is an issue:

--A--Z--A--Z--
  ^^^^^^^^^^
     A.*Z

If you want to match both A--Z, you'd have to use A.*?Z (the ? makes the * "reluctant", or lazy).

There are sometimes better ways to do this, though, e.g.

A[^Z]*+Z

This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.

In your case, the regex would be:

/(\[[^\]]++\])/

Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:

/(\[[^\]]+\])/

See also


Quick summary

*   Zero or more, greedy
*?  Zero or more, reluctant
*+  Zero or more, possessive

+   One or more, greedy
+?  One or more, reluctant
++  One or more, possessive

?   Zero or one, greedy
??  Zero or one, reluctant
?+  Zero or one, possessive

Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m} constructs.

Examples in Java:

System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!"));  // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"

System.out.println("xxxxxx".replaceAll("x{3,5}", "Y"));  // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"

How can I use "." as the delimiter with String.split() in java

If performance is an issue, you should consider using StringTokenizer instead of split. StringTokenizer is much much faster than split, even though it is a "legacy" class (but not deprecated).

Converting to upper and lower case in Java

I consider this simpler than any prior correct answer. I'll also throw in javadoc. :-)

/**
 * Converts the given string to title case, where the first
 * letter is capitalized and the rest of the string is in
 * lower case.
 * 
 * @param s a string with unknown capitalization
 * @return a title-case version of the string
 */
public static String toTitleCase(String s)
{
    if (s.isEmpty())
    {
        return s;
    }
    return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
}

Strings of length 1 do not needed to be treated as a special case because s.substring(1) returns the empty string when s has length 1.

"The stylesheet was not loaded because its MIME type, "text/html" is not "text/css"

Actually I had wrongly put href="", and hence the html file was referencing itself as the CSS. Mozilla had the similar bug once, and I got the answer from there.

Random strings in Python

Sometimes, I've wanted random strings that are semi-pronounceable, semi-memorable.

import random

def randomWord(length=5):
    consonants = "bcdfghjklmnpqrstvwxyz"
    vowels = "aeiou"

    return "".join(random.choice((consonants, vowels)[i%2]) for i in range(length))

Then,

>>> randomWord()
nibit
>>> randomWord()
piber
>>> randomWord(10)
rubirikiro

To avoid 4-letter words, don't set length to 4.

Jim

IndexOf function in T-SQL

You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.

CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4

Mind that you need to use the wildcards in PATINDEX on either side.

How to avoid pressing Enter with getchar() for reading a single character only?

getchar() is a standard function that on many platforms requires you to press ENTER to get the input, because the platform buffers input until that key is pressed. Many compilers/platforms support the non-standard getch() that does not care about ENTER (bypasses platform buffering, treats ENTER like just another key).

How to validate domain name in PHP?

Your regular expression is fine, but you're not using preg_match right. It returns an int (0 or 1), not a boolean. Just write if(!preg_match($regex, $string)) { ... }

Binding objects defined in code-behind

One way would be to create an ObservableCollection (System.Collections.ObjectModel) and have your dictionary data in there. Then you should be able to bind the ObservableCollection to your ListBox.

In your XAML you should have something like this:

<ListBox ItemsSource="{Binding Path=Name_of_your_ObservableCollection" />

How to remove numbers from string using Regex.Replace?

text= re.sub('[0-9\n]',' ',text)

install regex in python which is re then do the following code.

SQL Server Script to create a new user

Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:

USE [master];
GO
CREATE LOGIN MyNewAdminUser 
    WITH PASSWORD    = N'abcd',
    CHECK_POLICY     = OFF,
    CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember 
    @loginame = N'MyNewAdminUser', 
    @rolename = N'sysadmin';

You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).

iterating over each character of a String in ruby 1.8.6 (each_char)

Extending la_f0ka's comment, esp. if you also need the index position in your code, you should be able to do

s = 'ABCDEFG'
for pos in 0...s.length
    puts s[pos].chr
end

The .chr is important as Ruby < 1.9 returns the code of the character at that position instead of a substring of one character at that position.

In Python, how do I create a string of n characters in one line of code?

Why "one line"? You can fit anything onto one line.

Assuming you want them to start with 'a', and increment by one character each time (with wrapping > 26), here's a line:

>>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x))))
>>> mkstring(10)
'abcdefghij'
>>> mkstring(30)
'abcdefghijklmnopqrstuvwxyzabcd'

In Python, how to check if a string only contains certain characters?

Simpler approach? A little more Pythonic?

>>> ok = "0123456789abcdef"
>>> all(c in ok for c in "123456abc")
True
>>> all(c in ok for c in "hello world")
False

It certainly isn't the most efficient, but it's sure readable.

Add list to set?

To add the elements of a list to a set, use update

From https://docs.python.org/2/library/sets.html

s.update(t): return set s with elements added from t

E.g.

>>> s = set([1, 2])
>>> l = [3, 4]
>>> s.update(l)
>>> s
{1, 2, 3, 4}

If you instead want to add the entire list as a single element to the set, you can't because lists aren't hashable. You could instead add a tuple, e.g. s.add(tuple(l)). See also TypeError: unhashable type: 'list' when using built-in set function for more information on that.

Why should you use strncpy instead of strcpy?

The strncpy() function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy() function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits

Also for POSIX API functions like read() which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy().

In your example code, index is actually not an index, but a count - it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated

Changing one character in a string

A solution combining find and replace methods in a single line if statement could be:

```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}")           # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}")   # my_new_var = stackoverflow
```

How do malloc() and free() work?

Your strcpy line attempts to store 9 bytes, not 8, because of the NUL terminator. It invokes undefined behaviour.

The call to free may or may not crash. The memory "after" the 4 bytes of your allocation might be used for something else by your C or C++ implementation. If it is used for something else, then scribbling all over it will cause that "something else" to go wrong, but if it isn't used for anything else, then you could happen to get away with it. "Getting away with it" might sound good, but is actually bad, since it means your code will appear to run OK, but on a future run you might not get away with it.

With a debugging-style memory allocator, you might find that a special guard value has been written there, and that free checks for that value and panics if it doesn't find it.

Otherwise, you might find that the next 5 bytes includes part of a link node belonging to some other block of memory which hasn't been allocated yet. Freeing your block could well involved adding it to a list of available blocks, and because you've scribbled in the list node, that operation could dereference a pointer with an invalid value, causing a crash.

It all depends on the memory allocator - different implementations use different mechanisms.

Detect when browser receives file download

In my experience, there are two ways to handle this:

  1. Set a short-lived cookie on the download, and have JavaScript continually check for its existence. Only real issue is getting the cookie lifetime right - too short and the JS can miss it, too long and it might cancel the download screens for other downloads. Using JS to remove the cookie upon discovery usually fixes this.
  2. Download the file using fetch/XHR. Not only do you know exactly when the file download finishes, if you use XHR you can use progress events to show a progress bar! Save the resulting blob with msSaveBlob in IE/Edge and a download link (like this one) in Firefox/Chrome. The problem with this method is that iOS Safari doesn't seem to handle downloading blobs right - you can convert the blob into a data URL with a FileReader and open that in a new window, but that's opening the file, not saving it.

How do I remove a substring from the end of a string in Python?

You can use split:

'abccomputer.com'.split('.com',1)[0]
# 'abccomputer'

SQL Bulk Insert with FIRSTROW parameter skips the following line

I don't think you can skip rows in a different format with BULK INSERT/BCP.

When I run this:

TRUNCATE TABLE so1029384

BULK INSERT so1029384
FROM 'C:\Data\test\so1029384.txt'
WITH
(
--FIRSTROW = 2,
FIELDTERMINATOR= '|',
ROWTERMINATOR = '\n'
)

SELECT * FROM so1029384

I get:

col1                                               col2                                               col3
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
***A NICE HEADER HERE***
0000001234               SSNV                                               00013893-03JUN09
0000005678                                         ABCD                                               00013893-03JUN09
0000009112                                         0000                                               00013893-03JUN09
0000009112                                         0000                                               00013893-03JUN09

It looks like it requires the '|' even in the header data, because it reads up to that into the first column - swallowing up a newline into the first column. Obviously if you include a field terminator parameter, it expects that every row MUST have one.

You could strip the row with a pre-processing step. Another possibility is to select only complete rows, then process them (exluding the header). Or use a tool which can handle this, like SSIS.

How do I remove the first characters of a specific column in a table?

You Can also do this in SQL..

substring(StudentCode,4,len(StudentCode))

syntax

substring (ColumnName,<Number of starting Character which u want to remove>,<length of given string>)

How to Initialize char array from a string

Perhaps your character array needs to be constant. Since you're initializing your array with characters from a constant string, your array needs to be constant. Try this:

#define S "ABCD"
const char a[] = { S[0], S[1], S[2], S[3] };

How to swap String characters in Java?

StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();

Remove characters from NSString?

If you want to support more than one space at a time, or support any whitespace, you can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                           componentsJoinedByString:@""];

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

You'll need to decide how you'd like to handle exceptions thrown by the encrypt method.

Currently, encrypt is declared with throws Exception - however, in the body of the method, exceptions are caught in a try/catch block. I recommend you either:

  • remove the throws Exception clause from encrypt and handle exceptions internally (consider writing a log message at the very least); or,
  • remove the try/catch block from the body of encrypt, and surround the call to encrypt with a try/catch instead (i.e. in actionPerformed).

Regarding the compilation error you refer to: if an exception was thrown in the try block of encrypt, nothing gets returned after the catch block finishes. You could address this by initially declaring the return value as null:

public static byte[] encrypt(String toEncrypt) throws Exception{
  byte[] encrypted = null;
  try {
    // ...
    encrypted = ...
  }
  catch(Exception e){
    // ...
  }
  return encrypted;
}

However, if you can correct the bigger issue (the exception-handling strategy), this problem will take care of itself - particularly if you choose the second option I've suggested.

Python's most efficient way to choose longest string in list?

len(each) == max(len(x) for x in myList) or just each == max(myList, key=len)

How do I create a URL shortener?

You could hash the entire URL, but if you just want to shorten the id, do as marcel suggested. I wrote this Python implementation:

https://gist.github.com/778542

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

If you're dealing with character encodings other than UTF-16, you shouldn't be using java.lang.String or the char primitive -- you should only be using byte[] arrays or ByteBuffer objects. Then, you can use java.nio.charset.Charset to convert between encodings:

Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");

ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[]{(byte)0xC3, (byte)0xA2});

// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);

// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();

Sort a single String in Java

Without using Collections in Java:

import java.util.Scanner;

public class SortingaString {
    public static String Sort(String s1)
    {
        char ch[]=s1.toCharArray();         
        String res=" ";
        
        for(int i=0; i<ch.length ; i++)
        {
            for(int j=i+1;j<ch.length; j++)
            {
                if(ch[i]>=ch[j])
                {
                    char m=ch[i];
                    ch[i]=ch[j];
                    ch[j]=m;
                }
            }
            
            res=res+ch[i];
            
        }

        return res;
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("enter the string");
        
        String s1=sc.next();
        String ans=Sort( s1);
        
        System.out.println("after sorting=="+ans);
    }
}

Output:

enter the string==

sorting

after sorting== ginorst

Match at every second occurrence

There's no "direct" way of doing so but you can specify the pattern twice as in: a[^a]*a that match up to the second "a".

The alternative is to use your programming language (perl? C#? ...) to match the first occurence and then the second one.

EDIT: I've seen other responded using the "non-greedy" operators which might be a good way to go, assuming you have them in your regex library!

Using Excel as front end to Access database (with VBA)

I did it in one project of mine. I used MDB to store the data about bills and used Excel to render them, giving the user the possibility to adapt it.

In this case the best solution is:

  1. Not to use any ADO/DAO in Excel. I implemented everything as public functions in MDB modules and called them directly from Excel. You can return even complex data objects, like arrays of strings etc by calling MDB functions with necessary arguments. This is similar to client/server architecture of modern web applications: you web application just does the rendering and user interaction, database and middle tier is then on the server side.

  2. Use Excel forms for user interaction and for data visualisation.

  3. I usually have a very last sheet with some names regions for settings: the path to MDB files, some settings (current user, password if needed etc.) -- so you can easily adapt your Excel implementation to different location of you "back-end" data.

Select values from XML field in SQL Server 2008

MSSQL uses regular XPath rules as follows:

  • nodename Selects all nodes with the name "nodename"
  • / Selects from the root node
  • // Selects nodes in the document from the current node that match the selection no matter where they are
  • . Selects the current node
  • .. Selects the parent of the current node
  • @ Selects attributes

W3Schools

Continue For loop

This can also be solved using a boolean.

For Each rngCol In rngAll.Columns
    doCol = False '<==== Resets to False at top of each column
    For Each cell In Selection
        If cell.row = 1 Then
            If thisColumnShouldBeProcessed Then doCol = True
        End If
        If doCol Then
            'Do what you want to do to each cell in this column
        End If
    Next cell
Next rngCol

For example, here is the full example that:
(1) Identifies range of used cells on worksheet
(2) Loops through each column
(3) IF column title is an accepted title, Loops through all cells in the column

Sub HowToSkipForLoopIfConditionNotMet()
    Dim rngCol, rngAll, cell As Range, cnt As Long, doCol, cellValType As Boolean
    Set rngAll = Range("A1").CurrentRegion
    'MsgBox R.Address(0, 0), , "All data"
    cnt = 0
    For Each rngCol In rngAll.Columns
        rngCol.Select
        doCol = False
        For Each cell In Selection
            If cell.row = 1 Then
                If cell.Value = "AnAllowedColumnTitle" Then doCol = True
            End If
            If doCol Then '<============== THIS LINE ==========
                cnt = cnt + 1
                Debug.Print ("[" & cell.Value & "]" & " / " & cell.Address & " / " & cell.Column & " / " & cell.row)
                If cnt > 5 Then End '<=== NOT NEEDED. Just prevents too much demo output.
            End If
        Next cell
    Next rngCol
End Sub

Note: If you didn't immediately catch it, the line If docol Then is your inverted CONTINUE. That is, if doCol remains False, the script CONTINUES to the next cell and doesn't do anything.

Certainly not as fast/efficient as a proper continue or next for statement, but the end result is as close as I've been able to get.

VBA: Counting rows in a table (list object)

You need to go one level deeper in what you are retrieving.

Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects("MyTable")
MsgBox tbl.Range.Rows.Count
MsgBox tbl.HeaderRowRange.Rows.Count
MsgBox tbl.DataBodyRange.Rows.Count
Set tbl = Nothing

More information at:

ListObject Interface
ListObject.Range Property
ListObject.DataBodyRange Property
ListObject.HeaderRowRange Property

How do I show my global Git configuration?

You can use:

git config --list

or look at your ~/.gitconfig file. The local configuration will be in your repository's .git/config file.

Use:

git config --list --show-origin

to see where that setting is defined (global, user, repo, etc...)

What's the difference between event.stopPropagation and event.preventDefault?

stopPropagation prevents further propagation of the current event in the capturing and bubbling phases.

preventDefault prevents the default action the browser makes on that event.

Examples

preventDefault

_x000D_
_x000D_
$("#but").click(function (event) {
  event.preventDefault()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>
_x000D_
_x000D_
_x000D_

stopPropagation

_x000D_
_x000D_
$("#but").click(function (event) {
  event.stopPropagation()
})
$("#foo").click(function () {
  alert("parent click event fired!")
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="foo">
  <button id="but">button</button>
</div>
_x000D_
_x000D_
_x000D_

With stopPropagation, only the button's click handler is called while the div's click handler never fires.

Where as if you use preventDefault, only the browser's default action is stopped but the div's click handler still fires.

Below are some docs on the DOM event properties and methods from MDN:

For IE9 and FF you can just use preventDefault & stopPropagation.

To support IE8 and lower replace stopPropagation with cancelBubble and replace preventDefault with returnValue

Angular File Upload

Here is how I did it to upload the excel files:
Directory structure:

app
|-----uploadcomponent
           |-----uploadcomponent.module.ts
           |-----uploadcomponent.html
|-----app.module.ts
|-----app.component.ts
|-----app.service.ts

uploadcomponent.html

<div>
   <form [formGroup]="form" (ngSubmit)="onSubmit()">
     <input type="file" name="profile"  enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" />
     <button type="submit">Upload Template</button>
     <button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button> 
   </form>           
</div>

uploadcomponent.ts

    import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
    import { Component, OnInit } from '@angular/core';
    ....
    export class UploadComponent implements OnInit {
        form: FormGroup;
        constructor(private formBuilder: FormBuilder, private uploadService: AppService) {}
        ngOnInit() {  
            this.form = this.formBuilder.group({
               profile: ['']
            });
        }

        onChange(event) {
            if (event.target.files.length > 0) {
              const file = event.target.files[0];

              this.form.get('profile').setValue(file);
              console.log(this.form.get('profile').value)
            }
        }

        onSubmit() {
           const formData = new FormData();
           formData.append('file', this.form.get('profile').value);

           this.uploadService.upload(formData).subscribe(
             (res) => {
               this.response = res;

               console.log(res);

             },
             (err) => {  
               console.log(err);
             });
         }
    }

app.service.ts

    upload(formData) {
        const endpoint = this.service_url+'upload/';
        const httpOptions = headers: new HttpHeaders({    <<<< Changes are here
            'Authorization': 'token xxxxxxx'})
        };
        return this.http.post(endpoint, formData, httpOptions);
    }

In Backend I use DJango REST Framework.
models.py

from __future__ import unicode_literals
from django.db import models
from django.db import connection
from django_mysql.models import JSONField, Model
import uuid
import os


def change_filename(instance, filename):
    extension = filename.split('.')[-1]
    file_name = os.path.splitext(filename)[0]
    uuid_name = uuid.uuid4()
    return file_name+"_"+str(uuid_name)+"."+extension

class UploadTemplate (Model):
    id = models.AutoField(primary_key=True)
    file = models.FileField(blank=False, null=False, upload_to=change_filename)

    def __str__(self):
        return str(self.file.name)

views.py.

class UploadView(APIView):
    serializer_class = UploadSerializer
    parser_classes = [MultiPartParser]       

    def get_queryset(self):
        queryset = UploadTemplate.objects.all()
        return queryset

    def post(self, request, *args, **kwargs):
        file_serializer = UploadSerializer(data=request.data)
        status = None
        message = None
        if file_serializer.is_valid():
            file_serializer.save()
            status = "Success"
            message = "Success"
        else:
            status = "Failure"
            message = "Failure!"
        content = {'status': status, 'message': message}
        return Response(content)

serializers.py.

from uploadtemplate.models import UploadTemplate
from rest_framework import serializers

class UploadSerializer(serializers.ModelSerializer):
    class Meta:
        model = UploadTemplate
        fields = '__all__'   

urls.py.

router.register(r'uploadtemplate', uploadtemplateviews.UploadTemplateView, 
    base_name='UploadTemplate')
urlpatterns = [
    ....
    url(r'upload/', uploadtemplateviews.UploadTemplateView.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

MEDIA_URL and MEDIA_ROOT is defined in settings.py of the project.

Thanks!

android: stretch image in imageview to fit screen

use this:

ImageView.setAdjustViewBounds(true);

Combining (concatenating) date and time into a datetime

DECLARE @ADate Date, @ATime Time, @ADateTime Datetime

SELECT @ADate = '2010-02-20', @ATime = '18:53:00.0000000'

SET @ADateTime = CAST   (
    CONVERT(Varchar(10), @ADate, 112) + ' ' +   
    CONVERT(Varchar(8), @ATime) AS DateTime)

SELECT @ADateTime [A nice datetime :)]

This will render you a valid result.

Difference between jQuery .hide() and .css("display", "none")

jQuery('#id').css("display","block")

The display property can have many possible values, among which are block, inline, inline-block, and many more.

The .show() method doesn't set it necessarily to block, but rather resets it to what you defined it (if at all).

In the jQuery source code, you can see how they're setting the display property to "" (an empty string) to check what it was before any jQuery manipulation: little link.

On the other hand, hiding is done via display: none;, so you can consider .hide() and .css("display", "none") equivalent to some point.

It's recommended to use .show() and .hide() anyway to avoid any gotcha's (plus, they're shorter).

Including all the jars in a directory within the Java classpath

We get around this problem by deploying a main jar file myapp.jar which contains a manifest (Manifest.mf) file specifying a classpath with the other required jars, which are then deployed alongside it. In this case, you only need to declare java -jar myapp.jar when running the code.

So if you deploy the main jar into some directory, and then put the dependent jars into a lib folder beneath that, the manifest looks like:

Manifest-Version: 1.0
Implementation-Title: myapp
Implementation-Version: 1.0.1
Class-Path: lib/dep1.jar lib/dep2.jar

NB: this is platform-independent - we can use the same jars to launch on a UNIX server or on a Windows PC.

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

For SQL 2008 you can backup log to nul device:

BACKUP LOG [databaseName]
TO DISK = 'nul:' WITH STATS = 10

And then use DBCC SHRINKFILE to truncate the log file.

"Fade" borders in CSS

Add this class css to your style sheet

.border_gradient {
border: 8px solid #000;
-moz-border-bottom-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-top-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-left-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
-moz-border-right-colors:#897048 #917953 #a18a66 #b6a488 #c5b59b #d4c5ae #e2d6c4 #eae1d2;
padding: 5px 5px 5px 15px;
width: 300px;
}

set width to the width of your image. and use this html for image

<div class="border_gradient">
        <img src="image.png" />
</div>

though it may not give the same exact border, it will some gradient looks on the border.

source: CSS3 Borders

Sorting a List<int>

Sort list of int descending you could just sort first and reverse

class Program
{
    static void Main(string[] args)
    {

        List<int> myList = new List<int>();

        myList.Add(38);
        myList.Add(34);
        myList.Add(35);
        myList.Add(36);
        myList.Add(37);


        myList.Sort();
        myList.Reverse();
        myList.ForEach(Console.WriteLine);


    }



}

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I needed this, but the target process wasn't a child of current shell, in which case wait $PID doesn't work. I did find the following alternative instead:

while [ -e /proc/$PID ]; do sleep 0.1 ; done

That relies on the presence of procfs, which may not be available (Mac doesn't provide it for example). So for portability, you could use this instead:

while ps -p $PID >/dev/null ; do sleep 0.1 ; done

When to use margin vs padding in CSS

Here is some HTML that demonstrates how padding and margin affect clickability, and background filling. An object receives clicks to its padding, but clicks on an objects margin'd area go to its parent.

_x000D_
_x000D_
$(".outer").click(function(e) {_x000D_
  console.log("outer");_x000D_
  e.stopPropagation();_x000D_
});_x000D_
_x000D_
$(".inner").click(function(e) {_x000D_
  console.log("inner");_x000D_
  e.stopPropagation();_x000D_
});
_x000D_
.outer {_x000D_
  padding: 10px;_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  margin: 10px;_x000D_
  padding: 10px;_x000D_
  background: blue;_x000D_
  border: solid white 1px;_x000D_
}
_x000D_
<script src="http://code.jquery.com/jquery-latest.js"></script>_x000D_
_x000D_
<div class="outer">_x000D_
  <div class="inner" style="position:relative; height:0px; width:0px">_x000D_
_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Angular: How to update queryParams without changing route

First, we need to import the router module from angular router and declare its alias name

import { Router } from '@angular/router'; ---> import
class AbcComponent implements OnInit(){
constructor(
    private router: Router ---> decalre alias name
  ) { }
}

1. You can change query params by using "router.navigate" function and pass the query parameters

this.router.navigate([], { queryParams: {_id: "abc", day: "1", name: "dfd"} 
});

It will update query params in the current i.e activated route

  1. The below will redirect to abc page with _id, day and name as query params

    this.router.navigate(['/abc'], { queryParams: {_id: "abc", day: "1", name: "dfd"} });

    It will update query params in the "abc" route along with three query paramters

For fetching query params:-

    import { ActivatedRoute } from '@angular/router'; //import activated routed

    export class ABC implements OnInit {

    constructor(
        private route: ActivatedRoute //declare its alias name
      ) {}

    ngOnInit(){
       console.log(this.route.snapshot.queryParamMap.get('_id')); //this will fetch the query params
    }

How can I store HashMap<String, ArrayList<String>> inside a list?

Try the following:

List<Map<String, ArrayList<String>>> mapList = 
    new ArrayList<Map<String, ArrayList<String>>>();
mapList.add(map);

If your list must be of type List<HashMap<String, ArrayList<String>>>, then declare your map variable as a HashMap and not a Map.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

How to getElementByClass instead of GetElementById with JavaScript?

My solution:

First create "<style>" tags with an ID.

<style id="YourID">
    .YourClass {background-color:red}
</style>

Then, I create a function in JavaScript like this:

document.getElementById('YourID').innerHTML = '.YourClass {background-color:blue}'

Worked like a charm for me.

MySQL/SQL: Group by date only on a Datetime column

SELECT SUM(No), HOUR(dateofissue) 
FROM tablename 
WHERE dateofissue>='2011-07-30' 
GROUP BY HOUR(dateofissue)

It will give the hour by sum from a particular day!

Changing git commit message after push (given that no one pulled from remote)

additional information for same problem if you are using bitbucket pipeline

edit your message

git commit --amend

push to the sever

git push --force <repository> <branch>

then add --force to your push command on the pipeline

git ftp push --force

This will delete your previous commit(s) and push your current one.

remove the --force after first push

i tried it on bitbucket pipeline and its working fine

Spring RestTemplate GET with parameters

public static void main(String[] args) {
         HttpHeaders httpHeaders = new HttpHeaders();
         httpHeaders.set("Accept", MediaType.APPLICATION_JSON_VALUE);
         final String url = "https://host:port/contract/{code}";
         Map<String, String> params = new HashMap<String, String>();
         params.put("code", "123456");
         HttpEntity<?> httpEntity  = new HttpEntity<>(httpHeaders); 
         RestTemplate restTemplate  = new RestTemplate();
         restTemplate.exchange(url, HttpMethod.GET, httpEntity,String.class, params);
    }

How to pass a variable from Activity to Fragment, and pass it back?

thanks to @??s???? K and Terry ... it helps me a lot and works perfectly

From Activity you send data with intent as:

Bundle bundle = new Bundle(); 
bundle.putString("edttext", "From Activity"); 
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // get arguments
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

reference : Send data from activity to fragment in android

How/When does Execute Shell mark a build as failure in Jenkins?

In my opinion, turning off the -e option to your shell is a really bad idea. Eventually one of the commands in your script will fail due to transient conditions like out of disk space or network errors. Without -e Jenkins won't notice and will continue along happily. If you've got Jenkins set up to do deployment, that may result in bad code getting pushed and bringing down your site.

If you have a line in your script where failure is expected, like a grep or a find, then just add || true to the end of that line. That ensures that line will always return success.

If you need to use that exit code, you can either hoist the command into your if statement:

grep foo bar; if [ $? == 0 ]; then ...    -->   if grep foo bar; then ...

Or you can capture the return code in your || clause:

grep foo bar || ret=$?

Open fancybox from function

Here is working code as per the author's Tips & Tricks blog post, put it in document ready:

  $("#mybutton").click(function(){
    $(".fancybox").trigger('click');  
  })

This triggers the smaller version of the currently displayed image or content, as if you had clicked on it manually. It avoids initializing the Fancybox again, but instead keeps the parameters you initialized it with on document ready. If you need to do something different when opening the box with a separate button compared to clicking on the box, you will need the parameters, but for many, this will be what they were looking for.

Is there are way to make a child DIV's width wider than the parent DIV using CSS?

To make child div as wide as the content, try this:

.child{
    position:absolute;
    left:0;
    overflow:visible;
    white-space:nowrap;
}

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

I've just started using Typescript and I've been trying to solve a similar problem like this; how to tell the Typescript that I'm passing a callback without an interface.

After browsing a few answers on Stack Overflow and GitHub issues, I finally found a solution that may help anyone with the same problem.

A function's type can be defined with (arg0: type0) => returnType and we can use this type definition in another function's parameter list.

function runCallback(callback: (sum: number) => void, a: number, b: number): void {
    callback(a + b);
}

// Another way of writing the function would be:
// let logSum: (sum: number) => void = function(sum: number): void {
//     console.log(sum);
// };
function logSum(sum: number): void {
    console.log(`The sum is ${sum}.`);
}

runCallback(logSum, 2, 2);

How to playback MKV video in web browser?

<video controls width=800 autoplay>
    <source src="file path here">
</video>

This will display the video (.mkv) using Google Chrome browser only.

Converting A String To Hexadecimal In Java

Convert a letter in hex code and hex code in letter.

        String letter = "a";
    String code;
    int decimal;

    code = Integer.toHexString(letter.charAt(0));
    decimal = Integer.parseInt(code, 16);

    System.out.println("Hex code to " + letter + " = " + code);
    System.out.println("Char to " + code + " = " + (char) decimal);

What is this Javascript "require"?

So what is this "require?"

require() is not part of the standard JavaScript API. But in Node.js, it's a built-in function with a special purpose: to load modules.

Modules are a way to split an application into separate files instead of having all of your application in one file. This concept is also present in other languages with minor differences in syntax and behavior, like C's include, Python's import, and so on.

One big difference between Node.js modules and browser JavaScript is how one script's code is accessed from another script's code.

  • In browser JavaScript, scripts are added via the <script> element. When they execute, they all have direct access to the global scope, a "shared space" among all scripts. Any script can freely define/modify/remove/call anything on the global scope.

  • In Node.js, each module has its own scope. A module cannot directly access things defined in another module unless it chooses to expose them. To expose things from a module, they must be assigned to exports or module.exports. For a module to access another module's exports or module.exports, it must use require().

In your code, var pg = require('pg'); loads the pg module, a PostgreSQL client for Node.js. This allows your code to access functionality of the PostgreSQL client's APIs via the pg variable.

Why does it work in node but not in a webpage?

require(), module.exports and exports are APIs of a module system that is specific to Node.js. Browsers do not implement this module system.

Also, before I got it to work in node, I had to do npm install pg. What's that about?

NPM is a package repository service that hosts published JavaScript modules. npm install is a command that lets you download packages from their repository.

Where did it put it, and how does Javascript find it?

The npm cli puts all the downloaded modules in a node_modules directory where you ran npm install. Node.js has very detailed documentation on how modules find other modules which includes finding a node_modules directory.

A more useful statusline in vim?

Edit:-

Note vim-airline is gaining some traction as the new vimscript option as powerline has gone python.


Seems powerline is where it is at these days:-

Normal status line

powerline

Customised status lines for other plugins (e.g. ctrlp)

powerline

What is the difference between a static and const variable?

A static variable can get an initial value only one time. This means that if you have code such as "static int a=0" in a sample function, and this code is executed in a first call of this function, but not executed in a subsequent call of the function; variable (a) will still have its current value (for example, a current value of 5), because the static variable gets an initial value only one time.

A constant variable has its value constant in whole of the code. For example, if you set the constant variable like "const int a=5", then this value for "a" will be constant in whole of your program.

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

How to convert HH:mm:ss.SSS to milliseconds?

If you want to use SimpleDateFormat, you could write:

private final SimpleDateFormat sdf =
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    { sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }

private long parseTimeToMillis(final String time) throws ParseException
    { return sdf.parse("1970-01-01 " + time).getTime(); }

But a custom method would be much more efficient. SimpleDateFormat, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)

Also, SimpleDateFormat is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)

Personally, I'd probably write a custom method.

Batch Files - Error Handling

A successful ping on your local network can be trapped using ERRORLEVEL.

@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT

How to convert string to boolean php

you can use json_decode to decode that boolean

$string = 'false';
$boolean = json_decode($string);
if($boolean) {
  // Do something
} else {
  //Do something else
}

How do I update the element at a certain position in an ArrayList?

arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.

notify is optional, depends on conditions.

How to upload files to server using Putty (ssh)

Use WinSCP for file transfer over SSH, putty is only for SSH commands.

Giving multiple URL patterns to Servlet Filter

If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

You need to prefix your URL patterns with /faces/Html as well like so:

<url-pattern>/faces/Html/Admin/*</url-pattern>

You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

<filter-mapping>
    <filter-name>LoginFilter</filter-name>
    <url-pattern>/faces/Html/Employee/*</url-pattern>
    <url-pattern>/faces/Html/Admin/*</url-pattern>
    <url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>

Are there dictionaries in php?

Normal array can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.

$names = [
    'bob' => 27,
    'billy' => 43,
    'sam' => 76,
];

$names['bob'];

And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject or you can use SplObjectStorage class which is map (dictionary) implementation allowing objects to be assigned as keys.

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

wordpress contactform7 textarea cols and rows change in smaller screens

I was able to get this work. I added the following to my custom CSS:

.wpcf7-form textarea{ 
    width: 100% !important;
    height:50px;
}

Refresh certain row of UITableView based on Int in Swift

SWIFT 4.2

    func reloadYourRows(name: <anyname>) {
    let row = <your array name>.index(of: <name passing in>)
    let reloadPath = IndexPath(row: row!, section: 0)
    tableView.reloadRows(at: [reloadPath], with: .middle)
    }

How to terminate a process in vbscript

The Win32_Process class provides access to both 32-bit and 64-bit processes when the script is run from a 64-bit command shell.

If this is not an option for you, you can try using the taskkill command:

Dim oShell : Set oShell = CreateObject("WScript.Shell")

' Launch notepad '
oShell.Run "notepad"
WScript.Sleep 3000

' Kill notepad '
oShell.Run "taskkill /im notepad.exe", , True

How to perform keystroke inside powershell?

function Do-SendKeys {
    param (
        $SENDKEYS,
        $WINDOWTITLE
    )
    $wshell = New-Object -ComObject wscript.shell;
    IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
    Sleep 1
    IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'

How can I get date and time formats based on Culture Info?

Try setting a custom CultureInfo for CurrentCulture and CurrentUICulture:

Globalization.CultureInfo customCulture = new Globalization.CultureInfo("en-US", true);

customCulture.DateTimeFormat.ShortDatePattern = "yyyy-MM-dd h:mm tt";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = customCulture;

DateTime newDate = System.Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd h:mm tt"));

jQuery Dialog Box

I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.

The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.

So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!

<script type="text/javascript"> 
        jQuery(document).ready( function(){       
            jQuery("#myButton").click( showDialog );

            //variable to reference window
            $myWindow = jQuery('#myDiv');

            //instantiate the dialog
            $myWindow.dialog({ height: 350,
                width: 400,
                modal: true,
                position: 'center',
                autoOpen:false,
                title:'Hello World',
                overlay: { opacity: 0.5, background: 'black'}
                });
            }

        );
    //function to show dialog   
    var showDialog = function() {
        //if the contents have been hidden with css, you need this
        $myWindow.show(); 
        //open the dialog
        $myWindow.dialog("open");
        }

    //function to close dialog, probably called by a button in the dialog
    var closeDialog = function() {
        $myWindow.dialog("close");
    }


</script>
</head>

<body>

<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
    <p>I am a modal dialog</p>
</div>

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

Response you are getting is in object form i.e.

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

Replace below line of code :

List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))

with

Post post = gson.fromJson(reader, Post.class);

SQL - Create view from multiple tables

Union is not what you want. You want to use joins to create single rows. It's a little unclear what constitutes a unique row in your tables and how they really relate to each other and it's also unclear if one table will have rows for every country in every year. But I think this will work:

CREATE VIEW V AS (

  SELECT i.country,i.year,p.pop,f.food,i.income FROM
    INCOME i
  LEFT JOIN 
    POP p 
  ON
    i.country=p.country
  LEFT JOIN
    Food f
  ON 
    i.country=f.country
  WHERE 
    i.year=p.year
  AND
    i.year=f.year
);

The left (outer) join will return rows from the first table even if there are no matches in the second. I've written this assuming you would have a row for every country for every year in the income table. If you don't things get a bit hairy as MySQL does not have built in support for FULL OUTER JOINs last I checked. There are ways to simulate it, and they would involve unions. This article goes into some depth on the subject: http://www.xaprb.com/blog/2006/05/26/how-to-write-full-outer-join-in-mysql/

How can I show the table structure in SQL Server query?

Another way is,

mysql > SHOW CREATE TABLE my_db.my_table;

You should get the table name and create table sql

How to use a decimal range() step value?

Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.

You can use the linspace function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain). linspace takes a number of points to return, and also lets you specify whether or not to include the right endpoint:

>>> np.linspace(0,1,11)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

If you really want to use a floating-point step value, you can, with numpy.arange.

>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes arange to produce a length-4 array when it should only produce 3 numbers:

>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])

Sleep function in C++

On Unix, include #include <unistd.h>.

The call you're interested in is usleep(). Which takes microseconds, so you should multiply your millisecond value by 1000 and pass the result to usleep().

Finding the number of days between two dates

Convert your dates to unix timestamps, then substract one from the another. That will give you the difference in seconds, which you divide by 86400 (amount of seconds in a day) to give you an approximate amount of days in that range.

If your dates are in format 25.1.2010, 01/25/2010 or 2010-01-25, you can use the strtotime function:

$start = strtotime('2010-01-25');
$end = strtotime('2010-02-20');

$days_between = ceil(abs($end - $start) / 86400);

Using ceil rounds the amount of days up to the next full day. Use floor instead if you want to get the amount of full days between those two dates.

If your dates are already in unix timestamp format, you can skip the converting and just do the $days_between part. For more exotic date formats, you might have to do some custom parsing to get it right.

There is already an object named in the database

it seems there is a problem in migration process, run add-migration command in "Package Manager Console":

Add-Migration Initial -IgnoreChanges

do some changes, and then update database from "Initial" file:

Update-Database -verbose

Edit: -IgnoreChanges is in EF6 but not in EF Core, here's a workaround: https://stackoverflow.com/a/43687656/495455

How to rollback just one step using rake db:migrate

Roll back the most recent migration:

rake db:rollback

Roll back the n most recent migrations:

rake db:rollback STEP=n

You can find full instructions on the use of Rails migration tasks for rake on the Rails Guide for running migrations.


Here's some more:

  • rake db:migrate - Run all migrations that haven't been run already
  • rake db:migrate VERSION=20080906120000 - Run all necessary migrations (up or down) to get to the given version
  • rake db:migrate RAILS_ENV=test - Run migrations in the given environment
  • rake db:migrate:redo - Roll back one migration and run it again
  • rake db:migrate:redo STEP=n - Roll back the last n migrations and run them again
  • rake db:migrate:up VERSION=20080906120000 - Run the up method for the given migration
  • rake db:migrate:down VERSION=20080906120000 - Run the down method for the given migration

And to answer your question about where you get a migration's version number from:

The version is the numerical prefix on the migration's filename. For example, to migrate to version 20080906120000 run

$ rake db:migrate VERSION=20080906120000

(From Running Migrations in the Rails Guides)

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

tl;dr

The other Answers are outmoded as of Java 8.

Instant                           // Represent a moment in UTC. 
.parse( "2013-09-29T18:46:19Z" )  // Parse text in standard ISO 8601 format where the `Z` means UTC, pronounces “Zulu”.
.atZone(                          // Adjust from UTC to a time zone. 
    ZoneId.of( "Asia/Kolkata" )
)                                 // Returns a `ZonedDateTime` object. 

ISO 8601

Your string format happens to comply with the ISO 8601 standard. This standard defines sensible formats for representing various date-time values as text.

java.time

The old java.util.Date/.Calendar and java.text.SimpleDateFormat classes have been supplanted by the java.time framework built into Java 8 and later. See Tutorial. Avoid the old classes as they have proven to be poorly designed, confusing, and troublesome.

Part of the poor design in the old classes has bitten you, where the toString method applies the JVM's current default time zone when generating a text representation of the date-time value that is actually in UTC (GMT); well-intentioned but confusing.

The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to specify a parsing pattern.

An Instant is a moment on the timeline in UTC.

Instant instant = Instant.parse( "2013-09-29T18:46:19Z" );

You can apply a time zone as needed to produce a ZonedDateTime object.

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

Table of date-time types in Java, both modern and legacy

Set up a scheduled job?

One solution that I have employed is to do this:

1) Create a custom management command, e.g.

python manage.py my_cool_command

2) Use cron (on Linux) or at (on Windows) to run my command at the required times.

This is a simple solution that doesn't require installing a heavy AMQP stack. However there are nice advantages to using something like Celery, mentioned in the other answers. In particular, with Celery it is nice to not have to spread your application logic out into crontab files. However the cron solution works quite nicely for a small to medium sized application and where you don't want a lot of external dependencies.

EDIT:

In later version of windows the at command is deprecated for Windows 8, Server 2012 and above. You can use schtasks.exe for same use.

**** UPDATE **** This the new link of django doc for writing the custom management command

Check if inputs form are empty jQuery

You can do it using simple jQuery loop.

Total code

<!DOCTYPE html>
 <html lang="en">
  <head>
   <meta charset="UTF-8">
   <title></title>
  <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
  <style>
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{display:inline-block;height:20px;padding:4px;margin-bottom:9px;font-size:13px;line-height:18px;color:#555555;}
textarea{height:auto;}
select,textarea,input[type="text"],input[type="password"],input[type="datetime"],input[type="datetime-local"],input[type="date"],input[type="month"],input[type="time"],input[type="week"],input[type="number"],input[type="email"],input[type="url"],input[type="search"],input[type="tel"],input[type="color"],.uneditable-input{background-color:#ffffff;border:1px solid #cccccc;-webkit-border-radius:3px;-moz-border-radius:3px;border-radius:3px;-webkit-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-moz-box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);-webkit-transition:border linear 0.2s,box-shadow linear 0.2s;-moz-transition:border linear 0.2s,box-shadow linear 0.2s;-ms-transition:border linear 0.2s,box-shadow linear 0.2s;-o-transition:border linear 0.2s,box-shadow linear 0.2s;transition:border linear 0.2s,box-shadow linear 0.2s;}textarea:focus,input[type="text"]:focus,input[type="password"]:focus,input[type="datetime"]:focus,input[type="datetime-local"]:focus,input[type="date"]:focus,input[type="month"]:focus,input[type="time"]:focus,input[type="week"]:focus,input[type="number"]:focus,input[type="email"]:focus,input[type="url"]:focus,input[type="search"]:focus,input[type="tel"]:focus,input[type="color"]:focus,.uneditable-input:focus{border-color:rgba(82, 168, 236, 0.8);outline:0;outline:thin dotted \9;-webkit-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);-moz-box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);box-shadow:inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6);height: 20px;}
select,input[type="radio"],input[type="checkbox"]{margin:3px 0;*margin-top:0;line-height:normal;cursor:pointer;}
select,input[type="submit"],input[type="reset"],input[type="button"],input[type="radio"],input[type="checkbox"]{width:auto;}
.uneditable-textarea{width:auto;height:auto;}
#country{height: 30px;}
.highlight
{
    border: 1px solid red !important;
}
</style>
<script>
function test()
{
var isFormValid = true;

$(".bs-example input").each(function(){
    if ($.trim($(this).val()).length == 0){
        $(this).addClass("highlight");
        isFormValid = false;
        $(this).focus();
    }
    else{
        $(this).removeClass("highlight");
     }
    });

    if (!isFormValid) { 
    alert("Please fill in all the required fields (indicated by *)");
}

return isFormValid;
}   
</script>
</head>
<body>
<div class="bs-example">
<form onsubmit="return test()">
    <div class="form-group">
        <label for="inputEmail">Email</label>
        <input type="text" class="form-control" id="inputEmail" placeholder="Email">
    </div>
    <div class="form-group">
        <label for="inputPassword">Password</label>
        <input type="password" class="form-control" id="inputPassword" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>

Using an authorization header with Fetch in React Native

completed = (id) => {
    var details = {
        'id': id,

    };

    var formBody = [];
    for (var property in details) {
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
    formBody = formBody.join("&");

    fetch(markcompleted, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: formBody
    })
        .then((response) => response.json())
        .then((responseJson) => {
            console.log(responseJson, 'res JSON');
            if (responseJson.status == "success") {
                console.log(this.state);
                alert("your todolist is completed!!");
            }
        })
        .catch((error) => {
            console.error(error);
        });
};

OpenCV - DLL missing, but it's not?

No need to do any of that. It is a visual studio error.

just go here: http://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=31354

and download the appropriate fix for your computer's OS

close visual studio, run the fix and then restart VS

The code should run without any error.

How can I turn a JSONArray into a JSONObject?

Can't you originally get the data as a JSONObject?

Perhaps parse the string as both a JSONObject and a JSONArray in the first place? Where is the JSON string coming from?

I'm not sure that it is possible to convert a JsonArray into a JsonObject.

I presume you are using the following from json.org

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

Get the current fragment object

Maybe the simplest way is:

public MyFragment getVisibleFragment(){
    FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
    List<Fragment> fragments = fragmentManager.getFragments();
    for(Fragment fragment : fragments){
        if(fragment != null && fragment.getUserVisibleHint())
            return (MyFragment)fragment;
    }
    return null;
}

It worked for me

What are the differences between B trees and B+ trees?

In B+ Tree, since only pointers are stored in the internal nodes, their size becomes significantly smaller than the internal nodes of B tree (which store both data+key). Hence, the indexes of the B+ tree can be fetched from the external storage in a single disk read, processed to find the location of the target. If it has been a B tree, a disk read is required for each and every decision making process. Hope I made my point clear! :)

How do change the color of the text of an <option> within a <select>?

Here is my demo with jQuery

<!doctype html>
<html>
<head>
<style>
    select{
        color:#aaa;
    }
    option:not(first-child) {
        color: #000;
    }
</style>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("select").change(function(){
            if ($(this).val()=="") $(this).css({color: "#aaa"});
            else $(this).css({color: "#000"});
        });
    }); 
</script>
<meta charset="utf-8">
</head>
<body>
<select>
    <option disable hidden value="">CHOOSE</option>
    <option>#1</option>
    <option>#2</option>
    <option>#3</option>
    <option>#4</option>
</select>
</body>
</html> 

https://jsfiddle.net/monster75/cnt73375/1/

How could I use requests in asyncio?

DISCLAMER: Following code creates different threads for each function.

This might be useful for some of the cases as it is simpler to use. But know that it is not async but gives illusion of async using multiple threads, even though decorator suggests that.

To make any function non blocking, simply copy the decorator and decorate any function with a callback function as parameter. The callback function will receive the data returned from the function.

import asyncio
import requests


def run_async(callback):
    def inner(func):
        def wrapper(*args, **kwargs):
            def __exec():
                out = func(*args, **kwargs)
                callback(out)
                return out

            return asyncio.get_event_loop().run_in_executor(None, __exec)

        return wrapper

    return inner


def _callback(*args):
    print(args)


# Must provide a callback function, callback func will be executed after the func completes execution !!
@run_async(_callback)
def get(url):
    return requests.get(url)


get("https://google.com")
print("Non blocking code ran !!")

Fill username and password using selenium in python

I am new to selenium and I tried all solutions above but they don't work. Finally, I tried this manually by

driver = webdriver.Firefox()
import time

driver.get(url)

time.sleep(20)

print (driver.page_source.encode("utf-8"))

Then I could get contents from web.

SQL query for finding records where count > 1

I wouldn't recommend the HAVING keyword for newbies, it is essentially for legacy purposes.

I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:

I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.

So I've taken a literal interpretation.

The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES but it could be a VIEW:

WITH PAYMENT_TALLIES (user_id, zip, tally)
     AS
     (
      SELECT user_id, zip, COUNT(*) AS tally
        FROM PAYMENT
       GROUP 
          BY user_id, zip
     )
SELECT DISTINCT *
  FROM PAYMENT AS P
 WHERE EXISTS (
               SELECT * 
                 FROM PAYMENT_TALLIES AS PT
                WHERE P.user_id = PT.user_id
                      AND PT.tally > 1
              );

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

Here are two other solutions

When a module is not yours - try to install types from @types:

npm install -D @types/module-name

If the above install errors - try changing import statements to require:

// import * as yourModuleName from 'module-name';
const yourModuleName = require('module-name');

How do I convert a String object into a Hash object?

This short little snippet will do it, but I can't see it working with a nested hash. I think it's pretty cute though

STRING.gsub(/[{}:]/,'').split(', ').map{|h| h1,h2 = h.split('=>'); {h1 => h2}}.reduce(:merge)

Steps 1. I eliminate the '{','}' and the ':' 2. I split upon the string wherever it finds a ',' 3. I split each of the substrings that were created with the split, whenever it finds a '=>'. Then, I create a hash with the two sides of the hash I just split apart. 4. I am left with an array of hashes which I then merge together.

EXAMPLE INPUT: "{:user_id=>11, :blog_id=>2, :comment_id=>1}" RESULT OUTPUT: {"user_id"=>"11", "blog_id"=>"2", "comment_id"=>"1"}

BeautifulSoup: extract text from anchor tag

>>> txt = '<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a> '
>>> fragment = bs4.BeautifulSoup(txt)
>>> fragment
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a> 
>>> fragment.find('a', {'class': 'title'})
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a>
>>> fragment.find('a', {'class': 'title'}).string
u'Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)'

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

Set disable attribute based on a condition for Html.TextBoxFor

if you dont want to use Html Helpers take look it my solution

disabled="@(your Expression that returns true or false")"

that it

@{
    bool isManager = (Session["User"] as User).IsManager;
}
<textarea rows="4" name="LetterManagerNotes" disabled="@(!isManager)"></textarea>

and I think the better way to do it is to do that check in the controller and save it within a variable that is accessible inside the view(Razor engine) in order to make the view free from business logic

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Close popup window

You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :

window.open

then

window.close

will work. Or else not.

Calling multiple JavaScript functions on a button click

It isn't getting called because you have a return statement above it. In the following code:

function test(){
  return 1;
  doStuff();
}

doStuff() will never be called. What I would suggest is writing a wrapper function

function wrapper(){
   if (validateView()){
     showDiv();
     return true;
   }
}

and then call the wrapper function from your onclick handler.

How to style SVG <g> element?

You cannot add style to an SVG <g> element. Its only purpose is to group children. That means, too, that style attributes you give to it are given down to its children, so a fill="green" on the <g> means an automatic fill="green" on its child <rect> (as long as it has no own fill specification).

Your only option is to add a new <rect> to the SVG and place it accordingly to match the <g> children's dimensions.

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I found the answer!

I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).

The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS

#ActionBox {
  position: relative;
  float: right;
}

Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)

I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.

ComboBox- SelectionChanged event has old value, not new value

Use the DropDownClosed event instead of selectionChanged if you want the current value of the combo box.

private void comboBox_DropDownClosed(object sender, EventArgs e)
{
   MessageBox.Show(comboBox.Text) 
}

Is really that simple.

Python error when trying to access list by index - "List indices must be integers, not str"

A list is a chain of spaces that can be indexed by (0, 1, 2 .... etc). So if players was a list, players[0] or players[1] would have worked. If players is a dictionary, players["name"] would have worked.

take(1) vs first()

Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

first vs take vs single operators comparison

* Legend:
--o-- value
----! error
----| completion

Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

Already having all the answers, I wanted to add a more visual explanation

Hope it helps someone

C++ calling base class constructors

Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

class A {..}
class B : A {...}
class C : B {...}
C c;

When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

Derived() : Base(5)
{      
}

If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

The declared package does not match the expected package ""

I was using Spring Tool Suite 4. Not able to figure out the issue. The directory structure was according to the package name.

But cleaning the project helped me.

How do I draw a set of vertical lines in gnuplot?

From the Gnuplot documentation. To draw a vertical line from the bottom to the top of the graph at x=3, use:

set arrow from 3, graph 0 to 3, graph 1 nohead

How to add a line break in an Android TextView?

ok figured it out:

<string name="sample_string"><![CDATA[some test line 1 <br />some test line 2]]></string>

so wrap in CDATA is necessary and breaks added inside as html tags

How to automatically select all text on focus in WPF TextBox?

Donnelle's answer works the best, but having to derive a new class to use it is a pain.

Instead of doing that I register handlers the handlers in App.xaml.cs for all TextBoxes in the application. This allows me to use a Donnelle's answer with standard TextBox control.

Add the following methods to your App.xaml.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e) 
    {
        // Select the text in a TextBox when it receives focus.
        EventManager.RegisterClassHandler(typeof(TextBox), TextBox.PreviewMouseLeftButtonDownEvent,
            new MouseButtonEventHandler(SelectivelyIgnoreMouseButton));
        EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotKeyboardFocusEvent, 
            new RoutedEventHandler(SelectAllText));
        EventManager.RegisterClassHandler(typeof(TextBox), TextBox.MouseDoubleClickEvent,
            new RoutedEventHandler(SelectAllText));
        base.OnStartup(e); 
    }

    void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
    {
        // Find the TextBox
        DependencyObject parent = e.OriginalSource as UIElement;
        while (parent != null && !(parent is TextBox))
            parent = VisualTreeHelper.GetParent(parent);

        if (parent != null)
        {
            var textBox = (TextBox)parent;
            if (!textBox.IsKeyboardFocusWithin)
            {
                // If the text box is not yet focused, give it the focus and
                // stop further processing of this click event.
                textBox.Focus();
                e.Handled = true;
            }
        }
    }

    void SelectAllText(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    }
}

How to use a table type in a SELECT FROM statement?

In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;

In package body:

initialize the table in declarations:

exch_rt exch_tbl := exch_tbl();

in order to add record to the local collection, in begin - end block you can do:

exch_rt.extend;
                                one_row.exch_rt_usd := 2;
                                one_row.exch_rt_eur := 1;
                                one_row.currency_cd := 'dollar';
                                exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop 

in order to get data from this table , inside package body you can use:

select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)

enjoy!

P.S. sorry for a late answer :D

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

ETag vs Header Expires

Another summary:

You need to use both. ETags are a "server side" information. Expires are a "Client side" caching.

  • Use ETags except if you have a load-balanced server. They are safe and will let clients know they should get new versions of your server files every time you change something on your side.

  • Expires must be used with caution, as if you set a expiration date far in the future but want to change one of the files immediatelly (a JS file for instance), some users may not get the modified version until a long time!

How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)

I'm developing with android studio 2+.

to create class diagrams I did the following: - install "ObjectAid UML Explorer" as plugin for eclipse(in my case luna with android sdk but works with younger versions as well) ... go to eclipse marketplace and search for "ObjectAid UML Explorer". it's further down in the search results. after installation and restart of eclipse ...

open an empty android or what-ever-java-project in eclipse. then right click on the empty eclipse project in the project explorer -> select 'build path' then I link my ANDROID STUDIO SRC PATH into my eclipse android project. doesn't matter if there are errors. again right click on the eclipse-android project and select: New in the filter type 'class' then you should see among others an option 'class diagram' ... select it and confgure it ... png stuff, visibility, etc. drag/drop your ANDROID STUDIO project classes into the open diagram -> voila :)

hth

I open eclipse(luna, but that doesn't matter). I got the "ObjectAid UML Explorer"
that installed I open an empty android project oin eclipse, right

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

What is Join() in jQuery?

A practical example using a jQuery example might be

 var today = new Date();
 $('#'+[today.getMonth()+1, today.getDate(), today.getFullYear()].join("_")).whatever();

I do that in a calendar tool that I am using, this way on the page load, I can do certain things with today's date.

Does Java support default parameter values?

As Scala was mentioned, Kotlin is also worth mentioning. In Kotlin function parameters can have default values as well and they can even refer to other parameters:

fun read(b: Array<Byte>, off: Int = 0, len: Int = b.size) {
    ...
}

Like Scala, Kotlin runs on the JVM and can be easily integrated into existing Java projects.

Rails migration for change column

I think this should work.

change_column :table_name, :column_name, :date

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How do I integrate Ajax with Django applications?

I am writing this because the accepted answer is pretty old, it needs a refresher.

So this is how I would integrate Ajax with Django in 2019 :) And lets take a real example of when we would need Ajax :-

Lets say I have a model with registered usernames and with the help of Ajax I wanna know if a given username exists.

html:

<p id="response_msg"></p> 
<form id="username_exists_form" method='GET'>
      Name: <input type="username" name="username" />
      <button type='submit'> Check </button>           
</form>   

ajax:

$('#username_exists_form').on('submit',function(e){
    e.preventDefault();
    var username = $(this).find('input').val();
    $.get('/exists/',
          {'username': username},   
          function(response){ $('#response_msg').text(response.msg); }
    );
}); 

urls.py:

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('exists/', views.username_exists, name='exists'),
]

views.py:

def username_exists(request):
    data = {'msg':''}   
    if request.method == 'GET':
        username = request.GET.get('username').lower()
        exists = Usernames.objects.filter(name=username).exists()
        if exists:
            data['msg'] = username + ' already exists.'
        else:
            data['msg'] = username + ' does not exists.'
    return JsonResponse(data)

Also render_to_response which is deprecated and has been replaced by render and from Django 1.7 onwards instead of HttpResponse we use JsonResponse for ajax response. Because it comes with a JSON encoder, so you don’t need to serialize the data before returning the response object but HttpResponse is not deprecated.

Undefined reference to `sin`

I had the same problem, which went away after I listed my library last: gcc prog.c -lm

Python sum() function with list parameter

In the last answer, you don't need to make a list from numbers; it is already a list:

numbers = [1, 2, 3]
numsum = sum(numbers)
print(numsum)

HttpListener Access Denied

Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?

You can't, it has to start with elevated privileges. You can restart it with the runas verb, which will prompt the user to switch to admin mode

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}

EDIT: actually, that's not true; HttpListener can run without elevated privileges, but you need to give permission for the URL on which you want to listen. See Darrel Miller's answer for details.

Foreach value from POST from form

Use array-like fields:

<input name="name_for_the_items[]"/>

You can loop through the fields:

foreach($_POST['name_for_the_items'] as $item)
{
  //do something with $item
}

Replace forward slash "/ " character in JavaScript string?

Area.replace(new RegExp(/\//g), '-') replaces multiple forward slashes (/) with -

Posting parameters to a url using the POST method without using a form

cURL is an option, using Ajax as well eventhough solving back-end problems with the front-end isn't so neat.

A very useful post about doing it without cURL is this one: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl

The code to do this (untested, unimproved, from the blog post):

function do_post_request($url, $data, $optional_headers = null)
{
   $params = array('http' => array(
                'method' => 'POST',
                'content' => $data
             ));
   if ($optional_headers !== null) {
      $params['http']['header'] = $optional_headers;
   }
   $ctx = stream_context_create($params);
   $fp = @fopen($url, 'rb', false, $ctx);
   if (!$fp) {
      throw new Exception("Problem with $url, $php_errormsg");
   }
   $response = @stream_get_contents($fp);
   if ($response === false) {
      throw new Exception("Problem reading data from $url, $php_errormsg");
   }
   return $response;
}

Multiple argument IF statement - T-SQL

That's the way to create complex boolean expressions: combine them with AND and OR. The snippet you posted doesn't throw any error for the IF.

In PANDAS, how to get the index of a known value?

To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...

So, applied to your dataframe:

In [1]: a[a['c2'] == 1].index[0]     In [2]: a[a['c1'] > 7].index[0]   
Out[1]: 0                            Out[2]: 4                         

Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]

In [3]: a[a['c2'] >= 7].index[1]     In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]  
Out[3]: 4                            Out[4]: 3 

php form action php self

How about leaving it empty, what is wrong with that?

<form name="form1" id="mainForm" method="post" enctype="multipart/form-data" action="">

</form>

Also, you can omit the action attribute and it will work as expected.

How do you check "if not null" with Eloquent?

If someone like me want to do it with query builder in Laravel 5.2.23 it can be done like ->

 $searchResultQuery = Users::query(); 
 $searchResultQuery->where('status_message', '<>', '', 'and'); // is not null
 $searchResultQuery->where('is_deleted', 'IS NULL', null, 'and'); // is null 

Or with scope in model :

public function scopeNotNullOnly($query){

    return $query->where('status_message', '<>', '');
}

jQuery posting JSON

In case you are sending this post request to a cross domain, you should check out this link.

https://stackoverflow.com/a/1320708/969984

Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

How to delete a module in Android Studio

Assuming the following:

  • You are working with Android Studio 1.2.1 or 1.2.2 (I don't have the latest yet, will edit this again when I do).
  • Your Project Tool Window is displaying one of the following views: "Project", "Packages", "Android" or "Project Files"

You can delete an Android Studio module as follows:

  1. In the Project Tool Window click the module you want to delete.
  2. Between the Tool Bar and the Project Tool Window the tool bar you will see two "chips" that represent the path to the selected module, similar to: your-project-name > selected-module-name
  3. Right click on the selected-module-name chip. A context menu with multiple sections will appear. In the third section from the bottom there will be a section that contains "Reformat Code..", "Optimize Imports..." and "Delete".
  4. Select "Delete" and follow any prompts.

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)

Image library for Python 3

You can use my package mahotas on Python 3. It is numpy-based rather than PIL based.

Get single listView SelectedItem

I do this like that:

if (listView1.SelectedItems.Count > 0)
{
     var item = listView1.SelectedItems[0];
     //rest of your logic
}

Asynchronous method call in Python?

You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:

apply_async(func[, args[, kwds[, callback]]])

E.g.:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

Dynamically update values of a chartjs chart

Update: Looks like chartjs has been updated (see comment below). There are some examples up that look very nice:

  1. Here's an example of updating a line chart using new data: http://jsbin.com/yitep/5/edit
  2. Here's how we can update existing data on a line chart: http://jsbin.com/yitep/4/edit

Original Post

As of Nov 2013, there seem to be very few options for updating charts.

There is a good example here (duplicated below) of adding new points to a line chart. Still kind of jumpy but not too bad. However, I think the effect probably depends on the chart you are using.

It does look like this is somewhere in the development pipeline. I don't see any indication of a release date yet though: https://github.com/nnnick/Chart.js/issues/13 [Closed as of Jul 26, 2014]

JS

$(document).ready(function(){
  var count = 10;
  var data = {
      labels : ["1","2","3","4","5", "6", "7", "8", "9", "10"],
        datasets : [
          {
                fillColor : "rgba(220,220,220,0.5)",
                strokeColor : "rgba(220,220,220,1)",
                pointColor : "rgba(220,220,220,1)",
                pointStrokeColor : "#fff",
                data : [65,59,90,81,56,45,30,20,3,37]
            },
            {
                fillColor : "rgba(151,187,205,0.5)",
                strokeColor : "rgba(151,187,205,1)",
                pointColor : "rgba(151,187,205,1)",
                pointStrokeColor : "#fff",
                data : [28,48,40,19,96,87,66,97,92,85]
            }
        ]
  }
  // this is ugly, don't judge me
  var updateData = function(oldData){
    var labels = oldData["labels"];
    var dataSetA = oldData["datasets"][0]["data"];
    var dataSetB = oldData["datasets"][1]["data"];

    labels.shift();
    count++;
    labels.push(count.toString());
    var newDataA = dataSetA[9] + (20 - Math.floor(Math.random() * (41)));
    var newDataB = dataSetB[9] + (20 - Math.floor(Math.random() * (41)));
    dataSetA.push(newDataA);
    dataSetB.push(newDataB);
    dataSetA.shift();
    dataSetB.shift();    };

  var optionsAnimation = {
    //Boolean - If we want to override with a hard coded scale
    scaleOverride : true,
    //** Required if scaleOverride is true **
    //Number - The number of steps in a hard coded scale
    scaleSteps : 10,
    //Number - The value jump in the hard coded scale
    scaleStepWidth : 10,
    //Number - The scale starting value
    scaleStartValue : 0
  }

  // Not sure why the scaleOverride isn't working...
  var optionsNoAnimation = {
    animation : false,
    //Boolean - If we want to override with a hard coded scale
    scaleOverride : true,
    //** Required if scaleOverride is true **
    //Number - The number of steps in a hard coded scale
    scaleSteps : 20,
    //Number - The value jump in the hard coded scale
    scaleStepWidth : 10,
    //Number - The scale starting value
    scaleStartValue : 0
  }

  //Get the context of the canvas element we want to select
  var ctx = document.getElementById("myChart").getContext("2d");
  var optionsNoAnimation = {animation : false}
  var myNewChart = new Chart(ctx);
  myNewChart.Line(data, optionsAnimation);  

  setInterval(function(){
    updateData(data);
    myNewChart.Line(data, optionsNoAnimation)
    ;}, 2000
  );
});


// ChartJS
var Chart=function(s){function v(a,c,b){a=A((a-c.graphMin)/(c.steps*c.stepValue),1,0);return b*c.steps*a}function x(a,c,b,e){function h(){g+=f;var k=a.animation?A(d(g),null,0):1;e.clearRect(0,0,q,u);a.scaleOverlay?(b(k),c()):(c(),b(k));if(1>=g)D(h);else if("function"==typeof a.onAnimationComplete)a.onAnimationComplete()}var f=a.animation?1/A(a.animationSteps,Number.MAX_VALUE,1):1,d=B[a.animationEasing],g=a.animation?0:1;"function"!==typeof c&&(c=function(){});D(h)}function C(a,c,b,e,h,f){var d;a=
Math.floor(Math.log(e-h)/Math.LN10);h=Math.floor(h/(1*Math.pow(10,a)))*Math.pow(10,a);e=Math.ceil(e/(1*Math.pow(10,a)))*Math.pow(10,a)-h;a=Math.pow(10,a);for(d=Math.round(e/a);d<b||d>c;)a=d<b?a/2:2*a,d=Math.round(e/a);c=[];z(f,c,d,h,a);return{steps:d,stepValue:a,graphMin:h,labels:c}}function z(a,c,b,e,h){if(a)for(var f=1;f<b+1;f++)c.push(E(a,{value:(e+h*f).toFixed(0!=h%1?h.toString().split(".")[1].length:0)}))}function A(a,c,b){return!isNaN(parseFloat(c))&&isFinite(c)&&a>c?c:!isNaN(parseFloat(b))&&
isFinite(b)&&a<b?b:a}function y(a,c){var b={},e;for(e in a)b[e]=a[e];for(e in c)b[e]=c[e];return b}function E(a,c){var b=!/\W/.test(a)?F[a]=F[a]||E(document.getElementById(a).innerHTML):new Function("obj","var p=[],print=function(){p.push.apply(p,arguments);};with(obj){p.push('"+a.replace(/[\r\t\n]/g," ").split("<%").join("\t").replace(/((^|%>)[^\t]*)'/g,"$1\r").replace(/\t=(.*?)%>/g,"',$1,'").split("\t").join("');").split("%>").join("p.push('").split("\r").join("\\'")+"');}return p.join('');");return c?
b(c):b}var r=this,B={linear:function(a){return a},easeInQuad:function(a){return a*a},easeOutQuad:function(a){return-1*a*(a-2)},easeInOutQuad:function(a){return 1>(a/=0.5)?0.5*a*a:-0.5*(--a*(a-2)-1)},easeInCubic:function(a){return a*a*a},easeOutCubic:function(a){return 1*((a=a/1-1)*a*a+1)},easeInOutCubic:function(a){return 1>(a/=0.5)?0.5*a*a*a:0.5*((a-=2)*a*a+2)},easeInQuart:function(a){return a*a*a*a},easeOutQuart:function(a){return-1*((a=a/1-1)*a*a*a-1)},easeInOutQuart:function(a){return 1>(a/=0.5)?
0.5*a*a*a*a:-0.5*((a-=2)*a*a*a-2)},easeInQuint:function(a){return 1*(a/=1)*a*a*a*a},easeOutQuint:function(a){return 1*((a=a/1-1)*a*a*a*a+1)},easeInOutQuint:function(a){return 1>(a/=0.5)?0.5*a*a*a*a*a:0.5*((a-=2)*a*a*a*a+2)},easeInSine:function(a){return-1*Math.cos(a/1*(Math.PI/2))+1},easeOutSine:function(a){return 1*Math.sin(a/1*(Math.PI/2))},easeInOutSine:function(a){return-0.5*(Math.cos(Math.PI*a/1)-1)},easeInExpo:function(a){return 0==a?1:1*Math.pow(2,10*(a/1-1))},easeOutExpo:function(a){return 1==
a?1:1*(-Math.pow(2,-10*a/1)+1)},easeInOutExpo:function(a){return 0==a?0:1==a?1:1>(a/=0.5)?0.5*Math.pow(2,10*(a-1)):0.5*(-Math.pow(2,-10*--a)+2)},easeInCirc:function(a){return 1<=a?a:-1*(Math.sqrt(1-(a/=1)*a)-1)},easeOutCirc:function(a){return 1*Math.sqrt(1-(a=a/1-1)*a)},easeInOutCirc:function(a){return 1>(a/=0.5)?-0.5*(Math.sqrt(1-a*a)-1):0.5*(Math.sqrt(1-(a-=2)*a)+1)},easeInElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(1==(a/=1))return 1;b||(b=0.3);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*
Math.PI)*Math.asin(1/e);return-(e*Math.pow(2,10*(a-=1))*Math.sin((1*a-c)*2*Math.PI/b))},easeOutElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(1==(a/=1))return 1;b||(b=0.3);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/e);return e*Math.pow(2,-10*a)*Math.sin((1*a-c)*2*Math.PI/b)+1},easeInOutElastic:function(a){var c=1.70158,b=0,e=1;if(0==a)return 0;if(2==(a/=0.5))return 1;b||(b=1*0.3*1.5);e<Math.abs(1)?(e=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/e);return 1>a?-0.5*e*Math.pow(2,10*
(a-=1))*Math.sin((1*a-c)*2*Math.PI/b):0.5*e*Math.pow(2,-10*(a-=1))*Math.sin((1*a-c)*2*Math.PI/b)+1},easeInBack:function(a){return 1*(a/=1)*a*(2.70158*a-1.70158)},easeOutBack:function(a){return 1*((a=a/1-1)*a*(2.70158*a+1.70158)+1)},easeInOutBack:function(a){var c=1.70158;return 1>(a/=0.5)?0.5*a*a*(((c*=1.525)+1)*a-c):0.5*((a-=2)*a*(((c*=1.525)+1)*a+c)+2)},easeInBounce:function(a){return 1-B.easeOutBounce(1-a)},easeOutBounce:function(a){return(a/=1)<1/2.75?1*7.5625*a*a:a<2/2.75?1*(7.5625*(a-=1.5/2.75)*
a+0.75):a<2.5/2.75?1*(7.5625*(a-=2.25/2.75)*a+0.9375):1*(7.5625*(a-=2.625/2.75)*a+0.984375)},easeInOutBounce:function(a){return 0.5>a?0.5*B.easeInBounce(2*a):0.5*B.easeOutBounce(2*a-1)+0.5}},q=s.canvas.width,u=s.canvas.height;window.devicePixelRatio&&(s.canvas.style.width=q+"px",s.canvas.style.height=u+"px",s.canvas.height=u*window.devicePixelRatio,s.canvas.width=q*window.devicePixelRatio,s.scale(window.devicePixelRatio,window.devicePixelRatio));this.PolarArea=function(a,c){r.PolarArea.defaults={scaleOverlay:!0,
scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",
animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.PolarArea.defaults,c):r.PolarArea.defaults;return new G(a,b,s)};this.Radar=function(a,c){r.Radar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleShowLine:!0,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!1,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowLabelBackdrop:!0,scaleBackdropColor:"rgba(255,255,255,0.75)",
scaleBackdropPaddingY:2,scaleBackdropPaddingX:2,angleShowLineOut:!0,angleLineColor:"rgba(0,0,0,.1)",angleLineWidth:1,pointLabelFontFamily:"'Arial'",pointLabelFontStyle:"normal",pointLabelFontSize:12,pointLabelFontColor:"#666",pointDot:!0,pointDotRadius:3,pointDotStrokeWidth:1,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Radar.defaults,c):r.Radar.defaults;return new H(a,b,s)};this.Pie=function(a,
c){r.Pie.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,onAnimationComplete:null};var b=c?y(r.Pie.defaults,c):r.Pie.defaults;return new I(a,b,s)};this.Doughnut=function(a,c){r.Doughnut.defaults={segmentShowStroke:!0,segmentStrokeColor:"#fff",segmentStrokeWidth:2,percentageInnerCutout:50,animation:!0,animationSteps:100,animationEasing:"easeOutBounce",animateRotate:!0,animateScale:!1,
onAnimationComplete:null};var b=c?y(r.Doughnut.defaults,c):r.Doughnut.defaults;return new J(a,b,s)};this.Line=function(a,c){r.Line.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,bezierCurve:!0,
pointDot:!0,pointDotRadius:4,pointDotStrokeWidth:2,datasetStroke:!0,datasetStrokeWidth:2,datasetFill:!0,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Line.defaults,c):r.Line.defaults;return new K(a,b,s)};this.Bar=function(a,c){r.Bar.defaults={scaleOverlay:!1,scaleOverride:!1,scaleSteps:null,scaleStepWidth:null,scaleStartValue:null,scaleLineColor:"rgba(0,0,0,.1)",scaleLineWidth:1,scaleShowLabels:!0,scaleLabel:"<%=value%>",scaleFontFamily:"'Arial'",
scaleFontSize:12,scaleFontStyle:"normal",scaleFontColor:"#666",scaleShowGridLines:!0,scaleGridLineColor:"rgba(0,0,0,.05)",scaleGridLineWidth:1,barShowStroke:!0,barStrokeWidth:2,barValueSpacing:5,barDatasetSpacing:1,animation:!0,animationSteps:60,animationEasing:"easeOutQuart",onAnimationComplete:null};var b=c?y(r.Bar.defaults,c):r.Bar.defaults;return new L(a,b,s)};var G=function(a,c,b){var e,h,f,d,g,k,j,l,m;g=Math.min.apply(Math,[q,u])/2;g-=Math.max.apply(Math,[0.5*c.scaleFontSize,0.5*c.scaleLineWidth]);
d=2*c.scaleFontSize;c.scaleShowLabelBackdrop&&(d+=2*c.scaleBackdropPaddingY,g-=1.5*c.scaleBackdropPaddingY);l=g;d=d?d:5;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.length;f++)a[f].value>e&&(e=a[f].value),a[f].value<h&&(h=a[f].value);f=Math.floor(l/(0.66*d));d=Math.floor(0.5*(l/d));m=c.scaleShowLabels?c.scaleLabel:null;c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(m,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(l,f,d,e,h,
m);k=g/j.steps;x(c,function(){for(var a=0;a<j.steps;a++)if(c.scaleShowLine&&(b.beginPath(),b.arc(q/2,u/2,k*(a+1),0,2*Math.PI,!0),b.strokeStyle=c.scaleLineColor,b.lineWidth=c.scaleLineWidth,b.stroke()),c.scaleShowLabels){b.textAlign="center";b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;var e=j.labels[a];if(c.scaleShowLabelBackdrop){var d=b.measureText(e).width;b.fillStyle=c.scaleBackdropColor;b.beginPath();b.rect(Math.round(q/2-d/2-c.scaleBackdropPaddingX),Math.round(u/2-k*(a+
1)-0.5*c.scaleFontSize-c.scaleBackdropPaddingY),Math.round(d+2*c.scaleBackdropPaddingX),Math.round(c.scaleFontSize+2*c.scaleBackdropPaddingY));b.fill()}b.textBaseline="middle";b.fillStyle=c.scaleFontColor;b.fillText(e,q/2,u/2-k*(a+1))}},function(e){var d=-Math.PI/2,g=2*Math.PI/a.length,f=1,h=1;c.animation&&(c.animateScale&&(f=e),c.animateRotate&&(h=e));for(e=0;e<a.length;e++)b.beginPath(),b.arc(q/2,u/2,f*v(a[e].value,j,k),d,d+h*g,!1),b.lineTo(q/2,u/2),b.closePath(),b.fillStyle=a[e].color,b.fill(),
c.segmentShowStroke&&(b.strokeStyle=c.segmentStrokeColor,b.lineWidth=c.segmentStrokeWidth,b.stroke()),d+=h*g},b)},H=function(a,c,b){var e,h,f,d,g,k,j,l,m;a.labels||(a.labels=[]);g=Math.min.apply(Math,[q,u])/2;d=2*c.scaleFontSize;for(e=l=0;e<a.labels.length;e++)b.font=c.pointLabelFontStyle+" "+c.pointLabelFontSize+"px "+c.pointLabelFontFamily,h=b.measureText(a.labels[e]).width,h>l&&(l=h);g-=Math.max.apply(Math,[l,1.5*(c.pointLabelFontSize/2)]);g-=c.pointLabelFontSize;l=g=A(g,null,0);d=d?d:5;e=Number.MIN_VALUE;
h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(m=0;m<a.datasets[f].data.length;m++)a.datasets[f].data[m]>e&&(e=a.datasets[f].data[m]),a.datasets[f].data[m]<h&&(h=a.datasets[f].data[m]);f=Math.floor(l/(0.66*d));d=Math.floor(0.5*(l/d));m=c.scaleShowLabels?c.scaleLabel:null;c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(m,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(l,f,d,e,h,m);k=g/j.steps;x(c,function(){var e=2*Math.PI/
a.datasets[0].data.length;b.save();b.translate(q/2,u/2);if(c.angleShowLineOut){b.strokeStyle=c.angleLineColor;b.lineWidth=c.angleLineWidth;for(var d=0;d<a.datasets[0].data.length;d++)b.rotate(e),b.beginPath(),b.moveTo(0,0),b.lineTo(0,-g),b.stroke()}for(d=0;d<j.steps;d++){b.beginPath();if(c.scaleShowLine){b.strokeStyle=c.scaleLineColor;b.lineWidth=c.scaleLineWidth;b.moveTo(0,-k*(d+1));for(var f=0;f<a.datasets[0].data.length;f++)b.rotate(e),b.lineTo(0,-k*(d+1));b.closePath();b.stroke()}c.scaleShowLabels&&
(b.textAlign="center",b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily,b.textBaseline="middle",c.scaleShowLabelBackdrop&&(f=b.measureText(j.labels[d]).width,b.fillStyle=c.scaleBackdropColor,b.beginPath(),b.rect(Math.round(-f/2-c.scaleBackdropPaddingX),Math.round(-k*(d+1)-0.5*c.scaleFontSize-c.scaleBackdropPaddingY),Math.round(f+2*c.scaleBackdropPaddingX),Math.round(c.scaleFontSize+2*c.scaleBackdropPaddingY)),b.fill()),b.fillStyle=c.scaleFontColor,b.fillText(j.labels[d],0,-k*(d+
1)))}for(d=0;d<a.labels.length;d++){b.font=c.pointLabelFontStyle+" "+c.pointLabelFontSize+"px "+c.pointLabelFontFamily;b.fillStyle=c.pointLabelFontColor;var f=Math.sin(e*d)*(g+c.pointLabelFontSize),h=Math.cos(e*d)*(g+c.pointLabelFontSize);b.textAlign=e*d==Math.PI||0==e*d?"center":e*d>Math.PI?"right":"left";b.textBaseline="middle";b.fillText(a.labels[d],f,-h)}b.restore()},function(d){var e=2*Math.PI/a.datasets[0].data.length;b.save();b.translate(q/2,u/2);for(var g=0;g<a.datasets.length;g++){b.beginPath();
b.moveTo(0,d*-1*v(a.datasets[g].data[0],j,k));for(var f=1;f<a.datasets[g].data.length;f++)b.rotate(e),b.lineTo(0,d*-1*v(a.datasets[g].data[f],j,k));b.closePath();b.fillStyle=a.datasets[g].fillColor;b.strokeStyle=a.datasets[g].strokeColor;b.lineWidth=c.datasetStrokeWidth;b.fill();b.stroke();if(c.pointDot){b.fillStyle=a.datasets[g].pointColor;b.strokeStyle=a.datasets[g].pointStrokeColor;b.lineWidth=c.pointDotStrokeWidth;for(f=0;f<a.datasets[g].data.length;f++)b.rotate(e),b.beginPath(),b.arc(0,d*-1*
v(a.datasets[g].data[f],j,k),c.pointDotRadius,2*Math.PI,!1),b.fill(),b.stroke()}b.rotate(e)}b.restore()},b)},I=function(a,c,b){for(var e=0,h=Math.min.apply(Math,[u/2,q/2])-5,f=0;f<a.length;f++)e+=a[f].value;x(c,null,function(d){var g=-Math.PI/2,f=1,j=1;c.animation&&(c.animateScale&&(f=d),c.animateRotate&&(j=d));for(d=0;d<a.length;d++){var l=j*a[d].value/e*2*Math.PI;b.beginPath();b.arc(q/2,u/2,f*h,g,g+l);b.lineTo(q/2,u/2);b.closePath();b.fillStyle=a[d].color;b.fill();c.segmentShowStroke&&(b.lineWidth=
c.segmentStrokeWidth,b.strokeStyle=c.segmentStrokeColor,b.stroke());g+=l}},b)},J=function(a,c,b){for(var e=0,h=Math.min.apply(Math,[u/2,q/2])-5,f=h*(c.percentageInnerCutout/100),d=0;d<a.length;d++)e+=a[d].value;x(c,null,function(d){var k=-Math.PI/2,j=1,l=1;c.animation&&(c.animateScale&&(j=d),c.animateRotate&&(l=d));for(d=0;d<a.length;d++){var m=l*a[d].value/e*2*Math.PI;b.beginPath();b.arc(q/2,u/2,j*h,k,k+m,!1);b.arc(q/2,u/2,j*f,k+m,k,!0);b.closePath();b.fillStyle=a[d].color;b.fill();c.segmentShowStroke&&
(b.lineWidth=c.segmentStrokeWidth,b.strokeStyle=c.segmentStrokeColor,b.stroke());k+=m}},b)},K=function(a,c,b){var e,h,f,d,g,k,j,l,m,t,r,n,p,s=0;g=u;b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;t=1;for(d=0;d<a.labels.length;d++)e=b.measureText(a.labels[d]).width,t=e>t?e:t;q/a.labels.length<t?(s=45,q/a.labels.length<Math.cos(s)*t?(s=90,g-=t):g-=Math.sin(s)*t):g-=c.scaleFontSize;d=c.scaleFontSize;g=g-5-d;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(l=
0;l<a.datasets[f].data.length;l++)a.datasets[f].data[l]>e&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]<h&&(h=a.datasets[f].data[l]);f=Math.floor(g/(0.66*d));d=Math.floor(0.5*(g/d));l=c.scaleShowLabels?c.scaleLabel:"";c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(l,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(g,f,d,e,h,l);k=Math.floor(g/j.steps);d=1;if(c.scaleShowLabels){b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;
for(e=0;e<j.labels.length;e++)h=b.measureText(j.labels[e]).width,d=h>d?h:d;d+=10}r=q-d-t;m=Math.floor(r/(a.labels.length-1));n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0<s?(b.save(),b.textAlign="right"):b.textAlign="center";b.fillStyle=c.scaleFontColor;for(var d=0;d<a.labels.length;d++)b.save(),0<s?(b.translate(n+d*m,p+c.scaleFontSize),b.rotate(-(s*(Math.PI/180))),b.fillText(a.labels[d],
0,0),b.restore()):b.fillText(a.labels[d],n+d*m,p+c.scaleFontSize+3),b.beginPath(),b.moveTo(n+d*m,p+3),c.scaleShowGridLines&&0<d?(b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+d*m,5)):b.lineTo(n+d*m,p+3),b.stroke();b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(n,p+5);b.lineTo(n,5);b.stroke();b.textAlign="right";b.textBaseline="middle";for(d=0;d<j.steps;d++)b.beginPath(),b.moveTo(n-3,p-(d+1)*k),c.scaleShowGridLines?(b.lineWidth=c.scaleGridLineWidth,
b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+r+5,p-(d+1)*k)):b.lineTo(n-0.5,p-(d+1)*k),b.stroke(),c.scaleShowLabels&&b.fillText(j.labels[d],n-8,p-(d+1)*k)},function(d){function e(b,c){return p-d*v(a.datasets[b].data[c],j,k)}for(var f=0;f<a.datasets.length;f++){b.strokeStyle=a.datasets[f].strokeColor;b.lineWidth=c.datasetStrokeWidth;b.beginPath();b.moveTo(n,p-d*v(a.datasets[f].data[0],j,k));for(var g=1;g<a.datasets[f].data.length;g++)c.bezierCurve?b.bezierCurveTo(n+m*(g-0.5),e(f,g-1),n+m*(g-0.5),
e(f,g),n+m*g,e(f,g)):b.lineTo(n+m*g,e(f,g));b.stroke();c.datasetFill?(b.lineTo(n+m*(a.datasets[f].data.length-1),p),b.lineTo(n,p),b.closePath(),b.fillStyle=a.datasets[f].fillColor,b.fill()):b.closePath();if(c.pointDot){b.fillStyle=a.datasets[f].pointColor;b.strokeStyle=a.datasets[f].pointStrokeColor;b.lineWidth=c.pointDotStrokeWidth;for(g=0;g<a.datasets[f].data.length;g++)b.beginPath(),b.arc(n+m*g,p-d*v(a.datasets[f].data[g],j,k),c.pointDotRadius,0,2*Math.PI,!0),b.fill(),b.stroke()}}},b)},L=function(a,
c,b){var e,h,f,d,g,k,j,l,m,t,r,n,p,s,w=0;g=u;b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;t=1;for(d=0;d<a.labels.length;d++)e=b.measureText(a.labels[d]).width,t=e>t?e:t;q/a.labels.length<t?(w=45,q/a.labels.length<Math.cos(w)*t?(w=90,g-=t):g-=Math.sin(w)*t):g-=c.scaleFontSize;d=c.scaleFontSize;g=g-5-d;e=Number.MIN_VALUE;h=Number.MAX_VALUE;for(f=0;f<a.datasets.length;f++)for(l=0;l<a.datasets[f].data.length;l++)a.datasets[f].data[l]>e&&(e=a.datasets[f].data[l]),a.datasets[f].data[l]<
h&&(h=a.datasets[f].data[l]);f=Math.floor(g/(0.66*d));d=Math.floor(0.5*(g/d));l=c.scaleShowLabels?c.scaleLabel:"";c.scaleOverride?(j={steps:c.scaleSteps,stepValue:c.scaleStepWidth,graphMin:c.scaleStartValue,labels:[]},z(l,j.labels,j.steps,c.scaleStartValue,c.scaleStepWidth)):j=C(g,f,d,e,h,l);k=Math.floor(g/j.steps);d=1;if(c.scaleShowLabels){b.font=c.scaleFontStyle+" "+c.scaleFontSize+"px "+c.scaleFontFamily;for(e=0;e<j.labels.length;e++)h=b.measureText(j.labels[e]).width,d=h>d?h:d;d+=10}r=q-d-t;m=
Math.floor(r/a.labels.length);s=(m-2*c.scaleGridLineWidth-2*c.barValueSpacing-(c.barDatasetSpacing*a.datasets.length-1)-(c.barStrokeWidth/2*a.datasets.length-1))/a.datasets.length;n=q-t/2-r;p=g+c.scaleFontSize/2;x(c,function(){b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(q-t/2+5,p);b.lineTo(q-t/2-r-5,p);b.stroke();0<w?(b.save(),b.textAlign="right"):b.textAlign="center";b.fillStyle=c.scaleFontColor;for(var d=0;d<a.labels.length;d++)b.save(),0<w?(b.translate(n+
d*m,p+c.scaleFontSize),b.rotate(-(w*(Math.PI/180))),b.fillText(a.labels[d],0,0),b.restore()):b.fillText(a.labels[d],n+d*m+m/2,p+c.scaleFontSize+3),b.beginPath(),b.moveTo(n+(d+1)*m,p+3),b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+(d+1)*m,5),b.stroke();b.lineWidth=c.scaleLineWidth;b.strokeStyle=c.scaleLineColor;b.beginPath();b.moveTo(n,p+5);b.lineTo(n,5);b.stroke();b.textAlign="right";b.textBaseline="middle";for(d=0;d<j.steps;d++)b.beginPath(),b.moveTo(n-3,p-(d+1)*
k),c.scaleShowGridLines?(b.lineWidth=c.scaleGridLineWidth,b.strokeStyle=c.scaleGridLineColor,b.lineTo(n+r+5,p-(d+1)*k)):b.lineTo(n-0.5,p-(d+1)*k),b.stroke(),c.scaleShowLabels&&b.fillText(j.labels[d],n-8,p-(d+1)*k)},function(d){b.lineWidth=c.barStrokeWidth;for(var e=0;e<a.datasets.length;e++){b.fillStyle=a.datasets[e].fillColor;b.strokeStyle=a.datasets[e].strokeColor;for(var f=0;f<a.datasets[e].data.length;f++){var g=n+c.barValueSpacing+m*f+s*e+c.barDatasetSpacing*e+c.barStrokeWidth*e;b.beginPath();
b.moveTo(g,p);b.lineTo(g,p-d*v(a.datasets[e].data[f],j,k)+c.barStrokeWidth/2);b.lineTo(g+s,p-d*v(a.datasets[e].data[f],j,k)+c.barStrokeWidth/2);b.lineTo(g+s,p);c.barShowStroke&&b.stroke();b.closePath();b.fill()}}},b)},D=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){window.setTimeout(a,1E3/60)},F={}};

HTML

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
        <h1>Live Updating Chart.js</h1>

        <canvas id="myChart" width="400" height="150"></canvas>


    </body>
</html>

How to extract text from a PDF file?

You can download tika-app-xxx.jar(latest) from Here.

Then put this .jar file in the same folder of your python script file.

then insert the following code in the script:

import os
import os.path

tika_dir=os.path.join(os.path.dirname(__file__),'<tika-app-xxx>.jar')

def extract_pdf(source_pdf:str,target_txt:str):
    os.system('java -jar '+tika_dir+' -t {} > {}'.format(source_pdf,target_txt))

The advantage of this method:

fewer dependency. Single .jar file is easier to manage that a python package.

multi-format support. The position source_pdf can be the directory of any kind of document. (.doc, .html, .odt, etc.)

up-to-date. tika-app.jar always release earlier than the relevant version of tika python package.

stable. It is far more stable and well-maintained (Powered by Apache) than PyPDF.

disadvantage:

A jre-headless is necessary.

Adding :default => true to boolean in existing Rails column

If you don't want to create another migration-file for a small, recent change - from Rails Console:

ActiveRecord::Migration.change_column :profiles, :show_attribute, :boolean, :default => true

Then exit and re-enter rails console, so DB-Changes will be in-effect. Then, if you do this ...

Profile.new()

You should see the "show_attribute" default-value as true.

For existing records, if you want to preserve existing "false" settings and only update "nil" values to your new default:

Profile.all.each{|profile| profile.update_attributes(:show_attribute => (profile.show_attribute == nil ? true : false))  }

Update the migration that created this table, so any future builds of the DB will get it right from the onset. Also run the same process on any deployed-instances of the DB.

If using the "new db migration" method, you can do the update of existing nil-values in that migration.

Append data frames together in a for loop

Again maRtin is correct but for this to work you have start with a dataframe that already has at least one column

model <- #some processing
df <- data.frame(col1=model)

for (i in 2:17)
{
     model <- # some processing
     nextcol <-  data.frame(model)
     colnames(nextcol) <- c(paste("col", i, sep="")) # rename the comlum
     df <- cbind(df, nextcol)
}

golang why don't we have a set datastructure

Another possibility is to use bit sets, for which there is at least one package or you can use the built-in big package. In this case, basically you need to define a way to convert your object to an index.

How to source virtualenv activate in a Bash script

Although it doesn't add the "(.env)" prefix to the shell prompt, I found this script works as expected.

#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"

e.g.

user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit

ie8 var w= window.open() - "Message: Invalid argument."

I also meet this issue while I used the following code:

window.open('test.html','Window title','width=1200,height=800,scrollbars=yes');

but when I delete the blank space of the "Window title" the below code is working:

window.open('test.html','Windowtitle','width=1200,height=800,scrollbars=yes');

Inline comments for Bash?

Most commands allow args to come in any order. Just move the commented flags to the end of the line:

ls -l -a /etc # -F is turned off

Then to turn it back on, just uncomment and remove the text:

ls -l -a /etc -F

Why does "pip install" inside Python raise a SyntaxError?

To run pip in Python 3.x, just follow the instructions on Python's page: Installing Python Modules.

python -m pip install SomePackage

Note that this is run from the command line and not the python shell (the reason for syntax error in the original question).

How to check if a text field is empty or not in swift

use this extension

extension String {
    func isBlankOrEmpty() -> Bool {

      // Check empty string
      if self.isEmpty {
          return true
      }
      // Trim and check empty string
      return (self.trimmingCharacters(in: .whitespaces) == "")
   }
}

like so

// Disable the Save button if the text field is empty.
let text = nameTextField.text ?? ""
saveButton.isEnabled = !text.isBlankOrEmpty()

How to determine whether code is running in DEBUG / RELEASE build?

Most answers said that how to set #ifdef DEBUG and none of them saying how to determinate debug/release build.

My opinion:

  1. Edit scheme -> run -> build configuration :choose debug / release . It can control the simulator and your test iPhone's code status.

  2. Edit scheme -> archive -> build configuration :choose debug / release . It can control the test package app and App Store app 's code status. enter image description here

PHP: Show yes/no confirmation dialog

The best way that I found is here.

HTML CODE

<a href="delete.cfm" onclick="return confirm('Are you sure you want to delete?');">Delete</a>

ADD THIS TO HEAD SECTION

$(document).ready(function() {
    $('a[data-confirm]').click(function(ev) {
        var href = $(this).attr('href');
        if (!$('#dataConfirmModal').length) {
            $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
        } 
        $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
        $('#dataConfirmOK').attr('href', href);
        $('#dataConfirmModal').modal({show:true});
        return false;
    });
});

You should add Jquery and Bootstrap for this to work.

Python append() vs. + operator on lists, why do these give different results?

The method you're looking for is extend(). From the Python documentation:

list.append(x)
    Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)
    Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)
    Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

Can you center a Button in RelativeLayout?

It's pretty simple, just use Android:CenterInParent="true" to center both in horizontal and vertical, or use Android:Horizontal="true" to center in horizontal and Android:Vertical="true"

And make sure you write all this in RelaytiveLayout

How to update value of a key in dictionary in c#?

Try this simple function to add an dictionary item if it does not exist or update when it exists:

    public void AddOrUpdateDictionaryEntry(string key, int value)
    {
        if (dict.ContainsKey(key))
        {
            dict[key] = value;
        }
        else
        {
            dict.Add(key, value);
        }
    }

This is the same as dict[key] = value.

Execute script after specific delay using JavaScript

As other said, setTimeout is your safest bet
But sometimes you cannot separate the logic to a new function then you can use Date.now() to get milliseconds and do the delay yourself....

_x000D_
_x000D_
function delay(milisecondDelay) {_x000D_
   milisecondDelay += Date.now();_x000D_
   while(Date.now() < milisecondDelay){}_x000D_
}_x000D_
_x000D_
alert('Ill be back in 5 sec after you click OK....');_x000D_
delay(5000);_x000D_
alert('# Im back # date:' +new Date());
_x000D_
_x000D_
_x000D_

Android check permission for LocationManager

if you are working on dynamic permissions and any permission like ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION giving error "cannot resolve method PERMISSION_NAME" in this case write you code with permission name and then rebuild your project this will regenerate the manifest(Manifest.permission) file.

What are the uses of "using" in C#?

Thanks to the comments below, I will clean this post up a bit (I shouldn't have used the words 'garbage collection' at the time, apologies):
When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.
A bullet point here which will hopefully maybe get this un-markeddown: If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.

Relative instead of Absolute paths in Excel VBA

You could use one of these for the relative path root:

ActiveWorkbook.Path
ThisWorkbook.Path
App.Path

Get contentEditable caret index position

Try this:

Caret.js Get caret postion and offset from text field

https://github.com/ichord/Caret.js

demo: http://ichord.github.com/Caret.js

Bootstrap datepicker hide after selection

I got a perfect solution:

$('#Date_of_Birth').datepicker().on('changeDate', function (e) {
    if(e.viewMode === 'days')
        $(this).blur();
});

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/to/your/xml") and make sure that your compile script is copying the xml file to where in your CLASSPATH.

Is there a label/goto in Python?

No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.

syntax error: unexpected token <

I suspect you're getting text/html encoding in response to your request so I believe the issue is:

dataType : 'json',

try changing it to

dataType : 'html',

From http://api.jquery.com/jQuery.get/:

dataType Type: String The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).

How to print register values in GDB?

p $eax works as of GDB 7.7.1

As of GDB 7.7.1, the command you've tried works:

set $eax = 0
p $eax
# $1 = 0
set $eax = 1
p $eax
# $2 = 1

This syntax can also be used to select between different union members e.g. for ARM floating point registers that can be either floating point or integers:

p $s0.f
p $s0.u

From the docs:

Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names.

and:

You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine; use info registers to see the names used on your machine.

But I haven't had much luck with control registers so far: OSDev 2012 http://f.osdev.org/viewtopic.php?f=1&t=25968 || 2005 feature request https://www.sourceware.org/ml/gdb/2005-03/msg00158.html || alt.lang.asm 2013 https://groups.google.com/forum/#!topic/alt.lang.asm/JC7YS3Wu31I

ARM floating point registers

See: https://reverseengineering.stackexchange.com/questions/8992/floating-point-registers-on-arm/20623#20623

Blocking device rotation on mobile web pages

You could use the screenSize.width and screenSize.height properties and detect when the width > height and then handle that situation, either by letting the user know or by adjusting your screen accordingly.

But the best solution is what @Doozer1979 says... Why would you override what the user prefers?

<script> tag vs <script type = 'text/javascript'> tag

In HTML 4, the type attribute is required. In my experience, all browsers will default to text/javascript if it is absent, but that behaviour is not defined anywhere. While you can in theory leave it out and assume it will be interpreted as JavaScript, it's invalid HTML, so why not add it.

In HTML 5, the type attribute is optional and defaults to text/javascript

Use <script type="text/javascript"> or simply <script> (if omitted, the type is the same). Do not use <script language="JavaScript">; the language attribute is deprecated

Ref :
http://social.msdn.microsoft.com/Forums/vstudio/en-US/65aaf5f3-09db-4f7e-a32d-d53e9720ad4c/script-languagejavascript-or-script-typetextjavascript-?forum=netfxjscript
and
Difference between <script> tag with type and <script> without type?

Do you need type attribute at all?

I am using HTML5- No

I am not using HTML5 - Yes

How can I implement a tree in Python?

I've published a Python [3] tree implementation on my site: http://www.quesucede.com/page/show/id/python_3_tree_implementation.

Hope it is of use,

Ok, here's the code:

import uuid

def sanitize_id(id):
    return id.strip().replace(" ", "")

(_ADD, _DELETE, _INSERT) = range(3)
(_ROOT, _DEPTH, _WIDTH) = range(3)

class Node:

    def __init__(self, name, identifier=None, expanded=True):
        self.__identifier = (str(uuid.uuid1()) if identifier is None else
                sanitize_id(str(identifier)))
        self.name = name
        self.expanded = expanded
        self.__bpointer = None
        self.__fpointer = []

    @property
    def identifier(self):
        return self.__identifier

    @property
    def bpointer(self):
        return self.__bpointer

    @bpointer.setter
    def bpointer(self, value):
        if value is not None:
            self.__bpointer = sanitize_id(value)

    @property
    def fpointer(self):
        return self.__fpointer

    def update_fpointer(self, identifier, mode=_ADD):
        if mode is _ADD:
            self.__fpointer.append(sanitize_id(identifier))
        elif mode is _DELETE:
            self.__fpointer.remove(sanitize_id(identifier))
        elif mode is _INSERT:
            self.__fpointer = [sanitize_id(identifier)]

class Tree:

    def __init__(self):
        self.nodes = []

    def get_index(self, position):
        for index, node in enumerate(self.nodes):
            if node.identifier == position:
                break
        return index

    def create_node(self, name, identifier=None, parent=None):

        node = Node(name, identifier)
        self.nodes.append(node)
        self.__update_fpointer(parent, node.identifier, _ADD)
        node.bpointer = parent
        return node

    def show(self, position, level=_ROOT):
        queue = self[position].fpointer
        if level == _ROOT:
            print("{0} [{1}]".format(self[position].name,
                                     self[position].identifier))
        else:
            print("\t"*level, "{0} [{1}]".format(self[position].name,
                                                 self[position].identifier))
        if self[position].expanded:
            level += 1
            for element in queue:
                self.show(element, level)  # recursive call

    def expand_tree(self, position, mode=_DEPTH):
        # Python generator. Loosly based on an algorithm from 'Essential LISP' by
        # John R. Anderson, Albert T. Corbett, and Brian J. Reiser, page 239-241
        yield position
        queue = self[position].fpointer
        while queue:
            yield queue[0]
            expansion = self[queue[0]].fpointer
            if mode is _DEPTH:
                queue = expansion + queue[1:]  # depth-first
            elif mode is _WIDTH:
                queue = queue[1:] + expansion  # width-first

    def is_branch(self, position):
        return self[position].fpointer

    def __update_fpointer(self, position, identifier, mode):
        if position is None:
            return
        else:
            self[position].update_fpointer(identifier, mode)

    def __update_bpointer(self, position, identifier):
        self[position].bpointer = identifier

    def __getitem__(self, key):
        return self.nodes[self.get_index(key)]

    def __setitem__(self, key, item):
        self.nodes[self.get_index(key)] = item

    def __len__(self):
        return len(self.nodes)

    def __contains__(self, identifier):
        return [node.identifier for node in self.nodes
                if node.identifier is identifier]

if __name__ == "__main__":

    tree = Tree()
    tree.create_node("Harry", "harry")  # root node
    tree.create_node("Jane", "jane", parent = "harry")
    tree.create_node("Bill", "bill", parent = "harry")
    tree.create_node("Joe", "joe", parent = "jane")
    tree.create_node("Diane", "diane", parent = "jane")
    tree.create_node("George", "george", parent = "diane")
    tree.create_node("Mary", "mary", parent = "diane")
    tree.create_node("Jill", "jill", parent = "george")
    tree.create_node("Carol", "carol", parent = "jill")
    tree.create_node("Grace", "grace", parent = "bill")
    tree.create_node("Mark", "mark", parent = "jane")

    print("="*80)
    tree.show("harry")
    print("="*80)
    for node in tree.expand_tree("harry", mode=_WIDTH):
        print(node)
    print("="*80)

How to pass parameter to function using in addEventListener?

When you use addEventListener, this will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this from within your function:

productLineSelect.addEventListener('change',getSelection,false);

function getSelection(){
    var value = sel.options[this.selectedIndex].value;
    alert(value);
}

If you want to pass in some other argument from the context where you call addEventListener, you can use a closure, like this:

productLineSelect.addEventListener('change', function(){ 
    // pass in `this` (the element), and someOtherVar
    getSelection(this, someOtherVar); 
},false);

function getSelection(sel, someOtherVar){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
    alert(someOtherVar);
}

'node' is not recognized as an internal or external command

Nodejs's installation adds nodejs to the path in the environment properties incorrectly.

By default it adds the following to the path:

C:\Program Files\nodejs\

The ending \ is unnecessary. Remove the \ and everything will be beautiful again.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

You can get the raw data by calling ReadAsStringAsAsync on the Request.Content property.

string result = await Request.Content.ReadAsStringAsync();

There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:

public async Task<IHttpActionResult> GetSomething()
{
    var rawMessage = await Request.Content.ReadAsStringAsync();
    // ...
    return Ok();
}

EDIT: if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:

public IHttpActionResult GetSomething()
{
    var reader = new StreamReader(Request.Body);
    reader.BaseStream.Seek(0, SeekOrigin.Begin); 
    var rawMessage = reader.ReadToEnd();

    return Ok();
}

In this case, your endpoint doesn't need to be async (unless you have other async-methods)

WMI "installed" query different from add/remove programs list?

Besides the most commonly known registry key for installed programs:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall

wmic command and the add/remove programs also query another registry key:

HKEY_CLASSES_ROOT\Installer\Products

Software name shown in the list is read from the Value of a Data entry within this key called: ProductName

Removing the registry key for a certain product from both of the above locations will keep it from showing in the add/remove programs list. This is not a method to uninstall programs, it will just remove the entry from what's known to windows as installed software.

Since, by using this method you would lose the chance of using the Remove button from the add/remove list to cleanly remove the software from your system; it's recommended to export registry keys to a file before you delete them. In future, if you decided to bring that item back to the list, you would simply run the registry file you stored.

Java Long primitive type maximum limit

It will overflow and wrap around to Long.MIN_VALUE.

Its not too likely though. Even if you increment 1,000,000 times per second it will take about 300,000 years to overflow.

How to set menu to Toolbar in Android

In your activity override this method.

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

This will inflate your menu below:

 <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">

        <item
            android:id="@+id/menu_main_setting"
            android:icon="@drawable/ic_settings"
            android:orderInCategory="100"
            app:showAsAction="always"
            android:actionLayout="@layout/toolbar"
            android:title="Setting" />

        <item
            android:id="@+id/menu_main_setting2"
            android:icon="@drawable/ic_settings"
            android:orderInCategory="200"
            app:showAsAction="always"
            android:actionLayout="@layout/toolbar"
            android:title="Setting" />

    </menu>

How to install Ruby 2.1.4 on Ubuntu 14.04

update ubuntu:

 sudo apt-get update
 sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties libffi-dev

Install rvm, which manages the ruby versions:

to install rvm use the following command.

 \curl -sSL https://get.rvm.io | bash -s stable
 source ~/.bash_profile
 rvm install ruby-2.1.4

Check ruby versions installed and in use:

rvm list
rvm use --default ruby-2.1.4

Use grep --exclude/--include syntax to not grep through certain files

Use the shell globbing syntax:

grep pattern -r --include=\*.{cpp,h} rootdir

The syntax for --exclude is identical.

Note that the star is escaped with a backslash to prevent it from being expanded by the shell (quoting it, such as --include="*.{cpp,h}", would work just as well). Otherwise, if you had any files in the current working directory that matched the pattern, the command line would expand to something like grep pattern -r --include=foo.cpp --include=bar.h rootdir, which would only search files named foo.cpp and bar.h, which is quite likely not what you wanted.

Compare two files line by line and generate the difference in another file

diff(1) is not the answer, but comm(1) is.

NAME
       comm - compare two sorted files line by line

SYNOPSIS
       comm [OPTION]... FILE1 FILE2

...

       -1     suppress lines unique to FILE1

       -2     suppress lines unique to FILE2

       -3     suppress lines that appear in both files

So

comm -2 -3 file1 file2 > file3

The input files must be sorted. If they are not, sort them first. This can be done with a temporary file, or...

comm -2 -3 <(sort file1) <(sort file2) > file3

provided that your shell supports process substitution (bash does).

How to support different screen size in android

you can create bitmaps for the highes resolution / size your application will run and resize them in the code (at run time)

check this article http://nuvornapps-en.blogspot.com.es/

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

I try to perform a TLS1.2 connection. I tried eveything mention above but didn't work. Do you have any additional idea?

String WebserviceApiURL = "https://soapServiceURL";

Uri uri = new Uri(WebserviceApiURL);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
request.ContentType = "application/json";
request.Headers.Add("Token", "xxxxxx");

System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
System.Net.ServicePointManager.Expect100Continue = false;

request.KeepAlive = false;
request.ProtocolVersion = HttpVersion.Version10;
request.ServicePoint.ConnectionLimit = 1;

WebResponse response = request.GetResponse();

data.map is not a function

If you want to map an object you can use Lodash. Just make sure it's installed via NPM or Yarn and import it.

With Lodash:

Lodash provides a function _.mapValues to map the values and preserve the keys.

_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

How can I stop redis-server?

For OSX, I created the following aliases for starting and stopping redis (installed with Homebrew):

alias redstart='redis-server /usr/local/etc/redis/6379.conf'
alias redstop='redis-cli -h 127.0.0.1 -p 6379 shutdown'

This has worked great for local development!

Homebrew now has homebrew-services that can be used to start, stop and restart services. homebrew-services

brew services is automatically installed when run.

brew services start|run redis 
brew services stop redis
brew services restart redis

If you use run, then it will not start it at login (nor boot). start will start the redis service and add it at login and boot.

How can I update NodeJS and NPM to the next versions?

First update npm,

npm install -g npm@next

Then update node to the next version,

npm install -g node@next or npm install -g n@next or, to the latest,

npm install -g node@latest or npm install -g node

check after version installation,

node --versionor node -v

How can I multiply and divide using only bit shifting and adding?

Taken from here.

This is only for division:

int add(int a, int b) {
        int partialSum, carry;
        do {
            partialSum = a ^ b;
            carry = (a & b) << 1;
            a = partialSum;
            b = carry;
        } while (carry != 0);
        return partialSum;
}

int subtract(int a, int b) {
    return add(a, add(~b, 1));
}

int division(int dividend, int divisor) {
        boolean negative = false;
        if ((dividend & (1 << 31)) == (1 << 31)) { // Check for signed bit
            negative = !negative;
            dividend = add(~dividend, 1);  // Negation
        }
        if ((divisor & (1 << 31)) == (1 << 31)) {
            negative = !negative;
            divisor = add(~divisor, 1);  // Negation
        }
        int quotient = 0;
        long r;
        for (int i = 30; i >= 0; i = subtract(i, 1)) {
            r = (divisor << i);
           // Left shift divisor until it's smaller than dividend
            if (r < Integer.MAX_VALUE && r >= 0) { // Avoid cases where comparison between long and int doesn't make sense
                if (r <= dividend) { 
                    quotient |= (1 << i);    
                    dividend = subtract(dividend, (int) r);
                }
            }
        }
        if (negative) {
            quotient = add(~quotient, 1);
        }
        return quotient;
}

How to work with complex numbers in C?

For convenience, one may include tgmath.h library for the type generate macros. It creates the same function name as the double version for all type of variable. For example, For example, it defines a sqrt() macro that expands to the sqrtf() , sqrt() , or sqrtl() function, depending on the type of argument provided.

So one don't need to remember the corresponding function name for different type of variables!

#include <stdio.h>
#include <tgmath.h>//for the type generate macros. 
#include <complex.h>//for easier declare complex variables and complex unit I

int main(void)
{
    double complex z1=1./4.*M_PI+1./4.*M_PI*I;//M_PI is just pi=3.1415...
    double complex z2, z3, z4, z5; 

    z2=exp(z1);
    z3=sin(z1);
    z4=sqrt(z1);
    z5=log(z1);

    printf("exp(z1)=%lf + %lf I\n", creal(z2),cimag(z2));
    printf("sin(z1)=%lf + %lf I\n", creal(z3),cimag(z3));
    printf("sqrt(z1)=%lf + %lf I\n", creal(z4),cimag(z4));
    printf("log(z1)=%lf + %lf I\n", creal(z5),cimag(z5));

    return 0;
}

Binding select element to object in Angular

This code is very simple:

<select class="form-control" id="marasemaat" style="margin-top: 10%;font-size: 13px;" [(ngModel)]="fullNamePresentor" [formControl]="stateControl"  
            (change)="onSelect($event.target.value)">
            <option *ngFor="let char of programInfo1;let i = index;"   onclick="currentSlide(9,false)" value={{char.id}}>{{char.title + " "}}  ----> {{char.name + " "+ char.family }} ---- > {{(char.time.split('T', 2)[1]).split(':',2)}}</option>
  
          </select>

How to count the number of set bits in a 32-bit integer?

I have not seen this approach anywhere:

int nbits(unsigned char v) {
    return ((((v - ((v >> 1) & 0x55)) * 0x1010101) & 0x30c00c03) * 0x10040041) >> 0x1c;
}

It works per byte, so it would have to be called 4 times for a 32-bit integer. It is derived from the sideways addition but uses two 32-bit multiplications to reduce the number of instructions to only 7.

Most current C compilers will optimize this function using SIMD (SSE2) instructions when it is clear that the number of requests is a multiple of 4, and it becomes quite competitive. It is portable, can be defined as a macro or inline function and does not need data tables.

This approach can be extended to work on 16 bits at a time, using 64-bit multiplications. However, it fails when all 16 bits are set, returning zero, so it can be used only when the 0xffff input value is not present. It is also slower due to the 64-bit operations and does not optimize well.

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

If Python is interpreted, what are .pyc files?

Python's *.py file is just a text file in which you write some lines of code. When you try to execute this file using say "python filename.py"

This command invokes Python Virtual Machine. Python Virtual Machine has 2 components: "compiler" and "interpreter". Interpreter cannot directly read the text in *.py file, so this text is first converted into a byte code which is targeted to the PVM (not hardware but PVM). PVM executes this byte code. *.pyc file is also generated, as part of running it which performs your import operation on file in shell or in some other file.

If this *.pyc file is already generated then every next time you run/execute your *.py file, system directly loads your *.pyc file which won't need any compilation(This will save you some machine cycles of processor).

Once the *.pyc file is generated, there is no need of *.py file, unless you edit it.

How to center a navigation bar with CSS or HTML?

Add some CSS:

div#nav{
  text-align: center;
}
div#nav ul{
  display: inline-block;
}

Is it possible to return empty in react render function?

Slightly off-topic but if you ever needed a class-based component that never renders anything and you are happy to use some yet-to-be-standardised ES syntax, you might want to go:

render = () => null

This is basically an arrow method that currently requires the transform-class-properties Babel plugin. React will not let you define a component without the render function and this is the most concise form satisfying this requirement that I can think of.

I'm currently using this trick in a variant of ScrollToTop borrowed from the react-router documentation. In my case, there's only a single instance of the component and it doesn't render anything, so a short form of "render null" fits nice in there.

How to get min, seconds and milliseconds from datetime.now() in python?

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

Is there a way to make npm install (the command) to work behind proxy?

Try to find .npmrc in C:\Users\.npmrc

then open (notepad), write, and save inside :

proxy=http://<username>:<pass>@<proxyhost>:<port>

PS : remove "<" and ">" please !!

XOR operation with two strings in java

Pay attention:

A Java char corresponds to a UTF-16 code unit, and in some cases two consecutive chars (a so-called surrogate pair) are needed for one real Unicode character (codepoint).

XORing two valid UTF-16 sequences (i.e. Java Strings char by char, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)

The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.

Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF (plane 15) XOR U+10000 (plane 16) = U+1FFFFF (which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).

If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)


What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[] (or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).

How do you get the length of a list in the JSF expression language?

You mean size() don't you?

#{MyBean.somelist.size()}

works for me (using JBoss Seam which has the Jboss EL extensions)

Catch paste input

For cross platform compatibility, it should handle oninput and onpropertychange events:

$ (something).bind ("input propertychange", function (e) {
    // check for paste as in example above and
    // do something
})

Using AES encryption in C#

Look at sample in here..

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged(v=VS.100).aspx#Y2262

The example on MSDN does not run normally (an error occurs) because there is no initial value of Initial Vector(iv) and Key. I add 2 line code and now work normally.

More details see below:

using System.Windows.Forms;
using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace AES_TESTER
{
   public partial class Form1 : Form
   {
       public Form1()
       {
          InitializeComponent();
       }

       private void Form1_Load(object sender, EventArgs e)
       {
          try
          {

            string original = "Here is some data to encrypt!";
            MessageBox.Show("Original:   " + original);

            // Create a new instance of the RijndaelManaged
            // class.  This generates a new key and initialization 
            // vector (IV).
            using (RijndaelManaged myRijndael = new RijndaelManaged())
            {
                 myRijndael.GenerateKey();
                 myRijndael.GenerateIV();

                // Encrypt the string to an array of bytes.
                byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                StringBuilder s = new StringBuilder();
                foreach (byte item in encrypted)
                {
                   s.Append(item.ToString("X2") + " ");
                }
                MessageBox.Show("Encrypted:   " + s);

                // Decrypt the bytes to a string.
                string decrypted = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                //Display the original data and the decrypted data.
                MessageBox.Show("Decrypted:    " + decrypted);
            }

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error: {0}", ex.Message);
        }
    }

    static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");
        byte[] encrypted;
        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.Padding = PaddingMode.Zeros;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }


        // Return the encrypted bytes from the memory stream.
        return encrypted;

    }

    static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;
            rijAlg.Mode = CipherMode.CBC;
            rijAlg.Padding = PaddingMode.Zeros;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;
     }
   }
}

Define a fixed-size list in Java

Yes. You can pass a java array to Arrays.asList(Object[]).

List<String> fixedSizeList = Arrays.asList(new String[100]);

You cannot insert new Strings to the fixedSizeList (it already has 100 elements). You can only set its values like this:

fixedSizeList.set(7, "new value");

That way you have a fixed size list. The thing functions like an array and I can't think of a good reason to use it. I'd love to hear why you want your fixed size collection to be a list instead of just using an array.

Need to combine lots of files in a directory

I used this script on windows powershell:

ForEach ($f in get-ChildItem *.sql) { type "$f" >> all.sql }

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.

A:you need to configure the primeng tabulemodule in ngmodule

How do I declare an array of undefined or no initial size?

Modern C, aka C99, has variable length arrays, VLA. Unfortunately, not all compilers support this but if yours does this would be an alternative.

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

I think this will work even though this was forever ago.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum    FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

Remove CSS from a Div using JQuery

You can remove inline properties this way:

$(selector).css({'property':'', 'property':''});

For example:

$(actpar).css({'top':'', 'opacity':''});

This is essentially mentioned above, and it definitely does the trick.

BTW, this is useful in instances such as when you need to clear a state after animation. Sure I could write a half dozen classes to deal with this, or I could use my base class and #id do some math, and clear the inline style that the animation applies.

$(actpar).animate({top:0, opacity:1, duration:500}, function() {
   $(this).css({'top':'', 'opacity':''});
});

How to see JavaDoc in IntelliJ IDEA?

Alternatively you can position your cursor on the item and show JavaDoc using

CTRL+Q

which is the default shortcut.

Edit: As Methical mentioned on Mac the shortcut is

CTRL+j (^+j not ?+j)

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Asked and answered before...

Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )"

"1" is a non-null expression so it's the same as COUNT(*). The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK) = COUNT(*)

This is a similar myth to EXISTS (SELECT * ... or EXISTS (SELECT 1 ...

And see the ANSI 92 spec, section 6.5, General Rules, case 1

        a) If COUNT(*) is specified, then the result is the cardinality
          of T.

        b) Otherwise, let TX be the single-column table that is the
          result of applying the <value expression> to each row of T
          and eliminating null values. If one or more null values are
          eliminated, then a completion condition is raised: warning-
          null value eliminated in set function.

How do I put two increment statements in a C++ 'for' loop?

I agree with squelart. Incrementing two variables is bug prone, especially if you only test for one of them.

This is the readable way to do this:

int j = 0;
for(int i = 0; i < 5; ++i) {
    do_something(i, j);
    ++j;
}

For loops are meant for cases where your loop runs on one increasing/decreasing variable. For any other variable, change it in the loop.

If you need j to be tied to i, why not leave the original variable as is and add i?

for(int i = 0; i < 5; ++i) {
    do_something(i,a+i);
}

If your logic is more complex (for example, you need to actually monitor more than one variable), I'd use a while loop.

Enumerations on PHP

Depending upon use case, I would normally use something simple like the following:

abstract class DaysOfWeek
{
    const Sunday = 0;
    const Monday = 1;
    // etc.
}

$today = DaysOfWeek::Sunday;

However, other use cases may require more validation of constants and values. Based on the comments below about reflection, and a few other notes, here's an expanded example which may better serve a much wider range of cases:

abstract class BasicEnum {
    private static $constCacheArray = NULL;

    private static function getConstants() {
        if (self::$constCacheArray == NULL) {
            self::$constCacheArray = [];
        }
        $calledClass = get_called_class();
        if (!array_key_exists($calledClass, self::$constCacheArray)) {
            $reflect = new ReflectionClass($calledClass);
            self::$constCacheArray[$calledClass] = $reflect->getConstants();
        }
        return self::$constCacheArray[$calledClass];
    }

    public static function isValidName($name, $strict = false) {
        $constants = self::getConstants();

        if ($strict) {
            return array_key_exists($name, $constants);
        }

        $keys = array_map('strtolower', array_keys($constants));
        return in_array(strtolower($name), $keys);
    }

    public static function isValidValue($value, $strict = true) {
        $values = array_values(self::getConstants());
        return in_array($value, $values, $strict);
    }
}

By creating a simple enum class that extends BasicEnum, you now have the ability to use methods thusly for simple input validation:

abstract class DaysOfWeek extends BasicEnum {
    const Sunday = 0;
    const Monday = 1;
    const Tuesday = 2;
    const Wednesday = 3;
    const Thursday = 4;
    const Friday = 5;
    const Saturday = 6;
}

DaysOfWeek::isValidName('Humpday');                  // false
DaysOfWeek::isValidName('Monday');                   // true
DaysOfWeek::isValidName('monday');                   // true
DaysOfWeek::isValidName('monday', $strict = true);   // false
DaysOfWeek::isValidName(0);                          // false

DaysOfWeek::isValidValue(0);                         // true
DaysOfWeek::isValidValue(5);                         // true
DaysOfWeek::isValidValue(7);                         // false
DaysOfWeek::isValidValue('Friday');                  // false

As a side note, any time I use reflection at least once on a static/const class where the data won't change (such as in an enum), I cache the results of those reflection calls, since using fresh reflection objects each time will eventually have a noticeable performance impact (Stored in an assocciative array for multiple enums).

Now that most people have finally upgraded to at least 5.3, and SplEnum is available, that is certainly a viable option as well--as long as you don't mind the traditionally unintuitive notion of having actual enum instantiations throughout your codebase. In the above example, BasicEnum and DaysOfWeek cannot be instantiated at all, nor should they be.

Extension gd is missing from your system - laravel composer Update

Using Manjaro(Arch) Linux:

$ sudo pacman -S php-gd

In file /etc/php/php-ini, add the line:

extension=gd.so

grant remote access of MySQL database from any IP address

You can slove the problem of MariaDB via this command:

Note:

GRANT ALL ON *.* to root@'%' IDENTIFIED BY 'mysql root password';

% is a wildcard. In this case, it refers to all IP addresses.

How can I show a message box with two buttons?

I did

msgbox "TEXT HERE",3,"TITLE HERE"
If Yes=true then
(result)

else
msgbox "Closing..."

How to send JSON instead of a query string with $.ajax?

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Why is using "for...in" for array iteration a bad idea?

The for/in works with two types of variables: hashtables (associative arrays) and array (non-associative).

JavaScript will automatically determine the way its passes through the items. So if you know that your array is really non-associative you can use for (var i=0; i<=arrayLen; i++), and skip the auto-detection iteration.

But in my opinion, it's better to use for/in, the process required for that auto-detection is very small.

A real answer for this will depend on how the browser parsers/interpret the JavaScript code. It can change between browsers.

I can't think of other purposes to not using for/in;

//Non-associative
var arr = ['a', 'b', 'c'];
for (var i in arr)
   alert(arr[i]);

//Associative
var arr = {
   item1 : 'a',
   item2 : 'b',
   item3 : 'c'
};

for (var i in arr)
   alert(arr[i]);

HTTP Headers for File Downloads

As explained by Alex's link you're probably missing the header Content-Disposition on top of Content-Type.

So something like this:

Content-Disposition: attachment; filename="MyFileName.ext"

How to align a div to the top of its parent but keeping its inline-block behaviour?

As others have said, vertical-align: top is your friend.

As a bonus here is a forked fiddle with added enhancements that make it work in Internet Explorer 6 and Internet Explorer 7 too ;)

Example: here

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

iOS - Calling App Delegate method from ViewController

Even if technically feasible, is NOT a good approach. When You say: "The splash screen would have buttons for each room that would allow you to jump to any point on the walk through." So you want to pass through appdelegate to call these controllers via tohc events on buttons?

This approach does not follow Apple guidelines and has a lot of drawbacks.

How to retrieve the LoaderException property?

Another Alternative for those who are probing around and/or in interactive mode:

$Error[0].Exception.LoaderExceptions

Note: [0] grabs the most recent Error from the stack

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

How to detect the end of loading of UITableView

I always use this very simple solution:

-(void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([indexPath row] == lastRow){
        //end of loading
        //for example [activityIndicator stopAnimating];
    }
}

What is the (function() { } )() construct in JavaScript?

One more use case is memoization where a cache object is not global:

var calculate = (function() {
  var cache = {};
  return function(a) {

    if (cache[a]) {
      return cache[a];
    } else {
      // Calculate heavy operation
      cache[a] = heavyOperation(a);
      return cache[a];
    }
  }
})();

Nested Git repositories?

Just for completeness:

There is another solution, I would recommend: subtree merging.

In contrast to submodules, it's easier to maintain. You would create each repository the normal way. While in your main repository, you want to merge the master (or any other branch) of another repository in a directory of your main directory.

$ git remote add -f OtherRepository /path/to/that/repo
$ git merge -s ours --no-commit OtherRepository/master
$ git read-tree --prefix=AnyDirectoryToPutItIn/ -u OtherRepository/master
$ git commit -m "Merge OtherRepository project as our subdirectory"`

Then, in order to pull the other repository into your directory (to update it), use the subtree merge strategy:

$ git pull -s subtree OtherRepository master

I'm using this method for years now, it works :-)

More about this way including comparing it with sub modules may be found in this git howto doc.

PHP AES encrypt / decrypt

If you don't want to use a heavy dependency for something solvable in 15 lines of code, use the built in OpenSSL functions. Most PHP installations come with OpenSSL, which provides fast, compatible and secure AES encryption in PHP. Well, it's secure as long as you're following the best practices.

The following code:

  • uses AES256 in CBC mode
  • is compatible with other AES implementations, but not mcrypt, since mcrypt uses PKCS#5 instead of PKCS#7.
  • generates a key from the provided password using SHA256
  • generates a hmac hash of the encrypted data for integrity check
  • generates a random IV for each message
  • prepends the IV (16 bytes) and the hash (32 bytes) to the ciphertext
  • should be pretty secure

IV is a public information and needs to be random for each message. The hash ensures that the data hasn't been tampered with.

function encrypt($plaintext, $password) {
    $method = "AES-256-CBC";
    $key = hash('sha256', $password, true);
    $iv = openssl_random_pseudo_bytes(16);

    $ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
    $hash = hash_hmac('sha256', $ciphertext . $iv, $key, true);

    return $iv . $hash . $ciphertext;
}

function decrypt($ivHashCiphertext, $password) {
    $method = "AES-256-CBC";
    $iv = substr($ivHashCiphertext, 0, 16);
    $hash = substr($ivHashCiphertext, 16, 32);
    $ciphertext = substr($ivHashCiphertext, 48);
    $key = hash('sha256', $password, true);

    if (!hash_equals(hash_hmac('sha256', $ciphertext . $iv, $key, true), $hash)) return null;

    return openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
}

Usage:

$encrypted = encrypt('Plaintext string.', 'password'); // this yields a binary string

echo decrypt($encrypted, 'password');
// decrypt($encrypted, 'wrong password') === null

edit: Updated to use hash_equals and added IV to the hash.

Android: how to make keyboard enter button say "Search" and handle its click?

In Kotlin

evLoginPassword.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        doTheLoginWork()
    }
    true
}

Partial Xml Code

 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
       <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginUserEmail"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/email"
                android:inputType="textEmailAddress"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginTop="8dp"
            android:paddingLeft="24dp"
            android:paddingRight="24dp">

            <EditText
                android:id="@+id/evLoginPassword"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/password"
                android:inputType="textPassword"
                android:imeOptions="actionDone"
                android:textColor="@color/black_54_percent" />
        </android.support.design.widget.TextInputLayout>
</LinearLayout>