Programs & Examples On #Odt

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

Cast object to interface in TypeScript

Here's another way to force a type-cast even between incompatible types and interfaces where TS compiler normally complains:

export function forceCast<T>(input: any): T {

  // ... do runtime checks here

  // @ts-ignore <-- forces TS compiler to compile this as-is
  return input;
}

Then you can use it to force cast objects to a certain type:

import { forceCast } from './forceCast';

const randomObject: any = {};
const typedObject = forceCast<IToDoDto>(randomObject);

Note that I left out the part you are supposed to do runtime checks before casting for the sake of reducing complexity. What I do in my project is compiling all my .d.ts interface files into JSON schemas and using ajv to validate in runtime.

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

If you think a 64-bit DIV instruction is a good way to divide by two, then no wonder the compiler's asm output beat your hand-written code, even with -O0 (compile fast, no extra optimization, and store/reload to memory after/before every C statement so a debugger can modify variables).

See Agner Fog's Optimizing Assembly guide to learn how to write efficient asm. He also has instruction tables and a microarch guide for specific details for specific CPUs. See also the tag wiki for more perf links.

See also this more general question about beating the compiler with hand-written asm: Is inline assembly language slower than native C++ code?. TL:DR: yes if you do it wrong (like this question).

Usually you're fine letting the compiler do its thing, especially if you try to write C++ that can compile efficiently. Also see is assembly faster than compiled languages?. One of the answers links to these neat slides showing how various C compilers optimize some really simple functions with cool tricks. Matt Godbolt's CppCon2017 talk “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid” is in a similar vein.


even:
    mov rbx, 2
    xor rdx, rdx
    div rbx

On Intel Haswell, div r64 is 36 uops, with a latency of 32-96 cycles, and a throughput of one per 21-74 cycles. (Plus the 2 uops to set up RBX and zero RDX, but out-of-order execution can run those early). High-uop-count instructions like DIV are microcoded, which can also cause front-end bottlenecks. In this case, latency is the most relevant factor because it's part of a loop-carried dependency chain.

shr rax, 1 does the same unsigned division: It's 1 uop, with 1c latency, and can run 2 per clock cycle.

For comparison, 32-bit division is faster, but still horrible vs. shifts. idiv r32 is 9 uops, 22-29c latency, and one per 8-11c throughput on Haswell.


As you can see from looking at gcc's -O0 asm output (Godbolt compiler explorer), it only uses shifts instructions. clang -O0 does compile naively like you thought, even using 64-bit IDIV twice. (When optimizing, compilers do use both outputs of IDIV when the source does a division and modulus with the same operands, if they use IDIV at all)

GCC doesn't have a totally-naive mode; it always transforms through GIMPLE, which means some "optimizations" can't be disabled. This includes recognizing division-by-constant and using shifts (power of 2) or a fixed-point multiplicative inverse (non power of 2) to avoid IDIV (see div_by_13 in the above godbolt link).

gcc -Os (optimize for size) does use IDIV for non-power-of-2 division, unfortunately even in cases where the multiplicative inverse code is only slightly larger but much faster.


Helping the compiler

(summary for this case: use uint64_t n)

First of all, it's only interesting to look at optimized compiler output. (-O3). -O0 speed is basically meaningless.

Look at your asm output (on Godbolt, or see How to remove "noise" from GCC/clang assembly output?). When the compiler doesn't make optimal code in the first place: Writing your C/C++ source in a way that guides the compiler into making better code is usually the best approach. You have to know asm, and know what's efficient, but you apply this knowledge indirectly. Compilers are also a good source of ideas: sometimes clang will do something cool, and you can hand-hold gcc into doing the same thing: see this answer and what I did with the non-unrolled loop in @Veedrac's code below.)

This approach is portable, and in 20 years some future compiler can compile it to whatever is efficient on future hardware (x86 or not), maybe using new ISA extension or auto-vectorizing. Hand-written x86-64 asm from 15 years ago would usually not be optimally tuned for Skylake. e.g. compare&branch macro-fusion didn't exist back then. What's optimal now for hand-crafted asm for one microarchitecture might not be optimal for other current and future CPUs. Comments on @johnfound's answer discuss major differences between AMD Bulldozer and Intel Haswell, which have a big effect on this code. But in theory, g++ -O3 -march=bdver3 and g++ -O3 -march=skylake will do the right thing. (Or -march=native.) Or -mtune=... to just tune, without using instructions that other CPUs might not support.

My feeling is that guiding the compiler to asm that's good for a current CPU you care about shouldn't be a problem for future compilers. They're hopefully better than current compilers at finding ways to transform code, and can find a way that works for future CPUs. Regardless, future x86 probably won't be terrible at anything that's good on current x86, and the future compiler will avoid any asm-specific pitfalls while implementing something like the data movement from your C source, if it doesn't see something better.

Hand-written asm is a black-box for the optimizer, so constant-propagation doesn't work when inlining makes an input a compile-time constant. Other optimizations are also affected. Read https://gcc.gnu.org/wiki/DontUseInlineAsm before using asm. (And avoid MSVC-style inline asm: inputs/outputs have to go through memory which adds overhead.)

