Programs & Examples On #Min

Minimum value. Smallest, tiniest, least.

Remove NA values from a vector

You can call max(vector, na.rm = TRUE). More generally, you can use the na.omit() function.

Obtain smallest value from array in Javascript?

ES6 is the way of the future.

arr.reduce((a, b) => Math.min(a, b));

I prefer this form because it's easily generalized for other use cases

SQL: Group by minimum value in one field while selecting distinct rows

select 
    department, 
    min_salary, 
    (select s1.last_name from staff s1 where s1.salary=s3.min_salary ) lastname 
from 
    (select department, min (salary) min_salary from staff s2 group by s2.department) s3

How to exclude 0 from MIN formula Excel

Throwing my hat in the ring:

1) First we execute the NOT function on a set of integers, evaluating non-zeros to 0 and zeros to 1

2) Then we search for the MAX in our original set of integers

3) Then we multiply each number in the set generated in step 1 by the MAX found in step 2, setting ones as 0 and zeros as MAX

4) Then we add the set generated in step 3 to our original set

5) Lastly we look for the MIN in the set generated in step 4

{=MIN((NOT(A1:A5000)* MAX(A1:A5000))+ A1:A5000)}

If you know the rough range of numbers, you can replace the MAX(RANGE) with a constant. This speeds things up slightly, still not enough to compete with the faster functions.


Also did a quick test run on data set of 5000 integers with formula being executed 5000 times.

{=SMALL(A1:A5000,COUNTIF(A1:A5000,0)+1)}

1.700859 Seconds Elapsed | 5,301,902 Ticks Elapsed

{=SMALL(A1:A5000,INDEX(FREQUENCY(A1:A5000,0),1)+1)}

1.935807 Seconds Elapsed | 6,034,279 Ticks Elapsed

{=MIN((NOT(A1:A5000)* MAX(A1:A5000))+ A1:A5000)}

3.127774 Seconds Elapsed | 9,749,865 Ticks Elapsed

{=MIN(If(A1:A5000>0,A1:A5000))}

3.287850 Seconds Elapsed | 10,248,852 Ticks Elapsed

{"=MIN(((A1:A5000=0)* MAX(A1:A5000))+ A1:A5000)"}

3.328824 Seconds Elapsed | 10,376,576 Ticks Elapsed

{=MIN(IF(A1:A5000=0,MAX(A1:A5000),A1:A5000))}

3.394730 Seconds Elapsed | 10,582,017 Ticks Elapsed

Min and max value of input in angular4 application

You can write a directive to listen the change event on the input and reset the value to the min value if it is too low. StackBlitz

@HostListener('change') onChange() {
  const min = +this.elementRef.nativeElement.getAttribute('min');

  if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
    this.renderer2.setProperty(
      this.elementRef.nativeElement,
      'value',
      min + ''
    );
  }
}

Also listen for the ngModelChange event to do the same when the form value is set.

@HostListener('ngModelChange', ['$event'])
onModelChange(value: number) {
  const min = +this.elementRef.nativeElement.getAttribute('min');
  if (this.valueIsLessThanMin(min, value)) {
    const formControl = this.formControlName
      ? this.formControlName.control
      : this.formControlDirective.control;

    if (formControl) {
      if (formControl.updateOn === 'change') {
        console.warn(
          `minValueDirective: form control ${this.formControlName.name} is set to update on change
          this can cause issues with min update values.`
        );
      }
      formControl.reset(min);
    }
  }
}

Full code:

import {
  Directive,
  ElementRef,
  HostListener,
  Optional,
  Renderer2,
  Self
} from "@angular/core";
import { FormControlDirective, FormControlName } from "@angular/forms";

@Directive({
  // tslint:disable-next-line: directive-selector
  selector: "input[minValue][min][type=number]"
})
export class MinValueDirective {
  @HostListener("change") onChange() {
    const min = +this.elementRef.nativeElement.getAttribute("min");

    if (this.valueIsLessThanMin(min, +this.elementRef.nativeElement.value)) {
      this.renderer2.setProperty(
        this.elementRef.nativeElement,
        "value",
        min + ""
      );
    }
  }

  // if input is a form control validate on model change
  @HostListener("ngModelChange", ["$event"])
  onModelChange(value: number) {
    const min = +this.elementRef.nativeElement.getAttribute("min");
    if (this.valueIsLessThanMin(min, value)) {
      const formControl = this.formControlName
        ? this.formControlName.control
        : this.formControlDirective.control;

      if (formControl) {
        if (formControl.updateOn === "change") {
          console.warn(
            `minValueDirective: form control ${
              this.formControlName.name
            } is set to update on change
              this can cause issues with min update values.`
          );
        }
        formControl.reset(min);
      }
    }
  }

  constructor(
    private elementRef: ElementRef<HTMLInputElement>,
    private renderer2: Renderer2,
    @Optional() @Self() private formControlName: FormControlName,
    @Optional() @Self() private formControlDirective: FormControlDirective
  ) {}

  private valueIsLessThanMin(min: any, value: number): boolean {
    return typeof min === "number" && value && value < min;
  }
}

Make sure to use this with the form control set to updateOn blur or the user won't be able to enter a +1 digit number if the first digit is below the min value.

 this.formGroup = this.formBuilder.group({
    test: [
      null,
      {
        updateOn: 'blur',
        validators: [Validators.min(5)]
      }
    ]
  });

How can I get the max (or min) value in a vector?

In c++11, you can use some function like that:

int maxAt(std::vector<int>& vector_name) {
    int max = INT_MIN;
    for (auto val : vector_name) {
         if (max < val) max = val;
    }
    return max;
}

Use of min and max functions in C++

I always use the min and max macros for ints. I'm not sure why anyone would use fmin or fmax for integer values.

The big gotcha with min and max is that they're not functions, even if they look like them. If you do something like:

min (10, BigExpensiveFunctionCall())

That function call may get called twice depending on the implementation of the macro. As such, its best practice in my org to never call min or max with things that aren't a literal or variable.

Using std::max_element on a vector<double>

As others have said, std::max_element() and std::min_element() return iterators, which need to be dereferenced to obtain the value.

The advantage of returning an iterator (rather than just the value) is that it allows you to determine the position of the (first) element in the container with the maximum (or minimum) value.

For example (using C++11 for brevity):

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

int main()
{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    auto biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
}

This yields:

Max element is 5 at position 4
min element is 1 at position 0

Note:

Using std::minmax_element() as suggested in the comments above may be faster for large data sets, but may give slightly different results. The values for my example above would be the same, but the position of the "max" element would be 9 since...

If several elements are equivalent to the largest element, the iterator to the last such element is returned.

Get the key corresponding to the minimum value within a dictionary

Is this what you are looking for?

d = dict()
d[15.0]='fifteen'
d[14.0]='fourteen'
d[14.5]='fourteenandhalf'

print d[min(d.keys())]

Prints 'fourteen'

Most efficient way to find smallest of 3 numbers Java?

Let me first repeat what others already said, by quoting from the article "Structured Programming with go to Statements" by Donald Knuth:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

Yet we should not pass up our opportunities in that critical 3%. A good programmer will not be lulled into complacency by such reasoning, he will be wise to look carefully at the critical code; but only after that code has been identified.

(emphasis by me)

So if you have identified that a seemingly trivial operation like the computation of the minimum of three numbers is the actual bottleneck (that is, the "critical 3%") in your application, then you may consider optimizing it.

And in this case, this is actually possible: The Math#min(double,double) method in Java has very special semantics:

Returns the smaller of two double values. That is, the result is the value closer to negative infinity. If the arguments have the same value, the result is that same value. If either value is NaN, then the result is NaN. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero. If one argument is positive zero and the other is negative zero, the result is negative zero.

One can have a look at the implementation, and see that it's actually rather complex:

public static double min(double a, double b) {
    if (a != a)
        return a;   // a is NaN
    if ((a == 0.0d) &&
        (b == 0.0d) &&
        (Double.doubleToRawLongBits(b) == negativeZeroDoubleBits)) {
        // Raw conversion ok since NaN can't map to -0.0.
        return b;
    }
    return (a <= b) ? a : b;
}

Now, it may be important to point out that this behavior is different from a simple comparison. This can easily be examined with the following example:

public class MinExample
{
    public static void main(String[] args)
    {
        test(0.0, 1.0);
        test(1.0, 0.0);
        test(-0.0, 0.0);
        test(Double.NaN, 1.0);
        test(1.0, Double.NaN);
    }

    private static void test(double a, double b)
    {
        double minA = Math.min(a, b);
        double minB = a < b ? a : b;
        System.out.println("a: "+a);
        System.out.println("b: "+b);
        System.out.println("minA "+minA);
        System.out.println("minB "+minB);
        if (Double.doubleToRawLongBits(minA) !=
            Double.doubleToRawLongBits(minB))
        {
            System.out.println(" -> Different results!");
        }
        System.out.println();
    }
}

However: If the treatment of NaN and positive/negative zero is not relevant for your application, you can replace the solution that is based on Math.min with a solution that is based on a simple comparison, and see whether it makes a difference.

This will, of course, be application dependent. Here is a simple, artificial microbenchmark (to be taken with a grain of salt!)

import java.util.Random;

public class MinPerformance
{
    public static void main(String[] args)
    {
        bench();
    }

    private static void bench()
    {
        int runs = 1000;
        for (int size=10000; size<=100000; size+=10000)
        {
            Random random = new Random(0);
            double data[] = new double[size];
            for (int i=0; i<size; i++)
            {
                data[i] = random.nextDouble();
            }
            benchA(data, runs);
            benchB(data, runs);
        }
    }

    private static void benchA(double data[], int runs)
    {
        long before = System.nanoTime();
        double sum = 0;
        for (int r=0; r<runs; r++)
        {
            for (int i=0; i<data.length-3; i++)
            {
                sum += minA(data[i], data[i+1], data[i+2]);
            }
        }
        long after = System.nanoTime();
        System.out.println("A: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
    }

    private static void benchB(double data[], int runs)
    {
        long before = System.nanoTime();
        double sum = 0;
        for (int r=0; r<runs; r++)
        {
            for (int i=0; i<data.length-3; i++)
            {
                sum += minB(data[i], data[i+1], data[i+2]);
            }
        }
        long after = System.nanoTime();
        System.out.println("B: length "+data.length+", time "+(after-before)/1e6+", result "+sum);
    }

    private static double minA(double a, double b, double c)
    {
        return Math.min(a, Math.min(b, c));
    }

    private static double minB(double a, double b, double c)
    {
        if (a < b)
        {
            if (a < c)
            {
                return a;
            }
            return c;
        }
        if (b < c)
        {
            return b;
        }
        return c;
    }
}

(Disclaimer: Microbenchmarking in Java is an art, and for more reliable results, one should consider using JMH or Caliper).

Running this with JRE 1.8.0_31 may result in something like

....
A: length 90000, time 545.929078, result 2.247805342620906E7
B: length 90000, time 441.999193, result 2.247805342620906E7
A: length 100000, time 608.046928, result 2.5032781001456387E7
B: length 100000, time 493.747898, result 2.5032781001456387E7

This at least suggests that it might be possible to squeeze out a few percent here (again, in a very artifical example).


Analyzing this further, by looking at the hotspot disassembly output created with

java -server -XX:+UnlockDiagnosticVMOptions -XX:+TraceClassLoading -XX:+LogCompilation -XX:+PrintAssembly MinPerformance

one can see the optimized versions of both methods, minA and minB.

First, the output for the method that uses Math.min:

Decoding compiled method 0x0000000002992310:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000001c010910} &apos;minA&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;
  # parm0:    xmm0:xmm0   = double
  # parm1:    xmm1:xmm1   = double
  # parm2:    xmm2:xmm2   = double
  #           [sp+0x60]  (sp of caller)
  0x0000000002992480: mov    %eax,-0x6000(%rsp)
  0x0000000002992487: push   %rbp
  0x0000000002992488: sub    $0x50,%rsp
  0x000000000299248c: movabs $0x1c010cd0,%rsi
  0x0000000002992496: mov    0x8(%rsi),%edi
  0x0000000002992499: add    $0x8,%edi
  0x000000000299249c: mov    %edi,0x8(%rsi)
  0x000000000299249f: movabs $0x1c010908,%rsi   ; {metadata({method} {0x000000001c010910} &apos;minA&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;)}
  0x00000000029924a9: and    $0x3ff8,%edi
  0x00000000029924af: cmp    $0x0,%edi
  0x00000000029924b2: je     0x00000000029924e8  ;*dload_0
                        ; - MinPerformance::minA@0 (line 58)

  0x00000000029924b8: vmovsd %xmm0,0x38(%rsp)
  0x00000000029924be: vmovapd %xmm1,%xmm0
  0x00000000029924c2: vmovapd %xmm2,%xmm1       ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)

  0x00000000029924c6: nop
  0x00000000029924c7: callq  0x00000000028c6360  ; OopMap{off=76}
                        ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)
                        ;   {static_call}
  0x00000000029924cc: vmovapd %xmm0,%xmm1       ;*invokestatic min
                        ; - MinPerformance::minA@4 (line 58)

  0x00000000029924d0: vmovsd 0x38(%rsp),%xmm0   ;*invokestatic min
                        ; - MinPerformance::minA@7 (line 58)

  0x00000000029924d6: nop
  0x00000000029924d7: callq  0x00000000028c6360  ; OopMap{off=92}
                        ;*invokestatic min
                        ; - MinPerformance::minA@7 (line 58)
                        ;   {static_call}
  0x00000000029924dc: add    $0x50,%rsp
  0x00000000029924e0: pop    %rbp
  0x00000000029924e1: test   %eax,-0x27623e7(%rip)        # 0x0000000000230100
                        ;   {poll_return}
  0x00000000029924e7: retq
  0x00000000029924e8: mov    %rsi,0x8(%rsp)
  0x00000000029924ed: movq   $0xffffffffffffffff,(%rsp)
  0x00000000029924f5: callq  0x000000000297e260  ; OopMap{off=122}
                        ;*synchronization entry
                        ; - MinPerformance::minA@-1 (line 58)
                        ;   {runtime_call}
  0x00000000029924fa: jmp    0x00000000029924b8
  0x00000000029924fc: nop
  0x00000000029924fd: nop
  0x00000000029924fe: mov    0x298(%r15),%rax
  0x0000000002992505: movabs $0x0,%r10
  0x000000000299250f: mov    %r10,0x298(%r15)
  0x0000000002992516: movabs $0x0,%r10
  0x0000000002992520: mov    %r10,0x2a0(%r15)
  0x0000000002992527: add    $0x50,%rsp
  0x000000000299252b: pop    %rbp
  0x000000000299252c: jmpq   0x00000000028ec620  ; {runtime_call}
  0x0000000002992531: hlt
  0x0000000002992532: hlt
  0x0000000002992533: hlt
  0x0000000002992534: hlt
  0x0000000002992535: hlt
  0x0000000002992536: hlt
  0x0000000002992537: hlt
  0x0000000002992538: hlt
  0x0000000002992539: hlt
  0x000000000299253a: hlt
  0x000000000299253b: hlt
  0x000000000299253c: hlt
  0x000000000299253d: hlt
  0x000000000299253e: hlt
  0x000000000299253f: hlt
[Stub Code]
  0x0000000002992540: nop                       ;   {no_reloc}
  0x0000000002992541: nop
  0x0000000002992542: nop
  0x0000000002992543: nop
  0x0000000002992544: nop
  0x0000000002992545: movabs $0x0,%rbx          ; {static_stub}
  0x000000000299254f: jmpq   0x000000000299254f  ; {runtime_call}
  0x0000000002992554: nop
  0x0000000002992555: movabs $0x0,%rbx          ; {static_stub}
  0x000000000299255f: jmpq   0x000000000299255f  ; {runtime_call}
[Exception Handler]
  0x0000000002992564: callq  0x000000000297b9e0  ; {runtime_call}
  0x0000000002992569: mov    %rsp,-0x28(%rsp)
  0x000000000299256e: sub    $0x80,%rsp
  0x0000000002992575: mov    %rax,0x78(%rsp)
  0x000000000299257a: mov    %rcx,0x70(%rsp)
  0x000000000299257f: mov    %rdx,0x68(%rsp)
  0x0000000002992584: mov    %rbx,0x60(%rsp)
  0x0000000002992589: mov    %rbp,0x50(%rsp)
  0x000000000299258e: mov    %rsi,0x48(%rsp)
  0x0000000002992593: mov    %rdi,0x40(%rsp)
  0x0000000002992598: mov    %r8,0x38(%rsp)
  0x000000000299259d: mov    %r9,0x30(%rsp)
  0x00000000029925a2: mov    %r10,0x28(%rsp)
  0x00000000029925a7: mov    %r11,0x20(%rsp)
  0x00000000029925ac: mov    %r12,0x18(%rsp)
  0x00000000029925b1: mov    %r13,0x10(%rsp)
  0x00000000029925b6: mov    %r14,0x8(%rsp)
  0x00000000029925bb: mov    %r15,(%rsp)
  0x00000000029925bf: movabs $0x515db148,%rcx   ; {external_word}
  0x00000000029925c9: movabs $0x2992569,%rdx    ; {internal_word}
  0x00000000029925d3: mov    %rsp,%r8
  0x00000000029925d6: and    $0xfffffffffffffff0,%rsp
  0x00000000029925da: callq  0x00000000512a9020  ; {runtime_call}
  0x00000000029925df: hlt
[Deopt Handler Code]
  0x00000000029925e0: movabs $0x29925e0,%r10    ; {section_word}
  0x00000000029925ea: push   %r10
  0x00000000029925ec: jmpq   0x00000000028c7340  ; {runtime_call}
  0x00000000029925f1: hlt
  0x00000000029925f2: hlt
  0x00000000029925f3: hlt
  0x00000000029925f4: hlt
  0x00000000029925f5: hlt
  0x00000000029925f6: hlt
  0x00000000029925f7: hlt

One can see that the treatment of special cases involves some effort - compared to the output that uses simple comparisons, which is rather straightforward:

