Programs & Examples On #Split

Use this tag for questions about separating an item (e.g. a string) into parts, often by a delimiter or regular expression.

How to split a string in Ruby and get all items except the first one?

ex="test1,test2,test3,test4,test5"
all_but_first=ex.split(/,/)[1..-1]

How do I split a string on a delimiter in Bash?

Without setting the IFS

If you just have one colon you can do that:

a="foo:bar"
b=${a%:*}
c=${a##*:}

you will get:

b = foo
c = bar

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

How to split a file into equal parts, without breaking individual lines?

If you mean an equal number of lines, split has an option for this:

split --lines=75

If you need to know what that 75 should really be for N equal parts, its:

lines_per_part = int(total_lines + N - 1) / N

where total lines can be obtained with wc -l.

See the following script for an example:

#!/usr/bin/bash

# Configuration stuff

fspec=qq.c
num_files=6

# Work out lines per file.

total_lines=$(wc -l <${fspec})
((lines_per_file = (total_lines + num_files - 1) / num_files))

# Split the actual file, maintaining lines.

split --lines=${lines_per_file} ${fspec} xyzzy.

# Debug information

echo "Total lines     = ${total_lines}"
echo "Lines  per file = ${lines_per_file}"    
wc -l xyzzy.*

This outputs:

Total lines     = 70
Lines  per file = 12
  12 xyzzy.aa
  12 xyzzy.ab
  12 xyzzy.ac
  12 xyzzy.ad
  12 xyzzy.ae
  10 xyzzy.af
  70 total

More recent versions of split allow you to specify a number of CHUNKS with the -n/--number option. You can therefore use something like:

split --number=l/6 ${fspec} xyzzy.

(that's ell-slash-six, meaning lines, not one-slash-six).

That will give you roughly equal files in terms of size, with no mid-line splits.

I mention that last point because it doesn't give you roughly the same number of lines in each file, more the same number of characters.

So, if you have one 20-character line and 19 1-character lines (twenty lines in total) and split to five files, you most likely won't get four lines in every file.

Javascript how to split newline

The problem is that when you initialize ks, the value hasn't been set.

You need to fetch the value when user submits the form. So you need to initialize the ks inside the callback function

(function($){
   $(document).ready(function(){
      $('#data').submit(function(e){
      //Here it will fetch the value of #keywords
         var ks = $('#keywords').val().split("\n");
         ...
      });
   });
})(jQuery);

Split array into chunks

ONE-LINER

const chunk = (a,n)=>[...Array(Math.ceil(a.length/n))].map((_,i)=>a.slice(n*i,n+n*i));

For TypeScript

const chunk = <T>(arr: T[], size: number): T[][] =>
  [...Array(Math.ceil(arr.length / size))].map((_, i) =>
    arr.slice(size * i, size + size * i)
  );

DEMO

_x000D_
_x000D_
const chunk = (a,n)=>[...Array(Math.ceil(a.length/n))].map((_,i)=>a.slice(n*i,n+n*i));
document.write(JSON.stringify(chunk([1, 2, 3, 4], 2)));
_x000D_
_x000D_
_x000D_

Chunk By Number Of Groups

const part=(a,n)=>[...Array(n)].map((_,i)=>a.slice(i*Math.ceil(a.length/n),(i+1)*Math.ceil(a.length/n)));

For TypeScript

const part = <T>(a: T[], n: number): T[][] => {
  const b = Math.ceil(a.length / n);
  return [...Array(n)].map((_, i) => a.slice(i * b, (i + 1) * b));
};

DEMO

_x000D_
_x000D_
const part = (a, n) => {
    const b = Math.ceil(a.length / n);
    return [...Array(n)].map((_, i) => a.slice(i * b, (i + 1) * b));
};

document.write(JSON.stringify(part([1, 2, 3, 4, 5, 6], 2))+'<br/>');
document.write(JSON.stringify(part([1, 2, 3, 4, 5, 6, 7], 2)));
_x000D_
_x000D_
_x000D_

How to split a delimited string in Ruby and convert it to an array?

the simplest way to convert a string that has a delimiter like a comma is just to use the split method

"1,2,3,4".split(',') # "1", "2", "3", "4"]

you can find more info on how to use the split method in the ruby docs

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ‘ were specified.

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

Split Strings into words with multiple word boundary delimiters

I like pprzemek's solution because it does not assume that the delimiters are single characters and it doesn't try to leverage a regex (which would not work well if the number of separators got to be crazy long).

Here's a more readable version of the above solution for clarity:

def split_string_on_multiple_separators(input_string, separators):
    buffer = [input_string]
    for sep in separators:
        strings = buffer
        buffer = []  # reset the buffer
        for s in strings:
            buffer = buffer + s.split(sep)

    return buffer

How do I split a string with multiple separators in JavaScript?

Hi for example if you have split and replace in String 07:05:45PM

var hour = time.replace("PM", "").split(":");

Result

[ '07', '05', '45' ]

Splitting dataframe into multiple dataframes

You can convert groupby object to tuples and then to dict:

df = pd.DataFrame({'Name':list('aabbef'),
                   'A':[4,5,4,5,5,4],
                   'B':[7,8,9,4,2,3],
                   'C':[1,3,5,7,1,0]}, columns = ['Name','A','B','C'])

print (df)
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3
2    b  4  9  5
3    b  5  4  7
4    e  5  2  1
5    f  4  3  0

d = dict(tuple(df.groupby('Name')))
print (d)
{'b':   Name  A  B  C
2    b  4  9  5
3    b  5  4  7, 'e':   Name  A  B  C
4    e  5  2  1, 'a':   Name  A  B  C
0    a  4  7  1
1    a  5  8  3, 'f':   Name  A  B  C
5    f  4  3  0}

print (d['a'])
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3

It is not recommended, but possible create DataFrames by groups:

for i, g in df.groupby('Name'):
    globals()['df_' + str(i)] =  g

print (df_a)
  Name  A  B  C
0    a  4  7  1
1    a  5  8  3

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

splitting a string based on tab in the file

An other regex-based solution:

>>> strs = "foo\tbar\t\tspam"

>>> r = re.compile(r'([^\t]*)\t*')
>>> r.findall(strs)[:-1]
['foo', 'bar', 'spam']

Split string based on regex

Your question contains the string literal "\b[A-Z]{2,}\b", but that \b will mean backspace, because there is no r-modifier.

Try: r"\b[A-Z]{2,}\b".

How to split a comma-separated string?

Use this :

        List<String> splitString = (List<String>) Arrays.asList(jobtype.split(","));

Split a large dataframe into a list of data frames based on common value in column

From version 0.8.0, dplyr offers a handy function called group_split():

# On sample data from @Aus_10

df %>%
  group_split(g)

[[1]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     2.04      0.627 A    
 2     0.530    -0.703 A    
 3    -0.475     0.541 A    
 4     1.20     -0.565 A    
 5    -0.380    -0.126 A    
 6     1.25     -1.69  A    
 7    -0.153    -1.02  A    
 8     1.52     -0.520 A    
 9     0.905    -0.976 A    
10     0.517    -0.535 A    
# … with 15 more rows

[[2]]
# A tibble: 25 x 3
   ran_data1 ran_data2 g    
       <dbl>     <dbl> <fct>
 1     1.61      0.858 B    
 2     1.05     -1.25  B    
 3    -0.440    -0.506 B    
 4    -1.17      1.81  B    
 5     1.47     -1.60  B    
 6    -0.682    -0.726 B    
 7    -2.21      0.282 B    
 8    -0.499     0.591 B    
 9     0.711    -1.21  B    
10     0.705     0.960 B    
# … with 15 more rows

To not include the grouping column:

df %>%
 group_split(g, keep = FALSE)

Regex to split a CSV

The advantage of using JScript for classic ASP pages is that you can use one of the many, many libraries that have been written for JavaScript.

Like this one: https://github.com/gkindel/CSV-JS. Download it, include it in your ASP page, parse CSV with it.

<%@ language="javascript" %>

<script language="javascript" runat="server" src="scripts/csv.js"></script>
<script language="javascript" runat="server">

var text = '123,2.99,AMO024,Title,"Description, more info",,123987564',
    rows = CSV.parse(line);

    Response.Write(rows[0][4]);
</script>

How to split a string and assign it to variables

There's are multiple ways to split a string :

  1. If you want to make it temporary then split like this:

_

import net package

host, port, err := net.SplitHostPort("0.0.0.1:8080")
if err != nil {
fmt.Println("Error is splitting : "+err.error());
//do you code here
}
fmt.Println(host, port)
  1. Split based on struct :

    • Create a struct and split like this

_

type ServerDetail struct {
    Host       string
    Port       string
    err        error
}

ServerDetail = net.SplitHostPort("0.0.0.1:8080") //Specific for Host and Port

Now use in you code like ServerDetail.Host and ServerDetail.Port

If you don't want to split specific string do it like this:

type ServerDetail struct {
    Host       string
    Port       string
}

ServerDetail = strings.Split([Your_String], ":") // Common split method

and use like ServerDetail.Host and ServerDetail.Port.

That's All.

Pandas split DataFrame by column value

Using groupby you could split into two dataframes like

In [1047]: df1, df2 = [x for _, x in df.groupby(df['Sales'] < 30)]

In [1048]: df1
Out[1048]:
   A  Sales
2  7     30
3  6     40
4  1     50

In [1049]: df2
Out[1049]:
   A  Sales
0  3     10
1  4     20

Split a string into array in Perl

You already have multiple answers to your question, but I would like to add another minor one here that might help to add something.

To view data structures in Perl you can use Data::Dumper. To print a string you can use say, which adds a newline character "\n" after every call instead of adding it explicitly.

I usually use \s which matches a whitespace character. If you add + it matches one or more whitespace characters. You can read more about it here perlre.

#!/usr/bin/perl

use strict;
use warnings;

use Data::Dumper;

use feature 'say';

my $line = "file1.gz file2.gz file3.gz";
my @abc  = split /\s+/, $line;

print Dumper \@abc;
say for @abc;

Split string with delimiters in C

Method below will do all the job (memory allocation, counting the length) for you. More information and description can be found here - Implementation of Java String.split() method to split C string

int split (const char *str, char c, char ***arr)
{
    int count = 1;
    int token_len = 1;
    int i = 0;
    char *p;
    char *t;

    p = str;
    while (*p != '\0')
    {
        if (*p == c)
            count++;
        p++;
    }

    *arr = (char**) malloc(sizeof(char*) * count);
    if (*arr == NULL)
        exit(1);

    p = str;
    while (*p != '\0')
    {
        if (*p == c)
        {
            (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
            if ((*arr)[i] == NULL)
                exit(1);

            token_len = 0;
            i++;
        }
        p++;
        token_len++;
    }
    (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
    if ((*arr)[i] == NULL)
        exit(1);

    i = 0;
    p = str;
    t = ((*arr)[i]);
    while (*p != '\0')
    {
        if (*p != c && *p != '\0')
        {
            *t = *p;
            t++;
        }
        else
        {
            *t = '\0';
            i++;
            t = ((*arr)[i]);
        }
        p++;
    }

    return count;
}

How to use it:

int main (int argc, char ** argv)
{
    int i;
    char *s = "Hello, this is a test module for the string splitting.";
    int c = 0;
    char **arr = NULL;

    c = split(s, ' ', &arr);

    printf("found %d tokens.\n", c);

    for (i = 0; i < c; i++)
        printf("string #%d: %s\n", i, arr[i]);

    return 0;
}

How can I convert a comma-separated string to an array?

Pass your comma-separated string into this function and it will return an array, and if a comma-separated string is not found then it will return null.

function splitTheString(CommaSepStr) {
    var ResultArray = null;

    // Check if the string is null or so.
    if (CommaSepStr!= null) {

        var SplitChars = ',';

        // Check if the string has comma of not will go to else
        if (CommaSepStr.indexOf(SplitChars) >= 0) {
            ResultArray = CommaSepStr.split(SplitChars);

        }
        else {

            // The string has only one value, and we can also check
            // the length of the string or time and cross-check too.
            ResultArray = [CommaSepStr];
        }
    }
    return ResultArray;
}

Split string on whitespace in Python

Another method through re module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.

>>> import re
>>> s = "many   fancy word \nhello    \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']

Above regex would match one or more non-space characters.

How can I split a string with a string delimiter?

string[] tokens = str.Split(new[] { "is Marco and" }, StringSplitOptions.None);

If you have a single character delimiter (like for instance ,), you can reduce that to (note the single quotes):

string[] tokens = str.Split(',');

Split data frame string column into multiple columns

Yet another approach: use rbind on out:

before <- data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))  
out <- strsplit(as.character(before$type),'_and_') 
do.call(rbind, out)

     [,1]  [,2]   
[1,] "foo" "bar"  
[2,] "foo" "bar_2"
[3,] "foo" "bar"  
[4,] "foo" "bar_2"

And to combine:

data.frame(before$attr, do.call(rbind, out))

How to split a string into an array of characters in Python?

Well, much as I like the list(s) version, here's another more verbose way I found (but it's cool so I thought I'd add it to the fray):

>>> text = "My hovercraft is full of eels"
>>> [text[i] for i in range(len(text))]
['M', 'y', ' ', 'h', 'o', 'v', 'e', 'r', 'c', 'r', 'a', 'f', 't', ' ', 'i', 's', ' ', 'f', 'u', 'l', 'l', ' ', 'o', 'f', ' ', 'e', 'e', 'l', 's']

equivalent of vbCrLf in c#

"FirstLine" + "<br/>" "SecondLine"

Split large string in n-size chunks in JavaScript

it Split's large string in to Small strings of given words .

function chunkSubstr(str, words) {
  var parts = str.split(" ") , values = [] , i = 0 , tmpVar = "";
  $.each(parts, function(index, value) {
      if(tmpVar.length < words){
          tmpVar += " " + value;
      }else{
          values[i] = tmpVar.replace(/\s+/g, " ");
          i++;
          tmpVar = value;
      }
  });
  if(values.length < 1 &&  parts.length > 0){
      values[0] = tmpVar;
  }
  return values;
}

Attribute Error: 'list' object has no attribute 'split'

what i did was a quick fix by converting readlines to string but i do not recommencement it but it works and i dont know if there are limitations or not

`def getQuakeData():
    filename = input("Please enter the quake file: ")
    readfile = open(filename, "r")
    readlines = str(readfile.readlines())

    Type = readlines.split(",")
    x = Type[1]
    y = Type[2]
    for points in Type:
        print(x,y)
getQuakeData()`

How to split a string into an array in Bash?

All of the answers to this question are wrong in one way or another.


Wrong answer #1

IFS=', ' read -r -a array <<< "$string"

1: This is a misuse of $IFS. The value of the $IFS variable is not taken as a single variable-length string separator, rather it is taken as a set of single-character string separators, where each field that read splits off from the input line can be terminated by any character in the set (comma or space, in this example).

Actually, for the real sticklers out there, the full meaning of $IFS is slightly more involved. From the bash manual:

The shell treats each character of IFS as a delimiter, and splits the results of the other expansions into words using these characters as field terminators. If IFS is unset, or its value is exactly <space><tab><newline>, the default, then sequences of <space>, <tab>, and <newline> at the beginning and end of the results of the previous expansions are ignored, and any sequence of IFS characters not at the beginning or end serves to delimit words. If IFS has a value other than the default, then sequences of the whitespace characters <space>, <tab>, and <newline> are ignored at the beginning and end of the word, as long as the whitespace character is in the value of IFS (an IFS whitespace character). Any character in IFS that is not IFS whitespace, along with any adjacent IFS whitespace characters, delimits a field. A sequence of IFS whitespace characters is also treated as a delimiter. If the value of IFS is null, no word splitting occurs.

Basically, for non-default non-null values of $IFS, fields can be separated with either (1) a sequence of one or more characters that are all from the set of "IFS whitespace characters" (that is, whichever of <space>, <tab>, and <newline> ("newline" meaning line feed (LF)) are present anywhere in $IFS), or (2) any non-"IFS whitespace character" that's present in $IFS along with whatever "IFS whitespace characters" surround it in the input line.

For the OP, it's possible that the second separation mode I described in the previous paragraph is exactly what he wants for his input string, but we can be pretty confident that the first separation mode I described is not correct at all. For example, what if his input string was 'Los Angeles, United States, North America'?

IFS=', ' read -ra a <<<'Los Angeles, United States, North America'; declare -p a;
## declare -a a=([0]="Los" [1]="Angeles" [2]="United" [3]="States" [4]="North" [5]="America")

2: Even if you were to use this solution with a single-character separator (such as a comma by itself, that is, with no following space or other baggage), if the value of the $string variable happens to contain any LFs, then read will stop processing once it encounters the first LF. The read builtin only processes one line per invocation. This is true even if you are piping or redirecting input only to the read statement, as we are doing in this example with the here-string mechanism, and thus unprocessed input is guaranteed to be lost. The code that powers the read builtin has no knowledge of the data flow within its containing command structure.

You could argue that this is unlikely to cause a problem, but still, it's a subtle hazard that should be avoided if possible. It is caused by the fact that the read builtin actually does two levels of input splitting: first into lines, then into fields. Since the OP only wants one level of splitting, this usage of the read builtin is not appropriate, and we should avoid it.

3: A non-obvious potential issue with this solution is that read always drops the trailing field if it is empty, although it preserves empty fields otherwise. Here's a demo:

string=', , a, , b, c, , , '; IFS=', ' read -ra a <<<"$string"; declare -p a;
## declare -a a=([0]="" [1]="" [2]="a" [3]="" [4]="b" [5]="c" [6]="" [7]="")

Maybe the OP wouldn't care about this, but it's still a limitation worth knowing about. It reduces the robustness and generality of the solution.

This problem can be solved by appending a dummy trailing delimiter to the input string just prior to feeding it to read, as I will demonstrate later.


Wrong answer #2

string="1:2:3:4:5"
set -f                     # avoid globbing (expansion of *).
array=(${string//:/ })

Similar idea:

t="one,two,three"
a=($(echo $t | tr ',' "\n"))

(Note: I added the missing parentheses around the command substitution which the answerer seems to have omitted.)

Similar idea:

string="1,2,3,4"
array=(`echo $string | sed 's/,/\n/g'`)

These solutions leverage word splitting in an array assignment to split the string into fields. Funnily enough, just like read, general word splitting also uses the $IFS special variable, although in this case it is implied that it is set to its default value of <space><tab><newline>, and therefore any sequence of one or more IFS characters (which are all whitespace characters now) is considered to be a field delimiter.

This solves the problem of two levels of splitting committed by read, since word splitting by itself constitutes only one level of splitting. But just as before, the problem here is that the individual fields in the input string can already contain $IFS characters, and thus they would be improperly split during the word splitting operation. This happens to not be the case for any of the sample input strings provided by these answerers (how convenient...), but of course that doesn't change the fact that any code base that used this idiom would then run the risk of blowing up if this assumption were ever violated at some point down the line. Once again, consider my counterexample of 'Los Angeles, United States, North America' (or 'Los Angeles:United States:North America').

Also, word splitting is normally followed by filename expansion (aka pathname expansion aka globbing), which, if done, would potentially corrupt words containing the characters *, ?, or [ followed by ] (and, if extglob is set, parenthesized fragments preceded by ?, *, +, @, or !) by matching them against file system objects and expanding the words ("globs") accordingly. The first of these three answerers has cleverly undercut this problem by running set -f beforehand to disable globbing. Technically this works (although you should probably add set +f afterward to reenable globbing for subsequent code which may depend on it), but it's undesirable to have to mess with global shell settings in order to hack a basic string-to-array parsing operation in local code.

Another issue with this answer is that all empty fields will be lost. This may or may not be a problem, depending on the application.

Note: If you're going to use this solution, it's better to use the ${string//:/ } "pattern substitution" form of parameter expansion, rather than going to the trouble of invoking a command substitution (which forks the shell), starting up a pipeline, and running an external executable (tr or sed), since parameter expansion is purely a shell-internal operation. (Also, for the tr and sed solutions, the input variable should be double-quoted inside the command substitution; otherwise word splitting would take effect in the echo command and potentially mess with the field values. Also, the $(...) form of command substitution is preferable to the old `...` form since it simplifies nesting of command substitutions and allows for better syntax highlighting by text editors.)


Wrong answer #3

str="a, b, c, d"  # assuming there is a space after ',' as in Q
arr=(${str//,/})  # delete all occurrences of ','

This answer is almost the same as #2. The difference is that the answerer has made the assumption that the fields are delimited by two characters, one of which being represented in the default $IFS, and the other not. He has solved this rather specific case by removing the non-IFS-represented character using a pattern substitution expansion and then using word splitting to split the fields on the surviving IFS-represented delimiter character.

This is not a very generic solution. Furthermore, it can be argued that the comma is really the "primary" delimiter character here, and that stripping it and then depending on the space character for field splitting is simply wrong. Once again, consider my counterexample: 'Los Angeles, United States, North America'.

Also, again, filename expansion could corrupt the expanded words, but this can be prevented by temporarily disabling globbing for the assignment with set -f and then set +f.

Also, again, all empty fields will be lost, which may or may not be a problem depending on the application.


Wrong answer #4

string='first line
second line
third line'

oldIFS="$IFS"
IFS='
'
IFS=${IFS:0:1} # this is useful to format your code with tabs
lines=( $string )
IFS="$oldIFS"

This is similar to #2 and #3 in that it uses word splitting to get the job done, only now the code explicitly sets $IFS to contain only the single-character field delimiter present in the input string. It should be repeated that this cannot work for multicharacter field delimiters such as the OP's comma-space delimiter. But for a single-character delimiter like the LF used in this example, it actually comes close to being perfect. The fields cannot be unintentionally split in the middle as we saw with previous wrong answers, and there is only one level of splitting, as required.

One problem is that filename expansion will corrupt affected words as described earlier, although once again this can be solved by wrapping the critical statement in set -f and set +f.

Another potential problem is that, since LF qualifies as an "IFS whitespace character" as defined earlier, all empty fields will be lost, just as in #2 and #3. This would of course not be a problem if the delimiter happens to be a non-"IFS whitespace character", and depending on the application it may not matter anyway, but it does vitiate the generality of the solution.

So, to sum up, assuming you have a one-character delimiter, and it is either a non-"IFS whitespace character" or you don't care about empty fields, and you wrap the critical statement in set -f and set +f, then this solution works, but otherwise not.

(Also, for information's sake, assigning a LF to a variable in bash can be done more easily with the $'...' syntax, e.g. IFS=$'\n';.)


Wrong answer #5

countries='Paris, France, Europe'
OIFS="$IFS"
IFS=', ' array=($countries)
IFS="$OIFS"

Similar idea:

IFS=', ' eval 'array=($string)'

This solution is effectively a cross between #1 (in that it sets $IFS to comma-space) and #2-4 (in that it uses word splitting to split the string into fields). Because of this, it suffers from most of the problems that afflict all of the above wrong answers, sort of like the worst of all worlds.

Also, regarding the second variant, it may seem like the eval call is completely unnecessary, since its argument is a single-quoted string literal, and therefore is statically known. But there's actually a very non-obvious benefit to using eval in this way. Normally, when you run a simple command which consists of a variable assignment only, meaning without an actual command word following it, the assignment takes effect in the shell environment:

IFS=', '; ## changes $IFS in the shell environment

This is true even if the simple command involves multiple variable assignments; again, as long as there's no command word, all variable assignments affect the shell environment:

IFS=', ' array=($countries); ## changes both $IFS and $array in the shell environment

But, if the variable assignment is attached to a command name (I like to call this a "prefix assignment") then it does not affect the shell environment, and instead only affects the environment of the executed command, regardless whether it is a builtin or external:

IFS=', ' :; ## : is a builtin command, the $IFS assignment does not outlive it
IFS=', ' env; ## env is an external command, the $IFS assignment does not outlive it

Relevant quote from the bash manual:

If no command name results, the variable assignments affect the current shell environment. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment.

It is possible to exploit this feature of variable assignment to change $IFS only temporarily, which allows us to avoid the whole save-and-restore gambit like that which is being done with the $OIFS variable in the first variant. But the challenge we face here is that the command we need to run is itself a mere variable assignment, and hence it would not involve a command word to make the $IFS assignment temporary. You might think to yourself, well why not just add a no-op command word to the statement like the : builtin to make the $IFS assignment temporary? This does not work because it would then make the $array assignment temporary as well:

IFS=', ' array=($countries) :; ## fails; new $array value never escapes the : command

So, we're effectively at an impasse, a bit of a catch-22. But, when eval runs its code, it runs it in the shell environment, as if it was normal, static source code, and therefore we can run the $array assignment inside the eval argument to have it take effect in the shell environment, while the $IFS prefix assignment that is prefixed to the eval command will not outlive the eval command. This is exactly the trick that is being used in the second variant of this solution:

IFS=', ' eval 'array=($string)'; ## $IFS does not outlive the eval command, but $array does

So, as you can see, it's actually quite a clever trick, and accomplishes exactly what is required (at least with respect to assignment effectation) in a rather non-obvious way. I'm actually not against this trick in general, despite the involvement of eval; just be careful to single-quote the argument string to guard against security threats.

But again, because of the "worst of all worlds" agglomeration of problems, this is still a wrong answer to the OP's requirement.


Wrong answer #6

IFS=', '; array=(Paris, France, Europe)

IFS=' ';declare -a array=(Paris France Europe)

Um... what? The OP has a string variable that needs to be parsed into an array. This "answer" starts with the verbatim contents of the input string pasted into an array literal. I guess that's one way to do it.

It looks like the answerer may have assumed that the $IFS variable affects all bash parsing in all contexts, which is not true. From the bash manual:

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>.

So the $IFS special variable is actually only used in two contexts: (1) word splitting that is performed after expansion (meaning not when parsing bash source code) and (2) for splitting input lines into words by the read builtin.

Let me try to make this clearer. I think it might be good to draw a distinction between parsing and execution. Bash must first parse the source code, which obviously is a parsing event, and then later it executes the code, which is when expansion comes into the picture. Expansion is really an execution event. Furthermore, I take issue with the description of the $IFS variable that I just quoted above; rather than saying that word splitting is performed after expansion, I would say that word splitting is performed during expansion, or, perhaps even more precisely, word splitting is part of the expansion process. The phrase "word splitting" refers only to this step of expansion; it should never be used to refer to the parsing of bash source code, although unfortunately the docs do seem to throw around the words "split" and "words" a lot. Here's a relevant excerpt from the linux.die.net version of the bash manual:

Expansion is performed on the command line after it has been split into words. There are seven kinds of expansion performed: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion.

The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and pathname expansion.

You could argue the GNU version of the manual does slightly better, since it opts for the word "tokens" instead of "words" in the first sentence of the Expansion section:

Expansion is performed on the command line after it has been split into tokens.

The important point is, $IFS does not change the way bash parses source code. Parsing of bash source code is actually a very complex process that involves recognition of the various elements of shell grammar, such as command sequences, command lists, pipelines, parameter expansions, arithmetic substitutions, and command substitutions. For the most part, the bash parsing process cannot be altered by user-level actions like variable assignments (actually, there are some minor exceptions to this rule; for example, see the various compatxx shell settings, which can change certain aspects of parsing behavior on-the-fly). The upstream "words"/"tokens" that result from this complex parsing process are then expanded according to the general process of "expansion" as broken down in the above documentation excerpts, where word splitting of the expanded (expanding?) text into downstream words is simply one step of that process. Word splitting only touches text that has been spit out of a preceding expansion step; it does not affect literal text that was parsed right off the source bytestream.


Wrong answer #7

string='first line
        second line
        third line'

while read -r line; do lines+=("$line"); done <<<"$string"

This is one of the best solutions. Notice that we're back to using read. Didn't I say earlier that read is inappropriate because it performs two levels of splitting, when we only need one? The trick here is that you can call read in such a way that it effectively only does one level of splitting, specifically by splitting off only one field per invocation, which necessitates the cost of having to call it repeatedly in a loop. It's a bit of a sleight of hand, but it works.

But there are problems. First: When you provide at least one NAME argument to read, it automatically ignores leading and trailing whitespace in each field that is split off from the input string. This occurs whether $IFS is set to its default value or not, as described earlier in this post. Now, the OP may not care about this for his specific use-case, and in fact, it may be a desirable feature of the parsing behavior. But not everyone who wants to parse a string into fields will want this. There is a solution, however: A somewhat non-obvious usage of read is to pass zero NAME arguments. In this case, read will store the entire input line that it gets from the input stream in a variable named $REPLY, and, as a bonus, it does not strip leading and trailing whitespace from the value. This is a very robust usage of read which I've exploited frequently in my shell programming career. Here's a demonstration of the difference in behavior:

string=$'  a  b  \n  c  d  \n  e  f  '; ## input string

a=(); while read -r line; do a+=("$line"); done <<<"$string"; declare -p a;
## declare -a a=([0]="a  b" [1]="c  d" [2]="e  f") ## read trimmed surrounding whitespace

a=(); while read -r; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="  a  b  " [1]="  c  d  " [2]="  e  f  ") ## no trimming

The second issue with this solution is that it does not actually address the case of a custom field separator, such as the OP's comma-space. As before, multicharacter separators are not supported, which is an unfortunate limitation of this solution. We could try to at least split on comma by specifying the separator to the -d option, but look what happens:

string='Paris, France, Europe';
a=(); while read -rd,; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France")

Predictably, the unaccounted surrounding whitespace got pulled into the field values, and hence this would have to be corrected subsequently through trimming operations (this could also be done directly in the while-loop). But there's another obvious error: Europe is missing! What happened to it? The answer is that read returns a failing return code if it hits end-of-file (in this case we can call it end-of-string) without encountering a final field terminator on the final field. This causes the while-loop to break prematurely and we lose the final field.

Technically this same error afflicted the previous examples as well; the difference there is that the field separator was taken to be LF, which is the default when you don't specify the -d option, and the <<< ("here-string") mechanism automatically appends a LF to the string just before it feeds it as input to the command. Hence, in those cases, we sort of accidentally solved the problem of a dropped final field by unwittingly appending an additional dummy terminator to the input. Let's call this solution the "dummy-terminator" solution. We can apply the dummy-terminator solution manually for any custom delimiter by concatenating it against the input string ourselves when instantiating it in the here-string:

a=(); while read -rd,; do a+=("$REPLY"); done <<<"$string,"; declare -p a;
declare -a a=([0]="Paris" [1]=" France" [2]=" Europe")

There, problem solved. Another solution is to only break the while-loop if both (1) read returned failure and (2) $REPLY is empty, meaning read was not able to read any characters prior to hitting end-of-file. Demo:

a=(); while read -rd,|| [[ -n "$REPLY" ]]; do a+=("$REPLY"); done <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=$' Europe\n')

This approach also reveals the secretive LF that automatically gets appended to the here-string by the <<< redirection operator. It could of course be stripped off separately through an explicit trimming operation as described a moment ago, but obviously the manual dummy-terminator approach solves it directly, so we could just go with that. The manual dummy-terminator solution is actually quite convenient in that it solves both of these two problems (the dropped-final-field problem and the appended-LF problem) in one go.

So, overall, this is quite a powerful solution. It's only remaining weakness is a lack of support for multicharacter delimiters, which I will address later.


Wrong answer #8

string='first line
        second line
        third line'

readarray -t lines <<<"$string"

(This is actually from the same post as #7; the answerer provided two solutions in the same post.)

The readarray builtin, which is a synonym for mapfile, is ideal. It's a builtin command which parses a bytestream into an array variable in one shot; no messing with loops, conditionals, substitutions, or anything else. And it doesn't surreptitiously strip any whitespace from the input string. And (if -O is not given) it conveniently clears the target array before assigning to it. But it's still not perfect, hence my criticism of it as a "wrong answer".

First, just to get this out of the way, note that, just like the behavior of read when doing field-parsing, readarray drops the trailing field if it is empty. Again, this is probably not a concern for the OP, but it could be for some use-cases. I'll come back to this in a moment.

Second, as before, it does not support multicharacter delimiters. I'll give a fix for this in a moment as well.

Third, the solution as written does not parse the OP's input string, and in fact, it cannot be used as-is to parse it. I'll expand on this momentarily as well.

For the above reasons, I still consider this to be a "wrong answer" to the OP's question. Below I'll give what I consider to be the right answer.


Right answer

Here's a naïve attempt to make #8 work by just specifying the -d option:

string='Paris, France, Europe';
readarray -td, a <<<"$string"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=$' Europe\n')

We see the result is identical to the result we got from the double-conditional approach of the looping read solution discussed in #7. We can almost solve this with the manual dummy-terminator trick:

readarray -td, a <<<"$string,"; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=" Europe" [3]=$'\n')

The problem here is that readarray preserved the trailing field, since the <<< redirection operator appended the LF to the input string, and therefore the trailing field was not empty (otherwise it would've been dropped). We can take care of this by explicitly unsetting the final array element after-the-fact:

readarray -td, a <<<"$string,"; unset 'a[-1]'; declare -p a;
## declare -a a=([0]="Paris" [1]=" France" [2]=" Europe")

The only two problems that remain, which are actually related, are (1) the extraneous whitespace that needs to be trimmed, and (2) the lack of support for multicharacter delimiters.

The whitespace could of course be trimmed afterward (for example, see How to trim whitespace from a Bash variable?). But if we can hack a multicharacter delimiter, then that would solve both problems in one shot.

Unfortunately, there's no direct way to get a multicharacter delimiter to work. The best solution I've thought of is to preprocess the input string to replace the multicharacter delimiter with a single-character delimiter that will be guaranteed not to collide with the contents of the input string. The only character that has this guarantee is the NUL byte. This is because, in bash (though not in zsh, incidentally), variables cannot contain the NUL byte. This preprocessing step can be done inline in a process substitution. Here's how to do it using awk:

readarray -td '' a < <(awk '{ gsub(/, /,"\0"); print; }' <<<"$string, "); unset 'a[-1]';
declare -p a;
## declare -a a=([0]="Paris" [1]="France" [2]="Europe")

There, finally! This solution will not erroneously split fields in the middle, will not cut out prematurely, will not drop empty fields, will not corrupt itself on filename expansions, will not automatically strip leading and trailing whitespace, will not leave a stowaway LF on the end, does not require loops, and does not settle for a single-character delimiter.


Trimming solution

Lastly,

Splitting on last delimiter in Python string?

Use .rsplit() or .rpartition() instead:

s.rsplit(',', 1)
s.rpartition(',')

str.rsplit() lets you specify how many times to split, while str.rpartition() only splits once but always returns a fixed number of elements (prefix, delimiter & postfix) and is faster for the single split case.

Demo:

>>> s = "a,b,c,d"
>>> s.rsplit(',', 1)
['a,b,c', 'd']
>>> s.rsplit(',', 2)
['a,b', 'c', 'd']
>>> s.rpartition(',')
('a,b,c', ',', 'd')

Both methods start splitting from the right-hand-side of the string; by giving str.rsplit() a maximum as the second argument, you get to split just the right-hand-most occurrences.

Getting the last element of a split string array

You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:

array1.split(",").reverse()[0]

It's easy though, but also modifies the original array in question. That might or might not be a problem.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Probably you might want to use this though:

array1.split(",").pop()

How to split a string at the first `/` (slash) and surround part of it in a `<span>`?

Try this

$("div#date").text().trim().replace(/\W/g,'/');

DEMO

Look a regular expression http://regexone.com/lesson/misc_meta_characters

enjoy us ;-)

How do I iterate over the words of a string?

The code below uses strtok() to split a string into tokens and stores the tokens in a vector.

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;


char one_line_string[] = "hello hi how are you nice weather we are having ok then bye";
char seps[]   = " ,\t\n";
char *token;



int main()
{
   vector<string> vec_String_Lines;
   token = strtok( one_line_string, seps );

   cout << "Extracting and storing data in a vector..\n\n\n";

   while( token != NULL )
   {
      vec_String_Lines.push_back(token);
      token = strtok( NULL, seps );
   }
     cout << "Displaying end result in vector line storage..\n\n";

    for ( int i = 0; i < vec_String_Lines.size(); ++i)
    cout << vec_String_Lines[i] << "\n";
    cout << "\n\n\n";


return 0;
}

How do I split a string so I can access item x?

CREATE FUNCTION [dbo].[fnSplitString] 
( 
    @string NVARCHAR(MAX), 
    @delimiter CHAR(1) 
) 
RETURNS @output TABLE(splitdata NVARCHAR(MAX) 
) 
BEGIN 
    DECLARE @start INT, @end INT 
    SELECT @start = 1, @end = CHARINDEX(@delimiter, @string) 
    WHILE @start < LEN(@string) + 1 BEGIN 
        IF @end = 0  
            SET @end = LEN(@string) + 1

        INSERT INTO @output (splitdata)  
        VALUES(SUBSTRING(@string, @start, @end - @start)) 
        SET @start = @end + 1 
        SET @end = CHARINDEX(@delimiter, @string, @start)

    END 
    RETURN 
END

AND USE IT

select *from dbo.fnSplitString('Querying SQL Server','')

How does strtok() split the string into tokens in C?

So, this is a code snippet to help better understand this topic.

Printing Tokens

Task: Given a sentence, s, print each word of the sentence in a new line.

char *s;
s = malloc(1024 * sizeof(char));
scanf("%[^\n]", s);
s = realloc(s, strlen(s) + 1);
//logic to print the tokens of the sentence.
for (char *p = strtok(s," "); p != NULL; p = strtok(NULL, " "))
{
    printf("%s\n",p);
}

Input: How is that

Result:

How
is
that

Explanation: So here, "strtok()" function is used and it's iterated using for loop to print the tokens in separate lines.

The function will take parameters as 'string' and 'break-point' and break the string at those break-points and form tokens. Now, those tokens are stored in 'p' and are used further for printing.

Splitting a string at every n-th character

import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        for (String part : getParts("foobarspam", 3)) {
            System.out.println(part);
        }
    }
    private static List<String> getParts(String string, int partitionSize) {
        List<String> parts = new ArrayList<String>();
        int len = string.length();
        for (int i=0; i<len; i+=partitionSize)
        {
            parts.add(string.substring(i, Math.min(len, i + partitionSize)));
        }
        return parts;
    }
}

Split String by delimiter position using oracle SQL

Therefore, I would like to separate the string by the furthest delimiter.

I know this is an old question, but this is a simple requirement for which SUBSTR and INSTR would suffice. REGEXP are still slower and CPU intensive operations than the old subtsr and instr functions.

SQL> WITH DATA AS
  2    ( SELECT 'F/P/O' str FROM dual
  3    )
  4  SELECT SUBSTR(str, 1, Instr(str, '/', -1, 1) -1) part1,
  5         SUBSTR(str, Instr(str, '/', -1, 1) +1) part2
  6  FROM DATA
  7  /

PART1 PART2
----- -----
F/P   O

As you said you want the furthest delimiter, it would mean the first delimiter from the reverse.

You approach was fine, but you were missing the start_position in INSTR. If the start_position is negative, the INSTR function counts back start_position number of characters from the end of string and then searches towards the beginning of string.

Split a List into smaller lists of N size

how about:

while(locations.Any())
{    
    list.Add(locations.Take(nSize).ToList());
    locations= locations.Skip(nSize).ToList();
}

split string only on first instance - java

String[] func(String apple){
String[] tmp = new String[2];
for(int i=0;i<apple.length;i++){
   if(apple.charAt(i)=='='){
      tmp[0]=apple.substring(0,i);
      tmp[1]=apple.substring(i+1,apple.length);
      break;
   }
}
return tmp;
}
//returns string_ARRAY_!

i like writing own methods :)

Split a string by a delimiter in python

When you have two or more (in the example below there're three) elements in the string, then you can use comma to separate these items:

date, time, event_name = ev.get_text(separator='@').split("@")

After this line of code, the three variables will have values from three parts of the variable ev

So, if the variable ev contains this string and we apply separator '@':

Sa., 23. März@19:00@Klavier + Orchester: SPEZIAL

Then, after split operation the variable

  • date will have value "Sa., 23. März"
  • time will have value "19:00"
  • event_name will have value "Klavier + Orchester: SPEZIAL"

Scanner vs. StringTokenizer vs. String.Split

StringTokenizer was always there. It is the fastest of all, but the enumeration-like idiom might not look as elegant as the others.

split came to existence on JDK 1.4. Slower than tokenizer but easier to use, since it is callable from the String class.

Scanner came to be on JDK 1.5. It is the most flexible and fills a long standing gap on the Java API to support an equivalent of the famous Cs scanf function family.

Java equivalent to Explode and Implode(PHP)

The Javadoc for String reveals that String.split() is what you're looking for in regard to explode.

Java does not include a "implode" of "join" equivalent. Rather than including a giant external dependency for a simple function as the other answers suggest, you may just want to write a couple lines of code. There's a number of ways to accomplish that; using a StringBuilder is one:

String foo = "This,that,other";
String[] split = foo.split(",");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
    sb.append(split[i]);
    if (i != split.length - 1) {
        sb.append(" ");
    }
}
String joined = sb.toString();

Splitting a dataframe string column into multiple different columns

We could use tidyr::extract()

x <- c("F.US.CLE.V13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", "F.US.CA6.U13", 
  "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.U13", "F.US.DL.Z13", "F.US.DL.Z13"
)


library(tidyr)
extract(tibble(data=x),"data", regex = "^(.*?)\\.(.*?)\\.(.*?)\\.(.*?)$",into = LETTERS[1:4])
#> # A tibble: 13 x 4
#>    A     B     C     D    
#>    <chr> <chr> <chr> <chr>
#>  1 F     US    CLE   V13  
#>  2 F     US    CA6   U13  
#>  3 F     US    CA6   U13  
#>  4 F     US    CA6   U13  
#>  5 F     US    CA6   U13  
#>  6 F     US    CA6   U13  
#>  7 F     US    CA6   U13  
#>  8 F     US    CA6   U13  
#>  9 F     US    DL    U13  
#> 10 F     US    DL    U13  
#> 11 F     US    DL    U13  
#> 12 F     US    DL    Z13  
#> 13 F     US    DL    Z13

Another option is to use unglue::unglue_data()

# remotes::install_github("moodymudskipper/unglue")
library(unglue)
unglue_data(x,"{A}.{B}.{C}.{D}")
#>    A  B   C   D
#> 1  F US CLE V13
#> 2  F US CA6 U13
#> 3  F US CA6 U13
#> 4  F US CA6 U13
#> 5  F US CA6 U13
#> 6  F US CA6 U13
#> 7  F US CA6 U13
#> 8  F US CA6 U13
#> 9  F US  DL U13
#> 10 F US  DL U13
#> 11 F US  DL U13
#> 12 F US  DL Z13
#> 13 F US  DL Z13

Created on 2019-09-14 by the reprex package (v0.3.0)

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'

Excel CSV. file with more than 1,048,576 rows of data

If you have Matlab, you can open large CSV (or TXT) files via its import facility. The tool gives you various import format options including tables, column vectors, numeric matrix, etc. However, with Matlab being an interpreter package, it does take its own time to import such a large file and I was able to import one with more than 2 million rows in about 10 minutes.

The tool is accessible via Matlab's Home tab by clicking on the "Import Data" button. An example image of a large file upload is shown below: enter image description here Once imported, the data appears on the right-hand-side Workspace, which can then be double-clicked in an Excel-like format and even be plotted in different formats. enter image description here

How to extract a string between two delimiters

If there is only 1 occurrence, the answer of ivanovic is the best way I guess. But if there are many occurrences, you should use regexp:

\[(.*?)\] this is your pattern. And in each group(1) will get you your string.

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(input);
while(m.find())
{
    m.group(1); //is your string. do what you want
}

How to split CSV files as per number of rows specified?

Use the Linux split command:

split -l 20 file.txt new    

Split the file "file.txt" into files beginning with the name "new" each containing 20 lines of text each.

Type man split at the Unix prompt for more information. However you will have to first remove the header from file.txt (using the tail command, for example) and then add it back on to each of the split files.

How to count the number of lines of a string in javascript

To split using a regex use /.../

lines = str.split(/\r\n|\r|\n/); 

Parameter "stratify" from method "train_test_split" (scikit Learn)

This stratify parameter makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to parameter stratify.

For example, if variable y is a binary categorical variable with values 0 and 1 and there are 25% of zeros and 75% of ones, stratify=y will make sure that your random split has 25% of 0's and 75% of 1's.

Split string with JavaScript

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Uncaught TypeError: Cannot read property 'split' of undefined

og_date = "2012-10-01";
console.log(og_date); // => "2012-10-01"

console.log(og_date.split('-')); // => [ '2012', '10', '01' ]

og_date.value would only work if the date were stored as a property on the og_date object. Such as: var og_date = {}; og_date.value="2012-10-01"; In that case, your original console.log would work.

Split function in oracle to comma separated values with automatic sequence

Best Query For comma separated in This Query we Convert Rows To Column ...

SELECT listagg(BL_PRODUCT_DESC, ', ') within
   group(   order by BL_PRODUCT_DESC) PROD
  FROM GET_PRODUCT
--  WHERE BL_PRODUCT_DESC LIKE ('%WASH%')
  WHERE Get_Product_Type_Id = 6000000000007

How to split strings into text and number?

import re

s = raw_input()
m = re.match(r"([a-zA-Z]+)([0-9]+)",s)
print m.group(0)
print m.group(1)
print m.group(2)

Java String split removed empty values

From String.split() API Doc:

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Overloaded String.split(regex, int) is more appropriate for your case.

Get first word of string

Use regular expression

_x000D_
_x000D_
var totalWords = "foo love bar very much.";_x000D_
_x000D_
var firstWord = totalWords.replace(/ .*/,'');_x000D_
_x000D_
$('body').append(firstWord);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Reading a text file and splitting it into single words in python

As supplementary, if you are reading a vvvvery large file, and you don't want read all of the content into memory at once, you might consider using a buffer, then return each word by yield:

def read_words(inputfile):
    with open(inputfile, 'r') as f:
        while True:
            buf = f.read(10240)
            if not buf:
                break

            # make sure we end on a space (word boundary)
            while not str.isspace(buf[-1]):
                ch = f.read(1)
                if not ch:
                    break
                buf += ch

            words = buf.split()
            for word in words:
                yield word
        yield '' #handle the scene that the file is empty

if __name__ == "__main__":
    for word in read_words('./very_large_file.txt'):
        process(word)

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

Some clean solution without using regular expressions:

/**
* Create array with maximum chunk length = maxPartSize
* It work safe also for shorter strings than part size
**/
function convertStringToArray(str, maxPartSize){

  const chunkArr = [];
  let leftStr = str;
  do {

    chunkArr.push(leftStr.substring(0, maxPartSize));
    leftStr = leftStr.substring(maxPartSize, leftStr.length);

  } while (leftStr.length > 0);

  return chunkArr;
};

Usage example - https://jsfiddle.net/maciejsikora/b6xppj4q/.

I also tried to compare my solution to regexp one which was chosen as right answer. Some test can be found on jsfiddle - https://jsfiddle.net/maciejsikora/2envahrk/. Tests are showing that both methods have similar performance, maybe on first look regexp solution is little bit faster, but judge it Yourself.

Split comma separated column data into additional columns

You can use split function.

    SELECT 
    (select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
    (select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
    (select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
    (select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
    FROM MyTbl

How to split a string with any whitespace chars as delimiters

String str = "Hello   World";
String res[] = str.split("\\s+");

How to split the name string in mysql?

First Create Procedure as Below:

CREATE DEFINER=`root`@`%` PROCEDURE `sp_split`(str nvarchar(6500), dilimiter varchar(15), tmp_name varchar(50))
BEGIN

    declare end_index   int;
    declare part        nvarchar(6500);
    declare remain_len  int;

    set end_index      = INSTR(str, dilimiter);

    while(end_index   != 0) do

        /* Split a part */
        set part       = SUBSTRING(str, 1, end_index - 1);

        /* insert record to temp table */
        call `sp_split_insert`(tmp_name, part);

        set remain_len = length(str) - end_index;
        set str = substring(str, end_index + 1, remain_len);

        set end_index  = INSTR(str, dilimiter);

    end while;

    if(length(str) > 0) then

        /* insert record to temp table */
        call `sp_split_insert`(tmp_name, str);

    end if;

END

After that create procedure as below:

CREATE DEFINER=`root`@`%` PROCEDURE `sp_split_insert`(tb_name varchar(255), tb_value nvarchar(6500))
BEGIN
    SET @sql = CONCAT('Insert Into ', tb_name,'(item) Values(?)'); 
    PREPARE s1 from @sql;
    SET @paramA = tb_value;
    EXECUTE s1 USING @paramA;
END

How call test

CREATE DEFINER=`root`@`%` PROCEDURE `test_split`(test_text nvarchar(255))
BEGIN

    create temporary table if not exists tb_search
        (
            item nvarchar(6500)
        );

    call sp_split(test_split, ',', 'tb_search');

    select * from tb_search where length(trim(item)) > 0;

    drop table tb_search;

END


call `test_split`('Apple,Banana,Mengo');

Easiest way to split a string on newlines in .NET?

You should be able to split your string pretty easily, like so:

aString.Split(Environment.NewLine.ToCharArray());

Split string into array

Use split method:

entry = prompt("Enter your name");
entryArray = entry.split("");

Refer String.prototype.split() for more info.

How would I get everything before a : in a string Python

You don't need regex for this

>>> s = "Username: How are you today?"

You can use the split method to split the string on the ':' character

>>> s.split(':')
['Username', ' How are you today?']

And slice out element [0] to get the first part of the string

>>> s.split(':')[0]
'Username'

How to split a string after specific character in SQL Server and update this value to specific column

Try this:

UPDATE YourTable
SET Col2 = RIGHT(Col1,LEN(Col1)-CHARINDEX('/',Col1))

How to split large text file in windows?

Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
    Set rs = CreateObject("ADODB.Recordset")
    With rs
        .Fields.Append "LineNumber", 4 

        .Fields.Append "Txt", 201, 5000 
        .Open
        LineCount = 0
        Do Until Inp.AtEndOfStream
            LineCount = LineCount + 1
            .AddNew
            .Fields("LineNumber").value = LineCount
            .Fields("Txt").value = Inp.readline
            .UpDate
        Loop

        .Sort = "LineNumber ASC"

        If LCase(Arg(1)) = "t" then
            If LCase(Arg(2)) = "i" then
                .filter = "LineNumber < " & LCase(Arg(3)) + 1
            ElseIf LCase(Arg(2)) = "x" then
                .filter = "LineNumber > " & LCase(Arg(3))
            End If
        ElseIf LCase(Arg(1)) = "b" then
            If LCase(Arg(2)) = "i" then
                .filter = "LineNumber > " & LineCount - LCase(Arg(3))
            ElseIf LCase(Arg(2)) = "x" then
                .filter = "LineNumber < " & LineCount - LCase(Arg(3)) + 1
            End If
        End If

        Do While not .EOF
            Outp.writeline .Fields("Txt").Value

            .MoveNext
        Loop
    End With

Cut

filter cut {t|b} {i|x} NumOfLines

Cuts the number of lines from the top or bottom of file.

t - top of the file
b - bottom of the file
i - include n lines
x - exclude n lines

Example

cscript /nologo filter.vbs cut t i 5 < "%systemroot%\win.ini"

Another way This outputs lines 5001+, adapt for your use. This uses almost no memory.

Do Until Inp.AtEndOfStream
         Count = Count + 1
         If count > 5000 then
            OutP.WriteLine Inp.Readline
         End If
Loop

How can I split a text into sentences?

No doubt that NLTK is the most suitable for the purpose. But getting started with NLTK is quite painful (But once you install it - you just reap the rewards)

So here is simple re based code available at http://pythonicprose.blogspot.com/2009/09/python-split-paragraph-into-sentences.html

# split up a paragraph into sentences
# using regular expressions


def splitParagraphIntoSentences(paragraph):
    ''' break a paragraph into sentences
        and return a list '''
    import re
    # to split by multile characters

    #   regular expressions are easiest (and fastest)
    sentenceEnders = re.compile('[.!?]')
    sentenceList = sentenceEnders.split(paragraph)
    return sentenceList


if __name__ == '__main__':
    p = """This is a sentence.  This is an excited sentence! And do you think this is a question?"""

    sentences = splitParagraphIntoSentences(p)
    for s in sentences:
        print s.strip()

#output:
#   This is a sentence
#   This is an excited sentence

#   And do you think this is a question 

How to split a string by spaces in a Windows batch file?

Here is a solution based on a "function" which processes each character until it finds the delimiter character.

It is relatively slow, but it is at least not a brain teaser (except for the function part).

:: Example #1:
set data=aa bb cc
echo Splitting off from "%data%":
call :split_once "%data%" " " "left" "right"
echo Split off: %left%
echo Remaining: %right%
echo.

:: Example #2:
echo List of paths in PATH env var:
set paths=%PATH%
:loop
    call :split_once "%paths%" ";" "left" "paths"
    if "%left%" equ "" goto loop_end
    echo %left%
goto loop
:loop_end



:: HERE BE FUNCTIONS
goto :eof

:: USAGE:
::   call :split_once "string to split once" "delimiter_char" "left_var" "right_var"
:split_once
    setlocal
    set right=%~1
    set delimiter_char=%~2
    set left=

    if "%right%" equ "" goto split_once_done

    :split_once_loop
        if "%right:~0,1%" equ "%delimiter_char%" set right=%right:~1%&& goto split_once_done
        if "%right:~0,1%" neq "%delimiter_char%" set left=%left%%right:~0,1%
        if "%right:~0,1%" neq "%delimiter_char%" set right=%right:~1%
        if "%right%" equ "" goto split_once_done
    goto split_once_loop

    :split_once_done
    endlocal & set %~3=%left%& set %~4=%right%
goto:eof

Split value from one field to two

The only case where you may want such a function is an UPDATE query which will alter your table to store Firstname and Lastname into separate fields.

Database design must follow certain rules, and Database Normalization is among most important ones

How to split a string in Java

import java.io.*;

public class BreakString {

  public static void main(String args[]) {

    String string = "004-034556-1234-2341";
    String[] parts = string.split("-");

    for(int i=0;i<parts.length;i++) {
      System.out.println(parts[i]);
    }
  }
}

A method to reverse effect of java String.split()?

There has been an open feature request since at least 2009. The long and short of it is that it will part of the functionality of JDK 8's java.util.StringJoiner class. http://download.java.net/lambda/b81/docs/api/java/util/StringJoiner.html

Here is the Oracle issue if you are interested. http://bugs.sun.com/view_bug.do?bug_id=5015163

Here is an example of the new JDK 8 StringJoiner on an array of String

String[] a = new String[]{"first","second","third"};
StringJoiner sj = new StringJoiner(",");
for(String s:a) sj.add(s);
System.out.println(sj); //first,second,third

A utility method in String makes this even simpler:

String s = String.join(",", stringArray);

String split on new line, tab and some number of spaces

Regex's aren't really the best tool for the job here. As others have said, using a combination of str.strip() and str.split() is the way to go. Here's a one liner to do it:

>>> data = '''\n\tName: John Smith
... \n\t  Home: Anytown USA
... \n\t    Phone: 555-555-555
... \n\t  Other Home: Somewhere Else
... \n\t Notes: Other data
... \n\tName: Jane Smith
... \n\t  Misc: Data with spaces'''
>>> {line.strip().split(': ')[0]:line.split(': ')[1] for line in data.splitlines() if line.strip() != ''}
{'Name': 'Jane Smith', 'Other Home': 'Somewhere Else', 'Notes': 'Other data', 'Misc': 'Data with spaces', 'Phone': '555-555-555', 'Home': 'Anytown USA'}

How to use split?

Documentation can be found e.g. at MDN. Note that .split() is not a jQuery method, but a native string method.

If you use .split() on a string, then you get an array back with the substrings:

var str = 'something -- something_else';
var substr = str.split(' -- ');
// substr[0] contains "something"
// substr[1] contains "something_else"

If this value is in some field you could also do:

tRow.append($('<td>').text($('[id$=txtEntry2]').val().split(' -- ')[0])));

Split string in JavaScript and detect line break

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

Python read in string from file and split it into values

Use open(file, mode) for files. The mode is a variant of 'r' for read, 'w' for write, and possibly 'b' appended (e.g., 'rb') to open binary files. See the link below.

Use open with readline() or readlines(). The former will return a line at a time, while the latter returns a list of the lines.

Use split(delimiter) to split on the comma.

Lastly, you need to cast each item to an integer: int(foo). You'll probably want to surround your cast with a try block followed by except ValueError as in the link below.

You can also use 'multiple assignment' to assign a and b at once:

>>>a, b = map(int, "2342342,2234234".split(","))  
>>>print a  
2342342
>>>type(a)  
<type 'int'>

python io docs

python casting

How to split a delimited string into an array in awk?

Joke? :)

How about echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

This is my output:

p2> echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'
112312

so I guess it's working after all..

How can I split and parse a string in Python?

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

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

String.split takes a regex, and '.' has a special meaning for regexes.

You (probably) want something like:

String[] words = line.split("\\.");

Some folks seem to be having trouble getting this to work, so here is some runnable code you can use to verify correct behaviour.

import java.util.Arrays;

public class TestSplit {
  public static void main(String[] args) {
    String line = "aa.bb.cc.dd";
    String[] words = line.split("\\.");
    System.out.println(Arrays.toString(words));
    // Output is "[aa, bb, cc, dd]"
  }
}

string.split - by multiple character delimiter

More fast way using directly a no-string array but a string:

string[] StringSplit(string StringToSplit, string Delimitator)
{
    return StringToSplit.Split(new[] { Delimitator }, StringSplitOptions.None);
}

StringSplit("E' una bella giornata oggi", "giornata");
/* Output
[0] "E' una bella giornata"
[1] " oggi"
*/

splitting a number into the integer and decimal parts

I have come up with two statements that can divide positive and negative numbers into integers and fractions without compromising accuracy (bit overflow) and speed.

x = 100.1323 # A number to be divided into integers and fractions

# The two statement to divided a number into integers and fractions
i = int(x) # A positive or negative integer
f = (x*1e17-i*1e17)/1e17 # A positive or negative fraction

E.g. 100.1323 -> 100, 0.1323 or -100.1323 -> -100, -0.1323

Speedtest

The performance test shows that the two statements are faster than math.modf, as long as they are not put into their own function or method.

test.py:

#!/usr/bin/env python
import math
import cProfile

""" Get the performance of both statements and math.modf. """

X = -100.1323 # The number to be divided into integers and fractions
LOOPS = range(5*10**6) # Number of loops

def scenario_a():
    """ The integers (i) and the fractions (f)
        come out as integer and float. """
    for _ in LOOPS:
        i = int(X) # -100
        f = (X*1e17-i*1e17)/1e17 # -0.1323

def scenario_b():
    """ The integers (i) and the fractions (f)
        come out as float.
        NOTE: The only difference between this
              and math.modf is the accuracy. """
    for _ in LOOPS:
        i = int(X) # -100
        i, f = float(i), (X*1e17-i*1e17)/1e17 # (-100.0, -0.1323)

def scenario_c():
    """ Performance test of the statements in a function. """
    def modf(x):
        i = int(x)
        return i, (x*1e17-i*1e17)/1e17

    for _ in LOOPS:
        i, f = modf(X) # (-100, -0.1323)

def scenario_d():
    for _ in LOOPS:
        f, i = math.modf(X) # (-100.0, -0.13230000000000075)

def scenario_e():
    """ Convert the integer part to real integer. """
    for _ in LOOPS:
        f, i = math.modf(X) # (-100.0, -0.13230000000000075)
        i = int(i) # -100

if __name__ == '__main__':
    cProfile.run('scenario_a()')
    cProfile.run('scenario_b()')
    cProfile.run('scenario_c()')
    cProfile.run('scenario_d()')
    cProfile.run('scenario_e()')

Output:

         4 function calls in 1.312 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.312    1.312 <string>:1(<module>)
        1    1.312    1.312    1.312    1.312 test.py:10(scenario_a)
        1    0.000    0.000    1.312    1.312 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         4 function calls in 1.887 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.887    1.887 <string>:1(<module>)
        1    1.887    1.887    1.887    1.887 test.py:18(scenario_b)
        1    0.000    0.000    1.887    1.887 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         5000004 function calls in 2.797 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.797    2.797 <string>:1(<module>)
        1    1.261    1.261    2.797    2.797 test.py:27(scenario_c)
  5000000    1.536    0.000    1.536    0.000 test.py:31(modf)
        1    0.000    0.000    2.797    2.797 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         5000004 function calls in 1.852 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    1.852    1.852 <string>:1(<module>)
        1    1.050    1.050    1.852    1.852 test.py:38(scenario_d)
        1    0.000    0.000    1.852    1.852 {built-in method builtins.exec}
  5000000    0.802    0.000    0.802    0.000 {built-in method math.modf}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}


         5000004 function calls in 2.467 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.467    2.467 <string>:1(<module>)
        1    1.652    1.652    2.467    2.467 test.py:42(scenario_e)
        1    0.000    0.000    2.467    2.467 {built-in method builtins.exec}
  5000000    0.815    0.000    0.815    0.000 {built-in method math.modf}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

NOTE:

The statement can be faster with modulo, but modulo can not be used to split negative numbers into integer and fraction parts.

i, f = int(x), x*1e17%1e17/1e17 # x can not be negative

What is causing the error `string.split is not a function`?

Change this...

var string = document.location;

to this...

var string = document.location + '';

This is because document.location is a Location object. The default .toString() returns the location in string form, so the concatenation will trigger that.


You could also use document.URL to get a string.

Java split string to array

This is expected. Refer to Javadocs for split.

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

The split() method in Java does not work on a dot (.)

The documentation on split() says:

Splits this string around matches of the given regular expression.

(Emphasis mine.)

A dot is a special character in regular expression syntax. Use Pattern.quote() on the parameter to split() if you want the split to be on a literal string pattern:

String[] words = temp.split(Pattern.quote("."));

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'

Splitting a continuous variable into equal sized groups

ntile from dplyr now does this but behaves weirdly with NA's.

I've used similar code in the following function that works in base R and does the equivalent of the cut2 solution above:

ntile_ <- function(x, n) {
    b <- x[!is.na(x)]
    q <- floor((n * (rank(b, ties.method = "first") - 1)/length(b)) + 1)
    d <- rep(NA, length(x))
    d[!is.na(x)] <- q
    return(d)
}

Is there a function in python to split a word into a list?

Abuse of the rules, same result: (x for x in 'Word to split')

Actually an iterator, not a list. But it's likely you won't really care.

Split text file into smaller multiple text file using command line

here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.

var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);

using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        sw.WriteLine(reader.ReadLine());
        lines++;

        if (lines >= 10000000)
        {
              sw.Close();
              fstream.Close();
              lines = 0;
              fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
              sw = new StreamWriter(fstream);
        }
    }
}

sw.Close();
fstream.Close();

Split string with multiple delimiters in Python

Do a str.replace('; ', ', ') and then a str.split(', ')

How to Split Image Into Multiple Pieces in Python

As an alternative to other solutions, we will construct the tiles by generating a grid of coordinates using itertools.product. We will ignore partial tiles on the edges, only iterating through the Cartesian product between the two intervals, i.e. range(0, h-h%d, d) X range(0, w-w%d, d).

Given fp: the file name to the image, d: the tile size, opt.path: the path to the directory containing the images, and opt.out: is the directory where tiles will be outputted:

def tile(filename, dir_in, dir_out, d):
    name, ext = os.path.splitext(filename)
    img = Image.open(os.path.join(dir_in, fp))
    w, h = img.size
    
    grid = list(product(range(0, h-h%d, d), range(0, w-w%d, d)))
    for i, j in grid:
        box = (j, i, j+d, i+d)
        out = os.path.join(dir_out, f'{name}_{i}_{j}{ext}')
        img.crop(box).save(out)

enter image description here

Python 2: AttributeError: 'list' object has no attribute 'strip'

You can first concatenate the strings in the list with the separator ';' using the function join and then use the split function in order create the list:

l = ['Facebook;Google+;MySpace', 'Apple;Android']

l1 = ";".join(l)).split(";")  