In this case: your n has a signed type, and gcc uses the SAR/SHR/ADD sequence that gives the correct rounding. (IDIV and arithmetic-shift "round" differently for negative inputs, see the SAR insn set ref manual entry). (IDK if gcc tried and failed to prove that n can't be negative, or what. Signed-overflow is undefined behaviour, so it should have been able to.)

You should have used uint64_t n, so it can just SHR. And so it's portable to systems where long is only 32-bit (e.g. x86-64 Windows).


BTW, gcc's optimized asm output looks pretty good (using unsigned long n): the inner loop it inlines into main() does this:

 # from gcc5.4 -O3  plus my comments

 # edx= count=1
 # rax= uint64_t n

.L9:                   # do{
    lea    rcx, [rax+1+rax*2]   # rcx = 3*n + 1
    mov    rdi, rax
    shr    rdi         # rdi = n>>1;
    test   al, 1       # set flags based on n%2 (aka n&1)
    mov    rax, rcx
    cmove  rax, rdi    # n= (n%2) ? 3*n+1 : n/2;
    add    edx, 1      # ++count;
    cmp    rax, 1
    jne   .L9          #}while(n!=1)

  cmp/branch to update max and maxi, and then do the next n

The inner loop is branchless, and the critical path of the loop-carried dependency chain is:

  • 3-component LEA (3 cycles)
  • cmov (2 cycles on Haswell, 1c on Broadwell or later).

Total: 5 cycle per iteration, latency bottleneck. Out-of-order execution takes care of everything else in parallel with this (in theory: I haven't tested with perf counters to see if it really runs at 5c/iter).

The FLAGS input of cmov (produced by TEST) is faster to produce than the RAX input (from LEA->MOV), so it's not on the critical path.

Similarly, the MOV->SHR that produces CMOV's RDI input is off the critical path, because it's also faster than the LEA. MOV on IvyBridge and later has zero latency (handled at register-rename time). (It still takes a uop, and a slot in the pipeline, so it's not free, just zero latency). The extra MOV in the LEA dep chain is part of the bottleneck on other CPUs.

The cmp/jne is also not part of the critical path: it's not loop-carried, because control dependencies are handled with branch prediction + speculative execution, unlike data dependencies on the critical path.


Beating the compiler

GCC did a pretty good job here. It could save one code byte by using inc edx instead of add edx, 1, because nobody cares about P4 and its false-dependencies for partial-flag-modifying instructions.

It could also save all the MOV instructions, and the TEST: SHR sets CF= the bit shifted out, so we can use cmovc instead of test / cmovz.

 ### Hand-optimized version of what gcc does
.L9:                       #do{
    lea     rcx, [rax+1+rax*2] # rcx = 3*n + 1
    shr     rax, 1         # n>>=1;    CF = n&1 = n%2
    cmovc   rax, rcx       # n= (n&1) ? 3*n+1 : n/2;
    inc     edx            # ++count;
    cmp     rax, 1
    jne     .L9            #}while(n!=1)

See @johnfound's answer for another clever trick: remove the CMP by branching on SHR's flag result as well as using it for CMOV: zero only if n was 1 (or 0) to start with. (Fun fact: SHR with count != 1 on Nehalem or earlier causes a stall if you read the flag results. That's how they made it single-uop. The shift-by-1 special encoding is fine, though.)

Avoiding MOV doesn't help with the latency at all on Haswell (Can x86's MOV really be "free"? Why can't I reproduce this at all?). It does help significantly on CPUs like Intel pre-IvB, and AMD Bulldozer-family, where MOV is not zero-latency. The compiler's wasted MOV instructions do affect the critical path. BD's complex-LEA and CMOV are both lower latency (2c and 1c respectively), so it's a bigger fraction of the latency. Also, throughput bottlenecks become an issue, because it only has two integer ALU pipes. See @johnfound's answer, where he has timing results from an AMD CPU.

Even on Haswell, this version may help a bit by avoiding some occasional delays where a non-critical uop steals an execution port from one on the critical path, delaying execution by 1 cycle. (This is called a resource conflict). It also saves a register, which may help when doing multiple n values in parallel in an interleaved loop (see below).

LEA's latency depends on the addressing mode, on Intel SnB-family CPUs. 3c for 3 components ([base+idx+const], which takes two separate adds), but only 1c with 2 or fewer components (one add). Some CPUs (like Core2) do even a 3-component LEA in a single cycle, but SnB-family doesn't. Worse, Intel SnB-family standardizes latencies so there are no 2c uops, otherwise 3-component LEA would be only 2c like Bulldozer. (3-component LEA is slower on AMD as well, just not by as much).

So lea rcx, [rax + rax*2] / inc rcx is only 2c latency, faster than lea rcx, [rax + rax*2 + 1], on Intel SnB-family CPUs like Haswell. Break-even on BD, and worse on Core2. It does cost an extra uop, which normally isn't worth it to save 1c latency, but latency is the major bottleneck here and Haswell has a wide enough pipeline to handle the extra uop throughput.

Neither gcc, icc, nor clang (on godbolt) used SHR's CF output, always using an AND or TEST. Silly compilers. :P They're great pieces of complex machinery, but a clever human can often beat them on small-scale problems. (Given thousands to millions of times longer to think about it, of course! Compilers don't use exhaustive algorithms to search for every possible way to do things, because that would take too long when optimizing a lot of inlined code, which is what they do best. They also don't model the pipeline in the target microarchitecture, at least not in the same detail as IACA or other static-analysis tools; they just use some heuristics.)


Simple loop unrolling won't help; this loop bottlenecks on the latency of a loop-carried dependency chain, not on loop overhead / throughput. This means it would do well with hyperthreading (or any other kind of SMT), since the CPU has lots of time to interleave instructions from two threads. This would mean parallelizing the loop in main, but that's fine because each thread can just check a range of n values and produce a pair of integers as a result.

Interleaving by hand within a single thread might be viable, too. Maybe compute the sequence for a pair of numbers in parallel, since each one only takes a couple registers, and they can all update the same max / maxi. This creates more instruction-level parallelism.

The trick is deciding whether to wait until all the n values have reached 1 before getting another pair of starting n values, or whether to break out and get a new start point for just one that reached the end condition, without touching the registers for the other sequence. Probably it's best to keep each chain working on useful data, otherwise you'd have to conditionally increment its counter.


You could maybe even do this with SSE packed-compare stuff to conditionally increment the counter for vector elements where n hadn't reached 1 yet. And then to hide the even longer latency of a SIMD conditional-increment implementation, you'd need to keep more vectors of n values up in the air. Maybe only worth with 256b vector (4x uint64_t).

I think the best strategy to make detection of a 1 "sticky" is to mask the vector of all-ones that you add to increment the counter. So after you've seen a 1 in an element, the increment-vector will have a zero, and +=0 is a no-op.

Untested idea for manual vectorization

# starting with YMM0 = [ n_d, n_c, n_b, n_a ]  (64-bit elements)
# ymm4 = _mm256_set1_epi64x(1):  increment vector
# ymm5 = all-zeros:  count vector

.inner_loop:
    vpaddq    ymm1, ymm0, xmm0
    vpaddq    ymm1, ymm1, xmm0
    vpaddq    ymm1, ymm1, set1_epi64(1)     # ymm1= 3*n + 1.  Maybe could do this more efficiently?

    vprllq    ymm3, ymm0, 63                # shift bit 1 to the sign bit

    vpsrlq    ymm0, ymm0, 1                 # n /= 2

    # FP blend between integer insns may cost extra bypass latency, but integer blends don't have 1 bit controlling a whole qword.
    vpblendvpd ymm0, ymm0, ymm1, ymm3       # variable blend controlled by the sign bit of each 64-bit element.  I might have the source operands backwards, I always have to look this up.

    # ymm0 = updated n  in each element.

    vpcmpeqq ymm1, ymm0, set1_epi64(1)
    vpandn   ymm4, ymm1, ymm4         # zero out elements of ymm4 where the compare was true

    vpaddq   ymm5, ymm5, ymm4         # count++ in elements where n has never been == 1

    vptest   ymm4, ymm4
    jnz  .inner_loop
    # Fall through when all the n values have reached 1 at some point, and our increment vector is all-zero

    vextracti128 ymm0, ymm5, 1
    vpmaxq .... crap this doesn't exist
    # Actually just delay doing a horizontal max until the very very end.  But you need some way to record max and maxi.

You can and should implement this with intrinsics instead of hand-written asm.


Algorithmic / implementation improvement:

Besides just implementing the same logic with more efficient asm, look for ways to simplify the logic, or avoid redundant work. e.g. memoize to detect common endings to sequences. Or even better, look at 8 trailing bits at once (gnasher's answer)

@EOF points out that tzcnt (or bsf) could be used to do multiple n/=2 iterations in one step. That's probably better than SIMD vectorizing; no SSE or AVX instruction can do that. It's still compatible with doing multiple scalar ns in parallel in different integer registers, though.

So the loop might look like this:

goto loop_entry;  // C++ structured like the asm, for illustration only
do {
   n = n*3 + 1;
  loop_entry:
   shift = _tzcnt_u64(n);
   n >>= shift;
   count += shift;
} while(n != 1);

This may do significantly fewer iterations, but variable-count shifts are slow on Intel SnB-family CPUs without BMI2. 3 uops, 2c latency. (They have an input dependency on the FLAGS because count=0 means the flags are unmodified. They handle this as a data dependency, and take multiple uops because a uop can only have 2 inputs (pre-HSW/BDW anyway)). This is the kind that people complaining about x86's crazy-CISC design are referring to. It makes x86 CPUs slower than they would be if the ISA was designed from scratch today, even in a mostly-similar way. (i.e. this is part of the "x86 tax" that costs speed / power.) SHRX/SHLX/SARX (BMI2) are a big win (1 uop / 1c latency).

It also puts tzcnt (3c on Haswell and later) on the critical path, so it significantly lengthens the total latency of the loop-carried dependency chain. It does remove any need for a CMOV, or for preparing a register holding n>>1, though. @Veedrac's answer overcomes all this by deferring the tzcnt/shift for multiple iterations, which is highly effective (see below).

We can safely use BSF or TZCNT interchangeably, because n can never be zero at that point. TZCNT's machine-code decodes as BSF on CPUs that don't support BMI1. (Meaningless prefixes are ignored, so REP BSF runs as BSF).

TZCNT performs much better than BSF on AMD CPUs that support it, so it can be a good idea to use REP BSF, even if you don't care about setting ZF if the input is zero rather than the output. Some compilers do this when you use __builtin_ctzll even with -mno-bmi.

They perform the same on Intel CPUs, so just save the byte if that's all that matters. TZCNT on Intel (pre-Skylake) still has a false-dependency on the supposedly write-only output operand, just like BSF, to support the undocumented behaviour that BSF with input = 0 leaves its destination unmodified. So you need to work around that unless optimizing only for Skylake, so there's nothing to gain from the extra REP byte. (Intel often goes above and beyond what the x86 ISA manual requires, to avoid breaking widely-used code that depends on something it shouldn't, or that is retroactively disallowed. e.g. Windows 9x's assumes no speculative prefetching of TLB entries, which was safe when the code was written, before Intel updated the TLB management rules.)

Anyway, LZCNT/TZCNT on Haswell have the same false dep as POPCNT: see this Q&A. This is why in gcc's asm output for @Veedrac's code, you see it breaking the dep chain with xor-zeroing on the register it's about to use as TZCNT's destination when it doesn't use dst=src. Since TZCNT/LZCNT/POPCNT never leave their destination undefined or unmodified, this false dependency on the output on Intel CPUs is a performance bug / limitation. Presumably it's worth some transistors / power to have them behave like other uops that go to the same execution unit. The only perf upside is interaction with another uarch limitation: they can micro-fuse a memory operand with an indexed addressing mode on Haswell, but on Skylake where Intel removed the false dep for LZCNT/TZCNT they "un-laminate" indexed addressing modes while POPCNT can still micro-fuse any addr mode.


Improvements to ideas / code from other answers:

@hidefromkgb's answer has a nice observation that you're guaranteed to be able to do one right shift after a 3n+1. You can compute this more even more efficiently than just leaving out the checks between steps. The asm implementation in that answer is broken, though (it depends on OF, which is undefined after SHRD with a count > 1), and slow: ROR rdi,2 is faster than SHRD rdi,rdi,2, and using two CMOV instructions on the critical path is slower than an extra TEST that can run in parallel.

I put tidied / improved C (which guides the compiler to produce better asm), and tested+working faster asm (in comments below the C) up on Godbolt: see the link in @hidefromkgb's answer. (This answer hit the 30k char limit from the large Godbolt URLs, but shortlinks can rot and were too long for goo.gl anyway.)

Also improved the output-printing to convert to a string and make one write() instead of writing one char at a time. This minimizes impact on timing the whole program with perf stat ./collatz (to record performance counters), and I de-obfuscated some of the non-critical asm.


@Veedrac's code

I got a minor speedup from right-shifting as much as we know needs doing, and checking to continue the loop. From 7.5s for limit=1e8 down to 7.275s, on Core2Duo (Merom), with an unroll factor of 16.

code + comments on Godbolt. Don't use this version with clang; it does something silly with the defer-loop. Using a tmp counter k and then adding it to count later changes what clang does, but that slightly hurts gcc.

See discussion in comments: Veedrac's code is excellent on CPUs with BMI1 (i.e. not Celeron/Pentium)

Angular2 @Input to a property with get/set

You could set the @Input on the setter directly, as described below:

_allowDay: boolean;
get allowDay(): boolean {
    return this._allowDay;
}
@Input() set allowDay(value: boolean) {
    this._allowDay = value;
    this.updatePeriodTypes();
}

See this Plunkr: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview.

How to subscribe to an event on a service in Angular2?

Update: I have found a better/proper way to solve this problem using a BehaviorSubject or an Observable rather than an EventEmitter. Please see this answer: https://stackoverflow.com/a/35568924/215945

Also, the Angular docs now have a cookbook example that uses a Subject.


Original/outdated/wrong answer: again, don't use an EventEmitter in a service. That is an anti-pattern.

Using beta.1... NavService contains the EventEmiter. Component Navigation emits events via the service, and component ObservingComponent subscribes to the events.

nav.service.ts

import {EventEmitter} from 'angular2/core';
export class NavService {
  navchange: EventEmitter<number> = new EventEmitter();
  constructor() {}
  emitNavChangeEvent(number) {
    this.navchange.emit(number);
  }
  getNavChangeEmitter() {
    return this.navchange;
  }
}

components.ts

import {Component} from 'angular2/core';
import {NavService} from '../services/NavService';

@Component({
  selector: 'obs-comp',
  template: `obs component, item: {{item}}`
})
export class ObservingComponent {
  item: number = 0;
  subscription: any;
  constructor(private navService:NavService) {}
  ngOnInit() {
    this.subscription = this.navService.getNavChangeEmitter()
      .subscribe(item => this.selectedNavItem(item));
  }
  selectedNavItem(item: number) {
    this.item = item;
  }
  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

@Component({
  selector: 'my-nav',
  template:`
    <div class="nav-item" (click)="selectedNavItem(1)">nav 1 (click me)</div>
    <div class="nav-item" (click)="selectedNavItem(2)">nav 2 (click me)</div>
  `,
})
export class Navigation {
  item = 1;
  constructor(private navService:NavService) {}
  selectedNavItem(item: number) {
    console.log('selected nav item ' + item);
    this.navService.emitNavChangeEvent(item);
  }
}

Plunker

Mockito verify order / sequence of method calls

With BDD it's

@Test
public void testOrderWithBDD() {


    // Given
    ServiceClassA firstMock = mock(ServiceClassA.class);
    ServiceClassB secondMock = mock(ServiceClassB.class);

    //create inOrder object passing any mocks that need to be verified in order
    InOrder inOrder = inOrder(firstMock, secondMock);

    willDoNothing().given(firstMock).methodOne();
    willDoNothing().given(secondMock).methodTwo();

    // When
    firstMock.methodOne();
    secondMock.methodTwo();

    // Then
    then(firstMock).should(inOrder).methodOne();
    then(secondMock).should(inOrder).methodTwo();


}

How to refresh or show immediately in datagridview after inserting?

this.donorsTableAdapter.Fill(this.sbmsDataSet.donors);

How do I install Composer on a shared hosting?

Most of the time you can't - depending on the host. You can contact the support team where your hosting is subscribed to, and if they confirmed that it is really not allowed, you can just set up the composer on your dev machine, and commit and push all dependencies to your live server using Git or whatever you prefer.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

Your class MyClass creates a new MyClassToBeTested, instead of using your mock. My article on the Mockito wiki describes two ways of dealing with this.

angularjs directive call function specified in attribute and pass an argument to it

Just to add some info to the other answers - using & is a good way if you need an isolated scope.

The main downside of marko's solution is that it forces you to create an isolated scope on an element, but you can only have one of those on an element (otherwise you'll run into an angular error: Multiple directives [directive1, directive2] asking for isolated scope)

This means you :

  • can't use it on an element hat has an isolated scope itself
  • can't use two directives with this solution on the same element

Since the original question uses a directive with restrict:'A' both situations might arise quite often in bigger applications, and using an isolated scope here is not a good practice and also unnecessary. In fact rekna had a good intuition in this case, and almost had it working, the only thing he was doing wrong was calling the $parsed function wrong (see what it returns here: https://docs.angularjs.org/api/ng/service/$parse ).

TL;DR; Fixed question code

<div my-method='theMethodToBeCalled(id)'></div>

and the code

app.directive("myMethod",function($parse) {
  restrict:'A',
  link:function(scope,element,attrs) {
     // here you can parse any attribute (so this could as well be,
     // myDirectiveCallback or multiple ones if you need them )
     var expressionHandler = $parse(attrs.myMethod);
     $(element).on('theEvent',function( e, rowid ) {
        calculatedId = // some function called to determine id based on rowid

        // HERE: call the parsed function correctly (with scope AND params object)
        expressionHandler(scope, {id:calculatedId});
     }
  }
}

app.controller("myController",function($scope) {
   $scope.theMethodToBeCalled = function(id) { alert(id); };
}

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

Inserting data into a MySQL table using VB.NET

Dim connString as String ="server=localhost;userid=root;password=123456;database=uni_park_db"
Dim conn as MySqlConnection(connString)
Dim cmd as MysqlCommand
Dim dt as New DataTable
Dim ireturn as Boolean

Private Sub Insert_Car()

Dim sql as String = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@car_id,@member_id,@model,@color,@chassis_id,@plate_number,@code)"

Dim cmd = new MySqlCommand(sql, conn)

    cmd.Paramaters.AddwithValue("@car_id", txtCar.Text)
    cmd.Paramaters.AddwithValue("@member_id", txtMember.Text)
    cmd.Paramaters.AddwithValue("@model", txtModel.Text)
    cmd.Paramaters.AddwithValue("@color", txtColor.Text)
    cmd.Paramaters.AddwithValue("@chassis_id", txtChassis.Text)
    cmd.Paramaters.AddwithValue("@plate_number", txtPlateNo.Text)
    cmd.Paramaters.AddwithValue("@code", txtCode.Text)

    Try
        conn.Open()
        If cmd.ExecuteNonQuery() > 0 Then
            ireturn = True
        End If  
        conn.Close()


    Catch ex as Exception
        ireturn = False
        conn.Close()
    End Try

Return ireturn

End Sub

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Getting JSONObject from JSONArray

Here is your json:

{
    "syncresponse": {
       "synckey": "2011-09-30 14:52:00",
        "createdtrs": [

        ],
        "modtrs": [

        ],
        "deletedtrs": [
          {
           "companyid": "UTB17",
           "username": "DA",
           "date": "2011-09-26",
           "reportid": "31341"
      }
       ]
   }
}

and it's parsing:

JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
   JSONObject object3 = jArray3.getJSONObject(i);
   String comp_id = object3.getString("companyid");
   String username = object3.getString("username");
   String date = object3.getString("date");
   String report_id = object3.getString("reportid");
}

iOS (iPhone, iPad, iPodTouch) view real-time console log terminal

EDIT: Please use @cbowns solution - deviceconsole is compatible with iOS9 and much easier to use.

This is a open-source program that displays the iDevice's system log in Terminal (in a manner similar to tail -F). No jailbreak is required, and the output is fully grep'able so you can filter to see output from your program only. What's particularly good about this solution is you can view the log whether or not the app was launched in debug mode from XCode.

Here's how:

Grab the libimobiledevice binary for Mac OS X from my github account at https://github.com/benvium/libimobiledevice-macosx/zipball/master

Follow the install instructions here: https://github.com/benvium/libimobiledevice-macosx/blob/master/README.md

Connect your device, open up Terminal.app and type:

idevicesyslog

Up pops a real-time display of the device's system log.

With it being a console app, you can filter the log using unix commands, such as grep

For instance, see all log messages from a particular app:

idevicesyslog | grep myappname

Taken from my blog at http://pervasivecode.blogspot.co.uk/2012/06/view-log-output-of-any-app-on-iphone-or.html

Import SQL dump into PostgreSQL database

Works pretty well, in command line, all arguments are required, -W is for password

psql -h localhost -U user -W -d database_name -f path/to/file.sql

Implementing multiple interfaces with Java - is there a way to delegate?

There is one way to implement multiple interface.

Just extend one interface from another or create interface that extends predefined interface Ex:

public interface PlnRow_CallBack extends OnDateSetListener {
    public void Plan_Removed();
    public BaseDB getDB();
}

now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces

public class Calculator extends FragmentActivity implements PlnRow_CallBack {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

    }

    @Override
    public void Plan_Removed() {

    }

    @Override
    public BaseDB getDB() {

    }
}

hope this helps

Html attributes for EditorFor() in ASP.NET MVC

As of MVC 5.1, you can now do the following:

@Html.EditorFor(model => model, new { htmlAttributes = new { @class = "form-control" }, })

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

How to find indices of all occurrences of one string in another in JavaScript?

var str = "I learned to play the Ukulele in Lebanon."
var regex = /le/gi, result, indices = [];
while ( (result = regex.exec(str)) ) {
    indices.push(result.index);
}

UPDATE

I failed to spot in the original question that the search string needs to be a variable. I've written another version to deal with this case that uses indexOf, so you're back to where you started. As pointed out by Wrikken in the comments, to do this for the general case with regular expressions you would need to escape special regex characters, at which point I think the regex solution becomes more of a headache than it's worth.

_x000D_
_x000D_
function getIndicesOf(searchStr, str, caseSensitive) {_x000D_
    var searchStrLen = searchStr.length;_x000D_
    if (searchStrLen == 0) {_x000D_
        return [];_x000D_
    }_x000D_
    var startIndex = 0, index, indices = [];_x000D_
    if (!caseSensitive) {_x000D_
        str = str.toLowerCase();_x000D_
        searchStr = searchStr.toLowerCase();_x000D_
    }_x000D_
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {_x000D_
        indices.push(index);_x000D_
        startIndex = index + searchStrLen;_x000D_
    }_x000D_
    return indices;_x000D_
}_x000D_
_x000D_
var indices = getIndicesOf("le", "I learned to play the Ukulele in Lebanon.");_x000D_
_x000D_
document.getElementById("output").innerHTML = indices + "";
_x000D_
<div id="output"></div>
_x000D_
_x000D_
_x000D_

Unzipping files

I found jszip quite useful. I've used so far only for reading, but they have create/edit capabilities as well.

Code wise it looks something like this

var new_zip = new JSZip();
new_zip.load(file);
new_zip.files["doc.xml"].asText() // this give you the text in the file

One thing I noticed is that it seems the file has to be in binary stream format (read using the .readAsArrayBuffer of FileReader(), otherwise I was getting errors saying I might have a corrupt zip file

Edit: Note from the 2.x to 3.0.0 upgrade guide:

The load() method and the constructor with data (new JSZip(data)) have been replaced by loadAsync().

Thanks user2677034

Generating a drop down list of timezones with PHP

$timezone = array(
    'Pacific/Midway' => '(GMT-11:00) Midway Island, Samoa',
    'America/Adak' => '(GMT-10:00) Hawaii-Aleutian',
    'Etc/GMT+10' => '(GMT-10:00) Hawaii',
    'Pacific/Marquesas' => '(GMT-09:30) Marquesas Islands',
    'Pacific/Gambier' => '(GMT-09:00) Gambier Islands',
    'America/Anchorage' => '(GMT-09:00) Alaska',
    'America/Ensenada' => '(GMT-08:00) Tijuana, Baja California',
    'Etc/GMT+8' => '(GMT-08:00) Pitcairn Islands',
    'America/Los_Angeles' => '(GMT-08:00) Pacific Time (US & Canada)',
    'America/Denver' => '(GMT-07:00) Mountain Time (US & Canada)',
    'America/Chihuahua' => '(GMT-07:00) Chihuahua, La Paz, Mazatlan',
    'America/Dawson_Creek' => '(GMT-07:00) Arizona',
    'America/Belize' => '(GMT-06:00) Saskatchewan, Central America',
    'America/Cancun' => '(GMT-06:00) Guadalajara, Mexico City, Monterrey',
    'Chile/EasterIsland' => '(GMT-06:00) Easter Island',
    'America/Chicago' => '(GMT-06:00) Central Time (US & Canada)',
    'America/New_York' => '(GMT-05:00) Eastern Time (US & Canada)',
    'America/Havana' => '(GMT-05:00) Cuba',
    'America/Bogota' => '(GMT-05:00) Bogota, Lima, Quito, Rio Branco',
    'America/Caracas' => '(GMT-04:30) Caracas',
    'America/Santiago' => '(GMT-04:00) Santiago',
    'America/La_Paz' => '(GMT-04:00) La Paz',
    'Atlantic/Stanley' => '(GMT-04:00) Faukland Islands',
    'America/Campo_Grande' => '(GMT-04:00) Brazil',
    'America/Goose_Bay' => '(GMT-04:00) Atlantic Time (Goose Bay)',
    'America/Glace_Bay' => '(GMT-04:00) Atlantic Time (Canada)',
    'America/St_Johns' => '(GMT-03:30) Newfoundland',
    'America/Araguaina' => '(GMT-03:00) UTC-3',
    'America/Montevideo' => '(GMT-03:00) Montevideo',
    'America/Miquelon' => '(GMT-03:00) Miquelon, St. Pierre',
    'America/Godthab' => '(GMT-03:00) Greenland',
    'America/Argentina/Buenos_Aires' => '(GMT-03:00) Buenos Aires',
    'America/Sao_Paulo' => '(GMT-03:00) Brasilia',
    'America/Noronha' => '(GMT-02:00) Mid-Atlantic',
    'Atlantic/Cape_Verde' => '(GMT-01:00) Cape Verde Is.',
    'Atlantic/Azores' => '(GMT-01:00) Azores',
    'Europe/Belfast' => '(GMT) Greenwich Mean Time : Belfast',
    'Europe/Dublin' => '(GMT) Greenwich Mean Time : Dublin',
    'Europe/Lisbon' => '(GMT) Greenwich Mean Time : Lisbon',
    'Europe/London' => '(GMT) Greenwich Mean Time : London',
    'Africa/Abidjan' => '(GMT) Monrovia, Reykjavik',
    'Europe/Amsterdam' => '(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
    'Europe/Belgrade' => '(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',
    'Europe/Brussels' => '(GMT+01:00) Brussels, Copenhagen, Madrid, Paris',
    'Africa/Algiers' => '(GMT+01:00) West Central Africa',
    'Africa/Windhoek' => '(GMT+01:00) Windhoek',
    'Asia/Beirut' => '(GMT+02:00) Beirut',
    'Africa/Cairo' => '(GMT+02:00) Cairo',
    'Asia/Gaza' => '(GMT+02:00) Gaza',
    'Africa/Blantyre' => '(GMT+02:00) Harare, Pretoria',
    'Asia/Jerusalem' => '(GMT+02:00) Jerusalem',
    'Europe/Minsk' => '(GMT+02:00) Minsk',
    'Asia/Damascus' => '(GMT+02:00) Syria',
    'Europe/Moscow' => '(GMT+03:00) Moscow, St. Petersburg, Volgograd',
    'Africa/Addis_Ababa' => '(GMT+03:00) Nairobi',
    'Asia/Tehran' => '(GMT+03:30) Tehran',
    'Asia/Dubai' => '(GMT+04:00) Abu Dhabi, Muscat',
    'Asia/Yerevan' => '(GMT+04:00) Yerevan',
    'Asia/Kabul' => '(GMT+04:30) Kabul',
    'Asia/Yekaterinburg' => '(GMT+05:00) Ekaterinburg',
    'Asia/Tashkent' => '(GMT+05:00) Tashkent',
    'Asia/Kolkata' => '(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi',
    'Asia/Katmandu' => '(GMT+05:45) Kathmandu',
    'Asia/Dhaka' => '(GMT+06:00) Astana, Dhaka',
    'Asia/Novosibirsk' => '(GMT+06:00) Novosibirsk',
    'Asia/Rangoon' => '(GMT+06:30) Yangon (Rangoon)',
    'Asia/Bangkok' => '(GMT+07:00) Bangkok, Hanoi, Jakarta',
    'Asia/Krasnoyarsk' => '(GMT+07:00) Krasnoyarsk',
    'Asia/Hong_Kong' => '(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi',
    'Asia/Irkutsk' => '(GMT+08:00) Irkutsk, Ulaan Bataar',
    'Australia/Perth' => '(GMT+08:00) Perth',
    'Australia/Eucla' => '(GMT+08:45) Eucla',
    'Asia/Tokyo' => '(GMT+09:00) Osaka, Sapporo, Tokyo',
    'Asia/Seoul' => '(GMT+09:00) Seoul',
    'Asia/Yakutsk' => '(GMT+09:00) Yakutsk',
    'Australia/Adelaide' => '(GMT+09:30) Adelaide',
    'Australia/Darwin' => '(GMT+09:30) Darwin',
    'Australia/Brisbane' => '(GMT+10:00) Brisbane',
    'Australia/Hobart' => '(GMT+10:00) Hobart',
    'Asia/Vladivostok' => '(GMT+10:00) Vladivostok',
    'Australia/Lord_Howe' => '(GMT+10:30) Lord Howe Island',
    'Etc/GMT-11' => '(GMT+11:00) Solomon Is., New Caledonia',
    'Asia/Magadan' => '(GMT+11:00) Magadan',
    'Pacific/Norfolk' => '(GMT+11:30) Norfolk Island',
    'Asia/Anadyr' => '(GMT+12:00) Anadyr, Kamchatka',
    'Pacific/Auckland' => '(GMT+12:00) Auckland, Wellington',
    'Etc/GMT-12' => '(GMT+12:00) Fiji, Kamchatka, Marshall Is.',
    'Pacific/Chatham' => '(GMT+12:45) Chatham Islands',
    'Pacific/Tongatapu' => '(GMT+13:00) Nukualofa',
    'Pacific/Kiritimati' => '(GMT+14:00) Kiritimati',

date_default_timezone_set($timezone);

How to get a DOM Element from a JQuery Selector

If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.

But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.

UPDATE: Based on a comment: Here is a post with a nice explanation: http://www.mail-archive.com/[email protected]/msg04461.html

$(this).attr("checked") ? $(this).val() : 0

This will return the value if it's checked, or 0 if it's not.

$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

How do I pass a method as a parameter in Python

Lots of good answers but strange that no one has mentioned using a lambda function.
So if you have no arguments, things become pretty trivial:

def method1():
    return 'hello world'

def method2(methodToRun):
    result = methodToRun()
    return result

method2(method1)

But say you have one (or more) arguments in method1:

def method1(param):
    return 'hello ' + str(param)

def method2(methodToRun):
    result = methodToRun()
    return result

Then you can simply invoke method2 as method2(lambda: method1('world')).

method2(lambda: method1('world'))
>>> hello world
method2(lambda: method1('reader'))
>>> hello reader

I find this much cleaner than the other answers mentioned here.

Sorting std::map using value

In the following sample code, I wrote an simple way to output top words in an word_map map where key is string (word) and value is unsigned int (word occurrence).

The idea is simple, find the current top word and delete it from the map. It's not optimized, but it works well when the map is not large and we only need to output the top N words, instead of sorting the whole map.

const int NUMBER_OF_TOP_WORDS = 300;
for (int i = 1; i <= NUMBER_OF_TOP_WORDS; i++) {
  if (word_map.empty())
    break;
  // Go through the map and find the max item.
  int max_value = 0;
  string max_word = "";
  for (const auto& kv : word_map) {
    if (kv.second > max_value) {
      max_value = kv.second;
      max_word = kv.first;
    }
  }
  // Erase this entry and print.
  word_map.erase(max_word);
  cout << "Top:" << i << " Count:" << max_value << " Word:<" << max_word << ">" <<     endl;
}

SQL count rows in a table

Yes, SELECT COUNT(*) FROM TableName

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Improving upon @Ianl's answer,

It seems that if 2-step authentication is enabled, you have to use token instead of password. You could generate a token here.

If you want to disable the prompts for both the username and password then you can set the URL as follows -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

Note that the URL has both the username and password. Also the .git/config file should show your current settings.


Update 20200128:

If you don't want to store the password in the config file, then you can generate your personal token and replace the password with the token. Here are some details.

It would look like this -

git remote set-url origin https://username:[email protected]/WEMP/project-slideshow.git

How can I uninstall an application using PowerShell?

To add a little to this post, I needed to be able to remove software from multiple Servers. I used Jeff's answer to lead me to this:

First I got a list of servers, I used an AD query, but you can provide the array of computer names however you want:

$computers = @("computer1", "computer2", "computer3")

Then I looped through them, adding the -computer parameter to the gwmi query:

foreach($server in $computers){
    $app = Get-WmiObject -Class Win32_Product -computer $server | Where-Object {
        $_.IdentifyingNumber -match "5A5F312145AE-0252130-432C34-9D89-1"
    }
    $app.Uninstall()
}

I used the IdentifyingNumber property to match against instead of name, just to be sure I was uninstalling the correct application.

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

Unit test naming best practices

I like to follow the "Should" naming standard for tests while naming the test fixture after the unit under test (i.e. the class).

To illustrate (using C# and NUnit):

[TestFixture]
public class BankAccountTests
{
  [Test]
  public void Should_Increase_Balance_When_Deposit_Is_Made()
  {
     var bankAccount = new BankAccount();
     bankAccount.Deposit(100);
     Assert.That(bankAccount.Balance, Is.EqualTo(100));
  }
}

Why "Should"?

I find that it forces the test writers to name the test with a sentence along the lines of "Should [be in some state] [after/before/when] [action takes place]"

Yes, writing "Should" everywhere does get a bit repetitive, but as I said it forces writers to think in the correct way (so can be good for novices). Plus it generally results in a readable English test name.

Update:

I've noticed that Jimmy Bogard is also a fan of 'should' and even has a unit test library called Should.

Update (4 years later...)

For those interested, my approach to naming tests has evolved over the years. One of the issues with the Should pattern I describe above as its not easy to know at a glance which method is under test. For OOP I think it makes more sense to start the test name with the method under test. For a well designed class this should result in readable test method names. I now use a format similar to <method>_Should<expected>_When<condition>. Obviously depending on the context you may want to substitute the Should/When verbs for something more appropriate. Example: Deposit_ShouldIncreaseBalance_WhenGivenPositiveValue()

VSCode Change Default Terminal

You can also select your default terminal by pressing F1 in VS Code and typing/selecting Terminal: Select Default Shell.

Terminal Selection

Terminal Selection

What does "var" mean in C#?

It declares a type based on what is assigned to it in the initialisation.

A simple example is that the code:

var i = 53;

Will examine the type of 53, and essentially rewrite this as:

int i = 53;

Note that while we can have:

long i = 53;

This won't happen with var. Though it can with:

var i = 53l; // i is now a long

Similarly:

var i = null; // not allowed as type can't be inferred.
var j = (string) null; // allowed as the expression (string) null has both type and value.

This can be a minor convenience with complicated types. It is more important with anonymous types:

var i = from x in SomeSource where x.Name.Length > 3 select new {x.ID, x.Name};
foreach(var j in i)
  Console.WriteLine(j.ID.ToString() + ":" + j.Name);

Here there is no other way of defining i and j than using var as there is no name for the types that they hold.

Default optional parameter in Swift function

Default value doesn't mean default value of data type .Here default value mean value defined at the time of defining function. we have to declare default value of variable while defining variable in function.

Cannot read property 'addEventListener' of null

Thanks to @Rob M. for his help. This is what the final block of code looked like:

function swapper() {
  toggleClass(document.getElementById('overlay'), 'open');
}

var el = document.getElementById('overlayBtn');
if (el){
  el.addEventListener('click', swapper, false);

  var text = document.getElementById('overlayBtn');
  text.onclick = function(){
    this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
    return false;
  };
}

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

SSRS custom number format

You can use

 =Format(Fields!myField.Value,"F2") 

Resetting a multi-stage form with jQuery

I used the solution below and it worked for me (mixing traditional javascript with jQuery)

$("#myformId").submit(function() {
    comand="window.document."+$(this).attr('name')+".reset()";
    setTimeout("eval(comando)",4000);
})

How to remove entity with ManyToMany relationship in JPA (and corresponding join table rows)?

I found a possible solution, but... I don't know if it's a good solution.

@Entity
public class Role extends Identifiable {

    @ManyToMany(cascade ={CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Role_id"),
            inverseJoinColumns=@JoinColumn(name="Permission_id")
        )
    public List<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(List<Permission> permissions) {
        this.permissions = permissions;
    }
}

@Entity
public class Permission extends Identifiable {

    @ManyToMany(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH})
    @JoinTable(name="Role_Permission",
            joinColumns=@JoinColumn(name="Permission_id"),
            inverseJoinColumns=@JoinColumn(name="Role_id")
        )
    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

I have tried this and it works. When you delete Role, also the relations are deleted (but not the Permission entities) and when you delete Permission, the relations with Role are deleted too (but not the Role instance). But we are mapping a unidirectional relation two times and both entities are the owner of the relation. Could this cause some problems to Hibernate? Which type of problems?

Thanks!

The code above is from another post related.

How to uncheck a radio button?

Try

$(this).attr("checked" , false );

VBA Excel Provide current Date in Text box

Set the value from code on showing the form, not in the design-timeProperties for the text box.

Private Sub UserForm_Activate()
    Me.txtDate.Value = Format(Date, "mm/dd/yy")
End Sub

How do I "Add Existing Item" an entire directory structure in Visual Studio?

Drag the files / folders from Windows Explorer into the Solution Explorer. It will add them all. Note this doesn't work if Visual Studio is in Administrator Mode, because Windows Explorer is a User Mode process.

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

This may be late, but an extension that works for value and reference types alike based on Eric's answer:

public static partial class Extensions
{
    public static Nullable<T> Unanimous<T>(this IEnumerable<Nullable<T>> sequence, Nullable<T> other, IEqualityComparer comparer = null)  where T : struct, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (Nullable<T>)first ?? other;
    }

    public static T Unanimous<T>(this IEnumerable<T> sequence, T other, IEqualityComparer comparer = null)  where T : class, IComparable
    {
        object first = null;
        foreach(var item in sequence)
        {
            if (first == null)
                first = item;
            else if (comparer != null && !comparer.Equals(first, item))
                return other;
            else if (!first.Equals(item))
                return other;
        }
        return (T)first ?? other;
    }
}

document.getElementById vs jQuery $()

Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.

The equivalent would be this

var contents = $('#contents').get(0);

or this

var contents = $('#contents')[0];

These will pull the element out of the jQuery object.

How to make for loops in Java increase by increments other than 1

That’s because j+3 doesn’t change the value of j. You need to replace that with j = j + 3 or j += 3 so that the value of j is increased by 3:

for (j = 0; j <= 90; j += 3) { }

Make a dictionary in Python from input values

record = int(input("Enter the student record need to add :"))

stud_data={}

for i in range(0,record):
    Name = input("Enter the student name :").split()
    Age = input("Enter the {} age :".format(Name))
    Grade = input("Enter the {} grade :".format(Name)).split()
    Nam_key =  Name[0]
    Age_value = Age[0]
    Grade_value = Grade[0]
    stud_data[Nam_key] = {Age_value,Grade_value}

print(stud_data)

How to use Oracle's LISTAGG function with a unique filter?

I needed this peace of code as a subquery with some data filter before aggregation based on the outer most query but I wasn't able to do this using the chosen answer code because this filter should go in the inner most select (third level query) and the filter params was in the outer most select (first level query), which gave me the error ORA-00904: "TB_OUTERMOST"."COL": invalid identifier as the ANSI SQL states that table references (correlation names) are scoped to just one level deep.

I needed a solution with no levels of subquery and this one below worked great for me:

with

demotable as
(
  select 1 group_id, 'David'   name from dual union all
  select 1 group_id, 'John'    name from dual union all
  select 1 group_id, 'Alan'    name from dual union all
  select 1 group_id, 'David'   name from dual union all
  select 2 group_id, 'Julie'   name from dual union all
  select 2 group_id, 'Charlie' name from dual
)

select distinct 
  group_id, 
  listagg(name, ',') within group (order by name) over (partition by group_id) names
from demotable
-- where any filter I want
group by group_id, name
order by group_id;

How to change the colors of a PNG image easily?

Ok guys it can be done easy in photoshop.

Open png photo and then check image -> mode value(i had indexed color). Go image -> mode and check rgb color. Now change your color EASY.

How to set variables in HIVE scripts

Most of the answers here have suggested to either use hiveconf or hivevar namespace to store the variable. And all those answers are right. However, there is one more namespace.

There are total three namespaces available for holding variables.

  1. hiveconf - hive started with this, all the hive configuration is stored as part of this conf. Initially, variable substitution was not part of hive and when it got introduced, all the user-defined variables were stored as part of this as well. Which is definitely not a good idea. So two more namespaces were created.
  2. hivevar: To store user variables
  3. system: To store system variables.

And so if you are storing a variable as part of a query (i.e. date or product_number) you should use hivevar namespace and not hiveconf namespace.

And this is how it works.

hiveconf is still the default namespace, so if you don't provide any namespace it will store your variable in hiveconf namespace.

However, when it comes to referring a variable, it's not true. By default it refers to hivevar namespace. Confusing, right? It can become clearer with the following example.

If you do not provide namespace as mentioned below, variable var will be stored in hiveconf namespace.

set var="default_namespace";

So, to access this you need to specify hiveconf namespace

select ${hiveconf:var};

And if you do not provide namespace it will give you an error as mentioned below, reason being that by default if you try to access a variable it checks in hivevar namespace only. And in hivevar there is no variable named var

select ${var}; 

We have explicitly provided hivevar namespace

set hivevar:var="hivevar_namespace";

as we are providing the namespace this will work.

select ${hivevar:var}; 

And as default, workspace used during referring a variable is hivevar, the following will work too.

select ${var};

Sql Server return the value of identity column after insert statement

Here goes a bunch of different ways to get the ID, including Scope_Identity:

https://stackoverflow.com/a/42655/1504882

How I can filter a Datatable?

It is better to use DataView for this task.

Example of the using it you can find in this post: How to filter data in dataview

Delete forked repo from GitHub

Answer is NO. It won't affect the original/main repository where you forked from. (Functionally, it will be incorrect if such an access is provided to a non-owner).

Just wanted to add this though.

Warning: It will delete the local commits and branches you created on your forked repo. So, before deleting make sure there is a backup of that code with you if it is important.

Best way would be getting a git backup of forked repo using:

git bundle 

or other methods that are familiar.

Correct way to pass multiple values for same parameter name in GET request

I would suggest looking at how browsers handle forms by default. For example take a look at the form element <select multiple> and how it handles multiple values from this example at w3schools.

<form action="/action_page.php">
<select name="cars" multiple>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="opel">Opel</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

For PHP use:

<select name="cars[]" multiple>

Live example from above at w3schools.com

From above if you click "saab, opel" and click submit, it will generate a result of cars=saab&cars=opel. Then depending on the back-end server, the parameter cars should come across as an array that you can further process.

Hope this helps anyone looking for a more 'standard' way of handling this issue.

What is the way of declaring an array in JavaScript?

In your first example, you are making a blank array, same as doing var x = []. The 2nd example makes an array of size 3 (with all elements undefined). The 3rd and 4th examples are the same, they both make arrays with those elements.

Be careful when using new Array().

var x = new Array(10); // array of size 10, all elements undefined
var y = new Array(10, 5); // array of size 2: [10, 5]

The preferred way is using the [] syntax.

var x = []; // array of size 0
var y = [10] // array of size 1: [1]

var z = []; // array of size 0
z[2] = 12;  // z is now size 3: [undefined, undefined, 12]

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

I just encountered this and whilst we already had .NET 4.0 installed on the server it turns out we only had the "Client Profile" version and not the "Full" version. Installing the latter fixed the problem.

Check whether IIS is installed or not?

The quickest way to check is just to write "inetmgr" at run (By pressing Win + R) as a command, if a manager window is appeared then it's installed otherwise it isn't.

How to capture the "virtual keyboard show/hide" event in Android?

I did this way:

Add OnKeyboardVisibilityListener interface.

public interface OnKeyboardVisibilityListener {
    void onVisibilityChanged(boolean visible);
}

HomeActivity.java:

public class HomeActivity extends Activity implements OnKeyboardVisibilityListener {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign_up);
    // Other stuff...
    setKeyboardVisibilityListener(this);
}

private void setKeyboardVisibilityListener(final OnKeyboardVisibilityListener onKeyboardVisibilityListener) {
    final View parentView = ((ViewGroup) findViewById(android.R.id.content)).getChildAt(0);
    parentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        private boolean alreadyOpen;
        private final int defaultKeyboardHeightDP = 100;
        private final int EstimatedKeyboardDP = defaultKeyboardHeightDP + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? 48 : 0);
        private final Rect rect = new Rect();

        @Override
        public void onGlobalLayout() {
            int estimatedKeyboardHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, EstimatedKeyboardDP, parentView.getResources().getDisplayMetrics());
            parentView.getWindowVisibleDisplayFrame(rect);
            int heightDiff = parentView.getRootView().getHeight() - (rect.bottom - rect.top);
            boolean isShown = heightDiff >= estimatedKeyboardHeight;

            if (isShown == alreadyOpen) {
                Log.i("Keyboard state", "Ignoring global layout change...");
                return;
            }
            alreadyOpen = isShown;
            onKeyboardVisibilityListener.onVisibilityChanged(isShown);
        }
    });
}


@Override
public void onVisibilityChanged(boolean visible) {
    Toast.makeText(HomeActivity.this, visible ? "Keyboard is active" : "Keyboard is Inactive", Toast.LENGTH_SHORT).show();
  }
}

Hope this would help you.

Renaming files using node.js

  1. fs.readdir(path, callback)
  2. fs.rename(old,new,callback)

Go through http://nodejs.org/api/fs.html

One important thing - you can use sync functions also. (It will work like C program)

How do I obtain crash-data from my Android application?

I'm one of the founders of Bugsnag which we designed for exactly this purpose. Bugsnag automatically captures unhandled exceptions in Android apps and sends them to our dashboard, where you can prioritize fixes and dive into diagnostic information.

Here are some important things to consider when selecting or building a crash reporting system, along with some code snippets:

  • Detects unhandled exceptions automatically (example code)
  • Collects diagnostic data such as memory usage, device info, etc (example code)
  • Effectively groups crashes together by root cause
  • Allows you to track actions the user took before each crash to help reproduce (example code)

If you want to see some best practices around crash handling/reporting on Android you can check out the full source code for Bugsnag's crash reporting library which is fully open source, feel free to tear this apart and use it in your own applications!

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

I had to change compileSdkVersion = 26 and buildToolsVersion = '26.0.1' in all my dependencies build.gradle files

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

As I know, PDO_MYSQLND replaced PDO_MYSQL in PHP 5.3. Confusing part is that name is still PDO_MYSQL. So now ND is default driver for MySQL+PDO.

Overall, to execute multiple queries at once you need:

  • PHP 5.3+
  • mysqlnd
  • Emulated prepared statements. Make sure PDO::ATTR_EMULATE_PREPARES is set to 1 (default). Alternatively you can avoid using prepared statements and use $pdo->exec directly.

Using exec

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works regardless of statements emulation
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 0);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$db->exec($sql);

Using statements

$db = new PDO("mysql:host=localhost;dbname=test", 'root', '');

// works not with the following set to 0. You can comment this line as 1 is default
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, 1);

$sql = "
DELETE FROM car; 
INSERT INTO car(name, type) VALUES ('car1', 'coupe'); 
INSERT INTO car(name, type) VALUES ('car2', 'coupe');
";

$stmt = $db->prepare($sql);
$stmt->execute();

A note:

When using emulated prepared statements, make sure you have set proper encoding (that reflects actual data encoding) in DSN (available since 5.3.6). Otherwise there can be a slight possibility for SQL injection if some odd encoding is used.

How do I return multiple values from a function in C?

By passing parameters by reference to function.

Examples:

 void incInt(int *y)
 {
     (*y)++;  // Increase the value of 'x', in main, by one.
 }

Also by using global variables but it is not recommended.

Example:

int a=0;

void main(void)
{
    //Anything you want to code.
}

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How to align an input tag to the center without specifying the width?

you can put in a table cell and then align the cell content.

<table>
   <tr>
     <td align="center">
        <input type="button" value="Some Button">
     </td>
   </tr>
</table>

How do I redirect to the previous action in ASP.NET MVC?

Pass a returnUrl parameter (url encoded) to the change and login actions and inside redirect to this given returnUrl. Your login action might look something like this:

public ActionResult Login(string returnUrl) 
{
    // Do something...
    return Redirect(returnUrl);
}

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I had a similar error..This might be due to two reasons. a) If you have used variables, re-evaluate the expressions in which variables are used and make sure the expression is evaluated without errors. b) If you are deleting the excel sheet and creating excel sheet on the fly in your package.

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

