Programs & Examples On #Assembla

Assembla is a company that provides cloud-based tools to organize and manage open-source and commercial software development.

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

How do I set up a private Git repository on GitHub? Is it even possible?

Once you have a paid account on GitHub, it is not obvious how to create a private repository. To create a private repository for an organization with paid account, go to https://github.com/organizations/MYORGANIZATIONNAME.

The only way I've figured how to navigate there is:

  • Go to to your organization's home page: https://github.com/MYORGANIZATIONNAME
  • Click on the "Edit MYORGANIZATION's Profile" button at the top right
  • Click on the "GitHub" icon at the top left (non-obvious)
  • Click on the "News Feed" tab (non-obvious)
  • Click on the "New Repository" button at the right ...

How to create the branch from specific commit in different branch

If you are using this form of the branch command (with start point), it does not matter where your HEAD is.

What you are doing:

git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8
  • First, you set your HEAD to the branch dev,

  • Second, you start a new branch on commit 07aeec98. There is no bb.txt at this commit (according to your github repo).

If you want to start a new branch at the location you have just checked out, you can either run branch with no start point:

git branch test

or as other have answered, branch and checkout there in one operation:

git checkout -b test

I think that you might be confused by that fact that 07aeec98 is part of the branch dev. It is true that this commit is an ancestor of dev, its changes are needed to reach the latest commit in dev. However, they are other commits that are needed to reach the latest dev, and these are not necessarily in the history of 07aeec98.

8480e8ae (where you added bb.txt) is for example not in the history of 07aeec98. If you branch from 07aeec98, you won't get the changes introduced by 8480e8ae.

In other words: if you merge branch A and branch B into branch C, then create a new branch on a commit of A, you won't get the changes introduced in B.

Same here, you had two parallel branches master and dev, which you merged in dev. Branching out from a commit of master (older than the merge) won't provide you with the changes of dev.


If you want to permanently integrate new changes from master into your feature branches, you should merge master into them and go on. This will create merge commits in your feature branches, though.

If you have not published your feature branches, you can also rebase them on the updated master: git rebase master featureA. Be prepared to solve possible conflicts.

If you want a workflow where you can work on feature branches free of merge commits and still integrate with newer changes in master, I recommend the following:

  • base every new feature branch on a commit of master
  • create a dev branch on a commit of master
  • when you need to see how your feature branch integrates with new changes in master, merge both master and the feature branch into dev.

Do not commit into dev directly, use it only for merging other branches.

For example, if you are working on feature A and B:

a---b---c---d---e---f---g -master
    \       \
     \       \-x -featureB
      \
       \-j---k -featureA

Merge branches into a dev branch to check if they work well with the new master:

a---b---c---d---e---f---g -master
    \       \            \
     \       \            \--x'---k' -dev
      \       \             /    /   
       \       \-x----------    /    -featureB
        \                      /
         \-j---k--------------- -featureA

You can continue working on your feature branches, and keep merging in new changes from both master and feature branches into dev regularly.

a---b---c---d---e---f---g---h---i----- -master
    \       \            \            \
     \       \            \--x'---k'---i'---l' -dev
      \       \             /    /         /
       \       \-x----------    /         /  -featureB
        \                      /         /  
         \-j---k-----------------l------ -featureA

When it is time to integrate the new features, merge the feature branches (not dev!) into master.

How to find integer array size in java

Array's has

array.length

whereas List has

list.size()

Replace array.size() to array.length

How to get first and last element in an array in java?

I think there is only one intuitive solution and it is:

int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);

Output:

First: 1
Last: 5

Assign format of DateTime with data annotations?

After Commenting

          // [DataType(DataType.DateTime)] 

Use the Data Annotation Attribute:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]

STEP-7 of the following link may help you...

http://ilyasmamunbd.blogspot.com/2014/12/jquery-datepicker-in-aspnet-mvc-5.html

String replace method is not replacing characters

You should re-assign the result of the replacement, like this:

 sentence = sentence.replace("and", " ");

Be aware that the String class is immutable, meaning that all of its methods return a new string and never modify the original string in-place, so the result of invoking a method in an instance of String must be assigned to a variable or used immediately for the change to take effect.

How to draw a line with matplotlib?

I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:

import matplotlib.pyplot as plt
import matplotlib.lines as mlines

def newline(p1, p2):
    ax = plt.gca()
    xmin, xmax = ax.get_xbound()

    if(p2[0] == p1[0]):
        xmin = xmax = p1[0]
        ymin, ymax = ax.get_ybound()
    else:
        ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
        ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])

    l = mlines.Line2D([xmin,xmax], [ymin,ymax])
    ax.add_line(l)
    return l

So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.

import numpy as np
x = np.linspace(0,10)
y = x**2

p1 = [1,20]
p2 = [6,70]

plt.plot(x, y)
newline(p1,p2)
plt.show()

enter image description here

Including external HTML file to another HTML file

You can use jquery load for that.

<script type="text/javascript">
$(document).ready(function(e) {
    $('#header').load('name.html',function(){alert('loaded')});
});
</script>

Don't forget to include jquery library befor above code.

Can I concatenate multiple MySQL rows into one field?

we have two way to concatenate columns in MySql

select concat(hobbies) as `Hobbies` from people_hobbies where 1

Or

select group_concat(hobbies) as `Hobbies` from people_hobbies where 1

How to check the Angular version?

There are many way, you check angular version Just pent the comand prompt(for windows) and type

1. ng version
2. ng v
3. ng -v

check the angular version using comand line

4. You can pakage.json file

check the angular version on pakage.json file

5.You can check in browser by presing F12 then goto elements tab

check the angular version on your browser

Full understanding of subversion about(x.x.x) please see angular documentation angularJS and angular 2+

Removing time from a Date object?

Another way to work out here is to use java.sql.Date as sql Date doesn't have time associated with it, whereas java.util.Date always have a timestamp. Whats catching point here is java.sql.Date extends java.util.Date, therefore java.util.Date variable can be a reference to java.sql.Date(without time) and to java.util.Date of course(with timestamp).

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

Sometimes the .gz extension is wrongfully appended to the filename.

  • Run file foo.csv.gz to know the actual file type.
  • Rename the file to foo.csv or whatever the actual file type is.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

This is not an answer but a feedback with few compilers of 2021. On Intel CoffeeLake 9900k.

With Microsoft compiler (VS2019), toolset v142:

unsigned        209695540000    1.8322 sec      28.6152 GB/s
uint64_t        209695540000    3.08764 sec     16.9802 GB/s

With Intel compiler 2021:

unsigned        209695540000    1.70845 sec     30.688 GB/s
uint64_t        209695540000    1.57956 sec     33.1921 GB/s

According to Mysticial's answer, Intel compiler is aware of False Data Dependency, but not Microsoft compiler.