Decoding compiled method 0x0000000002998790:
Code:
[Entry Point]
[Verified Entry Point]
[Constants]
  # {method} {0x000000001c0109c0} &apos;minB&apos; &apos;(DDD)D&apos; in &apos;MinPerformance&apos;
  # parm0:    xmm0:xmm0   = double
  # parm1:    xmm1:xmm1   = double
  # parm2:    xmm2:xmm2   = double
  #           [sp+0x20]  (sp of caller)
  0x00000000029988c0: sub    $0x18,%rsp
  0x00000000029988c7: mov    %rbp,0x10(%rsp) ;*synchronization entry
                        ; - MinPerformance::minB@-1 (line 63)

  0x00000000029988cc: vucomisd %xmm0,%xmm1
  0x00000000029988d0: ja     0x00000000029988ee  ;*ifge
                        ; - MinPerformance::minB@3 (line 63)

  0x00000000029988d2: vucomisd %xmm1,%xmm2
  0x00000000029988d6: ja     0x00000000029988de  ;*ifge
                        ; - MinPerformance::minB@22 (line 71)

  0x00000000029988d8: vmovapd %xmm2,%xmm0
  0x00000000029988dc: jmp    0x00000000029988e2
  0x00000000029988de: vmovapd %xmm1,%xmm0 ;*synchronization entry
                        ; - MinPerformance::minB@-1 (line 63)

  0x00000000029988e2: add    $0x10,%rsp
  0x00000000029988e6: pop    %rbp
  0x00000000029988e7: test   %eax,-0x27688ed(%rip)        # 0x0000000000230000
                        ;   {poll_return}
  0x00000000029988ed: retq
  0x00000000029988ee: vucomisd %xmm0,%xmm2
  0x00000000029988f2: ja     0x00000000029988e2  ;*ifge
                        ; - MinPerformance::minB@10 (line 65)

  0x00000000029988f4: vmovapd %xmm2,%xmm0
  0x00000000029988f8: jmp    0x00000000029988e2
  0x00000000029988fa: hlt
  0x00000000029988fb: hlt
  0x00000000029988fc: hlt
  0x00000000029988fd: hlt
  0x00000000029988fe: hlt
  0x00000000029988ff: hlt
[Exception Handler]
[Stub Code]
  0x0000000002998900: jmpq   0x00000000028ec920  ;   {no_reloc}
[Deopt Handler Code]
  0x0000000002998905: callq  0x000000000299890a
  0x000000000299890a: subq   $0x5,(%rsp)
  0x000000000299890f: jmpq   0x00000000028c7340  ; {runtime_call}
  0x0000000002998914: hlt
  0x0000000002998915: hlt
  0x0000000002998916: hlt
  0x0000000002998917: hlt

Whether or not there are cases where such an optimization really makes a difference in an application is hard to tell. But at least, the bottom line is:

  • The Math#min(double,double) method is not the same as a simple comparison, and the treatment of the special cases does not come for free
  • There are cases where the special case treatment that is done by Math#min is not necessary, and then a comparison-based approach may be more efficient
  • As already pointed out in other answers: In most cases, the performance difference will not matter. However, for this particular example, one should probably create a utility method min(double,double,double) anyhow, for better convenience and readability, and then it would be easy to do two runs with the different implementations, and see whether it really affects the performance.

(Side note: The integer type methods, like Math.min(int,int) actually are a simple comparison - so I would expect no difference for these).

Getting the index of the returned max or min item using max()/min() on a list

A simple way for finding the indexes with minimal value in a list if you don't want to import additional modules:

min_value = min(values)
indexes_with_min_value = [i for i in range(0,len(values)) if values[i] == min_value]

Then choose for example the first one:

choosen = indexes_with_min_value[0]

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

from __future__ import division

somelist =  [1,12,2,53,23,6,17] 
max_value = max(somelist)
min_value = min(somelist)
avg_value = 0 if len(somelist) == 0 else sum(somelist)/len(somelist)

If you want to manually find the minimum as a function:

somelist =  [1,12,2,53,23,6,17] 

def my_min_function(somelist):
    min_value = None
    for value in somelist:
        if not min_value:
            min_value = value
        elif value < min_value:
            min_value = value
    return min_value

Python 3.4 introduced the statistics package, which provides mean and additional stats:

from statistics import mean, median

somelist =  [1,12,2,53,23,6,17]
avg_value = mean(somelist)
median_value = median(somelist)

What's the best way to select the minimum value from several columns?

The best way to do that is probably not to do it - it's strange that people insist on storing their data in a way that requires SQL "gymnastics" to extract meaningful information, when there are far easier ways to achieve the desired result if you just structure your schema a little better :-)

The right way to do this, in my opinion, is to have the following table:

ID    Col    Val
--    ---    ---
 1      1      3
 1      2     34
 1      3     76

 2      1     32
 2      2    976
 2      3     24

 3      1      7
 3      2    235
 3      3      3

 4      1    245
 4      2      1
 4      3    792

with ID/Col as the primary key (and possibly Col as an extra key, depending on your needs). Then your query becomes a simple select min(val) from tbl and you can still treat the individual 'old columns' separately by using where col = 2 in your other queries. This also allows for easy expansion should the number of 'old columns' grow.

This makes your queries so much easier. The general guideline I tend to use is, if you ever have something that looks like an array in a database row, you're probably doing something wrong and should think about restructuring the data.


However, if for some reason you can't change those columns, I'd suggest using insert and update triggers and add another column which these triggers set to the minimum on Col1/2/3. This will move the 'cost' of the operation away from the select to the update/insert where it belongs - most database tables in my experience are read far more often than written so incurring the cost on write tends to be more efficient over time.

In other words, the minimum for a row only changes when one of the other columns change, so that's when you should be calculating it, not every time you select (which is wasted if the data isn't changing). You would then end up with a table like:

ID   Col1   Col2   Col3   MinVal
--   ----   ----   ----   ------
 1      3     34     76        3
 2     32    976     24       24
 3      7    235      3        3
 4    245      1    792        1

Any other option that has to make decisions at select time is usually a bad idea performance-wise, since the data only changes on insert/update - the addition of another column takes up more space in the DB and will be slightly slower for the inserts and updates but can be much faster for selects - the preferred approach should depend on your priorities there but, as stated, most tables are read far more often than they're written.

How do I get the max and min values from a set of numbers entered?

//for excluding zero
public class SmallestInt {

    public static void main(String[] args) {

        Scanner input= new Scanner(System.in);

        System.out.println("enter number");
        int val=input.nextInt();
        int min=val;

        //String notNull;

        while(input.hasNextInt()==true)
        {
            val=input.nextInt();
            if(val<min)
                min=val;
        }
        System.out.println("min is: "+min);
    }
}

MIN and MAX in C

The maximum of two integers a and b is (int)(0.5((a+b)+abs(a-b))). This may also work with (double) and fabs(a-b) for doubles (similar for floats)

Min/Max of dates in an array?

Code is tested with IE,FF,Chrome and works properly:

var dates=[];
dates.push(new Date("2011/06/25"))
dates.push(new Date("2011/06/26"))
dates.push(new Date("2011/06/27"))
dates.push(new Date("2011/06/28"))
var maxDate=new Date(Math.max.apply(null,dates));
var minDate=new Date(Math.min.apply(null,dates));

Integrating CSS star rating into an HTML form

This is very easy to use, just copy-paste the code. You can use your own star image in background.

I have created a variable var userRating. you can use this variable to get value from stars.

Enjoy!! :)

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    // Check Radio-box_x000D_
    $(".rating input:radio").attr("checked", false);_x000D_
_x000D_
    $('.rating input').click(function () {_x000D_
        $(".rating span").removeClass('checked');_x000D_
        $(this).parent().addClass('checked');_x000D_
    });_x000D_
_x000D_
    $('input:radio').change(_x000D_
      function(){_x000D_
        var userRating = this.value;_x000D_
        alert(userRating);_x000D_
    }); _x000D_
});
_x000D_
.rating {_x000D_
    float:left;_x000D_
    width:300px;_x000D_
}_x000D_
.rating span { float:right; position:relative; }_x000D_
.rating span input {_x000D_
    position:absolute;_x000D_
    top:0px;_x000D_
    left:0px;_x000D_
    opacity:0;_x000D_
}_x000D_
.rating span label {_x000D_
    display:inline-block;_x000D_
    width:30px;_x000D_
    height:30px;_x000D_
    text-align:center;_x000D_
    color:#FFF;_x000D_
    background:#ccc;_x000D_
    font-size:30px;_x000D_
    margin-right:2px;_x000D_
    line-height:30px;_x000D_
    border-radius:50%;_x000D_
    -webkit-border-radius:50%;_x000D_
}_x000D_
.rating span:hover ~ span label,_x000D_
.rating span:hover label,_x000D_
.rating span.checked label,_x000D_
.rating span.checked ~ span label {_x000D_
    background:#F90;_x000D_
    color:#FFF;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="rating">_x000D_
    <span><input type="radio" name="rating" id="str5" value="5"><label for="str5"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str4" value="4"><label for="str4"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str3" value="3"><label for="str3"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str2" value="2"><label for="str2"></label></span>_x000D_
    <span><input type="radio" name="rating" id="str1" value="1"><label for="str1"></label></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

Cannot create SSPI context

In vb.net, if you are using a linked server than check your connection string. Integrated Security=true; doesn't work in all SQL providers, it throws an exception when used with the OleDb provider. So basically Integrated Security=SSPI; is preferred since works with both SQLClient & OleDB provide. If you still hit with error, remove the syntax completely.

Why shouldn't `&apos;` be used to escape single quotes?

&quot; is on the official list of valid HTML 4 entities, but &apos; is not.

From C.16. The Named Character Reference ':

The named character reference &apos; (the apostrophe, U+0027) was introduced in XML 1.0 but does not appear in HTML. Authors should therefore use &#39; instead of &apos; to work as expected in HTML 4 user agents.

How to get index of an item in java.util.Set

How about add the strings to a hashtable where the value is an index:

  Hashtable<String, Integer> itemIndex = new Hashtable<>();
  itemIndex.put("First String",1);
  itemIndex.put("Second String",2);
  itemIndex.put("Third String",3);

  int indexOfThirdString = itemIndex.get("Third String");

Run function in script from command line (Node JS)

Sometimes you want to run a function via CLI, sometimes you want to require it from another module. Here's how to do both.

// file to run
const runMe = () => {}
if (require.main === module) {
  runMe()
} 
module.exports = runMe

Android ListView with Checkbox and all clickable

this code works on my proyect and i can select the listview item and checkbox

<?xml version="1.0" encoding="utf-8"?>
<!-- Single List Item Design -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:clickable="true" >

    <TextView
        android:id="@+id/label"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="4" />

    <CheckBox
        android:id="@+id/check"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:focusable="false"
        android:text="" >
    </CheckBox>

</LinearLayout>

How to solve java.lang.NoClassDefFoundError?

It happens a lot with my genymotion devices. Make sure you have a good amount of memory available on your drive where Genymotion is installed.

How to convert UTF8 string to byte array?

function convertByte()
{
    var c=document.getElementById("str").value;
    var arr = [];
    var i=0;
    for(var ind=0;ind<c.length;ind++)
    {
        arr[ind]=c.charCodeAt(i);
        i++;
    }    
    document.getElementById("result").innerHTML="The converted value is "+arr.join("");    
}

Correct way to populate an Array with a Range in Ruby

Check this:

a = [*(1..10), :top, *10.downto( 1 )]

Valid characters in a Java class name

You can have almost any character, including most Unicode characters! The exact definition is in the Java Language Specification under section 3.8: Identifiers.

An identifier is an unlimited-length sequence of Java letters and Java digits, the first of which must be a Java letter. ...

Letters and digits may be drawn from the entire Unicode character set, ... This allows programmers to use identifiers in their programs that are written in their native languages.

An identifier cannot have the same spelling (Unicode character sequence) as a keyword (§3.9), boolean literal (§3.10.3), or the null literal (§3.10.7), or a compile-time error occurs.

However, see this question for whether or not you should do that.

difference between new String[]{} and new String[] in java

TL;DR

  • An array variable has to be typed T[]
    (note that T can be an arry type itself -> multidimensional arrays)
  • The length of the array must be determined either by:
    • giving it an explicit size
      (can be int constant or int expression, see n below)
    • initializing all the values inside the array
      (length is implicitly calculated from given elements)
  • Any variable that is typed T[] has one read-only field: length and an index operator [int] for reading/writing data at certain indices.

Replies

1. String[] array= new String[]{}; what is the use of { } here ?

It initializes the array with the values between { }. In this case 0 elements, so array.length == 0 and array[0] throws IndexOutOfBoundsException: 0.

2. what is the diff between String array=new String[]; and String array=new String[]{};

The first won't compile for two reasons while the second won't compile for one reason. The common reason is that the type of the variable array has to be an array type: String[] not just String. Ignoring that (probably just a typo) the difference is:

new String[]   // size not known, compile error
new String[]{} // size is known, it has 0 elements, listed inside {}
new String[0]  // size is known, it has 0 elements, explicitly sized

3. when am writing String array=new String[10]{}; got error why ?

(Again, ignoring the missing [] before array) In this case you're over-eager to tell Java what to do and you're giving conflicting data. First you tell Java that you want 10 elements for the array to hold and then you're saying you want the array to be empty via {}. Just make up your mind and use one of those - Java thinks.

help me i am confused

Examples

String[] noStrings = new String[0];
String[] noStrings = new String[] { };
String[] oneString = new String[] { "atIndex0" };
String[] oneString = new String[1];
String[] oneString = new String[] { null }; // same as previous
String[] threeStrings = new String[] { "atIndex0", "atIndex1", "atIndex2" };
String[] threeStrings = new String[] { "atIndex0", null, "atIndex2" }; // you can skip an index
String[] threeStrings = new String[3];
String[] threeStrings = new String[] { null, null, null }; // same as previous
int[] twoNumbers = new int[2];
int[] twoNumbers = new int[] { 0, 0 }; // same as above
int[] twoNumbers = new int[] { 1, 2 }; // twoNumbers.length == 2 && twoNumbers[0] == 1 && twoNumbers[1] == 2
int n = 2;
int[] nNumbers = new int[n]; // same as [2] and { 0, 0 }
int[] nNumbers = new int[2*n]; // same as new int[4] if n == 2

(Here, "same as" means it will construct the same array.)

Why does ++[[]][+[]]+[+[]] return the string "10"?

Step by steps of that, + turn value to a number and if you add to an empty array +[]...as it's empty and is equal to 0, it will

So from there, now look into your code, it's ++[[]][+[]]+[+[]]...

And there is plus between them ++[[]][+[]] + [+[]]

So these [+[]] will return [0] as they have an empty array which gets converted to 0 inside the other array...

So as imagine, the first value is a 2-dimensional array with one array inside... so [[]][+[]] will be equal to [[]][0] which will return []...

And at the end ++ convert it and increase it to 1...

So you can imagine, 1 + "0" will be "10"...

Why does return the string “10”?

Unable to connect to SQL Server instance remotely

  1. Open the SQL Server Configuration Manager.... 2.Check wheather TCP and UDP are running or not.... 3.If not running , Please enable them and also check the SQL Server Browser is running or not.If not running turn it on.....

  2. Next you have to check which ports TCP and UDP is using. You have to open those ports from your windows firewall.....

5.Click here to see the steps to open a specific port in windows firewall....

  1. Now SQL Server is ready to access over LAN.......

  2. If you wan to access it remotely (over internet) , you have to do another job that is 'Port Forwarding'. You have open the ports TCP and UDP is using in SQL Server on your router. Now the configuration of routers are different. If you give me the details of your router (i. e name of the company and version ) , I can show you the steps how to forward a specific port.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

In the middle of the stack trace, lost in the "reflection" junk, you can find the root cause:

The specified datastore driver ("com.mysql.jdbc.Driver") was not found in the CLASSPATH. Please check your CLASSPATH specification, and the name of the driver.

How to combine multiple conditions to subset a data-frame using "OR"?

Just for the sake of completeness, we can use the operators [ and [[:

set.seed(1)
df <- data.frame(v1 = runif(10), v2 = letters[1:10])

Several options

df[df[1] < 0.5 | df[2] == "g", ] 
df[df[[1]] < 0.5 | df[[2]] == "g", ] 
df[df["v1"] < 0.5 | df["v2"] == "g", ]

df$name is equivalent to df[["name", exact = FALSE]]

Using dplyr:

library(dplyr)
filter(df, v1 < 0.5 | v2 == "g")

Using sqldf:

library(sqldf)
sqldf('SELECT *
      FROM df 
      WHERE v1 < 0.5 OR v2 = "g"')

Output for the above options:

          v1 v2
1 0.26550866  a
2 0.37212390  b
3 0.20168193  e
4 0.94467527  g
5 0.06178627  j

How to get the path of running java program

You actually do not want to get the path to your main class. According to your example you want to get the current working directory, i.e. directory where your program started. In this case you can just say new File(".").getAbsolutePath()

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

How to send multiple data fields via Ajax?

Try with quotes:

data: {"status": status, "name": name}

It must work fine.

Double border with different color

you can add infinite borders using box-shadow using css3 suppose you want to apply multiple borders on one div then code is like:

div {
    border-radius: 4px;
    /* #1 */
    border: 5px solid hsl(0, 0%, 40%);
    
    /* #2 */
    padding: 5px;
    background: hsl(0, 0%, 20%);
    
    /* #3 */
    outline: 5px solid hsl(0, 0%, 60%);
    
    /* #4 AND INFINITY!!! (CSS3 only) */
    box-shadow:
        0 0 0 10px red,
        0 0 0 15px orange,
        0 0 0 20px yellow,
        0 0 0 25px green,
        0 0 0 30px blue;
}

What is the string concatenation operator in Oracle?

Using CONCAT(CONCAT(,),) worked for me when concatenating more than two strings.

My problem required working with date strings (only) and creating YYYYMMDD from YYYY-MM-DD as follows (i.e. without converting to date format):

CONCAT(CONCAT(SUBSTR(DATECOL,1,4),SUBSTR(DATECOL,6,2)),SUBSTR(DATECOL,9,2)) AS YYYYMMDD

Pull new updates from original GitHub repository into forked GitHub repository

If you want to do it without cli, you can do it fully on Github website.

  1. Go to your fork repository.
  2. Click on New pull request.
  3. Make sure to set your fork as the base repository, and the original (upstream) repository as head repository. Usually you only want to sync the master branch.
  4. Create new pull request.
  5. Select the arrow to the right of the merging button, and make sure to choose rebase instead of merge. Then click the button. This way, it will not produce unnecessary merge commit.
  6. Done.

java build path problems

Go for the second option, Edit the project to agree with the latest JDK

  • Right click "JRE System Library [J2SE 1.5] in your project"
  • Choose "Properties"
  • Select "Workspace default JRE (jdk1.6)

enter image description here

Best way to encode text data for XML

Microsoft's AntiXss library AntiXssEncoder Class in System.Web.dll has methods for this:

AntiXss.XmlEncode(string s)
AntiXss.XmlAttributeEncode(string s)

it has HTML as well:

AntiXss.HtmlEncode(string s)
AntiXss.HtmlAttributeEncode(string s)

Encode URL in JavaScript?

Encode URL String

    var url = $(location).attr('href'); //get current url
    //OR
    var url = 'folder/index.html?param=#23dd&noob=yes'; //or specify one

var encodedUrl = encodeURIComponent(url); console.log(encodedUrl); //outputs folder%2Findex.html%3Fparam%3D%2323dd%26noob%3Dyes for more info go http://www.sitepoint.com/jquery-decode-url-string

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

incompatible character encodings: ASCII-8BIT and UTF-8

it's very strange that I met this problem because I forgot specify the 'type' parameter. e.g.:

add_column :cms_push_msgs, :android_title

which should be:

add_column :cms_push_msgs, :android_content, :string 

When to encode space to plus (+) or %20?

So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.

The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.

Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').

But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.

Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)

But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.

C++ String Declaring

Preferred string type in C++ is string, defined in namespace std, in header <string> and you can initialize it like this for example:

#include <string>

int main()
{
   std::string str1("Some text");
   std::string str2 = "Some text";
}

More about it you can find here and here.

Comparing Class Types in Java

Try this:

MyObject obj = new MyObject();
if(obj instanceof MyObject){System.out.println("true");} //true

Because of inheritance this is valid for interfaces, too:

class Animal {}
class Dog extends Animal {}    

Dog obj = new Dog();
Animal animal = new Dog();
if(obj instanceof Animal){System.out.println("true");} //true
if(animal instanceof Animal){System.out.println("true");} //true
if(animal instanceof Dog){System.out.println("true");} //true

For further reading on instanceof: http://mindprod.com/jgloss/instanceof.html

$watch an object

The form object isn't changing, only the name property is

updated fiddle

function MyController($scope) {
$scope.form = {
    name: 'my name',
}

$scope.changeCount = 0;
$scope.$watch('form.name', function(newVal, oldVal){
    console.log('changed');
    $scope.changeCount++;
});
}

Failed to load resource 404 (Not Found) - file location error?

Looks like the path you gave doesn't have any bootstrap files in them.

href="~/lib/bootstrap/dist/css/bootstrap.min.css"

Make sure the files exist over there , else point the files to the correct path, which should be in your case

href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"

utf-8 special characters not displaying

If you're using PHP and none of the above worked (as it was my case), you need to set the locale with utf-8 encoding.

Like this

setlocale(LC_ALL, 'fr_CA.utf-8');

ViewPager PagerAdapter not updating the View

After a lot of searching for this problem, I found a really good solution that I think is the right way to go about this. Essentially, instantiateItem only gets called when the view is instantiated and never again unless the view is destroyed (this is what happens when you override the getItemPosition function to return POSITION_NONE). Instead, what you want to do is save the created views and either update them in the adapter, generate a get function so someone else can update it, or a set function which updates the adapter (my favorite).

So, in your MyViewPagerAdapter add a variable like:

private View updatableView;

an in your instantiateItem:

 public Object instantiateItem(View collection, int position) {
        updatableView = new TextView(ctx); //My change is here
        view.setText(data.get(position));
        ((ViewPager)collection).addView(view);
        return view;
    }

so, this way, you can create a function that will update your view:

public updateText(String txt)
{
    ((TextView)updatableView).setText(txt);
}

Hope this helps!

JWT (JSON Web Token) automatic prolongation of expiration

jwt-autorefresh

If you are using node (React / Redux / Universal JS) you can install npm i -S jwt-autorefresh.

This library schedules refresh of JWT tokens at a user calculated number of seconds prior to the access token expiring (based on the exp claim encoded in the token). It has an extensive test suite and checks for quite a few conditions to ensure any strange activity is accompanied by a descriptive message regarding misconfigurations from your environment.

Full example implementation

import autorefresh from 'jwt-autorefresh'

/** Events in your app that are triggered when your user becomes authorized or deauthorized. */
import { onAuthorize, onDeauthorize } from './events'

/** Your refresh token mechanism, returning a promise that resolves to the new access tokenFunction (library does not care about your method of persisting tokens) */
const refresh = () => {
  const init =  { method: 'POST'
                , headers: { 'Content-Type': `application/x-www-form-urlencoded` }
                , body: `refresh_token=${localStorage.refresh_token}&grant_type=refresh_token`
                }
  return fetch('/oauth/token', init)
    .then(res => res.json())
    .then(({ token_type, access_token, expires_in, refresh_token }) => {
      localStorage.access_token = access_token
      localStorage.refresh_token = refresh_token
      return access_token
    })
}

/** You supply a leadSeconds number or function that generates a number of seconds that the refresh should occur prior to the access token expiring */
const leadSeconds = () => {
  /** Generate random additional seconds (up to 30 in this case) to append to the lead time to ensure multiple clients dont schedule simultaneous refresh */
  const jitter = Math.floor(Math.random() * 30)

  /** Schedule autorefresh to occur 60 to 90 seconds prior to token expiration */
  return 60 + jitter
}

let start = autorefresh({ refresh, leadSeconds })
let cancel = () => {}
onAuthorize(access_token => {
  cancel()
  cancel = start(access_token)
})

onDeauthorize(() => cancel())

disclaimer: I am the maintainer

JQuery - Set Attribute value

"True" and "False" do not work, to disable, set to value disabled.

$('.someElement').attr('disabled', 'disabled');

To enable, remove.

$('.someElement').removeAttr('disabled');

Also, don't worry about multiple items being selected, jQuery will operate on all of them that match. If you need just one you can use many things :first, :last, nth, etc.

You are using name and not id as other mention -- remember, if you use id valid xhtml requires the ids be unique.

How can I make a .NET Windows Forms application that only runs in the System Tray?

Simply add

this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;

to your form object. You will see only an icon at system tray.

Boolean.parseBoolean("1") = false...?

I know this is an old thread, but what about borrowing from C syntax:

(o.get('uses_votes')).equals("1") ? true : false;

Matplotlib: Specify format of floats for tick labels

If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:

from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places

From the documentation:

class matplotlib.ticker.StrMethodFormatter(fmt)

Use a new-style format string (as used by str.format()) to format the tick.

The field used for the value must be labeled x and the field used for the position must be labeled pos.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How can I append a query parameter to an existing URL?

This can be done by using the java.net.URI class to construct a new instance using the parts from an existing one, this should ensure it conforms to URI syntax.

The query part will either be null or an existing string, so you can decide to append another parameter with & or start a new query.

public class StackOverflow26177749 {

    public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
        URI oldUri = new URI(uri);

        String newQuery = oldUri.getQuery();
        if (newQuery == null) {
            newQuery = appendQuery;
        } else {
            newQuery += "&" + appendQuery;  
        }

        return new URI(oldUri.getScheme(), oldUri.getAuthority(),
                oldUri.getPath(), newQuery, oldUri.getFragment());
    }

    public static void main(String[] args) throws Exception {
        System.out.println(appendUri("http://example.com", "name=John"));
        System.out.println(appendUri("http://example.com#fragment", "name=John"));
        System.out.println(appendUri("http://[email protected]", "name=John"));
        System.out.println(appendUri("http://[email protected]#fragment", "name=John"));
    }
}

Shorter alternative

public static URI appendUri(String uri, String appendQuery) throws URISyntaxException {
    URI oldUri = new URI(uri);
    return new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(),
            oldUri.getQuery() == null ? appendQuery : oldUri.getQuery() + "&" + appendQuery, oldUri.getFragment());
}

Output

http://example.com?name=John
http://example.com?name=John#fragment
http://[email protected]&name=John
http://[email protected]&name=John#fragment

Swift - iOS - Dates and times in different format

As already mentioned you have to use DateFormatter to format your Date objects. The easiest way to do it is creating a read-only computed property Date extension.


Read-Only Computed Properties

A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

Note:

You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.

You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:


extension Formatter {
    static let date = DateFormatter()
}

extension Date {
    var europeanFormattedEn_US : String {
        Formatter.date.calendar = Calendar(identifier: .iso8601)
        Formatter.date.locale   = Locale(identifier: "en_US_POSIX")
        Formatter.date.timeZone = .current
        Formatter.date.dateFormat = "dd/M/yyyy, H:mm"
        return Formatter.date.string(from: self)
    }
}

To convert it back you can create another read-only computed property but as a string extension:

 extension String {
    var date: Date? {
        return Formatter.date.date(from: self)
    }
    func dateFormatted(with dateFormat: String = "dd/M/yyyy, H:mm", calendar: Calendar = Calendar(identifier: .iso8601), defaultDate: Date? = nil, locale: Locale = Locale(identifier: "en_US_POSIX"), timeZone: TimeZone = .current) -> Date? {
        Formatter.date.calendar = calendar
        Formatter.date.defaultDate = defaultDate ?? calendar.date(bySettingHour: 12, minute: 0, second: 0, of: Date())
        Formatter.date.locale = locale
        Formatter.date.timeZone = timeZone
        Formatter.date.dateFormat = dateFormat
        return Formatter.date.date(from: self)
    }
}

Usage:

let dateFormatted = Date().europeanFormattedEn_US         //"29/9/2018, 16:16"
if let date = dateFormatted.date {
    print(date.description(with:.current)) // Saturday, September 29, 2018 at 4:16:00 PM Brasilia Standard Time\n"\
    date.europeanFormattedEn_US                         // "29/9/2018, 16:27"
}

let dateString = "14/7/2016"
if let date = dateString.toDateFormatted(with: "dd/M/yyyy") {
    print(date.description(with: .current))
 // Thursday, July 14, 2016 at 12:00:00 PM Brasilia Standard Time\n"
}

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
{ 
    return a.mProperty > b.mProperty; 
});

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

PHP MySQL Google Chart JSON - Complete Example

use this, it realy works:

data.addColumn no of your key, you can add more columns or remove

<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");

while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);

}