print l1

outputs

['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

To switch from vertical split to horizontal split fast in Vim

Ctrl-w followed by H, J, K or L (capital) will move the current window to the far left, bottom, top or right respectively like normal cursor navigation.

The lower case equivalents move focus instead of moving the window.

How to convert comma-separated String to List?

There are many ways to solve this using streams in Java 8 but IMO the following one liners are straight forward:

String  commaSeparated = "item1 , item2 , item3";
List<String> result1 = Arrays.stream(commaSeparated.split(" , "))
                                             .collect(Collectors.toList());
List<String> result2 = Stream.of(commaSeparated.split(" , "))
                                             .collect(Collectors.toList());

PHP: Split string into array, like explode with no delimiter

$array = str_split("$string");

will actuall work pretty fine, BUT if you want to preserve the special characters in that string, and you want to do some manipulation with them, THAN I would use

do {
    $array[] = mb_substr( $string, 0, 1, 'utf-8' );
} while ( $string = mb_substr( $string, 1, mb_strlen( $string ), 'utf-8' ) );

because for some of mine personal uses, it has been shown to be more reliable when there is an issue with special characters

How to split one string into multiple strings separated by at least one space in bash shell?

echo $WORDS | xargs -n1 echo

This outputs every word, you can process that list as you see fit afterwards.

How to split elements of a list?

I had to split a list for feature extraction in two parts lt,lc:

ltexts = ((df4.ix[0:,[3,7]]).values).tolist()
random.shuffle(ltexts)

featsets = [(act_features((lt)),lc) 
              for lc, lt in ltexts]

def act_features(atext):
  features = {}
  for word in nltk.word_tokenize(atext):
     features['cont({})'.format(word.lower())]=True
  return features

Split Java String by New Line

There are three different conventions (it could be said that those are de facto standards) to set and display a line break:

  • carriage return + line feed
  • line feed
  • carriage return

In some text editors, it is possible to exchange one for the other:

Notepad++

The simplest thing is to normalize to line feedand then split.

final String[] lines = contents.replace("\r\n", "\n")
                               .replace("\r", "\n")
                               .split("\n", -1);

PHP: Split string

to explode with '.' use

explode('\\.','a.b');

Split pandas dataframe in two if it has more than 10 rows

The method based on list comprehension and groupby, which stores all the split dataframes in a list variable and can be accessed using the index.

Example:

ans = [pd.DataFrame(y) for x, y in DF.groupby('column_name', as_index=False)]***
ans[0]
ans[0].column_name

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

stale element reference: element is not attached to the page document

To handle it, I use the following click method. This will attempt to find and click the element. If the DOM changes between the find and click, it will try again. The idea is that if it failed and I try again immediately the second attempt will succeed. If the DOM changes are very rapid then this will not work.

public boolean retryingFindClick(By by) {
    boolean result = false;
    int attempts = 0;
    while(attempts < 2) {
        try {
            driver.findElement(by).click();
            result = true;
            break;
        } catch(StaleElementException e) {
        }
        attempts++;
    }
    return result;
}

HTML entity for the middle dot

That's a bullet: •

&bull;

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

No grammar constraints (DTD or XML schema) detected for the document

Here's the working solution for this problem:


Step 1: Right click on project and go to properties

Step 2: Go to 'libraries' and remove the project's ' JRE system library'

Step 3: Click on 'Add library'-->'JRE System Library' -->select 'Workspace default JRE'

Step 3: Go to 'Order and Export' and mark the newly added ' JRE system library'

Step 4: Refresh and Clean the project

Eureka! It's working :)

Can you "compile" PHP code and upload a binary-ish file, which will just be run by the byte code interpreter?

see 5.5.x with the integrated OPcache module, volatile in a shared memory, much more performance and the dynamism principle of php remain untouched.

http://www.php.net/manual/en/opcache.installation.php

How to add a class to a given element?

I know IE9 is shutdown officially and we can achieve it with element.classList as many told above but I just tried to learn how it works without classList with help of many answers above I could learn it.

Below code extends many answers above and improves them by avoiding adding duplicate classes.

function addClass(element,className){
  var classArray = className.split(' ');
  classArray.forEach(function (className) {
    if(!hasClass(element,className)){
      element.className += " "+className;
    }
  });            
}
//this will add 5 only once
addClass(document.querySelector('#getbyid'),'3 4 5 5 5');

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

I had the same problem. Get the warning. Went to Data connections and deleted connection. Save, close reopen. Still get the warning. I use a xp/vista menu plugin for classic menus. I found under data, get external data, properties, uncheck the save query definition. Save close and reopen. That seemed to get rid of the warning. Just removing the connection does not work. You have to get rid of the query.

The difference between "require(x)" and "import x"

Let me give an example for Including express module with require & import

-require

var express = require('express');

-import

import * as  express from 'express';

So after using any of the above statement we will have a variable called as 'express' with us. Now we can define 'app' variable as,

var app = express(); 

So we use 'require' with 'CommonJS' and 'import' with 'ES6'.

For more info on 'require' & 'import', read through below links.

require - Requiring modules in Node.js: Everything you need to know

import - An Update on ES6 Modules in Node.js

How do you share constants in NodeJS modules?

Since Node.js is using the CommonJS patterns, you can only share variables between modules with module.exports or by setting a global var like you would in the browser, but instead of using window you use global.your_var = value;.

vertical & horizontal lines in matplotlib

If you want to add a bounding box, use a rectangle:

ax = plt.gca()
r = matplotlib.patches.Rectangle((.5, .5), .25, .1, fill=False)
ax.add_artist(r)

Rectangle doc

SOAP PHP fault parsing WSDL: failed to load external entity?

I am using selinux and with the following shell command (as root) I was able to allow PHP to make SOAP calls:

sudo setsebool -P httpd_can_network_connect on

AngularJS: Basic example to use authentication in Single Page Application

I've created a github repo summing up this article basically: https://medium.com/opinionated-angularjs/techniques-for-authentication-in-angularjs-applications-7bbf0346acec

ng-login Github repo

Plunker

I'll try to explain as good as possible, hope I help some of you out there:

(1) app.js: Creation of authentication constants on app definition

var loginApp = angular.module('loginApp', ['ui.router', 'ui.bootstrap'])
/*Constants regarding user login defined here*/
.constant('USER_ROLES', {
    all : '*',
    admin : 'admin',
    editor : 'editor',
    guest : 'guest'
}).constant('AUTH_EVENTS', {
    loginSuccess : 'auth-login-success',
    loginFailed : 'auth-login-failed',
    logoutSuccess : 'auth-logout-success',
    sessionTimeout : 'auth-session-timeout',
    notAuthenticated : 'auth-not-authenticated',
    notAuthorized : 'auth-not-authorized'
})

(2) Auth Service: All following functions are implemented in auth.js service. The $http service is used to communicate with the server for the authentication procedures. Also contains functions on authorization, that is if the user is allowed to perform a certain action.

angular.module('loginApp')
.factory('Auth', [ '$http', '$rootScope', '$window', 'Session', 'AUTH_EVENTS', 
function($http, $rootScope, $window, Session, AUTH_EVENTS) {

authService.login() = [...]
authService.isAuthenticated() = [...]
authService.isAuthorized() = [...]
authService.logout() = [...]

return authService;
} ]);

(3) Session: A singleton to keep user data. The implementation here depends on you.

angular.module('loginApp').service('Session', function($rootScope, USER_ROLES) {

    this.create = function(user) {
        this.user = user;
        this.userRole = user.userRole;
    };
    this.destroy = function() {
        this.user = null;
        this.userRole = null;
    };
    return this;
});

(4) Parent controller: Consider this as the "main" function of your application, all controllers inherit from this controller, and it's the backbone of the authentication of this app.

<body ng-controller="ParentController">
[...]
</body>

(5) Access control: To deny access on certain routes 2 steps have to be implemented:

a) Add data of the roles allowed to access each route, on ui router's $stateProvider service as can be seen below (same can work for ngRoute).