For intel compiler, I used /QxHost (optimize of CPU's architecture which is that of the host) /Oi (enable intrinsic functions) and #include <nmmintrin.h> instead of #include <immintrin.h>.

Full compile command: /GS /W3 /QxHost /Gy /Zi /O2 /D "NDEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /Qipo /Zc:forScope /Oi /MD /Fa"x64\Release\" /EHsc /nologo /Fo"x64\Release\" //fprofile-instr-use "x64\Release\" /Fp"x64\Release\Benchmark.pch" .

The decompiled (by IDA 7.5) assembly from ICC:

int __cdecl main(int argc, const char **argv, const char **envp)
{
  int v6; // er13
  _BYTE *v8; // rsi
  unsigned int v9; // edi
  unsigned __int64 i; // rbx
  unsigned __int64 v11; // rdi
  int v12; // ebp
  __int64 v13; // r14
  __int64 v14; // rbx
  unsigned int v15; // eax
  unsigned __int64 v16; // rcx
  unsigned int v17; // eax
  unsigned __int64 v18; // rcx
  __int64 v19; // rdx
  unsigned int v20; // eax
  int result; // eax
  std::ostream *v23; // rbx
  char v24; // dl
  std::ostream *v33; // rbx
  std::ostream *v41; // rbx
  __int64 v42; // rdx
  unsigned int v43; // eax
  int v44; // ebp
  __int64 v45; // r14
  __int64 v46; // rbx
  unsigned __int64 v47; // rax
  unsigned __int64 v48; // rax
  std::ostream *v50; // rdi
  char v51; // dl
  std::ostream *v58; // rdi
  std::ostream *v60; // rdi
  __int64 v61; // rdx
  unsigned int v62; // eax

  __asm
  {
    vmovdqa [rsp+98h+var_58], xmm8
    vmovapd [rsp+98h+var_68], xmm7
    vmovapd [rsp+98h+var_78], xmm6
  }
  if ( argc == 2 )
  {
    v6 = atol(argv[1]) << 20;
    _R15 = v6;
    v8 = operator new[](v6);
    if ( v6 )
    {
      v9 = 1;
      for ( i = 0i64; i < v6; i = v9++ )
        v8[i] = rand();
    }
    v11 = (unsigned __int64)v6 >> 3;
    v12 = 0;
    v13 = Xtime_get_ticks_0();
    v14 = 0i64;
    do
    {
      if ( v6 )
      {
        v15 = 4;
        v16 = 0i64;
        do
        {
          v14 += __popcnt(*(_QWORD *)&v8[8 * v16])
               + __popcnt(*(_QWORD *)&v8[8 * v15 - 24])
               + __popcnt(*(_QWORD *)&v8[8 * v15 - 16])
               + __popcnt(*(_QWORD *)&v8[8 * v15 - 8]);
          v16 = v15;
          v15 += 4;
        }
        while ( v11 > v16 );
        v17 = 4;
        v18 = 0i64;
        do
        {
          v14 += __popcnt(*(_QWORD *)&v8[8 * v18])
               + __popcnt(*(_QWORD *)&v8[8 * v17 - 24])
               + __popcnt(*(_QWORD *)&v8[8 * v17 - 16])
               + __popcnt(*(_QWORD *)&v8[8 * v17 - 8]);
          v18 = v17;
          v17 += 4;
        }
        while ( v11 > v18 );
      }
      v12 += 2;
    }
    while ( v12 != 10000 );
    _RBP = 100 * (Xtime_get_ticks_0() - v13);
    std::operator___std::char_traits_char___(std::cout, "unsigned\t");
    v23 = (std::ostream *)std::ostream::operator<<(std::cout, v14);
    std::operator___std::char_traits_char____0(v23, v24);
    __asm
    {
      vmovq   xmm0, rbp
      vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
      vpunpckldq xmm0, xmm0, xmm8
      vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
      vsubpd  xmm0, xmm0, xmm7
      vpermilpd xmm1, xmm0, 1
      vaddsd  xmm6, xmm1, xmm0
      vdivsd  xmm1, xmm6, cs:__real@41cdcd6500000000
    }
    v33 = (std::ostream *)std::ostream::operator<<(v23);
    std::operator___std::char_traits_char___(v33, " sec \t");
    __asm
    {
      vmovq   xmm0, r15
      vpunpckldq xmm0, xmm0, xmm8
      vsubpd  xmm0, xmm0, xmm7
      vpermilpd xmm1, xmm0, 1
      vaddsd  xmm0, xmm1, xmm0
      vmulsd  xmm7, xmm0, cs:__real@40c3880000000000
      vdivsd  xmm1, xmm7, xmm6
    }
    v41 = (std::ostream *)std::ostream::operator<<(v33);
    std::operator___std::char_traits_char___(v41, " GB/s");
    LOBYTE(v42) = 10;
    v43 = std::ios::widen((char *)v41 + *(int *)(*(_QWORD *)v41 + 4i64), v42);
    std::ostream::put(v41, v43);
    std::ostream::flush(v41);
    v44 = 0;
    v45 = Xtime_get_ticks_0();
    v46 = 0i64;
    do
    {
      if ( v6 )
      {
        v47 = 0i64;
        do
        {
          v46 += __popcnt(*(_QWORD *)&v8[8 * v47])
               + __popcnt(*(_QWORD *)&v8[8 * v47 + 8])
               + __popcnt(*(_QWORD *)&v8[8 * v47 + 16])
               + __popcnt(*(_QWORD *)&v8[8 * v47 + 24]);
          v47 += 4i64;
        }
        while ( v47 < v11 );
        v48 = 0i64;
        do
        {
          v46 += __popcnt(*(_QWORD *)&v8[8 * v48])
               + __popcnt(*(_QWORD *)&v8[8 * v48 + 8])
               + __popcnt(*(_QWORD *)&v8[8 * v48 + 16])
               + __popcnt(*(_QWORD *)&v8[8 * v48 + 24]);
          v48 += 4i64;
        }
        while ( v48 < v11 );
      }
      v44 += 2;
    }
    while ( v44 != 10000 );
    _RBP = 100 * (Xtime_get_ticks_0() - v45);
    std::operator___std::char_traits_char___(std::cout, "uint64_t\t");
    v50 = (std::ostream *)std::ostream::operator<<(std::cout, v46);
    std::operator___std::char_traits_char____0(v50, v51);
    __asm
    {
      vmovq   xmm0, rbp
      vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
      vsubpd  xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
      vpermilpd xmm1, xmm0, 1
      vaddsd  xmm6, xmm1, xmm0
      vdivsd  xmm1, xmm6, cs:__real@41cdcd6500000000
    }
    v58 = (std::ostream *)std::ostream::operator<<(v50);
    std::operator___std::char_traits_char___(v58, " sec \t");
    __asm { vdivsd  xmm1, xmm7, xmm6 }
    v60 = (std::ostream *)std::ostream::operator<<(v58);
    std::operator___std::char_traits_char___(v60, " GB/s");
    LOBYTE(v61) = 10;
    v62 = std::ios::widen((char *)v60 + *(int *)(*(_QWORD *)v60 + 4i64), v61);
    std::ostream::put(v60, v62);
    std::ostream::flush(v60);
    free(v8);
    result = 0;
  }
  else
  {
    std::operator___std::char_traits_char___(std::cerr, "usage: array_size in MB");
    LOBYTE(v19) = 10;
    v20 = std::ios::widen((char *)&std::cerr + *((int *)std::cerr + 1), v19);
    std::ostream::put(std::cerr, v20);
    std::ostream::flush(std::cerr);
    result = -1;
  }
  __asm
  {
    vmovaps xmm6, [rsp+98h+var_78]
    vmovaps xmm7, [rsp+98h+var_68]
    vmovaps xmm8, [rsp+98h+var_58]
  }
  return result;
}

and disassembly of main:

.text:0140001000    .686p
.text:0140001000    .mmx
.text:0140001000    .model flat
.text:0140001000
.text:0140001000 ; ===========================================================================
.text:0140001000
.text:0140001000 ; Segment type: Pure code
.text:0140001000 ; Segment permissions: Read/Execute
.text:0140001000 _text           segment para public 'CODE' use64
.text:0140001000    assume cs:_text
.text:0140001000    ;org 140001000h
.text:0140001000    assume es:nothing, ss:nothing, ds:_data, fs:nothing, gs:nothing
.text:0140001000
.text:0140001000 ; =============== S U B R O U T I N E =======================================
.text:0140001000
.text:0140001000
.text:0140001000 ; int __cdecl main(int argc, const char **argv, const char **envp)
.text:0140001000 main            proc near      ; CODE XREF: __scrt_common_main_seh+107?p
.text:0140001000      ; DATA XREF: .pdata:ExceptionDir?o
.text:0140001000
.text:0140001000 var_78          = xmmword ptr -78h
.text:0140001000 var_68          = xmmword ptr -68h
.text:0140001000 var_58          = xmmword ptr -58h
.text:0140001000
.text:0140001000    push    r15
.text:0140001002    push    r14
.text:0140001004    push    r13
.text:0140001006    push    r12
.text:0140001008    push    rsi
.text:0140001009    push    rdi
.text:014000100A    push    rbp
.text:014000100B    push    rbx
.text:014000100C    sub     rsp, 58h
.text:0140001010    vmovdqa [rsp+98h+var_58], xmm8
.text:0140001016    vmovapd [rsp+98h+var_68], xmm7
.text:014000101C    vmovapd [rsp+98h+var_78], xmm6
.text:0140001022    cmp     ecx, 2
.text:0140001025    jnz     loc_14000113E
.text:014000102B    mov     rcx, [rdx+8]    ; String
.text:014000102F    call    cs:__imp_atol
.text:0140001035    mov     r13d, eax
.text:0140001038    shl     r13d, 14h
.text:014000103C    movsxd  r15, r13d
.text:014000103F    mov     rcx, r15        ; size
.text:0140001042    call    ??_U@YAPEAX_K@Z ; operator new[](unsigned __int64)
.text:0140001047    mov     rsi, rax
.text:014000104A    test    r15d, r15d
.text:014000104D    jz      short loc_14000106E
.text:014000104F    mov     edi, 1
.text:0140001054    xor     ebx, ebx
.text:0140001056    mov     rbp, cs:__imp_rand
.text:014000105D    nop     dword ptr [rax]
.text:0140001060
.text:0140001060 loc_140001060:    ; CODE XREF: main+6C?j
.text:0140001060    call    rbp ; __imp_rand
.text:0140001062    mov     [rsi+rbx], al
.text:0140001065    mov     ebx, edi
.text:0140001067    inc     edi
.text:0140001069    cmp     rbx, r15
.text:014000106C    jb      short loc_140001060
.text:014000106E
.text:014000106E loc_14000106E:    ; CODE XREF: main+4D?j
.text:014000106E    mov     rdi, r15
.text:0140001071    shr     rdi, 3
.text:0140001075    xor     ebp, ebp
.text:0140001077    call    _Xtime_get_ticks_0
.text:014000107C    mov     r14, rax
.text:014000107F    xor     ebx, ebx
.text:0140001081    jmp     short loc_14000109F
.text:0140001081 ; ---------------------------------------------------------------------------
.text:0140001083    align 10h
.text:0140001090
.text:0140001090 loc_140001090:    ; CODE XREF: main+A2?j
.text:0140001090      ; main+EC?j ...
.text:0140001090    add     ebp, 2
.text:0140001093    cmp     ebp, 2710h
.text:0140001099    jz      loc_140001184
.text:014000109F
.text:014000109F loc_14000109F:    ; CODE XREF: main+81?j
.text:014000109F    test    r13d, r13d
.text:01400010A2    jz      short loc_140001090
.text:01400010A4    mov     eax, 4
.text:01400010A9    xor     ecx, ecx
.text:01400010AB    nop     dword ptr [rax+rax+00h]
.text:01400010B0
.text:01400010B0 loc_1400010B0:    ; CODE XREF: main+E7?j
.text:01400010B0    popcnt  rcx, qword ptr [rsi+rcx*8]
.text:01400010B6    add     rcx, rbx
.text:01400010B9    lea     edx, [rax-3]
.text:01400010BC    popcnt  rdx, qword ptr [rsi+rdx*8]
.text:01400010C2    add     rdx, rcx
.text:01400010C5    lea     ecx, [rax-2]
.text:01400010C8    popcnt  rcx, qword ptr [rsi+rcx*8]
.text:01400010CE    add     rcx, rdx
.text:01400010D1    lea     edx, [rax-1]
.text:01400010D4    xor     ebx, ebx
.text:01400010D6    popcnt  rbx, qword ptr [rsi+rdx*8]
.text:01400010DC    add     rbx, rcx
.text:01400010DF    mov     ecx, eax
.text:01400010E1    add     eax, 4
.text:01400010E4    cmp     rdi, rcx
.text:01400010E7    ja      short loc_1400010B0
.text:01400010E9    test    r13d, r13d
.text:01400010EC    jz      short loc_140001090
.text:01400010EE    mov     eax, 4
.text:01400010F3    xor     ecx, ecx
.text:01400010F5    db      2Eh
.text:01400010F5    nop     word ptr [rax+rax+00000000h]
.text:01400010FF    nop
.text:0140001100
.text:0140001100 loc_140001100:    ; CODE XREF: main+137?j
.text:0140001100    popcnt  rcx, qword ptr [rsi+rcx*8]
.text:0140001106    add     rcx, rbx
.text:0140001109    lea     edx, [rax-3]
.text:014000110C    popcnt  rdx, qword ptr [rsi+rdx*8]
.text:0140001112    add     rdx, rcx
.text:0140001115    lea     ecx, [rax-2]
.text:0140001118    popcnt  rcx, qword ptr [rsi+rcx*8]
.text:014000111E    add     rcx, rdx
.text:0140001121    lea     edx, [rax-1]
.text:0140001124    xor     ebx, ebx
.text:0140001126    popcnt  rbx, qword ptr [rsi+rdx*8]
.text:014000112C    add     rbx, rcx
.text:014000112F    mov     ecx, eax
.text:0140001131    add     eax, 4
.text:0140001134    cmp     rdi, rcx
.text:0140001137    ja      short loc_140001100
.text:0140001139    jmp     loc_140001090
.text:014000113E ; ---------------------------------------------------------------------------
.text:014000113E
.text:014000113E loc_14000113E:    ; CODE XREF: main+25?j
.text:014000113E    mov     rsi, cs:__imp_?cerr@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cerr
.text:0140001145    lea     rdx, aUsageArraySize ; "usage: array_size in MB"
.text:014000114C    mov     rcx, rsi        ; std::ostream *
.text:014000114F    call    std__operator___std__char_traits_char___
.text:0140001154    mov     rax, [rsi]
.text:0140001157    movsxd  rcx, dword ptr [rax+4]
.text:014000115B    add     rcx, rsi
.text:014000115E    mov     dl, 0Ah
.text:0140001160    call    cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:0140001166    mov     rcx, rsi
.text:0140001169    mov     edx, eax
.text:014000116B    call    cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001171    mov     rcx, rsi
.text:0140001174    call    cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000117A    mov     eax, 0FFFFFFFFh
.text:014000117F    jmp     loc_1400013E2
.text:0140001184 ; ---------------------------------------------------------------------------
.text:0140001184
.text:0140001184 loc_140001184:    ; CODE XREF: main+99?j
.text:0140001184    call    _Xtime_get_ticks_0
.text:0140001189    sub     rax, r14
.text:014000118C    imul    rbp, rax, 64h ; 'd'
.text:0140001190    mov     r14, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001197    lea     rdx, aUnsigned  ; "unsigned\t"
.text:014000119E    mov     rcx, r14        ; std::ostream *
.text:01400011A1    call    std__operator___std__char_traits_char___
.text:01400011A6    mov     rcx, r14
.text:01400011A9    mov     rdx, rbx
.text:01400011AC    call    cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:01400011B2    mov     rbx, rax
.text:01400011B5    mov     rcx, rax        ; std::ostream *
.text:01400011B8    call    std__operator___std__char_traits_char____0
.text:01400011BD    vmovq   xmm0, rbp
.text:01400011C2    vmovdqa xmm8, cs:__xmm@00000000000000004530000043300000
.text:01400011CA    vpunpckldq xmm0, xmm0, xmm8
.text:01400011CF    vmovapd xmm7, cs:__xmm@45300000000000004330000000000000
.text:01400011D7    vsubpd  xmm0, xmm0, xmm7
.text:01400011DB    vpermilpd xmm1, xmm0, 1
.text:01400011E1    vaddsd  xmm6, xmm1, xmm0
.text:01400011E5    vdivsd  xmm1, xmm6, cs:__real@41cdcd6500000000
.text:01400011ED    mov     r12, cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@N@Z ; std::ostream::operator<<(double)
.text:01400011F4    mov     rcx, rbx
.text:01400011F7    call    r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:01400011FA    mov     rbx, rax
.text:01400011FD    lea     rdx, aSec       ; " sec \t"
.text:0140001204    mov     rcx, rax        ; std::ostream *
.text:0140001207    call    std__operator___std__char_traits_char___
.text:014000120C    vmovq   xmm0, r15
.text:0140001211    vpunpckldq xmm0, xmm0, xmm8
.text:0140001216    vsubpd  xmm0, xmm0, xmm7
.text:014000121A    vpermilpd xmm1, xmm0, 1
.text:0140001220    vaddsd  xmm0, xmm1, xmm0
.text:0140001224    vmulsd  xmm7, xmm0, cs:__real@40c3880000000000
.text:014000122C    vdivsd  xmm1, xmm7, xmm6
.text:0140001230    mov     rcx, rbx
.text:0140001233    call    r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001236    mov     rbx, rax
.text:0140001239    lea     rdx, aGbS       ; " GB/s"
.text:0140001240    mov     rcx, rax        ; std::ostream *
.text:0140001243    call    std__operator___std__char_traits_char___
.text:0140001248    mov     rax, [rbx]
.text:014000124B    movsxd  rcx, dword ptr [rax+4]
.text:014000124F    add     rcx, rbx
.text:0140001252    mov     dl, 0Ah
.text:0140001254    call    cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:014000125A    mov     rcx, rbx
.text:014000125D    mov     edx, eax
.text:014000125F    call    cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:0140001265    mov     rcx, rbx
.text:0140001268    call    cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:014000126E    xor     ebp, ebp
.text:0140001270    call    _Xtime_get_ticks_0
.text:0140001275    mov     r14, rax
.text:0140001278    xor     ebx, ebx
.text:014000127A    jmp     short loc_14000128F
.text:014000127A ; ---------------------------------------------------------------------------
.text:014000127C    align 20h
.text:0140001280
.text:0140001280 loc_140001280:    ; CODE XREF: main+292?j
.text:0140001280      ; main+2DB?j ...
.text:0140001280    add     ebp, 2
.text:0140001283    cmp     ebp, 2710h
.text:0140001289    jz      loc_14000131D
.text:014000128F
.text:014000128F loc_14000128F:    ; CODE XREF: main+27A?j
.text:014000128F    test    r13d, r13d
.text:0140001292    jz      short loc_140001280
.text:0140001294    xor     eax, eax
.text:0140001296    db      2Eh
.text:0140001296    nop     word ptr [rax+rax+00000000h]
.text:01400012A0
.text:01400012A0 loc_1400012A0:    ; CODE XREF: main+2D6?j
.text:01400012A0    xor     ecx, ecx
.text:01400012A2    popcnt  rcx, qword ptr [rsi+rax*8]
.text:01400012A8    add     rcx, rbx
.text:01400012AB    xor     edx, edx
.text:01400012AD    popcnt  rdx, qword ptr [rsi+rax*8+8]
.text:01400012B4    add     rdx, rcx
.text:01400012B7    xor     ecx, ecx
.text:01400012B9    popcnt  rcx, qword ptr [rsi+rax*8+10h]
.text:01400012C0    add     rcx, rdx
.text:01400012C3    xor     ebx, ebx
.text:01400012C5    popcnt  rbx, qword ptr [rsi+rax*8+18h]
.text:01400012CC    add     rbx, rcx
.text:01400012CF    add     rax, 4
.text:01400012D3    cmp     rax, rdi
.text:01400012D6    jb      short loc_1400012A0
.text:01400012D8    test    r13d, r13d
.text:01400012DB    jz      short loc_140001280
.text:01400012DD    xor     eax, eax
.text:01400012DF    nop
.text:01400012E0
.text:01400012E0 loc_1400012E0:    ; CODE XREF: main+316?j
.text:01400012E0    xor     ecx, ecx
.text:01400012E2    popcnt  rcx, qword ptr [rsi+rax*8]
.text:01400012E8    add     rcx, rbx
.text:01400012EB    xor     edx, edx
.text:01400012ED    popcnt  rdx, qword ptr [rsi+rax*8+8]
.text:01400012F4    add     rdx, rcx
.text:01400012F7    xor     ecx, ecx
.text:01400012F9    popcnt  rcx, qword ptr [rsi+rax*8+10h]
.text:0140001300    add     rcx, rdx
.text:0140001303    xor     ebx, ebx
.text:0140001305    popcnt  rbx, qword ptr [rsi+rax*8+18h]
.text:014000130C    add     rbx, rcx
.text:014000130F    add     rax, 4
.text:0140001313    cmp     rax, rdi
.text:0140001316    jb      short loc_1400012E0
.text:0140001318    jmp     loc_140001280
.text:014000131D ; ---------------------------------------------------------------------------
.text:014000131D
.text:014000131D loc_14000131D:    ; CODE XREF: main+289?j
.text:014000131D    call    _Xtime_get_ticks_0
.text:0140001322    sub     rax, r14
.text:0140001325    imul    rbp, rax, 64h ; 'd'
.text:0140001329    mov     rdi, cs:__imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A ; std::ostream std::cout
.text:0140001330    lea     rdx, aUint64T   ; "uint64_t\t"
.text:0140001337    mov     rcx, rdi        ; std::ostream *
.text:014000133A    call    std__operator___std__char_traits_char___
.text:014000133F    mov     rcx, rdi
.text:0140001342    mov     rdx, rbx
.text:0140001345    call    cs:__imp_??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV01@_K@Z ; std::ostream::operator<<(unsigned __int64)
.text:014000134B    mov     rdi, rax
.text:014000134E    mov     rcx, rax        ; std::ostream *
.text:0140001351    call    std__operator___std__char_traits_char____0
.text:0140001356    vmovq   xmm0, rbp
.text:014000135B    vpunpckldq xmm0, xmm0, cs:__xmm@00000000000000004530000043300000
.text:0140001363    vsubpd  xmm0, xmm0, cs:__xmm@45300000000000004330000000000000
.text:014000136B    vpermilpd xmm1, xmm0, 1
.text:0140001371    vaddsd  xmm6, xmm1, xmm0
.text:0140001375    vdivsd  xmm1, xmm6, cs:__real@41cdcd6500000000
.text:014000137D    mov     rcx, rdi
.text:0140001380    call    r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:0140001383    mov     rdi, rax
.text:0140001386    lea     rdx, aSec       ; " sec \t"
.text:014000138D    mov     rcx, rax        ; std::ostream *
.text:0140001390    call    std__operator___std__char_traits_char___
.text:0140001395    vdivsd  xmm1, xmm7, xmm6
.text:0140001399    mov     rcx, rdi
.text:014000139C    call    r12 ; std::ostream::operator<<(double) ; std::ostream::operator<<(double)
.text:014000139F    mov     rdi, rax
.text:01400013A2    lea     rdx, aGbS       ; " GB/s"
.text:01400013A9    mov     rcx, rax        ; std::ostream *
.text:01400013AC    call    std__operator___std__char_traits_char___
.text:01400013B1    mov     rax, [rdi]
.text:01400013B4    movsxd  rcx, dword ptr [rax+4]
.text:01400013B8    add     rcx, rdi
.text:01400013BB    mov     dl, 0Ah
.text:01400013BD    call    cs:__imp_?widen@?$basic_ios@DU?$char_traits@D@std@@@std@@QEBADD@Z ; std::ios::widen(char)
.text:01400013C3    mov     rcx, rdi
.text:01400013C6    mov     edx, eax
.text:01400013C8    call    cs:__imp_?put@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@D@Z ; std::ostream::put(char)
.text:01400013CE    mov     rcx, rdi
.text:01400013D1    call    cs:__imp_?flush@?$basic_ostream@DU?$char_traits@D@std@@@std@@QEAAAEAV12@XZ ; std::ostream::flush(void)
.text:01400013D7    mov     rcx, rsi        ; Block
.text:01400013DA    call    cs:__imp_free
.text:01400013E0    xor     eax, eax
.text:01400013E2
.text:01400013E2 loc_1400013E2:    ; CODE XREF: main+17F?j
.text:01400013E2    vmovaps xmm6, [rsp+98h+var_78]
.text:01400013E8    vmovaps xmm7, [rsp+98h+var_68]
.text:01400013EE    vmovaps xmm8, [rsp+98h+var_58]
.text:01400013F4    add     rsp, 58h
.text:01400013F8    pop     rbx
.text:01400013F9    pop     rbp
.text:01400013FA    pop     rdi
.text:01400013FB    pop     rsi
.text:01400013FC    pop     r12
.text:01400013FE    pop     r13
.text:0140001400    pop     r14
.text:0140001402    pop     r15
.text:0140001404    retn
.text:0140001404 main            endp

Coffee lake specification update "POPCNT instruction may take longer to execute than expected".

Can I use Class.newInstance() with constructor arguments?

Do not use Class.newInstance(); see this thread: Why is Class.newInstance() evil?

Like other answers say, use Constructor.newInstance() instead.

auto create database in Entity Framework Core

If you get the context via the parameter list of Configure in Startup.cs, You can instead do this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  LoggerFactory loggerFactory,
    ApplicationDbContext context)
 {
      context.Database.Migrate();
      ...

Can I use VARCHAR as the PRIMARY KEY?

Of course you can, in the sense that your RDBMS will let you do it. The answer to a question of whether or not you should do it is different, though: in most situations, values that have a meaning outside your database system should not be chosen to be a primary key.

If you know that the value is unique in the system that you are modeling, it is appropriate to add a unique index or a unique constraint to your table. However, your primary key should generally be some "meaningless" value, such as an auto-incremented number or a GUID.

The rationale for this is simple: data entry errors and infrequent changes to things that appear non-changeable do happen. They become much harder to fix on values which are used as primary keys.

DLL Load Library - Error Code 126

This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.

Error in plot.new() : figure margins too large, Scatter plot

Every time you are creating plots you might get this error - "Error in plot.new() : figure margins too large". To avoid such errors you can first check par("mar") output. You should be getting:

[1] 5.1 4.1 4.1 2.1

To change that write:

par(mar=c(1,1,1,1))

This should rectify the error. Or else you can change the values accordingly.

Hope this works for you.

How to send email from MySQL 5.1

I agree with Jim Blizard. The database is not the part of your technology stack that should send emails. For example, what if you send an email but then roll back the change that triggered that email? You can't take the email back.

It's better to send the email in your application code layer, after your app has confirmed that the SQL change was made successfully and committed.

How to add DOM element script to head section?

Best solution I've found:

AppendToHead('script', 'alert("hii"); ');
//or
AppendToHead('script', 'http://example.com/script.js');
//or
AppendToHead('style',  '#myDiv{color:red;} ');
//or
AppendToHead('style',  'http://example.com/style.css');



function AppendToHead(elemntType, content){
    // detect whether provided content is "link" (instead of inline codes)
    var Is_Link = content.split(/\r\n|\r|\n/).length <= 1  &&  content.indexOf("//") > -1 && content.indexOf(" ")<=-1;
    if(Is_Link){
        if (elemntType=='script')    { var x=document.createElement('script');x.id=id;  x.src=content;  x.type='text/javascript'; }
        else if (elemntType=='style'){ var x=document.createElement('link');  x.id=id;  x.href=content; x.type='text/css';  x.rel = 'stylesheet'; }
    }
    else{
        var x = document.createElement(elemntType);
        if (elemntType=='script')    { x.type='text/javascript';    x.innerHTML = content;  }
        else if (elemntType=='style'){ x.type='text/css';    if (x.styleSheet){ x.styleSheet.cssText=content; } else { x.appendChild(document.createTextNode(content)); }   }
    }
    //append in head
    (document.head || document.getElementsByTagName('head')[0]).appendChild(x);
}

How to import a jar in Eclipse

Adding external Jar is not smart in case you want to change the project location in filesystem.

The best way is to add the jar to build path so your project will compile if exported:

  1. Create a folder called lib in your project folder.

  2. copy to this folder all the jar files you need.

  3. Refresh your project in eclipse.

  4. Select all the jar files, then right click on one of them and select Build Path -> Add to Build Path

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

Show datalist labels but submit the actual value

Using PHP i've found a quite simple way to do this. Guys, Just Use something like this

<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
            <datalist id="customers">
                <?php 
    $querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
    $resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());

                while ($row_this = mysqli_fetch_array($resultSnamex)) {
                    echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
                    <input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
                }

                 ?>
            </datalist>