for($i=0;$i<count($arr1);$i++)
{
    $chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
     var data = new google.visualization.DataTable();
        data.addColumn("string", "YEAR");
        data.addColumn("number", "NO of record");

        data.addRows(<?php $data ?>);

        ]); 
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

Regular expression \p{L} and \p{N}

These are Unicode property shortcuts (\p{L} for Unicode letters, \p{N} for Unicode digits). They are supported by .NET, Perl, Java, PCRE, XML, XPath, JGSoft, Ruby (1.9 and higher) and PHP (since 5.1.0)

At any rate, that's a very strange regex. You should not be using alternation when a character class would suffice:

[\p{L}\p{N}_.-]*

Compare two MySQL databases

SQL Compare by RedGate http://www.red-gate.com/products/SQL_Compare/index.htm

DBDeploy to help with database change management in an automated fashion http://dbdeploy.com/

Using Get-childitem to get a list of files modified in the last 3 days

Very similar to previous responses, but the is from the current directory, looks at any file and only for ones that are 4 days old. This is what I needed for my research and the above answers were all very helpful. Thanks.

Get-ChildItem -Path . -Recurse| ? {$_.LastWriteTime -gt (Get-Date).AddDays(-4)}

How do I combine 2 javascript variables into a string

You can use the JavaScript String concat() Method,

var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"

Its syntax is:

string.concat(string1, string2, ..., stringX)

Extract substring from a string

use text untold class from android:
TextUtils.substring (charsequence source, int start, int end)

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

What does 'git blame' do?

The git blame command annotates lines with information from the revision which last modified the line, and... with Git 2.22 (Q2 2019), will do so faster, because of a performance fix around "git blame", especially in a linear history (which is the norm we should optimize for).

See commit f892014 (02 Apr 2019) by David Kastrup (fedelibre). (Merged by Junio C Hamano -- gitster -- in commit 4d8c4da, 25 Apr 2019)

blame.c: don't drop origin blobs as eagerly

When a parent blob already has chunks queued up for blaming, dropping the blob at the end of one blame step will cause it to get reloaded right away, doubling the amount of I/O and unpacking when processing a linear history.

Keeping such parent blobs in memory seems like a reasonable optimization that should incur additional memory pressure mostly when processing the merges from old branches.

How do I connect C# with Postgres?

Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):

In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.

Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.

Upload files from Java client to a HTTP server

public static String simSearchByImgURL(int  catid ,String imgurl) throws IOException{
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String result =null;
    try {
        HttpPost httppost = new HttpPost("http://api0.visualsearchapi.com:8084/vsearchtech/api/v1.0/apisim_search");
        StringBody catidBody = new StringBody(catid+"" , ContentType.TEXT_PLAIN);
        StringBody keyBody = new StringBody(APPKEY , ContentType.TEXT_PLAIN);
        StringBody langBody = new StringBody(LANG , ContentType.TEXT_PLAIN);
        StringBody fmtBody = new StringBody(FMT , ContentType.TEXT_PLAIN);
        StringBody imgurlBody = new StringBody(imgurl , ContentType.TEXT_PLAIN);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart("apikey", keyBody).addPart("catid", catidBody)
        .addPart("lang", langBody)
        .addPart("fmt", fmtBody)
        .addPart("imgurl", imgurlBody);
        HttpEntity reqEntity =  builder.build();
        httppost.setEntity(reqEntity);
        response = httpClient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
           // result = ConvertStreamToString(resEntity.getContent(), "UTF-8");
            String charset = "UTF-8";   
          String content=EntityUtils.toString(response.getEntity(), charset);   
            System.out.println(content);
        }
        EntityUtils.consume(resEntity);
    }catch(Exception e){
        e.printStackTrace();
    }finally {
        response.close();
        httpClient.close();
    }
    return result;
}

Hide div after a few seconds

You can try the .delay()

$(".formSentMsg").delay(3200).fadeOut(300);

call the div set the delay time in milliseconds and set the property you want to change, in this case I used .fadeOut() so it could be animated, but you can use .hide() as well.

http://api.jquery.com/delay/

How can I combine multiple nested Substitute functions in Excel?

=SUBSTITUTE(text, old_text, new_text)

if: a=!, b=@, c=#,... x=>, y=?, z=~, " "="     "
then: abcdefghijklmnopqrstuvwxyz ... try this out
equals: !@#$%^&*()-=+[]\{}|;:/<>?~     ...     ;}?     ;*(|     ]:;

RULES:

(1) text to substitute is in cell A1
(2) max 64 substitution levels (the formula below only has 27 levels [alphabet + space])
(2) "old_text" cannot also be a "new_text" (ie: if a=z .: z cannot be "old text")

---so if a=z,b=y,...y=b,z=a, then the result is 
---abcdefghijklmnopqrstuvwxyz = zyxwvutsrqponnopqrstuvwxyz (and z changes to a then changes back to z) ... (pattern starts to fail after m=n, n=m... and n becomes n)

The formula is:

=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"a","!"),"b","@"),"c","#"),"d","$"),"e","%"),"f","^"),"g","&"),"h","*"),"i","("),"j",")"),"k","-"),"l","="),"m","+"),"n","["),"o","]"),"p","\"),"q","{"),"r","}"),"s","|"),"t",";"),"u",":"),"v","/"),"w","<"),"x",">"),"y","?"),"z","~")," ","     ")

How to create checkbox inside dropdown?

_x000D_
_x000D_
var expanded = false;_x000D_
_x000D_
function showCheckboxes() {_x000D_
  var checkboxes = document.getElementById("checkboxes");_x000D_
  if (!expanded) {_x000D_
    checkboxes.style.display = "block";_x000D_
    expanded = true;_x000D_
  } else {_x000D_
    checkboxes.style.display = "none";_x000D_
    expanded = false;_x000D_
  }_x000D_
}
_x000D_
.multiselect {_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
.selectBox {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.selectBox select {_x000D_
  width: 100%;_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.overSelect {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
}_x000D_
_x000D_
#checkboxes {_x000D_
  display: none;_x000D_
  border: 1px #dadada solid;_x000D_
}_x000D_
_x000D_
#checkboxes label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#checkboxes label:hover {_x000D_
  background-color: #1e90ff;_x000D_
}
_x000D_
<form>_x000D_
  <div class="multiselect">_x000D_
    <div class="selectBox" onclick="showCheckboxes()">_x000D_
      <select>_x000D_
        <option>Select an option</option>_x000D_
      </select>_x000D_
      <div class="overSelect"></div>_x000D_
    </div>_x000D_
    <div id="checkboxes">_x000D_
      <label for="one">_x000D_
        <input type="checkbox" id="one" />First checkbox</label>_x000D_
      <label for="two">_x000D_
        <input type="checkbox" id="two" />Second checkbox</label>_x000D_
      <label for="three">_x000D_
        <input type="checkbox" id="three" />Third checkbox</label>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Open another page in php

header( 'Location: http://www.yoursite.com/new_page.html' );

in your process.php file

Check whether a value exists in JSON object

var JSONObject = {"animals": [{name:"cat"}, {name:"dog"}]};

 var Duplicate= JSONObject .find(s => s.name== "cat");
        if (typeof (Duplicate) === "undefined") {
           alert("Not Exist");
           return;
        } else {
            if (JSON.stringify(Duplicate).length > 0) {
                alert("Value Exist");
                return;
            }
        }

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

try {
    Class<?> c = Class.forName("java.lang.Daemons");
    Field maxField = c.getDeclaredField("MAX_FINALIZE_NANOS");
    maxField.setAccessible(true);
    maxField.set(null, Long.MAX_VALUE);
} catch (ClassNotFoundException e) {
    e.printStackTrace();
} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

I found that implementing a simple destroy() method to de-register any JDBC drivers works nicely.

/**
 * Destroys the servlet cleanly by unloading JDBC drivers.
 * 
 * @see javax.servlet.GenericServlet#destroy()
 */
public void destroy() {
    String prefix = getClass().getSimpleName() +" destroy() ";
    ServletContext ctx = getServletContext();
    try {
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while(drivers.hasMoreElements()) {
            DriverManager.deregisterDriver(drivers.nextElement());
        }
    } catch(Exception e) {
        ctx.log(prefix + "Exception caught while deregistering JDBC drivers", e);
    }
    ctx.log(prefix + "complete");
}

Action Bar's onClick listener for the Home button

Best way to customize Action bar onClickListener is onSupportNavigateUp()

This code will be helpful link for helping code

Regex to match only uppercase "words" with some exceptions

Why do you need to do this in one monster-regex? You can use actual code to implement some of these rules, and doing so would be much easier to modify if those requirements change later.

For example:

if(/^[A-Z0-9\s]*$/)
    # sentence is all uppercase, so just fail out
    return 0;

# Carry on with matching uppercase terms

jQuery hover and class selector

Since this is a menu, might as well take it to the next level, and clean up the HTML, and make it more semantic by using a list element:

HTML:

  <ul id="menu">
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
    <li><a href="#">Bla</a></li>
  </ul>

CSS:

#menu {
  margin: 0;
}
#menu li {
  float: left;
  list-style: none;
  margin: 0;
}
#menu li a {
  display: block;
  line-height:30px;
  width:100px;
  background-color:#000;
}
#menu li a:hover {
  background-color:#F00;
}

Get properties of a class

I am currently working on a Linq-like library for Typescript and wanted to implement something like GetProperties of C# in Typescript / Javascript. The more I work with Typescript and generics, the clearer picture I get of that you usually have to have an instantiated object with intialized properties to get any useful information out at runtime about properties of a class. But it would be nice to retrieve information anyways just from the constructor function object, or an array of objects and be flexible about this.

Here is what I ended up with for now.