.config(function ($stateProvider, USER_ROLES) {
  $stateProvider.state('dashboard', {
    url: '/dashboard',
    templateUrl: 'dashboard/index.html',
    data: {
      authorizedRoles: [USER_ROLES.admin, USER_ROLES.editor]
    }
  });
})

b) On $rootScope.$on('$stateChangeStart') add the function to prevent state change if the user is not authorized.

$rootScope.$on('$stateChangeStart', function (event, next) {
    var authorizedRoles = next.data.authorizedRoles;
    if (!Auth.isAuthorized(authorizedRoles)) {
      event.preventDefault();
      if (Auth.isAuthenticated()) {
        // user is not allowed
        $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
      } else {
        // user is not logged in
        $rootScope.$broadcast(AUTH_EVENTS.notAuthenticated);
      }
    }
});

(6) Auth interceptor: This is implemented, but can't be checked on the scope of this code. After each $http request, this interceptor checks the status code, if one of the below is returned, then it broadcasts an event to force the user to log-in again.

angular.module('loginApp')
.factory('AuthInterceptor', [ '$rootScope', '$q', 'Session', 'AUTH_EVENTS',
function($rootScope, $q, Session, AUTH_EVENTS) {
    return {
        responseError : function(response) {
            $rootScope.$broadcast({
                401 : AUTH_EVENTS.notAuthenticated,
                403 : AUTH_EVENTS.notAuthorized,
                419 : AUTH_EVENTS.sessionTimeout,
                440 : AUTH_EVENTS.sessionTimeout
            }[response.status], response);
            return $q.reject(response);
        }
    };
} ]);