The Code Above lets the form carry the id of the option also selected.

XSL substring and indexOf

The following is the complete example containing both XML and XSLT where substring-before and substring-after are used

<?xml version="1.0" encoding="UTF-8"?>
<persons name="Group_SOEM">
    <person>
        <first>Joe Smith</first>
        <last>Joe Smith</last>
        <address>123 Main St, Anycity</address>
    </person>
</persons>    

The following is XSLT which changes value of first/last name by separating the value by space so that after applying this XSL the first name element will have value "Joe" and last "Smith".

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="first">
    <first>
        <xsl:value-of select="substring-before(.,' ')" />
    </first>
</xsl:template> 
<xsl:template match="last">
    <last>
        <xsl:value-of select="substring-after(.,' ')" />
    </last>
</xsl:template> 
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>   

Is there a "goto" statement in bash?

No, there is not; see §3.2.4 "Compound Commands" in the Bash Reference Manual for information about the control structures that do exist. In particular, note the mention of break and continue, which aren't as flexible as goto, but are more flexible in Bash than in some languages, and may help you achieve what you want. (Whatever it is that you want . . .)

How to declare and add items to an array in Python?

I believe you are all wrong. you need to do:

array = array[] in order to define it, and then:

array.append ["hello"] to add to it.

React : difference between <Route exact path="/" /> and <Route path="/" />

In short, if you have multiple routes defined for your app's routing, enclosed with Switch component like this;

<Switch>

  <Route exact path="/" component={Home} />
  <Route path="/detail" component={Detail} />

  <Route exact path="/functions" component={Functions} />
  <Route path="/functions/:functionName" component={FunctionDetails} />

</Switch>

Then you have to put exact keyword to the Route which it's path is also included by another Route's path. For example home path / is included in all paths so it needs to have exact keyword to differentiate it from other paths which start with /. The reason is also similar to /functions path. If you want to use another route path like /functions-detail or /functions/open-door which includes /functions in it then you need to use exact for the /functions route.

linux shell script: split string, put them in an array then loop through them

If you don't wish to mess with IFS (perhaps for the code within the loop) this might help.

If know that your string will not have whitespace, you can substitute the ';' with a space and use the for/in construct:

#local str
for str in ${STR//;/ } ; do 
   echo "+ \"$str\""
done

But if you might have whitespace, then for this approach you will need to use a temp variable to hold the "rest" like this:

#local str rest
rest=$STR
while [ -n "$rest" ] ; do
   str=${rest%%;*}  # Everything up to the first ';'
   # Trim up to the first ';' -- and handle final case, too.
   [ "$rest" = "${rest/;/}" ] && rest= || rest=${rest#*;}
   echo "+ \"$str\""
done

How to get records randomly from the oracle database?

SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;

This is more efficient as it doesn't need to sort the Table.

declaring a priority_queue in c++ with a custom comparator

You have to define the compare first. There are 3 ways to do that:

  1. use class
  2. use struct (which is same as class)
  3. use lambda function.

It's easy to use class/struct because easy to declare just write this line of code above your executing code

struct compare{
  public:
  bool operator()(Node& a,Node& b) // overloading both operators 
  {
      return a.w < b.w: // if you want increasing order;(i.e increasing for minPQ)
      return a.w > b.w // if you want reverse of default order;(i.e decreasing for minPQ)
   }
};

Calling code:

priority_queue<Node,vector<Node>,compare> pq;

Inline comments for Bash?

Most commands allow args to come in any order. Just move the commented flags to the end of the line:

ls -l -a /etc # -F is turned off

Then to turn it back on, just uncomment and remove the text:

ls -l -a /etc -F

What's the difference between commit() and apply() in SharedPreferences

From javadoc:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself

Cannot uninstall angular-cli

I had the same problem. This doesn't work:

npm uninstall -g angular/cli
npm cache clean

instead use:

npm uninstall -g @ angular/cli

set date in input type date

For me the shortest way to get locale date and in correct format for input type="date" is this :

var d = new Date(); 
var today = d.getFullYear()+"-"+("0"+(d.getMonth()+1)).slice(-2)+"-"+("0"+d.getDate()).slice(-2);

Or this :

var d = new Date().toLocaleDateString().split('/');
var today = d[2]+"-"+("0"+d[0]).slice(-2)+"-"+("0"+d[1]).slice(-2);

Then just set the date input value :

$('#datePicker').val(today);

SQL WHERE ID IN (id1, id2, ..., idn)

Option 1 is the only good solution.

Why?

  • Option 2 does the same but you repeat the column name lots of times; additionally the SQL engine doesn't immediately know that you want to check if the value is one of the values in a fixed list. However, a good SQL engine could optimize it to have equal performance like with IN. There's still the readability issue though...

  • Option 3 is simply horrible performance-wise. It sends a query every loop and hammers the database with small queries. It also prevents it from using any optimizations for "value is one of those in a given list"

How can I change the text inside my <span> with jQuery?

This will be used to change the Html content inside the span

 $('#abc span').html('goes inside the span');

if you want to change the text inside the span, you can use:

 $('#abc span').text('goes inside the span');

Position last flex item at the end of container

This flexbox principle also works horizontally

During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Setting an automatic left margin for the Last Item will do the work.

.last-item {
  margin-left: auto;
}

Code Example:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 400px;_x000D_
  outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  margin: 5px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p class="last-item"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen Snippet

This can be very useful for Desktop Footers.

As Envato did here with the company logo.

Codepen Snippet

Substring in excel

kennytm's links are dead and he doesn't provide an example so here's how you do substrings:

=MID(text, start_num, char_num)

Let's say cell A1 is Hello.

=MID(A1, 2, 3) 

Would return

ell

Because it says to start at character 2, e, and to return 3 characters.

How can I get my Android device country code without using GPS?

Here is a complete example. It tries to get the country code from TelephonyManager (from SIM or CDMA devices), and if not available, tries to get it from the local configuration.

private static String getDeviceCountryCode(Context context) {
    String countryCode;

    // Try to get country code from TelephonyManager service
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if(tm != null) {
        // Query first getSimCountryIso()
        countryCode = tm.getSimCountryIso();
        if (countryCode != null && countryCode.length() == 2)
            return countryCode.toLowerCase();

        if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_CDMA) {
            // Special case for CDMA Devices
            countryCode = getCDMACountryIso();
        }
        else {
            // For 3G devices (with SIM) query getNetworkCountryIso()
            countryCode = tm.getNetworkCountryIso();
        }

        if (countryCode != null && countryCode.length() == 2)
            return countryCode.toLowerCase();
    }

    // If network country not available (tablets maybe), get country code from Locale class
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        countryCode = context.getResources().getConfiguration().getLocales().get(0).getCountry();
    }
    else {
        countryCode = context.getResources().getConfiguration().locale.getCountry();
    }

    if (countryCode != null && countryCode.length() == 2)
        return  countryCode.toLowerCase();

    // General fallback to "us"
    return "us";
}

@SuppressLint("PrivateApi")
private static String getCDMACountryIso() {
    try {
        // Try to get country code from SystemProperties private class
        Class<?> systemProperties = Class.forName("android.os.SystemProperties");
        Method get = systemProperties.getMethod("get", String.class);

        // Get homeOperator that contain MCC + MNC
        String homeOperator = ((String) get.invoke(systemProperties,
                "ro.cdma.home.operator.numeric"));

        // First three characters (MCC) from homeOperator represents the country code
        int mcc = Integer.parseInt(homeOperator.substring(0, 3));

        // Mapping just countries that actually use CDMA networks
        switch (mcc) {
            case 330: return "PR";
            case 310: return "US";
            case 311: return "US";
            case 312: return "US";
            case 316: return "US";
            case 283: return "AM";
            case 460: return "CN";
            case 455: return "MO";
            case 414: return "MM";
            case 619: return "SL";
            case 450: return "KR";
            case 634: return "SD";
            case 434: return "UZ";
            case 232: return "AT";
            case 204: return "NL";
            case 262: return "DE";
            case 247: return "LV";
            case 255: return "UA";
        }
    }
    catch (ClassNotFoundException ignored) {
    }
    catch (NoSuchMethodException ignored) {
    }
    catch (IllegalAccessException ignored) {
    }
    catch (InvocationTargetException ignored) {
    }
    catch (NullPointerException ignored) {
    }

    return null;
}

Also another idea is to try an API request like in this answer.

References are here and here.

How do I convert from stringstream to string in C++?

std::stringstream::str() is the method you are looking for.

With std::stringstream:

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::stringstream ss;
    ss << NumericValue;
    return ss.str();
}

std::stringstream is a more generic tool. You can use the more specialized class std::ostringstream for this specific job.

template <class T>
std::string YourClass::NumericToString(const T & NumericValue)
{
    std::ostringstream oss;
    oss << NumericValue;
    return oss.str();
}

If you are working with std::wstring type of strings, you must prefer std::wstringstream or std::wostringstream instead.

template <class T>
std::wstring YourClass::NumericToString(const T & NumericValue)
{
    std::wostringstream woss;
    woss << NumericValue;
    return woss.str();
}

if you want the character type of your string could be run-time selectable, you should also make it a template variable.

template <class CharType, class NumType>
std::basic_string<CharType> YourClass::NumericToString(const NumType & NumericValue)
{
    std::basic_ostringstream<CharType> oss;
    oss << NumericValue;
    return oss.str();
}

For all the methods above, you must include the following two header files.

#include <string>
#include <sstream>