First off, I define Array prototype method ('extension method' for you C# developers).

export { } //creating a module of below code
declare global {
  interface Array<T> {
    GetProperties<T>(TClass: Function, sortProps: boolean): string[];
} }

The GetProperties method then looks like this, inspired by madreason's answer.

if (!Array.prototype.GetProperties) {
  Array.prototype.GetProperties = function <T>(TClass: any = null, sortProps: boolean = false): string[] {
    if (TClass === null || TClass === undefined) {
      if (this === null || this === undefined || this.length === 0) {
        return []; //not possible to find out more information - return empty array
      }
    }
    // debugger
    if (TClass !== null && TClass !== undefined) {
      if (this !== null && this !== undefined) {
        if (this.length > 0) {
          let knownProps: string[] = Describer.describe(this[0]).Where(x => x !== null && x !== undefined);
          if (sortProps && knownProps !== null && knownProps !== undefined) {
            knownProps = knownProps.OrderBy(p => p);
          }
          return knownProps;
        }
        if (TClass !== null && TClass !== undefined) {
          let knownProps: string[] = Describer.describe(TClass).Where(x => x !== null && x !== undefined);
          if (sortProps && knownProps !== null && knownProps !== undefined) {
            knownProps = knownProps.OrderBy(p => p);
          }
          return knownProps;
        }
      }
    }
    return []; //give up..
  }
}

The describer method is about the same as madreason's answer. It can handle both class Function and if you get an object instead. It will then use Object.getOwnPropertyNames if no class Function is given (i.e. the class 'type' for C# developers).

class Describer {
  private static FRegEx = new RegExp(/(?:this\.)(.+?(?= ))/g);
  static describe(val: any, parent = false): string[] {
    let isFunction = Object.prototype.toString.call(val) == '[object Function]';
    if (isFunction) {
      let result = [];
      if (parent) {
        var proto = Object.getPrototypeOf(val.prototype);
        if (proto) {
          result = result.concat(this.describe(proto.constructor, parent));
        }
      }
      result = result.concat(val.toString().match(this.FRegEx));
      result = result.Where(r => r !== null && r !== undefined);
      return result;
    }
    else {
      if (typeof val == "object") {
        let knownProps: string[] = Object.getOwnPropertyNames(val);
        return knownProps;
      }
    }
    return val !== null ? [val.tostring()] : [];
  }
}

Here you see two specs for testing this out with Jasmine.

class Hero {
  name: string;
  gender: string;
  age: number;
  constructor(name: string = "", gender: string = "", age: number = 0) {
    this.name = name;
    this.gender = gender;
    this.age = age;
  }
}

class HeroWithAbility extends Hero {
  ability: string;
  constructor(ability: string = "") {
    super();
    this.ability = ability;
  }
}

describe('Array Extensions tests for TsExtensions Linq esque library', () => {

  it('can retrieve props for a class items of an array', () => {
    let heroes: Hero[] = [<Hero>{ name: "Han Solo", age: 44, gender: "M" }, <Hero>{ name: "Leia", age: 29, gender: "F" }, <Hero>{ name: "Luke", age: 24, gender: "M" }, <Hero>{ name: "Lando", age: 47, gender: "M" }];
    let foundProps = heroes.GetProperties(Hero, false);
    //debugger
    let expectedArrayOfProps = ["name", "age", "gender"];
    expect(foundProps).toEqual(expectedArrayOfProps);
    expect(heroes.GetProperties(Hero, true)).toEqual(["age", "gender", "name"]);
  });

  it('can retrieve props for a class only knowing its function', () => {
    let heroes: Hero[] = [];
    let foundProps = heroes.GetProperties(Hero, false);
    let expectedArrayOfProps = ["this.name", "this.gender", "this.age"];
    expect(foundProps).toEqual(expectedArrayOfProps);
    let foundPropsThroughClassFunction = heroes.GetProperties(Hero, true);
    //debugger
    expect(foundPropsThroughClassFunction.SequenceEqual(["this.age", "this.gender", "this.name"])).toBe(true);
  });

And as madreason mentioned, you have to initialize the props to get any information out from just the class Function itself, or else it is stripped away when Typescript code is turned into Javascript code.

Typescript 3.7 is very good with Generics, but coming from a C# and Reflection background, some fundamental parts of Typescript and generics still feels somewhat loose and unfinished business. Like my code here, but at least I got out the information I wanted - a list of property names for a given class or instance of objects.

SequenceEqual is this method btw:

    if (!Array.prototype.SequenceEqual) {
  Array.prototype.SequenceEqual = function <T>(compareArray: T): boolean {
    if (!Array.isArray(this) || !Array.isArray(compareArray) || this.length !== compareArray.length)
      return false;
    var arr1 = this.concat().sort();
    var arr2 = compareArray.concat().sort();
    for (var i = 0; i < arr1.length; i++) {
      if (arr1[i] !== arr2[i])
        return false;
    }
    return true;
  }
}

Error handling in Bash

This trick is useful for missing commands or functions. The name of the missing function (or executable) will be passed in $_

function handle_error {
    status=$?
    last_call=$1

    # 127 is 'command not found'
    (( status != 127 )) && return

    echo "you tried to call $last_call"
    return
}

# Trap errors.
trap 'handle_error "$_"' ERR

Phone validation regex

I have a more generic regex to allow the user to enter only numbers, +, -, whitespace and (). It respects the parenthesis balance and there is always a number after a symbol.

^([+]?[\s0-9]+)?(\d{3}|[(]?[0-9]+[)])?([-]?[\s]?[0-9])+$

false, ""
false, "+48 504 203 260@@"
false, "+48.504.203.260"
false, "+55(123) 456-78-90-"
false, "+55(123) - 456-78-90"
false, "504.203.260"
false, " "
false, "-"
false, "()"
false, "() + ()"
false, "(21 7777"
false, "+48 (21)"
false, "+"
true , " 1"
true , "1"
true, "555-5555-555"
true, "+48 504 203 260"
true, "+48 (12) 504 203 260"
true, "+48 (12) 504-203-260"
true, "+48(12)504203260"
true, "+4812504203260"
true, "4812504203260

How can I indent multiple lines in Xcode?

Danish Keyboard

Unindent: ? + ? + 8

Indent: ? + ? + 9

How to get current page URL in MVC 3

One thing that isn't mentioned in other answers is case sensitivity, if it is going to be referenced in multiple places (which it isn't in the original question but is worth taking into consideration as this question appears in a lot of similar searches). Based on other answers I found the following worked for me initially:

Request.Url.AbsoluteUri.ToString()

But in order to be more reliable this then became:

Request.Url.AbsoluteUri.ToString().ToLower()

And then for my requirements (checking what domain name the site is being accessed from and showing the relevant content):

Request.Url.AbsoluteUri.ToString().ToLower().Contains("xxxx")

How to change legend size with matplotlib.pyplot

you can reduce the legend size setting:

plt.legend(labelspacing=y, handletextpad=x,fontsize)  

labelspacing is the vertical space between each label.

handletextpad is the distance between the actual legend and your label.

And fontsize is self-explanatory

When to use IList and when to use List

You are most often better of using the most general usable type, in this case the IList or even better the IEnumerable interface, so that you can switch the implementation conveniently at a later time.

However, in .NET 2.0, there is an annoying thing - IList does not have a Sort() method. You can use a supplied adapter instead:

ArrayList.Adapter(list).Sort()

Javascript Error Null is not an Object

Any JS code which executes and deals with DOM elements should execute after the DOM elements have been created. JS code is interpreted from top to down as layed out in the HTML. So, if there is a tag before the DOM elements, the JS code within script tag will execute as the browser parses the HTML page.

So, in your case, you can put your DOM interacting code inside a function so that only function is defined but not executed.

Then you can add an event listener for document load to execute the function.

That will give you something like:

<script>
  function init() {
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");
    myButton.onclick = function() {
      var userName = myTextfield.value;
      greetUser(userName);
    }
  }

  function greetUser(userName) {
    var greeting = "Hello " + userName + "!";
    document.getElementsByTagName ("h2")[0].innerHTML = greeting;
  }

  document.addEventListener('readystatechange', function() {
    if (document.readyState === "complete") {
      init();
    }
  });

</script>
<h2>Hello World!</h2>
<p id="myParagraph">This is an example website</p>

<form>
  <input type="text" id="myTextfield" placeholder="Type your name" />
  <input type="button" id="myButton" value="Go" />
</form>

Fiddle at - http://jsfiddle.net/poonia/qQMEg/4/

php refresh current page?

$_SERVER['REQUEST_URI'] should work.

Printing 2D array in matrix format

I wrote extension method

public static string ToMatrixString<T>(this T[,] matrix, string delimiter = "\t")
{
    var s = new StringBuilder();

    for (var i = 0; i < matrix.GetLength(0); i++)
    {
        for (var j = 0; j < matrix.GetLength(1); j++)
        {
            s.Append(matrix[i, j]).Append(delimiter);
        }

        s.AppendLine();
    }

    return s.ToString();
}

To use just call the method

results.ToMatrixString();

ReactJS: setTimeout() not working?

Your code scope (this) will be your window object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000) will crash this way.

That comes from javascript not React, it is js closure


So, in order to bind your current react component scope, do this:

setTimeout(function(){this.setState({position: 1})}.bind(this), 3000);

Or if your browser supports es6 or your projs has support to compile es6 to es5, try arrow function as well, as arrow func is to fix 'this' issue:

setTimeout(()=>this.setState({position: 1}), 3000);

how to draw smooth curve through N points using javascript HTML5 canvas?

I decide to add on, rather than posting my solution to another post. Below are the solution that I build, may not be perfect, but so far the output are good.

Important: it will pass through all the points!

If you have any idea, to make it better, please share to me. Thanks.

Here are the comparison of before after:

enter image description here

Save this code to HTML to test it out.

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
     <canvas id="myCanvas" width="1200" height="700" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
     <script>_x000D_
      var cv = document.getElementById("myCanvas");_x000D_
      var ctx = cv.getContext("2d");_x000D_
    _x000D_
      function gradient(a, b) {_x000D_
       return (b.y-a.y)/(b.x-a.x);_x000D_
      }_x000D_
    _x000D_
      function bzCurve(points, f, t) {_x000D_
       //f = 0, will be straight line_x000D_
       //t suppose to be 1, but changing the value can control the smoothness too_x000D_
       if (typeof(f) == 'undefined') f = 0.3;_x000D_
       if (typeof(t) == 'undefined') t = 0.6;_x000D_
    _x000D_
       ctx.beginPath();_x000D_
       ctx.moveTo(points[0].x, points[0].y);_x000D_
    _x000D_
       var m = 0;_x000D_
       var dx1 = 0;_x000D_
       var dy1 = 0;_x000D_
    _x000D_
       var preP = points[0];_x000D_
       for (var i = 1; i < points.length; i++) {_x000D_
        var curP = points[i];_x000D_
        nexP = points[i + 1];_x000D_
        if (nexP) {_x000D_
         m = gradient(preP, nexP);_x000D_
         dx2 = (nexP.x - curP.x) * -f;_x000D_
         dy2 = dx2 * m * t;_x000D_
        } else {_x000D_
         dx2 = 0;_x000D_
         dy2 = 0;_x000D_
        }_x000D_
        ctx.bezierCurveTo(preP.x - dx1, preP.y - dy1, curP.x + dx2, curP.y + dy2, curP.x, curP.y);_x000D_
        dx1 = dx2;_x000D_
        dy1 = dy2;_x000D_
        preP = curP;_x000D_
       }_x000D_
       ctx.stroke();_x000D_
      }_x000D_
    _x000D_
      // Generate random data_x000D_
      var lines = [];_x000D_
      var X = 10;_x000D_
      var t = 40; //to control width of X_x000D_
      for (var i = 0; i < 100; i++ ) {_x000D_
       Y = Math.floor((Math.random() * 300) + 50);_x000D_
       p = { x: X, y: Y };_x000D_
       lines.push(p);_x000D_
       X = X + t;_x000D_
      }_x000D_
    _x000D_
      //draw straight line_x000D_
      ctx.beginPath();_x000D_
      ctx.setLineDash([5]);_x000D_
      ctx.lineWidth = 1;_x000D_
      bzCurve(lines, 0, 1);_x000D_
    _x000D_
      //draw smooth line_x000D_
      ctx.setLineDash([0]);_x000D_
      ctx.lineWidth = 2;_x000D_
      ctx.strokeStyle = "blue";_x000D_
      bzCurve(lines, 0.3, 1);_x000D_
     </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

How to delete migration files in Rails 3

Another way to delete the migration:

$ rails d migration SameMigrationNameAsUsedToGenerate

Use it before rake db:migrate is executed because changes in database will stay forever :) - or remove changes in Database manually

Best way to implement multi-language/globalization in large .NET project

Most opensource projects use GetText for this purpose. I don't know how and if it's ever been used on a .Net project before.

sizing div based on window width

Live Demo

Here is an actual implementation of what you described. I rewrote your code a bit using the latest best practices to actualize is. If you resize your browser windows under 1000px, the image's left and right side will be cropped using negative margins and it will be 300px narrower.

<style>
   .container {
      position: relative;
      width: 100%;
   }

   .bg {
      position:relative;
      z-index: 1;
      height: 100%;
      min-width: 1000px;
      max-width: 1500px;
      margin: 0 auto;
   }

   .nebula {
      width: 100%;
   }

   @media screen and (max-width: 1000px) {
      .nebula {
         width: 100%;
         overflow: hidden;
         margin: 0 -150px 0 -150px;
      }
   }
</style>

<div class="container">
   <div class="bg">
      <img src="http://i.stack.imgur.com/tFshX.jpg" class="nebula">
   </div>
</div>

Do I use <img>, <object>, or <embed> for SVG files?

If you use <img> tags, then webkit based browsers won't display embedded bitmapped images.

For any kind of advanced SVG use, including the SVG inline offers by far the most flexibility.

Internet Explorer and Edge will resize the SVG correctly, but you must specify both the height and width.

You can add onclick, onmouseover, etc. inside the svg, to any shape in the SVG: onmouseover="top.myfunction(evt);"

You can also use web fonts in the SVG by including them in your regular style sheet.

Note: if you are exporting SVG's from Illustrator, the web font names will be wrong. You can correct this in your CSS and avoid messing around in the SVG. For example, Illustrator gives the wrong name to Arial, and you can fix it like this:

@font-face {    
    font-family: 'ArialMT';    
    src:    
        local('Arial'),    
        local('Arial MT'),    
        local('Arial Regular');    
    font-weight: normal;    
    font-style: normal;    
}

All this works on any browser released since 2013.

For an example, see ozake.com. The whole site is made of SVG's except for the contact form.

Warning: Web fonts are imprecisely resized in Safari — and if you have lots of transitions from plain text to bold or italic, there may be a small amount of extra or missing space at the transition points. See my answer at this question for more information.

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

The imported project "C:\Microsoft.CSharp.targets" was not found

In my case, I opened my .csproj file in notepad and removed the following three lines. Worked like a charm:

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.3.2\build\Microsoft.Net.Compilers.props')" />

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

Angular 4 Pipe Filter

Pipes in Angular 2+ are a great way to transform and format data right from your templates.

Pipes allow us to change data inside of a template; i.e. filtering, ordering, formatting dates, numbers, currencies, etc. A quick example is you can transfer a string to lowercase by applying a simple filter in the template code.

List of Built-in Pipes from API List Examples

{{ user.name | uppercase }}

Example of Angular version 4.4.7. ng version


Custom Pipes which accepts multiple arguments.

HTML « *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] "
TS   « transform(json: any[], args: any[]) : any[] { ... }

Filtering the content using a Pipe « json-filter-by.pipe.ts

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]) : any[] {
    var searchText = args[0];
    var jsonKey = args[1];

    // json = undefined, args = (2) [undefined, "name"]
    if(searchText == null || searchText == 'undefined') return json;
    if(jsonKey    == null || jsonKey    == 'undefined') return json;

    // Copy all objects of original array into new Array.
    var returnObjects = json;
    json.forEach( function ( filterObjectEntery ) {

      if( filterObjectEntery.hasOwnProperty( jsonKey ) ) {
        console.log('Search key is available in JSON object.');

        if ( typeof filterObjectEntery[jsonKey] != "undefined" && 
        filterObjectEntery[jsonKey].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
            // object value contains the user provided text.
        } else {
            // object didn't match a filter value so remove it from array via filter
            returnObjects = returnObjects.filter(obj => obj !== filterObjectEntery);
        }
      } else {
        console.log('Search key is not available in JSON object.');
      }

    })
    return returnObjects;
  }
}

Add to @NgModule « Add JsonFilterByPipe to your declarations list in your module; if you forget to do this you'll get an error no provider for jsonFilterBy. If you add to module then it is available to all the component's of that module.

@NgModule({
  imports: [
    CommonModule,
    RouterModule,
    FormsModule, ReactiveFormsModule,
  ],
  providers: [ StudentDetailsService ],
  declarations: [
    UsersComponent, UserComponent,

    JsonFilterByPipe,
  ],
  exports : [UsersComponent, UserComponent]
})
export class UsersModule {
    // ...
}

File Name: users.component.ts and StudentDetailsService is created from this link.

import { MyStudents } from './../../services/student/my-students';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { StudentDetailsService } from '../../services/student/student-details.service';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: [ './users.component.css' ],

  providers:[StudentDetailsService]
})
export class UsersComponent implements OnInit, OnDestroy  {

  students: MyStudents[];
  selectedStudent: MyStudents;

  constructor(private studentService: StudentDetailsService) { }

  ngOnInit(): void {
    this.loadAllUsers();
  }
  ngOnDestroy(): void {
    // ONDestroy to prevent memory leaks
  }

  loadAllUsers(): void {
    this.studentService.getStudentsList().then(students => this.students = students);
  }

  onSelect(student: MyStudents): void {
    this.selectedStudent = student;
  }

}

File Name: users.component.html

<div>
    <br />
    <div class="form-group">
        <div class="col-md-6" >
            Filter by Name: 
            <input type="text" [(ngModel)]="searchText" 
                   class="form-control" placeholder="Search By Category" />
        </div>
    </div>

    <h2>Present are Students</h2>
    <ul class="students">
    <li *ngFor="let student of students | jsonFilterBy:[searchText, 'name'] " >
        <a *ngIf="student" routerLink="/users/update/{{student.id}}">
            <span class="badge">{{student.id}}</span> {{student.name | uppercase}}
        </a>
    </li>
    </ul>
</div>

How do you do Impersonation in .NET?

Here is some good overview of .NET impersonation concepts.

Basically you will be leveraging these classes that are out of the box in the .NET framework:

The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.

How to get access token from FB.login method in javascript SDK

_x000D_
_x000D_
window.fbAsyncInit = function () {_x000D_
    FB.init({_x000D_
        appId: 'Your-appId',_x000D_
        cookie: false,  // enable cookies to allow the server to access _x000D_
        // the session_x000D_
        xfbml: true,  // parse social plugins on this page_x000D_
        version: 'v2.0' // use version 2.0_x000D_
    });_x000D_
};_x000D_
_x000D_
// Load the SDK asynchronously_x000D_
(function (d, s, id) {_x000D_
    var js, fjs = d.getElementsByTagName(s)[0];_x000D_
    if (d.getElementById(id)) return;_x000D_
    js = d.createElement(s); js.id = id;_x000D_
    js.src = "//connect.facebook.net/en_US/sdk.js";_x000D_
    fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));_x000D_
_x000D_
   _x000D_