P.S. A bug with the form data autofill as stated on the 1st article can be easily avoided by adding the directive that is included in directives.js.

P.S.2 This code can be easily tweaked by the user, to allow different routes to be seen, or display content that was not meant to be displayed. The logic MUST be implemented server-side, this is just a way to show things properly on your ng-app.

Get parent of current directory from Python script

'..' returns parent of current directory.

import os
os.chdir('..')

Now your current directory will be /home/kristina/desire-directory.

Force browser to clear cache

Updating the URL to the following works for me:

/custom.js?id=1

By adding a unique number after ?id= and incrementing it for new changes, users do not have to press CTRL + F5 to refresh the cache. Alternatively, you can append hash or string version of the current time or Epoch after ?id=

Something like ?id=1520606295

"Eliminate render-blocking CSS in above-the-fold content"

I too have struggled with this new pagespeed metric.

Although I have found no practical way to get my score back up to %100 there are a few things I have found helpful.

Combining all css into one file helped a lot. All my sites are back up to %95 - %98.

The only other thing I could think of was to inline all the necessary css (which appears to be most of it - at least for my pages) on the first page to get the sweet high score. Although it may help your speed score this will probably make your page load slower though.

getting JRE system library unbound error in build path

oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

Outside of the direct answers here, one should note the other key difference between python 2 and 3. The official python wiki goes into almost all of the major differences and focuses on when you should use either of the versions. This blog post also does a fine job of explaining the current python universe and the somehow unsolved puzzle of moving to python 3.

As far as I can tell, you are beginning to learn the python language. You should consider the aforementioned articles before you continue down the python 3 route. Not only will you have to change some of your syntax, you will also need to think about which packages will be available to you (an advantage of python 2) and potential optimizations that could be made in your code (an advantage of python 3).

How to create war files

You can use Ant to set up, compile, WAR, and deploy your solution.

<target name="default" depends="setup,compile,buildwar,deploy"></target>

You can then execute one click in Eclipse to run that Ant target. Here are examples of each of the steps:

Preconditions

We'll assume that you have your code organized like:

  • ${basedir}/src: Java files, properties, XML config files
  • ${basedir}/web: Your JSP files
  • ${basedir}/web/lib: Any JARs required at runtime
  • ${basedir}/web/META-INF: Your manifest
  • ${basedir}/web/WEB-INF: Your web.xml files

Set up

Define a setup task that creates the distribution directory and copies any artifacts that need to be WARred directly:

<target name="setup">
    <mkdir dir="dist" />
    <echo>Copying web into dist</echo>
    <copydir dest="dist/web" src="web" />
    <copydir dest="dist/web/WEB-INF/lib" src="${basedir}/../web/WEB-INF/lib" />
</target>

Compile

Build your Java files into classes and copy over any non-Java artifacts that reside under src but need to be available at runtime (e.g. properties, XML files, etc.):

<target name="compile">
    <delete dir="${dist.dir}/web/WEB-INF/classes" />
    <mkdir dir="${dist.dir}/web/WEB-INF/classes" />
    <javac destdir="${dist.dir}/web/WEB-INF/classes" srcdir="src">
        <classpath>
            <fileset dir="${basedir}/../web/WEB-INF/lib">
                  <include name="*" />
            </fileset>
        </classpath>
    </javac>
    <copy todir="${dist.dir}/web/WEB-INF/classes">
        <fileset dir="src">
            <include name="**/*.properties" />
            <include name="**/*.xml" />
        </fileset>
    </copy>
</target>

Build WAR

Create the WAR itself:

<target name="buildwar">
    <war basedir="${basedir}/dist/web" destfile="My.war"
     webxml="${basedir}/dist/web/WEB-INF/web.xml">
        <exclude name="WEB-INF/**" />
        <webinf dir="${basedir}/dist/web/WEB-INF/">
            <include name="**/*.jar" />
        </webinf>
    </war>
</target>

Deploy

Finally, you can set up a task to deploy the WAR directly into your Tomcat deploy location:

<target name="deploy">
    <copy file="My.war" todir="${tomcat.deploydir}" />
</target>

Click and go!

Once all this is set up, simply launching the default target from Eclipse will compile, WAR, and deploy your solution.

The advantage of this approach is that it will work outside Eclipse as well as within Eclipse and can be used to easily share your deployment strategy (e.g. via source control) with other developers who are also working on your project.

Getting query parameters from react-router hash fragment

You may get the following error while creating an optimized production build when using query-string module.

Failed to minify the code from this file: ./node_modules/query-string/index.js:8

To overcome this, kindly use the alternative module called stringquery which does the same process well without any issues while running the build.

import querySearch from "stringquery";

var query = querySearch(this.props.location.search);

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

Method to Add new or update existing item in Dictionary

The only problem could be if one day

map[key] = value

will transform to -

map[key]++;

and that will cause a KeyNotFoundException.

C# Sort and OrderBy comparison

Why not measure it:

class Program
{
    class NameComparer : IComparer<string>
    {
        public int Compare(string x, string y)
        {
            return string.Compare(x, y, true);
        }
    }

    class Person
    {
        public Person(string id, string name)
        {
            Id = id;
            Name = name;
        }
        public string Id { get; set; }
        public string Name { get; set; }
    }

    static void Main()
    {
        List<Person> persons = new List<Person>();
        persons.Add(new Person("P005", "Janson"));
        persons.Add(new Person("P002", "Aravind"));
        persons.Add(new Person("P007", "Kazhal"));

        Sort(persons);
        OrderBy(persons);

        const int COUNT = 1000000;
        Stopwatch watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            Sort(persons);
        }
        watch.Stop();
        Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

        watch = Stopwatch.StartNew();
        for (int i = 0; i < COUNT; i++)
        {
            OrderBy(persons);
        }
        watch.Stop();
        Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);
    }

    static void Sort(List<Person> list)
    {
        list.Sort((p1, p2) => string.Compare(p1.Name, p2.Name, true));
    }

    static void OrderBy(List<Person> list)
    {
        var result = list.OrderBy(n => n.Name, new NameComparer()).ToArray();
    }
}

On my computer when compiled in Release mode this program prints:

Sort: 1162ms
OrderBy: 1269ms

UPDATE:

As suggested by @Stefan here are the results of sorting a big list fewer times:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), "Janson" + i.ToString()));
}

Sort(persons);
OrderBy(persons);

const int COUNT = 30;
Stopwatch watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    Sort(persons);
}
watch.Stop();
Console.WriteLine("Sort: {0}ms", watch.ElapsedMilliseconds);

watch = Stopwatch.StartNew();
for (int i = 0; i < COUNT; i++)
{
    OrderBy(persons);
}
watch.Stop();
Console.WriteLine("OrderBy: {0}ms", watch.ElapsedMilliseconds);

Prints:

Sort: 8965ms
OrderBy: 8460ms

In this scenario it looks like OrderBy performs better.


UPDATE2:

And using random names:

List<Person> persons = new List<Person>();
for (int i = 0; i < 100000; i++)
{
    persons.Add(new Person("P" + i.ToString(), RandomString(5, true)));
}

Where:

private static Random randomSeed = new Random();
public static string RandomString(int size, bool lowerCase)
{
    var sb = new StringBuilder(size);
    int start = (lowerCase) ? 97 : 65;
    for (int i = 0; i < size; i++)
    {
        sb.Append((char)(26 * randomSeed.NextDouble() + start));
    }
    return sb.ToString();
}

Yields:

Sort: 8968ms
OrderBy: 8728ms

Still OrderBy is faster

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

The best practice is selecting the most appropriate one.

.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.

The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.

Reference : Here

For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.

Reference : Here

Check the source code (Reference Source .NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}

Examples

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false

Odd behavior when Java converts int to byte?

132 is outside the range of a byte which is -128 to 127 (Byte.MIN_VALUE to Byte.MAX_VALUE) Instead the top bit of the 8-bit value is treated as the signed which indicates it is negative in this case. So the number is 132 - 256 = -124.

HTML - Arabic Support

This is the answer that was required but everybody answered only part one of many.

  • Step 1 - You cannot have the multilingual characters in unicode document.. convert the document to UTF-8 document

advanced editors don't make it simple for you... go low level...
use notepad to save the document as meName.html & change the encoding
type to UTF-8

  • Step 2 - Mention in your html page that you are going to use such characters by

    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
    
  • Step 3 - When you put in some characters make sure your container tags have the following 2 properties set

    dir='rtl'
    lang='ar'
    
  • Step 4 - Get the characters from some specific tool\editor or online editor like i did with Arabic-Keyboard.org

example

<p dir="rtl" lang="ar" style="color:#e0e0e0;font-size:20px;">????? ??????? ??????</p>

NOTE: font type, font family, font face setting will have no effect on special characters

Qt Creator color scheme

Linux, Qt Creator >= 3.4:

You could edit theese themes:

/usr/share/qtcreator/themes/default.creatortheme
/usr/share/qtcreator/themes/dark.creatortheme

Convert JSON to Map

If you're using org.json, JSONObject has a method toMap(). You can easily do:

Map<String, Object> myMap = myJsonObject.toMap();

Increase max_execution_time in PHP?

Theres a setting max_input_time (on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.

So your problem is not necessarily solvable with php only but you will need to change the server settings too.

Exporting the values in List to excel

Using ClosedXML library( there is no need to install MS Excel

I just write a simple example to show you how you can name the file, the worksheet and select cells:

    var workbook = new XLWorkbook();
    workbook.AddWorksheet("sheetName");
    var ws = workbook.Worksheet("sheetName");

    int row = 1;
    foreach (object item in itemList)
    {
        ws.Cell("A" + row.ToString()).Value = item.ToString();
        row++;
    }

    workbook.SaveAs("yourExcel.xlsx");

If you prefer you can create a System.Data.DataSet or a System.Data.DataTable with all data and then just add it as a workseet with workbook.AddWorksheet(yourDataset) or workbook.AddWorksheet(yourDataTable);

Difference between "char" and "String" in Java

char is a primitive type, and it can hold a single character. String is instead a reference type, thus a full-blown object.

How to Access Hive via Python?

I have solved the same problem with you,here is my operation environment( System:linux Versions:python 3.6 Package:Pyhive) please refer to my answer as follows:

from pyhive import hive
conn = hive.Connection(host='149.129.***.**', port=10000, username='*', database='*',password="*",auth='LDAP')

The key point is to add the reference password & auth and meanwhile set the auth equal to 'LDAP' . Then it works well, any questions please let me know

How do I apply a diff patch on Windows?

I made pure Python tool just for that. It has predictable cross-platform behavior. Although it doesn't create new files (at the time of writing this) and lacks a GUI, it can be used as a library to create graphic tool.

UPDATE: It should be more convenient to use it if you have Python installed.

pip install patch
python -m patch

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I have finally figured out why this is happening !

In visual studio 2015, stdin, stderr, stdout are defined as follow :

#define stdin  (__acrt_iob_func(0))
#define stdout (__acrt_iob_func(1))
#define stderr (__acrt_iob_func(2))

But previously, they were defined as:

#define stdin  (&__iob_func()[0])
#define stdout (&__iob_func()[1])
#define stderr (&__iob_func()[2])

So now __iob_func is not defined anymore which leads to a link error when using a .lib file compiled with previous versions of visual studio.

To solve the issue, you can try defining __iob_func() yourself which should return an array containing {*stdin,*stdout,*stderr}.

Regarding the other link errors about stdio functions (in my case it was sprintf()), you can add legacy_stdio_definitions.lib to your linker options.

Resolving instances with ASP.NET Core DI from within ConfigureServices

You can inject dependencies in attributes like AuthorizeAttribute in this way

var someservice = (ISomeService)context.HttpContext.RequestServices.GetService(typeof(ISomeService));

HTML to PDF with Node.js

In my view, the best way to do this is via an API so that you do not add a large and complex dependency into your app that runs unmanaged code, that needs to be frequently updated.

Here is a simple way to do this, which is free for 800 requests/month:

var CloudmersiveConvertApiClient = require('cloudmersive-convert-api-client');
var defaultClient = CloudmersiveConvertApiClient.ApiClient.instance;

// Configure API key authorization: Apikey
var Apikey = defaultClient.authentications['Apikey'];
Apikey.apiKey = 'YOUR API KEY';



var apiInstance = new CloudmersiveConvertApiClient.ConvertWebApi();

var input = new CloudmersiveConvertApiClient.HtmlToPdfRequest(); // HtmlToPdfRequest | HTML to PDF request parameters
input.Html = "<b>Hello, world!</b>";


var callback = function(error, data, response) {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
};
apiInstance.convertWebHtmlToPdf(input, callback);

With the above approach you can also install the API on-premises or on your own infrastructure if you prefer.

Activity transition in Android

An even easy way to do it is:

  1. Create an animation style into your styles.xml file
<style name="WindowAnimationTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
  1. Add this style to your app theme
<style name="AppBaseTheme" parent="Theme.Material.Light.DarkActionBar">
      <item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
</style>

That's it :)

How can I filter a date of a DateTimeField in Django?

Hm.. My solution is working:

Mymodel.objects.filter(date_time_field__startswith=datetime.datetime(1986, 7, 28))

Why is NULL undeclared?

NULL isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef> or #include <stddef.h> should be sufficient.

The definition of NULL is guaranteed to be available if you include cstddef or stddef.h. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.

How do I check what version of Python is running my script?

import sys
sys.version.split(' ')[0]

sys.version gives you what you want, just pick the first number :)

SMTP connect() failed PHPmailer - PHP

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

When to use references vs. pointers

Like others already answered: Always use references, unless the variable being NULL/nullptr is really a valid state.

John Carmack's viewpoint on the subject is similar:

NULL pointers are the biggest problem in C/C++, at least in our code. The dual use of a single value as both a flag and an address causes an incredible number of fatal issues. C++ references should be favored over pointers whenever possible; while a reference is “really” just a pointer, it has the implicit contract of being not-NULL. Perform NULL checks when pointers are turned into references, then you can ignore the issue thereafter.

http://www.altdevblogaday.com/2011/12/24/static-code-analysis/

Edit 2012-03-13

User Bret Kuhns rightly remarks:

The C++11 standard has been finalized. I think it's time in this thread to mention that most code should do perfectly fine with a combination of references, shared_ptr, and unique_ptr.

True enough, but the question still remains, even when replacing raw pointers with smart pointers.

For example, both std::unique_ptr and std::shared_ptr can be constructed as "empty" pointers through their default constructor:

... meaning that using them without verifying they are not empty risks a crash, which is exactly what J. Carmack's discussion is all about.

And then, we have the amusing problem of "how do we pass a smart pointer as a function parameter?"

Jon's answer for the question C++ - passing references to boost::shared_ptr, and the following comments show that even then, passing a smart pointer by copy or by reference is not as clear cut as one would like (I favor myself the "by-reference" by default, but I could be wrong).

How to use System.Net.HttpClient to post a complex type?

After investigating lots of alternatives, I have come across another approach, suitable for the API 2.0 version.

(VB.NET is my favorite, sooo...)

Public Async Function APIPut_Response(ID as Integer, MyWidget as Widget) as Task(Of HttpResponseMessage)
    Dim DesiredContent as HttpContent = New StringContent(JsonConvert.SerializeObject(MyWidget))
    Return Await APIClient.PutAsync(String.Format("api/widget/{0}", ID), DesiredContent)
End Function

Good luck! For me this worked out (in the end!).

Regards, Peter

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

As mentioned above the following would solve the problem: mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);

However in my case the provider did this [0..1] or [0..*] serialization rather as a bug and I could not enforce fixing. On the other hand it did not want to impact my strict mapper for all other cases which needs to be validated strictly.

So I did a Jackson NASTY HACK (which should not be copied in general ;-) ), especially because my SingleOrListElement had only few properties to patch:

@JsonProperty(value = "SingleOrListElement", access = JsonProperty.Access.WRITE_ONLY)
private Object singleOrListElement; 

public List<SingleOrListElement> patch(Object singleOrListElement) {
  if (singleOrListElement instanceof List) {
    return (ArrayList<SingleOrListElement>) singleOrListElement;
  } else {
    LinkedHashMap map = (LinkedHashMap) singleOrListElement;
    return Collections.singletonList(SingletonList.builder()
                            .property1((String) map.get("p1"))
                            .property2((Integer) map.get("p2"))
                            .build());
  }

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

My issue was resolved by replacing the'SID' in URL with 'service name' and correct host.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

What's new in .NET Framework 4 Client Profile RTM explains many of the differences:

When to use NET4 Client Profile and when to use NET4 Full Framework?
NET4 Client Profile:
Always target NET4 Client Profile for all your client desktop applications (including Windows Forms and WPF apps).

NET4 Full framework:
Target NET4 Full only if the features or assemblies that your app need are not included in the Client Profile. This includes:

  • If you are building Server apps. Such as:
    o ASP.Net apps
    o Server-side ASMX based web services
  • If you use legacy client scenarios. Such as:
    o Use System.Data.OracleClient.dll which is deprecated in NET4 and not included in the Client Profile.
    o Use legacy Windows Workflow Foundation 3.0 or 3.5 (WF3.0 , WF3.5)
  • If you targeting developer scenarios and need tool such as MSBuild or need access to design assemblies such as System.Design.dll

However, as stated on MSDN, this is not relevant for >=4.5:

Starting with the .NET Framework 4.5, the Client Profile has been discontinued and only the full redistributable package is available. Optimizations provided by the .NET Framework 4.5, such as smaller download size and faster deployment, have eliminated the need for a separate deployment package. The single redistributable streamlines the installation process and simplifies your app's deployment options.

Cannot uninstall angular-cli

I have also faced the same issue in recent past for me I have do the following commands one by one in terminal.

sudo npm uninstall -g angular-cli
sudo npm cache clean

After this run

ng -v

If still get angular-cli version 1.0.0-beta.2x.x then run the following command

which ng

It will show the ng path. Go to the path and if it is linked with any file remove the same the link and actual ng file. In my case the link is in /usr/bin/ng and actual path of ng file is /lib/node_modules/@angular/cli/bin/ng.

sudo rm -rf /lib/node_modules/@angular/cli/bin/ng
sudo rm -rf /usr/bin/ng

Next you need to install @angular/cli using

sudo npm install -g @angular/cli

Close all the terminal and run ng -v and you are on. May be it will help someone. Thanks :)

How to extract IP Address in Spring MVC Controller get call?

Put this method in your BaseController:

@SuppressWarnings("ConstantConditions")
protected String fetchClientIpAddr() {
    HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest();
    String ip = Optional.ofNullable(request.getHeader("X-FORWARDED-FOR")).orElse(request.getRemoteAddr());
    if (ip.equals("0:0:0:0:0:0:0:1")) ip = "127.0.0.1";
    Assert.isTrue(ip.chars().filter($ -> $ == '.').count() == 3, "Illegal IP: " + ip);
    return ip;
}

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

"unable to locate adb" using Android Studio

I use android studio in Windows 7 and i have AVG for antivirus. The first time you launch adb, AVG prompts you to add avg.exe in antivirus vault. If you accept, then you android studio dont have access to run adb.exe. So open avg >> options >> Virus Vault >> Restore (select the adb file)

Simple way to compare 2 ArrayLists

If your requirement is to maintain the insertion order plus check the contents of the two arraylist then you should do following:

List<String> listOne = new ArrayList<String>();
List<String> listTwo = new ArrayList<String>();

listOne.add("stack");
listOne.add("overflow");

listTwo.add("stack");
listTwo.add("overflow");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

This will return true.

However, if you change the ordering for example:

listOne.add("stack");
listOne.add("overflow");

listTwo.add("overflow");
listTwo.add("stack");

boolean result = Arrays.equals(listOne.toArray(),listTwo.toArray());

will return false as ordering is different.

Adding one day to a date

<?php
$stop_date = '2009-09-30 20:24:00';
echo 'date before day adding: ' . $stop_date; 
$stop_date = date('Y-m-d H:i:s', strtotime($stop_date . ' +1 day'));
echo 'date after adding 1 day: ' . $stop_date;
?>

For PHP 5.2.0+, you may also do as follows:

$stop_date = new DateTime('2009-09-30 20:24:00');
echo 'date before day adding: ' . $stop_date->format('Y-m-d H:i:s'); 
$stop_date->modify('+1 day');
echo 'date after adding 1 day: ' . $stop_date->format('Y-m-d H:i:s');

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Creating a new empty branch for a new project

The best solution is to create a new branch with --orphan option as shown below

git checkout --orphan <branch name>

By this you will be able to create a new branch and directly checkout to the new branch. It will be a parentless branch.

By default the --orphan option doesn't remove the files in the working directory, so you can delete the working directory files by this:

git rm --cached -r

In details what the --orphan does:

--orphan <new_branch>
Create a new orphan branch, named <new_branch>, started from <start_point> and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.

The index and the working tree are adjusted as if you had previously run git checkout <start_point>. This allows you to start a new history that records a set of paths similar to <start_point> by easily running git commit -a to make the root commit.

This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is "clean", but whose full history contains proprietary or otherwise encumbered bits of code.

If you want to start a disconnected history that records a set of paths that is totally different from the one of <start_point>, then you should clear the index and the working tree right after creating the orphan branch by running git rm -rf . from the top level of the working tree. Afterwards you will be ready to prepare your new files, repopulating the working tree, by copying them from elsewhere, extracting a tarball, etc.

Python: how to capture image from webcam on click using OpenCV

Breaking down your code example (Explanations are under the line of code.)

import cv2

imports openCV for usage

camera = cv2.VideoCapture(0)

creates an object called camera, of type openCV video capture, using the first camera in the list of cameras connected to the computer.

for i in range(10):

tells the program to loop the following indented code 10 times

    return_value, image = camera.read()

read values from the camera object, using it's read method. it resonds with 2 values save the 2 data values into two temporary variables called "return_value" and "image"

    cv2.imwrite('opencv'+str(i)+'.png', image)

use the openCV method imwrite (that writes an image to a disk) and write an image using the data in the temporary data variable

fewer indents means that the loop has now ended...

del(camera)

deletes the camrea object, we no longer needs it.

you can what you request in many ways, one could be to replace the for loop with a while loop, (running forever, instead of 10 times), and then wait for a keypress (like answered by danidee while I was typing)

or create a much more evil service that hides in the background and captures an image everytime someone presses the keyboard...

Regular expression for floating point numbers

In C++ using the regex library

The answer would go about like this:

[0-9]?([0-9]*[.])?[0-9]+

Notice that I don't take the sign symbol, if you wanted it with the sign symbol it would go about this:

[+-]?([0-9]*[.])?[0-9]+

This also separates a regular number or a decimal number.

What does character set and collation mean exactly?

A character encoding is a way to encode characters so that they fit in memory. That is, if the charset is ISO-8859-15, the euro symbol, €, will be encoded as 0xa4, and in UTF-8, it will be 0xe282ac.

The collation is how to compare characters, in latin9, there are letters as e é è ê f, if sorted by their binary representation, it will go e f é ê è but if the collation is set to, for example, French, you'll have them in the order you thought they would be, which is all of e é è ê are equal, and then f.

Setting focus to a textbox control

I think what you're looking for is:

textBox1.Select();

in the constructor. (This is in C#. Maybe in VB that would be the same but without the semicolon.)

From http://msdn.microsoft.com/en-us/library/system.windows.forms.control.focus.aspx :

Focus is a low-level method intended primarily for custom control authors. Instead, application programmers should use the Select method or the ActiveControl property for child controls, or the Activate method for forms.

How to trigger an event after using event.preventDefault()

It is possible to use currentTarget of the event. Example shows how to proceed with form submit. Likewise you could get function from onclick attribute etc.

$('form').on('submit', function(event) {
  event.preventDefault();

  // code

  event.currentTarget.submit();
});

When use getOne and findOne methods Spring Data JPA

I really find very difficult from the above answers. From debugging perspective i almost spent 8 hours to know the silly mistake.

I have testing spring+hibernate+dozer+Mysql project. To be clear.

I have User entity, Book Entity. You do the calculations of mapping.

Were the Multiple books tied to One user. But in UserServiceImpl i was trying to find it by getOne(userId);

public UserDTO getById(int userId) throws Exception {

    final User user = userDao.getOne(userId);

    if (user == null) {
        throw new ServiceException("User not found", HttpStatus.NOT_FOUND);
    }
    userDto = mapEntityToDto.transformBO(user, UserDTO.class);

    return userDto;
}

The Rest result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 1,
        "name": "TEST_ME",
        "bookList": null
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

The above code did not fetch the books which is read by the user let say.

The bookList was always null because of getOne(ID). After changing to findOne(ID). The result is

{
"collection": {
    "version": "1.0",
    "data": {
        "id": 0,
        "name": "Annama",
        "bookList": [
            {
                "id": 2,
                "book_no": "The karma of searching",
            }
        ]
    },
    "error": null,
    "statusCode": 200
},
"booleanStatus": null

}

Quadratic and cubic regression in Excel

The LINEST function described in a previous answer is the way to go, but an easier way to show the 3 coefficients of the output is to additionally use the INDEX function. In one cell, type: =INDEX(LINEST(B2:B21,A2:A21^{1,2},TRUE,FALSE),1) (by the way, the B2:B21 and A2:A21 I used are just the same values the first poster who answered this used... of course you'd change these ranges appropriately to match your data). This gives the X^2 coefficient. In an adjacent cell, type the same formula again but change the final 1 to a 2... this gives the X^1 coefficient. Lastly, in the next cell over, again type the same formula but change the last number to a 3... this gives the constant. I did notice that the three coefficients are very close but not quite identical to those derived by using the graphical trendline feature under the charts tab. Also, I discovered that LINEST only seems to work if the X and Y data are in columns (not rows), with no empty cells within the range, so be aware of that if you get a #VALUE error.

Fetching distinct values on a column using Spark DataFrame

This solution demonstrates how to transform data with Spark native functions which are better than UDFs. It also demonstrates how dropDuplicates which is more suitable than distinct for certain queries.

Suppose you have this DataFrame:

+-------+-------------+
|country|    continent|
+-------+-------------+
|  china|         asia|
| brazil|south america|
| france|       europe|
|  china|         asia|
+-------+-------------+

Here's how to take all the distinct countries and run a transformation:

df
  .select("country")
  .distinct
  .withColumn("country", concat(col("country"), lit(" is fun!")))
  .show()
+--------------+
|       country|
+--------------+
|brazil is fun!|
|france is fun!|
| china is fun!|
+--------------+

You can use dropDuplicates instead of distinct if you don't want to lose the continent information:

df
  .dropDuplicates("country")
  .withColumn("description", concat(col("country"), lit(" is a country in "), col("continent")))
  .show(false)
+-------+-------------+------------------------------------+
|country|continent    |description                         |
+-------+-------------+------------------------------------+
|brazil |south america|brazil is a country in south america|
|france |europe       |france is a country in europe       |
|china  |asia         |china is a country in asia          |
+-------+-------------+------------------------------------+

See here for more information about filtering DataFrames and here for more information on dropping duplicates.

Ultimately, you'll want to wrap your transformation logic in custom transformations that can be chained with the Dataset#transform method.

Convert JsonNode into POJO

In Jackson 2.4, you can convert as follows:

MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);

where jsonObjectMapper is a Jackson ObjectMapper.


In older versions of Jackson, it would be

MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);