Note that, the argument NumericValue in the examples above can also be passed as std::string or std::wstring to be used with the std::ostringstream and std::wostringstream instances respectively. It is not necessary for the NumericValue to be a numeric value.

Read XML file using javascript

The code below will convert any XMLObject or string to a native JavaScript object. Then you can walk on the object to extract any value you want.

/**
 * Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
 * If a string is given, it first tries to create an XMLDomElement from the given string.
 * 
 * @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
 * @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
 * @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
 */
Object.fromXML = function( source, includeRoot ) {
    if( typeof source == 'string' )
    {
        try
        {
            if ( window.DOMParser )
                source = ( new DOMParser() ).parseFromString( source, "application/xml" );
            else if( window.ActiveXObject )
            {
                var xmlObject = new ActiveXObject( "Microsoft.XMLDOM" );
                xmlObject.async = false;
                xmlObject.loadXML( source );
                source = xmlObject;
                xmlObject = undefined;
            }
            else
                throw new Error( "Cannot find an XML parser!" );
        }
        catch( error )
        {
            return false;
        }
    }

    var result = {};

    if( source.nodeType == 9 )
        source = source.firstChild;
    if( !includeRoot )
        source = source.firstChild;

    while( source ) {
        if( source.childNodes.length ) {
            if( source.tagName in result ) {
                if( result[source.tagName].constructor != Array ) 
                    result[source.tagName] = [result[source.tagName]];
                result[source.tagName].push( Object.fromXML( source ) );
            }
            else 
                result[source.tagName] = Object.fromXML( source );
        } else if( source.tagName )
            result[source.tagName] = source.nodeValue;
        else if( !source.nextSibling ) {
            if( source.nodeValue.clean() != "" ) {
                result = source.nodeValue.clean();
            }
        }
        source = source.nextSibling;
    }
    return result;
};

String.prototype.clean = function() {
    var self = this;
    return this.replace(/(\r\n|\n|\r)/gm, "").replace(/^\s+|\s+$/g, "");
}

Simple C example of doing an HTTP POST and consuming the response

A message has a header part and a message body separated by a blank line. The blank line is ALWAYS needed even if there is no message body. The header starts with a command and has additional lines of key value pairs separated by a colon and a space. If there is a message body, it can be anything you want it to be.

Lines in the header and the blank line at the end of the header must end with a carraige return and linefeed pair (see HTTP header line break style) so that's why those lines have \r\n at the end.

A URL has the form of http://host:port/path?query_string

There are two main ways of submitting a request to a website:

  • GET: The query string is optional but, if specified, must be reasonably short. Because of this the header could just be the GET command and nothing else. A sample message could be:

    GET /path?query_string HTTP/1.0\r\n
    \r\n
    
  • POST: What would normally be in the query string is in the body of the message instead. Because of this the header needs to include the Content-Type: and Content-Length: attributes as well as the POST command. A sample message could be:

    POST /path HTTP/1.0\r\n
    Content-Type: text/plain\r\n
    Content-Length: 12\r\n
    \r\n
    query_string
    

So, to answer your question: if the URL you are interested in POSTing to is http://api.somesite.com/apikey=ARG1&command=ARG2 then there is no body or query string and, consequently, no reason to POST because there is nothing to put in the body of the message and so nothing to put in the Content-Type: and Content-Length:

I guess you could POST if you really wanted to. In that case your message would look like:

POST /apikey=ARG1&command=ARG2 HTTP/1.0\r\n
\r\n

So to send the message the C program needs to:

  • create a socket
  • lookup the IP address
  • open the socket
  • send the request
  • wait for the response
  • close the socket

The send and receive calls won't necessarily send/receive ALL the data you give them - they will return the number of bytes actually sent/received. It is up to you to call them in a loop and send/receive the remainder of the message.

What I did not do in this sample is any sort of real error checking - when something fails I just exit the program. Let me know if it works for you:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    /* first what are we going to send and where are we going to send it? */
    int portno =        80;
    char *host =        "api.somesite.com";
    char *message_fmt = "POST /apikey=%s&command=%s HTTP/1.0\r\n\r\n";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total;
    char message[1024],response[4096];

    if (argc < 3) { puts("Parameters: <apikey> <command>"); exit(0); }

    /* fill in the parameters */
    sprintf(message,message_fmt,argv[1],argv[2]);
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    return 0;
}

Like the other answer pointed out, 4096 bytes is not a very big response. I picked that number at random assuming that the response to your request would be short. If it can be big you have two choices:

  • read the Content-Length: header from the response and then dynamically allocate enough memory to hold the whole response.
  • write the response to a file as the pieces arrive

Additional information to answer the question asked in the comments:

What if you want to POST data in the body of the message? Then you do need to include the Content-Type: and Content-Length: headers. The Content-Length: is the actual length of everything after the blank line that separates the header from the body.

Here is a sample that takes the following command line arguments:

  • host
  • port
  • command (GET or POST)
  • path (not including the query data)
  • query data (put into the query string for GET and into the body for POST)
  • list of headers (Content-Length: is automatic if using POST)

So, for the original question you would run:

a.out api.somesite.com 80 GET "/apikey=ARG1&command=ARG2"

And for the question asked in the comments you would run:

a.out api.somesite.com 80 POST / "name=ARG1&value=ARG2" "Content-Type: application/x-www-form-urlencoded"

Here is the code:

#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */

void error(const char *msg) { perror(msg); exit(0); }

int main(int argc,char *argv[])
{
    int i;

    /* first where are we going to send it? */
    int portno = atoi(argv[2])>0?atoi(argv[2]):80;
    char *host = strlen(argv[1])>0?argv[1]:"localhost";

    struct hostent *server;
    struct sockaddr_in serv_addr;
    int sockfd, bytes, sent, received, total, message_size;
    char *message, response[4096];

    if (argc < 5) { puts("Parameters: <host> <port> <method> <path> [<data> [<headers>]]"); exit(0); }

    /* How big is the message? */
    message_size=0;
    if(!strcmp(argv[3],"GET"))
    {
        message_size+=strlen("%s %s%s%s HTTP/1.0\r\n");        /* method         */
        message_size+=strlen(argv[3]);                         /* path           */
        message_size+=strlen(argv[4]);                         /* headers        */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* query string   */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        message_size+=strlen("\r\n");                          /* blank line     */
    }
    else
    {
        message_size+=strlen("%s %s HTTP/1.0\r\n");
        message_size+=strlen(argv[3]);                         /* method         */
        message_size+=strlen(argv[4]);                         /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            message_size+=strlen(argv[i])+strlen("\r\n");
        if(argc>5)
            message_size+=strlen("Content-Length: %d\r\n")+10; /* content length */
        message_size+=strlen("\r\n");                          /* blank line     */
        if(argc>5)
            message_size+=strlen(argv[5]);                     /* body           */
    }

    /* allocate space for the message */
    message=malloc(message_size);

    /* fill in the parameters */
    if(!strcmp(argv[3],"GET"))
    {
        if(argc>5)
            sprintf(message,"%s %s%s%s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/",                 /* path           */
                strlen(argv[5])>0?"?":"",                      /* ?              */
                strlen(argv[5])>0?argv[5]:"");                 /* query string   */
        else
            sprintf(message,"%s %s HTTP/1.0\r\n",
                strlen(argv[3])>0?argv[3]:"GET",               /* method         */
                strlen(argv[4])>0?argv[4]:"/");                /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        strcat(message,"\r\n");                                /* blank line     */
    }
    else
    {
        sprintf(message,"%s %s HTTP/1.0\r\n",
            strlen(argv[3])>0?argv[3]:"POST",                  /* method         */
            strlen(argv[4])>0?argv[4]:"/");                    /* path           */
        for(i=6;i<argc;i++)                                    /* headers        */
            {strcat(message,argv[i]);strcat(message,"\r\n");}
        if(argc>5)
            sprintf(message+strlen(message),"Content-Length: %d\r\n",strlen(argv[5]));
        strcat(message,"\r\n");                                /* blank line     */
        if(argc>5)
            strcat(message,argv[5]);                           /* body           */
    }

    /* What are we going to send? */
    printf("Request:\n%s\n",message);

    /* create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) error("ERROR opening socket");

    /* lookup the ip address */
    server = gethostbyname(host);
    if (server == NULL) error("ERROR, no such host");

    /* fill in the structure */
    memset(&serv_addr,0,sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);
    memcpy(&serv_addr.sin_addr.s_addr,server->h_addr,server->h_length);

    /* connect the socket */
    if (connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
        error("ERROR connecting");

    /* send the request */
    total = strlen(message);
    sent = 0;
    do {
        bytes = write(sockfd,message+sent,total-sent);
        if (bytes < 0)
            error("ERROR writing message to socket");
        if (bytes == 0)
            break;
        sent+=bytes;
    } while (sent < total);

    /* receive the response */
    memset(response,0,sizeof(response));
    total = sizeof(response)-1;
    received = 0;
    do {
        bytes = read(sockfd,response+received,total-received);
        if (bytes < 0)
            error("ERROR reading response from socket");
        if (bytes == 0)
            break;
        received+=bytes;
    } while (received < total);

    if (received == total)
        error("ERROR storing complete response from socket");

    /* close the socket */
    close(sockfd);

    /* process response */
    printf("Response:\n%s\n",response);

    free(message);
    return 0;
}

Correct way to select from two tables in SQL Server with no common field to join on

You can (should) use CROSS JOIN. Following query will be equivalent to yours:

SELECT 
   table1.columnA
 , table2.columnA
FROM table1 
CROSS JOIN table2
WHERE table1.columnA = 'Some value'

or you can even use INNER JOIN with some always true conditon:

FROM table1 
INNER JOIN table2 ON 1=1

How to overwrite files with Copy-Item in PowerShell

Robocopy is designed for reliable copying with many copy options, file selection restart, etc.

/xf to excludes files and /e for subdirectories:

robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"

How to log Apache CXF Soap Request and Soap Response using Log4j?

Procedure for global setting of client/server logging of SOAP/REST requests/ responses with log4j logger. This way you set up logging for the whole application without having to change the code, war, jar files, etc.

  1. install file cxf-rt-features-logging-X.Y.Z.jar to your CLASS_PATH

  2. create file (path for example: /opt/cxf/cxf-logging.xml):

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cxf="http://cxf.apache.org/core" xsi:schemaLocation="http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
    <cxf:bus>
     <cxf:features>
     <bean class="org.apache.cxf.ext.logging.LoggingFeature">
     <property name="prettyLogging" value="true"/>
     </bean>
     </cxf:features>
     </cxf:bus>
     </beans>
    
  3. set logging for org.apache.cxf (log4j 1.x) log4j.logger.org.apache.cxf=INFO,YOUR_APPENDER

  4. set these properties on java start-up

java ... -Dcxf.config.file.url=file:///opt/cxf/cxf-logging.xml -Dorg.apache.cxf.Logger=org.apache.cxf.common.logging.Log4jLogger -Dcom.sun.xml.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump=true -Dcom.sun.xml.ws.transport.http.HttpAdapter.dump=true -Dcom.sun.xml.internal.ws.transport.http.HttpAdapter.dump=true ...

I don't know why, but it is necessary to set variables as well com.sun.xml.*

How to install JSON.NET using NuGet?

I have Had the same issue and the only Solution i found was open Package manager> Select Microsoft and .Net as Package Source and You will install it..

enter image description here

Resizing image in Java

Resize image with high quality:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image = ImageIO.read(uploadedInputStream);
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);
            g2d.dispose();
            g2d.setComposite(AlphaComposite.Src);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;
        }
    }

React.js: Set innerHTML vs dangerouslySetInnerHTML

According to Dangerously Set innerHTML,

Improper use of the innerHTML can open you up to a cross-site scripting (XSS) attack. Sanitizing user input for display is notoriously error-prone, and failure to properly sanitize is one of the leading causes of web vulnerabilities on the internet.

Our design philosophy is that it should be "easy" to make things safe, and developers should explicitly state their intent when performing “unsafe” operations. The prop name dangerouslySetInnerHTML is intentionally chosen to be frightening, and the prop value (an object instead of a string) can be used to indicate sanitized data.

After fully understanding the security ramifications and properly sanitizing the data, create a new object containing only the key __html and your sanitized data as the value. Here is an example using the JSX syntax:

function createMarkup() {
    return {
       __html: 'First &middot; Second'    };
 }; 

<div dangerouslySetInnerHTML={createMarkup()} /> 

Read more about it using below link:

documentation: React DOM Elements - dangerouslySetInnerHTML.

How to find Control in TemplateField of GridView?