function fb_login() {_x000D_
    FB.login(function (response) {_x000D_
_x000D_
        if (response.authResponse) {_x000D_
            console.log('Welcome!  Fetching your information.... ');_x000D_
            //console.log(response); // dump complete info_x000D_
            access_token = response.authResponse.accessToken; //get access token_x000D_
            user_id = response.authResponse.userID; //get FB UID_x000D_
_x000D_
            FB.api('/me', function (response) {_x000D_
                var email = response.email;_x000D_
                var name = response.name;_x000D_
                window.location = 'http://localhost:12962/Account/FacebookLogin/' + email + '/' + name;_x000D_
                // used in my mvc3 controller for //AuthenticationFormsAuthentication.SetAuthCookie(email, true);          _x000D_
            });_x000D_
_x000D_
        } else {_x000D_
            //user hit cancel button_x000D_
            console.log('User cancelled login or did not fully authorize.');_x000D_
_x000D_
        }_x000D_
    }, {_x000D_
        scope: 'email'_x000D_
    });_x000D_
}
_x000D_
<!-- custom image -->_x000D_
<a href="#" onclick="fb_login();"><img src="/Public/assets/images/facebook/facebook_connect_button.png" /></a>_x000D_
_x000D_
<!-- Facebook button -->_x000D_
<fb:login-button scope="public_profile,email" onlogin="fb_login();">_x000D_
                </fb:login-button>
_x000D_
_x000D_
_x000D_

How to retrieve the hash for the current commit in Git?

If you only want the shortened commit hash:

git log --pretty=format:'%h' -n 1

Furthermore, using %H is another way to get the long commit hash, and simply -1 can be used in place of -n 1.

Can not deserialize instance of java.lang.String out of START_OBJECT token

Data content is so variable, I think the best form is to define it as "ObjectNode" and next create his own class to parse:

Finally:

private ObjectNode data;

ASP.Net MVC: How to display a byte array image from model

If you can base-64 encode your bytes, you could try using the result as your image source. In your model you might add something like:

public string ImageSource
{
    get
    {
        string mimeType = /* Get mime type somehow (e.g. "image/png") */;
        string base64 = Convert.ToBase64String(yourImageBytes);
        return string.Format("data:{0};base64,{1}", mimeType, base64);
    }
}

And in your view:

<img ... src="@Model.ImageSource" />

Java8: sum values from specific field of the objects in a list

You can do

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();

or (using Method reference)

int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();

modal View controllers - how to display and dismiss

This line:

[self dismissViewControllerAnimated:YES completion:nil];

isn't sending a message to itself, it's actually sending a message to its presenting VC, asking it to do the dismissing. When you present a VC, you create a relationship between the presenting VC and the presented one. So you should not destroy the presenting VC while it is presenting (the presented VC can't send that dismiss message back…). As you're not really taking account of it you are leaving the app in a confused state. See my answer Dismissing a Presented View Controller in which I recommend this method is more clearly written:

[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

In your case, you need to ensure that all of the controlling is done in mainVC . You should use a delegate to send the correct message back to MainViewController from ViewController1, so that mainVC can dismiss VC1 and then present VC2.

In VC2 VC1 add a protocol in your .h file above the @interface:

@protocol ViewController1Protocol <NSObject>

    - (void)dismissAndPresentVC2;

@end

and lower down in the same file in the @interface section declare a property to hold the delegate pointer:

@property (nonatomic,weak) id <ViewController1Protocol> delegate;

In the VC1 .m file, the dismiss button method should call the delegate method

- (IBAction)buttonPressedFromVC1:(UIButton *)sender {
    [self.delegate dissmissAndPresentVC2]
}

Now in mainVC, set it as VC1's delegate when creating VC1:

- (IBAction)present1:(id)sender {
    ViewController1* vc = [[ViewController1 alloc] initWithNibName:@"ViewController1" bundle:nil];
    vc.delegate = self;
    [self present:vc];
}

and implement the delegate method:

- (void)dismissAndPresent2 {
    [self dismissViewControllerAnimated:NO completion:^{
        [self present2:nil];
    }];
}

present2: can be the same method as your VC2Pressed: button IBAction method. Note that it is called from the completion block to ensure that VC2 is not presented until VC1 is fully dismissed.

You are now moving from VC1->VCMain->VC2 so you will probably want only one of the transitions to be animated.

update

In your comments you express surprise at the complexity required to achieve a seemingly simple thing. I assure you, this delegation pattern is so central to much of Objective-C and Cocoa, and this example is about the most simple you can get, that you really should make the effort to get comfortable with it.

In Apple's View Controller Programming Guide they have this to say:

Dismissing a Presented View Controller

When it comes time to dismiss a presented view controller, the preferred approach is to let the presenting view controller dismiss it. In other words, whenever possible, the same view controller that presented the view controller should also take responsibility for dismissing it. Although there are several techniques for notifying the presenting view controller that its presented view controller should be dismissed, the preferred technique is delegation. For more information, see “Using Delegation to Communicate with Other Controllers.”

If you really think through what you want to achieve, and how you are going about it, you will realise that messaging your MainViewController to do all of the work is the only logical way out given that you don't want to use a NavigationController. If you do use a NavController, in effect you are 'delegating', even if not explicitly, to the navController to do all of the work. There needs to be some object that keeps a central track of what's going on with your VC navigation, and you need some method of communicating with it, whatever you do.

In practice Apple's advice is a little extreme... in normal cases, you don't need to make a dedicated delegate and method, you can rely on [self presentingViewController] dismissViewControllerAnimated: - it's when in cases like yours that you want your dismissing to have other effects on remote objects that you need to take care.

Here is something you could imagine to work without all the delegate hassle...

- (IBAction)dismiss:(id)sender {
    [[self presentingViewController] dismissViewControllerAnimated:YES 
                                                        completion:^{
        [self.presentingViewController performSelector:@selector(presentVC2:) 
                                            withObject:nil];
    }];

}

After asking the presenting controller to dismiss us, we have a completion block which calls a method in the presentingViewController to invoke VC2. No delegate needed. (A big selling point of blocks is that they reduce the need for delegates in these circumstances). However in this case there are a few things getting in the way...

  • in VC1 you don't know that mainVC implements the method present2 - you can end up with difficult-to-debug errors or crashes. Delegates help you to avoid this.
  • once VC1 is dismissed, it's not really around to execute the completion block... or is it? Does self.presentingViewController mean anything any more? You don't know (neither do I)... with a delegate, you don't have this uncertainty.
  • When I try to run this method, it just hangs with no warning or errors.

So please... take the time to learn delegation!

update2

In your comment you have managed to make it work by using this in VC2's dismiss button handler:

 [self.view.window.rootViewController dismissViewControllerAnimated:YES completion:nil]; 

This is certainly much simpler, but it leaves you with a number of issues.

Tight coupling
You are hard-wiring your viewController structure together. For example, if you were to insert a new viewController before mainVC, your required behaviour would break (you would navigate to the prior one). In VC1 you have also had to #import VC2. Therefore you have quite a lot of inter-dependencies, which breaks OOP/MVC objectives.

Using delegates, neither VC1 nor VC2 need to know anything about mainVC or it's antecedents so we keep everything loosely-coupled and modular.

Memory
VC1 has not gone away, you still hold two pointers to it:

  • mainVC's presentedViewController property
  • VC2's presentingViewController property

You can test this by logging, and also just by doing this from VC2

[self dismissViewControllerAnimated:YES completion:nil]; 

It still works, still gets you back to VC1.

That seems to me like a memory leak.

The clue to this is in the warning you are getting here:

[self presentViewController:vc2 animated:YES completion:nil];
[self dismissViewControllerAnimated:YES completion:nil];
 // Attempt to dismiss from view controller <VC1: 0x715e460>
 // while a presentation or dismiss is in progress!

The logic breaks down, as you are attempting to dismiss the presenting VC of which VC2 is the presented VC. The second message doesn't really get executed - well perhaps some stuff happens, but you are still left with two pointers to an object you thought you had got rid of. (edit - I've checked this and it's not so bad, both objects do go away when you get back to mainVC)

That's a rather long-winded way of saying - please, use delegates. If it helps, I made another brief description of the pattern here:
Is passing a controller in a construtor always a bad practice?

update 3
If you really want to avoid delegates, this could be the best way out:

In VC1:

[self presentViewController:VC2
                   animated:YES
                 completion:nil];

But don't dismiss anything... as we ascertained, it doesn't really happen anyway.

In VC2:

[self.presentingViewController.presentingViewController 
    dismissViewControllerAnimated:YES
                       completion:nil];

As we (know) we haven't dismissed VC1, we can reach back through VC1 to MainVC. MainVC dismisses VC1. Because VC1 has gone, it's presented VC2 goes with it, so you are back at MainVC in a clean state.

It's still highly coupled, as VC1 needs to know about VC2, and VC2 needs to know that it was arrived at via MainVC->VC1, but it's the best you're going to get without a bit of explicit delegation.

How to convert a string to an integer in JavaScript?

we can use +(stringOfNumber) instead of using parseInt(stringOfNumber)

Ex: +("21") returns int of 21 like the parseInt("21").

we can use this unary "+" operator for parsing float too...

Google Maps API v3: How to remove all markers?

I've tried all of proposed solutions, but nothing worked for me while all my markers were under a cluster. Eventually I just put this:

var markerCluster = new MarkerClusterer(map, markers,
    { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
agentsGpsData[agentGpsData.ID].CLUSTER = markerCluster;

//this did the trick
agentsGpsData[agentId].CLUSTER.clearMarkers();

In other words, if you wrap markers in a cluster and want to remove all markers, you call:

clearMarkers();

In AVD emulator how to see sdcard folder? and Install apk to AVD?

if you are using Eclipse. You should switch to DDMS perspective from top-right corner there after selecting your device you can see folder tree. to install apk manually you can use adb command

adb install apklocation.apk

Replacing Numpy elements if condition is met

I am not sure I understood your question, but if you write:

mask_data[:3, :3] = 1
mask_data[3:, 3:] = 0

This will make all values of mask data whose x and y indexes are less than 3 to be equal to 1 and all rest to be equal to 0

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

With Java 8 and later, use the java.time package.

ZonedDateTime.now().getYear();
ZonedDateTime.now().getMonthValue();
ZonedDateTime.now().getDayOfMonth();
ZonedDateTime.now().getHour();
ZonedDateTime.now().getMinute();
ZonedDateTime.now().getSecond();

ZonedDateTime.now() is a static method returning the current date-time from the system clock in the default time-zone. All the get methods return an int value.

DateTime2 vs DateTime in SQL Server

Almost all the Answers and Comments have been heavy on the Pros and light on the Cons. Here's a recap of all Pros and Cons so far plus some crucial Cons (in #2 below) I've only seen mentioned once or not at all.

  1. PROS:

1.1. More ISO compliant (ISO 8601) (although I don’t know how this comes into play in practice).

1.2. More range (1/1/0001 to 12/31/9999 vs. 1/1/1753-12/31/9999) (although the extra range, all prior to year 1753, will likely not be used except for ex., in historical, astronomical, geologic, etc. apps).

1.3. Exactly matches the range of .NET’s DateTime Type’s range (although both convert back and forth with no special coding if values are within the target type’s range and precision except for Con # 2.1 below else error / rounding will occur).

1.4. More precision (100 nanosecond aka 0.000,000,1 sec. vs. 3.33 millisecond aka 0.003,33 sec.) (although the extra precision will likely not be used except for ex., in engineering / scientific apps).

1.5. When configured for similar (as in 1 millisec not "same" (as in 3.33 millisec) as Iman Abidi has claimed) precision as DateTime, uses less space (7 vs. 8 bytes), but then of course, you’d be losing the precision benefit which is likely one of the two (the other being range) most touted albeit likely unneeded benefits).

  1. CONS:

2.1. When passing a Parameter to a .NET SqlCommand, you must specify System.Data.SqlDbType.DateTime2 if you may be passing a value outside the SQL Server DateTime’s range and/or precision, because it defaults to System.Data.SqlDbType.DateTime.

2.2. Cannot be implicitly / easily converted to a floating-point numeric (# of days since min date-time) value to do the following to / with it in SQL Server expressions using numeric values and operators:

2.2.1. add or subtract # of days or partial days. Note: Using DateAdd Function as a workaround is not trivial when you're needing to consider multiple if not all parts of the date-time.

2.2.2. take the difference between two date-times for purposes of “age” calculation. Note: You cannot simply use SQL Server’s DateDiff Function instead, because it does not compute age as most people would expect in that if the two date-times happens to cross a calendar / clock date-time boundary of the units specified if even for a tiny fraction of that unit, it’ll return the difference as 1 of that unit vs. 0. For example, the DateDiff in Day’s of two date-times only 1 millisecond apart will return 1 vs. 0 (days) if those date-times are on different calendar days (i.e. “1999-12-31 23:59:59.9999999” and “2000-01-01 00:00:00.0000000”). The same 1 millisecond difference date-times if moved so that they don’t cross a calendar day, will return a “DateDiff” in Day’s of 0 (days).

2.2.3. take the Avg of date-times (in an Aggregate Query) by simply converting to “Float” first and then back again to DateTime.

NOTE: To convert DateTime2 to a numeric, you have to do something like the following formula which still assumes your values are not less than the year 1970 (which means you’re losing all of the extra range plus another 217 years. Note: You may not be able to simply adjust the formula to allow for extra range because you may run into numeric overflow issues.

25567 + (DATEDIFF(SECOND, {d '1970-01-01'}, @Time) + DATEPART(nanosecond, @Time) / 1.0E + 9) / 86400.0 – Source: “ https://siderite.dev/blog/how-to-translate-t-sql-datetime2-to.html

Of course, you could also Cast to DateTime first (and if necessary back again to DateTime2), but you'd lose the precision and range (all prior to year 1753) benefits of DateTime2 vs. DateTime which are prolly the 2 biggest and also at the same time prolly the 2 least likely needed which begs the question why use it when you lose the implicit / easy conversions to floating-point numeric (# of days) for addition / subtraction / "age" (vs. DateDiff) / Avg calcs benefit which is a big one in my experience.

Btw, the Avg of date-times is (or at least should be) an important use case. a) Besides use in getting average duration when date-times (since a common base date-time) are used to represent duration (a common practice), b) it’s also useful to get a dashboard-type statistic on what the average date-time is in the date-time column of a range / group of Rows. c) A standard (or at least should be standard) ad-hoc Query to monitor / troubleshoot values in a Column that may not be valid ever / any longer and / or may need to be deprecated is to list for each value the occurrence count and (if available) the Min, Avg and Max date-time stamps associated with that value.

How to use document.getElementByName and getElementByTag?

I assume you are talking about getElementById() returning a reference to an element whilst the others return a node list. Just subscript the nodelist for the others, e.g. document.getElementBytag('table')[4].

Also, elements is only a property of a form (HTMLFormElement), not a table such as in your example.

How to insert values into the database table using VBA in MS access

You can't run two SQL statements into one like you are doing.

You can't "execute" a select query.

db is an object and you haven't set it to anything: (e.g. set db = currentdb)

In VBA integer types can hold up to max of 32767 - I would be tempted to use Long.

You might want to be a bit more specific about the date you are inserting:

INSERT INTO Test (Start_Date) VALUES ('#" & format(InDate, "mm/dd/yyyy") & "#' );"

Creating a list of objects in Python

If I understand correctly your question, you ask a way to execute a deep copy of an object. What about using copy.deepcopy?

import copy

x = SimpleClass()

for count in range(0,4):
  y = copy.deepcopy(x)
  (...)
  y.attr1= '*Bob* '* count

A deepcopy is a recursive copy of the entire object. For more reference, you can have a look at the python documentation: https://docs.python.org/2/library/copy.html

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

I dont understand the frustrations. Why not just make a broadcastreceiver that filters for this intent:

android.provider.Telephony.MMS_RECEIVED

I checked a little further and you might need system level access to get this (rooted phone).

How to convert date to string and to date again?

try this:

 String DATE_FORMAT_NOW = "yyyy-MM-dd";
 Date date = new Date();
 SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
 String stringDate = sdf.format(date );
    try {
        Date date2 = sdf.parse(stringDate);
    } catch(ParseException e){
     //Exception handling
    } catch(Exception e){
     //handle exception
    }

Ant: How to execute a command for each file in directory?

Do what blak3r suggested and define your targets classpath like so

<taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
        <fileset dir="lib">
          <include name="**/*.jar"/>
        </fileset>
    </classpath>        
</taskdef>

where lib is where you store your jar's

How to set placeholder value using CSS?

Change your meta tag to the one below and use placeholder attribute inside your HTML input tag.

_x000D_
_x000D_
<meta http-equiv="X-UA-Compatible" content="IE=edge" />_x000D_
<input type="text" placeholder="Placeholder text" />?
_x000D_
_x000D_
_x000D_

Map and filter an array at the same time

Use reduce, Luke!

function renderOptions(options) {
    return options.reduce(function (res, option) {
        if (!option.assigned) {
            res.push(someNewObject);
        }
        return res;
    }, []);   
}

Youtube - downloading a playlist - youtube-dl

I found the best solution after many attempts for this problem.

youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}

Using .text() to retrieve only text not nested in child tags

Simple answer:

$("#listItem").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "The text you want to replace with" 

Get a filtered list of files in a directory

You can use pathlib that is available in Python standard library 3.4 and above.

from pathlib import Path

files = [f for f in Path.cwd().iterdir() if f.match("145592*.jpg")]

Launch Android application without main Activity and start Service on launching application

Android Studio Version 2.3

You can create a Service without a Main Activity by following a few easy steps. You'll be able to install this app through Android Studio and debug it like a normal app.

First, create a project in Android Studio without an activity. Then create your Service class and add the service to your AndroidManifest.xml

<application android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <service android:name="com.whatever.myservice.MyService">
        <intent-filter>
            <action android:name="com.whatever.myservice.MyService" />
        </intent-filter>
    </service>
</application>

Now, in the drop down next to the "Run" button(green arrow), go to "edit configurations" and within the "Launch Options" choose "Nothing". This will allow you to install your Service without Android Studio complaining about not having a Main Activity.

Once installed, the service will NOT be running but you will be able to start it with this adb shell command...

am startservice -n com.whatever.myservice/.MyService

Can check it's running with...

ps | grep whatever

I haven't tried yet but you can likely have Android Studio automatically start the service too. This would be done in that "Edit Configurations" menu.

How to draw interactive Polyline on route google maps v2 android

I've created a couple of map tutorials that will cover what you need

Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.

Take a look at these 2 tutorials and the Github project containing the sample app.

It contains some tips to make your code cleaner and more efficient:

  • Using Google HTTP Library for more efficient API access and easy JSON handling.
  • Using google-map-utils library for maps-related functions (like decoding the polylines)
  • Animating markers

How to check currently internet connection is available or not in android

This will show an dialog error box if there is not network connectivity

    ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        new AlertDialog.Builder(this)
            .setTitle("Connection Failure")
            .setMessage("Please Connect to the Internet")
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
    }

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

Max size of an iOS application

4GB's is the maximum size your iOS app can be.

As of January 26, 2017

App Size for iOS (& tvOS) only

Your app’s total uncompressed size must be less than 4GB. Each Mach-O executable file (for example, app_name.app/app_name) must not exceed these limits:

  • For apps whose MinimumOSVersion is less than 7.0: maximum of 80 MB for the total of all __TEXT sections in the binary.
  • For apps whose MinimumOSVersion is 7.x through 8.x: maximum of 60 MB per slice for the __TEXT section of each architecture slice in the binary.
  • For apps whose MinimumOSVersion is 9.0 or greater: maximum of 500 MB for the total of all __TEXT sections in the binary.

However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found at iTunes Connect Developer Guide: Submitting the App to App Review.


As of February 12, 2015

(iOS only) App Size

iOS App binary files can be as large as 4 GB, but each executable file (app_name.app/app_name) must not exceed 60 MB. Additionally, the total uncompressed size of the app must be less than 4 billion bytes. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found on page 77 of the iTunes Connect Developer Guide.


As of December 12, 2013

(iOS only) App Size

iOS App binary files can be as large as 2 GB, but the executable file (app_name.app/app_name) cannot exceed 60MB. However, consider download times when determining your app’s size. Minimize the file’s size as much as possible, keeping in mind that there is a 100 MB limit for over-the-air downloads.

This information can be found on page 58 of the iTunes Connect Developer Guide.


As of June 6, 2013

The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 237 of the guide.


As of January 10, 2013

The above information is still the same with the exception of the Executable File size which is now limited to 60MB's. These changes can be found on page 208 of the guide.


As of October 31, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 206 of the guide. Thanks to comment from Ozair Kafray.


As of July 19, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 214 of the guide. Thanks to comment from marsbear. In addition, the document has moved here:

http://developer.apple.com/library/ios/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/iTunesConnect_Guide.pdf


As of July 13, 2012

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.


As of March 29, 2012 (version 7.4)

The above information is still the same with the exception of Over The Air downloads which is now 50MB's. These changes can be found on page 209 of the guide.


As of January 23, 2012 (version 7.3)

The above information is still the same, however, it can be found on page 172 of the guide.


As of October 17, 2011 (version 7.2)

The above information is still the same, however, it can be found on page 180 of the guide. Thanks to comment from Luke for the update.


As of September 22, 2011 (version 7.1)

The above information is still the same, however, it can be found on page 179 of the guide. Thanks to comment from Saxon Druce for the update.

Entity Framework - Include Multiple Levels of Properties

For EF 6

using System.Data.Entity;

query.Include(x => x.Collection.Select(y => y.Property))

Make sure to add using System.Data.Entity; to get the version of Include that takes in a lambda.


For EF Core

Use the new method ThenInclude

query.Include(x => x.Collection)
     .ThenInclude(x => x.Property);

T-SQL get SELECTed value of stored procedure

There is also a combination, you can use a return value with a recordset:

--Stored Procedure--

CREATE PROCEDURE [TestProc]

AS
BEGIN

    DECLARE @Temp TABLE
    (
        [Name] VARCHAR(50)
    )

    INSERT INTO @Temp VALUES ('Mark') 
    INSERT INTO @Temp VALUES ('John') 
    INSERT INTO @Temp VALUES ('Jane') 
    INSERT INTO @Temp VALUES ('Mary') 

    -- Get recordset
    SELECT * FROM @Temp

    DECLARE @ReturnValue INT
    SELECT @ReturnValue = COUNT([Name]) FROM @Temp

    -- Return count
    RETURN @ReturnValue

END

--Calling Code--

DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc] 