Translating touch events from Javascript to jQuery

$(window).on("touchstart", function(ev) {
    var e = ev.originalEvent;
    console.log(e.touches);
});

I know it been asked a long time ago, but I thought a concrete example might help.

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

RHEL 6 - how to install 'GLIBC_2.14' or 'GLIBC_2.15'?

To install GLIBC_2.14 or GLIBC_2.15, download package from /gnu/libc/ index at

https://ftp.gnu.org/gnu/libc/

Then follow instructions listed by Timo:

For example glibc-2.14.tar.gz in your case.

  1. tar xvfz glibc-2.14.tar.gz

  2. cd glibc-2.14

  3. mkdir build

  4. cd build

  5. ../configure --prefix=/opt/glibc-2.14

  6. make

  7. sudo make install

  8. export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH

How to access route, post, get etc. parameters in Zend Framework 2

The easiest way to do that would be to use the Params plugin, introduced in beta5. It has utility methods to make it easy to access different types of parameters. As always, reading the tests can prove valuable to understand how something is supposed to be used.

Get a single value

To get the value of a named parameter in a controller, you will need to select the appropriate method for the type of parameter you are looking for and pass in the name.

Examples:

$this->params()->fromPost('paramname');   // From POST
$this->params()->fromQuery('paramname');  // From GET
$this->params()->fromRoute('paramname');  // From RouteMatch
$this->params()->fromHeader('paramname'); // From header
$this->params()->fromFiles('paramname');  // From file being uploaded

 