protected void gvTurnos_RowDataBound(object sender, GridViewRowEventArgs e)
{
    try
    {

        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
        {
            LinkButton btn = (LinkButton)e.Row.FindControl("btnAgregarVacio");
            if (btn != null)
            {
                btn.Visible = rbFiltroEstatusCampus.SelectedValue == "1" ? true : false;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

jQuery make global variable

Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable

jQuery(function(){
    //here it is a closure variable
    var a_href;
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

To make the variable global, one solution is to declare the variable in global scope

var a_href;
jQuery(function(){
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

another is to set the variable as a property of the window object

window.a_href = $(this).attr('href')

Why console printing undefined

You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError

Reading images in python

you can try to use cv2 like this

import cv2

image= cv2.imread('image page')

cv2.imshow('image', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

How to remove files from git staging area?

It is very simple:

  1. To check the current status of any file in the current dir, whether it is staged or not:

    git status

  2. Staging any files:

    git add . for all files in the current directory

    git add <filename> for specific file

  3. Unstaging the file:

    git restore --staged <filename>

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

Forking vs. Branching in GitHub

Here are the high-level differences:

Forking

Pros

  • Keeps branches separated by user
  • Reduces clutter in the primary repository
  • Your team process reflects the external contributor process

Cons

  • Makes it more difficult to see all of the branches that are active (or inactive, for that matter)
  • Collaborating on a branch is trickier (the fork owner needs to add the person as a collaborator)
  • You need to understand the concept of multiple remotes in Git
    • Requires additional mental bookkeeping
    • This will make the workflow more difficult for people who aren't super comfortable with Git

Branching

Pros

  • Keeps all of the work being done around a project in one place
  • All collaborators can push to the same branch to collaborate on it
  • There's only one Git remote to deal with

Cons

  • Branches that get abandoned can pile up more easily
  • Your team contribution process doesn't match the external contributor process
  • You need to add team members as contributors before they can branch

jQuery AJAX file upload PHP

Use pure js

_x000D_
_x000D_
async function saveFile() _x000D_
{_x000D_
    let formData = new FormData();           _x000D_
    formData.append("file", sortpicture.files[0]);_x000D_
    await fetch('/uploads', {method: "POST", body: formData});    _x000D_
    alert('works');_x000D_
}
_x000D_
<input id="sortpicture" type="file" name="sortpic" />_x000D_
<button id="upload" onclick="saveFile()">Upload</button>_x000D_
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
_x000D_
_x000D_
_x000D_

The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending

_x000D_
_x000D_
async function saveFile(inp) _x000D_
{_x000D_
    let user = { name:'john', age:34 };_x000D_
    let formData = new FormData();_x000D_
    let photo = inp.files[0];      _x000D_
         _x000D_
    formData.append("photo", photo);_x000D_
    formData.append("user", JSON.stringify(user));  _x000D_
    _x000D_
    try {_x000D_
       let r = await fetch('/upload/image', {method: "POST", body: formData}); _x000D_
       console.log('HTTP response code:',r.status); _x000D_
       alert('success');_x000D_
    } catch(e) {_x000D_
       console.log('Huston we have problem...:', e);_x000D_
    }_x000D_
    _x000D_
}
_x000D_
<input type="file" onchange="saveFile(this)" >_x000D_
<br><br>_x000D_
Before selecting the file Open chrome console > network tab to see the request details._x000D_
<br><br>_x000D_
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
_x000D_
_x000D_
_x000D_

How to initialize a private static const map in C++?

I often use this pattern and recommend you to use it as well:

class MyMap : public std::map<int, int>
{
public:
    MyMap()
    {
        //either
        insert(make_pair(1, 2));
        insert(make_pair(3, 4));
        insert(make_pair(5, 6));
        //or
        (*this)[1] = 2;
        (*this)[3] = 4;
        (*this)[5] = 6;
    }
} const static my_map;

Sure it is not very readable, but without other libs it is best we can do. Also there won't be any redundant operations like copying from one map to another like in your attempt.

This is even more useful inside of functions: Instead of:

void foo()
{
   static bool initComplete = false;
   static Map map;
   if (!initComplete)
   {
      initComplete = true;
      map= ...;
   }
}

Use the following:

void bar()
{
    struct MyMap : Map
    {
      MyMap()
      {
         ...
      }
    } static mymap;
}

Not only you don't need here to deal with boolean variable anymore, you won't have hidden global variable that is checked if initializer of static variable inside function was already called.

Convert char array to a int number in C

I personally don't like atoi function. I would suggest sscanf:

char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);

It's very standard, it's in the stdio.h library :)

And in my opinion, it allows you much more freedom than atoi, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.

EDIT I just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi, sscanf and strtol. Also, there is a nice more-detailed insight into sscanf (actually, the whole family of *scanf functions).

EDIT2 Looks like it's not just me personally disliking the atoi function. Here's a link to an answer explaining that the atoi function is deprecated and should not be used in newer code.

Checking for empty or null JToken in a JObject

Try something like this to convert JToken to JArray:

static public JArray convertToJArray(JToken obj)
{
    // if ((obj).Type == JTokenType.Null) --> You can check if it's null here

    if ((obj).Type == JTokenType.Array)
        return (JArray)(obj);
    else
        return new JArray(); // this will return an empty JArray
}

Open a Web Page in a Windows Batch FIle

When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com

Also you cannot have http:// in the url.

How to add custom Http Header for C# Web Service Client consuming Axis 1.4 Web service

I find this code and is resolve my problem.

http://arcware.net/setting-http-header-authorization-for-web-services/

protected override WebRequest GetWebRequest(Uri uri)
{
    // Assuming authValue is set from somewhere, such as the config file
    HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
    request.Headers.Add("Authorization", string.Format("Basic {0}", authValue));
    return request;
}

Java : Cannot format given Object as a Date

SimpleDateFormat.format(...) takes a Date as parameter and format Date to String. So you need have a look API carefully

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

It cant find the entry point for your program, in this case main(). Your linker settings are likely incorrect.

See this post here

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

In actionPerformed(ActionEvent e) you call encrypt(), which is declared to throw Exception. However, actionPerformed neither catches this Exception (with try/catch around the call to encrypt()) nor declares that it throws Exception itself.

Your encrypt method, however, does not truly throw Exception. It swallows all Exceptions without even as much as logging a complaint. (Bad practice and bad style!)

Also, your encrypt method does the following:

public static byte[] encrypt(String toEncrypt) throws Exception {
  try{
    ....
    return encrypted; // HERE YOU CORRECTLY RETURN A VALUE
  } catch(Exception e) {
  }
  // YOU DO NOT RETURN ANYTHING HERE
}

That is, if you do catch any Exception, you discard it silently and then fall off the bottom of your encrypt method without actually returning anything. This won't compile (as you see), because a method that is declared to return a value must either return a value or throw an Exception for every single possible code path.

How to format a JavaScript date

Plain JavaScript is the best pick for small onetimers.

On the other hand, if you need more date stuff, MomentJS is a great solution.

For example:

moment().format('YYYY-MM-DD HH:m:s');     // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours

How to drop a database with Mongoose?

There is no method for dropping a collection from mongoose, the best you can do is remove the content of one :

Model.remove({}, function(err) { 
   console.log('collection removed') 
});

But there is a way to access the mongodb native javascript driver, which can be used for this

mongoose.connection.collections['collectionName'].drop( function(err) {
    console.log('collection dropped');
});

Warning

Make a backup before trying this in case anything goes wrong!

Lumen: get URL parameter in a Blade view

Given your URL:

http://locahost:8000/example?a=10

The best way that I have found to get the value for 'a' and display it on the page is to use the following:

{{ request()->get('a') }}

However, if you want to use it within an if statement, you could use:

@if( request()->get('a') )
    <script>console.log('hello')</script>
@endif

Hope that helps someone! :)

How do you remove duplicates from a list whilst preserving order?

If you routinely use pandas, and aesthetics is preferred over performance, then consider the built-in function pandas.Series.drop_duplicates:

    import pandas as pd
    import numpy as np

    uniquifier = lambda alist: pd.Series(alist).drop_duplicates().tolist()

    # from the chosen answer 
    def f7(seq):
        seen = set()
        seen_add = seen.add
        return [ x for x in seq if not (x in seen or seen_add(x))]

    alist = np.random.randint(low=0, high=1000, size=10000).tolist()

    print uniquifier(alist) == f7(alist)  # True

Timing:

    In [104]: %timeit f7(alist)
    1000 loops, best of 3: 1.3 ms per loop
    In [110]: %timeit uniquifier(alist)
    100 loops, best of 3: 4.39 ms per loop

#1071 - Specified key was too long; max key length is 767 bytes

I did some search on this topic finally got some custom change

For MySQL workbench 6.3.7 Version Graphical inter phase is available

  1. Start Workbench and select the connection.
  2. Go to management or Instance and select Options File.
  3. If Workbench ask you permission to read configuration file and then allow it by pressing OK two times.
  4. At center place Administrator options file window comes.
  5. Go To InnoDB tab and check the innodb_large_prefix if it not checked in the General section.
  6. set innodb_default_row_format option value to DYNAMIC.

For Versions below 6.3.7 direct options are not available so need to go with command prompt

  1. Start CMD as administrator.
  2. Go To director where mysql server is install Most of cases its at "C:\Program Files\MySQL\MySQL Server 5.7\bin" so command is "cd \" "cd Program Files\MySQL\MySQL Server 5.7\bin".
  3. Now Run command mysql -u userName -p databasescheema Now it asked for password of respective user. Provide password and enter into mysql prompt.
  4. We have to set some global settings enter the below commands one by one set global innodb_large_prefix=on; set global innodb_file_format=barracuda; set global innodb_file_per_table=true;
  5. Now at the last we have to alter the ROW_FORMAT of required table by default its COMPACT we have to set it to DYNAMIC.
  6. use following command alter table table_name ROW_FORMAT=DYNAMIC;
  7. Done

How to get All input of POST in Laravel

Try this :

use Illuminate\Support\Facades\Request;
public function add_question(Request $request)
{
    return $request->all();
}

Display TIFF image in all web browser

Tiff images can be displayed directly onto IE and safari only.. no support of tiff images on chrome and firefox. you can encode the image and then display it on browser by decoding the encoded image to some other format. Hope this works for you

How to replace space with comma using sed?

On Linux use below to test (it would replace the whitespaces with comma)

 sed 's/\s/,/g' /tmp/test.txt | head

later you can take the output into the file using below command:

sed 's/\s/,/g' /tmp/test.txt > /tmp/test_final.txt

PS: test is the file which you want to use

Setting width/height as percentage minus pixels

  1. Use negative margins on the element you would like to minus pixels off. (desired element)
  2. Make overflow:hidden; on the containing element
  3. Switch to overflow:auto; on the desired element.

It worked for me!

How to add new column to an dataframe (to the front not end)?

The previous answers show 3 approaches

  1. By creating a new data frame
  2. By using "cbind"
  3. By adding column "a", and sort data frame by columns using column names or indexes

Let me show #4 approach "By using "cbind" and "rename" that works for my case

1. Create data frame

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))

2. Get values for "new" column

new_column = c(0, 0, 0)

3. Combine "new" column with existed

df <- cbind(new_column, df)

4. Rename "new" column name

colnames(df)[1] <- "a"

Getting String Value from Json Object Android

If you can use JSONObject library, you could just

    JSONArray ja = new JSONArray("[{\"Date\":\"2012-1-4T00:00:00\",\"keywords\":null,\"NeededString\":\"this is the sample string I am needed for my project\",\"others\":\"not needed\"}]");
    String result = ja.getJSONObject(0).getString("NeededString");

Is there a Social Security Number reserved for testing/examples?

To expand on the Wikipedia-based answers:

The Social Security Administration (SSA) explicitly states in this document that the having "000" in the first group of numbers "will NEVER be a valid SSN":

I'd consider that pretty definitive.

However, that the 2nd or 3rd groups of numbers won't be "00" or "0000" can be inferred from a FAQ that the SSA publishes which indicates that allocation of those groups starts at "01" or "0001":

But this is only a FAQ and it's never outright stated that "00" or "0000" will never be used.

In another FAQ they provide (http://www.socialsecurity.gov/employer/randomizationfaqs.html#a0=6) that "00" or "0000" will never be used.

I can't find a reference to the 'advertisement' reserved SSNs on the SSA site, but it appears that no numbers starting with a 3 digit number higher than 772 (according to the document referenced above) have been assigned yet, but there's nothing I could find that states those numbers are reserved. Wikipedia's reference is a book that I don't have access to. The Wikipedia information on the advertisement reserved numbers is mentioned across the web, but many are clearly copied from Wikipedia. I think it would be nice to have a citation from the SSA, though I suspect that now that Wikipedia has made the idea popular that these number would now have to be reserved for advertisements even if they weren't initially.

The SSA has a page with a couple of stories about SSN's they've had to retire because they were used in advertisements/samples (maybe the SSA should post a link to whatever their current policy on this might be):

Select a row from html table and send values onclick of a button

In my case $(document).ready(function() was missing. Try this.

$(document).ready(function(){   
("#table tr").click(function(){
       $(this).addClass('selected').siblings().removeClass('selected');    
       var value=$(this).find('td:first').html();
       alert(value);    
    });
    $('.ok').on('click', function(e){
        alert($("#table tr.selected td:first").html());
    });
});

Error: Configuration with name 'default' not found in Android Studio

This is probably a rare case, but for me a library that was included in the settings.gradle was not there.

E.g. I had: include ':libraries:Android-RateThisApp:library' in my settings.gradle

but the folder Android-RateThisApp was empty. As soon as I checked out this submodule the gradle sync succeed.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

If you transferred these files through disk or other means, it is likely they were not saved properly.

How to remove CocoaPods from a project?

  1. The first thing that you will need to do is remove the Podfile, Podfile.lock, the Pods folder, and the generated workspace.
  2. Next, in the .xcodeproj, remove the references to the Pods.xcconfig files and the libPods.a file.
  3. Within the Build Phases project tab, delete the Check Pods Manifest.lock section (open), Copy Pods Resources section (bottom) and Embed Pod Resources(bottom).
  4. Remove Pods.framework.

The only thing you may want to do is include some of the libraries that you were using before. You can do this by simply draging whatever folders where in the pods folders into your project (I prefer to put them into my Supporting Files folder).

It worked for me.

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

Can I underline text in an Android layout?

Strings.xml file content:

<resource>
     <string name="my_text">This is an <u>underline</u>.</string> 
</resources> 

Layout xml file shold use the above string resource with below properties of textview, as shown below:

<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:text="@string/my_text"

    android:selectAllOnFocus="false"
    android:linksClickable="false"
    android:autoLink="all"
    />

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<?php 
    $sessionDetails = $this->Session->read('Auth.User');

    if (!empty($sessionDetails)) {


        $loginFlag = 1;
        # code...
    }else{
        $loginFlag =  0;
    }


?>

<script type="text/javascript">

    var sessionValue = '<?php echo $loginFlag; ?>';
    if (sessionValue = 0) {

        //model show
    }
</script>

Django Template Variables and Javascript

I was facing simillar issue and answer suggested by S.Lott worked for me.

<script type="text/javascript"> 
   var a = "{{someDjangoVariable}}"
</script>

However I would like to point out major implementation limitation here. If you are planning to put your javascript code in different file and include that file in your template. This won't work.

This works only when you main template and javascript code is in same file. Probably django team can address this limitation.

Explanation of JSONB introduced by PostgreSQL

First, hstore is a contrib module, which only allows you to store key => value pairs, where keys and values can only be texts (however values can be sql NULLs too).

Both json & jsonb allows you to store a valid JSON value (defined in its spec).

F.ex. these are valid JSON representations: null, true, [1,false,"string",{"foo":"bar"}], {"foo":"bar","baz":[null]} - hstore is just a little subset compared to what JSON is capable (but if you only need this subset, it's fine).

The only difference between json & jsonb is their storage:

  • json is stored in its plain text format, while
  • jsonb is stored in some binary representation

There are 3 major consequences of this:

  • jsonb usually takes more disk space to store than json (sometimes not)
  • jsonb takes more time to build from its input representation than json
  • json operations take significantly more time than jsonb (& parsing also needs to be done each time you do some operation at a json typed value)

When jsonb will be available with a stable release, there will be two major use cases, when you can easily select between them:

  1. If you only work with the JSON representation in your application, PostgreSQL is only used to store & retrieve this representation, you should use json.
  2. If you do a lot of operations on the JSON value in PostgreSQL, or use indexing on some JSON field, you should use jsonb.

How to check if a float value is a whole number

You don't need to loop or to check anything. Just take a cube root of 12,000 and round it down:

r = int(12000**(1/3.0))
print r*r*r # 10648

How do you add a timed delay to a C++ program?

I found that "_sleep(milliseconds);" (without the quotes) works well for Win32 if you include the chrono library

E.g:

#include <chrono>

using namespace std;

main
{
    cout << "text" << endl;
    _sleep(10000); // pauses for 10 seconds
}

Make sure you include the underscore before sleep.

Convert JS Object to form data

If you have an object, you can easily create a FormData object and append the names and values from that object to formData.

You haven't posted any code, so it's a general example;

var form_data = new FormData();

for ( var key in item ) {
    form_data.append(key, item[key]);
}

$.ajax({
    url         : 'http://example.com/upload.php',
    data        : form_data,
    processData : false,
    contentType : false,
    type: 'POST'
}).done(function(data){
    // do stuff
});

There are more examples in the documentation on MDN

CSS Vertical align does not work with float

You need to set line-height.

<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>

http://jsfiddle.net/VBR5J/

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

Try this

myApp.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

Just setting useXDomain = true is not enough. AJAX request are also send with the X-Requested-With header, which indicate them as being AJAX. Removing the header is necessary, so the server is not rejecting the incoming request.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

function printr($data)
{
   echo "<pre>";
      print_r($data);
   echo "</pre>";
}

And call your function on the page you need, don't forget to include the file where you put your function in for example: functions.php

include('functions.php');

printr($data);

Where does linux store my syslog?

Default log location (rhel) are

General messages:

/var/log/messages

Authentication messages:

/var/log/secure

Mail events:

/var/log/maillog

Check your /etc/syslog.conf or /etc/syslog-ng.conf (it depends on which of syslog facility you have installed)

Example:

$ cat /etc/syslog.conf
# Log anything (except mail) of level info or higher.
# Don't log private authentication messages!
*.info;mail.none;authpriv.none         /var/log/messages

# The authpriv file has restricted access.
authpriv.*                             /var/log/secure

# Log all the mail messages in one place.
mail.*                                 /var/log/maillog

#For a start, use this simplified approach.
*.*                                     /var/log/messages

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

    private const string strconneciton = "Data Source=.;Initial Catalog=Employees;Integrated Security=True";
    SqlConnection con = new SqlConnection(strconneciton);

    private void button1_Click(object sender, EventArgs e)
    {

        con.Open();
        SqlCommand cmd = new SqlCommand("insert into EmployeeData (Name,S/O,Address,Phone,CellNo,CNICNO,LicenseNo,LicenseDistrict,LicenseValidPhoto,ReferenceName,ReferenceContactNo) values ( '" + textName.Text + "','" + textSO.Text + "','" + textAddress.Text + "','" + textPhone.Text + "','" + textCell.Text + "','" + textCNIC.Text + "','" + textLicenseNo.Text + "','" + textLicenseDistrict.Text + "','" + textLicensePhoto.Text + "','" + textReferenceName.Text + "','" + textContact.Text + "' )", con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

SQL to Entity Framework Count Group-By

Edit: EF Core 2.1 finally supports GroupBy

But always look out in the console / log for messages. If you see a notification that your query could not be converted to SQL and will be evaluated locally then you may need to rewrite it.


Entity Framework 7 (now renamed to Entity Framework Core 1.0 / 2.0) does not yet support GroupBy() for translation to GROUP BY in generated SQL (even in the final 1.0 release it won't). Any grouping logic will run on the client side, which could cause a lot of data to be loaded.

Eventually code written like this will automagically start using GROUP BY, but for now you need to be very cautious if loading your whole un-grouped dataset into memory will cause performance issues.

For scenarios where this is a deal-breaker you will have to write the SQL by hand and execute it through EF.

If in doubt fire up Sql Profiler and see what is generated - which you should probably be doing anyway.

https://blogs.msdn.microsoft.com/dotnet/2016/05/16/announcing-entity-framework-core-rc2

right align an image using CSS HTML

 img {
     display: block;
     margin-left: auto;
   }

How do C++ class members get initialized if I don't do it explicitly?

You can also initialize data members at the point you declare them:

class another_example{
public:
    another_example();
    ~another_example();
private:
    int m_iInteger=10;
    double m_dDouble=10.765;
};

I use this form pretty much exclusively, although I have read some people consider it 'bad form', perhaps because it was only recently introduced - I think in C++11. To me it is more logical.

Another useful facet to the new rules is how to initialize data-members that are themselves classes. For instance suppose that CDynamicString is a class that encapsulates string handling. It has a constructor that allows you specify its initial value CDynamicString(wchat_t* pstrInitialString). You might very well use this class as a data member inside another class - say a class that encapsulates a windows registry value which in this case stores a postal address. To 'hard code' the registry key name to which this writes you use braces:

class Registry_Entry{
public:
    Registry_Entry();
    ~Registry_Entry();
    Commit();//Writes data to registry.
    Retrieve();//Reads data from registry;
private:
    CDynamicString m_cKeyName{L"Postal Address"};
    CDynamicString m_cAddress;
};

Note the second string class which holds the actual postal address does not have an initializer so its default constructor will be called on creation - perhaps automatically setting it to a blank string.

PowerShell array initialization

$array = @()
for($i=0; $i -lt 5; $i++)
{
    $array += $i
}

Create instance of generic type in Java?

You can achieve this with the following snippet:

import java.lang.reflect.ParameterizedType;

public class SomeContainer<E> {
   E createContents() throws InstantiationException, IllegalAccessException {
      ParameterizedType genericSuperclass = (ParameterizedType)
         getClass().getGenericSuperclass();
      @SuppressWarnings("unchecked")
      Class<E> clazz = (Class<E>)
         genericSuperclass.getActualTypeArguments()[0];
      return clazz.newInstance();
   }
   public static void main( String[] args ) throws Throwable {
      SomeContainer< Long > scl = new SomeContainer<>();
      Long l = scl.createContents();
      System.out.println( l );
   }
}

Open mvc view in new window from controller

I assigned the javascript in my Controller:

model.linkCode = "window.open('https://www.yahoo.com', '_blank')";

And in my view:

@section Scripts{
    <script @Html.CspScriptNonce()>

    $(function () {

        @if (!String.IsNullOrEmpty(Model.linkCode))
        {
            WriteLiteral(Model.linkCode);
        }
    });

That opened a new tab with the link, and went to it.

Interestingly, run locally it engaged a popup blocker, but seemed to work fine on the servers.

Creating and Update Laravel Eloquent

One more option if your id isn't autoincrement and you know which one to insert/update:

$object = MyModel::findOrNew($id);
//assign attributes to update...
$object->save();

Copy file from source directory to binary directory using CMake

This is what I used to copy some resource files: the copy-files is an empty target to ignore errors

 add_custom_target(copy-files ALL
    COMMAND ${CMAKE_COMMAND} -E copy_directory
    ${CMAKE_BINARY_DIR}/SOURCEDIRECTORY
    ${CMAKE_BINARY_DIR}/DESTINATIONDIRECTORY
    )

multi line comment vb.net in Visual studio 2010

I just learned this trick from a friend. Put your code inside these 2 statements and it will be commented out.

#if false

#endif

Accessing localhost of PC from USB connected Android mobile device

How to Easily access LocalHost in Actual Android Device -> Connect your pc with the android device via USB

  1. Go to Chrome inspection click 'f12' or Control+Shift+C

Chrome Inspection tool

  1. Check the bottom of the chrome inspection tool.

  2. Now go to settings in Remote Device Tab.

Remote Devices Tab

  1. check on "Discover USB Device" option as well as check on "Port Forwarding" option.

  2. Now Click on Add Rules, Enter Any Device Port e.g(4880) and in Local Address Enter the Actual Address of the local host in my case e.g (127.0.0.1:480)

  3. After Adding the Rule go to your android studio -> inside your code URL(http://127.0.0.1:4880). Remember to change the port from 480 -> 4880.

  4. Go to Remote Device Tab in Chrome and Click on your connected Device. Add New URL(127.0.0.1:4880) Inspect the Android Device Chrome Browser

Check your Actual Device Chrome Browser and start Debugging the code on Actual Android device.

TypeError: $.ajax(...) is not a function?

I encountered the same question, and my solution was: add the JQuery script.

Especially, we should make sure the corresponding JQuery is loaded when we debug our js under the firefox/chrome.

Manually put files to Android emulator SD card

Use the adb tool that comes with the SDK.

adb push myDirectory /sdcard/targetDir

If you only specify /sdcard/ (with the trailing slash) as destination, then the CONTENTS of myDirectory will end up in the root of /sdcard.

raw vs. html_safe vs. h to unescape html

The best safe way is: <%= sanitize @x %>

It will avoid XSS!

Using Caps Lock as Esc in Mac OS X

In order to actually swap the escape key with the caps lock key (not just map one to the other) using both PCKeyboardHack and KeyRemap4MacBook, you have to follow the instructions in this thread, mapping the caps lock key to a keycode not used by the keyboard but accounted for by KeyRemap4MacBook (eg. 110). Then, in PCKeyboardHack, select the appropriate option that maps that keycode to escape (in the case of 110, it's "Application Key to Escape"). Here's what your KeyRemap4MacBook preferences should look like (provided you've selected the "show enabled only" checkbox).

enter image description here

I originally attempted to post this information as an edit to cwd's excellent answer, but it was rejected. I encourage anyone who wants to go the route that I describe to first read his/her response.

Get method arguments using Spring AOP?

Yes, the value of any argument can be found using getArgs

@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {

   Object[] signatureArgs = thisJoinPoint.getArgs();
   for (Object signatureArg: signatureArgs) {
      System.out.println("Arg: " + signatureArg);
      ...
   }
}

Learning to write a compiler

  1. This is a vast subject. Do not underestimate this point. And do not underestimate my point to not underestimate it.
  2. I hear the Dragon Book is a (the?) place to start, along with searching. :) Get better at searching, eventually it will be your life.
  3. Building your own programming language is absolutely a good exercise! But know that it will never be used for any practical purpose in the end. Exceptions to this are few and very far between.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

SELECT only rows that contain only alphanumeric characters in MySQL

Try this:

REGEXP '^[a-z0-9]+$'

As regexp is not case sensitive except for binary fields.

How to run Nginx within a Docker container without halting?

To expand on John's answer you can also use the Dockerfile CMD command as following (in case you want it to self start without additional args)

CMD ["nginx", "-g", "daemon off;"]

Parse a URI String into Name-Value Collection

use google Guava and do it in 2 lines:

import java.util.Map;
import com.google.common.base.Splitter;

public class Parser {
    public static void main(String... args) {
        String uri = "https://google.com.ua/oauth/authorize?client_id=SS&response_type=code&scope=N_FULL&access_type=offline&redirect_uri=http://localhost/Callback";
        String query = uri.split("\\?")[1];
        final Map<String, String> map = Splitter.on('&').trimResults().withKeyValueSeparator('=').split(query);
        System.out.println(map);
    }
}

which gives you

{client_id=SS, response_type=code, scope=N_FULL, access_type=offline, redirect_uri=http://localhost/Callback}

How to include Javascript file in Asp.Net page

I assume that you are using MasterPage so within your master page you should have

<head runat="server">
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>

And within any of your pages based on that MasterPage add this

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <script src="js/yourscript.js" type="text/javascript"></script>
</asp:Content>

Copying HTML code in Google Chrome's inspect element

  1. Select the <html> tag in Elements.
  2. Do CTRL-C.
  3. Check if there is only lefting <!DOCTYPE html> before the <html>.

How to forcefully set IE's Compatibility Mode off from the server-side?

Update: More useful information What does <meta http-equiv="X-UA-Compatible" content="IE=edge"> do?

Maybe this url can help you: Activating Browser Modes with Doctype

Edit: Today we were able to override the compatibility view with: <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" />

jQuery UI Dialog OnBeforeUnload

jQuery API specifically says not to bind to beforeunload, and instead should bind directly to the window.onbeforeunload, I just ran across a pretty bad memory in part due binding to beforeunload with jQuery.

How to export collection to CSV in MongoDB?

Also if you want to export inner json fields use dot (. operator).

JSON record:

{
    "_id" : "00118685076F2C77",
    "value" : {
        "userIds" : [ 
            "u1"
        ],
        "deviceId" : "dev"
}

mongoexport command with dot operator (using mongo version 3.4.7):

./mongoexport --host localhost --db myDB --collection myColl --type=csv --out out.csv --fields value.deviceId,value.userIds

Output csv:

value.deviceId,value.userIds
d1,"[""u1""]"
d2,"[""u2""]"

Note: Make sure you do not export an array. It would corrupt the CSV format like field userIds shown above

Storing image in database directly or as base64 data?

  • Pro base64: the encoded representation you handle is a pretty safe string. It contains neither control chars nor quotes. The latter point helps against SQL injection attempts. I wouldn't expect any problem to just add the value to a "hand coded" SQL query string.

  • Pro BLOB: the database manager software knows what type of data it has to expect. It can optimize for that. If you'd store base64 in a TEXT field it might try to build some index or other data structure for it, which would be really nice and useful for "real" text data but pointless and a waste of time and space for image data. And it is the smaller, as in number of bytes, representation.

How can I perform an inspect element in Chrome on my Galaxy S3 Android device?

Keep in mind that if you want to use the chrome inspect in Windows, besides enabling usb debugging on you mobile, you should also install the usb driver for Windows.

You can find the drivers you need from the list here:

http://androidxda.com/download-samsung-usb-drivers

Furthermore, you should use a newer version of Chrome mobile than the one in your Desktop.

Find an item in List by LINQ?

There's a few ways (note this is not a complete list).

1) Single will return a single result, but will throw an exception if it finds none or more than one (which may or may not be what you want):

string search = "lookforme";
List<string> myList = new List<string>();
string result = myList.Single(s => s == search);

Note SingleOrDefault() will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.

2) Where will return all items which match your criteria, so you may get an IEnumerable with one element:

IEnumerable<string> results = myList.Where(s => s == search);

3) First will return the first item which matches your criteria:

string result = myList.First(s => s == search);

Note FirstOrDefault() will behave the same, except it will return null for reference types, or the default value for value types, instead of throwing an exception.

click command in selenium webdriver does not work

I was using firefox and some reason, it was not taking the click command though from past 2months it was working. My feeling was to make use of sendKeys and this page solved the problem. Now I am using sendKeys(Keys.Enter)

How to parse data in JSON format?

Sometimes your json is not a string. For example if you are getting a json from a url like this:

j = urllib2.urlopen('http://site.com/data.json')

you will need to use json.load, not json.loads:

j_obj = json.load(j)

(it is easy to forget: the 's' is for 'string')

Difference between iCalendar (.ics) and the vCalendar (.vcs)

Both .ics and .vcs files are in ASCII. If you use "Save As" option to save a calendar entry (Appt, Meeting Request/Response/Postpone/Cancel and etc) in both .ics and .vcs format and use vimdiff, you can easily see the difference.

Both .vcs (vCal) and .ics (iCal) belongs to the same VCALENDAR camp, but .vcs file shows "VERSION:1.0" whereas .ics file uses "VERSION:2.0".

The spec for vCalendar v1.0 can be found at http://www.imc.org/pdi/pdiproddev.html. The spec for iCalendar (vCalendar v2.0) is in RFC5545. In general, the newer is better, and that is true for Outlook 2007 and onward, but not for Outlook 2003.

For Outlook 2003, the behavior is peculiar. It can save the same calendar entry in both .ics and .vcs format, but it only read & display .vcs file correctly. It can read .ics file but it omits some fields and does not display it in calendar mode. My guess is that back then Microsoft wanted to provide .ics to be compatible with Mac's iCal but not quite committed to v2.0 yet.

So I would say for Outlook 2003, .vcs is the native format.

How do I install the yaml package for Python?

Update: Nowadays installing is done with pip, but libyaml is still required to build the C extension (on mac):

brew install libyaml
python -m pip install pyyaml

Outdated method:

For MacOSX (mavericks), the following seems to work:

brew install libyaml
sudo python -m easy_install pyyaml

ElasticSearch - Return Unique Values

if you want to get the first document for each language field unique value, you can do this:

{
 "query": {
    "match_all": {
    }
  },
  "collapse": {
    "field": "language.keyword",
    "inner_hits": {
    "name": "latest",
      "size": 1
    }
  }
}

Android Webview - Completely Clear the Cache

To clear cookie and cache from Webview,

    // Clear all the Application Cache, Web SQL Database and the HTML5 Web Storage
    WebStorage.getInstance().deleteAllData();

    // Clear all the cookies
    CookieManager.getInstance().removeAllCookies(null);
    CookieManager.getInstance().flush();

    webView.clearCache(true);
    webView.clearFormData();
    webView.clearHistory();
    webView.clearSslPreferences();

What's the fastest way to read a text file line-by-line?

If you have enough memory, I've found some performance gains by reading the entire file into a memory stream, and then opening a stream reader on that to read the lines. As long as you actually plan on reading the whole file anyway, this can yield some improvements.

How to find the 'sizeof' (a pointer pointing to an array)?

There is no magic solution. C is not a reflective language. Objects don't automatically know what they are.

But you have many choices:

  1. Obviously, add a parameter
  2. Wrap the call in a macro and automatically add a parameter
  3. Use a more complex object. Define a structure which contains the dynamic array and also the size of the array. Then, pass the address of the structure.

Setting "checked" for a checkbox with jQuery

This selects elements that have the specified attribute with a value containing the given substring "ckbItem":

$('input[name *= ckbItem]').prop('checked', true);

It will select all elements that contain ckbItem in its name attribute.

(Built-in) way in JavaScript to check if a string is a valid number

This is built on some of the previous answers and comments. The following covers all the edge cases and fairly concise as well:

const isNumRegEx = /^-?(\d*\.)?\d+$/;

function isNumeric(n, allowScientificNotation = false) {
    return allowScientificNotation ? 
                !Number.isNaN(parseFloat(n)) && Number.isFinite(n) :
                isNumRegEx.test(n);
}

How to display data from database into textbox, and update it

Populate the text box values in the Page Init event as opposed to using the Postback.

protected void Page_Init(object sender, EventArgs e)
{
    DropDownTitle();
}

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

I had the same issue on the Linux server I was working on. Connecting java to a X11 display worked on the head node, but not on any other. After contacting the administrator, it turned out that the current version of our job-scheduling system (SLURM) did not support X11 forwarding. They had to update SLURM (newer versions of SLURM support it) for it to work.

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

:before and background-image... should it work?

 color: transparent; 

make the tricks for me

#videos-part:before{
    font-size: 35px;
    line-height: 33px;
    width: 16px;
    color: transparent;
    content: 'AS YOU LIKE';
    background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
    background-size: 25px;
    background-repeat: no-repeat;
    }

Programmatically shut down Spring Boot application

Closing a SpringApplication basically means closing the underlying ApplicationContext. The SpringApplication#run(String...) method gives you that ApplicationContext as a ConfigurableApplicationContext. You can then close() it yourself.

For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to shut down...
        ctx.close();
    }
}

Alternatively, you can use the static SpringApplication.exit(ApplicationContext, ExitCodeGenerator...) helper method to do it for you. For example,

@SpringBootApplication
public class Example {
    public static void main(String[] args) {
        ConfigurableApplicationContext ctx = SpringApplication.run(Example.class, args);
        // ...determine it's time to stop...
        int exitCode = SpringApplication.exit(ctx, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                // no errors
                return 0;
            }
        });

        // or shortened to
        // int exitCode = SpringApplication.exit(ctx, () -> 0);

        System.exit(exitCode);
    }
}

Spring Security with roles and permissions

After reading this post, from Baeldung. I found that the solution is pretty simple.

What I have done, is to add the role and permissions into the GrantedAuthority. I was able to access both methods hasRole() and hasAuthority().

Using jQuery to test if an input has focus

jQuery 1.6+

jQuery added a :focus selector so we no longer need to add it ourselves. Just use $("..").is(":focus")

jQuery 1.5 and below

Edit: As times change, we find better methods for testing focus, the new favorite is this gist from Ben Alman:

jQuery.expr[':'].focus = function( elem ) {
  return elem === document.activeElement && ( elem.type || elem.href );
};

Quoted from Mathias Bynens here:

Note that the (elem.type || elem.href) test was added to filter out false positives like body. This way, we make sure to filter out all elements except form controls and hyperlinks.

You're defining a new selector. See Plugins/Authoring. Then you can do:

if ($("...").is(":focus")) {
  ...
}

or:

$("input:focus").doStuff();

Any jQuery

If you just want to figure out which element has focus, you can use

$(document.activeElement)

If you aren't sure if the version will be 1.6 or lower, you can add the :focus selector if it is missing:

(function ( $ ) {
    var filters = $.expr[":"];
    if ( !filters.focus ) { 
        filters.focus = function( elem ) {
           return elem === document.activeElement && ( elem.type || elem.href );
        };
    }
})( jQuery );

How to convert NSData to byte array in iPhone?

That's because the return type for [data bytes] is a void* c-style array, not a Uint8 (which is what Byte is a typedef for).

The error is because you are trying to set an allocated array when the return is a pointer type, what you are looking for is the getBytes:length: call which would look like:

[data getBytes:&byteData length:len];

Which fills the array you have allocated with data from the NSData object.

How to concatenate columns in a Postgres SELECT?

The problem was in nulls in the values; then the concatenation does not work with nulls. The solution is as follows:

SELECT coalesce(a, '') || coalesce(b, '') FROM foo;

Why is HttpClient BaseAddress not working?

Ran into a issue with the HTTPClient, even with the suggestions still could not get it to authenticate. Turns out I needed a trailing '/' in my relative path.

i.e.

var result = await _client.GetStringAsync(_awxUrl + "api/v2/inventories/?name=" + inventoryName);
var result = await _client.PostAsJsonAsync(_awxUrl + "api/v2/job_templates/" + templateId+"/launch/" , new {
                inventory = inventoryId
            });

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Have a look at C++11 Features (Modern C++)

and section "Quick Reference Guide to Visual C++ Version Numbers" ...

DIV :after - add content after DIV

Position your <div> absolutely at the bottom and don't forget to give div.A a position: relative - http://jsfiddle.net/TTaMx/

    .A {
        position: relative;
        margin: 40px 0;
        height: 40px;
        width: 200px;
        background: #eee;
    }

    .A:after {
        content: " ";
        display: block;
        background: #c00;
        height: 29px;
        width: 100%;

        position: absolute;
        bottom: -29px;
    }?

Turn off warnings and errors on PHP and MySQL

When you are sure your script is perfectly working, you can get rid of warning and notices like this: Put this line at the beginning of your PHP script:

error_reporting(E_ERROR);

Before that, when working on your script, I would advise you to properly debug your script so that all notice or warning disappear one by one.

So you should first set it as verbose as possible with:

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

UPDATE: how to log errors instead of displaying them

As suggested in the comments, the better solution is to log errors into a file so only the PHP developer sees the error messages, not the users.

A possible implementation is via the .htaccess file, useful if you don't have access to the php.ini file (source).

# Suppress PHP errors
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off
php_value docref_root 0
php_value docref_ext 0

# Enable PHP error logging
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

# Prevent access to PHP error log
<Files PHP_errors.log>
 Order allow,deny
 Deny from all
 Satisfy All
</Files>

How to store JSON object in SQLite database

https://github.com/requery/sqlite-android allows you to query JSON fields (and arrays in them, I've tried it and am using it). Before that I was just storing JSON strings into a TEXT column. It supports FTS3, FTS4, & JSON1

As of July 2019, it still gets version bumps every now and then, so it isn't a dead project.

python-pandas and databases like mysql

For the record, here is an example using a sqlite database:

import pandas as pd
import sqlite3

with sqlite3.connect("whatever.sqlite") as con:
    sql = "SELECT * FROM table_name"
    df = pd.read_sql_query(sql, con)
    print df.shape

Make A List Item Clickable (HTML/CSS)

Here is a working solution - http://jsfiddle.net/STTaf/

I used simple jQuery:

$(function() {
    $('li').css('cursor', 'pointer')

    .click(function() {
        window.location = $('a', this).attr('href');
        return false;
    });
});

Understanding the difference between Object.create() and new SomeFunction()

This:

var foo = new Foo();

and

var foo = Object.create(Foo.prototype);

are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

function Foo() {
    alert("This constructor does not run with Object.create");
}

Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

Set the Value of a Hidden field using JQuery

The selector should not be #input. That means a field with id="input" which is not your case. You want:

$('#chag_sort').val(sort2);

Or if your hidden input didn't have an unique id but only a name="chag_sort":

$('input[name="chag_sort"]').val(sort2);

How to access parameters in a RESTful POST method

Your @POST method should be accepting a JSON object instead of a string. Jersey uses JAXB to support marshaling and unmarshaling JSON objects (see the jersey docs for details). Create a class like:

@XmlRootElement
public class MyJaxBean {
    @XmlElement public String param1;
    @XmlElement public String param2;
}

Then your @POST method would look like the following:

@POST @Consumes("application/json")
@Path("/create")
public void create(final MyJaxBean input) {
    System.out.println("param1 = " + input.param1);
    System.out.println("param2 = " + input.param2);
}

This method expects to receive JSON object as the body of the HTTP POST. JAX-RS passes the content body of the HTTP message as an unannotated parameter -- input in this case. The actual message would look something like:

POST /create HTTP/1.1
Content-Type: application/json
Content-Length: 35
Host: www.example.com

{"param1":"hello","param2":"world"}

Using JSON in this way is quite common for obvious reasons. However, if you are generating or consuming it in something other than JavaScript, then you do have to be careful to properly escape the data. In JAX-RS, you would use a MessageBodyReader and MessageBodyWriter to implement this. I believe that Jersey already has implementations for the required types (e.g., Java primitives and JAXB wrapped classes) as well as for JSON. JAX-RS supports a number of other methods for passing data. These don't require the creation of a new class since the data is passed using simple argument passing.


HTML <FORM>

The parameters would be annotated using @FormParam:

@POST
@Path("/create")
public void create(@FormParam("param1") String param1,
                   @FormParam("param2") String param2) {
    ...
}

The browser will encode the form using "application/x-www-form-urlencoded". The JAX-RS runtime will take care of decoding the body and passing it to the method. Here's what you should see on the wire:

POST /create HTTP/1.1
Host: www.example.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-Length: 25

param1=hello&param2=world

The content is URL encoded in this case.

If you do not know the names of the FormParam's you can do the following:

@POST @Consumes("application/x-www-form-urlencoded")
@Path("/create")
public void create(final MultivaluedMap<String, String> formParams) {
    ...
}

HTTP Headers

You can using the @HeaderParam annotation if you want to pass parameters via HTTP headers:

@POST
@Path("/create")
public void create(@HeaderParam("param1") String param1,
                   @HeaderParam("param2") String param2) {
    ...
}

Here's what the HTTP message would look like. Note that this POST does not have a body.

POST /create HTTP/1.1
Content-Length: 0
Host: www.example.com
param1: hello
param2: world

I wouldn't use this method for generalized parameter passing. It is really handy if you need to access the value of a particular HTTP header though.


HTTP Query Parameters

This method is primarily used with HTTP GETs but it is equally applicable to POSTs. It uses the @QueryParam annotation.

@POST
@Path("/create")
public void create(@QueryParam("param1") String param1,
                   @QueryParam("param2") String param2) {
    ...
}

Like the previous technique, passing parameters via the query string does not require a message body. Here's the HTTP message:

POST /create?param1=hello&param2=world HTTP/1.1
Content-Length: 0
Host: www.example.com

You do have to be particularly careful to properly encode query parameters on the client side. Using query parameters can be problematic due to URL length restrictions enforced by some proxies as well as problems associated with encoding them.


HTTP Path Parameters

Path parameters are similar to query parameters except that they are embedded in the HTTP resource path. This method seems to be in favor today. There are impacts with respect to HTTP caching since the path is what really defines the HTTP resource. The code looks a little different than the others since the @Path annotation is modified and it uses @PathParam:

@POST
@Path("/create/{param1}/{param2}")
public void create(@PathParam("param1") String param1,
                   @PathParam("param2") String param2) {
    ...
}

The message is similar to the query parameter version except that the names of the parameters are not included anywhere in the message.

POST /create/hello/world HTTP/1.1
Content-Length: 0
Host: www.example.com

This method shares the same encoding woes that the query parameter version. Path segments are encoded differently so you do have to be careful there as well.


As you can see, there are pros and cons to each method. The choice is usually decided by your clients. If you are serving FORM-based HTML pages, then use @FormParam. If your clients are JavaScript+HTML5-based, then you will probably want to use JAXB-based serialization and JSON objects. The MessageBodyReader/Writer implementations should take care of the necessary escaping for you so that is one fewer thing that can go wrong. If your client is Java based but does not have a good XML processor (e.g., Android), then I would probably use FORM encoding since a content body is easier to generate and encode properly than URLs are. Hopefully this mini-wiki entry sheds some light on the various methods that JAX-RS supports.

Note: in the interest of full disclosure, I haven't actually used this feature of Jersey yet. We were tinkering with it since we have a number of JAXB+JAX-RS applications deployed and are moving into the mobile client space. JSON is a much better fit that XML on HTML5 or jQuery-based solutions.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I got this error because I forgot the type="module" inside the script tag:

<script type="module" src="milsymbol-2.0.0/src/milsymbol.js"></script>

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Have had the same problem happen to me twice now, the only fix sofa has been to restart the tomcat server and restart the build.

Best way to test for a variable's existence in PHP; isset() is clearly broken

If the variable you are checking would be in the global scope you could do:

array_key_exists('v', $GLOBALS) 

How to Completely Uninstall Xcode and Clear All Settings

Run this to find all instances of Xcode in your filesystem:

for i in find / -name Xcode -print; do echo $i; done

UITableView Cell selected Color?

I use below approach and works fine for me,

class MyTableViewCell : UITableViewCell {

                var defaultStateColor:UIColor?
                var hitStateColor:UIColor?

                 override func awakeFromNib(){
                     super.awakeFromNib()
                     self.selectionStyle = .None
                 }

// if you are overriding init you should set selectionStyle = .None

                override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let hitColor = hitStateColor {
                        self.contentView.backgroundColor = hitColor
                    }
                }

                override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }

                override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
                    if let defaultColor = defaultStateColor {
                        self.contentView.backgroundColor = defaultColor
                    }
                }
            }

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

Read this:

http://www.quora.com/OAuth-2-0/How-does-OAuth-2-0-work

or an even simpler but quick explanation:

http://agileanswer.blogspot.se/2012/08/oauth-20-for-my-ninth-grader.html

The redirect URI is the callback entry point of the app. Think about how OAuth for Facebook works - after end user accepts permissions, "something" has to be called by Facebook to get back to the app, and that "something" is the redirect URI. Furthermore, the redirect URI should be different than the initial entry point of the app.

The other key point to this puzzle is that you could launch your app from a URL given to a webview. To do this, i simply followed the guide on here:

http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html

and

http://inchoo.net/mobile-development/iphone-development/launching-application-via-url-scheme/

note: on those last 2 links, "http://" works in opening mobile safari but "tel://" doesn't work in simulator

in the first app, I call

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"secondApp://"]];

In my second app, I register "secondApp" (and NOT "secondApp://") as the name of URL Scheme, with my company as the URL identifier.

How to specify the port an ASP.NET Core application is hosted on?

When hosted in docker containers (linux version for me), you might get a 'Connection Refused' message. In that case you can use IP address 0.0.0.0 which means "all IP addresses on this machine" instead of the localhost loopback to fix the port forwarding.

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://0.0.0.0:5000/")
            .Build();

        host.Run();
    }
}