SELECT @SelectedValue

--Results--

enter image description here

AngularJS - difference between pristine/dirty and touched/untouched

AngularJS Developer Guide - CSS classes used by AngularJS

  • @property {boolean} $untouched True if control has not lost focus yet.
  • @property {boolean} $touched True if control has lost focus.
  • @property {boolean} $pristine True if user has not interacted with the control yet.
  • @property {boolean} $dirty True if user has already interacted with the control.

angular 2 how to return data from subscribe

I have used this way lots time ...

_x000D_
_x000D_
@Component({_x000D_
   selector: "data",_x000D_
   template: "<h1>{{ getData() }}</h1>"_x000D_
})_x000D_
_x000D_
export class DataComponent{_x000D_
    this.http.get(path).subscribe({_x000D_
       DataComponent.setSubscribeData(res);_x000D_
    })_x000D_
}_x000D_
_x000D_
_x000D_
static subscribeData:any;_x000D_
static setSubscribeData(data):any{_x000D_
    DataComponent.subscribeData=data;_x000D_
    return data;_x000D_
}
_x000D_
_x000D_
_x000D_

use static keyword and save your time... here either you can use static variable or directly return object you want.... hope it will help you.. happy coding...

How to get exception message in Python properly

I too had the same problem. Digging into this I found that the Exception class has an args attribute, which captures the arguments that were used to create the exception. If you narrow the exceptions that except will catch to a subset, you should be able to determine how they were constructed, and thus which argument contains the message.

try:
   # do something that may raise an AuthException
except AuthException as ex:
   if ex.args[0] == "Authentication Timeout.":
      # handle timeout
   else:
      # generic handling

How to re-index all subarray elements of a multidimensional array?

$array[9] = 'Apple';
$array[12] = 'Orange';
$array[5] = 'Peach';

$array = array_values($array);

through this function you can reset your array

$array[0] = 'Apple';
$array[1] = 'Orange';
$array[2] = 'Peach';

How can I get an HTTP response body as a string?

If you are using Jackson to deserialize the response body, one very simple solution is to use request.getResponseBodyAsStream() instead of request.getResponseBodyAsString()

Console app arguments, how arguments are passed to Main method

The main method of the runtime engine looks something like int main(int argc, char *argv[]), where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.

Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().

Remove all special characters, punctuation and spaces from string

Shorter way :

import re
cleanString = re.sub('\W+','', string )

If you want spaces between words and numbers substitute '' with ' '

default value for struct member in C

Even more so, to add on the existing answers, you may use a macro that hides a struct initializer:

#define DEFAULT_EMPLOYEE { 0, "none" }

Then in your code:

employee john = DEFAULT_EMPLOYEE;

When to use Common Table Expression (CTE)

 ;with cte as
  (
  Select Department, Max(salary) as MaxSalary
  from test
  group by department
  )  
  select t.* from test t join cte c on c.department=t.department 
  where t.salary=c.MaxSalary;

try this

Making HTML page zoom by default

Solved it as follows,

in CSS

#my{
zoom: 100%;
}

Now, it loads in 100% zoom by default. Tested it by giving 290% zoom and it loaded by that zoom percentage on default, it's upto the user if he wants to change zoom.

Though this is not the best way to do it, there is another effective solution

Check the page code of stack over flow, even they have buttons and they use un ordered lists to solve this problem.

Check array position for null/empty

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",//post
     url: 'Your URL',
     data: "id="+id, // appears as $_GET['id'] @ ur backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

String field value length in mongoDB

Queries with $where and $expr are slow if there are too many documents.

Using $regex is much faster than $where, $expr.

db.usercollection.find({ 
  "name": /^[\s\S]{40,}$/, // name.length >= 40
})

or 

db.usercollection.find({ 
  "name": { "$regex": "^[\s\S]{40,}$" }, // name.length >= 40
})

This query is the same meaning with

db.usercollection.find({ 
  "$where": "this.name && this.name.length >= 40",
})

or

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gte": [ { "$strLenCP": "$name" }, 40 ] } 
})

I tested each queries for my collection.

# find
$where: 10529.359ms
$expr: 5305.801ms
$regex: 2516.124ms

# count
$where: 10872.006ms
$expr: 2630.155ms
$regex: 158.066ms

What is the difference between Scrum and Agile Development?

Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.

As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful

ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.

The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

How can I retrieve Id of inserted entity using Entity framework?

When you use EF 6.x code first

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }

and initialize a database table, it will put a

(newsequentialid())

inside the table properties under the header Default Value or Binding, allowing the ID to be populated as it is inserted.

The problem is if you create a table and add the

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

part later, future update-databases won't add back the (newsequentialid())

To fix the proper way is to wipe migration, delete database and re-migrate... or you can just add (newsequentialid()) into the table designer.

How to add to an NSDictionary

A mutable dictionary can be changed, i.e. you can add and remove objects. An immutable is fixed once it is created.

create and add:

NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];
[dict setObject:[NSNumber numberWithInt:42] forKey:@"A cool number"];

and retrieve:

int myNumber = [[dict objectForKey:@"A cool number"] intValue];

Iterating on a file doesn't work the second time

Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0) to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.

If you prefer you can use the with syntax instead which will automatically close the file for you.

e.g.,

with open('baby1990.html', 'rU') as f:
  for line in f:
     print line

once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

It is also possible to receive this error from a select component if the query fails in an unusual manner (eg: a sub-query returns multiple rows in an oracle oledb connection)

adb shell su works but adb root does not

I have a rooted Samsung Galaxy Trend Plus (GT-S7580).

Running 'adb root' gives me the same 'adbd cannot run as root in production builds' error.

For devices that have Developer Options -> Root access, choose "ADB only" to provide adb root access to the device (as suggested by NgaNguyenDuy).

Then try to run the command as per the solution at Launch a script as root through ADB. In my case, I just wanted to run the 'netcfg rndis0 dhcp' command, and I did it this way:

adb shell "su -c netcfg rndis0 dhcp"

Please check whether you are making any mistakes while running it this way.

If it still does not work, check whether you rooted the device correctly. If still no luck, try installing a custom ROM such as Cyanogen Mod in order for 'adb root' to work.

Is there a naming convention for MySQL?

Simple Answer: NO

Well, at least a naming convention as such encouraged by Oracle or community, no, however, basically you have to be aware of following the rules and limits for identifiers, such as indicated in MySQL documentation: https://dev.mysql.com/doc/refman/8.0/en/identifiers.html

About the naming convention you follow, I think it is ok, just the number 5 is a little bit unnecesary, I think most visual tools for managing databases offer a option for sorting column names (I use DBeaver, and it have it), so if the purpouse is having a nice visual presentation of your table you can use this option I mention.

By personal experience, I would recommed this:

  • Use lower case. This almost ensures interoperability when you migrate your databases from one server to another. Sometimes the lower_case_table_names is not correctly configured and your server start throwing errors just by simply unrecognizing your camelCase or PascalCase standard (case sensitivity problem).
  • Short names. Simple and clear. The most easy and fast is identify your table or columns, the better. Trust me, when you make a lot of different queries in a short amount of time is better having all simple to write (and read).
  • Avoid prefixes. Unless you are using the same database for tables of different applications, don't use prefixes. This only add more verbosity to your queries. There are situations when this could be useful, for example, when you want to indentify primary keys and foreign keys, that usually table names are used as prefix for id columns.
  • Use underscores for separating words. If you still want to use more than one word for naming a table, column, etc., so use underscores for separating_the_words, this helps for legibility (your eyes and your stressed brain are going to thank you).
  • Be consistent. Once you have your own standard, follow it. Don´t be the person that create the rules and is the first who breaking them, that is shameful.

And what about the "Plural vs Singular" naming? Well, this is most a situation of personal preferences. In my case I try to use plural names for tables because I think a table as a collection of elements or a package containig elements, so a plural name make sense for me; and singular names for columns because I see columns as attributes that describe singularly to those table elements.

How do I use vim registers?

My favorite feature is the ability to append into registers by using capital letters. For example, say you want to move a subset of imports from buffer X to buffer Y.

  1. Go to line x1 in buffer X.
  2. Type "ayy to replace register a with the content of line x1.
  3. Go to line x5.
  4. Type "Ayy (capital A) to append line x5 at the end of register a.
  5. Go to buffer Y and type "ap to paste
<content of line x1>
<content of line x5>

MySQL selecting yesterday's date

Query for the last weeks:

SELECT *
FROM dual
WHERE search_date BETWEEN SUBDATE(CURDATE(), 7) AND CURDATE()

How to set the LDFLAGS in CMakeLists.txt?

For linking against libraries see Andre's answer.

For linker flags - the following 4 CMake variables:

CMAKE_EXE_LINKER_FLAGS
CMAKE_MODULE_LINKER_FLAGS
CMAKE_SHARED_LINKER_FLAGS
CMAKE_STATIC_LINKER_FLAGS

can be easily manipulated for different configs (debug, release...) with the ucm_add_linker_flags macro of ucm

NuGet auto package restore does not work with MSBuild

It took me some time to figure out the whole picture and I'd like to share here.

Visual Studio has two approaches to use package restore: Automatic Package Restore and MSBuild-Integrated package restore. The 'MSBuild-Integrated Package Restore' restores packages DURING the building process that might cause issues in some scenarios. The 'Automatic Package Restore' is the recommended approach by the NuGet team.

There are several steps to to make 'Automatic Package Restore' work:

  1. In Visual Studio, Tools -> Extensions and Updates, Upgrade NuGet if there is a newer version (Version 2.7 or later)

  2. If you use TFS, in your solution's .nuget folder, remove the NuGet.exe and NuGet.targes files. Then edit NuGet.Config to not check in NuGet packages:

    <configuration>  
      <solution>  
        <add key="disableSourceControlIntegration" value="true" />  
      </solution>  
    </configuration> 
    

    If you checked in the solution's packages folder to TFS before, delete the folder and check in the deletion of package folder deletion.

    If you don't use TFS, delete the .nuget folder.

  3. In each project file (.csproj or .vbproj) in your solution, remove the line that references NuGet.targets file. The reference looks like this:

    <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
    

    Remove this line in every project file in your solution.

  4. In Visual Studio menu, either through

    Tools -> Options -> Package Manager -> General or Tools -> NuGet Package Manager -> Package Manager Settings

    please enable the following two options 1) 'Allow NuGet to download missing packages' 2) 'Automatically check for missing packages during build in Visual Studio'

  5. Test your package restore configuration by the following steps

    • Save your solution and close Visual Studio
    • Delete your solution's packages folder
    • Start Visual Studio, open your solution and rebuild it.

document.getElementById("test").style.display="hidden" not working

you can use something like this....div container

<script type="text/javascript">
function hide(){
document.getElementById("test").innerHTML.style.display="none";
}
</script>
<div id="test">
<form method="post" >

<table width="60%" border="0" cellspacing="2" cellpadding="2"  >
  <tr style="background:url(../images/nav.png) repeat-x; color:#fff; font-weight:bold" align="center">
    <td>Ample Id</td>
    <td>Find</td>
  </tr>

  <tr align="center" bgcolor="#E8F8FF" style="color:#006" >
    <td><input type="text" name="ampid" id="ampid" value="<?php echo $_POST['ampid'];?>" /></td>
   <td><input type="image" src="../images/btnFind.png" id="find" name="find" onclick="javascript:hide();"/></td>
   </tr>

</table>

</form>
</div>

Can I limit the length of an array in JavaScript?

arr.length = Math.min(arr.length, 5)

How to add a scrollbar to an HTML5 table?

This was a challenging question. I think I finally have a solution that satisfies complete requirements: a vertical and horizontal scrollable dynamic table (dynamic because you can change the amount of rows and columns, and no cells have fixed width or height).

The HTML and CSS layout is quite simple as other people have mentioned. The key issue is recalculating (JavaScript) cell widths. And to make sure horizontal scrolling works, I also recalculate theader and tbody width.

Here's a fiddle https://jsfiddle.net/jmarcos00/6hv0dsj8/1/

HTML code:

<!--
thead and tbody have identifiers
table is inside a div container
-->
<div>
  <table>
    <thead id="mythead">
      <tr>
        <th>header one</th>
        <th>two</th>
        <th>header three</th>
        <th>header one</th>
        <th>two</th>
        <th>header three</th>
      </tr>
    </thead>
    <tbody id="mytbody">
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
      <tr>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
        <td>one</td>
        <td>data two</td>
        <td>three</td>
      </tr>
    </tbody>
  </table>
</div>

CSS code:

/* table border rule */
table, td, th { border: 1px solid black; }

/* display as block plus display vertical scroll bars */
thead, tbody { display: block; overflow-y: scroll; }

/* sample height */
tbody { height: 100px; }

/* sample width and horizontal scroll bar */
div { width: 200px; overflow-x: auto; }

JavaScript code:

var i, w, wtot, thtot, thw, tdw, theadtr, tbodytr;
var th_rect, td_rect, theadtr_rect, tbodytr_rect;
var safe = new Array();

// get thead and tbody
var mythead = document.getElementById("mythead");
var mytbody = document.getElementById("mytbody");

// get first tr of thead and tbody
theadtr = mythead.children[0];
tbodytr = mytbody.children[0];
theadtr_rect = theadtr.getBoundingClientRect();
tbodytr_rect = tbodytr.getBoundingClientRect();

// get width difference of longer first tr
//   difference between tr and parent
if (tbodytr_rect.width > theadtr_rect.width)
    wtot = mytbody.getBoundingClientRect().width - tbodytr_rect.width;
else
    wtot = mythead.getBoundingClientRect().width - theadtr_rect.width;

// get width difference between tr and total th width (first step)
thtot = theadtr_rect.width;

// get th thead array and td tbody array
theadtr = theadtr.children;
tbodytr = tbodytr.children;

// get loop
for (i = 0; i < theadtr.length; i++)
{
    // second step for width difference between tr and total th width
    th_rect = theadtr[i].getBoundingClientRect();
    td_rect = tbodytr[i].getBoundingClientRect();
    thtot -= th_rect.width;

    // get width of each th and first row td (without paddings etc)
    tdw = parseFloat(window.getComputedStyle(tbodytr[i]).getPropertyValue("width"));
    thw = parseFloat(window.getComputedStyle(theadtr[i]).getPropertyValue("width"));

    // get bigger width
    w = (tdw > thw) ? tdw : thw;
    safe.push(w);

    // add to width total (decimal value with paddings etc)
    w = (tdw > thw) ? td_rect.width : th_rect.width;
    wtot += w;
}

// consider tr width and total th width difference
wtot += thtot;

// set loop
for (i = 0; i < theadtr.length; i++)
{
    // set width to th and first row td
    w = safe[i] + "px";
    theadtr[i].style.width = w;
    tbodytr[i].style.width = w; 
}

// set width for thead and tbody
wtot = wtot + "px";
mythead.style.width = wtot;
mytbody.style.width = wtot;

Count number of lines in a git repository

If you want to get the number of lines from a certain author, try the following code:

git ls-files "*.java" | xargs -I{} git blame {} | grep ${your_name} | wc -l

Querying data by joining two tables in two database on different servers

You'll need to use sp_addlinkedserver to create a server link. See the reference documentation for usage. Once the server link is established, you'll construct the query as normal, just prefixing the database name with the other server. I.E:

-- FROM DB1
SELECT *
FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
    INNER JOIN [DB2].[MyDatabaseOnDB2].[dbo].[MyOtherTable] tab2
        ON tab1.ID = tab2.ID

Once the link is established, you can also use OPENQUERY to execute a SQL statement on the remote server and transfer only the data back to you. This can be a bit faster, and it will let the remote server optimize your query. If you cache the data in a temporary (or in-memory) table on DB1 in the example above, then you'll be able to query it just like joining a standard table. For example:

-- Fetch data from the other database server
SELECT *
INTO #myTempTable
FROM OPENQUERY([DB2], 'SELECT * FROM [MyDatabaseOnDB2].[dbo].[MyOtherTable]')