Default values

All of these methods also support default values that will be returned if no parameter with the given name is found.

Example:

$orderBy = $this->params()->fromQuery('orderby', 'name');

When visiting http://example.com/?orderby=birthdate, $orderBy will have the value birthdate.
When visiting http://example.com/, $orderBy will have the default value name.
 

Get all parameters

To get all parameters of one type, just don't pass in anything and the Params plugin will return an array of values with their names as keys.

Example:

$allGetValues = $this->params()->fromQuery(); // empty method call

When visiting http://example.com/?orderby=birthdate&filter=hasphone $allGetValues will be an array like

array(
    'orderby' => 'birthdate',
    'filter'  => 'hasphone',
);

 

Not using Params plugin

If you check the source code for the Params plugin, you will see that it's just a thin wrapper around other controllers to allow for more consistent parameter retrieval. If you for some reason want/need to access them directly, you can see in the source code how it's done.

Example:

$this->getRequest()->getRequest('name', 'default');
$this->getEvent()->getRouteMatch()->getParam('name', 'default');

NOTE: You could have used the superglobals $_GET, $_POST etc., but that is discouraged.

How to create an Excel File with Nodejs?

Use exceljs library for creating and writing into existing excel sheets.

You can check this tutorial for detailed explanation.

link

Get list of all input objects using JavaScript, without accessing a form object

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
  // ...
}

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)

This would work, if your are trying to Sum up a list.

Excel Looping through rows and copy cell values to another worksheet

Private Sub CommandButton1_Click() 

Dim Z As Long 
Dim Cellidx As Range 
Dim NextRow As Long 
Dim Rng As Range 
Dim SrcWks As Worksheet 
Dim DataWks As Worksheet 
Z = 1 
Set SrcWks = Worksheets("Sheet1") 
Set DataWks = Worksheets("Sheet2") 
Set Rng = EntryWks.Range("B6:ad6") 

NextRow = DataWks.UsedRange.Rows.Count 
NextRow = IIf(NextRow = 1, 1, NextRow + 1) 

For Each RA In Rng.Areas 
    For Each Cellidx In RA 
        Z = Z + 1 
        DataWks.Cells(NextRow, Z) = Cellidx 
    Next Cellidx 
Next RA 
End Sub

Alternatively

Worksheets("Sheet2").Range("P2").Value = Worksheets("Sheet1").Range("L10") 

This is a CopynPaste - Method

Sub CopyDataToPlan()

Dim LDate As String
Dim LColumn As Integer
Dim LFound As Boolean

On Error GoTo Err_Execute

'Retrieve date value to search for
LDate = Sheets("Rolling Plan").Range("B4").Value

Sheets("Plan").Select

'Start at column B
LColumn = 2
LFound = False

While LFound = False

  'Encountered blank cell in row 2, terminate search
  If Len(Cells(2, LColumn)) = 0 Then
     MsgBox "No matching date was found."
     Exit Sub

  'Found match in row 2
  ElseIf Cells(2, LColumn) = LDate Then

     'Select values to copy from "Rolling Plan" sheet
     Sheets("Rolling Plan").Select
     Range("B5:H6").Select
     Selection.Copy

     'Paste onto "Plan" sheet
     Sheets("Plan").Select
     Cells(3, LColumn).Select
     Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
     False, Transpose:=False

     LFound = True
     MsgBox "The data has been successfully copied."

     'Continue searching
      Else
         LColumn = LColumn + 1
      End If

   Wend

   Exit Sub

Err_Execute:
  MsgBox "An error occurred."

End Sub

And there might be some methods doing that in Excel.

Check if a number has a decimal place/is a whole number

Or you could just use this to find out if it is NOT a decimal:

string.indexOf(".") == -1;

User Authentication in ASP.NET Web API

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

That's because you are getting confused about these two concepts:

  • Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:

    • Who is the user?
    • Is the user really who he/she represents himself to be?
  • Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:

    • Is user X authorized to access resource R?
    • Is user X authorized to perform operation P?
    • Is user X authorized to perform operation P on resource R?

The Authorize attribute in MVC is used to apply access rules, for example:

 [System.Web.Http.Authorize(Roles = "Admin, Super User")]
 public ActionResult AdministratorsOnly()
 {
     return View();
 }

The above rule will allow only users in the Admin and Super User roles to access the method

These rules can also be set in the web.config file, using the location element. Example:

  <location path="Home/AdministratorsOnly">
    <system.web>
      <authorization>
        <allow roles="Administrators"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>

However, before those authorization rules are executed, you have to be authenticated to the current web site.

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

From here, we could split the problem in two:

  • Authenticate users when consuming the Web API services within the same Web application

    This would be the simplest approach, because you would rely on the Authentication in ASP.Net

    This is a simple example:

    Web.config

    <authentication mode="Forms">
      <forms
        protection="All"
        slidingExpiration="true"
        loginUrl="account/login"
        cookieless="UseCookies"
        enableCrossAppRedirects="false"
        name="cookieName"
      />
    </authentication>
    

    Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using:

        if (ModelState.IsValid)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }
        }
    
        // If we got this far, something failed, redisplay form
        return View(model);
    
  • Cross - platform authentication

    This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc)

    For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net.

    <authentication mode="Windows" />
    

    If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service.

    For more info, take a loot to the following articles:

AngularJS $resource RESTful example

you can just do $scope.todo = Todo.get({ id: 123 }). .get() and .query() on a Resource return an object immediately and fill it with the result of the promise later (to update your template). It's not a typical promise which is why you need to either use a callback or the $promise property if you have some special code you want executed after the call. But there is no need to assign it to your scope in a callback if you are only using it in the template.

jQuery get mouse position within an element

If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.

Can't connect to MySQL server on 'localhost' (10061)

Another possibility:

There are two ways the MySQL client can connect to the server: over TCP/IP, or using sockets. It's possible you have your MySQL server configured to support socket connections, but not network connections.

Sorting JSON by values

Demo: https://jsfiddle.net/kvxazhso/

Successfully pass equal values (keep same order). Flexible : handle ascendant (123) or descendant (321), works for numbers, letters, and unicodes. Works on all tested devices (Chrome, Android default browser, FF).

Given data such :

var people = [ 
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 3 },
{ 'myKey': 'C', 'status': 3 },
{ 'myKey': 'D', 'status': 2 },
{ 'myKey': 'E', 'status': 7 },
...
];

Sorting by ascending or reverse order:

function sortJSON(arr, key, way) {
    return arr.sort(function(a, b) {
        var x = a[key]; var y = b[key];
        if (way === '123') { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }
        if (way === '321') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }
    });
}

people2 = sortJSON(people,'status', '321'); // 123 or 321
alert("2. After processing (0 to x if 123; x to 0 if 321): "+JSON.stringify(people2));

Disabling of EditText in Android

android:editable="false"

is now deprecated and use

 YourEditText.setInputType(InputType.TYPE_NULL);

What is polymorphism, what is it for, and how is it used?

Polymorphism is when you can treat an object as a generic version of something, but when you access it, the code determines which exact type it is and calls the associated code.

Here is an example in C#. Create four classes within a console application:

public abstract class Vehicle
{
    public abstract int Wheels;
}

public class Bicycle : Vehicle
{
    public override int Wheels()
    {
        return 2;
    }
}

public class Car : Vehicle
{
    public override int Wheels()
    {
        return 4;
    }
}

public class Truck : Vehicle
{
    public override int Wheels()
    {
        return 18;
    }
}

Now create the following in the Main() of the module for the console application:

public void Main()
{
    List<Vehicle> vehicles = new List<Vehicle>();

    vehicles.Add(new Bicycle());
    vehicles.Add(new Car());
    vehicles.Add(new Truck());

    foreach (Vehicle v in vehicles)
    {
        Console.WriteLine(
            string.Format("A {0} has {1} wheels.",
                v.GetType().Name, v.Wheels));
    }
}

In this example, we create a list of the base class Vehicle, which does not know about how many wheels each of its sub-classes has, but does know that each sub-class is responsible for knowing how many wheels it has.

We then add a Bicycle, Car and Truck to the list.

Next, we can loop through each Vehicle in the list, and treat them all identically, however when we access each Vehicles 'Wheels' property, the Vehicle class delegates the execution of that code to the relevant sub-class.