how to start stop tomcat server using CMD?

Add %CATALINA_HOME%/bin to path system variable.

Go to Environment Variables screen under System Variables there will be a Path variable edit the variable and add ;%CATALINA_HOME%\bin to the variable then click OK to save the changes. Close all opened command prompts then open a new command prompt and try to use the command startup.bat.

Why would we call cin.clear() and cin.ignore() after reading input?

The cin.clear() clears the error flag on cin (so that future I/O operations will work correctly), and then cin.ignore(10000, '\n') skips to the next newline (to ignore anything else on the same line as the non-number so that it does not cause another parse failure). It will only skip up to 10000 characters, so the code is assuming the user will not put in a very long, invalid line.

How do I specify different layouts for portrait and landscape orientations?

Fastest way for Android Studio 3.x.x and Android Studio 4.x.x

1.Go to the design tab of the activity layout

2.At the top you should press on the orientation for preview button, there is a option to create a landscape layout (check image), a new folder will be created as your xml layout file for that particular orientation

enter image description here

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

DB2 SQL error: SQLCODE: -206, SQLSTATE: 42703

That only means that an undefined column or parameter name was detected. The errror that DB2 gives should point what that may be:

DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=[THE_UNDEFINED_COLUMN_OR_PARAMETER_NAME], DRIVER=4.8.87