How to add a new line in textarea element?

I think you are confusing the syntax of different languages.

  • &#10; is (the HtmlEncoded value of ASCII 10 or) the linefeed character literal in a HTML string. But the line feed character does NOT render as a line break in HTML (see notes at bottom).

  • \n is the linefeed character literal (ASCII 10) in a Javascript string.

  • <br/> is a line break in HTML. Many other elements, eg <p>, <div>, etc also render line breaks unless overridden with some styles.

Hopefully the following illustration will make it clearer:

_x000D_
_x000D_
T.innerText = "Position of LF: " + t.value.indexOf("\n");_x000D_
_x000D_
p1.innerHTML = t.value;_x000D_
p2.innerHTML = t.value.replace("\n", "<br/>");_x000D_
p3.innerText = t.value.replace("\n", "<br/>");
_x000D_
<textarea id="t">Line 1&#10;Line 2</textarea>_x000D_
_x000D_
<p id='T'></p>_x000D_
<p id='p1'></p>_x000D_
<p id='p2'></p>_x000D_
<p id='p3'></p>
_x000D_
_x000D_
_x000D_

A few points to note about Html:

  • The innerHTML value of the TEXTAREA element does not render Html. Try the following: <textarea>A <a href='x'>link</a>.</textarea> to see.
  • The P element renders all contiguous white spaces (including new lines) as one space.
  • The LF character does not render to a new line or line break in HTML.
  • The TEXTAREA renders LF as a new line inside the text area box.

How to use jQuery with Angular?

Now it has become very easy, You can do it by simply declaring jQuery variable with any type inside Angular2 controller.

declare var jQuery:any;

Add this just after import statements and before component decorator.

To access any element with id X or Class X you just have to do

jQuery("#X or .X").someFunc();

How do I install Python 3 on an AWS EC2 instance?

On Debian derivatives such as Ubuntu, use apt. Check the apt repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo apt-get install python3

On Red Hat and derivatives, use yum. Check the yum repository for the versions of Python available to you. Then, run a command similar to the following, substituting the correct package name:

sudo yum install python36

On SUSE and derivatives, use zypper. Check the repository for the versions of Python available to you. Then. run a command similar to the following, substituting the correct package name:

sudo zypper install python3

SQL Server - Convert varchar to another collation (code page) to fix character encoding

Character set conversion is done implicitly on the database connection level. You can force automatic conversion off in the ODBC or ADODB connection string with the parameter "Auto Translate=False". This is NOT recommended. See: https://msdn.microsoft.com/en-us/library/ms130822.aspx

There has been a codepage incompatibility in SQL Server 2005 when Database and Client codepage did not match. https://support.microsoft.com/kb/KbView/904803

SQL-Management Console 2008 and upwards is a UNICODE application. All values entered or requested are interpreted as such on the application level. Conversation to and from the column collation is done implicitly. You can verify this with:

SELECT CAST(N'±' as varbinary(10)) AS Result

This will return 0xB100 which is the Unicode character U+00B1 (as entered in the Management Console window). You cannot turn off "Auto Translate" for Management Studio.

If you specify a different collation in the select, you eventually end up in a double conversion (with possible data loss) as long as "Auto Translate" is still active. The original character is first transformed to the new collation during the select, which in turn gets "Auto Translated" to the "proper" application codepage. That's why your various COLLATION tests still show all the same result.

You can verify that specifying the collation DOES have an effect in the select, if you cast the result as VARBINARY instead of VARCHAR so the SQL Server transformation is not invalidated by the client before it is presented:

SELECT cast(columnName COLLATE SQL_Latin1_General_CP850_BIN2 as varbinary(10)) from tableName
SELECT cast(columnName COLLATE SQL_Latin1_General_CP1_CI_AS as varbinary(10)) from tableName

This will get you 0xF1 or 0xB1 respectively if columnName contains just the character '±'

You still might get the correct result and yet a wrong character, if the font you are using does not provide the proper glyph.

Please double check the actual internal representation of your character by casting the query to VARBINARY on a proper sample and verify whether this code indeed corresponds to the defined database collation SQL_Latin1_General_CP850_BIN2

SELECT CAST(columnName as varbinary(10)) from tableName

Differences in application collation and database collation might go unnoticed as long as the conversion is always done the same way in and out. Troubles emerge as soon as you add a client with a different collation. Then you might find that the internal conversion is unable to match the characters correctly.

All that said, you should keep in mind that Management Studio usually is not the final reference when interpreting result sets. Even if it looks gibberish in MS, it still might be the correct output. The question is whether the records show up correctly in your applications.

How to force a script reload and re-execute?

Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.

<script>
    function reload_js(src) {
        $('script[src="' + src + '"]').remove();
        $('<script>').attr('src', src).appendTo('head');
    }
    reload_js('source_file.js');
</script>

Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)

React-Redux: Actions must be plain objects. Use custom middleware for async actions

Make use of Arrow functions it improves the readability of code. No need to return anything in API.fetchComments, Api call is asynchronous when the request is completed then will get the response, there you have to just dispatch type and data.

Below code does the same job by making use of Arrow functions.

export const bindComments = postId => {
  return dispatch => {
    API.fetchComments(postId).then(comments => {
      dispatch({
        type: BIND_COMMENTS,
        comments,
        postId
      });
    });
  };
};

PHP - get base64 img string decode and save as jpg (resulting empty image )

Decode and save image as PNG

header('content-type: image/png');

           ob_start();

        $ret = fopen($fullurl, 'r', true, $context);
        $contents = stream_get_contents($ret);
        $base64 = 'data:image/PNG;base64,' . base64_encode($contents);
        echo "<img src=$base64 />" ;


        ob_end_flush();

How to watch and reload ts-node when TypeScript files change

Add "watch": "nodemon --exec ts-node -- ./src/index.ts" to scripts section of your package.json.

SQL Query for Student mark functionality

I will try to get the answer with one query using CTE and window function rank()

create the tables

create table Students 
(student_id int,
Name varchar(255),
details varchar(255));

create table Subject(
Sub_id int,
name varchar(255));

create table marks
(student_id int,
subject_id int,
mark int);

the answer should be a table with the below fields

student_name | subject_name | mark

plan the execution steps

  1. Create a CTE
  • join the tables;
  • rank the subjects, order them by mark descending
  1. Select the output fields from the CTE
with CTE as (select s.name, sb.name as subject_name, m.mark, rank() over(partition by sb.name order by m.mark desc) as rn 
from Students s
join marks m on s.student_id = m.student_id
join subject sb
on sb.Sub_id = m.subject_id)
select name , subject_name, mark
from CTE
where rn = 1

Use getElementById on HTMLElement instead of HTMLDocument

Thanks to dee for the answer above with the Scrape() subroutine. The code worked perfectly as written, and I was able to then convert the code to work with the specific website I am trying to scrape.

I do not have enough reputation to upvote or to comment, but I do actually have some minor improvements to add to dee's answer:

  1. You will need to add the VBA Reference via "Tools\References" to "Microsoft HTML Object Library in order for the code to compile.

  2. I commented out the Browser.Visible line and added the comment as follows

    'if you need to debug the browser page, uncomment this line:
    'Browser.Visible = True
    
  3. And I added a line to close the browser before Set Browser = Nothing:

    Browser.Quit
    

Thanks again dee!

ETA: this works on machines with IE9, but not machines with IE8. Anyone have a fix?

Found the fix myself, so came back here to post it. The ClassName function is available in IE9. For this to work in IE8, you use querySelectorAll, with a dot preceding the class name of the object you are looking for:

'Set repList = doc.getElementsByClassName("reportList") 'only works in IE9, not in IE8
Set repList = doc.querySelectorAll(".reportList")       'this works in IE8+

How do I format date and time on ssrs report?

If you want date and time separate then use below expressions: Date and Time Expression

Expression1 for current date : =formatdatetime(today) its return date is = 11/15/2016

Expression2 for current time : =CDate(Now).ToString("hh:mm tt") its return time is = 3:44 PM

This report printed on Expression1 at Expression2

Output will be : Output of Both Expression

This report printed on 11/15/2016 at 3:44 PM

iOS 7's blurred overlay effect using CSS?

Here is my take on this with jQuery. Solution isn't universal, meaning one would have to tweak some of the positions and stuff depending on the actual design.

Basically what I did is: on trigger clone/remove the whole background (what should be blurred) to a container with unblurred content (which, optionally, has hidden overflow if it is not full width) and position it correctly. Caveat is that on window resize blurred div will mismatch the original in terms of position, but this could be solved with some on window resize function (honestly I couldn't be bothered with that now).

I would really appreciate your opinion on this solution!

Thanks

Here is the fiddle, not tested in IE.

HTML

<div class="slide-up">
<div class="slide-wrapper">
    <div class="slide-background"></div>
    <div class="blured"></div>
    <div class="slide-content">
         <h2>Pop up title</h2>

        <p>Pretty neat!</p>
    </div>
</div>
</div>
<div class="wrapper">
<div class="content">
     <h1>Some title</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque molestie magna elit, quis pulvinar lectus gravida sit amet. Phasellus lacinia massa et metus blandit fermentum. Cras euismod gravida scelerisque. Fusce molestie ligula diam, non porta ipsum faucibus sed. Nam interdum dui at fringilla laoreet. Donec sit amet est eu eros suscipit commodo eget vitae velit.</p>
</div> <a class="trigger" href="#">trigger slide</a>

</div>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<filter id="blur">
    <feGaussianBlur stdDeviation="3" />
</filter>
</svg>

CSS

body {
margin: 0;
padding: 0;
font-family:'Verdana', sans-serif;
color: #fff;
}
.wrapper {
position: relative;
height: 100%;
overflow: hidden;
z-index: 100;
background: #CD535B;
}
img {
width: 100%;
height: auto;
}
.blured {
top: 0;
height: 0;
-webkit-filter: blur(3px);
-moz-filter: blur(3px);
-ms-filter: blur(3px);
filter: blur(3px);
filter: url(#blur);
filter:progid:DXImageTransform.Microsoft.Blur(PixelRadius='3');
position: absolute;
z-index: 1000;
}
.blured .wrapper {
position: absolute;
width: inherit;
}
.content {
width: 300px;
margin: 0 auto;
}
.slide-up {
top:10px;
position: absolute;
width: 100%;
z-index: 2000;
display: none;
height: auto;
overflow: hidden;
}
.slide-wrapper {
width: 200px;
margin: 0 auto;
position: relative;
border: 1px solid #fff;
overflow: hidden;
}
.slide-content {
z-index: 2222;
position: relative;
text-align: center;
color: #333333;
}
.slide-background {
position: absolute;
top: 0;
width: 100%;
height: 100%;
background-color: #fff;
z-index: 1500;
opacity: 0.5;
}

jQuery

// first just grab some pixels we will use to correctly position the blured element
var height = $('.slide-up').outerHeight();
var slide_top = parseInt($('.slide-up').css('top'), 10);
$wrapper_width = $('body > .wrapper').css("width");
$('.blured').css("width", $wrapper_width);

$('.trigger').click(function () {
    if ($(this).hasClass('triggered')) { // sliding up
        $('.blured').animate({
            height: '0px',
            background: background
        }, 1000, function () {
            $('.blured .wrapper').remove();
        });
        $('.slide-up').slideUp(700);
        $(this).removeClass('triggered');
    } else { // sliding down
        $('.wrapper').clone().appendTo('.blured');
        $('.slide-up').slideDown(1000);
        $offset = $('.slide-wrapper').offset();
        $('.blured').animate({
            height: $offset.top + height + slide_top + 'px'
        }, 700);
        $('.blured .wrapper').animate({
            left: -$offset.left,
            top: -$offset.top
        }, 100);
        $(this).addClass('triggered');
    }
});

sprintf like functionality in Python

This is probably the closest translation from your C code to Python code.

A = 1
B = "hello"
buf = "A = %d\n , B= %s\n" % (A, B)

c = 2
buf += "C=%d\n" % c

f = open('output.txt', 'w')
print >> f, c
f.close()

The % operator in Python does almost exactly the same thing as C's sprintf. You can also print the string to a file directly. If there are lots of these string formatted stringlets involved, it might be wise to use a StringIO object to speed up processing time.

So instead of doing +=, do this:

import cStringIO
buf = cStringIO.StringIO()

...

print >> buf, "A = %d\n , B= %s\n" % (A, B)

...

print >> buf, "C=%d\n" % c

...

print >> f, buf.getvalue()

How to know which is running in Jupyter notebook?

Assuming you have the wrong backend system you can change the backend kernel by creating a new or editing the existing kernel.json in the kernels folder of your jupyter data path jupyter --paths. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda specific kernel:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

Should create a new kernel:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

You need to ensure ipykernel package is installed in the anaconda distribution.

This way you can just switch between kernels and have different notebooks using different kernels.

Where can I download IntelliJ IDEA Color Schemes?

The Solarized color theme (both light and dark versions) for IntelliJ IDEA is available here.

Solarized color theme for IntelliJ IDEA

How to install XNA game studio on Visual Studio 2012?

Yes, it's possible with a bit of tweak. Unfortunately, you still have to have VS 2010 installed.

  1. First, install XNA Game Studio 4.0. The easiest way is to install the Windows Phone SDK 7.1 which contains everything required.

  2. Copy the XNA Game Extension from VS 10 to VS 11 by opening a command prompt 'as administrator' and executing the following (may vary if not x64 computer with defaults paths) :

    xcopy /e "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0" "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"

  3. Run notepad as administrator then open extension.vsixmanifest in the destination directory just created.

  4. Upgrade the Supported product version to match the new version (or duplicate the whole VisualStudio element and change the Version attribute, as @brainslugs83 said in comments):

    <SupportedProducts>
      <VisualStudio Version="11.0">
        <Edition>VSTS</Edition>
        <Edition>VSTD</Edition>
        <Edition>Pro</Edition>
        <Edition>VCSExpress</Edition>
        <Edition>VPDExpress</Edition>
      </VisualStudio>
    </SupportedProducts>
    
  5. Don't forget to clear/delete your cache in %localappdata%\Microsoft\VisualStudio\12.0\Extensions.

  6. You may have to run the command to tells Visual Studio that new extensions are available. If you see an 'access denied' message, try launching the console as an administrator.

    "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\devenv.exe" /setup
    

This has been tested for Windows Games, but not WP7 or Xbox games.

[Edit] According Jowsty, this works also for XBox 360 Games.

[Edit for Visual Studio 2013 & Windows 8.1] See here for documentation on installing Windows Phone SDK 7.1 on Windows 8.1. Use VS version number 12.0 in place of 11.0 for all of these steps, and they will still work correctly.

WebService Client Generation Error with JDK8

I used it with a regular maven project, and got it solved with this plugin dependency configuration for running the xjc plugin:

     <plugin>
        <!-- Needed to run the plugin xjc en Java 8 or superior -->
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-2</version>
        <executions>
            <execution>
                <id>set-additional-system-properties</id>
                <goals>
                    <goal>set-system-properties</goal>
                </goals>
            </execution>
        </executions>
        <configuration>
            <properties>
                <property>
                    <name>javax.xml.accessExternalSchema</name>
                    <value>all</value>
                </property>
                <property>
                    <name>javax.xml.accessExternalDTD</name>
                    <value>all</value>
                </property>
            </properties>
        </configuration>
    </plugin>

Highlight label if checkbox is checked

You can't do this with CSS alone. Using jQuery you can do

HTML

<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />

CSS

.highlight{
    background:yellow;
}

jQuery

$('#check').click(function(){
    $('#lab').toggleClass('highlight')
})

This will work in all browsers

Check working example at http://jsfiddle.net/LgADZ/

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

ping response "Request timed out." vs "Destination Host unreachable"

As I understand it, "request timeout" means the ICMP packet reached from one host to the other host but the reply could not reach the requesting host. There may be more packet loss or some physical issue. "destination host unreachable" means there is no proper route defined between two hosts.

Connect over ssh using a .pem file

You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip

What determines the monitor my app runs on?

Get UltraMon. Quickly.

http://realtimesoft.com/ultramon/

It doesn't let you specify what monitor an app starts on, but it lets you move an app to the another monitor, and keep its aspect ratio intact, with one mouse click. It is a very handy utility.

Most programs will start where you last left them. So if you have two monitors at work, but only one at home, it's possible to start you laptop at home and not see the apps running on the other monitor (which now isn't there). UltrMon also lets you move those orphan apps back to the main screen quickly and easily.

How can I conditionally import an ES6 module?

obscuring it in an eval worked for me, hiding it from the static analyzer ...

if (typeof __CLI__ !== 'undefined') {
  eval("require('fs');")
}

AppSettings get value from .config file

You can simply type:

string filePath = Sysem.Configuration.ConfigurationManager.AppSettings[key.ToString()];

because key is an object and AppSettings takes a string

`ui-router` $stateParams vs. $state.params

The documentation reiterates your findings here: https://github.com/angular-ui/ui-router/wiki/URL-Routing#stateparams-service

If my memory serves, $stateParams was introduced later than the original $state.params, and seems to be a simple helper injector to avoid continuously writing $state.params.

I doubt there are any best practice guidelines, but context wins out for me. If you simply want access to the params received into the url, then use $stateParams. If you want to know something more complex about the state itself, use $state.

How to trigger a build only if changes happen on particular set of files

If you are using a declarative syntax of Jenkinsfile to describe your building pipeline, you can use changeset condition to limit stage execution only to the case when specific files are changed. This is now a standard feature of Jenkins and does not require any additional configruation/software.

stages {
    stage('Nginx') {
        when { changeset "nginx/*"}
        steps {
            sh "make build-nginx"
            sh "make start-nginx"
        }
    }
}

You can combine multiple conditions using anyOf or allOf keywords for OR or AND behaviour accordingly:

when {
    anyOf {
        changeset "nginx/**"
        changeset "fluent-bit/**"
    }
}
steps {
    sh "make build-nginx"
    sh "make start-nginx"
}

Sublime Text 2 multiple line edit

Worked for me on OS X + Sublime build 3083:

OPTION (ALT) + select lines

How to count the number of letters in a string without the spaces?

Try using...

resp = input("Hello, I am stuck in doors! What is the weather outside?")
print("You answered in", resp.ascii_letters, "letters!")

Didn't work for me but should work for some random guys.

pandas get column average/mean

Mean for each column in df :

    A   B   C
0   5   3   8
1   5   3   9
2   8   4   9

df.mean()

A    6.000000
B    3.333333
C    8.666667
dtype: float64

and if you want average of all columns:

df.stack().mean()
6.0

Change application's starting activity

If you are using Android Studio and you might have previously selected another Activity to launch.

Click on Run > Edit configuration and then make sure that Launch default Activity is selected.

Launch default Activity

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Some of the data processing requirements doesn't need sort at all. Syncsort had made the sorting in Hadoop pluggable. Here is a nice blog from them on sorting. The process of moving the data from the mappers to the reducers is called shuffling, check this article for more information on the same.

C++, copy set to vector

Just use the constructor for the vector that takes iterators:

std::set<T> s;

//...

std::vector v( s.begin(), s.end() );

Assumes you just want the content of s in v, and there's nothing in v prior to copying the data to it.

Convert a list to a data frame

More answers, along with timings in the answer to this question: What is the most efficient way to cast a list as a data frame?

The quickest way, that doesn't produce a dataframe with lists rather than vectors for columns appears to be (from Martin Morgan's answer):

l <- list(list(col1="a",col2=1),list(col1="b",col2=2))
f = function(x) function(i) unlist(lapply(x, `[[`, i), use.names=FALSE)
as.data.frame(Map(f(l), names(l[[1]])))

JSON.stringify output to div in pretty print way