This code is said to be polymorphic, as the exact code which is executed is determined by the sub-class being referenced at runtime.

I hope that this helps you.

How to tell if a string contains a certain character in JavaScript?

To find "hello" in your_string

if (your_string.indexOf('hello') > -1)
{
  alert("hello found inside your_string");
}

For the alpha numeric you can use a regular expression:

http://www.regular-expressions.info/javascript.html

Alpha Numeric Regular Expression

Mean per group in a data.frame

I describe two ways to do this, one based on data.table and the other based on reshape2 package . The data.table way already has an answer, but I have tried to make it cleaner and more detailed.

The data is like this:

 d <- structure(list(Name = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("Aira", "Ben", "Cat"), class = "factor"), 
    Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(12L, 
    18L, 19L, 53L, 22L, 19L, 22L, 67L, 45L), Rate2 = c(23L, 73L, 
    45L, 19L, 87L, 45L, 87L, 43L, 32L)), .Names = c("Name", "Month", 
"Rate1", "Rate2"), class = "data.frame", row.names = c(NA, -9L
))
head(d)
  Name Month Rate1 Rate2
1 Aira     1    12    23
2 Aira     2    18    73
3 Aira     3    19    45
4  Ben     1    53    19
5  Ben     2    22    87
6  Ben     3    19    45


library("reshape2")
mym <- melt(d, id = c("Name"))
res <- dcast(mym, Name ~ variable, mean)
res
#Name Month    Rate1    Rate2
#1 Aira     2 16.33333 47.00000
#2  Ben     2 31.33333 50.33333
#3  Cat     2 44.66667 54.00000

Using data.table:

# At first, I convert the data.frame to data.table and then I group it 
setDT(d)
d[, .(Rate1 = mean(Rate1), Rate2 = mean(Rate2)), by = .(Name)]
#   Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

There is another way of doing it by avoiding to write many argument for j in data.table using a .SD

d[, lapply(.SD, mean), by = .(Name)]
#   Name Month    Rate1    Rate2
#1: Aira     2 16.33333 47.00000
#2:  Ben     2 31.33333 50.33333
#3:  Cat     2 44.66667 54.00000

if we only want to have Rate1 and Rate2 then we can use the .SDcols as follows:

d[, lapply(.SD, mean), by = .(Name), .SDcols = 3:4]
#  Name    Rate1    Rate2
#1: Aira 16.33333 47.00000
#2:  Ben 31.33333 50.33333
#3:  Cat 44.66667 54.00000

How to set UICollectionViewCell Width and Height programmatically

Try below method

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    return CGSize(width: 100.0, height: 100.0)
}

How do I move a redis database from one server to another?

Save a snapshot of the database into a dump.rdb by either running BGSAVE or SAVE from the command line. This will create a file named dump.rdb in the same folder as your redis server. See a list of all server commands.

Copy this dump.rdb to the other redis server you want to migrate to. When redis starts up, it looks for this file to initialize the database from.

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

How to use ADB in Android Studio to view an SQLite DB

Easiest way for me is using Android Device Monitor to get the database file and SQLite DataBase Browser to view the file while still using Android Studio to program android.

1) Run and launch database app with Android emulator from Android Studio. (I inserted some data to database app to verify)

2) Run Android Device Monitor. How to run?; Go to [your_folder] > sdk >tools. You can see monitor.bat in that folder. shift + right click inside the folder and select "Open command window here". This action will launch command prompt. type monitor and Android Device Monitor will be launched.

3) Select the emulator that you are currently running. Then Go to data>data>[your_app_name]>databases

4) Click on the icon (located at top right corner) (hover on the icon and you will see "pull a file from the device") and save anywhere you like

5) Launch SQLite DataBase Browser. Drag and drop the file that you just saved into that Browser.

6) Go to Browse Data tab and select your table to view.

enter image description here enter image description here

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Complementing Marco Bonelli's answer: the best current way of interacting between frames/iframes is using window.postMessage, supported by all browsers

Getting unique values in Excel by using formulas only

This is an oldie, and there are a few solutions out there, but I came up with a shorter and simpler formula than any other I encountered, and it might be useful to anyone passing by.

I have named the colors list Colors (A2:A7), and the array formula put in cell C2 is this (fixed):

=IFERROR(INDEX(Colors,MATCH(SUM(COUNTIF(C$1:C1,Colors)),COUNTIF(Colors,"<"&Colors),0)),"")

Use Ctrl+Shift+Enter to enter the formula in C2, and copy C2 down to C3:C7.

Explanation with sample data {"red"; "blue"; "red"; "green"; "blue"; "black"}:

  1. COUNTIF(Colors,"<"&Colors) returns an array (#1) with the count of values that are smaller then each item in the data {4;1;4;3;1;0} (black=0 items smaller, blue=1 item, red=4 items). This can be translated to a sort value for each item.
  2. COUNTIF(C$1:C...,Colors) returns an array (#2) with 1 for each data item that is already in the sorted result. In C2 it returns {0;0;0;0;0;0} and in C3 {0;0;0;0;0;1} because "black" is first in the sort and last in the data. In C4 {0;1;0;0;1;1} it indicates "black" and all the occurrences of "blue" are already present.
  3. The SUM returns the k-th sort value, by counting all the smaller values occurrences that are already present (sum of array #2).
  4. MATCH finds the first index of the k-th sort value (index in array #1).
  5. The IFERROR is only to hide the #N/A error in the bottom cells, when the sorted unique list is complete.

To know how many unique items you have you can use this regular formula:

=SUM(IF(FREQUENCY(COUNTIF(Colors,"<"&Colors),COUNTIF(Colors,"<"&Colors)),1))

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

Using Selenium Web Driver to retrieve value of a HTML input

With selenium 2,

i usually write it like that :

WebElement element = driver.findElement(By.id("input_name"));
String elementval = element.getAttribute("value");

OR

String elementval = driver.findElement(By.id("input_name")).getAttribute("value");

Rotating a two-dimensional array in Python

def ruota_orario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento) for elemento in ruota]
def ruota_antiorario(matrix):
   ruota=list(zip(*reversed(matrix)))
   return[list(elemento)[::-1] for elemento in ruota][::-1]

Build error, This project references NuGet

In my case, I deleted the Previous Project & created a new project with different name, when i was building the Project it shows me the same error.

I just edited the Project Name in csproj file of the Project & it Worked...!

How to delete columns in pyspark dataframe

Adding to @Patrick's answer, you can use the following to drop multiple columns

columns_to_drop = ['id', 'id_copy']
df = df.drop(*columns_to_drop)

Singleton: How should it be used

Anti-Usage:

One major problem with excessive singleton usage is that the pattern prevents easy extension and swapping of alternate implementations. The class-name is hard coded wherever the singleton is used.

Check image width and height before upload with Javascript

You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Based on Mozilla docs:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

And the browser compatibility is listed too.

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this

setInterval

private void update() {
    new android.os.Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            long cur = player.getCurrentPosition();
            long dur = player.getDuration();
            currentTime = millisecondsToTime(cur);
            currentTimeView.setText(currentTime);
            if (cur < dur) {
                updatePlayer();
            }

            // update seekbar
            seekBar.setProgress( (int) Math.round((float)cur / (float)dur * 100f));
        }
    }, 500);
}

which calls the same method recursively

How to print the array?

You could try this:

#include <stdio.h>

int main() 
{  
  int i,j;
  int my_array[3][3] ={10, 23, 42, 1, 654, 0, 40652, 22, 0};
  for(i = 0; i < 3; i++) 
  {
       for(j = 0; j < 3; j++) 
       {
         printf("%d ", my_array[i][j]);
       }
    printf("\n");
  } 
  return 0;
}

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Go to resources folder where the application.properties is present, update the below code in that.

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

Style bottom Line in Android

I feel it is straightforward, without all this negative paddings or storks.

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/main_bg_color"/>
    <item android:gravity="bottom">
        <shape android:shape="rectangle">
            <size android:height="5dp"/>
            <solid android:color="@color/bottom_bar_color"/>
        </shape>
    </item>
</layer-list>

Should import statements always be at the top of a module?

Module initialization only occurs once - on the first import. If the module in question is from the standard library, then you will likely import it from other modules in your program as well. For a module as prevalent as datetime, it is also likely a dependency for a slew of other standard libraries. The import statement would cost very little then since the module intialization would have happened already. All it is doing at this point is binding the existing module object to the local scope.

Couple that information with the argument for readability and I would say that it is best to have the import statement at module scope.

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

convert string to date in sql server

I think style no. 111 (Japan) should work:

SELECT CONVERT(DATETIME, '2012-08-17', 111)

And if that doesn't work for some reason - you could always just strip out the dashes and then you have the totally reliable ISO-8601 format (YYYYMMDD) which works for any language and date format setting in SQL Server:

SELECT CAST(REPLACE('2012-08-17', '-', '') AS DATETIME)

Insert, on duplicate update in PostgreSQL?

PostgreSQL since version 9.5 has UPSERT syntax, with ON CONFLICT clause. with the following syntax (similar to MySQL)

INSERT INTO the_table (id, column_1, column_2) 
VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z')
ON CONFLICT (id) DO UPDATE 
  SET column_1 = excluded.column_1, 
      column_2 = excluded.column_2;

Searching postgresql's email group archives for "upsert" leads to finding an example of doing what you possibly want to do, in the manual:

Example 38-2. Exceptions with UPDATE/INSERT

This example uses exception handling to perform either UPDATE or INSERT, as appropriate:

CREATE TABLE db (a INT PRIMARY KEY, b TEXT);

CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
    LOOP
        -- first try to update the key
        -- note that "a" must be unique
        UPDATE db SET b = data WHERE a = key;
        IF found THEN
            RETURN;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
            INSERT INTO db(a,b) VALUES (key, data);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- do nothing, and loop to try the UPDATE again
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

SELECT merge_db(1, 'david');
SELECT merge_db(1, 'dennis');

There's possibly an example of how to do this in bulk, using CTEs in 9.1 and above, in the hackers mailing list:

WITH foos AS (SELECT (UNNEST(%foo[])).*)
updated as (UPDATE foo SET foo.a = foos.a ... RETURNING foo.id)
INSERT INTO foo SELECT foos.* FROM foos LEFT JOIN updated USING(id)
WHERE updated.id IS NULL;

See a_horse_with_no_name's answer for a clearer example.

How do I simulate placeholder functionality on input date field?