Double check your table definition. Maybe you just missed adding something.

I also tried google-ing this problem and saw this:

http://www.coderanch.com/t/515475/JDBC/databases/sql-insert-statement-giving-sqlcode

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

Zip folder in C#

This answer changes with .NET 4.5. Creating a zip file becomes incredibly easy. No third-party libraries will be required.

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);

phpmailer error "Could not instantiate mail function"

For what it's worth I had this issue and had to go into cPanel where I saw the error message

"Attention! Please register your email IDs used in non-smtp mails through cpanel plugin. Unregistered email IDs will not be allowed in non-smtp emails sent through scripts. Go to Mail section and find "Registered Mail IDs" plugin in paper_lantern theme."

Registering the emails in cPanel (Register Mail IDs) and waiting 10 mins got mine to work.

Hope that helps someone.

R apply function with multiple parameters

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
mapply(mult_one,vars1,vars2)

which gives you:

> mapply(mult_one,vars1,vars2)
[1] 10 40 90

Select row on click react-table

The answer you selected is correct, however if you are using a sorting table it will crash since rowInfo will became undefined as you search, would recommend using this function instead

                getTrGroupProps={(state, rowInfo, column, instance) => {
                    if (rowInfo !== undefined) {
                        return {
                            onClick: (e, handleOriginal) => {
                              console.log('It was in this row:', rowInfo)
                              this.setState({
                                  firstNameState: rowInfo.row.firstName,
                                  lastNameState: rowInfo.row.lastName,
                                  selectedIndex: rowInfo.original.id
                              })
                            },
                            style: {
                                cursor: 'pointer',
                                background: rowInfo.original.id === this.state.selectedIndex ? '#00afec' : 'white',
                                color: rowInfo.original.id === this.state.selectedIndex ? 'white' : 'black'
                            }
                        }
                    }}
                }