If your <pre> tag is showing a single-line of JSON because that's how the string is provided already (via an api or some function/page out of your control), you can reformat it like this:

HTML:

<pre id="json">{"some":"JSON string"}</pre>

JavaScript:

    (function() {
        var element = document.getElementById("json");
        var obj = JSON.parse(element.innerText);
        element.innerHTML = JSON.stringify(obj, undefined, 2);
    })();

or jQuery:

    $(formatJson);

    function formatJson() {
        var element = $("#json");
        var obj = JSON.parse(element.text());
        element.html(JSON.stringify(obj, undefined, 2));
    }

How should I remove all the leading spaces from a string? - swift

To remove leading and trailing whitespaces:

let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Swift 3 / Swift 4:

let trimmedString = string.trimmingCharacters(in: .whitespaces)

What is a "callable"?

A Callable is an object that has the __call__ method. This means you can fake callable functions or do neat things like Partial Function Application where you take a function and add something that enhances it or fills in some of the parameters, returning something that can be called in turn (known as Currying in functional programming circles).

Certain typographic errors will have the interpreter attempting to call something you did not intend, such as (for example) a string. This can produce errors where the interpreter attempts to execute a non-callable application. You can see this happening in a python interpreter by doing something like the transcript below.

[nigel@k9 ~]$ python
Python 2.5 (r25:51908, Nov  6 2007, 15:55:44) 
[GCC 4.1.2 20070925 (Red Hat 4.1.2-27)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'aaa'()    # <== Here we attempt to call a string.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
>>> 

How to get the number of characters in a std::string?

In C++ std::string the length() and size() method gives you the number of bytes, and not necessarily the number of characters !. Same with the c-Style sizeof() function!

For most of the printable 7bit-ASCII Characters this is the same value, but for characters that are not 7bit-ASCII it's definitely not. See the following example to give you real results (64bit linux).

There is no simple c/c++ function that can really count the number of characters. By the way, all of this stuff is implementation dependent and may be different on other environments (compiler, win 16/32, linux, embedded, ...)

See following example:

#include <string>
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
/* c-Style char Array */
const char * Test1 = "1234";
const char * Test2 = "ÄÖÜ€";
const char * Test3 = "aß?";

/* c++ string object */
string sTest1 = "1234";
string sTest2 = "ÄÖÜ€";
string sTest3 = "aß?";

printf("\r\nC Style Resluts:\r\n");
printf("Test1: %s, strlen(): %d\r\n",Test1, (int) strlen(Test1));
printf("Test2: %s, strlen(): %d\r\n",Test2, (int) strlen(Test2));
printf("Test3: %s, strlen(): %d\r\n",Test3, (int) strlen(Test3));

printf("\r\nC++ Style Resluts:\r\n");
cout << "Test1: " << sTest1 << ", Test1.size():  " <<sTest1.size() <<"  sTest1.length(): " << sTest1.length() << endl;
cout << "Test1: " << sTest2 << ", Test2.size():  " <<sTest2.size() <<"  sTest1.length(): " << sTest2.length() << endl;
cout << "Test1: " << sTest3 << ", Test3.size(): " <<sTest3.size() << "  sTest1.length(): " << sTest3.length() << endl;
return 0;
}

The output of the example is this:

C Style Results:
Test1: ABCD, strlen(): 4    
Test2: ÄÖÜ€, strlen(): 9
Test3: aß?, strlen(): 10

C++ Style Results:
Test1: ABCD, sTest1.size():  4  sTest1.length(): 4
Test2: ÄÖÜ€, sTest2.size():  9  sTest2.length(): 9
Test3: aß?, sTest3.size(): 10  sTest3.length(): 10

How to validate a form with multiple checkboxes to have atleast one checked

I had a slighlty different scenario. My checkboxes were created in dynamic and they were not of same group. But atleast any one of them had to be checked. My approach (never say this is perfect), I created a genric validator for all of them:

jQuery.validator.addMethod("validatorName", function(value, element) {
    if (($('input:checkbox[name=chkBox1]:checked').val() == "Val1") ||
        ($('input:checkbox[name=chkBox2]:checked').val() == "Val2") ||
        ($('input:checkbox[name=chkBox3]:checked').val() == "Val3")) 
    {   
        return true;
    }
    else
    {
        return false;
    }       
}, "Please Select any one value");

Now I had to associate each of the chkbox to this one single validator.

Again I had to trigger the validation when any of the checkboxes were clicked triggering the validator.

$('#piRequest input:checkbox[name=chkBox1]').click(function(e){
    $("#myform").valid();
});

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Error while installing json gem 'mkmf.rb can't find header files for ruby'

sudo apt-get --reinstall install ruby

try it for ubuntu 16.04

How to convert byte array to string and vice versa?

You can use simple for loop for conversion:

public void byteArrToString(){
   byte[] b = {'a','b','$'};
   String str = ""; 
   for(int i=0; i<b.length; i++){
       char c = (char) b[i];
       str+=c;
   }
   System.out.println(str);
}

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Turns out you can't use the root user in 5.7 anymore without becoming a sudoer. That means you can't just run mysql -u root anymore and have to do sudo mysql -u root instead.

That also means that it will no longer work if you're using the root user in a GUI (or supposedly any non-command line application). To make it work you'll have to create a new user with the required privileges and use that instead.

See this answer for more details.

Relative Paths in Javascript in an external file

Please use the following syntax to enjoy the luxury of asp.net tilda ("~") in javascript

<script src=<%=Page.ResolveUrl("~/MasterPages/assets/js/jquery.js")%>></script>

Convert a list to a string in C#

String.Join(" ", myList) or String.Join(" ", myList.ToArray()). The first argument is the separator between the substrings.

var myList = new List<String> { "foo","bar","baz"};
Console.WriteLine(String.Join("-", myList)); // prints "foo-bar-baz"

Depending on your version of .NET you might need to use ToArray() on the list first..

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

Adding header to all request with Retrofit 2

If you use addInterceptor method for add HttpLoggingInterceptor, it won't be logging the things that added by other interceptors applied later than HttpLoggingInterceptor.

For example: If you have two interceptors "HttpLoggingInterceptor" and "AuthInterceptor", and HttpLoggingInterceptor applied first, then you can't view the http-params or headers which set by AuthInterceptor.

OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addNetworkInterceptor(logging)
.addInterceptor(new AuthInterceptor());

I solved it, via using addNetworkInterceptor method.

Read binary file as string in Ruby

on os x these are the same for me... could this maybe be extra "\r" in windows?

in any case you may be better of with:

contents = File.read("e.tgz")
newFile = File.open("ee.tgz", "w")
newFile.write(contents)

JWT authentication for ASP.NET Web API

I think you should use some 3d party server to support the JWT token and there is no out of the box JWT support in WEB API 2.

However there is an OWIN project for supporting some format of signed token (not JWT). It works as a reduced OAuth protocol to provide just a simple form of authentication for a web site.

You can read more about it e.g. here.

It's rather long, but most parts are details with controllers and ASP.NET Identity that you might not need at all. Most important are

Step 9: Add support for OAuth Bearer Tokens Generation

Step 12: Testing the Back-end API

There you can read how to set up endpoint (e.g. "/token") that you can access from frontend (and details on the format of the request).

Other steps provide details on how to connect that endpoint to the database, etc. and you can chose the parts that you require.

How can one see the structure of a table in SQLite?

.schema TableName

Where TableName is the name of the Table

How are VST Plugins made?

I realize this is a very old post, but I have had success using the JUCE library, which builds projects for the major IDE's like Xcode, VS, and Codeblocks and automatically builds VST/3, AU/v3, RTAS, and AAX.

https://www.juce.com/

Is there functionality to generate a random character in Java?

If you don't mind adding a new library in your code you can generate characters with MockNeat (disclaimer: I am one of the authors).

MockNeat mock = MockNeat.threadLocal();

Character chr = mock.chars().val();
Character lowerLetter = mock.chars().lowerLetters().val();
Character upperLetter = mock.chars().upperLetters().val();
Character digit = mock.chars().digits().val();
Character hex = mock.chars().hex().val(); 

Difference Between ViewResult() and ActionResult()

In the Controller , one could use the below syntax

public ViewResult EditEmployee() {
    return View();
}

public ActionResult EditEmployee() {
    return View();
}

In the above example , only the return type varies . one returns ViewResult whereas the other one returns ActionResult.

ActionResult is an abstract class . It can accept:

ViewResult , PartialViewResult, EmptyResult , RedirectResult , RedirectToRouteResult , JsonResult , JavaScriptResult , ContentResult, FileContentResult , FileStreamResult , FilePathResult etc.

The ViewResult is a subclass of ActionResult.

Custom format for time command

To use the Bash builtin time rather than /bin/time you can set this variable:

TIMEFORMAT='%3R'

which will output the real time that looks like this:

5.009

or

65.233

The number specifies the precision and can range from 0 to 3 (the default).

You can use:

TIMEFORMAT='%3lR'

to get output that looks like:

3m10.022s

The l (ell) gives a long format.

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Today is DateTime.Now with time set to zero.

It is important to note that there is a difference between a DateTime value, which represents the number of ticks that have elapsed since midnight of January 1, 0000, and the string representation of that DateTime value, which expresses a date and time value in a culture-specific-specific format: https://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx

DateTime.Now.Ticks is the actual time stored by .net (essentially UTC time), the rest are just representations (which are important for display purposes).

If the Kind property is DateTimeKind.Local it implicitly includes the time zone information of the local computer. When sending over a .net web service, DateTime values are by default serialized with time zone information included, e.g. 2008-10-31T15:07:38.6875000-05:00, and a computer in another time zone can still exactly know what time is being referred to.

So, using DateTime.Now and DateTime.Today is perfectly OK.

You usually start running into trouble when you begin confusing the string representation with the actual value and try to "fix" the DateTime, when it isn't broken.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Try the below code snippet:

with open(path, 'rb') as f:
  text = f.read()

HTML if image is not found

This one worked for me. using the srcset. I have just learnt about it so i dont know if browsers support it but it has worked for me. Try it and later give me your feed back.

 <img src="smiley.gif" srcset="alternatve.gif" width="32" height="32" />

Replacing &nbsp; from javascript dom text node

Removes everything between & and ; which all such symbols have. if you juts want to get rid of them.

text.replace(/&.*;/g,'');

Count number of tables in Oracle

try:

SELECT COUNT(*) FROM USER_TABLES;

Well i dont have oracle on my machine, i run mysql (OP comment)

at the time of writing, this site was great for testing on a variety of database types.

Why am I getting the error "connection refused" in Python? (Sockets)

Assume s = socket.socket() The server can be bound by following methods: Method 1:

host = socket.gethostname()
s.bind((host, port))

Method 2:

host = socket.gethostbyname("localhost")  #Note the extra letters "by"
s.bind((host, port))

Method 3:

host = socket.gethostbyname("192.168.1.48")
s.bind((host, port))

If you do not exactly use same method on the client side, you will get the error: socket.error errno 111 connection refused.

So, you have to use on the client side exactly same method to get the host, as you do on the server. For example, in case of client, you will correspondingly use following methods:

Method 1:

host = socket.gethostname() 
s.connect((host, port))

Method 2:

host = socket.gethostbyname("localhost") # Get local machine name
s.connect((host, port))

Method 3:

host = socket.gethostbyname("192.168.1.48") # Get local machine name
s.connect((host, port))

Hope that resolves the problem.

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

How to detect if javascript files are loaded?

When they say "The bottom of the page" they don't literally mean the bottom: they mean just before the closing </body> tag. Place your scripts there and they will be loaded before the DOMReady event; place them afterwards and the DOM will be ready before they are loaded (because it's complete when the closing </html> tag is parsed), which as you have found will not work.

If you're wondering how I know that this is what they mean: I have worked at Yahoo! and we put our scripts just before the </body> tag :-)

EDIT: also, see T.J. Crowder's reply and make sure you have things in the correct order.

Flatten nested dictionaries, compressing keys

Davoud's solution is very nice but doesn't give satisfactory results when the nested dict also contains lists of dicts, but his code be adapted for that case:

def flatten_dict(d):
    items = []
    for k, v in d.items():
        try:
            if (type(v)==type([])): 
                for l in v: items.extend(flatten_dict(l).items())
            else: 
                items.extend(flatten_dict(v).items())
        except AttributeError:
            items.append((k, v))
    return dict(items)

regex error - nothing to repeat

It's not only a Python bug with * actually, it can also happen when you pass a string as a part of your regular expression to be compiled, like ;

import re
input_line = "string from any input source"
processed_line= "text to be edited with {}".format(input_line)
target = "text to be searched"
re.search(processed_line, target)

this will cause an error if processed line contained some "(+)" for example, like you can find in chemical formulae, or such chains of characters. the solution is to escape but when you do it on the fly, it can happen that you fail to do it properly...

How to check if type is Boolean

You can create a function that checks the typeof for an argument.

function isBoolean(value) {
  return typeof value === "boolean";
}

MySQL InnoDB not releasing disk space after deleting data rows from table

There are several ways to reclaim diskspace after deleting data from table for MySQL Inodb engine

If you don't use innodb_file_per_table from the beginning, dumping all data, delete all file, recreate database and import data again is only way ( check answers of FlipMcF above )

If you are using innodb_file_per_table, you may try

  1. If you can delete all data truncate command will delete data and reclaim diskspace for you.
  2. Alter table command will drop and recreate table so it can reclaim diskspace. Therefore after delete data, run alter table that change nothing to release hardisk ( ie: table TBL_A has charset uf8, after delete data run ALTER TABLE TBL_A charset utf8 -> this command change nothing from your table but It makes mysql recreate your table and regain diskspace
  3. Create TBL_B like TBL_A . Insert select data you want to keep from TBL_A into TBL_B. Drop TBL_A, and rename TBL_B to TBL_A. This way is very effective if TBL_A and data that needed to delete is big (delete command in MySQL innodb is very bad performance)

How can I run multiple curl requests processed sequentially?

This will do what you want, uses an input file and is super fast

#!/bin/bash
IFS=$'\n'
file=/path/to/input.txt
lines=$(cat ${file})
for line in ${lines}; do
   curl "${line}"
done
IFS=""
exit ${?}

one entry per line on your input file, it will follow the order of your input file

save it as whatever.sh and make it executable

How to output to the console and file?

Create an output file and custom function:

outputFile = open('outputfile.log', 'w')

def printing(text):
    print(text)
    if outputFile:
        outputFile.write(str(text))

Then instead of print(text) in your code, call printing function.

printing("START")
printing(datetime.datetime.now())
printing("COMPLETE")
printing(datetime.datetime.now())

How to remove files that are listed in the .gitignore but still on the repository?

I can't say it's an appropriate solution but you can try this.

Steps

  • I am hoping that you have already cloned your repo.
  • Now copy the file somewhere outside of your project.
  • Add that filename with a location in gitigonre file.
  • Remove that file from your local project.
  • Push your code to remote origin.
  • And now add that copied file into your project it'll be ignored.

This is just a hack solution if you want to maintain the history and don't to create mass in it.

If you don't want to use this solution please kindly ignore and try to avoid devote it. Because I am really trying to increase my score on this side

Enzyme - How to access and set <input> value?

I am using create-react-app which comes with jest by default and enzyme 2.7.0.

This worked for me:

const wrapper = mount(<EditableText defaultValue="Hello" />);
const input = wrapper.find('input')[index]; // where index is the position of the input field of interest
input.node.value = 'Change';
input.simulate('change', input);
done();

plot different color for different categorical levels using matplotlib

Here's a succinct and generic solution to use a seaborn color palette.

First find a color palette you like and optionally visualize it:

sns.palplot(sns.color_palette("Set2", 8))

Then you can use it with matplotlib doing this:

# Unique category labels: 'D', 'F', 'G', ...
color_labels = df['color'].unique()

# List of RGB triplets
rgb_values = sns.color_palette("Set2", 8)

# Map label to RGB
color_map = dict(zip(color_labels, rgb_values))

# Finally use the mapped values
plt.scatter(df['carat'], df['price'], c=df['color'].map(color_map))

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

How do I see the extensions loaded by PHP?

Running

php -m
will give you all the modules, and
php -i
will give you a lot more detailed information on what the current configuration.

Can I write into the console in a unit test? If yes, why doesn't the console window open?

You can use

Trace.WriteLine()

to write to the Output window when debugging a unit test.

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

php string to int

Use str_replace to remove the spaces first ?

How to call a Parent Class's method from Child Class in Python?

Here is an example of using super():

#New-style classes inherit from object, or from another new-style class
class Dog(object):

    name = ''
    moves = []

    def __init__(self, name):
        self.name = name

    def moves_setup(self):
        self.moves.append('walk')
        self.moves.append('run')

    def get_moves(self):
        return self.moves

class Superdog(Dog):

    #Let's try to append new fly ability to our Superdog
    def moves_setup(self):
        #Set default moves by calling method of parent class
        super(Superdog, self).moves_setup()
        self.moves.append('fly')

dog = Superdog('Freddy')
print dog.name # Freddy
dog.moves_setup()
print dog.get_moves() # ['walk', 'run', 'fly']. 
#As you can see our Superdog has all moves defined in the base Dog class

RestTemplate: How to send URL and query parameters together

One simple way to do that is:

String url = "http://test.com/Services/rest/{id}/Identifier"

UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));

and then adds the query params.

Save a subplot in matplotlib

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

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

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

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

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

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

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

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

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

How to export datagridview to excel using vb.net?

The following code works fine for me :)

Protected Sub ExportToExcel(sender As Object, e As EventArgs) Handles ExportExcel.Click
        Try
            Response.Clear()
            Response.Buffer = True
            Response.AddHeader("content-disposition", "attachment;filename=ExportEthias.xls")
            Response.Charset = ""
            Response.ContentType = "application/vnd.ms-excel"
            Using sw As New StringWriter()
                Dim hw As New HtmlTextWriter(sw)
                GvActifs.RenderControl(hw)
                'Le format de base est le texte pour éviter les problèmes d'arrondis des nombres
                Dim style As String = "<style> .textmode { } </style>"
                Response.Write(Style)
                Response.Output.Write(sw.ToString())
                Response.Flush()
                Response.End()
            End Using
        Catch ex As Exception
            lblMessage.Text = "Erreur export Excel : " & ex.Message
        End Try
    End Sub
    Public Overrides Sub VerifyRenderingInServerForm(control As Control)
        ' Verifies that the control is rendered
    End Sub

Hopes this help you.

Div table-cell vertical align not working

In my case, I wanted to center in a parent container with position: absolute.

<div class="absolute-container">
    <div class="parent-container">
        <div class="centered-content">
            My content
        </div>
    </div>
</div>

I had to add some positioning for top, bottom, left & right.

.absolute-container {
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}

.parent-container {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    display: table
}

.centered-content {
    display: table-cell;
    text-align: center;
    vertical-align: middle
}

What is a constant reference? (not a reference to a constant)

The statement icr=y; does not make the reference refer to y; it assigns the value of y to the variable that icr refers to, i.

References are inherently const, that is you can't change what they refer to. There are 'const references' which are really 'references to const', that is you can't change the value of the object they refer to. They are declared const int& or int const& rather than int& const though.

Where is Ubuntu storing installed programs?

If you installed the package with the Ubuntu package manager (apt, synaptic, dpkg or similar), you can get information about the installed package with

dpkg -L <package_name>

Why can't I shrink a transaction log file, even after backup?

Thank you to everyone for answering.

We finally found the issue. In sys.databases, log_reuse_wait_desc was equal to 'replication'. Apparently this means something to the effect of SQL Server waiting for a replication task to finish before it can reuse the log space.

Replication has never been used on this DB or this server was toyed with once upon a time on this db. We cleared the incorrect state by running sp_removedbreplication. After we ran this, backup log and dbcc shrinkfile worked just fine.

Definitely one for the bag-of-tricks.

Sources:

http://social.technet.microsoft.com/Forums/pt-BR/sqlreplication/thread/34ab68ad-706d-43c4-8def-38c09e3bfc3b

http://www.eggheadcafe.com/conversation.aspx?messageid=34020486&threadid=33890705

What is the best open source help ticket system?

TRAC. Open source, Python-based

What's the difference between "2*2" and "2**2" in Python?