Using a jQuery (sure you can achieve this with Vanilla. This make sure the date format still the same.

_x000D_
_x000D_
$(function() {_x000D_
  $('.sdate').on('focus', function() {_x000D_
    $(this).attr('type', 'date');_x000D_
  });_x000D_
  $('.sdate').on('blur', function() {_x000D_
    if(!$(this).val()) { // important_x000D_
      $(this).attr('type', 'text');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="sdate" placeholder="From">
_x000D_
_x000D_
_x000D_

Java out.println() how is this possible?

PrintStream out = System.out;
out.println( "hello" );

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

You can solve this by finding

ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci;

in your .sql file, and swapping it with

ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

In my case, web server prevented "OPTIONS" method

Check your web server for the options method

I'm using "webtier"

/www/webtier/domains/[domainname]/config/fmwconfig/components/OHS/VCWeb1/httpd.conf

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_METHOD} ^OPTIONS
  RewriteRule .* . [F]
</IfModule>

change to

<IfModule mod_rewrite.c>
  RewriteEngine off
  RewriteCond %{REQUEST_METHOD} ^OPTIONS
  RewriteRule .* . [F]
</IfModule>

Html.DropDownList - Disabled/Readonly

@Html.DropDownList("Types", Model.Types, new { @disabled = "" })

Works

How to revert to origin's master branch's version of file

I've faced same problem and came across to this thread but my problem was with upstream. Below git command worked for me.

Syntax

git checkout {remoteName}/{branch} -- {../path/file.js}

Example

git checkout upstream/develop -- public/js/index.js

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

How to add "on delete cascade" constraints?

Usage:

select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');

Function:

CREATE OR REPLACE FUNCTION 
    replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR) 
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN

SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name 
FROM 
    information_schema.table_constraints AS tc 
    JOIN information_schema.key_column_usage AS kcu
      ON tc.constraint_name = kcu.constraint_name
    JOIN information_schema.constraint_column_usage AS ccu
      ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY' 
   AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;

EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name || 
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';

RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
 ' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;

END;
$$ LANGUAGE plpgsql;

Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.

WPF Timer Like C# Timer

The timer has special functions.

  1. Call an asynchronous timer or synchronous timer.
  2. Change the time interval
  3. Ability to cancel and resume  

if you use StartAsync () or Start (), the thread does not block the user interface element

     namespace UITimer


     {
        using thread = System.Threading;
        public class Timer
        {

        public event Action<thread::SynchronizationContext> TaskAsyncTick;
        public event Action Tick;
        public event Action AsyncTick;
        public int Interval { get; set; } = 1;
        private bool canceled = false;
        private bool canceling = false;
        public async void Start()
        {
            while(true)
            {

                if (!canceled)
                {
                    if (!canceling)
                    {
                        await Task.Delay(Interval);
                        Tick.Invoke();
                    }
                }
                else
                {
                    canceled = false;
                    break;
                }
            }


        }
        public void Resume()
        {
            canceling = false;
        }
        public void Cancel()
        {
            canceling = true;
        }
        public async void StartAsyncTask(thread::SynchronizationContext 
        context)
        {

                while (true)
                {
                    if (!canceled)
                    {
                    if (!canceling)
                    {
                        await Task.Delay(Interval).ConfigureAwait(false);

                        TaskAsyncTick.Invoke(context);
                    }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }

        }
        public void StartAsync()
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while (true)
                {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);

                    Application.Current.Dispatcher.Invoke(AsyncTick);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }

        public void StartAsync(thread::SynchronizationContext context)
        {
            thread::ThreadPool.QueueUserWorkItem((x) =>
            {
                while(true)
                 {

                    if (!canceled)
                    {
                        if (!canceling)
                        {
                            thread::Thread.Sleep(Interval);
                            context.Post((xfail) => { AsyncTick.Invoke(); }, null);
                        }
                    }
                    else
                    {
                        canceled = false;
                        break;
                    }
                }
            });
        }
        public void Abort()
        {
            canceled = true;
        }
    }


     }

Why can't Python import Image from PIL?

The current free version is PIL 1.1.7. This release supports Python 1.5.2 and newer, including 2.5 and 2.6. A version for 3.X will be released later.

Python Imaging Library (PIL)

Your python version is 3.4.1, PIL do not support!

pip install gives error: Unable to find vcvarsall.bat

I appreciate this might not be the answer to resolving on 3.4 but I tried a huge variety of things to fix this on 3.4 and thought this might be useful if someone is time pressed or doesn't have the know-how to correct it (in my case, work demands).

With exactly the same setup, I found that my installation problems only happened with Python 3.4. When I changed to 2.7, all my issues seemed to be resolved.

We have a rather overzealous security setup though so I'm going to try the same on my home version (still 3.4) and see if I have any more joy. My inclination is that my VS version has somehow been restricted and the answers above should help. If I find anything more tonight I'll add further detail.

This is my first reply, not the most technical I'm afraid!

Get key from a HashMap using the value

You mixed the keys and the values.

Hashmap <Integer,String> hashmap = new HashMap<Integer, String>();

hashmap.put(100, "one");
hashmap.put(200, "two");

Afterwards a

hashmap.get(100);

will give you "one"

Find an object in array?

Use Dollar which is Lo-Dash or Underscore.js for Swift:

import Dollar

let found = $.find(array) { $0.name == "Foo" }

Forgot Oracle username and password, how to retrieve?

if you are on Windows

  1. Start the Oracle service if it is not started (most probably it starts automatically when Windows starts)
  2. Start CMD.exe
  3. in the cmd (black window) type: sqlplus / as sysdba

Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.

How can I insert data into a MySQL database?

#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()

edit working for me:

>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>> 
>>> #setup cursor
... cursor = db.cursor()
>>> 
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>> 
>>> sql = """CREATE TABLE anooog1 (
...          COL1 INT,  
...          COL2 INT )"""
>>> cursor.execute(sql)
0L
>>> 
>>> #insert to table
... try:
...     cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
...     db.commit()
... except:     
...     db.rollback()
... 
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>> 
>>> db.close()

table in mysql;

mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
|  188 |   90 |
+------+------+
1 row in set (0.00 sec)

mysql> 

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

Android adding simple animations while setvisibility(view.Gone)

Try adding this line to the xml parent layout

 android:animateLayoutChanges="true"

Your layout will look like this

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:longClickable="false"
    android:orientation="vertical"
    android:weightSum="16">

    .......other code here

    </LinearLayout>

Convert a String representation of a Dictionary to a dictionary?

https://docs.python.org/3.8/library/json.html

JSON can solve this problem though its decoder wants double quotes around keys and values. If you don't mind a replace hack...

import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}

NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.

More about json single quote: jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Can I try/catch a warning?

Be careful with the @ operator - while it suppresses warnings it also suppresses fatal errors. I spent a lot of time debugging a problem in a system where someone had written @mysql_query( '...' ) and the problem was that mysql support was not loaded into PHP and it threw a silent fatal error. It will be safe for those things that are part of the PHP core but please use it with care.

bob@mypc:~$ php -a
Interactive shell

php > echo @something(); // this will just silently die...

No further output - good luck debugging this!

bob@mypc:~$ php -a
Interactive shell

php > echo something(); // lets try it again but don't suppress the error
PHP Fatal error:  Call to undefined function something() in php shell code on line 1
PHP Stack trace:
PHP   1. {main}() php shell code:0
bob@mypc:~$ 

This time we can see why it failed.

"for loop" with two variables?

for (i,j) in [(i,j) for i in range(x) for j in range(y)]

should do it.

How to create a JavaScript callback for knowing when an image is loaded?

Not suitable for 2008 when the question was asked, but these days this works well for me:

async function newImageSrc(src) {
  // Get a reference to the image in whatever way suits.
  let image = document.getElementById('image-id');

  // Update the source.
  img.src = src;

  // Wait for it to load.
  await new Promise((resolve) => { image.onload = resolve; });

  // Done!
  console.log('image loaded! do something...');
}

Query to count the number of tables I have in MySQL

Hope this helps, and returns only number of tables in a database

Use database;

SELECT COUNT(*) FROM sys.tables;

How do I convert uint to int in C#?

Assuming that the value contained in the uint can be represented in an int, then it is as simple as:

int val = (int) uval;

How to Check if value exists in a MySQL database

I tried to d this for a while and $sqlcommand = 'SELECT * FROM database WHERE search="'.$searchString.'";';
$sth = $db->prepare($sqlcommand); $sth->execute(); $record = $sth->fetch(); if ($sth->fetchColumn() > 0){}
just works if there are TWO identical entries, but, if you replace if ($sth->fetchColumn() > 0){} with if ($result){} it works with only one matching record, hope this helps.

Xpath: select div that contains class AND whose specific child element contains text

You could use the xpath :

//div[@class="measure-tab" and .//span[contains(., "someText")]]

Input :

<root>
<div class="measure-tab">
  <td> someText</td>
</div>
<div class="measure-tab">
  <div>
    <div2>
       <span>someText2</span>
   </div2>
  </div>
</div>
</root>

Output :

    Element='<div class="measure-tab">
  <div>
    <div2>
      <span>someText2</span>
    </div2>
  </div>
</div>'

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

Minimum rights required to run a windows service as a domain account

I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.

How to limit google autocomplete results to City and Country only

<html>
  <head>
    <title>Example Using Google Complete API</title>   
  </head>
  <body>

<form>
   <input id="geocomplete" type="text" placeholder="Type an address/location"/>
    </form>
   <script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

  <script src="http://ubilabs.github.io/geocomplete/jquery.geocomplete.js"></script>
  <script>
   $(function(){        
    $("#geocomplete").geocomplete();                           
   });
  </script>
 </body>
</html>

For more information visit this link

What's the difference between a POST and a PUT HTTP REQUEST?

Actually there's no difference other than their title. There's actually a basic difference between GET and the others. With a "GET"-Request method, you send the data in the url-address-line, which are separated first by a question-mark, and then with a & sign.

But with a "POST"-request method, you can't pass data through the url, but you have to pass the data as an object in the so called "body" of the request. On the server side, you have then to read out the body of the received content in order to get the sent data. But there's on the other side no possibility to send content in the body, when you send a "GET"-Request.

The claim, that "GET" is only for getting data and "POST" is for posting data, is absolutely wrong. Noone can prevent you from creating new content, deleting existing content, editing existing content or do whatever in the backend, based on the data, that is sent by the "GET" request or by the "POST" request. And nobody can prevent you to code the backend in a way, that with a "POST"-Request, the client asks for some data.

With a request, no matter which method you use, you call a URL and send or don't send some data to specify, which information you want to pass to the server to deal with your request, and then the client gets an answer from the server. The data can contain whatever you want to send, the backend is allowed to do whatever it wants with the data and the response can contain any information, that you want to put in there.

There are only these two BASIC METHODS. GET and POST. But it's their structure, which makes them different and not what you code in the backend. In the backend you can code whatever you want to, with the received data. But with the "POST"-request you have to send/retrieve the data in the body and not in the url-addressline, and with a "GET" request, you have to send/retrieve data in the url-addressline and not in the body. That's all.

All the other methods, like "PUT", "DELETE" and so on, they have the same structure as "POST".

The POST Method is mainly used, if you want to hide the content somewhat, because whatever you write in the url-addressline, this will be saved in the cache and a GET-Method is the same as writing a url-addressline with data. So if you want to send sensitive data, which is not always necessarily username and password, but for example some ids or hashes, which you don't want to be shown in the url-address-line, then you should use the POST method.

Also the URL-Addressline's length is limited to 1024 symbols, whereas the "POST"-Method is not restricted. So if you have a bigger amount of data, you might not be able to send it with a GET-Request, but you'll need to use the POST-Request. So this is also another plus point for the POST-request.

But dealing with the GET-request is way easier, when you don't have complicated text to send. Otherwise, and this is another plus point for the POST method, is, that with the GET-method you need to url-encode the text, in order to be able to send some symbols within the text or even spaces. But with a POST method you have no restrictions and your content doesn't need to be changed or manipulated in any way.

How to tell if tensorflow is using gpu acceleration from inside python shell?

For TF2.4+ listed as the "official" way on tensorflow website to check if TF is using GPU or Not

>>> import tensorflow as tf
>>> print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
Num GPUs Available:  2

How to stop INFO messages displaying on spark console?

  1. Adjust conf/log4j.properties as described by other log4j.rootCategory=ERROR, console
  2. Make sure while executing your spark job you pass --file flag with log4j.properties file path
  3. If it still doesn't work you might have a jar that has log4j.properties that is being called before your new log4j.properties. Remove that log4j.properties from jar (if appropriate)

Amazon S3 - HTTPS/SSL - Is it possible?

payton109’s answer is correct if you’re in the default US-EAST-1 region. If your bucket is in a different region, use a slightly different URL:

https://s3-<region>.amazonaws.com/your.domain.com/some/asset

Where <region> is the bucket location name. For example, if your bucket is in the us-west-2 (Oregon) region, you can do this:

https://s3-us-west-2.amazonaws.com/your.domain.com/some/asset

Different font size of strings in the same TextView

In case you want to avoid too much confusion for your translators, I've come up with a way to have just a placeholder in the strings, which will be handled in code.

So, supposed you have this in the strings:

    <string name="test">
        <![CDATA[
        We found %1$s items]]>
    </string>

And you want the placeholder text to have a different size and color, you can use this:

        val textToPutAsPlaceHolder = "123"
        val formattedStr = getString(R.string.test, "$textToPutAsPlaceHolder<bc/>")
        val placeHolderTextSize = resources.getDimensionPixelSize(R.dimen.some_text_size)
        val placeHolderTextColor = ContextCompat.getColor(this, R.color.design_default_color_primary_dark)
        val textToShow = HtmlCompat.fromHtml(formattedStr, HtmlCompat.FROM_HTML_MODE_LEGACY, null, object : Html.TagHandler {
            var start = 0
            override fun handleTag(opening: Boolean, tag: String, output: Editable, xmlReader: XMLReader) {
                when (tag) {
                    "bc" -> if (!opening) start = output.length - textToPutAsPlaceHolder.length
                    "html" -> if (!opening) {
                        output.setSpan(AbsoluteSizeSpan(placeHolderTextSize), start, start + textToPutAsPlaceHolder.length, 0)
                        output.setSpan(ForegroundColorSpan(placeHolderTextColor), start, start + textToPutAsPlaceHolder.length, 0)
                    }
                }
            }
        })
        textView.text = textToShow

And the result:

enter image description here

Declaring a xsl variable and assigning value to it

No, unlike in a lot of other languages, XSLT variables cannot change their values after they are created. You can however, avoid extraneous code with a technique like this:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes" omit-xml-declaration="yes"/>

  <xsl:variable name="mapping">
    <item key="1" v1="A" v2="B" />
    <item key="2" v1="X" v2="Y" />
  </xsl:variable>
  <xsl:variable name="mappingNode"
                select="document('')//xsl:variable[@name = 'mapping']" />

  <xsl:template match="....">
    <xsl:variable name="testVariable" select="'1'" />

    <xsl:variable name="values" select="$mappingNode/item[@key = $testVariable]" />

    <xsl:variable name="variable1" select="$values/@v1" />
    <xsl:variable name="variable2" select="$values/@v2" />
  </xsl:template>
</xsl:stylesheet>

In fact, once you've got the values variable, you may not even need separate variable1 and variable2 variables. You could just use $values/@v1 and $values/@v2 instead.

Adding items to end of linked list

The above programs might give you NullPointerException. This is an easier way to add an element to the end of linkedList.

public class LinkedList {
    Node head;

    public static class Node{
        int data;
        Node next;

        Node(int item){
            data = item;
            next = null;
        }
    }
    public static void main(String args[]){
        LinkedList ll = new LinkedList();
        ll.head = new Node(1);
        Node second = new Node(2);
        Node third = new Node(3);
        Node fourth = new Node(4);

        ll.head.next = second;
        second.next = third;
        third.next = fourth;
        fourth.next = null;

        ll.printList();
        System.out.println("Add element 100 to the last");
        ll.addLast(100);
        ll.printList();
    }
    public void printList(){
        Node t = head;
        while(n != null){
            System.out.println(t.data);
            t = t.next;
        }

    }

    public void addLast(int item){
        Node new_item = new Node(item);
        if(head == null){
            head = new_item;
            return;
        }
        new_item.next = null;

        Node last = head;
        Node temp = null;
        while(last != null){
            if(last != null)
                temp = last;
            last = last.next;
        }   

        temp.next = new_item;   
        return;
    }
}

How to remove specific object from ArrayList in Java?

use this code

test.remove(test.indexOf(obj));

test is your ArrayList and obj is the Object, first you find the index of obj in ArrayList and then you remove it from the ArrayList.

How to connect to remote Redis server?

redis-cli -h XXX.XXX.XXX.XXX -p YYYY

xxx.xxx.xxx.xxx is the IP address and yyyy is the port

EXAMPLE from my dev environment

redis-cli -h 10.144.62.3 -p 30000

REDIS CLI COMMANDS

Host, port, password and database By default redis-cli connects to the server at 127.0.0.1 port 6379. As you can guess, you can easily change this using command line options. To specify a different host name or an IP address, use -h. In order to set a different port, use -p.

redis-cli -h redis15.localnet.org -p 6390 ping

Passing base64 encoded strings in URL

@joeshmo Or instead of writing a helper function, you could just urlencode the base64 encoded string. This would do the exact same thing as your helper function, but without the need of two extra functions.

$str = 'Some String';

$encoded = urlencode( base64_encode( $str ) );
$decoded = base64_decode( urldecode( $encoded ) );

Listview Scroll to the end of the list after updating the list

Using : Set the head of the list to it bottom lv.setStackFromBottom(true);

Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

No IEnumerable is an interface, you can't create instance of interface

you can do something like this

IEnumerable<object> a = new object[0];

Find where python is installed (if it isn't default dir)

You should be able to type "which python" and it will print out a path to python.

or you can type:

python
>>> import re
>>> re.__file__

and it will print a path to the re module and you'll see where python is that way.

How do I assert an Iterable contains elements with a certain property?

Assertj is good at this.

import static org.assertj.core.api.Assertions.assertThat;

    assertThat(myClass.getMyItems()).extracting("name").contains("foo", "bar");

Big plus for assertj compared to hamcrest is easy use of code completion.

Is there any way to wait for AJAX response and halt execution?

When using promises they can be used in a promise chain. async=false will be deprecated so using promises is your best option.

function functABC() {
  return new Promise(function(resolve, reject) {
    $.ajax({
      url: 'myPage.php',
      data: {id: id},
      success: function(data) {
        resolve(data) // Resolve promise and go to then()
      },
      error: function(err) {
        reject(err) // Reject the promise and go to catch()
      }
    });
  });
}

functABC().then(function(data) {
  // Run this when your request was successful
  console.log(data)
}).catch(function(err) {
  // Run this when promise was rejected via reject()
  console.log(err)
})

mysql -> insert into tbl (select from another table) and some default values

You simply have to do:

INSERT INTO def (catid, title, page, publish) 
SELECT catid, title, 'page','yes' from `abc`

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:

if(theHref){
   // do stuff
}else{
  // do other stuff
}

An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)

Ripple effect on Android Lollipop CardView

I managed to get the ripple effect on the cardview by :

<android.support.v7.widget.CardView 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    android:clickable="true" 
    android:foreground="@drawable/custom_bg"/>

and for the custom_bg that you can see in above code, you have to define a xml file for both lollipop(in drawable-v21 package) and pre-lollipop(in drawable package) devices. for custom_bg in drawable-v21 package the code is:

<ripple 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="?android:attr/colorControlHighlight">
<item
    android:id="@android:id/mask"
    android:drawable="@android:color/white"/>
</ripple>

for custom_bg in the drawable package, code is:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_pressed="true">
    <shape>
        <solid android:color="@color/colorHighlight"></solid>
    </shape>
</item>
<item>
    <shape>
        <solid android:color="@color/navigation_drawer_background"></solid>
    </shape>
</item>
</selector>

so on pre-lollipop devices you will have a solid click effect and on lollipop devices you will have a ripple effect on the cardview.

apache redirect from non www to www

<VirtualHost *:80>
    ServerAlias example.com
    RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>

difference between throw and throw new Exception()

throw or throw ex, both are used to throw or rethrow the exception, when you just simply log the error information and don't want to send any information back to the caller you simply log the error in catch and leave. But incase you want to send some meaningful information about the exception to the caller you use throw or throw ex. Now the difference between throw and throw ex is that throw preserves the stack trace and other information but throw ex creates a new exception object and hence the original stack trace is lost. So when should we use throw and throw e, There are still a few situations in which you might want to rethrow an exception like to reset the call stack information. For example, if the method is in a library and you want to hide the details of the library from the calling code, you don’t necessarily want the call stack to include information about private methods within the library. In that case, you could catch exceptions in the library’s public methods and then rethrow them so that the call stack begins at those public methods.

Is there any way to delete local commits in Mercurial?

hg strip is what you are looking for. It's analogous of git reset if you familiar with git.

Use console:

  1. You need to know the revision number. hg log -l 10. This command shows the last 10 commits. Find commit you are looking for. You need 4 digit number from changeset line changeset: 5888:ba6205914681

  2. Then hg strip -r 5888 --keep. This removes the record of the commit but keeps all files modified and then you could recommit them. (if you want to delete files to just remove --keep hg strip -r 5888

Imported a csv-dataset to R but the values becomes factors

for me the solution was to include skip = 0 (number of rows to skip at the top of the file. Can be set >0)

mydata <- read.csv(file = "file.csv", header = TRUE, sep = ",", skip = 22)

What's the best way to do a backwards loop in C/C#/C++?

NOTE: This post ended up being far more detailed and therefore off topic, I apologize.

That being said my peers read it and believe it is valuable 'somewhere'. This thread is not the place. I would appreciate your feedback on where this should go (I am new to the site).


Anyway this is the C# version in .NET 3.5 which is amazing in that it works on any collection type using the defined semantics. This is a default measure (reuse!) not performance or CPU cycle minimization in most common dev scenario although that never seems to be what happens in the real world (premature optimization).

*** Extension method working over any collection type and taking an action delegate expecting a single value of the type, all executed over each item in reverse **

Requres 3.5:

public static void PerformOverReversed<T>(this IEnumerable<T> sequenceToReverse, Action<T> doForEachReversed)
      {
          foreach (var contextItem in sequenceToReverse.Reverse())
              doForEachReversed(contextItem);
      }

Older .NET versions or do you want to understand Linq internals better? Read on.. Or not..

ASSUMPTION: In the .NET type system the Array type inherits from the IEnumerable interface (not the generic IEnumerable only IEnumerable).

This is all you need to iterate from beginning to end, however you want to move in the opposite direction. As IEnumerable works on Array of type 'object' any type is valid,

CRITICAL MEASURE: We assume if you can process any sequence in reverse order that is 'better' then only being able to do it on integers.

Solution a for .NET CLR 2.0-3.0:

Description: We will accept any IEnumerable implementing instance with the mandate that each instance it contains is of the same type. So if we recieve an array the entire array contains instances of type X. If any other instances are of a type !=X an exception is thrown:

A singleton service:

public class ReverserService { private ReverserService() { }

    /// <summary>
    /// Most importantly uses yield command for efficiency
    /// </summary>
    /// <param name="enumerableInstance"></param>
    /// <returns></returns>
    public static IEnumerable ToReveresed(IEnumerable enumerableInstance)
    {
        if (enumerableInstance == null)
        {
            throw new ArgumentNullException("enumerableInstance");
        }

        // First we need to move forwarad and create a temp
        // copy of a type that allows us to move backwards
        // We can use ArrayList for this as the concrete
        // type

        IList reversedEnumerable = new ArrayList();
        IEnumerator tempEnumerator = enumerableInstance.GetEnumerator();

        while (tempEnumerator.MoveNext())
        {
            reversedEnumerable.Add(tempEnumerator.Current);
        }

        // Now we do the standard reverse over this using yield to return
        // the result
        // NOTE: This is an immutable result by design. That is 
        // a design goal for this simple question as well as most other set related 
        // requirements, which is why Linq results are immutable for example
        // In fact this is foundational code to understand Linq

        for (var i = reversedEnumerable.Count - 1; i >= 0; i--)
        {
            yield return reversedEnumerable[i];
        }
    }
}



public static class ExtensionMethods
{

      public static IEnumerable ToReveresed(this IEnumerable enumerableInstance)
      {
          return ReverserService.ToReveresed(enumerableInstance);
      }
 }

[TestFixture] public class Testing123 {

    /// <summary>
    /// .NET 1.1 CLR
    /// </summary>
    [Test]
    public void Tester_fornet_1_dot_1()
    {
        const int initialSize = 1000;

        // Create the baseline data
        int[] myArray = new int[initialSize];

        for (var i = 0; i < initialSize; i++)
        {
            myArray[i] = i + 1;
        }

        IEnumerable _revered = ReverserService.ToReveresed(myArray);

        Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));
    }

    [Test]
    public void tester_why_this_is_good()
    {

        ArrayList names = new ArrayList();
        names.Add("Jim");
        names.Add("Bob");
        names.Add("Eric");
        names.Add("Sam");

        IEnumerable _revered = ReverserService.ToReveresed(names);

        Assert.IsTrue(TestAndGetResult(_revered).Equals("Sam"));


    }

    [Test]
    public void tester_extension_method()
  {

        // Extension Methods No Linq (Linq does this for you as I will show)
        var enumerableOfInt = Enumerable.Range(1, 1000);

        // Use Extension Method - which simply wraps older clr code
        IEnumerable _revered = enumerableOfInt.ToReveresed();

        Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));


    }


    [Test]
    public void tester_linq_3_dot_5_clr()
    {

        // Extension Methods No Linq (Linq does this for you as I will show)
        IEnumerable enumerableOfInt = Enumerable.Range(1, 1000);

        // Reverse is Linq (which is are extension methods off IEnumerable<T>
        // Note you must case IEnumerable (non generic) using OfType or Cast
        IEnumerable _revered = enumerableOfInt.Cast<int>().Reverse();

        Assert.IsTrue(TestAndGetResult(_revered).Equals(1000));


    }



    [Test]
    public void tester_final_and_recommended_colution()
    {

        var enumerableOfInt = Enumerable.Range(1, 1000);
        enumerableOfInt.PerformOverReversed(i => Debug.WriteLine(i));

    }



    private static object TestAndGetResult(IEnumerable enumerableIn)
    {
      //  IEnumerable x = ReverserService.ToReveresed(names);

        Assert.IsTrue(enumerableIn != null);
        IEnumerator _test = enumerableIn.GetEnumerator();

        // Move to first
        Assert.IsTrue(_test.MoveNext());
        return _test.Current;
    }
}