-- Now I can join my temp table to see the data
SELECT * FROM [MyDatabaseOnDB1].[dbo].[MyTable] tab1
    INNER JOIN #myTempTable tab2 ON tab1.ID = tab2.ID

Check out the documentation for OPENQUERY to see some more examples. The example above is pretty contrived. I would definitely use the first method in this specific example, but the second option using OPENQUERY can save some time and performance if you use the query to filter out some data.

How do I make CMake output into a 'bin' dir?

English is not my native language; please excuse typing errors.

use this line config :
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build/)
place your any CMakeLists.txt project.
this ${PROJECT_SOURCE_DIR} is your current source directory where project place .
and if wander why is ${EXECUTABLE_OUTPUT_PATH}
check this file CMakeCache.txt then search the key word output path,
all the variables define here , it would give a full explanation of the project all setting·

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

Don't use userForm = new FormGroup()

Use form = new FormGroup() instead.

And in the form use <form [formGroup]="form"> ...</form>. It works for me with angular 6

How to Automatically Close Alerts using Twitter Bootstrap

After going over some of the answers here an in another thread, here's what I ended up with:

I created a function named showAlert() that would dynamically add an alert, with an optional type and closeDealy. So that you can, for example, add an alert of type danger (i.e., Bootstrap's alert-danger) that will close automatically after 5 seconds like so:

showAlert("Warning message", "danger", 5000);

To achieve that, add the following Javascript function:

function showAlert(message, type, closeDelay) {

    if ($("#alerts-container").length == 0) {
        // alerts-container does not exist, add it
        $("body")
            .append( $('<div id="alerts-container" style="position: fixed;
                width: 50%; left: 25%; top: 10%;">') );
    }

    // default to alert-info; other options include success, warning, danger
    type = type || "info";    

    // create the alert div
    var alert = $('<div class="alert alert-' + type + ' fade in">')
        .append(
            $('<button type="button" class="close" data-dismiss="alert">')
            .append("&times;")
        )
        .append(message);

    // add the alert div to top of alerts-container, use append() to add to bottom
    $("#alerts-container").prepend(alert);

    // if closeDelay was passed - set a timeout to close the alert
    if (closeDelay)
        window.setTimeout(function() { alert.alert("close") }, closeDelay);     
}

Java Reflection Performance

If there really is need for something faster than reflection, and it's not just a premature optimization, then bytecode generation with ASM or a higher level library is an option. Generating the bytecode the first time is slower than just using reflection, but once the bytecode has been generated, it is as fast as normal Java code and will be optimized by the JIT compiler.

Some examples of applications which use code generation:

  • Invoking methods on proxies generated by CGLIB is slightly faster than Java's dynamic proxies, because CGLIB generates bytecode for its proxies, but dynamic proxies use only reflection (I measured CGLIB to be about 10x faster in method calls, but creating the proxies was slower).

  • JSerial generates bytecode for reading/writing the fields of serialized objects, instead of using reflection. There are some benchmarks on JSerial's site.

  • I'm not 100% sure (and I don't feel like reading the source now), but I think Guice generates bytecode to do dependency injection. Correct me if I'm wrong.

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

How to use MapView in android using google map V2?

More complete sample from here and here.

Or you can check out my layout sample. p.s no need to put API key in the map view.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
            android:id="@+id/map_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"
            />

    <ListView android:id="@+id/nearby_lv"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="@color/white"
              android:layout_weight="1"
            />

</LinearLayout>

How do I clone a single branch in Git?

You can try the long-winded way:

mkdir newrepo.git
cd newrepo.git
git init
git remote add origin file:///path/to/original
git fetch origin branchiwant:refs/remotes/origin/branchiwant
git checkout -b branchiwant --track origin/branchiwant

What this does is:

  • Create and init an empty Git repository.
  • Adds the original repository as a remote called origin.
  • Fetches only the branch you require from the remote called origin.
  • Creates and checks out a new branch that is set up to track the source branch you just cloned.

Hopefully that will be something like what you are after.

Remove directory which is not empty

I don't usually resurrect old threads but there is a lot on churn here and sans the rimraf answer these all seem overly complicated to me.

First in modern Node (>= v8.0.0) you can simplify the process using only node core modules, fully asynchronous, and parallelize the unlinking of files concurrently all in a function of five lines and still keep readability:

const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
const readdir = promisify(fs.readdir);
const rmdir = promisify(fs.rmdir);
const unlink = promisify(fs.unlink);

exports.rmdirs = async function rmdirs(dir) {
  let entries = await readdir(dir, { withFileTypes: true });
  await Promise.all(entries.map(entry => {
    let fullPath = path.join(dir, entry.name);
    return entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath);
  }));
  await rmdir(dir);
};

On another note a guard for path traversal attacks is inappropriate for this function because

  1. It is out of scope based on the Single Responsibility Principle.
  2. Should be handled by the caller not this function. This is akin to the command-line rm -rf in that it takes an argument and will allow the user to rm -rf / if asked to. It would be the responsibility of a script to guard not the rm program itself.
  3. This function would be unable to determine such an attack since it does not have a frame of reference. Again that is the responsibility of the caller who would have the context of intent which would provide it a reference to compare the path traversal.
  4. Sym-links are not a concern as .isDirectory() is false for sym-links and are unlinked not recursed into.

Last but not least, there is a rare race condition that the recursion could error if one of the entries was unlinked or deleted outside this script at just the right time while this recursion is running. Since this scenario is not typical in most environments it can likely be overlooked. However, if required (for some edge cases) this issue can be mitigated with this slightly more complex example:

exports.rmdirs = async function rmdirs(dir) {
  let entries = await readdir(dir, { withFileTypes: true });
  let results = await Promise.all(entries.map(entry => {
    let fullPath = path.join(dir, entry.name);
    let task = entry.isDirectory() ? rmdirs(fullPath) : unlink(fullPath);
    return task.catch(error => ({ error }));
  }));
  results.forEach(result => {
    // Ignore missing files/directories; bail on other errors
    if (result && result.error.code !== 'ENOENT') throw result.error;
  });
  await rmdir(dir);
};

EDIT: Make isDirectory() a function. Remove the actual directory at the end. Fix missing recursion.

Android; Check if file exists without creating a new one

Your chunk of code does not create a new one, it only checks if its already there and nothing else.

File file = new File(filePath);
if(file.exists())      
//Do something
else
// Do something else.

How do I write good/correct package __init__.py files

My own __init__.py files are empty more often than not. In particular, I never have a from blah import * as part of __init__.py -- if "importing the package" means getting all sort of classes, functions etc defined directly as part of the package, then I would lexically copy the contents of blah.py into the package's __init__.py instead and remove blah.py (the multiplication of source files does no good here).

If you do insist on supporting the import * idioms (eek), then using __all__ (with as miniscule a list of names as you can bring yourself to have in it) may help for damage control. In general, namespaces and explicit imports are good things, and I strong suggest reconsidering any approach based on systematically bypassing either or both concepts!-)

I want to exception handle 'list index out of range.'

for i in range (1, len(list))
    try:
        print (list[i])

    except ValueError:
        print("Error Value.")
    except indexError:
        print("Erorr index")
    except :
        print('error ')

How do I calculate the normal vector of a line segment?

If we define dx = x2 - x1 and dy = y2 - y1, then the normals are (-dy, dx) and (dy, -dx).

Note that no division is required, and so you're not risking dividing by zero.

Reducing video size with same format and reducing frame size

ffmpeg -i <input.mp4> -b:v 2048k -s 1000x600 -fs 2048k -vcodec mpeg4 -acodec copy <output.mp4>
  • -i input file

  • -b:v videobitrate of output video in kilobytes (you have to try)

  • -s dimensions of output video

  • -fs FILESIZE of output video in kilobytes

  • -vcodec videocodec (use ffmpeg -codecs to list all available codecs)

  • -acodec audio codec for output video (only copy the audiostream, don't temper)

Find the smallest positive integer that does not occur in a given sequence

For JavaScript i would do it this way:

function solution(arr)
{
    let minValue = 1;

    arr.sort();

    if (arr[arr.length - 1] > 0)
    {
        for (let i = 0; i < arr.length; i++)
        {
            if (arr[i] === minValue)
            {
                minValue = minValue + 1;
            }
            if (arr[i] > minValue)
            {
                break;
            }
        }
    }

    return minValue;
}

Tested it with the following sample data:

console.log(solution([1, 3, 6, 4, 1, 2]));
console.log(solution([1, 2, 3]));
console.log(solution([-1, -3]));

Count occurrences of a char in a string using Bash

also check this out, for example we wanna count t

echo "test" | awk -v RS='t' 'END{print NR-1}'

or in python

python -c 'print "this is for test".count("t")'

or even better, we can make our script dynamic with awk

echo 'test' | awk '{for (i=1 ; i<=NF ; i++) array[$i]++ } END{ for (char in array) print char,array[char]}' FS=""

in this case output is like this :

e 1
s 1
t 2

Angular 2 optional route parameter

Ran into another instance of this problem, and in searching for a solution to it came here. My issue was that I was doing the children, and lazy loading of the components as well to optimize things a bit. In short if you are lazy loading the parent module. Main thing was my using '/:id' in the route, and it's complaints about '/' being a part of it. Not the exact problem here, but it applies.

App-routing from parent

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'pathOne',
        loadChildren: 'app/views/$MODULE_PATH.module#PathOneModule'
      },
      {
        path: 'pathTwo',
        loadChildren: 'app/views/$MODULE_PATH.module#PathTwoModule'
      },
...

Child routes lazy loaded

...
const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: OverviewComponent
      },
      {
        path: ':id',
        component: DetailedComponent
      },
    ]
  }
];
...

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Converting newline formatting from Mac to Windows

vim also can convert files from UNIX to DOS format. For example:

vim hello.txt <<EOF
:set fileformat=dos
:wq
EOF

Download Excel file via AJAX MVC

CSL's answer was implemented in a project I'm working on but the problem I incurred was scaling out on Azure broke our file downloads. Instead, I was able to do this with one AJAX call:

SERVER

[HttpPost]
public FileResult DownloadInvoice(int id1, int id2)
{
    //necessary to get the filename in the success of the ajax callback
    HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");

    byte[] fileBytes = _service.GetInvoice(id1, id2);
    string fileName = "Invoice.xlsx";
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

CLIENT (modified version of Handle file download from ajax post)

$("#downloadInvoice").on("click", function() {
    $("#loaderInvoice").removeClass("d-none");

    var xhr = new XMLHttpRequest();
    var params = [];
    xhr.open('POST', "@Html.Raw(Url.Action("DownloadInvoice", "Controller", new { id1 = Model.Id1, id2 = Model.Id2 }))", true);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status === 200) {
            var filename = "";
            var disposition = xhr.getResponseHeader('Content-Disposition');
            if (disposition && disposition.indexOf('attachment') !== -1) {
                var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                var matches = filenameRegex.exec(disposition);
                if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
            }
            var type = xhr.getResponseHeader('Content-Type');

            var blob = typeof File === 'function'
                ? new File([this.response], filename, { type: type })
                : new Blob([this.response], { type: type });
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
                // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed."
                window.navigator.msSaveBlob(blob, filename);
            } else {
                var URL = window.URL || window.webkitURL;
                var downloadUrl = URL.createObjectURL(blob);

                if (filename) {
                    // use HTML5 a[download] attribute to specify filename
                    var a = document.createElement("a");
                    // safari doesn't support this yet
                    if (typeof a.download === 'undefined') {
                        window.location = downloadUrl;
                    } else {
                        a.href = downloadUrl;
                        a.download = filename;
                        document.body.appendChild(a);
                        a.click();
                    }
                } else {
                    window.location = downloadUrl;

                }

                setTimeout(function() {
                        URL.revokeObjectURL(downloadUrl);
                    $("#loaderInvoice").addClass("d-none");
                }, 100); // cleanup
            }
        }
    };
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    xhr.send($.param(params));
});

SVN 405 Method Not Allowed

I got this error because I replaced URL address with new one ending up with "/". I mean record in wc.db database in .svn folder in REPOSITORY table.

When I removed sign: "/" then the error went away.

How do I add indices to MySQL tables?

ALTER TABLE TABLE_NAME ADD INDEX (COLUMN_NAME);

Build error: "The process cannot access the file because it is being used by another process"

I struggled with issue for 5 days and could get the source of the problem through Event Viewer Logs; Port 443, my application trying to access was in use, so I had to change the registry settings ; Basically you will b able to reach to source of issue thru error logs in event viewer.

Save and retrieve image (binary) from SQL Server using Entity Framework 6

Convert the image to a byte[] and store that in the database.


Add this column to your model:

public byte[] Content { get; set; }

Then convert your image to a byte array and store that like you would any other data:

public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
    using(var ms = new MemoryStream())
    {
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);

        return ms.ToArray();
    }
}

public Image ByteArrayToImage(byte[] byteArrayIn)
{
     using(var ms = new MemoryStream(byteArrayIn))
     {
         var returnImage = Image.FromStream(ms);

         return returnImage;
     }
}

Source: Fastest way to convert Image to Byte array

var image = new ImageEntity()
{
   Content = ImageToByteArray(image)
};

_context.Images.Add(image);
_context.SaveChanges();

When you want to get the image back, get the byte array from the database and use the ByteArrayToImage and do what you wish with the Image

This stops working when the byte[] gets to big. It will work for files under 100Mb

Extract a page from a pdf as a jpeg

GhostScript performs much faster than Poppler for a Linux based system.

Following is the code for pdf to image conversion.

def get_image_page(pdf_file, out_file, page_num):
    page = str(page_num + 1)
    command = ["gs", "-q", "-dNOPAUSE", "-dBATCH", "-sDEVICE=png16m", "-r" + str(RESOLUTION), "-dPDFFitPage",
               "-sOutputFile=" + out_file, "-dFirstPage=" + page, "-dLastPage=" + page,
               pdf_file]
    f_null = open(os.devnull, 'w')
    subprocess.call(command, stdout=f_null, stderr=subprocess.STDOUT)

GhostScript can be installed on macOS using brew install ghostscript

Installation information for other platforms can be found here. If it is not already installed on your system.

How to populate HTML dropdown list with values from database