A double asterisk means to the power of. A single asterisk means multiplied by. 22 is the same as 2x2 which is why both answers came out as 4.

Select From all tables - MySQL

SELECT product FROM Your_table_name WHERE Product LIKE '%XYZ%';

The above statement will show result from a single table. If you want to add more tables then simply use the UNION statement.

SELECT product FROM Table_name_1 
WHERE Product LIKE '%XYZ%'  
UNION  
SELECT product FROM Table_name_2 
WHERE Product LIKE '%XYZ%'  
UNION  
SELECT product FROM Table_name_3 
WHERE Product LIKE '%XYZ%' 

... and so on

Getting cursor position in Python

You will not find such function in standard Python libraries, while this function is Windows specific. However if you use ActiveState Python, or just install win32api module to standard Python Windows installation you can use:

x, y = win32api.GetCursorPos()

PHP - SSL certificate error: unable to get local issuer certificate

I tried this it works

open

vendor\guzzlehttp\guzzle\src\Handler\CurlFactory.php

and change this

 $conf[CURLOPT_SSL_VERIFYHOST] = 2;
 `enter code here`$conf[CURLOPT_SSL_VERIFYPEER] = true;

to this

$conf[CURLOPT_SSL_VERIFYHOST] = 0;
$conf[CURLOPT_SSL_VERIFYPEER] = FALSE;

Reminder - \r\n or \n\r?

The sequence is CR (Carriage Return) - LF (Line Feed). Remember dot matrix printers? Exactly. So - the correct order is \r \n

Can there exist two main methods in a Java program?

the possibility of two main(String[] args) methods within the same scope create confusion for the JVM. It fails to use them as overloaded methods. So the signatures in terms of parameters) must be different.

How do you calculate log base 2 in Java for integers?

let's add:

int[] fastLogs;

private void populateFastLogs(int length) {
    fastLogs = new int[length + 1];
    int counter = 0;
    int log = 0;
    int num = 1;
    fastLogs[0] = 0;
    for (int i = 1; i < fastLogs.length; i++) {
        counter++;
        fastLogs[i] = log;
        if (counter == num) {
            log++;
            num *= 2;
            counter = 0;
        }
    }
}

Source: https://github.com/pochuan/cs166/blob/master/ps1/rmq/SparseTableRMQ.java

Set 4 Space Indent in Emacs in Text Mode

(setq tab-width 4)
(setq tab-stop-list '(4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72 76 80))
(setq indent-tabs-mode nil)

javascript - pass selected value from popup window to parent window input box

(parent window)

<html> 
<script language="javascript"> 
function openWindow() { 
  window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no"); 
} 
</script> 
<body> 
<form name=frm> 
<input id=text1 type=text> 
<input type=button onclick="javascript:openWindow()" value="Open window.."> 
</form> 
</body> 
</html>

(child window)

<html> 
<script language="javascript"> 
function changeParent() { 
  window.opener.document.getElementById('text1').value="Value changed..";
  window.close();
} 
</script> 
<body> 
<form> 
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value.."> 
</form> 
</body> 
</html>

http://www.codehappiness.com/post/access-parent-window-from-child-window-or-access-child-window-from-parent-window-using-javascript.aspx

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

how to get vlc logs?

Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...

Superscript in Python plots

You just need to have the full expression inside the $. Basically, you need "meters $10^1$". You don't need usetex=True to do this (or most any mathematical formula).

You may also want to use a raw string (e.g. r"\t", vs "\t") to avoid problems with things like \n, \a, \b, \t, \f, etc.

For example:

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $e^{\sin(\omega\phi)}$',
       xlabel='meters $10^1$', ylabel=r'Hertz $(\frac{1}{s})$')
plt.show()

enter image description here

If you don't want the superscripted text to be in a different font than the rest of the text, use \mathregular (or equivalently \mathdefault). Some symbols won't be available, but most will. This is especially useful for simple superscripts like yours, where you want the expression to blend in with the rest of the text.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title=r'This is an expression $\mathregular{e^{\sin(\omega\phi)}}$',
       xlabel='meters $\mathregular{10^1}$',
       ylabel=r'Hertz $\mathregular{(\frac{1}{s})}$')
plt.show()

enter image description here

For more information (and a general overview of matplotlib's "mathtext"), see: http://matplotlib.org/users/mathtext.html

How to determine whether an object has a given property in JavaScript

You can trim that up a bit like this:

if ( x.y !== undefined ) ...

How to Sort a List<T> by a property in the object

Make use of LiNQ OrderBy

List<Order> objListOrder=new List<Order> ();
    objListOrder=GetOrderList().OrderBy(o=>o.orderid).ToList();

Get index of a row of a pandas dataframe as an integer

Little sum up for searching by row:

This can be useful if you don't know the column values ??or if columns have non-numeric values

if u want get index number as integer u can also do:

item = df[4:5].index.item()
print(item)
4

it also works in numpy / list:

numpy = df[4:7].index.to_numpy()[0]
lista = df[4:7].index.to_list()[0]

in [x] u pick number in range [4:7], for example if u want 6:

numpy = df[4:7].index.to_numpy()[2]
print(numpy)
6

for DataFrame:

df[4:7]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449

or:

df[(df.index>=4) & (df.index<7)]

    A          B
4   5   0.894525
5   6   0.978174
6   7   0.859449   

Extract the filename from a path

Just to complete the answer above that use .Net.

In this code the path is stored in the %1 argument (which is written in the registry under quote that are escaped: \"%1\" ). To retrieve it, we need the $arg (inbuilt arg). Don't forget the quote around $FilePath.

# Get the File path:  
$FilePath = $args
Write-Host "FilePath: " $FilePath

# Get the complete file name:
$file_name_complete = [System.IO.Path]::GetFileName("$FilePath")
Write-Host "fileNameFull :" $file_name_complete

# Get File Name Without Extension:
$fileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension("$FilePath")
Write-Host "fileNameOnly :" $fileNameOnly

# Get the Extension:
$fileExtensionOnly = [System.IO.Path]::GetExtension("$FilePath")
Write-Host "fileExtensionOnly :" $fileExtensionOnly

How to get 30 days prior to current date?

startDate = new Date(today.getTime() - 30*24*60*60*1000);

The .getTime() method returns a standard JS timestamp (milliseconds since Jan 1/1970) on which you can use regular math operations, which can be fed back to the Date object directly.

X11/Xlib.h not found in Ubuntu

Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.

A simple get started:

Create test.cpp: (This will be built and run to verify you got things set up right.)

#include <X11/Xlib.h>
#include <unistd.h>


main()
{
  // Open a display.
  Display *d = XOpenDisplay(0);

  if ( d )
    {
      // Create the window
      Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
                   100, 0, CopyFromParent, CopyFromParent,
                   CopyFromParent, 0, 0);

      // Show the window
      XMapWindow(d, w);
      XFlush(d);

      // Sleep long enough to see the window.
      sleep(10);
    }
  return 0;
}

(Source: LinuxGazette)

Try: g++ test.cpp -lX11 If it builds to a.out, try running it. If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.

If your response is:

    test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
    compilation terminated.

you need to install X11 development libraries. sudo apt-get install libx11-dev

Retry g++ test.cpp -lX11

If it works, you're golden.

Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

This type of warnings are usually flagged because of the request HTTP headers. Specifically the Accept request header. The MDN documentation for HTTP headers states

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json is probably not on the list of MIME types in the Accept header sent by the browser hence the warning.

Solution

Custom HTTP headers can only be sent programmatically via XMLHttpRequest or any of the js library wrappers implementing it.

How to check whether an object is a date?

We can also validate it by below code

var a = new Date();
a.constructor === Date
/*
true
*/

enter image description here

How to insert text into the textarea at the current cursor position?

For the sake of proper Javascript

HTMLTextAreaElement.prototype.insertAtCaret = function (text) {
  text = text || '';
  if (document.selection) {
    // IE
    this.focus();
    var sel = document.selection.createRange();
    sel.text = text;
  } else if (this.selectionStart || this.selectionStart === 0) {
    // Others
    var startPos = this.selectionStart;
    var endPos = this.selectionEnd;
    this.value = this.value.substring(0, startPos) +
      text +
      this.value.substring(endPos, this.value.length);
    this.selectionStart = startPos + text.length;
    this.selectionEnd = startPos + text.length;
  } else {
    this.value += text;
  }
};

How to flip background image using CSS?

For what it's worth, for Gecko-based browsers you can't condition this thing off of :visited due to the resulting privacy leaks. See http://hacks.mozilla.org/2010/03/privacy-related-changes-coming-to-css-vistited/

How to prevent text in a table cell from wrapping

Have a look at the white-space property, used like this:

th {
    white-space: nowrap;
}

This will force the contents of <th> to display on one line.

From linked page, here are the various options for white-space:

normal
This value directs user agents to collapse sequences of white space, and break lines as necessary to fill line boxes.

pre
This value prevents user agents from collapsing sequences of white space. Lines are only broken at preserved newline characters.

nowrap
This value collapses white space as for 'normal', but suppresses line breaks within text.

pre-wrap
This value prevents user agents from collapsing sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

pre-line
This value directs user agents to collapse sequences of white space. Lines are broken at preserved newline characters, and as necessary to fill line boxes.

Resize jqGrid when browser is resized?

The main answer worked for me but made the app extremely unresponsive in IE, so I used a timer as suggested. Code looks something like this ($(#contentColumn) is the div that the JQGrid sits in):

  function resizeGrids() {
    var reportObjectsGrid = $("#ReportObjectsGrid");
    reportObjectsGrid.setGridWidth($("#contentColumn").width());
};

var resizeTimer;

$(window).bind('resize', function () {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resizeGrids, 60);
});

Rename computer and join to domain in one step with PowerShell

I was looking for the same thing today and finally got a way to do it. I was hinted that it was possible due to the use of sconfig, which ask you if you want to change the computer name after joining it to a domain. Here is my raw code line. It might be enhanced but to tired to think about it for now.

$strCompName = Read-host 'Name '
$strAdmin = read-host "Authorized user for this operation "
$strDomain = read-host "Name of the domain to be joined "
add-computer -DomainName $strDomain -Credential $strAdmin
Rename-computer -newname $strCompName -DomainCredential $strAdmin

Quicksort: Choosing the pivot

In a truly optimized implementation, the method for choosing pivot should depend on the array size - for a large array, it pays off to spend more time choosing a good pivot. Without doing a full analysis, I would guess "middle of O(log(n)) elements" is a good start, and this has the added bonus of not requiring any extra memory: Using tail-call on the larger partition and in-place partitioning, we use the same O(log(n)) extra memory at almost every stage of the algorithm.

How to align entire html body to the center?

I just stumbled on this old post, and while I'm sure user01 has long since found his answer, I found the current answers don't quite work. After playing around for a little bit using info provided by the others, I found a solution that worked in IE, Firefox, and Chrome. In CSS:

html, body {
    height: 100%;
}

html {
    display: table;
    margin: auto;
}

body {
    display: table-cell;
    vertical-align: middle;
}

This is almost identical to abernier's answer, but I found that including width would break the centering, as would omitting the auto margin. I hope anyone else who stumbles on this thread will find my answer helpful.

Note: Omit html, body { height: 100%; } to only center horizontally.

How to show x and y axes in a MATLAB graph?

By default, plot does show axes, unless you've modified some settings. Try the following

hold on; % make sure no new plot window is created on every plot command
axes(); % produce plot window with axes
plot(% whatever your plot command is);
plot([0 10], [0 0], 'k-'); % plot the horizontal line

What are the use cases for selecting CHAR over VARCHAR in SQL?

It's the classic space versus performance tradeoff.

In MS SQL 2005, Varchar (or NVarchar for lanuagues requiring two bytes per character ie Chinese) are variable length. If you add to the row after it has been written to the hard disk it will locate the data in a non-contigious location to the original row and lead to fragmentation of your data files. This will affect performance.

So, if space is not an issue then Char are better for performance but if you want to keep the database size down then varchars are better.

What's a good (free) visual merge tool for Git? (on windows)

On Windows, a good 3-way diff/merge tool remains kdiff3 (WinMerge, for now, is still 2-way based, pending WinMerge3)

See "How do you merge in GIT on Windows?" and this config.


Update 7 years later (Aug. 2018): Artur Kedzior mentions in the comments:

If you guys happen to use Visual Studio (Community Edition is free), try the tool that is shipped with it: vsDiffMerge.exe. It's really awesome and easy to use.

How to set time delay in javascript

you can use of promise

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

use

console.log("Hello");
sleep(2000).then(() => { console.log("World!"); });

or

console.log("Hello");
await sleep(2000);
console.log("World!");

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

How to remove newlines from beginning and end of a string?

For anyone else looking for answer to the question when dealing with different linebreaks:

string.replaceAll("(\n|\r|\r\n)$", ""); // Java 7
string.replaceAll("\\R$", "");          // Java 8

This should remove exactly the last line break and preserve all other whitespace from string and work with Unix (\n), Windows (\r\n) and old Mac (\r) line breaks: https://stackoverflow.com/a/20056634, https://stackoverflow.com/a/49791415. "\\R" is matcher introduced in Java 8 in Pattern class: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html

This passes these tests:

// Windows:
value = "\r\n test \r\n value \r\n";
assertEquals("\r\n test \r\n value ", value.replaceAll("\\R$", ""));

// Unix:
value = "\n test \n value \n";
assertEquals("\n test \n value ", value.replaceAll("\\R$", ""));

// Old Mac:
value = "\r test \r value \r";
assertEquals("\r test \r value ", value.replaceAll("\\R$", ""));

jQuery-- Populate select from json

fiddle

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

How to set cornerRadius for only top-left and top-right corner of a UIView?

Simple extension

extension UIView {
    func roundCorners(corners: UIRectCorner, radius: CGFloat) {
        if #available(iOS 11, *) {
            self.clipsToBounds = true
            self.layer.cornerRadius = radius
            var masked = CACornerMask()
            if corners.contains(.topLeft) { masked.insert(.layerMinXMinYCorner) }
            if corners.contains(.topRight) { masked.insert(.layerMaxXMinYCorner) }
            if corners.contains(.bottomLeft) { masked.insert(.layerMinXMaxYCorner) }
            if corners.contains(.bottomRight) { masked.insert(.layerMaxXMaxYCorner) }
            self.layer.maskedCorners = masked
        }
        else {
            let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
            let mask = CAShapeLayer()
            mask.path = path.cgPath
            layer.mask = mask
        }
    }
}

Usage:

view.roundCorners(corners: [.bottomLeft, .bottomRight], radius: 12)

Select n random rows from SQL Server table

I was using it in subquery and it returned me same rows in subquery

 SELECT  ID ,
            ( SELECT TOP 1
                        ImageURL
              FROM      SubTable 
              ORDER BY  NEWID()
            ) AS ImageURL,
            GETUTCDATE() ,
            1
    FROM    Mytable

then i solved with including parent table variable in where

SELECT  ID ,
            ( SELECT TOP 1
                        ImageURL
              FROM      SubTable 
              Where Mytable.ID>0
              ORDER BY  NEWID()
            ) AS ImageURL,
            GETUTCDATE() ,
            1
    FROM    Mytable

Note the where condtition

Java correct way convert/cast object to Double

You can use the instanceof operator to test to see if it is a double prior to casting. You can then safely cast it to a double. In addition you can test it against other known types (e.g. Integer) and then coerce them into a double manually if desired.

    Double d = null;
    if (obj instanceof Double) {
        d = (Double) obj;
    }

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

I suggest you use TO_CHAR() when converting to string. In order to do that, you need to build a date first.

SELECT TO_CHAR(TO_DATE(DAY||'-'||MONTH||'-'||YEAR, 'dd-mm-yyyy'), 'dd-mm-yyyy') AS FORMATTED_DATE
FROM
    (SELECT EXTRACT( DAY FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy')
        FROM DUAL
        )) AS DAY, TO_NUMBER(EXTRACT( MONTH FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )), 09) AS MONTH, EXTRACT(YEAR FROM
        (SELECT TO_DATE('1/21/2000', 'mm/dd/yyyy') FROM DUAL
        )) AS YEAR
    FROM DUAL
    );

Setting up Eclipse with JRE Path

This may sound dumb, but it may be a fresh, or damaged install, so is the JDK installed? If not, go to the download site and download the latest version of Java JRE. Like I said, this may sound dumb, but it solved my problem.

http://www.oracle.com/technetwork/java/javase/downloads/index.html

How to install PHP intl extension in Ubuntu 14.04

In Ubuntu 20.04, PHP 7.4 use the following command:

sudo apt-get install php7.4-intl

replace 7.4 with your PHP version

How to enter quotes in a Java string?

In Java, you can escape quotes with \:

String value = " \"ROM\" ";

Button Listener for button in fragment in android

    //sure run it i will also test it
//we make a class that extends with the fragment
    public class Example_3_1 extends Fragment  implements OnClickListener
    {
       View vi;
        EditText t;
        EditText t1;
        Button bu;
 // that are by defult function of fragment extend class
     @Override
       public View onCreateView(LayoutInflater inflater,ViewGroup container,BundlesavedInstanceState) 
       {        
           vi=inflater.inflate(R.layout.example_3_1, container, false);// load the xml file 
           bu=(Button) vi.findViewById(R.id.button1);// get button id from example_3_1 xml file
           bu.setOnClickListener(this); //on button appay click listner
           t=(EditText) vi.findViewById(R.id.editText1);// id get from example_3_1 xml file
           t1=(EditText) vi.findViewById(R.id.editText2);
          return vi; // return the view object,that set the xml file  example_3_1 xml file
       }
       @Override
       public void onClick(View v)//on button click that called
       {

          switch(v.getId())// on run time get id what button os click and get id
          {
          case R.id.button1:        // it mean if button1 click then this work
           t.setText("UMTien");     //set text 
           t1.setText("programming");
           break;
          }
    }     }

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

One good thing about @LazyCollection(LazyCollectionOption.FALSE) is that several fields with this annotation can coexist while FetchType.EAGER cannot, even in the situations where such coexistence is legit.

For example, an Order may have a list of OrderGroup(a short one) as well as a list of Promotions(also short). @LazyCollection(LazyCollectionOption.FALSE) can be used on both without causing LazyInitializationException neither MultipleBagFetchException.

In my case @Fetch did solve my problem of MultipleBacFetchException but then causes LazyInitializationException, the infamous no Session error.

How do I change file permissions in Ubuntu

So that you don't mess up other permissions already on the file, use the flag +, such as via

sudo chmod -R o+rw /var/www

Where does gcc look for C and C++ header files?

`gcc -print-prog-name=cc1plus` -v

This command asks gcc which C++ preprocessor it is using, and then asks that preprocessor where it looks for includes.

You will get a reliable answer for your specific setup.

Likewise, for the C preprocessor:

`gcc -print-prog-name=cpp` -v

How to import a module given its name as string?

With Python older than 2.7/3.1, that's pretty much how you do it.

For newer versions, see importlib.import_module for Python 2 and and Python 3.

You can use exec if you want to as well.

Or using __import__ you can import a list of modules by doing this:

>>> moduleNames = ['sys', 'os', 're', 'unittest'] 
>>> moduleNames
['sys', 'os', 're', 'unittest']
>>> modules = map(__import__, moduleNames)

Ripped straight from Dive Into Python.

Single Line Nested For Loops

You can use two for loops in same line by using zip function

Code:

list1 = ['Abbas', 'Ali', 'Usman']
list2 = ['Kamran', 'Asgar', 'Hamza', 'Umer']
list3 = []
for i,j in zip(list1,list2):
    list3.append(i)
    list3.append(j)
print(list3)

Output:

['Abbas', 'Kamran', 'Ali', 'Asgar', 'Usman', 'Hamza']

So, by using zip function, we can use two for loops or we can iterate two lists in same row.

Angularjs - display current date

You can use moment() and format() functions in AngularJS.

Controller:

var app = angular.module('demoApp', []);   
app.controller( 'demoCtrl', ['$scope', '$moment' function($scope , $moment) {
$scope.date = $moment().format('MM/DD/YYYY');
}]);

View:

<div ng-app="demoApp">
  <div ng-controller="demoCtrl">
    {{date}}
  </div>
</div>