How do I parse JSON with Objective-C?

  1. I recommend and use TouchJSON for parsing JSON.
  2. To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:

    NSDictionary *userinfo=[jsondic valueforKey:@"#data"];
    NSDictionary *user;
    NSInteger i = 0;
    NSString *skey;
    if(userinfo != nil){
        for( i = 0; i < [userinfo count]; i++ ) {
            if(i)
                skey = [NSString stringWithFormat:@"%d",i];
            else
                skey = @"";
    
            user = [userinfo objectForKey:skey];
            NSLog(@"activity_details:%@",[user objectForKey:@"activity_details"]);
            NSLog(@"last_name:%@",[user objectForKey:@"last_name"]);
            NSLog(@"first_name:%@",[user objectForKey:@"first_name"]);
            NSLog(@"photo_url:%@",[user objectForKey:@"photo_url"]);
        }
    }
    

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

try to call jQuery library before bootstrap.js

<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>

Node.js fs.readdir recursive directory search

For fun, here is a flow based version that works with highland.js streams library. It was co-authored by Victor Vu.

###
  directory >---m------> dirFilesStream >---------o----> out
                |                                 |
                |                                 |
                +--------< returnPipe <-----------+

  legend: (m)erge  (o)bserve

 + directory         has the initial file
 + dirListStream     does a directory listing
 + out               prints out the full path of the file
 + returnPipe        runs stat and filters on directories

###

_ = require('highland')
fs = require('fs')
fsPath = require('path')

directory = _(['someDirectory'])
mergePoint = _()
dirFilesStream = mergePoint.merge().flatMap((parentPath) ->
  _.wrapCallback(fs.readdir)(parentPath).sequence().map (path) ->
    fsPath.join parentPath, path
)
out = dirFilesStream
# Create the return pipe
returnPipe = dirFilesStream.observe().flatFilter((path) ->
  _.wrapCallback(fs.stat)(path).map (v) ->
    v.isDirectory()
)
# Connect up the merge point now that we have all of our streams.
mergePoint.write directory
mergePoint.write returnPipe
mergePoint.end()
# Release backpressure.  This will print files as they are discovered
out.each H.log
# Another way would be to queue them all up and then print them all out at once.
# out.toArray((files)-> console.log(files))

How to export query result to csv in Oracle SQL Developer?

Version I am using

alt text

Update 5th May 2012

Jeff Smith has blogged showing, what I believe is the superior method to get CSV output from SQL Developer. Jeff's method is shown as Method 1 below:

Method 1

Add the comment /*csv*/ to your SQL query and run the query as a script (using F5 or the 2nd execution button on the worksheet toolbar)

enter image description here

That's it.

Method 2

Run a query

alt text

Right click and select unload.

Update. In Sql Developer Version 3.0.04 unload has been changed to export Thanks to Janis Peisenieks for pointing this out

alt text

Revised screen shot for SQL Developer Version 3.0.04

enter image description here

From the format drop down select CSV

alt text

And follow the rest of the on screen instructions.

Decimal precision and scale in EF Code First

this code line could be a simpler way to acomplish the same:

 public class ProductConfiguration : EntityTypeConfiguration<Product>
    {
        public ProductConfiguration()
        {
            this.Property(m => m.Price).HasPrecision(10, 2);
        }
    }

How can I get the browser's scrollbar sizes?

window.scrollBarWidth = function() {
  document.body.style.overflow = 'hidden'; 
  var width = document.body.clientWidth;
  document.body.style.overflow = 'scroll'; 
  width -= document.body.clientWidth; 
  if(!width) width = document.body.offsetWidth - document.body.clientWidth;
  document.body.style.overflow = ''; 
  return width; 
} 

Refer to a cell in another worksheet by referencing the current worksheet's name?

Still using indirect. Say your A1 cell is your variable that will contain the name of the referenced sheet (Jan). If you go by:

=INDIRECT(CONCATENATE("'",A1," Item'", "!J3"))

Then you will have the 'Jan Item'!J3 value.

addEventListener in Internet Explorer

I would use these polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->

delete map[key] in go?

From Effective Go:

To delete a map entry, use the delete built-in function, whose arguments are the map and the key to be deleted. It's safe to do this even if the key is already absent from the map.

delete(timeZone, "PDT")  // Now on Standard Time

How to get value from form field in django framework?

Using a form in a view pretty much explains it.

The standard pattern for processing a form in a view looks like this:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            print form.cleaned_data['my_form_field_name']

            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

Convert SVG to PNG in Python

Here is what I did using cairosvg:

from cairosvg import svg2png

svg_code = """
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12" y2="16"/>
    </svg>
"""

svg2png(bytestring=svg_code,write_to='output.png')

And it works like a charm!

See more: cairosvg document

How to hide underbar in EditText

You can set EditText's backgroundTint value to a specific color. If you set transparent color, underbar should gone.

android:backgroundTint="@color/Transparent"

<color name="Transparent">#00000000</color>

But you can use this in Api v21(Lollipop) or higher

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.

I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:

void find_squares(Mat& image, vector<vector<Point> >& squares)
{
    // blur will enhance edge detection
    Mat blurred(image);
    medianBlur(image, blurred, 9);

    Mat gray0(blurred.size(), CV_8U), gray;
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    for (int c = 0; c < 3; c++)
    {
        int ch[] = {c, 0};
        mixChannels(&blurred, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        const int threshold_level = 2;
        for (int l = 0; l < threshold_level; l++)
        {
            // Use Canny instead of zero threshold level!
            // Canny helps to catch squares with gradient shading
            if (l == 0)
            {
                Canny(gray0, gray, 10, 20, 3); // 

                // Dilate helps to remove potential holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                    gray = gray0 >= (l+1) * 255 / threshold_level;
            }

            // Find contours and store them in a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            // Test contours
            vector<Point> approx;
            for (size_t i = 0; i < contours.size(); i++)
            {
                    // approximate contour with accuracy proportional
                    // to the contour perimeter
                    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                    // Note: absolute value of an area is used because
                    // area may be positive or negative - in accordance with the
                    // contour orientation
                    if (approx.size() == 4 &&
                            fabs(contourArea(Mat(approx))) > 1000 &&
                            isContourConvex(Mat(approx)))
                    {
                            double maxCosine = 0;

                            for (int j = 2; j < 5; j++)
                            {
                                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                    maxCosine = MAX(maxCosine, cosine);
                            }

                            if (maxCosine < 0.3)
                                    squares.push_back(approx);
                    }
            }
        }
    }
}

After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >:

opencv paper sheet detection

I'm letting you write the function to find the largest square. ;)

PHP - iterate on string characters

Step 1: convert the string to an array using the str_split function

$array = str_split($your_string);

Step 2: loop through the newly created array

foreach ($array as $char) {
 echo $char;
}

You can check the PHP docs for more information: str_split

How can I String.Format a TimeSpan object with a custom format in .NET?

Personally, I like this approach:

TimeSpan ts = ...;
string.Format("{0:%d}d {0:%h}h {0:%m}m {0:%s}s", ts);

You can make this as custom as you like with no problems:

string.Format("{0:%d}days {0:%h}hours {0:%m}min {0:%s}sec", ts);
string.Format("{0:%d}d {0:%h}h {0:%m}' {0:%s}''", ts);

how to make a jquery "$.post" request synchronous

If you want an synchronous request set the async property to false for the request. Check out the jQuery AJAX Doc

How can I install Visual Studio Code extensions offline?

I wanted to throw a PowerShell download option on the pile in case anyone else comes across this. I have several offline scenarios and I run this in a loop to download and update all of the extensions I use offline.

$page = Invoke-WebRequest -Uri 'https://marketplace.visualstudio.com/items?itemName=ms-vscode.PowerShell'

$details = ( $page.Scripts | ? {$_.class -eq 'vss-extension'}).innerHTML | Convertfrom-Json

$extensionName = $details.extensionName 
$publisher     = $details.publisher.publisherName
$version       = $details.versions.version

Invoke-WebRequest -uri "$($details.versions.fallbackAssetUri)/Microsoft.VisualStudio.Services.VSIXPackage" `
                  -OutFile "C:\Scripts\extensions\$publisher.$extensionName.$version.VSIX"

Python concatenate text files

def concatFiles():
    path = 'input/'
    files = os.listdir(path)
    for idx, infile in enumerate(files):
        print ("File #" + str(idx) + "  " + infile)
    concat = ''.join([open(path + f).read() for f in files])
    with open("output_concatFile.txt", "w") as fo:
        fo.write(path + concat)

if __name__ == "__main__":
    concatFiles()

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

Well that is Because of

you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.

look this. Try and u will be able to resolve this

public static String decrypt(String encryptedData) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
    System.out.println("This is Data to be Decrypted" + decordedValue);
    return decordedValue;
}

hope that will help.

How to solve java.lang.NoClassDefFoundError?

Don't use test classes outside the module

I do not have a solution, just another flavour of the "present at compilation, absent at run time" case.

I was trying to use a very convenient method from a JUnit test class from another test class which resides in a different module. That's a no-no, since test code is not part of the packaged jar, but I didn't realize because it appears visible for the user class from within Eclipse.

My solution was to place the method in a existing utilities class that is part of the production code.

Getting each individual digit from a whole integer

//this can be easily understandable for beginners     
int score=12344534;
int div;
for (div = 1; div <= score; div *= 10)
{

}
/*for (div = 1; div <= score; div *= 10); for loop with semicolon or empty body is same*/
while(score>0)
{
    div /= 10;
    printf("%d\n`enter code here`", score / div);
    score %= div;
}

RegEx - Match Numbers of Variable Length

You can specify how many times you want the previous item to match by using {min,max}.

{[0-9]{1,3}:[0-9]{1,3}}

Also, you can use \d for digits instead of [0-9] for most regex flavors:

{\d{1,3}:\d{1,3}}

You may also want to consider escaping the outer { and }, just to make it clear that they are not part of a repetition definition.

How can I check if a var is a string in JavaScript?

Combining the previous answers provides these solutions:

if (typeof str == 'string' || str instanceof String)

or

Object.prototype.toString.call(str) == '[object String]'

Bootstrap Carousel image doesn't align properly

I faced the same problem and solved it this way: It's possible to insert non-image content to Carousel, so we can use it. You should first insert div.inner-item (where you will make center alignment), and then insert image inside this div.

Here is my code (Ruby):

<div id="myCarousel" class="carousel slide">
    <!-- Carousel items -->
    <div class="carousel-inner">
        <div class="active item">
            <%= image_tag "couples/1.jpg" %>
        </div> 
        <% (2..55).each do |t|%>
            <div class="item">
                <div class='inner-item'>
                    <%= image_tag "couples/#{t}.jpg" %>
                </div>
            </div> 
        <% end -%>
    </div>
    <!-- Carousel nav -->
    <a class="carousel-control left" href="#myCarousel" data-slide="prev">&lsaquo;</a>
    <a class="carousel-control right" href="#myCarousel" data-slide="next">&rsaquo;</a>
</div>

And my css-code(.scss):

.inner-item {
    text-align: center;
    img {
        margin: 0 auto;
    }
}

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

Go to Phone Settings --> Developer Options --> Simulate Secondary Displays and turn it to None. If you don't see Developer Options in the settings menu (it should be at the bottom, go Settings ==> About phone and tap on the Build number a lot of times)

PHP order array by date?

You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.

$data = array(
    array(
        "title" => "Another title",
        "date"  => "Fri, 17 Jun 2011 08:55:57 +0200"
    ),
    array(
        "title" => "My title",
        "date"  => "Mon, 16 Jun 2010 06:55:57 +0200"
    )
);

function sortFunction( $a, $b ) {
    return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);

psql: FATAL: database "<user>" does not exist

By default, postgres tries to connect to a database with the same name as your user. To prevent this default behaviour, just specify user and database:

psql -U Username DatabaseName 

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

As suggested above, i had similar issue with mysql-5.7.18,
i did this in this way

1. Executed this command from "MYSQL_HOME\bin\mysqld.exe --initialize-insecure"
2. then started "MYSQL_HOME\bin\mysqld.exe"
3. Connect workbench to this localhost:3306 with username 'root'
4. then executed this query "SET PASSWORD FOR 'root'@'localhost' = 'root';"

password was also updated successfully.

Render HTML in React Native

 <WebView ref={'webview'} automaticallyAdjustContentInsets={false} source={require('../Assets/aboutus.html')} />

This worked for me :) I have html text aboutus file.

HTML how to clear input using javascript?

You could use a placeholder because it does it for you, but for old browsers that don't support placeholder, try this:

<script>
function clearThis(target) {
    if (target.value == "[email protected]") {
        target.value = "";
    }
}
function replace(target) {
    if (target.value == "" || target.value == null) {
        target.value == "[email protected]";
    }
}
</script>
<input type="text" name="email" value="[email protected]" size="x" onfocus="clearThis(this)" onblur="replace(this)" />

CODE EXPLAINED: When the text box has focus, clear the value. When text box is not focused AND when the box is blank, replace the value.

I hope that works, I have been having the same issue, but then I tried this and it worked for me.

Can I update a JSF component from a JSF backing bean method?

Everything is possible only if there is enough time to research :)

What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree

<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">

Than the ids in the html were something like:

myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType

Than in the view I got one method like:

<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>

And its implementation was in the bean like:

String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);

So this way I updated the element from the bean with no issues. PF version 6.2

Good luck and happy coding :)

SQL Server - An expression of non-boolean type specified in a context where a condition is expected, near 'RETURN'

An expression of non-boolean type specified in a context where a condition is expected

I also got this error when I forgot to add ON condition when specifying my join clause.

Is the order of elements in a JSON list preserved?

Some JavaScript engines keep keys in insertion order. V8, for instance, keeps all keys in insertion order except for keys that can be parsed as unsigned 32-bit integers.

This means that if you run either of the following:

var animals = {};
animals['dog'] = true;
animals['bear'] = true;
animals['monkey'] = true;
for (var animal in animals) {
  if (animals.hasOwnProperty(animal)) {
    $('<li>').text(animal).appendTo('#animals');
  }
}
var animals = JSON.parse('{ "dog": true, "bear": true, "monkey": true }');
for (var animal in animals) {
  $('<li>').text(animal).appendTo('#animals');
}

You'll consistently get dog, bear, and monkey in that order, on Chrome, which uses V8. Node.js also uses V8. This will hold true even if you have thousands of items. YMMV with other JavaScript engines.

Demo here and here.

How can Print Preview be called from Javascript?

You can't, Print Preview is a feature of a browser, and therefore should be protected from being called by JavaScript as it would be a security risk.

That's why your example uses Active X, which bypasses the JavaScript security issues.

So instead use the print stylesheet that you already should have and show it for media=screen,print instead of media=print.

Read Alist Apart: Going to Print for a good article on the subject of print stylesheets.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I think the Key and IV used for encryption using command line and decryption using your program are not same.

Please note that when you use the "-k" (different from "-K"), the input given is considered as a password from which the key is derived. Generally in this case, there is no need for the "-iv" option as both key and password will be derived from the input given with "-k" option.

It is not clear from your question, how you are ensuring that the Key and IV are same between encryption and decryption.

In my suggestion, better use "-K" and "-iv" option to explicitly specify the Key and IV during encryption and use the same for decryption. If you need to use "-k", then use the "-p" option to print the key and iv used for encryption and use the same in your decryption program.

More details can be obtained at https://www.openssl.org/docs/manmaster/apps/enc.html

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

Express-js wildcard routing to cover everything under and including a path

In array you also can use variables passing to req.params:

app.get(["/:foo", "/:foo/:bar"], /* function */);

What's the difference between xsd:include and xsd:import?

Another difference is that <import> allows importing by referring to another namespace. <include> only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.

For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.

Code sample of valid and invalid imports and includes:

Valid:

<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>

<xsd:include schemaLocation="classpath://mine.xsd"/>

Invalid:

<xsd:include namespace="some/name/space"/>

Measuring execution time of a function in C++

simple program to find a function execution time taken.

#include <iostream>
#include <ctime> // time_t
#include <cstdio>

void function()
{
     for(long int i=0;i<1000000000;i++)
     {
        // do nothing
     }
}

int main()
{

time_t begin,end; // time_t is a datatype to store time values.

time (&begin); // note time before execution
function();
time (&end); // note time after execution

double difference = difftime (end,begin);
printf ("time taken for function() %.2lf seconds.\n", difference );

return 0;
}

How to convert an enum type variable to a string?

Did you try this:

#define stringify( name ) # name

enum enMyErrorValue
  {
  ERROR_INVALIDINPUT = 0,
  ERROR_NULLINPUT,
  ERROR_INPUTTOOMUCH,
  ERROR_IAMBUSY
  };

const char* enMyErrorValueNames[] = 
  {
  stringify( ERROR_INVALIDINPUT ),
  stringify( ERROR_NULLINPUT ),
  stringify( ERROR_INPUTTOOMUCH ),
  stringify( ERROR_IAMBUSY )
  };

void vPrintError( enMyErrorValue enError )
  {
  cout << enMyErrorValueNames[ enError ] << endl;
  }

int main()
  {
  vPrintError((enMyErrorValue)1);
  }

The stringify() macro can be used to turn any text in your code into a string, but only the exact text between the parentheses. There are no variable dereferencing or macro substitutions or any other sort of thing done.

http://www.cplusplus.com/forum/general/2949/

Cancel a UIView animation?

I have the same problem; the APIs don't have anything to cancel some specific animation. The

+ (void)setAnimationsEnabled:(BOOL)enabled

disables ALL animations, and thus does not work for me. There's two solutions:

1) make your animated object a subview. Then, when you want to cancel the animations for that view, remove the view or hide it. Very simple, but you need to recreate the subview without animations if you need to keep it in view.

2) repeat the anim only one, and make a delegate selector to restart the anim if needed, like this:

-(void) startAnimation {
NSLog(@"startAnim alpha:%f", self.alpha);
[self setAlpha:1.0];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationRepeatCount:1];
[UIView setAnimationRepeatAutoreverses:YES];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(pulseAnimationDidStop:finished:context:)];
[self setAlpha:0.1];
[UIView commitAnimations];
}

- (void)pulseAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
if(hasFocus) {
    [self startAnimation];
} else {
    self.alpha = 1.0;
}
}

-(void) setHasFocus:(BOOL)_hasFocus {
hasFocus = _hasFocus;
if(hasFocus) {
    [self startAnimation];
}
}

Problem with 2) is that there's always delay stopping the anim as it finishes the current animation cycle.

Hope this helps.

How to merge a list of lists with same type of items to a single list of items?

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

Can I add extension methods to an existing static class?

Maybe you could add a static class with your custom namespace and the same class name:

using CLRConsole = System.Console;

namespace ExtensionMethodsDemo
{
    public static class Console
    {
        public static void WriteLine(string value)
        {
            CLRConsole.WriteLine(value);
        }

        public static void WriteBlueLine(string value)
        {
            System.ConsoleColor currentColor = CLRConsole.ForegroundColor;

            CLRConsole.ForegroundColor = System.ConsoleColor.Blue;
            CLRConsole.WriteLine(value);

            CLRConsole.ForegroundColor = currentColor;
        }

        public static System.ConsoleKeyInfo ReadKey(bool intercept)
        {
            return CLRConsole.ReadKey(intercept);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.WriteBlueLine("This text is blue");   
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey(true);
        }
    }
}

Python strftime - date without leading 0?

Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to http://docs.python.org/library/time.html -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

How do you round a number to two decimal places in C#?

You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)

You can read more here.

How can I set a cookie in react?

A very simple solution is using the sfcookies package. You just have to install it using npm for example: npm install sfcookies --save

Then you import on the file:

import { bake_cookie, read_cookie, delete_cookie } from 'sfcookies';

create a cookie key:

const cookie_key = 'namedOFCookie';

on your submit function, you create the cookie by saving data on it just like this:

bake_cookie(cookie_key, 'test');

to delete it just do

delete_cookie(cookie_key);

and to read it:

read_cookie(cookie_key)

Simple and easy to use.

How do I diff the same file between two different commits on the same branch?

From the git-diff manpage:

git diff [--options] <commit> <commit> [--] [<path>...]

For instance, to see the difference for a file "main.c" between now and two commits back, here are three equivalent commands:

$ git diff HEAD^^ HEAD main.c
$ git diff HEAD^^..HEAD -- main.c
$ git diff HEAD~2 HEAD -- main.c

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

OS X: equivalent of Linux's wget

Curl has a mode that is almost equivalent to the default wget.

curl -O <url>

This works just like

wget <url>

And, if you like, you can add this to your .bashrc:

alias wget='curl -O'

It's not 100% compatible, but it works for the most common wget usage (IMO)

Print Html template in Angular 2 (ng-print in Angular 2)

Windows applications usually come with build in print capability, but for a web application, I would choose to simply generate a PDF file.

The simplest way that I found is to generate a PDf file using PDFMake (www.pdfmake.org). You can then offer the user the choice to open or download the generated PDF file.

Non-invocable member cannot be used like a method?

I had the same issue and realized that removing the parentheses worked. Sometimes having someone else read your code can be useful if you have been the only one working on it for some time.

E.g.

  cmd.CommandType = CommandType.Text(); 

Replace: cmd.CommandType = CommandType.Text;

Dialog to pick image from gallery or from camera

I think that's up to you to show that dialog for choosing. For Gallery you'll use that code, and for Camera try this.

How to write a Python module/package?

Make a file named "hello.py"

If you are using Python 2.x

def func():
    print "Hello"

If you are using Python 3.x

def func():
    print("Hello")

Run the file. Then, you can try the following:

>>> import hello
>>> hello.func()
Hello

If you want a little bit hard, you can use the following:

If you are using Python 2.x

def say(text):
    print text

If you are using Python 3.x

def say(text):
    print(text)

See the one on the parenthesis beside the define? That is important. It is the one that you can use within the define.

Text - You can use it when you want the program to say what you want. According to its name, it is text. I hope you know what text means. It means "words" or "sentences".

Run the file. Then, you can try the following if you are using Python 3.x:

>>> import hello
>>> hello.say("hi")
hi
>>> from hello import say
>>> say("test")
test

For Python 2.x - I guess same thing with Python 3? No idea. Correct me if I made a mistake on Python 2.x (I know Python 2 but I am used with Python 3)

How to include "zero" / "0" results in COUNT aggregate?

You want an outer join for this (and you need to use person as the "driving" table)

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person 
  LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;

The reason why this is working, is that the outer (left) join will return NULL for those persons that do not have an appointment. The aggregate function count() will not count NULL values and thus you'll get a zero.

If you want to learn more about outer joins, here is a nice tutorial: http://sqlzoo.net/wiki/Using_Null

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

How to draw circle by canvas in Android?

    private Paint green = new Paint();

    private int greenx , greeny;


 green.setColor(Color.GREEN);

        green.setAntiAlias(false);

        canvas.drawCircle(greenx,greeny,20,green);

How do Python functions handle the types of the parameters that you pass in?

I have implemented a wrapper if anyone would like to specify variable types.

import functools
    
def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for i in range(len(args)):
            v = args[i]
            v_name = list(func.__annotations__.keys())[i]
            v_type = list(func.__annotations__.values())[i]
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        v = result
        v_name = 'return'
        v_type = func.__annotations__['return']
        error_msg = 'Variable `' + str(v_name) + '` should be type ('
        error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
        if not isinstance(v, v_type):
                raise TypeError(error_msg)
        return result

    return check

Use it as:

@type_check
def test(name : str) -> float:
    return 3.0

@type_check
def test2(name : str) -> str:
    return 3.0

>> test('asd')
>> 3.0

>> test(42)
>> TypeError: Variable `name` should be type (<class 'str'>) but instead is type (<class 'int'>)

>> test2('asd')
>> TypeError: Variable `return` should be type (<class 'str'>) but instead is type (<class 'float'>)

EDIT

The code above does not work if any of the arguments' (or return's) type is not declared. The following edit can help, on the other hand, it only works for kwargs and does not check args.

def type_check(func):

    @functools.wraps(func)
    def check(*args, **kwargs):
        for name, value in kwargs.items():
            v = value
            v_name = name
            if name not in func.__annotations__:
                continue
                
            v_type = func.__annotations__[name]

            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ') '
            if not isinstance(v, v_type):
                raise TypeError(error_msg)

        result = func(*args, **kwargs)
        if 'return' in func.__annotations__:
            v = result
            v_name = 'return'
            v_type = func.__annotations__['return']
            error_msg = 'Variable `' + str(v_name) + '` should be type ('
            error_msg += str(v_type) + ') but instead is type (' + str(type(v)) + ')'
            if not isinstance(v, v_type):
                    raise TypeError(error_msg)
        return result

    return check

How do I escape double quotes in attributes in an XML String in T-SQL?

Cannot comment anymore but voted it up and wanted to let folks know that &quot; works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src=&quot;(.*)&quot;.*" using the escaped version instead of double-quotes.

CSS transition fade in

I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS

div {
  opacity:0;
  transition:opacity 1s linear;*
}
div.SomeClass {
  opacity:1;
}

How to declare a inline object with inline variables without a parent class

yes, there is:

object[] x = new object[2];

x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };

you were practically there, just the declaration of the anonymous types was a little off.

Git resolve conflict using --ours/--theirs for all files

In case anyone else is looking to simply overwrite everything from one branch (say master) with the contents of another, there's an easier way:

git merge origin/master --strategy=ours

Thanks to https://stackoverflow.com/a/1295232/560114

Or for the other way around, see Is there a "theirs" version of "git merge -s ours"?

Adding to a vector of pair

revenue.push_back(pair<string,double> ("String",map[i].second));

this will work.

Get Selected Item Using Checkbox in Listview

You can use model class and use setTag() getTag() methods to keep track which items from listview are checked and which not.

More reference for this : listview with checkbox in android

Source code for model

public class Model {

    private boolean isSelected;
    private String animal;

    public String getAnimal() {
        return animal;
    }

    public void setAnimal(String animal) {
        this.animal = animal;
    }

    public boolean getSelected() {
        return isSelected;
    }

    public void setSelected(boolean selected) {
        isSelected = selected;
    }
}

put this in your custom adapter

 holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

whole code for customAdapter is

public class CustomAdapter  extends BaseAdapter {

    private Context context;
    public static ArrayList<Model> modelArrayList;


    public CustomAdapter(Context context, ArrayList<Model> modelArrayList) {

        this.context = context;
        this.modelArrayList = modelArrayList;

    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

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

    @Override
    public Object getItem(int position) {
        return modelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder(); LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_item, null, true);

            holder.checkBox = (CheckBox) convertView.findViewById(R.id.cb);
            holder.tvAnimal = (TextView) convertView.findViewById(R.id.animal);

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }


        holder.checkBox.setText("Checkbox "+position);
        holder.tvAnimal.setText(modelArrayList.get(position).getAnimal());

        holder.checkBox.setChecked(modelArrayList.get(position).getSelected());

        holder.checkBox.setTag(R.integer.btnplusview, convertView);
        holder.checkBox.setTag( position);
        holder.checkBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View tempview = (View) holder.checkBox.getTag(R.integer.btnplusview);
                TextView tv = (TextView) tempview.findViewById(R.id.animal); 
                Integer pos = (Integer)  holder.checkBox.getTag();
                Toast.makeText(context, "Checkbox "+pos+" clicked!", Toast.LENGTH_SHORT).show();

                if(modelArrayList.get(pos).getSelected()){
                    modelArrayList.get(pos).setSelected(false);
                }else {
                    modelArrayList.get(pos).setSelected(true);
                }

            }
        });

        return convertView;
    }

    private class ViewHolder {

        protected CheckBox checkBox;
        private TextView tvAnimal;

    }

}

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116