<select name="owner">
<?php 
$sql = mysql_query("SELECT username FROM users");
while ($row = mysql_fetch_array($sql)){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

Show a div with Fancybox

Simple: e.g. if div id 'mydiv'

jQuery.fancybox.open({href: "#mydiv"});

This also makes JS code functional which is inside div.

Change the column label? e.g.: change column "A" to column "Name"

What version of Excel?

In general, you cannot change the column letters. They are part of the Excel system.

You can use a row in the sheet to enter headers for a table that you are using. The table headers can be descriptive column names.

In Excel 2007 and later, you can convert a range of data into an Excel Table (Insert Ribbon > Table). An Excel Table can use structured table references instead of cell addresses, so the labels in the first row of the table now serve as a name reference for the data in the column.

If you have an Excel Table in your sheet (Excel 2007 and later) and scroll down, the column letters will be replaced with the column headers for the table column.

enter image description here

If this does not answer your question, please consider editing your question to include the detail you want to learn about.

Get sum of MySQL column in PHP

Try this:

$sql = mysql_query("SELECT SUM(Value) as total FROM Codes");
$row = mysql_fetch_array($sql);
$sum = $row['total'];

What is the simplest method of inter-process communication between 2 C# processes?

The easiest solution in C# for inter-process communication when security is not a concern and given your constraints (two C# processes on the same machine) is the Remoting API. Now Remoting is a legacy technology (not the same as deprecated) and not encouraged for use in new projects, but it does work well and does not require a lot of pomp and circumstance to get working.

There is an excellent article on MSDN for using the class IpcChannel from the Remoting framework (credit to Greg Beech for the find here) for setting up a simple remoting server and client.

I Would suggest trying this approach first, and then try to port your code to WCF (Windows Communication Framework). Which has several advantages (better security, cross-platform), but is necessarily more complex. Luckily MSDN has a very good article for porting code from Remoting to WCF.

If you want to dive in right away with WCF there is a great tutorial here.

IOS - How to segue programmatically using swift

If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using

self.performSegueWithIdentifier("yourIdentifierInStoryboard", sender: self)

If you are in Navigation controller

let viewController = YourViewController(nibName: "YourViewController", bundle: nil)        
self.navigationController?.pushViewController(viewController, animated: true)

I will recommend you for second approach using navigation controller.

TypeError: $(...).DataTable is not a function

Here is the complete set of JS and CSS required for the export table plugin to work perfectly.

Hope it will save your time

   <!--Import jQuery before export.js-->
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>


    <!--Data Table-->
    <script type="text/javascript"  src=" https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript"  src=" https://cdn.datatables.net/buttons/1.2.4/js/dataTables.buttons.min.js"></script>

    <!--Export table buttons-->
    <script type="text/javascript"  src="https://cdnjs.cloudflare.com/ajax/libs/jszip/2.5.0/jszip.min.js"></script>
    <script type="text/javascript" src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/pdfmake.min.js" ></script>
    <script type="text/javascript"  src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.24/build/vfs_fonts.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.4/js/buttons.html5.min.js"></script>
    <script type="text/javascript" src="https://cdn.datatables.net/buttons/1.2.1/js/buttons.print.min.js"></script>

<!--Export table button CSS-->

<link rel="stylesheet" href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.2.4/css/buttons.dataTables.min.css">

javascript to add export buttons on the table with id = tbl

  $('#tbl').DataTable({
                        dom: 'Bfrtip',
                        buttons: [
                            'copy', 'csv', 'excel', 'pdf', 'print'
                        ]
                    });

Result :-

enter image description here

DBCC CHECKIDENT Sets Identity to 0

I have used this in SQL to set IDENTITY to a particular value:-

DECLARE @ID int = 42;
DECLARE @TABLENAME  varchar(50) = 'tablename'

DECLARE @SQL nvarchar(1000) = 'IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = '''+@TABLENAME+''' AND last_value IS NOT NULL)
    BEGIN
        DBCC CHECKIDENT('+@TABLENAME+', RESEED,' + CONVERT(VARCHAR(10),@ID-1)+');
    END
    ELSE
    BEGIN
        DBCC CHECKIDENT('+@TABLENAME+', RESEED,' + CONVERT(VARCHAR(10),@ID)+');
    END';
EXEC (@SQL);

And this in C# to set a particular value:-

SetIdentity(context, "tablename", 42);
.
.
private static void SetIdentity(DbContext context, string table,int id)
{
    string str = "IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = '" + table
        + "' AND last_value IS NOT NULL)\nBEGIN\n";
    str += "DBCC CHECKIDENT('" + table + "', RESEED," + (id - 1).ToString() + ");\n";
    str += "END\nELSE\nBEGIN\n";
    str += "DBCC CHECKIDENT('" + table + "', RESEED," + (id).ToString() + ");\n";
    str += "END\n";
    context.Database.ExecuteSqlCommand(str);
}

This builds on the above answers and always makes sure the next value is 42 (in this case).

Java: convert List<String> to a String

You can use the apache commons library which has a StringUtils class and a join method.

Check this link: https://commons.apache.org/proper/commons-lang/javadocs/api.2.0/org/apache/commons/lang/StringUtils.html

Note that the link above may become obsolete over time, in which case you can just search the web for "apache commons StringUtils", which should allow you to find the latest reference.

(referenced from this thread) Java equivalents of C# String.Format() and String.Join()

When to use 'npm start' and when to use 'ng serve'?

If you want to run angular app ported from another machine without ng command then edit package.json as follows

"scripts": {
    "ng": "ng",
    "start": "node node_modules/.bin/ng serve",
    "build": "node node_modules/.bin/ng build",
    "test": "node node_modules/.bin/ng test",
    "lint": "node node_modules/.bin/ng lint",
    "e2e": "node node_modules/.bin/ng e2e"
  }

Finally run usual npm start command to start build server.

How to set component default props on React component

For a function type prop you can use the following code:

AddAddressComponent.defaultProps = {
    callBackHandler: () => {}
};

AddAddressComponent.propTypes = {
    callBackHandler: PropTypes.func,
};

Iterating through a range of dates in Python

import datetime

def daterange(start, stop, step=datetime.timedelta(days=1), inclusive=False):
  # inclusive=False to behave like range by default
  if step.days > 0:
    while start < stop:
      yield start
      start = start + step
      # not +=! don't modify object passed in if it's mutable
      # since this function is not restricted to
      # only types from datetime module
  elif step.days < 0:
    while start > stop:
      yield start
      start = start + step
  if inclusive and start == stop:
    yield start

# ...

for date in daterange(start_date, end_date, inclusive=True):
  print strftime("%Y-%m-%d", date.timetuple())

This function does more than you strictly require, by supporting negative step, etc. As long as you factor out your range logic, then you don't need the separate day_count and most importantly the code becomes easier to read as you call the function from multiple places.

Finding all objects that have a given property inside a collection

Try the commons collections API:

List<Cat> bigList = ....; // master list

Collection<Cat> smallList = CollectionUtils.select(bigList, new Predicate() {
    public boolean evaluate(Object o) {
        Cat c = (Cat)o;
        return c.getFavoriteFood().equals("Wiskas") 
            && c.getWhateverElse().equals(Something);
    }
});

Of course you don't have to use an anonymous class every time, you could create implementations of the Predicate interface for commonly used searchs.

error::make_unique is not a member of ‘std’

In my case I was needed update the std=c++

I mean in my gradle file was this

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11", "-Wall"
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

I changed this line

android {
    ...

    defaultConfig {
        ...

        externalNativeBuild {
            cmake {
                cppFlags "-std=c++17", "-Wall"   <-- this number from 11 to 17 (or 14)
                arguments "-DANDROID_STL=c++_static",
                        "-DARCORE_LIBPATH=${arcore_libpath}/jni",
                        "-DARCORE_INCLUDE=${project.rootDir}/app/src/main/libs"
            }
        }
       ....
    }

That's it...

How can I check if a single character appears in a string?

String.contains(String) or String.indexOf(String) - suggested

"abc".contains("Z"); // false - correct
"zzzz".contains("Z"); // false - correct
"Z".contains("Z"); // true - correct
"and".contains(""); // true - correct
"and".contains(""); // false - correct
"and".indexOf(""); // 0 - correct
"and".indexOf(""); // -1 - correct

String.indexOf(int) and carefully considered String.indexOf(char) with char to int widening

"and".indexOf("".charAt(0)); // 0 though incorrect usage has correct output due to portion of correct data
"and".indexOf("".charAt(0)); // 0 -- incorrect usage and ambiguous result
"and".indexOf("".codePointAt(0)); // -1 -- correct usage and correct output

The discussions around character is ambiguous in Java world

can the value of char or Character considered as single character?

No. In the context of unicode characters, char or Character can sometimes be part of a single character and should not be treated as a complete single character logically.

if not, what should be considered as single character (logically)?

Any system supporting character encodings for Unicode characters should consider unicode's codepoint as single character.

So Java should do that very clear & loud rather than exposing too much of internal implementation details to users.

String class is bad at abstraction (though it requires confusingly good amount of understanding of its encapsulations to understand the abstraction and hence an anti-pattern).

How is it different from general char usage?

char can be only be mapped to a character in Basic Multilingual Plane.

Only codePoint - int can cover the complete range of Unicode characters.

Why is this difference?

char is internally treated as 16-bit unsigned value and could not represent all the unicode characters using UTF-16 internal representation using only 2-bytes. Sometimes, values in a 16-bit range have to be combined with another 16-bit value to correctly define character.

Without getting too verbose, the usage of indexOf, charAt, length and such methods should be more explicit. Sincerely hoping Java will add new UnicodeString and UnicodeCharacter classes with clearly defined abstractions.

Reason to prefer contains and not indexOf(int)

  1. Practically there are many code flows that treat a logical character as char in java.
  2. In Unicode context, char is not sufficient
  3. Though the indexOf takes in an int, char to int conversion masks this from the user and user might do something like str.indexOf(someotherstr.charAt(0))(unless the user is aware of the exact context)
  4. So, treating everything as CharSequence (aka String) is better
    public static void main(String[] args) {
        System.out.println("and".indexOf("".charAt(0))); // 0 though incorrect usage has correct output due to portion of correct data
        System.out.println("and".indexOf("".charAt(0))); // 0 -- incorrect usage and ambiguous result
        System.out.println("and".indexOf("".codePointAt(0))); // -1 -- correct usage and correct output
        System.out.println("and".contains("")); // true - correct
        System.out.println("and".contains("")); // false - correct
    }

How to add a default "Select" option to this ASP.NET DropDownList control?

If you want to make the first item unselectable, try this:

DropDownList1.Items.Insert(0, new ListItem("Select", "-1"));
DropDownList1.Items[0].Attributes.Add("disabled", "disabled");

Passing a string with spaces as a function argument in bash

Another solution to the issue above is to set each string to a variable, call the function with variables denoted by a literal dollar sign \$. Then in the function use eval to read the variable and output as expected.

#!/usr/bin/ksh

myFunction()
{
  eval string1="$1"
  eval string2="$2"
  eval string3="$3"

  echo "string1 = ${string1}"
  echo "string2 = ${string2}"
  echo "string3 = ${string3}"
}

var1="firstString"
var2="second string with spaces"
var3="thirdString"

myFunction "\${var1}" "\${var2}" "\${var3}"

exit 0

Output is then:

    string1 = firstString
    string2 = second string with spaces
    string3 = thirdString

In trying to solve a similar problem to this, I was running into the issue of UNIX thinking my variables were space delimeted. I was trying to pass a pipe delimited string to a function using awk to set a series of variables later used to create a report. I initially tried the solution posted by ghostdog74 but could not get it to work as not all of my parameters were being passed in quotes. After adding double-quotes to each parameter it then began to function as expected.

Below is the before state of my code and fully functioning after state.

Before - Non Functioning Code

#!/usr/bin/ksh

#*******************************************************************************
# Setup Function To Extract Each Field For The Error Report
#*******************************************************************************
getField(){
  detailedString="$1"
  fieldNumber=$2

  # Retrieves Column ${fieldNumber} From The Pipe Delimited ${detailedString} 
  #   And Strips Leading And Trailing Spaces
  echo ${detailedString} | awk -F '|' -v VAR=${fieldNumber} '{ print $VAR }' | sed 's/^[ \t]*//;s/[ \t]*$//'
}

while read LINE
do
  var1="$LINE"

  # Below Does Not Work Since There Are Not Quotes Around The 3
  iputId=$(getField "${var1}" 3)
done<${someFile}

exit 0

After - Functioning Code

#!/usr/bin/ksh

#*******************************************************************************
# Setup Function To Extract Each Field For The Report
#*******************************************************************************
getField(){
  detailedString="$1"
  fieldNumber=$2

  # Retrieves Column ${fieldNumber} From The Pipe Delimited ${detailedString} 
  #   And Strips Leading And Trailing Spaces
  echo ${detailedString} | awk -F '|' -v VAR=${fieldNumber} '{ print $VAR }' | sed 's/^[ \t]*//;s/[ \t]*$//'
}

while read LINE
do
  var1="$LINE"

  # Below Now Works As There Are Quotes Around The 3
  iputId=$(getField "${var1}" "3")
done<${someFile}

exit 0

How can you program if you're blind?

I'm a postgraduate student in Beijing,China. I major in computer science and a lot of my work is programming. I am born with low sight, I need to use magnifying tools to see fonts on screen clearly. I use microsoft's mgnify tools on windows and use compiz's magnify plug in if on linux. I usally set the tool to magnify as three times many as the original font size. For me maginify tools is ok, the main problem is the speed,I have to move mouse to keep cursors follow the text I'm looking at, microsoft's magnify provides a option of "auto follow the text edit points",that set me from continuously mouse movement when editting or coding. But it doesn't always works because of the edit software or IDE may not support that. Magnifying tools on linux are hard to use. The KMag come with KDE has a terrible refresh rate which make my eyes unconfortable, compiz's magnifying plugs which I'm using now is OK,but has no function of auto focus(focus auto following). iOS provides quite perfect solution for me with full screen magnifying, especially on ipad's 9.7 inches screen. there auto focus is not necessary because I hardly use them to code or do other edit stuff. Android provides very little accessibility functions, only like shake feedback, which is useless for me. there is no any kind of good magnifying tools on android , not to mention advance function like full screen magnify on iOS. I used to study Qt, want to build a useful magnify tools on linux, even on android. But hardly have some progress.

How to clean project cache in Intellij idea like Eclipse's clean?

In addition to the .Intellij* files, and invalidating the cache, if you really want to clear everything out, then also delete the .idea folder and *.iml per-project files that IntelliJ also generates...

"id cannot be resolved or is not a field" error?

One possible solution:-

Summary: make sure you are using import com.yourpkgdomainname.yourpkgappname.R instead of import android.R

Details: The problem occured when I changed ID of a label which was being referred in other places in the layout XML file. Due to this error, the R file stopped generating at first. Eclipse is bad in handling errors with the layout files.

When I corrected the ID reference (with project clean few times and Eclipse restarts, I noticed that my import packages now has:
import android.R

Changing it to following fixed the error:
import com.example.app.R

Measure string size in Bytes in php

You can use mb_strlen() to get the byte length using a encoding that only have byte-characters, without worring about multibyte or singlebyte strings. For example, as drake127 saids in a comment of mb_strlen, you can use '8bit' encoding:

<?php
    $string = 'Cién cañones por banda';
    echo mb_strlen($string, '8bit');
?>

You can have problems using strlen function since php have an option to overload strlen to actually call mb_strlen. See more info about it in http://php.net/manual/en/mbstring.overload.php

For trim the string by byte length without split in middle of a multibyte character you can use:

mb_strcut(string $str, int $start [, int $length [, string $encoding ]] )

Copy existing project with a new name in Android Studio

When refactoring the package name in Android Studio, you may need to click the little cogwheel up to the right by the package/android/project/etc - navigator and uncheck 'compact empty middle packages' in order to see each part of the package name as an own directory. Then for individual directories do refactor.

This is important if you need to change all parts of the package name. For example, from com.example.originalproject to org.mydomain.newproject. Otherwise, the refactor/rename operation will only let you change "originalproject" to "newproject", and it will leave "com.example" unchanged. There is a good video that shows this: https://www.youtube.com/watch?v=dMK-RBVLeIY

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

Generate random int value from 3 to 6

DECLARE @min INT = 3;
DECLARE @max INT = 6;
SELECT @min + ROUND(RAND() * (@max - @min), 0);

Step by step

DECLARE @min INT = 3;
DECLARE @max INT = 6;

DECLARE @rand DECIMAL(19,4) = RAND();
DECLARE @difference INT = @max - @min;
DECLARE @chunk INT = ROUND(@rand * @difference, 0);
DECLARE @result INT = @min + @chunk; 
SELECT @result;

Note that a user-defined function thus not allow the use of RAND(). A workaround for this (source: http://blog.sqlauthority.com/2012/11/20/sql-server-using-rand-in-user-defined-functions-udf/) is to create a view first.

CREATE VIEW [dbo].[vw_RandomSeed]
AS
SELECT        RAND() AS seed

and then create the random function

CREATE FUNCTION udf_RandomNumberBetween
(
    @min INT,
    @max INT
)
RETURNS INT
AS
BEGIN
    RETURN @min + ROUND((SELECT TOP 1 seed FROM vw_RandomSeed) * (@max - @min), 0);
END

Using C# to read/write Excel files (.xls/.xlsx)

If you want easy to use libraries, you can use the NUGET packages:

  • ExcelDataReader - to read Excel files (most file formats)
  • SwiftExcel - to write Excel files (.xlsx)

Note these are 3rd-Party packages - you can use them for basic functionality for free, but if you want more features there might be a "pro" version.

They are using a two-dimensional object array (i.e. object[][] cells) to read / write data.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

Just like that nice warning you got, you are trying to do something that is an Anti-Pattern in React. This is a no-no. React is intended to have an unmount happen from a parent to child relationship. Now if you want a child to unmount itself, you can simulate this with a state change in the parent that is triggered by the child. let me show you in code.

class Child extends React.Component {
    constructor(){}
    dismiss() {
        this.props.unmountMe();
    } 
    render(){
        // code
    }
}

class Parent ...
    constructor(){
        super(props)
        this.state = {renderChild: true};
        this.handleChildUnmount = this.handleChildUnmount.bind(this);
    }
    handleChildUnmount(){
        this.setState({renderChild: false});
    }
    render(){
        // code
        {this.state.renderChild ? <Child unmountMe={this.handleChildUnmount} /> : null}
    }

}

this is a very simple example. but you can see a rough way to pass through to the parent an action

That being said you should probably be going through the store (dispatch action) to allow your store to contain the correct data when it goes to render

I've done error/status messages for two separate applications, both went through the store. It's the preferred method... If you'd like I can post some code as to how to do that.

EDIT: Here is how I set up a notification system using React/Redux/Typescript

Few things to note first. this is in typescript so you would need to remove the type declarations :)

I am using the npm packages lodash for operations, and classnames (cx alias) for inline classname assignment.

The beauty of this setup is I use a unique identifier for each notification when the action creates it. (e.g. notify_id). This unique ID is a Symbol(). This way if you want to remove any notification at any point in time you can because you know which one to remove. This notification system will let you stack as many as you want and they will go away when the animation is completed. I am hooking into the animation event and when it finishes I trigger some code to remove the notification. I also set up a fallback timeout to remove the notification just in case the animation callback doesn't fire.

notification-actions.ts

import { USER_SYSTEM_NOTIFICATION } from '../constants/action-types';

interface IDispatchType {
    type: string;
    payload?: any;
    remove?: Symbol;
}

export const notifySuccess = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: true, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const notifyFailure = (message: any, duration?: number) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, payload: { isSuccess: false, message, notify_id: Symbol(), duration } } as IDispatchType);
    };
};

export const clearNotification = (notifyId: Symbol) => {
    return (dispatch: Function) => {
        dispatch({ type: USER_SYSTEM_NOTIFICATION, remove: notifyId } as IDispatchType);
    };
};

notification-reducer.ts

const defaultState = {
    userNotifications: []
};

export default (state: ISystemNotificationReducer = defaultState, action: IDispatchType) => {
    switch (action.type) {
        case USER_SYSTEM_NOTIFICATION:
            const list: ISystemNotification[] = _.clone(state.userNotifications) || [];
            if (_.has(action, 'remove')) {
                const key = parseInt(_.findKey(list, (n: ISystemNotification) => n.notify_id === action.remove));
                if (key) {
                    // mutate list and remove the specified item
                    list.splice(key, 1);
                }
            } else {
                list.push(action.payload);
            }
            return _.assign({}, state, { userNotifications: list });
    }
    return state;
};

app.tsx

in the base render for your application you would render the notifications

render() {
    const { systemNotifications } = this.props;
    return (
        <div>
            <AppHeader />
            <div className="user-notify-wrap">
                { _.get(systemNotifications, 'userNotifications') && Boolean(_.get(systemNotifications, 'userNotifications.length'))
                    ? _.reverse(_.map(_.get(systemNotifications, 'userNotifications', []), (n, i) => <UserNotification key={i} data={n} clearNotification={this.props.actions.clearNotification} />))
                    : null
                }
            </div>
            <div className="content">
                {this.props.children}
            </div>
        </div>
    );
}

user-notification.tsx

user notification class

/*
    Simple notification class.

    Usage:
        <SomeComponent notifySuccess={this.props.notifySuccess} notifyFailure={this.props.notifyFailure} />
        these two functions are actions and should be props when the component is connect()ed

    call it with either a string or components. optional param of how long to display it (defaults to 5 seconds)
        this.props.notifySuccess('it Works!!!', 2);
        this.props.notifySuccess(<SomeComponentHere />, 15);
        this.props.notifyFailure(<div>You dun goofed</div>);

*/

interface IUserNotifyProps {
    data: any;
    clearNotification(notifyID: symbol): any;
}

export default class UserNotify extends React.Component<IUserNotifyProps, {}> {
    public notifyRef = null;
    private timeout = null;

    componentDidMount() {
        const duration: number = _.get(this.props, 'data.duration', '');
       
        this.notifyRef.style.animationDuration = duration ? `${duration}s` : '5s';

        
        // fallback incase the animation event doesn't fire
        const timeoutDuration = (duration * 1000) + 500;
        this.timeout = setTimeout(() => {
            this.notifyRef.classList.add('hidden');
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }, timeoutDuration);

        TransitionEvents.addEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    componentWillUnmount() {
        clearTimeout(this.timeout);

        TransitionEvents.removeEndEventListener(
            this.notifyRef,
            this.onAmimationComplete
        );
    }
    onAmimationComplete = (e) => {
        if (_.get(e, 'animationName') === 'fadeInAndOut') {
            this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
        }
    }
    handleCloseClick = (e) => {
        e.preventDefault();
        this.props.clearNotification(_.get(this.props, 'data.notify_id') as symbol);
    }
    assignNotifyRef = target => this.notifyRef = target;
    render() {
        const {data, clearNotification} = this.props;
        return (
            <div ref={this.assignNotifyRef} className={cx('user-notification fade-in-out', {success: data.isSuccess, failure: !data.isSuccess})}>
                {!_.isString(data.message) ? data.message : <h3>{data.message}</h3>}
                <div className="close-message" onClick={this.handleCloseClick}>+</div>
            </div>
        );
    }
}

How to remove last n characters from every element in the R vector

Similar to @Matthew_Plourde using gsub

However, using a pattern that will trim to zero characters i.e. return "" if the original string is shorter than the number of characters to cut:

cs <- c("foo_bar","bar_foo","apple","beer","so","a")
gsub('.{0,3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"    ""    ""

Difference is, {0,3} quantifier indicates 0 to 3 matches, whereas {3} requires exactly 3 matches otherwise no match is found in which case gsub returns the original, unmodified string.

N.B. using {,3} would be equivalent to {0,3}, I simply prefer the latter notation.

See here for more information on regex quantifiers: https://www.regular-expressions.info/refrepeat.html