How to enable Bootstrap tooltip on disabled button?

This is what myself and tekromancr came up with.

Example element:

<a href="http://www.google.com" id="btn" type="button" class="btn btn-disabled" data-placement="top" data-toggle="tooltip" data-title="I'm a tooltip">Press Me</a>

note: the tooltip attributes can be added to a separate div, in which the id of that div is to be used when calling .tooltip('destroy'); or .tooltip();

this enables the tooltip, put it in any javascript that is included in the html file. this line might not be necessary to add, however. (if the tooltip shows w/o this line then don't bother including it)

$("#element_id").tooltip();

destroys tooltip, see below for usage.

$("#element_id").tooltip('destroy');

prevents the button from being clickable. because the disabled attribute is not being used, this is necessary, otherwise the button would still be clickable even though it "looks" as if it is disabled.

$("#element_id").click(
  function(evt){
    if ($(this).hasClass("btn-disabled")) {
      evt.preventDefault();
      return false;
    }
  });

Using bootstrap, the classes btn and btn-disabled are available to you. Override these in your own .css file. you can add any colors or whatever you want the button to look like when disabled. Make sure you keep the cursor: default; you can also change what .btn.btn-success looks like.

.btn.btn-disabled{
    cursor: default;
}

add the code below to whatever javascript is controlling the button becoming enabled.

$("#element_id").removeClass('btn-disabled');
$("#element_id").addClass('btn-success');
$('#element_id).tooltip('destroy');

tooltip should now only show when the button is disabled.

if you are using angularjs i also have a solution for that, if desired.

How to prevent vim from creating (and leaving) temporary files?

On Windows add following lines to _vimrc

" store backup, undo, and swap files in temp directory
set directory=$HOME/temp//
set backupdir=$HOME/temp//
set undodir=$HOME/temp//

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

How to make a new line or tab in <string> XML (eclipse/android)?

Use \t to add tab and \n for new line, here is a simple example below.

<string name="list_with_tab_tag">\tbanana\torange\tblueberry\tmango</string>
<string name="sentence_with_new_line_tag">This is the first sentence\nThis is the second scentence\nThis is the third sentence</string>

standard size for html newsletter template

Bdizzle,

I would recommend that you read this link

You will see that Newsletters can have different widths, There seems to be no major standard, What is recommended is that the width will be about 95% of the page width, as different browsers use the extra margins differently. You will also find that email readers have problems when reading css so applying the guide lines in this tutorial might help you save some time and trouble-shooting down the road.

Be happy, Julian

mkdir's "-p" option

-p|--parent will be used if you are trying to create a directory with top-down approach. That will create the parent directory then child and so on iff none exists.

-p, --parents no error if existing, make parent directories as needed

About rlidwka it means giving full or administrative access. Found it here https://itservices.stanford.edu/service/afs/intro/permissions/unix.

Make a dictionary with duplicate keys in Python

You can refer to the following article: http://www.wellho.net/mouth/3934_Multiple-identical-keys-in-a-Python-dict-yes-you-can-.html

In a dict, if a key is an object, there are no duplicate problems.

For example:

class p(object):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name
    def __str__(self):
        return self.name
d = {p('k'): 1, p('k'): 2}

Start a fragment via Intent within a Fragment

Try this it may help you:

private void changeFragment(Fragment targetFragment){

    getSupportFragmentManager()
         .beginTransaction()
         .replace(R.id.main_fragment, targetFragment, "fragment")
         .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
         .commit();

}

How to send HTML email using linux command line

you should use "append" mode redirection >> instead of >

How to get the size of the current screen in WPF?

This will give you the current screen based on the top left of the window just call this.CurrentScreen() to get info on the current screen.

using System.Windows;
using System.Windows.Forms;

namespace Common.Helpers
{
    public static class WindowHelpers
     {
        public static Screen CurrentScreen(this Window window)
         {
             return Screen.FromPoint(new System.Drawing.Point((int)window.Left,(int)window.Top));
         }
     }
}

Regular expression for excluding special characters

I would just white list the characters.

^[a-zA-Z0-9äöüÄÖÜ]*$

Building a black list is equally simple with regex but you might need to add much more characters - there are a lot of Chinese symbols in unicode ... ;)

^[^<>%$]*$

The expression [^(many characters here)] just matches any character that is not listed.

How do I create a new branch?

Right click and open SVN Repo-browser:

Enter image description here

Right click on Trunk (working copy) and choose Copy to...:

Enter image description here

Input the respective branch's name/path:

Enter image description here

Click OK, type the respective log message, and click OK.

Java ArrayList clear() function

If you in any doubt, have a look at JDK source code

ArrayList.clear() source code:

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

You will see that size is set to 0 so you start from 0 position.

Please note that when adding elements to ArrayList, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear() you only remove references to array elements and sets size to 0, however, capacity stays as it was.

How to download a branch with git?

Navigate to the folder on your new machine you want to download from git on git bash.

Use below command to download the code from any branch you like

git clone 'git ssh url' -b 'Branch Name'

It will download the respective branch code.

JavaScript: location.href to open in new window/tab?

You can open it in a new window with window.open('https://support.wwf.org.uk/earth_hour/index.php?type=individual');. If you want to open it in new tab open the current page in two tabs and then alllow the script to run so that both current page and the new page will be obtained.

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

Angular - Set headers for every request

The simplest of all

Create a config.ts file

import { HttpHeaders } from '@angular/common/http';

export class Config {
    url: string = 'http://localhost:3000';
    httpOptions: any = {
        headers: new HttpHeaders({
           'Content-Type': 'application/json',
           'Authorization': JSON.parse(localStorage.getItem('currentUser')).token
        })
    }
}

Then on your service, just import the config.ts file

import { Config } from '../config';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class OrganizationService {
  config = new Config;

  constructor(
    private http: HttpClient
  ) { }

  addData(data): Observable<any> {
     let sendAddLink = `${this.config.url}/api/addData`;

     return this.http.post(sendAddLink , data, this.config.httpOptions).pipe(
       tap(snap => {
      return snap;
        })
    );
 } 

I think it was the simplest and the safest.

Correct way to work with vector of arrays

You cannot store arrays in a vector or any other container. The type of the elements to be stored in a container (called the container's value type) must be both copy constructible and assignable. Arrays are neither.

You can, however, use an array class template, like the one provided by Boost, TR1, and C++0x:

std::vector<std::array<double, 4> >

(You'll want to replace std::array with std::tr1::array to use the template included in C++ TR1, or boost::array to use the template from the Boost libraries. Alternatively, you can write your own; it's quite straightforward.)

mysql update multiple columns with same now()

Mysql isn't very clever. When you want to use the same timestamp in multiple update or insert queries, you need to declare a variable.

When you use the now() function, the system will call the current timestamp every time you call it in another query.

Reverse a string in Python

Reverse a string without python magic.

>>> def reversest(st):
    a=len(st)-1
    for i in st:
        print(st[a],end="")
        a=a-1

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

Why does integer division in C# return an integer and not a float?

As a little trick to know what you are obtaining you can use var, so the compiler will tell you the type to expect:

int a = 1;
int b = 2;
var result = a/b;

your compiler will tell you that result would be of type int here.

How do I undo 'git add' before commit?

git remove or git rm can be used for this, with the --cached flag. Try:

git help rm

Difference between Width:100% and width:100vw?

You can solve this issue be adding max-width:

#element {
   width: 100vw;
   height: 100vw;
   max-width: 100%;
}

When you using CSS to make the wrapper full width using the code width: 100vw; then you will notice a horizontal scroll in the page, and that happened because the padding and margin of html and body tags added to the wrapper size, so the solution is to add max-width: 100%

How to get Real IP from Visitor?

Proxies may send a HTTP_X_FORWARDED_FOR header but even that is optional.

Also keep in mind that visitors may share IP addresses; University networks, large companies and third-world/low-budget ISPs tend to share IPs over many users.

How to Compare two strings using a if in a stored procedure in sql server 2008?

What you want is a SQL case statement. The form of these is either:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

or:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

In your example you are after:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

What are major differences between C# and Java?

Comparing Java 7 and C# 3

(Some features of Java 7 aren't mentioned here, but the using statement advantage of all versions of C# over Java 1-6 has been removed.)

Not all of your summary is correct:

  • In Java methods are virtual by default but you can make them final. (In C# they're sealed by default, but you can make them virtual.)
  • There are plenty of IDEs for Java, both free (e.g. Eclipse, Netbeans) and commercial (e.g. IntelliJ IDEA)

Beyond that (and what's in your summary already):

  • Generics are completely different between the two; Java generics are just a compile-time "trick" (but a useful one at that). In C# and .NET generics are maintained at execution time too, and work for value types as well as reference types, keeping the appropriate efficiency (e.g. a List<byte> as a byte[] backing it, rather than an array of boxed bytes.)
  • C# doesn't have checked exceptions
  • Java doesn't allow the creation of user-defined value types
  • Java doesn't have operator and conversion overloading
  • Java doesn't have iterator blocks for simple implemetation of iterators
  • Java doesn't have anything like LINQ
  • Partly due to not having delegates, Java doesn't have anything quite like anonymous methods and lambda expressions. Anonymous inner classes usually fill these roles, but clunkily.
  • Java doesn't have expression trees
  • C# doesn't have anonymous inner classes
  • C# doesn't have Java's inner classes at all, in fact - all nested classes in C# are like Java's static nested classes
  • Java doesn't have static classes (which don't have any instance constructors, and can't be used for variables, parameters etc)
  • Java doesn't have any equivalent to the C# 3.0 anonymous types
  • Java doesn't have implicitly typed local variables
  • Java doesn't have extension methods
  • Java doesn't have object and collection initializer expressions
  • The access modifiers are somewhat different - in Java there's (currently) no direct equivalent of an assembly, so no idea of "internal" visibility; in C# there's no equivalent to the "default" visibility in Java which takes account of namespace (and inheritance)
  • The order of initialization in Java and C# is subtly different (C# executes variable initializers before the chained call to the base type's constructor)
  • Java doesn't have properties as part of the language; they're a convention of get/set/is methods
  • Java doesn't have the equivalent of "unsafe" code
  • Interop is easier in C# (and .NET in general) than Java's JNI
  • Java and C# have somewhat different ideas of enums. Java's are much more object-oriented.
  • Java has no preprocessor directives (#define, #if etc in C#).
  • Java has no equivalent of C#'s ref and out for passing parameters by reference
  • Java has no equivalent of partial types
  • C# interfaces cannot declare fields
  • Java has no unsigned integer types
  • Java has no language support for a decimal type. (java.math.BigDecimal provides something like System.Decimal - with differences - but there's no language support)
  • Java has no equivalent of nullable value types
  • Boxing in Java uses predefined (but "normal") reference types with particular operations on them. Boxing in C# and .NET is a more transparent affair, with a reference type being created for boxing by the CLR for any value type.

This is not exhaustive, but it covers everything I can think of off-hand.

Javascript: Easier way to format numbers?

There's the NUMBERFORMATTER jQuery plugin, details below:

https://code.google.com/p/jquery-numberformatter/

From the above link:

This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.

EDIT: Replaced the link with a more direct one.

commons httpclient - Adding query string parameters to GET/POST request

The HttpParams interface isn't there for specifying query string parameters, it's for specifying runtime behaviour of the HttpClient object.

If you want to pass query string parameters, you need to assemble them on the URL yourself, e.g.

new HttpGet(url + "key1=" + value1 + ...);

Remember to encode the values first (using URLEncoder).