Programs & Examples On #Rms

In Java ME MIDP, RMS stands for Record Management System API, a persistent storage mechanism, through which MIDlets can persistently store data and retrieve it later. It is also a popular R package where it is an acronym for "Regression Modeling Strategies".

Method Call Chaining; returning a pointer vs a reference?

Since nullptr is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', '')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

Just go to your in your project and remove all from it

and copy below code and paste it. It will solve your issue :)

/* To learn more about this file see: */
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": [],

  "files": [
  "include": [
  "angularCompilerOptions": {
    "enableIvy": false

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

These issue arise generally due to mismatch between @ngx-translate/core version and Angular .Before installing check compatible version of corresponding ngx_trnalsate/Core, @ngx-translate/http-loader and Angular at

Eg: For Angular 6.X versions,

npm install @ngx-translate/core@10 @ngx-translate/http-loader@3 rxjs --save

Like as above, follow below command and rest of code part is common for all versions(Note: Version can obtain from(

npm install @ngx-translate/core@version @ngx-translate/http-loader@version rxjs --save

How to prevent Google Colab from disconnecting?

function ClickConnect(){
    console.log("Clicked on connect button"); 
    document.querySelector("connect").click() // Change id here

Try above code it worked for me:)

How to set value to form control in Reactive Forms in Angular

In Reactive Form, there are 2 primary solutions to update value(s) of form field(s).


  • Initialize Model Structure in Constructor:

    this.newForm ={  
       firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],
       lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]]
  • If you want to update all fields of form:

       firstName: 'abc',
       lastName: 'def'
  • If you want to update specific field of form:


Note: It’s mandatory to provide complete model structure for all form field controls within the FormGroup. If you miss any property or subset collections, then it will throw an exception.


  • If you want to update some/ specific fields of form:

       firstName: 'abc'

Note: It’s not mandatory to provide model structure for all/ any form field controls within the FormGroup. If you miss any property or subset collections, then it will not throw any exception.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

In my case updating buildToolsVersion in app level build.gradle worked perfectly. If you don't know which to use you can create new project and copy buildToolsVersion from that into existing one.

Error: Java: invalid target release: 11 - IntelliJ IDEA

I tried all the above and found this secret sauce

  1. make sure pom.xml specifies your desired jdk.
  2. make sure maven specifies your desired jdk.
  3. make sure Projects specifies your desired jdk.
  4. make sure Modules specifies your integer jdk AND Dependencies specifies your jdk. hth.

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

      children: <Widget>[
          child: ListView(...),

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

      children: <Widget>[
          height: 200, // constrain height
          child: ListView(),

  1. Use shrinkWrap, if your ListView isn't too big.

      children: <Widget>[
          shrinkWrap: true, // use it

Confirm password validation in Angular 6

I am using angular 6 and I have been searching on best way to match password and confirm password. This can also be used to match any two inputs in a form. I used Angular Directives. I have been wanting to use them

ng g d compare-validators --spec false and i will be added in your module. Below is the directive

import { Directive, Input } from '@angular/core';
import { Validator, NG_VALIDATORS, AbstractControl, ValidationErrors } from '@angular/forms';
import { Subscription } from 'rxjs';

  // tslint:disable-next-line:directive-selector
  selector: '[compare]',
  providers: [{ provide: NG_VALIDATORS, useExisting: CompareValidatorDirective, multi: true}]
export class CompareValidatorDirective implements Validator {
  // tslint:disable-next-line:no-input-rename
  @Input('compare') controlNameToCompare;

  validate(c: AbstractControl): ValidationErrors | null {
    if (c.value.length < 6 || c.value === null) {
      return null;
    const controlToCompare = c.root.get(this.controlNameToCompare);

    if (controlToCompare) {
      const subscription: Subscription = controlToCompare.valueChanges.subscribe(() => {

    return controlToCompare && controlToCompare.value !== c.value ? {'compare': true } : null;


Now in your component

<div class="col-md-6">
              <div class="form-group">
                <label class="bmd-label-floating">Password</label>
                <input type="password" class="form-control" formControlName="usrpass" [ngClass]="{ 'is-invalid': submitAttempt && f.usrpass.errors }">
                <div *ngIf="submitAttempt && signupForm.controls['usrpass'].errors" class="invalid-feedback">
                  <div *ngIf="signupForm.controls['usrpass'].errors.required">Your password is required</div>
                  <div *ngIf="signupForm.controls['usrpass'].errors.minlength">Password must be at least 6 characters</div>
            <div class="col-md-6">
              <div class="form-group">
                <label class="bmd-label-floating">Confirm Password</label>
                <input type="password" class="form-control" formControlName="confirmpass" compare = "usrpass"
                [ngClass]="{ 'is-invalid': submitAttempt && f.confirmpass.errors }">
                <div *ngIf="submitAttempt && signupForm.controls['confirmpass'].errors" class="invalid-feedback">
                  <div *ngIf="signupForm.controls['confirmpass'].errors.required">Your confirm password is required</div>
                  <div *ngIf="signupForm.controls['confirmpass'].errors.minlength">Password must be at least 6 characters</div>
                  <div *ngIf="signupForm.controls['confirmpass'].errors['compare']">Confirm password and Password dont match</div>

I hope this one helps

Best way to "push" into C# array

There are couple of ways this can be done.

First, is converting to list and then to array again:

List<int> tmpList = intArry.ToList();
intArry = tmpList.ToArray();

Now this is not recommended as you convert to list and back again to array. If you do not want to use a list, you can use the second way which is assigning values directly into the array:

int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
    terms[runs] = value;

This is the direct approach and if you do not want to tangle with lists and conversions, this is recommended for you.

Xcode couldn't find any provisioning profiles matching


  1. Unique name (across all Apple Apps)
  2. Have to sign in while your phone is connected (mine had a large warning here)

Worked great without restart on Xcode 10


How to add image in Flutter

I think the error is caused by the redundant ,

  uses-material-design: true, # <<< redundant , at the end of the line
    - images/lake.jpg

I'd also suggest to create an assets folder in the directory that contains the pubspec.yaml file and move images there and use

  uses-material-design: true
    - assets/images/lake.jpg

The assets directory will get some additional IDE support that you won't have if you put assets somewhere else.

Can not find module “@angular-devkit/build-angular”

From angular 6 you can run the command below to fix that issue

npm install --save-dev @angular-devkit/build-angular


yarn add @angular-devkit/build-angular --dev 

If your you still can not resolve issues, you can see other option from an unhandled exception occurred: cannot find module '@angular-devkit/build-angular/package.json'

Could not find module "@angular-devkit/build-angular"

Install @angular-devkit/build-angular as dev dependency. This package is newly introduced in Angular 6.0

npm install --save-dev @angular-devkit/build-angular


yarn add @angular-devkit/build-angular --dev

Angular 5 Button Submit On Enter Key Press

Another alternative can be to execute the Keydown or KeyUp in the tag of the Form

<form name="nameForm" [formGroup]="groupForm" (keydown.enter)="executeFunction()" >

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Make sure you have imported HttpClientModule instead of adding HttpClient direcly to the list of providers.

See for more info.

The HttpClientModule actually provides HttpClient for you. See

Code sample:

import { HttpClientModule, /* other http imports */ } from "@angular/common/http";

    // ...other declarations, providers, entryComponents, etc.
    imports: [
        // ...some other imports
export class AppModule { }

Extract Google Drive zip from Google colab notebook

Colab research team has a notebook for helping you out.

Still, in short, if you are dealing with a zip file, like for me it is mostly thousands of images and I want to store them in a folder within drive then do this --

!unzip -u "/content/drive/My Drive/folder/" -d "/content/drive/My Drive/folder/NewFolder"

-u part controls extraction only if new/necessary. It is important if suddenly you lose connection or hardware switches off.

-d creates the directory and extracted files are stored there.

Of course before doing this you need to mount your drive

from google.colab import drive 

I hope this helps! Cheers!!

Adding an .env file to React Project

If in case you are getting the values as undefined, then you should consider restarting the node server and recompile again.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

In my case, I had to create a new app, reinstall my node packages, and copy my src document over. That worked.

error: resource android:attr/fontVariationSettings not found

try to change the compileSdkVersion to:

compileSdkVersion 28

fontVariationSettings added in api level 28. Api doc here

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

I was having similar problem but I came out of the solution the problem was that you were using any thing in the dependency that correspond to same domain but with different versions make sure those all are same

Error : Program type already present:$Behavior

I m using android studio 3.0 and i upgrade the design pattern dependency from 26.0.1 to 27.1.1 and the error is gone now.

Add Following in gradle implementation ''

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female

How do I deal with installing peer dependencies in Angular CLI?

You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.

ng update @angular/cli @angular/core --force

For a full list of options, check the docs:

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code


    @import ",400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    /* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    _x000D_ {_x000D_
      margin-left: -250px;_x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    #sidebar ul>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    _x000D_ {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    /* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    _x000D_ {_x000D_
      width: 100%;_x000D_
    /* ---------------------------------------------------_x000D_
----------------------------------------------------- */_x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_ {_x000D_
        margin-left: 0;_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_ {_x000D_
        width: calc(100% - 250px);_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
<!DOCTYPE html>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="">_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
          <a href="#menu">Interacción</a>_x000D_
          <a href="#">Blog</a>_x000D_
          <a href="#">Acerca</a>_x000D_
          <a href="#">contacto</a>_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src=""></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src=""></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src=""></script>_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_

if this is what you want .

'mat-form-field' is not a known element - Angular 5 & Material2

You're only exporting it in your NgModule, you need to import it too

  imports: [
  exports: [
  declarations: [
})export class MaterialModule {};

better yet

const modules = [

  imports: [...modules],
  exports: [...modules]
})export class MaterialModule {};


You're declaring component (SearchComponent) depending on Angular Material before all Angular dependency are imported

Like BrowserAnimationsModule

Try moving it to MaterialModule, or before it

ng serve not detecting file changes automatically

Only need to run sudo ng serve to resolve the issue.

Property 'value' does not exist on type 'Readonly<{}>'

The Component is defined like so:

interface Component<P = {}, S = {}> extends ComponentLifecycle<P, S> { }

Meaning that the default type for the state (and props) is: {}.
If you want your component to have value in the state then you need to define it like this:

class App extends React.Component<{}, { value: string }> {


type MyProps = { ... };
type MyState = { value: string };
class App extends React.Component<MyProps, MyState> {

No provider for HttpClient

Add HttpModule and HttpClientModule in both imports and providers in app.module.ts solved the issue. imports -> import {HttpModule} from "@angular/http"; import {HttpClientModule} from "@angular/common/http";

Angular 4 - Select default value in dropdown [Reactive Forms]

In your component -

Make sure to initialize the formControl name country with a value.

For instance: Assuming that your form group name is myForm and _fb is FormBuilder instance then,

this.myForm ={

and also try replacing [value] with [ngValue].

EDIT 1: If you are unable to initialize the value when declaring then set the value when you have the value like this. 

How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium?


is not a supported browser


Open Browser    ${event_url}    ${BROWSER}   options=add_argument("--no-sandbox"); add_argument("--ignore-certificate-errors"); add_argument("--disable-dev-shm-usage'")

don't forget to add spaces between ${BROWSER} options

Angular: Cannot Get /

I had the same problem with an Angular 9.

In my case, I changed the angular.json file from

"aot": true


"aot": false

It works for me.

Please add a @Pipe/@Directive/@Component annotation. Error

In my case I mistakenly added this:

    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]

declare var configuration: any;

while the correct form is:

declare var configuration: any;

    selector: 'app-some-item',
    templateUrl: './some-item.component.html',
    styleUrls: ['./some-item.component.scss'],
    providers: [ConfirmationService]

ERROR Error: No value accessor for form control with unspecified name attribute on switch

in my case, I had a <TEXTAREA> tag from old html while converting to angular. Had to change to <textarea>.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

Had the same issue installing angular material CDK:

npm install --save @angular/material @angular/cdk @angular/animations

Adding -dev like below worked for me:

npm install --save-dev @angular/material @angular/cdk @angular/animations

How to get param from url in angular 4?

Hope this helps someone. In case that u get undefined while doing this with something that's not "id", check if u are passing right parameter:

If your route in parent-component.ts is:

 onSelect(elem) {

And in child-component.ts

  type: string;
  elem: ElemModel;

    private elemService: ElemService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.route.params.subscribe((data) => {

      console.log(data);  // 'data' will give u an object with the type inside, check the 
      name of that type inside console of devTool, as u will put that name inside 
      data[HERE] down below.

      this.type = data["elem-type-maybe"]; // Don't do this.type = data["type"], do 
      data[NAME] as said above.

      this.elem = this.elemService.getElem(this.type); // getElem is method in service 
      which returns that specific type.

VSCode cannot find module '@angular/core' or any other modules

This worked for me.

 npm install --save-dev @angular-devkit/build-angular

Only on Firefox "Loading failed for the <script> with source"

If the src is https and the certificate has expired -- and even if you've made an exception -- firefox will still display this error message, and you can see the exact reason why if you look at the request under the network tab.

Django - Reverse for '' not found. '' is not a valid view function or pattern name

The common error that I have find is when you forget to define your url in yourapp/

we don't want any suggetion!! solution plz..

Input type number "only numeric value" validation

Sometimes it is just easier to try something simple like this.

validateNumber(control: FormControl): { [s: string]: boolean } {

  //revised to reflect null as an acceptable value 
  if (control.value === null) return null;

  // check to see if the control value is no a number
  if (isNaN(control.value)) {
    return { 'NaN': true };

  return null; 

Hope this helps.

updated as per comment, You need to to call the validator like this

number: new FormControl('',[this.validateNumber.bind(this)])

The bind(this) is necessary if you are putting the validator in the component which is how I do it.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Add FormsModule in Imports Array.

declarations: [
imports: [
providers: [],
bootstrap: [AppComponent]

Or this can be done without using [(ngModel)] by using

<input [value]='' (input)='$' placeholder="name">

instead of

<input [(ngModel)]="" placeholder="Name">

Component is not part of any NgModule or the module has not been imported into your module

I got this error because I had same name of component in 2 different modules. One solution is if its shared use the exporting technique etc but in my case both had to be named same but the purpose was different.

The Real Issue

So while importing component B, the intellisense imported the path of Component A so I had to choose 2nd option of the component path from intellisense and that resolved my issue.

Angular 4 Pipe Filter

The transform method signature changed somewhere in an RC of Angular 2. Try something more like this:

export class FilterPipe implements PipeTransform {
    transform(items: any[], filterBy: string): any {
        return items.filter(item => !== -1);

And if you want to handle nulls and make the filter case insensitive, you may want to do something more like the one I have here:

export class ProductFilterPipe implements PipeTransform {

    transform(value: IProduct[], filterBy: string): IProduct[] {
        filterBy = filterBy ? filterBy.toLocaleLowerCase() : null;
        return filterBy ? value.filter((product: IProduct) =>
            product.productName.toLocaleLowerCase().indexOf(filterBy) !== -1) : value;

And NOTE: Sorting and filtering in pipes is a big issue with performance and they are NOT recommended. See the docs here for more info:

How to send json data in POST request using C#

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
    // This would be the like
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   

'router-outlet' is not a known element

In your app.module.ts file

import { RouterModule, Routes } from '@angular/router';

const appRoutes: Routes = [
    path: '',
    redirectTo: '/dashboard',
    pathMatch: 'full',
    component: DashboardComponent
    path: 'dashboard',
    component: DashboardComponent

imports: [
declarations: [
bootstrap: [AppComponent]
export class AppModule {


Add this code. Happy Coding.

Cannot find control with name: formControlName in angular reactive form

In your HTML code

<form [formGroup]="userForm">
    <input type="text" class="form-control"  [value]="item.UserFirstName" formControlName="UserFirstName">
    <input type="text" class="form-control"  [value]="item.UserLastName" formControlName="UserLastName">

In your Typescript code

export class UserprofileComponent implements OnInit {
    userForm: FormGroup;
       this.userForm = new FormGroup({
          UserFirstName: new FormControl(),
          UserLastName: new FormControl()

This works perfectly, it does not give any error.

Load json from local file with http.get() in angular 2

I you want to put the response of the request in the navItems. Because http.get() return an observable you will have to subscribe to it.

Look at this example:

// version without map_x000D_
    .subscribe((success) => {_x000D_
      this.navItems = success.json();          _x000D_
// with map_x000D_
import 'rxjs/add/operator/map'_x000D_
    .map((data) => {_x000D_
      return data.json();_x000D_
    .subscribe((success) => {_x000D_
      this.navItems = success;          _x000D_

How to change the application launcher icon on Flutter?

The one marked as correct answer, is not enough, you need one more step, type this command in the terminal in order to create the icons:

flutter pub run flutter_launcher_icons:main

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

In my case,I use the below solution

Front-end or Angular

    this.serverUrl, dataObjToPost,
      headers: new HttpHeaders({
           'Content-Type':  'application/json',

back-end (I use php)

header("Access-Control-Allow-Origin: http://localhost:4200");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header("Access-Control-Allow-Headers: Content-Type, Authorization");

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

How to fix the error "Windows SDK version 8.1" was not found?

Another way (worked for 2015) is open "Install/remove programs" (Apps & features), find Visual Studio, select Modify. In opened window, press Modify, check

  • Languages -> Visual C++ -> Common tools for Visual C++
  • Windows and web development -> Tools for universal windows apps -> Tools (1.4.1) and Windows 10 SDK ([version])
  • Windows and web development -> Tools for universal windows apps -> Windows 10 SDK ([version])

and install. Then right click on solution -> Re-target and it will compile

How to predict input image using trained model in Keras?

If someone is still struggling to make predictions on images, here is the optimized code to load the saved model and make predictions:

# Modify 'test1.jpg' and 'test2.jpg' to the images you want to predict on

from keras.models import load_model
from keras.preprocessing import image
import numpy as np

# dimensions of our images
img_width, img_height = 320, 240

# load the model we saved
model = load_model('model.h5')

# predicting images
img = image.load_img('test1.jpg', target_size=(img_width, img_height))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

images = np.vstack([x])
classes = model.predict_classes(images, batch_size=10)
print classes

# predicting multiple images at once
img = image.load_img('test2.jpg', target_size=(img_width, img_height))
y = image.img_to_array(img)
y = np.expand_dims(y, axis=0)

# pass the list of multiple images np.vstack()
images = np.vstack([x, y])
classes = model.predict_classes(images, batch_size=10)

# print the classes, the images belong to
print classes
print classes[0]
print classes[0][0]

cordova Android requirements failed: "Could not find an installed version of Gradle"

Solution for Windows (Windows 10) is:

  1. Make sure you have Java 8 installed
  2. Download Gradle binary from
  3. Create a new directory C:\Gradle with File Explorer
  4. Extract and copy gradle-6.7.1 to C:\Gradle
  5. Configure your PATH environment variable to include the path C:\Gradle\gradle-6.7.1\bin
  6. Run gradle -v to confirm all is okay. C:>Gradle -v

Gradle 6.7.1

Build time: 2020-11-16 17:09:24 UTC Revision: 2972ff02f3210d2ceed2f1ea880f026acfbab5c0

Kotlin: 1.3.72 Groovy: 2.5.12 Ant: Apache Ant(TM) version 1.10.8 compiled on May 10 2020 JVM: 1.8.0_144 (Oracle Corporation 25.144-b01) OS: Windows 10 10.0 x86


Finally, run [Cordova environments] to check that all is set for development.

C:\Users\opiyog\AndroidStudioProjects\IONIC\SecondApp>cordova requirements

Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed true Android target: installed android-30,android-29,android-28,android-27,android-26,android-25,android-24,android-23,android-22,android-21,android-19 Gradle: installed C:\Gradle\gradle-6.7.1\bin\gradle.BAT

Bootstrap 4 File Input

Bootstrap 4

More details are here

Today I need to create a browse button with multi-upload files option all above snippets are not good for me.

The official Bootstrap example is also not working when I select multiple files.

I come up with this code may be will help others in the future.

<div class="container mt-5">
  <h1 class="text-center">Bootstrap 4 Upload multiple files</h1>
  <div class="col-sm-4 mr-auto ml-auto border p-4">
  <form method="post" enctype="multipart/form-data" action="upload.php">
    <div class="form-group">
      <label><strong>Upload Files</strong></label>
      <div class="custom-file">
        <input type="file" name="files[]" multiple class="custom-file-input form-control" id="customFile">
        <label class="custom-file-label" for="customFile">Choose file</label>
    <div class="form-group">
      <button type="submit" name="upload" value="upload" id="upload" class="btn btn-block btn-dark"><i class="fa fa-fw fa-upload"></i> Upload</button>

The js code is given below.

$(document).ready(function() {
  $('input[type="file"]').on("change", function() {
    let filenames = [];
    let files = document.getElementById("customFile").files;
    if (files.length > 1) {
      filenames.push("Total Files (" + files.length + ")");
    } else {
      for (let i in files) {
        if (files.hasOwnProperty(i)) {

The working code example is given here with bootstrap 3 and bootstrap 4.3.1.

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

import the ReactiveForms Module to your components module

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

While using formControl, you have to import ReactiveFormsModule to your imports array.


import {FormsModule, ReactiveFormsModule} from '@angular/forms';

  imports: [
export class AppModule {}

Field 'browser' doesn't contain a valid alias configuration

In my case I was using invalid templateUrl.By correcting it problem solved.

        selector: 'app-edit-feather-object',
        templateUrl: ''

No provider for Router?

If you created a separate module (eg. AppRoutingModule) to contain your routing commands you can get this same error:

Error: StaticInjectorError(AppModule)[RouterLinkWithHref -> Router]: 
StaticInjectorError(Platform: core)[RouterLinkWithHref -> Router]: 
NullInjectorError: No provider for Router!

You may have forgotten to import it to the main AppModule as shown here:

  imports:      [ BrowserModule, FormsModule, RouterModule, AppRoutingModule ],
  declarations: [ AppComponent, Page1Component, Page2Component ],
  bootstrap:    [ AppComponent ]
export class AppModule { }

How to define an optional field in protobuf 3

Based on Kenton's answer, a simpler yet working solution looks like:

message Foo {
    oneof optional_baz { // "optional_" prefix here just serves as an indicator, not keyword in proto2
        int32 baz = 1;

Cannot find module '@angular/compiler'

I just run npm install and then ok.

not finding android sdk (Unity)

I have same problem.

I fixed by android sdk tool version downgrade.

The steps.

  1. Delete android sdk "tools" folder : [Your Android SDK root]/tools -> tools

  2. Download SDK Tools:

  3. Extract that to Android SDK root

  4. Build your project

When to use RabbitMQ over Kafka?

I hear this question every week... While RabbitMQ (like IBM MQ or JMS or other messaging solutions in general) is used for traditional messaging, Apache Kafka is used as streaming platform (messaging + distributed storage + processing of data). Both are built for different use cases.

You can use Kafka for "traditional messaging", but not use MQ for Kafka-specific scenarios.

The article “Apache Kafka vs. Enterprise Service Bus (ESB)—Friends, Enemies, or Frenemies? (” discusses why Kafka is not competitive but complementary to integration and messaging solutions (including RabbitMQ) and how to integrate both.

Can't bind to 'routerLink' since it isn't a known property

This problem is because you did not import the module

import {RouterModule} from '@angular/router';

And you must declare this modulce in the import section


Remove all items from a FormArray in Angular

Provided the data structure for what you will be replacing the information in the array with matches what is already there you can use patchValue!#reset-anchor

patchValue(value: any[], {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Patches the value of the FormArray. It accepts an array that matches the structure of the control, and will do its best to match the values to the correct controls in the group.

It accepts both super-sets and sub-sets of the array without throwing an error.

const arr = new FormArray([
   new FormControl(),
   new FormControl()
console.log(arr.value);   // [null, null]
console.log(arr.value);   // ['Nancy', null]

Alternatively you could use reset

reset(value?: any, {onlySelf, emitEvent}?: {onlySelf?: boolean, emitEvent?: boolean}) : void Resets the FormArray. This means by default:

The array and all descendants are marked pristine The array and all descendants are marked untouched The value of all descendants will be null or null maps You can also reset to a specific form state by passing in an array of states that matches the structure of the control. The state can be a standalone value or a form state object with both a value and a disabled status.

this.arr.reset(['name', 'last name']);
console.log(this.arr.value);  // ['name', 'last name']


this.arr.reset([   {value: 'name', disabled: true},   'last' ]);
console.log(this.arr.value);  // ['name', 'last name']
console.log(this.arr.get(0).status);  // 'DISABLED'

Here's a forked Plunker demo from some earlier work of mine demoing a very simple utilization of each.

Cleanest way to reset forms

Easiest and cleanest way to clear forms as well as their error states (dirty, pristine etc)


for more info on forms read out here

PS: As you asked a question there is no form used in your question code you are using simple two-day data binding using ngModel, not with formControl.

form.reset() method works only for formControls reset call

How Spring Security Filter Chain works

The Spring security filter chain is a very complex and flexible engine.

Key filters in the chain are (in the order)

  • SecurityContextPersistenceFilter (restores Authentication from JSESSIONID)
  • UsernamePasswordAuthenticationFilter (performs authentication)
  • ExceptionTranslationFilter (catch security exceptions from FilterSecurityInterceptor)
  • FilterSecurityInterceptor (may throw authentication and authorization exceptions)

Looking at the current stable release 4.2.1 documentation, section 13.3 Filter Ordering you could see the whole filter chain's filter organization:

13.3 Filter Ordering

The order that filters are defined in the chain is very important. Irrespective of which filters you are actually using, the order should be as follows:

  1. ChannelProcessingFilter, because it might need to redirect to a different protocol

  2. SecurityContextPersistenceFilter, so a SecurityContext can be set up in the SecurityContextHolder at the beginning of a web request, and any changes to the SecurityContext can be copied to the HttpSession when the web request ends (ready for use with the next web request)

  3. ConcurrentSessionFilter, because it uses the SecurityContextHolder functionality and needs to update the SessionRegistry to reflect ongoing requests from the principal

  4. Authentication processing mechanisms - UsernamePasswordAuthenticationFilter, CasAuthenticationFilter, BasicAuthenticationFilter etc - so that the SecurityContextHolder can be modified to contain a valid Authentication request token

  5. The SecurityContextHolderAwareRequestFilter, if you are using it to install a Spring Security aware HttpServletRequestWrapper into your servlet container

  6. The JaasApiIntegrationFilter, if a JaasAuthenticationToken is in the SecurityContextHolder this will process the FilterChain as the Subject in the JaasAuthenticationToken

  7. RememberMeAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, and the request presents a cookie that enables remember-me services to take place, a suitable remembered Authentication object will be put there

  8. AnonymousAuthenticationFilter, so that if no earlier authentication processing mechanism updated the SecurityContextHolder, an anonymous Authentication object will be put there

  9. ExceptionTranslationFilter, to catch any Spring Security exceptions so that either an HTTP error response can be returned or an appropriate AuthenticationEntryPoint can be launched

  10. FilterSecurityInterceptor, to protect web URIs and raise exceptions when access is denied

Now, I'll try to go on by your questions one by one:

I'm confused how these filters are used. Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not? Does the form-login namespace element auto-configure these filters? Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Once you are configuring a <security-http> section, for each one you must at least provide one authentication mechanism. This must be one of the filters which match group 4 in the 13.3 Filter Ordering section from the Spring Security documentation I've just referenced.

This is the minimum valid security:http element which can be configured:

<security:http authentication-manager-ref="mainAuthenticationManager" 
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>

Just doing it, these filters are configured in the filter chain proxy:

        "1": "",
        "2": "",
        "3": "",
        "4": "",
        "5": "",
        "6": "",
        "7": "",
        "8": "",
        "9": "",
        "10": ""

Note: I get them by creating a simple RestController which @Autowires the FilterChainProxy and returns it's contents:

    private FilterChainProxy filterChainProxy;

    public @ResponseBody Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        return this.getSecurityFilterChainProxy();

    public Map<Integer, Map<Integer, String>> getSecurityFilterChainProxy(){
        Map<Integer, Map<Integer, String>> filterChains= new HashMap<Integer, Map<Integer, String>>();
        int i = 1;
        for(SecurityFilterChain secfc :  this.filterChainProxy.getFilterChains()){
            //filters.put(i++, secfc.getClass().getName());
            Map<Integer, String> filters = new HashMap<Integer, String>();
            int j = 1;
            for(Filter filter : secfc.getFilters()){
                filters.put(j++, filter.getClass().getName());
            filterChains.put(i++, filters);
        return filterChains;

Here we could see that just by declaring the <security:http> element with one minimum configuration, all the default filters are included, but none of them is of a Authentication type (4th group in 13.3 Filter Ordering section). So it actually means that just by declaring the security:http element, the SecurityContextPersistenceFilter, the ExceptionTranslationFilter and the FilterSecurityInterceptor are auto-configured.

In fact, one authentication processing mechanism should be configured, and even security namespace beans processing claims for that, throwing an error during startup, but it can be bypassed adding an entry-point-ref attribute in <http:security>

If I add a basic <form-login> to the configuration, this way:

<security:http authentication-manager-ref="mainAuthenticationManager">
    <security:intercept-url pattern="/sectest/zone1/**" access="hasRole('ROLE_ADMIN')"/>
    <security:form-login />

Now, the filterChain will be like this:

        "1": "",
        "2": "",
        "3": "",
        "4": "",
        "5": "",
        "6": "",
        "7": "",
        "8": "",
        "9": "",
        "10": "",
        "11": "",
        "12": ""

Now, this two filters and are created and configured in the FilterChainProxy.

So, now, the questions:

Is it that for the spring provided form-login, UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

Yes, it is used to try to complete a login processing mechanism in case the request matches the UsernamePasswordAuthenticationFilter url. This url can be configured or even changed it's behaviour to match every request.

You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy (such as HttpBasic, CAS, etc).

Does the form-login namespace element auto-configure these filters?

No, the form-login element configures the UsernamePasswordAUthenticationFilter, and in case you don't provide a login-page url, it also configures the, which ends in a simple autogenerated login page.

The other filters are auto-configured by default just by creating a <security:http> element with no security:"none" attribute.

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

Every request should reach it, as it is the element which takes care of whether the request has the rights to reach the requested url. But some of the filters processed before might stop the filter chain processing just not calling FilterChain.doFilter(request, response);. For example, a CSRF filter might stop the filter chain processing if the request has not the csrf parameter.

What if I want to secure my REST API with JWT-token, which is retrieved from login? I must configure two namespace configuration http tags, rights? Other one for /login with UsernamePasswordAuthenticationFilter, and another one for REST url's, with custom JwtAuthenticationFilter.

No, you are not forced to do this way. You could declare both UsernamePasswordAuthenticationFilter and the JwtAuthenticationFilter in the same http element, but it depends on the concrete behaviour of each of this filters. Both approaches are possible, and which one to choose finnally depends on own preferences.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, that's true

Is UsernamePasswordAuthenticationFilter turned off by default, until I declare form-login?

Yes, you could see it in the filters raised in each one of the configs I posted

How do I replace SecurityContextPersistenceFilter with one, which will obtain Authentication from existing JWT-token rather than JSESSIONID?

You could avoid SecurityContextPersistenceFilter, just configuring session strategy in <http:element>. Just configure like this:

<security:http create-session="stateless" >

Or, In this case you could overwrite it with another filter, this way inside the <security:http> element:

<security:http ...>  
   <security:custom-filter ref="myCustomFilter" position="SECURITY_CONTEXT_FILTER"/>    
<beans:bean id="myCustomFilter" class="" />


One question about "You could too have more than one Authentication processing mechanisms configured in the same FilterchainProxy". Will the latter overwrite the authentication performed by first one, if declaring multiple (Spring implementation) authentication filters? How this relates to having multiple authentication providers?

This finally depends on the implementation of each filter itself, but it's true the fact that the latter authentication filters at least are able to overwrite any prior authentication eventually made by preceding filters.

But this won't necesarily happen. I have some production cases in secured REST services where I use a kind of authorization token which can be provided both as a Http header or inside the request body. So I configure two filters which recover that token, in one case from the Http Header and the other from the request body of the own rest request. It's true the fact that if one http request provides that authentication token both as Http header and inside the request body, both filters will try to execute the authentication mechanism delegating it to the manager, but it could be easily avoided simply checking if the request is already authenticated just at the begining of the doFilter() method of each filter.

Having more than one authentication filter is related to having more than one authentication providers, but don't force it. In the case I exposed before, I have two authentication filter but I only have one authentication provider, as both of the filters create the same type of Authentication object so in both cases the authentication manager delegates it to the same provider.

And opposite to this, I too have a scenario where I publish just one UsernamePasswordAuthenticationFilter but the user credentials both can be contained in DB or LDAP, so I have two UsernamePasswordAuthenticationToken supporting providers, and the AuthenticationManager delegates any authentication attempt from the filter to the providers secuentially to validate the credentials.

So, I think it's clear that neither the amount of authentication filters determine the amount of authentication providers nor the amount of provider determine the amount of filters.

Also, documentation states SecurityContextPersistenceFilter is responsible of cleaning the SecurityContext, which is important due thread pooling. If I omit it or provide custom implementation, I have to implement the cleaning manually, right? Are there more similar gotcha's when customizing the chain?

I did not look carefully into this filter before, but after your last question I've been checking it's implementation, and as usually in Spring, nearly everything could be configured, extended or overwrited.

The SecurityContextPersistenceFilter delegates in a SecurityContextRepository implementation the search for the SecurityContext. By default, a HttpSessionSecurityContextRepository is used, but this could be changed using one of the constructors of the filter. So it may be better to write an SecurityContextRepository which fits your needs and just configure it in the SecurityContextPersistenceFilter, trusting in it's proved behaviour rather than start making all from scratch.

How to upgrade Angular CLI project?


Use the official Angular Update Guide select your current version and the version you wish to upgrade to for the relevant upgrade guide.

See GitHub repository Angular CLI diff for comparing Angular CLI changes.

UPDATED 26/12/2018:

Use the official Angular Update Guide mentioned in the useful section above. It provides the most up to date information with links to other resources that may be useful during the upgrade.

UPDATED 08/05/2018:

Angular CLI 1.7 introduced ng update.

ng update

A new Angular CLI command to help simplify keeping your projects up to date with the latest versions. Packages can define logic which will be applied to your projects to ensure usage of latest features as well as making changes to reduce or eliminate the impact related to breaking changes.

Configuration information for ng update can be found here

1.7 to 6 update

CLI 1.7 does not support an automatic v6 update. Manually install @angular/cli via your package manager, then run the update migration schematic to finish the process.

npm install @angular/cli@^6.0.0
ng update @angular/cli --migrate-only --from=1

UPDATED 30/04/2017:

1.0 Update

You should now follow the Angular CLI migration guide

UPDATED 04/03/2017:

RC Update

You should follow the Angular CLI RC migration guide

UPDATED 20/02/2017:

Please be aware 1.0.0-beta.32 has breaking changes and has removed ng init and ng update

The pull request here states the following:

BREAKING CHANGE: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Update functionality will return to the CLI, until then manual updates of applications will need done.

The angular-cli states the following:

BREAKING CHANGES - @angular/cli: Removing the ng init & ng update commands because their current implementation causes more problems than it solves. Once RC is released, we won't need to use those to update anymore as the step will be as simple as installing the latest version of the CLI.

UPDATED 17/02/2017:

Angular-cli has now been added to the NPM @angular package. You should now replace the above command with the following -

Global package:

npm uninstall -g angular-cli @angular/cli
npm cache clean
npm install -g @angular/cli@latest

Local project package:

rm -rf node_modules dist # On Windows use rmdir /s /q node_modules dist
npm install --save-dev @angular/cli@latest
npm install
ng init


You should follow the steps from the on GitHub for updating angular via the angular-cli.

Here they are:

Updating angular-cli

To update angular-cli to a new version, you must update both the global package and your project's local package.

Global package:

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

Local project package:

rm -rf node_modules dist tmp # On Windows use rmdir /s /q node_modules dist tmp
npm install --save-dev angular-cli@latest
npm install
ng init

Running ng init will check for changes in all the auto-generated files created by ng new and allow you to update yours. You are offered four choices for each changed file: y (overwrite), n (don't overwrite), d (show diff between your file and the updated file) and h (help).

Carefully read the diffs for each code file, and either accept the changes or incorporate them manually after ng init finishes.

Angular2 module has no exported member

I had the component name wrong(it is case sensitive) in either app.rounting.ts or app.module.ts.

can not find module "@angular/material"

I followed each of the suggestions here (I'm using Angular 7), but nothing worked. My app refused to acknowledge that @angular/material existed, so it showed an error on this line:

import { MatCheckboxModule } from '@angular/material';

Even though I was using the --save parameter to add Angular Material to my project:

npm install --save @angular/material @angular/cdk refused to add anything to my "package.json" file.

I even tried deleting the package-lock.json file, as some articles suggest that this causes problems, but this had no effect.

To fix this issue, I had to manually add these two lines to my "package.json" file.

    "devDependencies": {
        "@angular/material": "~7.2.2",
        "@angular/cdk": "~7.2.2",

What I can't tell is whether this is an issue related to using Angular 7, or if it's been around for years....

No value accessor for form control

For UnitTest angular 2 with angular material you have to add MatSelectModule module in imports section.

import { MatSelectModule } from '@angular/material';

beforeEach(async(() => {
      declarations: [ CreateUserComponent ],
      imports : [ReactiveFormsModule,        

      providers: [.........]

Angular ReactiveForms: Producing an array of checkbox values?

With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.

I use a method to add or remove values in the formArray. It may be a bad approch, but it works !


<div *ngFor="let choice of checks; let i=index" class="col-md-2">
    <input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">


// For example, an array of choices
public checks: Array<ChoiceClass> = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}

initModelForm(): FormGroup{
    otherControls: [''],
    // The formArray, empty 
    myChoices: new FormArray([]),

onCheckChange(event) {
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
    // Add a new control in the arrayForm
    formArray.push(new FormControl(;
  /* unselected */
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == {
        // Remove the unselected element from the arrayForm


When I submit my form, for example my model looks like:

  otherControls : "foo",
  myChoices : ['value1', 'value2']

Only one thing is missing, a function to fill the formArray if your model already has checked values.

Can anyone explain me StandardScaler?

This is useful when you want to compare data that correspond to different units. In that case, you want to remove the units. To do that in a consistent way of all the data, you transform the data in a way that the variance is unitary and that the mean of the series is 0.

How to call a vue.js function on page load

You need to do something like this (If you want to call the method on page load):

new Vue({
    // ...
        getUnits: function() {...}
    created: function(){

Reportviewer tool missing in visual studio 2017 RC

If you're like me and tried a few of these methods and are stuck at the point that you have the control in the toolbox and can draw it on the form but it disappears from the form and puts it down in the components, then simply edit the designer and add the following in the appropriate area of InitializeComponent() to make it visible:




You'll also need to make adjustments to the location and size manually after you've added the control.

Not a great answer for sure, but if you're stuck and just need to get work done for now until you have more time to figure it out, it should help.

Get all validation errors from Angular 2 FormGroup

You can iterate over this.form.errors property.

Reactive forms - disabled attribute

When you create new Form control, use next:

variable: FormControl = new FormControl({value: '', disabled: true});

If you want change activity, use next:




How to change the integrated terminal in visual studio code or VSCode

It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).

To do so:

  1. Create an environment variable "CMDER_ROOT" pointing to your Cmder directory.
  2. In (Preferences > User Settings) in VS Code add the following settings:

"": "cmd.exe"

"": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]

Failed to find target with hash string 'android-25'

I have got same error for Android-28. In SDK manager - SDK Platform it shows me that Android API 28 is partially installed and no further updates available. so that I updated ANDROID-SDK-BUILD-TOOLS from SDK Tools and after restarting project. It will work. This might be helpful for other who faces same issue as I faced.

JWT authentication for ASP.NET Web API

In my case the JWT is created by a separate API so ASP.NET need only decode and validate it. In contrast to the accepted answer we're using RSA which is a non-symmetric algorithm, so the SymmetricSecurityKey class mentioned above won't work.

Here's the result.

using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Threading;
using System.Threading.Tasks;

    public static async Task<JwtSecurityToken> VerifyAndDecodeJwt(string accessToken)
            var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{securityApiOrigin}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
            var openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);
            var validationParameters = new TokenValidationParameters()
                ValidateLifetime = true,
                ValidateAudience = false,
                ValidateIssuer = false,
                RequireSignedTokens = true,
                IssuerSigningKeys = openIdConfig.SigningKeys,
            new JwtSecurityTokenHandler().ValidateToken(accessToken, validationParameters, out var validToken);
            // threw on invalid, so...
            return validToken as JwtSecurityToken;
        catch (Exception ex)
            return null;

What's the difference between an Angular component and module

A picture is worth a thousand words !

The concept of Angular is very simple. It propose to "build" an app with "bricks" -> modules.

This concept makes it possible to better structure the code and to facilitate reuse and sharing.

Be careful not to confuse the Angular modules with the ES2015 / TypeScript modules.

Regarding the Angular module, it is a mechanism for:

1- group components (but also services, directives, pipes etc ...)

2- define their dependencies

3- define their visibility.

An Angular module is simply defined with a class (usually empty) and the NgModule decorator.

Angular 2 : No NgModule metadata found

In my case, I was trying to upgrade my angular 6 project using ng update after that the entire universe collapse.

I was trying to update my project using this commands:

  • ng update @angular/cli
  • ng update @angular/core
  • ng update @angular/material

And then I found a problem with rxjs package and I run also this command. - npm install --save rxjs

And then I get the error

No NgModule metadata found

I solve this by deleting my node_modules folder in the project root and then I run:

  • npm install

That's is, all works nice.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

In my case even though I used all the solutions mentioned above but nothing worked for me. So I decided to uninstall docker and install it again.

Now in the process, I have noticed that I did not check Use Windows containers instead of Linux containers (this can be changed after installation) in my previous installation, and that is why I got the problem above and the solutions still did not fix it. So ensure to check it before you run desktop docker or uninstall it and install it again by checking this option.

Docker Installation Process

Is it possible to make desktop GUI application in .NET Core?

For the special case of existing Windows Forms applications:

There is a way - though I don't know how well it works.
It goes like this:
Take the Windows Forms implementation from Mono.
Port it to .NET Core or NetStandard.

Recompile your Windows Forms applications against the new System.Windows.Forms.
Fix anything that may be broken by .NET Core.
Pray that mono implements the parts you need flawlessly.
(If it doesn't, you can always stop praying, and send the Mono project a pull request with your fix/patch/feature.)

Here's my CoreFX Windows Forms repository:

Use component from another module

You have to export it from your NgModule:

  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule],
  providers: []
export class TaskModule{}

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Another item check:

Make sure you component is added to the declarations array of @NgModule in app.module.ts

declarations: [

When running the ng generate component command, it does not automatilly add it to app.module.

Python/Json:Expecting property name enclosed in double quotes

I had the same problem and what I did is to replace the single quotes with the double one, but what was worse is the fact I had the same error when I had a comma for the last attribute of the json object. So I used regex in python to replace it before using the json.loads() function. (Be careful about the s at the end of "loads")

import re

with open("file.json", 'r') as f:
     s =
     correct_format = re.sub(", *\n *}", "}", s)
     data_json = json.loads(correct_format)

The used regex return each comma followed by a newline and "}", replacing it just with a "}".

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error


    selector: 'app-logout',
    template: `<button class="btn btn-primary"(click)="logout()">Logout</button>`
export class LogoutComponent{}


    imports: [...],
    exports: [
    declarations: [LogoutComponent]
export class AccountModule{};

LogoutComponent Needs to be exported

import AccountModule in module where we want to use <app-logout> import { AccountModule } from 'util.module';

  imports: [
    CommonModule, AccountModule
  declarations: [DashboardComponent]
export class DashboardModule { }


import { Component, OnInit } from '@angular/core';

  selector: 'app-dashboard',
  template: `<div><app-logout></app-logout></div>`
export class DashboardComponent implements OnInit {
  constructor() {}
  ngOnInit() {}

I am not required to import and use CUSTOM_ELEMENTS_SCHEMA.
however its not working when dashboard.module is lazy loaded.
When using CUSTOM_ELEMENTS_SCHEMA in case of lazy loading, error is suppressed but the component is not added to dom.

What is mapDispatchToProps?

mapStateToProps() is a utility which helps your component get updated state(which is updated by some other components),
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)

Error: Unexpected value 'undefined' imported by the module

Make sure you should not import a module/component like this:

import { YOUR_COMPONENT } from './';

But it should be

import { YOUR_COMPONENT } from './YOUR_COMPONENT.ts';

@viewChild not working - cannot read property nativeElement of undefined

Sometimes, this error occurs when you're trying to target an element that is wrapped in a condition, for example: <div *ngIf="canShow"> <p #target>Targeted Element</p></div>

In this code, if canShow is false on render, Angular won't be able to get that element as it won't be rendered, hence the error that comes up.

One of the solutions is to use a display: hidden on the element instead of the *ngIf so the element gets rendered but is hidden until your condition is fulfilled.

Read More over at Github

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

I've been struggling with this error during the last 3 days. I added the ReactiveFormsModule and FormsModule as mentionned in the comments above in both of my modules but it had no effect until I reloaded my project with another "ng serve". I don't know why it didn't reload automatically but at least i'm glad it worked finally! Any explanation please?

The pipe ' ' could not be found angular2 custom pipe

Make sure you are not facing a "cross module" problem

If the component which is using the pipe, doesn't belong to the module which has declared the pipe component "globally" then the pipe is not found and you get this error message.

In my case I've declared the pipe in a separate module and imported this pipe module in any other module having components using the pipe.

I have declared a that the component in which you are using the pipe is

the Pipe Module

 import { NgModule }      from '@angular/core';
 import { myDateFormat }          from '../directives/myDateFormat';

     imports:        [],
     declarations:   [myDateFormat],
     exports:        [myDateFormat],

 export class PipeModule {

   static forRoot() {
      return {
          ngModule: PipeModule,
          providers: [],

Usage in another module (e.g. app.module)

  import { PipeModule }    from './tools/PipeModule';

     imports: [
    , PipeModule.forRoot()

No value accessor for form control with name: 'recipient'

You should add the ngDefaultControl attribute to your input like this:


Taken from comments in this post:

angular2 rc.5 custom input, No value accessor for form control with unspecified name

Note: For later versions of @angular/material:

Nowadays you should instead write:



Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

Angular 2: Can't bind to 'ngModel' since it isn't a known property of 'input'

In order to make ngModel work when using AppModules (NgModule ), you have to import FormsModule in your AppModule .

Like this:

import { NgModule } from '@angular/core';
import { BrowserModule  } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent }   from './app.component';

    declarations: [AppComponent],
    imports: [BrowserModule, FormsModule],
    bootstrap: [AppComponent]
export class AppModule {}

Angular2 set value for formGroup

To set all FormGroup values use, setValue:

  formControlName1: myValue1, 
  formControlName2: myValue2

To set only some values, use patchValue:

  formControlName1: myValue1, 
  // formControlName2: myValue2 (can be omitted)

With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

If you are getting this instead:

Error: Template parse errors:

There is no directive with "exportAs" set to "ngModel"

Which was reported as a bug in github, then likely it is not a bug since you might:

  1. have a syntax error (e.g. an extra bracket: [(ngModel)]]=), OR
  2. be mixing Reactive forms directives, such as formControlName, with the ngModel directive. This "has been deprecated in Angular v6 and will be removed in Angular v7", since this mixes both form strategies, making it:
  • seem like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work (...)

  • this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. (...)

  • To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.

When you have an input like this:

<input formControlName="first" [(ngModel)]="value">

It will show a warning about mixed form strategies in the browser's console:

It looks like you're using ngModel on the same form field as formControlName.

However, if you add the ngModel as a value in a reference variable, example:

<input formControlName="first" #firstIn="ngModel" [(ngModel)]="value">

The error above is then triggered and no warning about strategy mixing is shown.

How to get HttpContext.Current in ASP.NET Core?

YES YOU CAN, and this is how.
A secret tip for those migrating large junks chunks of code:
The following method is an evil carbuncle of a hack which is actively engaged in carrying out the express work of satan (in the eyes of .NET Core framework developers), but it works:

In public class Startup

add a property

public IConfigurationRoot Configuration { get; }

And then add a singleton IHttpContextAccessor to DI in ConfigureServices.

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

Then in Configure

    public void Configure(
              IApplicationBuilder app
             ,IHostingEnvironment env
             ,ILoggerFactory loggerFactory

add the DI Parameter IServiceProvider svp, so the method looks like:

    public void Configure(
           IApplicationBuilder app
          ,IHostingEnvironment env
          ,ILoggerFactory loggerFactory
          ,IServiceProvider svp)

Next, create a replacement class for System.Web:

namespace System.Web

    namespace Hosting
        public static class HostingEnvironment 
            public static bool m_IsHosted;

            static HostingEnvironment()
                m_IsHosted = false;

            public static bool IsHosted
                    return m_IsHosted;

    public static class HttpContext
        public static IServiceProvider ServiceProvider;

        static HttpContext()
        { }

        public static Microsoft.AspNetCore.Http.HttpContext Current
                // var factory2 = ServiceProvider.GetService<Microsoft.AspNetCore.Http.IHttpContextAccessor>();
                object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

                // Microsoft.AspNetCore.Http.HttpContextAccessor fac =(Microsoft.AspNetCore.Http.HttpContextAccessor)factory;
                Microsoft.AspNetCore.Http.HttpContext context = ((Microsoft.AspNetCore.Http.HttpContextAccessor)factory).HttpContext;
                // context.Response.WriteAsync("Test");

                return context;

    } // End Class HttpContext 


Now in Configure, where you added the IServiceProvider svp, save this service provider into the static variable "ServiceProvider" in the just created dummy class System.Web.HttpContext (System.Web.HttpContext.ServiceProvider)

and set HostingEnvironment.IsHosted to true

System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

this is essentially what System.Web did, just that you never saw it (I guess the variable was declared as internal instead of public).

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)

    ServiceProvider = svp;
    System.Web.HttpContext.ServiceProvider = svp;
    System.Web.Hosting.HostingEnvironment.m_IsHosted = true;

    app.UseCookieAuthentication(new CookieAuthenticationOptions()
        AuthenticationScheme = "MyCookieMiddlewareInstance",
        LoginPath = new Microsoft.AspNetCore.Http.PathString("/Account/Unauthorized/"),
        AccessDeniedPath = new Microsoft.AspNetCore.Http.PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        CookieSecure = Microsoft.AspNetCore.Http.CookieSecurePolicy.SameAsRequest

       , CookieHttpOnly=false


Like in ASP.NET Web-Forms, you'll get a NullReference when you're trying to access a HttpContext when there is none, such as it used to be in Application_Start in global.asax.

I stress again, this only works if you actually added

services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();

like I wrote you should.
Welcome to the ServiceLocator pattern within the DI pattern ;)
For risks and side effects, ask your resident doctor or pharmacist - or study the sources of .NET Core at, and do some testing.

Perhaps a more maintainable method would be adding this helper class

namespace System.Web

    public static class HttpContext
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;

        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
            m_httpContextAccessor = httpContextAccessor;

        public static Microsoft.AspNetCore.Http.HttpContext Current
                return m_httpContextAccessor.HttpContext;



And then calling HttpContext.Configure in Startup->Configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider svp)


formGroup expects a FormGroup instance

There are a few issues in your code

  • <div [formGroup]="form"> outside of a <form> tag
  • <form [formGroup]="form"> but the name of the property containing the FormGroup is loginForm therefore it should be <form [formGroup]="loginForm">
  • [formControlName]="dob" which passes the value of the property dob which doesn't exist. What you need is to pass the string dob like [formControlName]="'dob'" or simpler formControlName="dob"

Plunker example

Setting selected option in laravel form

Try this

<select class="form-control" name="country_code" value="{{ old('country_code') }}">
   @foreach (\App\SystemCountry::orderBy('country')->get() as $country)
       <option value="{{ $country->country_code }}"
           @if ($country->country_code == "LKA")
          {{ $country->country }}

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.


How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

The term "Add-Migration" is not recognized

I think the answer needs updating in 2017, as MS have made some (breaking) changes that is detailed here.

To summarise, you will now need a reference to EntityFrameWorkCore.Tools.DotNet in the Tools Section as below

"Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0"

I have also posted a working project.json file below in case some one runs in problems.

  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.Extensions.Configuration.Json": "1.0.1",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"

  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.0.0"

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true

  "publishOptions": {
    "include": [

  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]

What's the difference between .NET Core, .NET Framework, and Xamarin?

Xamarin is used for phone applications (both IOS/Android). The .NET Core is used for designing Web applications that can work on both Apache and IIS.

That is the difference in two sentences.

How to install and run Typescript locally in npm?

As of npm 5.2.0, once you've installed locally via

npm i typescript --save-dev no longer need an entry in the scripts section of package.json -- you can now run the compiler with npx:

npx tsc

Now you don't have to update your package.json file every time you want to compile with different arguments.

SyntaxError: Unexpected token function - Async Await Nodejs

include and specify the node engine version to the latest, say at this time I did add version 8.

  "name": "functions",
  "dependencies": {
    "firebase-admin": "~7.3.0",
    "firebase-functions": "^2.2.1",
  "engines": {
    "node": "8"
  "private": true

in the following file


.NET Core vs Mono

You have chosen not only a realistic path, but arguably one of the best ecosystems strongly backed(also X-platforms) by MS. Still you should consider following points:

  • Update: Main doc about .Net platform standard is here:
  • Update: Current Mono 4.4.1 cannot run latest Asp.Net core 1.0 RTM
  • Although mono is more feature complete, its future is unclear, because MS owns it for some months now and its a duplicate work for them to support it. But MS is definitely committed to .Net Core and betting big on it.
  • Although .Net core is released, the 3rd party ecosystem is not quite there. For example Nhibernate, Umbraco etc cannot run over .Net core yet. But they have a plan.
  • There are some features missing in .Net Core like System.Drawing, you should look for 3rd party libraries
  • You should use nginx as front server with kestrelserver for apps, because kestrelserver is not quite ready for production. For example HTTP/2 is not implemented.

I hope it helps

Extract Month and Year From Date in R

The data.table package introduced the IDate class some time ago and zoo-package-like functions to retrieve months, days, etc (Check ?IDate). so, you can extract the desired info now in the following ways:

df <- data.frame(id = 1:3,
                 date = c("2004-02-06" , "2006-03-14" , "2007-07-16"))
df[ , date := as.IDate(date) ] # instead of as.Date()
df[ , yrmn := paste0(year(date), '-', month(date)) ]
df[ , yrmn2 := format(date, '%Y-%m') ]

How to return a specific status code and no contents from Controller?

Look at how the current Object Results are created. Here is the BadRequestObjectResult. Just an extension of the ObjectResult with a value and StatusCode.

I created a TimeoutExceptionObjectResult just the same way for 408.

/// <summary>
/// An <see cref="ObjectResult"/> that when executed will produce a Request Timeout (408) response.
/// </summary>
public class TimeoutExceptionObjectResult : ObjectResult
    private const int DefaultStatusCode = StatusCodes.Status408RequestTimeout;

    /// <summary>
    /// Creates a new <see cref="TimeoutExceptionObjectResult"/> instance.
    /// </summary>
    /// <param name="error">Contains the errors to be returned to the client.</param>
    public TimeoutExceptionObjectResult(object error)
        : base(error)
        StatusCode = DefaultStatusCode;


if (ex is TimeoutException)
    return new TimeoutExceptionObjectResult("The request timed out.");

How to configure Spring Security to allow Swagger URL to be accessed without authentication

For those who using a newer swagger 3 version org.springdoc:springdoc-openapi-ui

public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/v3/api-docs/**", "/swagger-ui.html", "/swagger-ui/**");

Adb install failure: INSTALL_CANCELED_BY_USER

Its a Xiaomi's issue If possible update MIUI to latest version then go to Settings > Additional Settings > Developer Options > Developer options: Check the Install via USB option.

This solved my issue hope it will also solve yours good luck!

JavaScript Array splice vs slice

splice() changes the original array whereas slice() doesn't but both of them returns array object.

See the examples below:

var array=[1,2,3,4,5];

This will return [3,4,5]. The original array is affected resulting in array being [1,2].

var array=[1,2,3,4,5]

This will return [3,4,5]. The original array is NOT affected with resulting in array being [1,2,3,4,5].

Below is simple fiddle which confirms this:

var array=[1,2,3,4,5];_x000D_
var array2=[1,2,3,4,5]_x000D_

Send push to Android by C# using FCM (Firebase Cloud Messaging)

I write this code and It's worked for me .

public static string ExcutePushNotification(string title, string msg, string fcmToken, object data) 

        var serverKey = "AAAA*******************";
        var senderId = "3333333333333";

        var result = "-1";

        var httpWebRequest = (HttpWebRequest)WebRequest.Create("");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Headers.Add(string.Format("Authorization: key={0}", serverKey));
        httpWebRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
        httpWebRequest.Method = "POST";

        var payload = new
            notification = new
                title = title,
                body = msg,
                sound = "default"

            data = new
                info = data
            to = fcmToken,
            priority = "high",
            content_available = true,


        var serializer = new JavaScriptSerializer();

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            string json = serializer.Serialize(payload);

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            result = streamReader.ReadToEnd();
        return result;

React.js, wait for setState to finish before triggering a function?

setState takes new state and optional callback function which is called after the state has been updated.

  {newState: 'whatever'},
  () => {/*do something after the state has been updated*/}

git status (nothing to commit, working directory clean), however with changes commited

Delete your .git folder, and reinitialize the git with git init, in my case that's work , because git add command staging the folder and the files in .git folder, if you close CLI after the commit , there will be double folder in staging area that make git system throw this issue.

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

To fix this problem on specific page need to set some validation settings when page loading. Write code below in Page_Load() method:

protected void Page_Load(object sender, EventArgs e)
        ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;

Its work for me in .NET 4.5

CSS3 100vh not constant in mobile browser

The following code solved the problem (with jQuery).

var vhHeight = $("body").height();
var chromeNavbarHeight = vhHeight - window.innerHeight;
$('body').css({ height: window.innerHeight, marginTop: chromeNavbarHeight });

And the other elements use % as a unit to replace vh.

How to return history of validation loss in Keras

The dictionary with histories of "acc", "loss", etc. is available and saved in hist.history variable.

Extract Data from PDF and Add to Worksheet

You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)

Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)

Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):

Function getTextFromPDF(ByVal strFilename As String) As String
   Dim objAVDoc As New AcroAVDoc
   Dim objPDDoc As New AcroPDDoc
   Dim objPage As AcroPDPage
   Dim objSelection As AcroPDTextSelect
   Dim objHighlight As AcroHiliteList
   Dim pageNum As Long
   Dim strText As String

   strText = ""
   If (objAvDoc.Open(strFilename, "") Then
      Set objPDDoc = objAVDoc.GetPDDoc
      For pageNum = 0 To objPDDoc.GetNumPages() - 1
         Set objPage = objPDDoc.AcquirePage(pageNum)
         Set objHighlight = New AcroHiliteList
         objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
         Set objSelection = objPage.CreatePageHilite(objHighlight)

         If Not objSelection Is Nothing Then
            For tCount = 0 To objSelection.GetNumText - 1
               strText = strText & objSelection.GetText(tCount)
            Next tCount
         End If
      Next pageNum
      objAVDoc.Close 1
   End If

   getTextFromPDF = strText

End Function

What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.

Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.

Hope that helps!

How to fix Error: this class is not key value coding-compliant for the key tableView.'

Any chance that you changed the name of your table view from "tableView" to "myTableView" at some point?

Failed to find 'ANDROID_HOME' environment variable

In Windows, If you are running this command from VS code terminal and Even after setting up all the environment variable (, platform-tools, tools) it is not working trying running the same command from external cmd terminal. In my case even after starting a new VS code terminal, it was not able to take the updated Environment path.

It worked when I ran the same command from Windows cmd.

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

I had same problem and eventually found out that in file build.gradle the version does not match the version of buildTools in my installed sdk. (because I imported project done at home on different computed with updated sdk)


  • build.gradle(app): buildToolsVersion "24.0.2"

  • Android\sdk\build-tools: file "25.0.1"

fixed: build.gradle(app): buildToolsVersion "25.0.1"

Then just sync your project with gradle files and it should work.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

I've updated jdk to 1.8.0_74, Android-studio to 2.1 preview 1 and add to Application file

protected void attachBaseContext(Context base) {

Call to a member function fetch_assoc() on boolean in <path>

Please use if condition with while loop and try.


if ($result = $conn->query($query)) {

    /* fetch associative array */
    while ($row = $result->fetch_assoc()) {

    /* free result set */

How can I display a modal dialog in Redux that performs asynchronous actions?

Wrap the modal into a connected container and perform the async operation in here. This way you can reach both the dispatch to trigger actions and the onClose prop too. To reach dispatch from props, do not pass mapDispatchToProps function to connect.

class ModalContainer extends React.Component {
  handleDelete = () => {
    const { dispatch, onClose } = this.props;
    dispatch({type: 'DELETE_POST'});

    someAsyncOperation().then(() => {
      dispatch({type: 'DELETE_POST_SUCCESS'});

  render() {
    const { onClose } = this.props;
    return <Modal onClose={onClose} onSubmit={this.handleDelete} />

export default connect(/* no map dispatch to props here! */)(ModalContainer);

The App where the modal is rendered and its visibility state is set:

class App extends React.Component {
  state = {
    isModalOpen: false

  handleModalClose = () => this.setState({ isModalOpen: false });


    return (
      <ModalContainer onClose={this.handleModalClose} />  


How to implement the Softmax function in Python

Everybody seems to post their solution so I'll post mine:

def softmax(x):
    e_x = np.exp(x.T - np.max(x, axis = -1))
    return (e_x / e_x.sum(axis=0)).T

I get the exact same results as the imported from sklearn:

from sklearn.utils.extmath import softmax

TokenMismatchException in VerifyCsrfToken.php Line 67

I have also faced the same issue and solved it later. first of all execute the artisan command:

php artisan cache:clear

And after that restart the project. Hope it will help.

Can I use an HTML input type "date" to collect only a year?

No, you can't, it doesn't support only year, so to do that you need a script, like jQuery or the webshim link you have, which shows year only.

If jQuery would be an option, here is one, borrowed from Sibu:


$(function() {
    $( "#datepicker" ).datepicker({dateFormat: 'yy'});


.ui-datepicker-calendar {
   display: none;


Src fiddle:

Here is an updated fiddle, without the month and prev/next buttons

If bootstrap is an option, check this link, they have a layout how you want.

Why do we need middleware for async flow in Redux?

Abramov's goal - and everyone's ideally - is simply to encapsulate complexity (and async calls) in the place where it's most appropriate.

Where's the best place to do that in the standard Redux dataflow? How about:

  • Reducers? No way. They should be pure functions with no side-effects. Updating the store is serious, complicated business. Don't contaminate it.
  • Dumb View Components? Definitely No. They have one concern: presentation and user-interaction, and should be as simple as possible.
  • Container Components? Possible, but sub-optimal. It makes sense in that the container is a place where we encapsulate some view related complexity and interact with the store, but:
    • Containers do need to be more complex than dumb components, but it's still a single responsibility: providing bindings between view and state/store. Your async logic is a whole separate concern from that.
    • By placing it in a container, you'd be locking your async logic into a single context, for a single view/route. Bad idea. Ideally it's all reusable, and totally decoupled.
  • Some other Service Module? Bad idea: you'd need to inject access to the store, which is a maintainability/testability nightmare. Better to go with the grain of Redux and access the store only using the APIs/models provided.
  • Actions and the Middlewares that interpret them? Why not?! For starters, it's the only major option we have left. :-) More logically, the action system is decoupled execution logic that you can use from anywhere. It's got access to the store and can dispatch more actions. It has a single responsibility which is to organize the flow of control and data around the application, and most async fits right into that.
    • What about the Action Creators? Why not just do async in there, instead of in the actions themselves, and in Middleware?
      • First and most important, the creators don't have access to the store, as middleware does. That means you can't dispatch new contingent actions, can't read from the store to compose your async, etc.
      • So, keep complexity in a place that's complex of necessity, and keep everything else simple. The creators can then be simple, relatively pure functions that are easy to test.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

I was getting the same error when I tried to do :

cordova build ios

except mine said ** ARCHIVE FAILED ** rather than ** BUILD FAILED **.

I fixed it by opening the projectName.xcodeproj file in Xcode and then adjusting these 2 settings :

  1. In Targets > General > Signing ensure you have selected a Team

enter image description here

  1. In Targets > Build Settings > (search for "bitcode") set Enable Bitcode to "Yes"

enter image description here

Then I quit out of Xcode and reran cordova build ios and it worked.

TLS 1.2 in .NET Framework 4.0

The only way I have found to change this is directly on the code :

at the very beginning of your app you set

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

you should include the class

I did this before calling a web service because we had to block tls1 too.

Where can I read the Console output in Visual Studio 2015

My problem was that I needed to Reset Window Layout.

Reset Window Layout

How to build and use Google TensorFlow C++ api

answers above are good enough to show how to build the library, but how to collect the headers are still tricky. here I share the little script I use to copy the necessary headers.

SOURCE is the first param, which is the tensorflow source(build) direcoty;
DST is the second param, which is the include directory holds the collected headers. (eg. in cmake, include_directories(./collected_headers_here)).


echo "-- target dir is $DST"
echo "-- source dir is $SOURCE"

if [[ -e $DST ]];then
    echo "clean $DST"
    rm -rf $DST
    mkdir $DST

# 1. copy the source code c++ api needs
mkdir -p $DST/tensorflow
cp -r $SOURCE/tensorflow/core $DST/tensorflow
cp -r $SOURCE/tensorflow/cc $DST/tensorflow
cp -r $SOURCE/tensorflow/c $DST/tensorflow

# 2. copy the generated code, put them back to
# the right directories along side the source code
if [[ -e $SOURCE/bazel-genfiles/tensorflow ]];then
    from=$(expr $(echo -n $prefix | wc -m) + 1)

    # eg. compiled protobuf files
    find $SOURCE/bazel-genfiles/tensorflow -type f | while read line;do
        #echo "procese file --> $line"
        line_len=$(echo -n $line | wc -m)
        filename=$(echo $line | rev | cut -d'/' -f1 | rev )
        filename_len=$(echo -n $filename | wc -m)
        to=$(expr $line_len - $filename_len)

        target_dir=$(echo $line | cut -c$from-$to)
        #echo "[$filename] copy $line $DST/tensorflow/$target_dir"
        cp $line $DST/tensorflow/$target_dir

# 3. copy third party files. Why?
# In the tf source code, you can see #include "third_party/...", so you need it
cp -r $SOURCE/third_party $DST

# 4. these headers are enough for me now.
# if your compiler complains missing headers, maybe you can find it in bazel-tensorflow/external
cp -RLf $SOURCE/bazel-tensorflow/external/eigen_archive/Eigen $DST
cp -RLf $SOURCE/bazel-tensorflow/external/eigen_archive/unsupported $DST
cp -RLf $SOURCE/bazel-tensorflow/external/protobuf_archive/src/google $DST
cp -RLf $SOURCE/bazel-tensorflow/external/com_google_absl/absl $DST

There is no argument given that corresponds to the required formal parameter - .NET Error

I got the same error but it was due to me not creating a default constructor. If you haven't already tried that, create the default constructor like this:

public TestClass() {


Close Bootstrap modal on form submit

I am using rails and ajax too and I had the same problem. just run this code


that worked for me but I am trying to also fix it without using jQuery.

failed to find target with hash string android-23

Nothing worked for me. I changed SDK path to new SDK location and reinstalled SDK.Its working perfectly.

Convert pandas data frame to series

It's not smart enough to realize it's still a "vector" in math terms.

Say rather that it's smart enough to recognize a difference in dimensionality. :-)

I think the simplest thing you can do is select that row positionally using iloc, which gives you a Series with the columns as the new index and the values as the values:

>>> df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
>>> df
   a0  a1  a2  a3  a4
0   0   1   2   3   4
>>> df.iloc[0]
a0    0
a1    1
a2    2
a3    3
a4    4
Name: 0, dtype: int64
>>> type(_)
<class 'pandas.core.series.Series'>

Best way to get the max value in a Spark dataframe column

I believe the best solution will be using head()

Considering your example:

|  A|  B|

Using agg and max method of python we can get the value as following :

from pyspark.sql.functions import max df.agg(max(df.A)).head()[0]

This will return: 3.0

Make sure you have the correct import:
from pyspark.sql.functions import max The max function we use here is the pySPark sql library function, not the default max function of python.

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

Python pandas: how to specify data types when reading an Excel file?

You just specify converters. I created an excel spreadsheet of the following structure:

names   ages
bob     05
tom     4
suzy    3

Where the "ages" column is formatted as strings. To load:

import pandas as pd

df = pd.read_excel('Book1.xlsx',sheetname='Sheet1',header=0,converters={'names':str,'ages':str})
>>> df
       names ages
   0   bob   05
   1   tom   4
   2   suzy  3

Best way to verify string is empty or null

Simply and clearly:

if (str == null || str.trim().length() == 0) {
    // str is empty

Ionic android build Error - Failed to find 'ANDROID_HOME' environment variable

To add ANDROID_HOME value permanently,

gedit ~/.bashrc

and add the following lines

export ANDROID_HOME=/root/Android/Sdk

Save the file and you need not update ANDROID_HOME value everytime.

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

This was asked on the www-style list, and Tab Atkins (spec editor) provided an answer explaining why. I'll elaborate on that a bit here.

To start out, let's initially assume our flex container is single-line (flex-wrap: nowrap). In this case, there's clearly an alignment difference between the main axis and the cross axis -- there are multiple items stacked in the main axis, but only one item stacked in the cross axis. So it makes sense to have a customizeable-per-item "align-self" in the cross axis (since each item is aligned separately, on its own), whereas it doesn't make sense in the main axis (since there, the items are aligned collectively).

For multi-line flexbox, the same logic applies to each "flex line". In a given line, items are aligned individually in the cross axis (since there's only one item per line, in the cross axis), vs. collectively in the main axis.

Here's another way of phrasing it: so, all of the *-self and *-content properties are about how to distribute extra space around things. But the key difference is that the *-self versions are for cases where there's only a single thing in that axis, and the *-content versions are for when there are potentially many things in that axis. The one-thing vs. many-things scenarios are different types of problems, and so they have different types of options available -- for example, the space-around / space-between values make sense for *-content, but not for *-self.

SO: In a flexbox's main axis, there are many things to distribute space around. So a *-content property makes sense there, but not a *-self property.

In contrast, in the cross axis, we have both a *-self and a *-content property. One determines how we'll distribute space around the many flex lines (align-content), whereas the other (align-self) determines how to distribute space around individual flex items in the cross axis, within a given flex line.

(I'm ignoring *-items properties here, since they simply establish defaults for *-self.)

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

This error means that file was not found. Either path is wrong or file is not present where you want it to be. Try to access it by entering source address in your browser to check if it really is there. Browse the directories on server to ensure the path is correct. You may even copy and paste the relative path to be certain it is alright.

Unable to Install Any Package in Visual Studio 2015

Just to help out anyone who has landed on this page after updating VS2015 to update 2 and trying to manage packages on a website, receiving the "NuGet configuration file is invalid" error, this is a known and acknowledged issue:

I got mine working again by installing package manager 3.4.4 (beta) from

They do also state update 3 for Visual Studio will also contain a fix

The target principal name is incorrect. Cannot generate SSPI context

I had this issue when I changed SQL Server service user. When it happened on a main instance, following point 1 and two below fixed the problem, due to SPN not being updated.

I also had this issue when I changed a named instance service user. This new user was a domain account already in use by the main instance. I am not aware of what went wrong, but I fixed it this way:

  1. I followed the above advice (see previous threads) to run the Microsoft® Kerberos Configuration Manager for SQL Server®
  2. The tool discovered some issues and fixed them for me
  3. The tool suggested that dynamic ports enabled on the named instance were not a good idea and I therefore ran my sql server configuration manager and:
  4. configured the named instance to use a static port (number is not important as long as it's available). Path to configuration: Protocols for named instance, right click on the TCP/IP, properties, IP Addresses, clear all TCP dynamic ports content, set the port number of your choice to all TCP port properties.
  5. Created an alias: sql native client configuration -> aliases -> new alias. The server is your database server name, the port is the one mentioned above, the alias name I chose was the same as the instance name without the server name (eg server1\sqlsrv2017: server = server1, alias = sqlsrv2017)
  6. Restarted the instance service, as promped

Needless to say the the port must be cleared using the firewall, if this is enabled

Reading json files in C++

You can use c++ boost::property_tree::ptree for parsing json data. here is the example for your json data. this would be more easy if you shift name inside each child nodes

#include <iostream>                                                             
#include <string>                                                               
#include <tuple>                                                                

#include <boost/property_tree/ptree.hpp>                                        
#include <boost/property_tree/json_parser.hpp> 
 int main () {

    namespace pt = boost::property_tree;                                        
    pt::ptree loadPtreeRoot;                                                    

    pt::read_json("example.json", loadPtreeRoot);                               
    std::vector<std::tuple<std::string, std::string, std::string>> people;      

    pt::ptree temp ;                                                            
    pt::ptree tage ;                                                            
    pt::ptree tprofession ;                                                     

    std::string age ;                                                           
    std::string profession ;                                                    
    //Get first child                                                           
    temp = loadPtreeRoot.get_child("Anna");                                     
    tage = temp.get_child("age");                                               
    tprofession = temp.get_child("profession");                                 

    age =  tage.get_value<std::string>();                                       
    profession =  tprofession.get_value<std::string>();                         
    std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
    //push tuple to vector                                                      
    people.push_back(std::make_tuple("Anna", age, profession));                 

    //Get Second child                                                          
    temp = loadPtreeRoot.get_child("Ben");                                      
    tage = temp.get_child("age");                                               
    tprofession = temp.get_child("profession");                                 

    age =  tage.get_value<std::string>();                                       
    profession  =  tprofession.get_value<std::string>();                        
    std::cout << "age: " << age << "\n" << "profession :" << profession << "\n" ;
    //push tuple to vector                                                      
    people.push_back(std::make_tuple("Ben", age, profession));                  

    for (const auto& tmppeople: people) {                                       
        std::cout << "Child[" << std::get<0>(tmppeople) << "] = " << "  age : " 
        << std::get<1>(tmppeople) << "\n    profession : " << std::get<2>(tmppeople) << "\n";

pip install failing with: OSError: [Errno 13] Permission denied on directory

Option a) Create a virtualenv, activate it and install:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

Option b) Install in your homedir:

pip install --user -r requirements.txt

My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.

TypeError: $(...).DataTable is not a function

In my case the solution was to delete cookies from the browser.

ionic build Android | error: No installed build tools found. Please install the Android build tools

For me, the problem was that ANDROID_HOME was pointing to an old Android SDK path. After installing Android Studio, I had to update ~/.bash_profile accordingly for MAC (El Capitan)

export ANDROID_HOME="/Users/corneliusparkin/Library/Android/sdk"

Remember to re-start terminal or run this command after updating ~/.bash_profile

source ~/.bash_profile

Microsoft.ReportViewer.Common Version=

I was getting this error after deploying on IIS Server PC.

  1. First Install Microsoft SQL Server 2014 Feature Pack link description here

  1. Install Microsoft Report Viewer 2015 Runtime redistributable package

It may require restart your computer.

Cordova - Error code 1 for command | Command failed for

Delete platforms/android folder and try to rebuild. That helped me a lot.

(Visual Studio Tools for Apache Cordova)

Impact of Xcode build options "Enable bitcode" Yes/No

Bitcode is a new feature of iOS 9

Bitcode is an intermediate representation of a compiled program. Apps you upload to iTunes Connect that contain bitcode will be compiled and linked on the App Store. Including bitcode will allow Apple to re-optimize your app binary in the future without the need to submit a new version of your app to the store.

Note: For iOS apps, bitcode is the default, but optional. If you provide bitcode, all apps and frameworks in the app bundle need to include bitcode. For watchOS apps, bitcode is required

So you should disabled bitcode until all the frameworks of your app have bitcode enabled.

Why calling react setState method doesn't mutate the state immediately?

You could try using ES7 async/await. For instance using your example:

handleChange: async function(event) {
    await this.setState({value:});

Laravel-5 'LIKE' equivalent (Eloquent)

$data = DB::table('borrowers')
        ->join('loans', '', '=', 'loans.borrower_id')
        ->select('borrowers.*', 'loans.*')   
        ->where('loan_officers', 'like', '%' . $officerId . '%')
        ->where('loans.maturity_date', '<', date("Y-m-d"))

Simple InputBox function

It would be something like this

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript" 
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
$_userInput = $inputObject.eval("getInput") 

return $_userInput

Then you can call the function similar to this.

$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null ) 
 echo "Input was [$userInput]"
 echo "User cancelled the form!"

This is the most simple way to do this that I can think of.

Shift elements in a numpy array

You can convert ndarray to Series or DataFrame with pandas first, then you can use shift method as you want.


In [1]: from pandas import Series

In [2]: data = np.arange(10)

In [3]: data
Out[3]: array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

In [4]: data = Series(data)

In [5]: data
0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int64

In [6]: data = data.shift(3)

In [7]: data
0    NaN
1    NaN
2    NaN
3    0.0
4    1.0
5    2.0
6    3.0
7    4.0
8    5.0
9    6.0
dtype: float64

In [8]: data = data.values

In [9]: data
Out[9]: array([ nan,  nan,  nan,   0.,   1.,   2.,   3.,   4.,   5.,   6.])

How to display Woocommerce product price by ID number on a custom page?

In woocommerce,

Get regular price :

$price = get_post_meta( get_the_ID(), '_regular_price', true);
// $price will return regular price

Get sale price:

$sale = get_post_meta( get_the_ID(), '_sale_price', true);
// $sale will return sale price

Base table or view not found: 1146 Table Laravel 5

When you are passing the custom request in the controller method, and your request file doesn't follow the proper syntax or table name is changed, then laravel through this type of exception. I'll show you in Example.

My Request code.
     public function rules()
            return [
                'name' => 'required|unique:posts|max:50',
                'description' => 'required',

But my table name is todos not posts so that's why it through "Base table or view not found: 1146 Table Laravel 7

    I forgot to change the table name in first index.
     public function rules()
            return [
                'name' => 'required|unique:todos|max:50',
                'description' => 'required',

Converting Array to List

If you are dealing with String[] instead of int[], We can use

ArrayList<String> list = new ArrayList<>();

Using lodash to compare jagged arrays (items existence without order)

There are already answers here, but here's my pure JS implementation. I'm not sure if it's optimal, but it sure is transparent, readable, and simple.

// Does array a contain elements of array b?
const contains = (a, b) => new Set([...a, ...b]).size === a.length
const isEqualSet = (a, b) => contains(a, b) && contains(b, a)

The rationale in contains() is that if a does contain all the elements of b, then putting them into the same set would not change the size.

For example, if const a = [1,2,3,4] and const b = [1,2], then new Set([...a, ...b]) === {1,2,3,4}. As you can see, the resulting set has the same elements as a.

From there, to make it more concise, we can boil it down to the following:

const isEqualSet = (a, b) => {
  const unionSize = new Set([...a, ...b])
  return unionSize === a.length && unionSize === b.length
} SSL handshake aborted: Failure in SSL library, usually a protocol error

It was reproducible only when I use proxy on genymotion(<4.4).

Check your proxy settings in Settings-> Wireless & Networks-> WiFi->(Long Press WiredSSID)-> Modify Network

Select show advanced options: set Proxy settings to NONE.

command/usr/bin/codesign failed with exit code 1- code sign error

I had the same error on January 2018 with xcode 8.2.1

Before I try to open xcode I couldn't because the system was updating. I tried sometime later and it let me working on it, and then I got the same error.

I followed most of the solutions described in this article but they didn't work for me.

Then I remembered the message about the system updating and I tried to reboot the machine.

And that did the magic. It worked for me.

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.

You can indeed use filters inside a boolean query.

How do I use a delimiter with Scanner.useDelimiter in Java?

With Scanner the default delimiters are the whitespace characters.

But Scanner can define where a token starts and ends based on a set of delimiter, wich could be specified in two ways:

  1. Using the Scanner method: useDelimiter(String pattern)
  2. Using the Scanner method : useDelimiter(Pattern pattern) where Pattern is a regular expression that specifies the delimiter set.

So useDelimiter() methods are used to tokenize the Scanner input, and behave like StringTokenizer class, take a look at these tutorials for further information:

And here is an Example:

public static void main(String[] args) {

    // Initialize Scanner object
    Scanner scan = new Scanner("Anna Mills/Female/18");
    // initialize the string delimiter
    // Printing the tokenized Strings
    // closing the scanner stream

Prints this output:

Anna Mills

Programmatically go back to previous ViewController in Swift

Try this: for the previous view use this:

navigationController?.popViewController(animated: true)  

pop to root use this code:

navigationController?.popToRootViewController(animated: true) 

java.lang.IllegalStateException: Fragment not attached to Activity

This issue occurs whenever you call a context which is unavailable or null when you call it. This can be a situation when you are calling main activity thread's context on a background thread or background thread's context on main activity thread.

For instance , I updated my shared preference string like following.


And called finish() right after it. Now what it does is that as commit runs on main thread and stops any other Async commits if coming until it finishes. So its context is alive until the write is completed. Hence previous context is live , causing the error to occur.

So make sure to have your code rechecked if there is some code having this context issue.

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

lets keep it short :

CI: A software development practice where members of a team integrate their work at least daily. Each integration is verified by automated build (include tests)to detect error as quick as possible. CD: CD Builds on CI, where you build software in such a way that the software can be released to production at any time.

Android Recyclerview vs ListView with Viewholder

RecyclerView was created as a ListView improvement, so yes, you can create an attached list with ListView control, but using RecyclerView is easier as it:

  1. Reuses cells while scrolling up/down : this is possible with implementing View Holder in the ListView adapter, but it was an optional thing, while in the RecycleView it's the default way of writing adapter.

  2. Decouples list from its container : so you can put list items easily at run time in the different containers (linearLayout, gridLayout) with setting LayoutManager.

mRecyclerView = (RecyclerView) findViewById(; mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));

  1. Animates common list actions : Animations are decoupled and delegated to ItemAnimator. There is more about RecyclerView, but I think these points are the main ones.

So, to conclude, RecyclerView is a more flexible control for handling "list data" that follows patterns of delegation of concerns and leaves for itself only one task - recycling items.

Setting onSubmit in React.js

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
        render: function() {
        doSomething = function(event){
           alert('it works!');

        return <form onSubmit={this.doSomething}>
        <button>Click me</button>

Wi-Fi Direct and iOS Support

According to this thread:

The peer-to-peer Wi-Fi implemented by iOS (and recent versions of OS X) is not compatible with Wi-Fi Direct. Note Just as an aside, you can access peer-to-peer Wi-Fi without using Multipeer Connectivity. The underlying technology is Bonjour + TCP/IP, and you can access that directly from your app. The WiTap sample code shows how.

Materialize CSS - Select Doesn't Seem to Render

If you're using Angularjs, you can use the angular-materialize plugin, which provides some handy directives. Then you don't need to initialize in the js, just add material-select to your select:

<div input-field>
    <select class="" ng-model="select.value1" material-select>
        <option ng-repeat="value in select.choices">{{value}}</option>

Class file has wrong version 52.0, should be 50.0

Have got the same error as in header because of failed attempt to compile my project with java 8 and then reattempting to compile with java 6. Some classes where compiled at the first attempt with 8 and did not recompile with 6. Mixed classes did not compile then. Cleaning project solved the problem. This answer is not strictly relevant to the question, but could be useful for someone.

Use Excel VBA to click on a button in Internet Explorer, when the button has no "name" associated


EDIT: to loop through the collection (items should appear in the same order as they are in the source document)

Dim links, link 

Set links = IE.Document.getElementById("dgTime").getElementsByTagName("a")

'For Each loop
For Each link in links
Next link

'For Next loop
Dim n, i
n = links.length
For i = 0 to n-1 Step 2
Next I

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

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
        "platform": "iphone"
        "platform": "ipad"
        "platform": "android_phone"
        "platform": "android_tablet"

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;

public void setPlatforms(List platforms){
    this.platforms = platforms;

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;

jQuery has deprecated synchronous XMLHTTPRequest

It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:

When you update the content of an element with new html using jQuery/javascript, and this new html contains <script> tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.

You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR in the console window. (firefox).

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Change to root build.gradle file


// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
    dependencies {
        classpath ''

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files

allprojects {
    repositories {

task clean(type: Delete) {
    delete rootProject.buildDir

NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference

This issue is due to ArrayList variable not being instantiated. Need to declare "recordings" variable like following, that should solve the issue;

ArrayList<String> recordings = new ArrayList<String>();

this calls default constructor and assigns empty string to the recordings variable so that it is not null anymore.

Eclipse: Java was started but returned error code=13

This error occurs because your Eclipse version is 64-bit. You should download and install 64-bit JRE and add the path to it in eclipse.ini. For example:

C:\Program Files\Java\jre1.8.0_45\bin\javaw.exe

Note: The -vm parameter should be just before -vmargs and the path should be on a separate line. It should be the full path to the javaw.exe file. Do not enclose the path in double quotes (").

If your Eclipse is 32-bit, install a 32-bit JRE and use the path to its javaw.exe file.

What is the difference between cache and persist?

The difference between cache and persist operations is purely syntactic. cache is a synonym of persist or persist(MEMORY_ONLY), i.e. cache is merely persist with the default storage level MEMORY_ONLY

But Persist() We can save the intermediate results in 5 storage levels.


/** * Persist this RDD with the default storage level (MEMORY_ONLY). */
def persist(): this.type = persist(StorageLevel.MEMORY_ONLY)

/** * Persist this RDD with the default storage level (MEMORY_ONLY). */
def cache(): this.type = persist()

see more details here...

Caching or persistence are optimization techniques for (iterative and interactive) Spark computations. They help saving interim partial results so they can be reused in subsequent stages. These interim results as RDDs are thus kept in memory (default) or more solid storage like disk and/or replicated. RDDs can be cached using cache operation. They can also be persisted using persist operation.

#persist, cache

These functions can be used to adjust the storage level of a RDD. When freeing up memory, Spark will use the storage level identifier to decide which partitions should be kept. The parameter less variants persist() and cache() are just abbreviations for persist(StorageLevel.MEMORY_ONLY).

Warning: Once the storage level has been changed, it cannot be changed again!

Warning -Cache judiciously... see ((Why) do we need to call cache or persist on a RDD)

Just because you can cache a RDD in memory doesn’t mean you should blindly do so. Depending on how many times the dataset is accessed and the amount of work involved in doing so, recomputation can be faster than the price paid by the increased memory pressure.

It should go without saying that if you only read a dataset once there is no point in caching it, it will actually make your job slower. The size of cached datasets can be seen from the Spark Shell..

Listing Variants...

def cache(): RDD[T]
 def persist(): RDD[T]
 def persist(newLevel: StorageLevel): RDD[T]

See below example :

val c = sc.parallelize(List("Gnu", "Cat", "Rat", "Dog", "Gnu", "Rat"), 2)
     res0: = StorageLevel(false, false, false, false, 1)
     res2: = StorageLevel(false, true, false, true, 1)

enter image here

Note : Due to the very small and purely syntactic difference between caching and persistence of RDDs the two terms are often used interchangeably.

See more visually here....

Persist in memory and disk:

enter image description here


Caching can improve the performance of your application to a great extent.

enter image description here

Javascript querySelector vs. getElementById

The functions getElementById and getElementsByClassName are very specific, while querySelector and querySelectorAll are more elaborate. My guess is that they will actually have a worse performance.

Also, you need to check for the support of each function in the browsers you are targetting. The newer it is, the higher probability of lack of support or the function being "buggy".

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

My app is running in .net 4.7.2. Simplest solution was to add this to the config:

    <httpRuntime targetFramework="4.7.2"/>

Jquery Ajax, return success/error from controller

When you return value from server to jQuery's Ajax call you can also use the below code to indicate a server error:

return StatusCode(500, "My error");


return StatusCode((int)HttpStatusCode.InternalServerError, "My error");


Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return Json(new { responseText = "my error" });

Codes other than Http Success codes (e.g. 200[OK]) will trigger the function in front of error: in client side (ajax).

you can have ajax call like:

        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
       success: function (response)  {
            console.log("Custom message : " + response.responseText);
        }, //Is Called when Status Code is 200[OK] or other Http success code
        error: function (jqXHR, textStatus, errorThrown)  {
            console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
        }, //Is Called when Status Code is 500[InternalServerError] or other Http Error code

Additionally you can handle different HTTP errors from jQuery side like:

        type: "POST",
        url: "/General/ContactRequestPartial",
        data: {
            HashId: id
        statusCode: {
            500: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);
            501: function (jqXHR, textStatus, errorThrown)  {
                console.log("Custom error : " + jqXHR.responseText + " Status: " + textStatus + " Http error:" + errorThrown);

statusCode: is useful when you want to call different functions for different status codes that you return from server.

You can see list of different Http Status codes here:Wikipedia

Additional resources:

  1. Returning Server-Side Errors from AJAX Calls
  2. Returning a JsonResult within the Error function of JQuery Ajax
  3. Handling Ajax errors with jQuery

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
Next i

end sub

Command failed due to signal: Segmentation fault: 11

I actually screwed up Core Data entities a bit while porting from Swift 2.0 to 1.2 (don't ask why) I deleted all the entity classes and recreated them again. I got lots of error messages then and when I fixed them all the project built successfully.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

Download the latest "sdk platform" and "sdk build tools" of same version like 23.* for 
both from "sdk Managar".

(for reference see above hosted image from back track). Then right click on your project -> properties -> Android -> in "project build properties" select "API level" 23 or the latest one which you updated. Then clean your project once.

Note: But all three should be in same version.

How to create a signed APK file using Cordova command line interface?

For Windows, I've created a build.cmd file:

(replace the keystore path and alias)

For Cordova:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

And for Ionic:

@echo off 
set /P spassw="Store Password: " && set /P kpassw="Key Password: " && ionic build --prod && cordova build android --release -- --keystore=../../local/my.keystore --storePassword=%spassw% --alias=tmpalias --password=%kpassw%

Save it in the ptoject's directory, you can double click or open it with cmd.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

In my case, it was the UIAlertView on iPad: UIAlertController is Crashed (iPad). I didn't setup sourceView and sourceRect.

OperationalError, no such column. Django

If the error persists after doing what @Burhan Khalid said

Try this line: python migrate --run-syncdb

Validating Phone Numbers Using Javascript

As for your regexp I guess it should be

^\+{0,2}([\-\. ])?(\(?\d{0,3}\))?([\-\. ])?\(?\d{0,3}\)?([\-\. ])?\d{3}([\-\. ])?\d{4}

But in general the presumption is not correct because one might enter something like ++44 20 1234 56789 or +44 (0) 1234 567890 it is better to do something like this

var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {  return true;  }

this will assure that entered value has 7 to 10 figures nevertheless what the formatting is. But you have to think about max length for number might be more than 10 as in the sample above.

I have filtered my Excel data and now I want to number the rows. How do I do that?

I had the same problem. I'm no expert but this is the solution we used: Before you filter your data, first create a temporary column to populate your entire data set with your original sort order. Auto number the temporary "original sort order" column. Now filter your data. Copy and paste the filtered data into a new worksheet. This will move only the filtered data to the new sheet so that your row numbers will become consecutive. Now auto number your desired field. Go back to your original worksheet and delete the filtered rows. Copy and paste the newly numbered data from the secondary sheet onto the bottom of your original worksheet. Then clear your filter and sort the worksheet by the temporary "original sort order" column. This will put your newly numbered data back into its original order and you can then delete the temporary column.

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email: Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

Xamarin.Forms ListView: Set the highlight color of a tapped item

Found this lovely option using effects here.


[assembly: ResolutionGroupName("MyEffects")]
[assembly: ExportEffect(typeof(ListViewHighlightEffect), nameof(ListViewHighlightEffect))]
namespace Effects.iOS.Effects
    public class ListViewHighlightEffect : PlatformEffect
        protected override void OnAttached()
            var listView = (UIKit.UITableView)Control;

            listView.AllowsSelection = false;

        protected override void OnDetached()


[assembly: ResolutionGroupName("MyEffects")]
[assembly: ExportEffect(typeof(ListViewHighlightEffect), nameof(ListViewHighlightEffect))]
namespace Effects.Droid.Effects
    public class ListViewHighlightEffect : PlatformEffect
        protected override void OnAttached()
            var listView = (Android.Widget.ListView)Control;

            listView.ChoiceMode = ChoiceMode.None;

        protected override void OnDetached()



How to create a service running a .exe file on Windows 2012 Server?

You can use PowerShell.

New-Service -Name "TestService" -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"

Refer -

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

How to turn off INFO logging in Spark?

You can use setLogLevel

val spark = SparkSession
      .config("spark.master", "local[1]")


Insert picture/table in R Markdown

In March I made a deck presentation in slidify, Rmarkdown with impress.js which is a cool 3D framework. My index.Rmdheader looks like

title       : French TER (regional train) monthly regularity
subtitle    : since January 2013
author      : brigasnuncamais
job         : Business Intelligence / Data Scientist consultant
framework   : impressjs     # {io2012, html5slides, shower, dzslides, ...}
highlighter : highlight.js  # {highlight.js, prettify, highlight}
hitheme     : tomorrow      # 
widgets     : []            # {mathjax, quiz, bootstrap}
mode        : selfcontained # {standalone, draft}
knit        : slidify::knit2slides

subdirs are:

/assets /css    /impress-demo.css
        /fig    /unnamed-chunk-1-1.png (generated by included R code)
        /img    /SS850452.png (my image used as background)
        /js     /impress.js
        /layouts/custbg.html # content:--- layout: slide --- {{{ slide.html }}}
        /libraries  /frameworks /impressjs
                    /highlighters   /highlight.js

A slide with image in background code snippet would be in my .Rmd:

<div id="bg">
  <img src="assets/img/SS850452.png" alt="">

Some issues appeared since I last worked on it (photos are no more in background, text it too large on my R plot) but it works fine on my local. Troubles come when I run it on RPubs.

How do you switch pages in Xamarin.Forms?

One page to another page navigation in Xamarin.forms using Navigation property Below sample code

void addClicked(object sender, EventArgs e)
            //var createEmp = (Employee)BindingContext;
            Employee emp = new Employee();
            emp.Address = AddressEntry.Text;   
            this.Navigation.PushAsync(new EmployeeDetails());
  this.Navigation.PushModalAsync(new EmployeeDetails());

To navigate one page to another page with in view cell Below code Xamrian.forms

 private async void BtnEdit_Clicked1(object sender, EventArgs e)
            await App.Current.MainPage.Navigation.PushModalAsync(new EmployeeRegistration(empid));

Example like below

public class OptionsViewCell : ViewCell
        int empid;
        Button btnEdit;
        public OptionsViewCell()
        protected override void OnBindingContextChanged()

            if (this.BindingContext == null)

            dynamic obj = BindingContext;
            empid = Convert.ToInt32(obj.Eid);
            var lblname = new Label
                BackgroundColor = Color.Lime,
                Text = obj.Ename,

            var lblAddress = new Label
                BackgroundColor = Color.Yellow,
                Text = obj.Address,

            var lblphonenumber = new Label
                BackgroundColor = Color.Pink,
                Text = obj.phonenumber,

            var lblemail = new Label
                BackgroundColor = Color.Purple,
                Text =,

            var lbleid = new Label
                BackgroundColor = Color.Silver,
                Text = (empid).ToString(),

             //var lbleid = new Label
            //    BackgroundColor = Color.Silver,
            //    // HorizontalOptions = LayoutOptions.CenterAndExpand
            //lbleid.SetBinding(Label.TextProperty, "Eid");
            Button btnDelete = new Button
                BackgroundColor = Color.Gray,

                Text = "Delete",
                //WidthRequest = 15,
                //HeightRequest = 20,
                TextColor = Color.Red,
                HorizontalOptions = LayoutOptions.EndAndExpand,
            btnDelete.Clicked += BtnDelete_Clicked;
            //btnDelete.PropertyChanged += BtnDelete_PropertyChanged;  

            btnEdit = new Button
                BackgroundColor = Color.Gray,
                Text = "Edit",
                TextColor = Color.Green,
            // lbleid.SetBinding(Label.TextProperty, "Eid");
            btnEdit.Clicked += BtnEdit_Clicked1; ;
            //btnEdit.Clicked += async (s, e) =>{
            //    await App.Current.MainPage.Navigation.PushModalAsync(new EmployeeRegistration());

            View = new StackLayout()
                Orientation = StackOrientation.Horizontal,
                BackgroundColor = Color.White,
                Children = { lbleid, lblname, lblAddress, lblemail, lblphonenumber, btnDelete, btnEdit },


        private async void BtnEdit_Clicked1(object sender, EventArgs e)
            await App.Current.MainPage.Navigation.PushModalAsync(new EmployeeRegistration(empid));

        private void BtnDelete_Clicked(object sender, EventArgs e)
            // var eid = Convert.ToInt32(empid);
            // var item = (Xamarin.Forms.Button)sender;
            int eid = empid;


AngularJS - difference between pristine/dirty and touched/untouched

It's worth mentioning that the validation properties are different for forms and form elements (note that touched and untouched are for fields only):

Input fields have the following states:

$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

$pristine No fields have been modified yet
$dirty One or more have been modified
$invalid The form content is not valid
$valid The form content is valid
$submitted The form is submitted

They are all properties of the form, and are either true or false.

How to initialize to empty

IMO, you cannot create an empty Date(java.util). You can create a Date object with null value and can put a null check.

 Date date = new Date(); // Today's date and current time
 Date date2 = new Date(0); // Default date and time
 Date date3 = null; //Date object with null as value.
 if(null != date3) {
    // do your work.

S3 limit to objects in a bucket

There are no limits to the number of objects you can store in your S3 bucket. AWS claims it to have unlimited storage. However, there are some limitations -

  1. By default, customers can provision up to 100 buckets per AWS account. However, you can increase your Amazon S3 bucket limit by visiting AWS Service Limits.
  2. An object can be 0 bytes to 5TB.
  3. The largest object that can be uploaded in a single PUT is 5 gigabytes
  4. For objects larger than 100 megabytes, customers should consider using the Multipart Upload capability.

That being said if you really have a lot of objects to be stored in S3 bucket consider randomizing your object name prefix to improve performance.

When your workload is a mix of request types, introduce some randomness to key names by adding a hash string as a prefix to the key name. By introducing randomness to your key names the I/O load will be distributed across multiple index partitions. For example, you can compute an MD5 hash of the character sequence that you plan to assign as the key and add 3 or 4 characters from the hash as a prefix to the key name.

More details -

-- As of June 2018

How to unset (remove) a collection element after fetching it?

Laravel Collection implements the PHP ArrayAccess interface (which is why using foreach is possible in the first place).

If you have the key already you can just use PHP unset.

I prefer this, because it clearly modifies the collection in place, and is easy to remember.

foreach ($collection as $key => $value) {

Regex allow digits and a single dot

My try is combined solution.

string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;

First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.

Second line cleans numbers after dot.

How do I view 'git diff' output with my preferred diff tool/ viewer?

Since Git1.6.3, you can use the git difftool script: see my answer below.

May be this article will help you. Here are the best parts:

There are two different ways to specify an external diff tool.

The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:

path old-file old-hex old-mode new-file new-hex new-mode

As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.

The second method, which I prefer, is to configure the external diff tool via "git config". Here is what I did:

1) Create a wrapper script "" which contains something like


# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode

"<path_to_diff_executable>" "$2" "$5" | cat

As you can see, only the second ("old-file") and fifth ("new-file") arguments will be passed to the diff tool.

2) Type

$ git config --global diff.external <path_to_wrapper_script>

at the command prompt, replacing with the path to "", so your ~/.gitconfig contains

    external = <path_to_wrapper_script>

Be sure to use the correct syntax to specify the paths to the wrapper script and diff tool, i.e. use forward slashed instead of backslashes. In my case, I have

    external = \"c:/Documents and Settings/sschuber/\"

in .gitconfig and

"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat

in the wrapper script. Mind the trailing "cat"!

(I suppose the '| cat' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)

(Diomidis Spinellis adds in the comments:

The cat command is required, because diff(1), by default exits with an error code if the files differ.
Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.
By piping the output of git to cat the non-zero error code is masked.
More efficiently, the program could just run exit with and argument of 0.)

That (the article quoted above) is the theory for external tool defined through config file (not through environment variable).
In practice (still for config file definition of external tool), you can refer to:

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

phpmailer: Reply using only "Reply To" address

At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.

    $mail->addReplyTo([email protected], 'EXAMPLE');

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).

For more information try this link.

Adding background image to div using CSS

You can try this also for setting the class in a div section:

/** CSS **/
.content {
    background: url('') center no-repeat;

.displaybg {
   text-align: center;
   color: #FFF;
<div class="content">

    <p class="displaybg">This is just a test</p>


Onclick event to remove default value in a text input field

HTML5 Placeholder Attribute

You are likely wanting placeholder functionality:

<input name="Name" placeholder="Enter Your Name" />

Polyfill for Older Browsers

This will not work in some older browsers, but polyfills exist (some require jQuery, others don't) to patch that functionality.

"Screw it, I'll do it myself."

If you wanted to roll your own solution, you could use the onfocus and onblur events of your element to determine what its value should be:

<input name="Name" value="Enter Your Name"
       onfocus="(this.value == 'Enter Your Name') && (this.value = '')"
       onblur="(this.value == '') && (this.value = 'Enter Your Name')" />

Avoid Mixing HTML with JavaScript

You'll find that most of us aren't big fans of evaluating JavaScript from attributes like onblur and onfocus. Instead, it's more commonly encouraged to bind this logic up purely with JavaScript. Granted, it's a bit more verbose, but it keeps a nice separation between your logic and your markup:

var nameElement = document.forms.myForm.Name;

function nameFocus( e ) {
  var element = || window.event.srcElement;
  if (element.value == "Enter Your Name") element.value = "";

function nameBlur( e ) {
  var element = || window.event.srcElement;
  if (element.value == "") element.value = "Enter Your Name";

if ( nameElement.addEventListener ) {
  nameElement.addEventListener("focus", nameFocus, false);
  nameElement.addEventListener("blur", nameBlur, false);
} else if ( nameElement.attachEvent ) {
  nameElement.attachEvent("onfocus", nameFocus);
  nameElement.attachEvent("onblur", nameBlur);


PostgreSQL: Which version of PostgreSQL am I running?

If Select version() returns with Memo try using the command this way:

Select version::char(100) 


Select version::varchar(100)

How to sort a Collection<T>?

Collections by themselves do not have a predefined order, therefore you must convert them to a java.util.List. Then you can use one form of java.util.Collections.sort

Collection< T > collection = ...;

List< T > list = new ArrayList< T >( collection );

Collections.sort( list );
 // or
Collections.sort( list, new Comparator< T >( ){...} );

// list now is sorted

Implementing two interfaces in a class with same method. Which interface method is overridden?

As in interface,we are just declaring methods,concrete class which implements these both interfaces understands is that there is only one method(as you described both have same name in return type). so there should not be an issue with it.You will be able to define that method in concrete class.

But when two interface have a method with the same name but different return type and you implement two methods in concrete class:

Please look at below code:

public interface InterfaceA {
  public void print();

public interface InterfaceB {
  public int print();

public class ClassAB implements InterfaceA, InterfaceB {
  public void print()
    System.out.println("Inside InterfaceA");
  public int print()
    System.out.println("Inside InterfaceB");
    return 5;

when compiler gets method "public void print()" it first looks in InterfaceA and it gets it.But still it gives compile time error that return type is not compatible with method of InterfaceB.

So it goes haywire for compiler.

In this way, you will not be able to implement two interface having a method of same name but different return type.

JQuery select2 set default value from an option in list?

Came from the future? Looking for the ajax source default value ?

// Set up the Select2 control
    ajax: {
        url: '/api/students'

// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
    type: 'GET',
    url: '/api/students/s/' + studentId
}).then(function (data) {
    // create the option and append to Select2
    var option = new Option(data.full_name,, true, true);

    // manually trigger the `select2:select` event
        type: 'select2:select',
        params: {
            data: data

You're welcome.


How to find the Number of CPU Cores via .NET/C#?

The following program prints the logical and physical cores of a windows machine.

#define STRICT
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <omp.h>

template<typename T>
T *AdvanceBytes(T *p, SIZE_T cb)
 return reinterpret_cast<T*>(reinterpret_cast<BYTE *>(p) + cb);

class EnumLogicalProcessorInformation
 EnumLogicalProcessorInformation(LOGICAL_PROCESSOR_RELATIONSHIP Relationship)
  : m_pinfoBase(nullptr), m_pinfoCurrent(nullptr), m_cbRemaining(0)
  DWORD cb = 0;
  if (GetLogicalProcessorInformationEx(Relationship,
                                       nullptr, &cb)) return;
  if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) return;

  m_pinfoBase =
                                     (LocalAlloc(LMEM_FIXED, cb));
  if (!m_pinfoBase) return;

  if (!GetLogicalProcessorInformationEx(Relationship, 
                                        m_pinfoBase, &cb)) return;

  m_pinfoCurrent = m_pinfoBase;
  m_cbRemaining = cb;

 ~EnumLogicalProcessorInformation() { LocalFree(m_pinfoBase); }

 void MoveNext()
  if (m_pinfoCurrent) {
   m_cbRemaining -= m_pinfoCurrent->Size;
   if (m_cbRemaining) {
    m_pinfoCurrent = AdvanceBytes(m_pinfoCurrent,
   } else {
    m_pinfoCurrent = nullptr;

                                         { return m_pinfoCurrent; }
 DWORD m_cbRemaining;

int __cdecl main(int argc, char **argv)
  int numLogicalCore = 0;
  int numPhysicalCore = 0;

  for (EnumLogicalProcessorInformation enumInfo(RelationProcessorCore);
      auto pinfo = enumInfo.Current(); enumInfo.MoveNext()) 
      int numThreadPerCore = (pinfo->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
      // std::cout << "thread per core: "<< numThreadPerCore << std::endl;
      numLogicalCore += numThreadPerCore;
      numPhysicalCore += 1;

  printf ("Number of physical core = %d , Number of Logical core = %d \n", numPhysicalCore, numLogicalCore );

 char c = getchar(); /* just to wait on to see the results in the command prompt */
 return 0;

I tested with Intel Xeon four cores with hyper threading and here is the result
Number of physical core = 4 , Number of Logical core = 8

HTML5 Video // Completely Hide Controls

<video width="320" height="240" autoplay="autoplay">
  <source src="movie.mp4" type="video/mp4">
  <source src="movie.ogg" type="video/ogg">
  Your browser does not support the video tag.

Speed comparison with Project Euler: C vs Python vs Erlang vs Haskell

#include <stdio.h>
#include <math.h>

int factorCount (long n)
    double square = sqrt (n);
    int isquare = (int) square+1;
    long candidate = 2;
    int count = 1;
    while(candidate <= isquare && candidate<=n){
        int c = 1;
        while (n % candidate == 0) {
           n /= candidate;
        count *= c;
    return count;

int main ()
    long triangle = 1;
    int index = 1;
    while (factorCount (triangle) < 1001)
        index ++;
        triangle += index;
    printf ("%ld\n", triangle);

gcc -lm -Ofast euler.c

time ./a.out

2.79s user 0.00s system 99% cpu 2.794 total

Scala: write string to file in one statement

Here is a concise one-liner using, this works with Scala 2.12:"filename").writeAll("hello world")

Alternatively, if you want to use the Java libraries you can do this hack:

Some(new PrintWriter("filename")).foreach{p => p.write("hello world"); p.close}

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

@Amit's answer is good because it will work in both Mustache and Handlebars.

As far as Handlebars-only solutions, I've seen a few and I like the each_with_key block helper at the best.

  • It allows you to iterate over object literals without having to restructure them first, and
  • It gives you control over what you call the key variable. With many other solutions you have to be careful about using object keys named 'key', or 'property', etc.

Bringing a subview to be in front of all other views

In c#, View.BringSubviewToFront(childView); YourView.Layer.ZPosition = 1; both should work.

Add primary key to existing table

Please try this-


Determine if Python is running inside virtualenv

According to the virtualenv pep at you can just use sys.prefix instead os.environ['VIRTUAL_ENV'].

the sys.real_prefix does not exist in my virtualenv and same with sys.base_prefix.

Setting a log file name to include current date in Log4j

Using file, and including apache-log4j-extras 1.1 in my POM with log4j 1.2.16


git stash blunder: git stash pop and ended up with merge conflicts

See man git merge (HOW TO RESOLVE CONFLICTS):

After seeing a conflict, you can do two things:

  • Decide not to merge. The only clean-ups you need are to reset the index file to the HEAD commit to reverse 2. and to clean up working tree changes made by 2. and 3.; git-reset --hard can be used for this.

  • Resolve the conflicts. Git will mark the conflicts in the working tree. Edit the files into shape and git add them to the index. Use git commit to seal the deal.

And under TRUE MERGE (to see what 2. and 3. refers to):

When it is not obvious how to reconcile the changes, the following happens:

  1. The HEAD pointer stays the same.

  2. The MERGE_HEAD ref is set to point to the other branch head.

  3. Paths that merged cleanly are updated both in the index file and in your working tree.

  4. ...

So: use git reset --hard if you want to remove the stash changes from your working tree, or git reset if you want to just clean up the index and leave the conflicts in your working tree to merge by hand.

Under man git stash (OPTIONS, pop) you can read in addition:

Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards.

OTP (token) should be automatically read from the message

Sorry for late reply but still felt like posting my answer if it helps.It works for 6 digits OTP.

    public void onOTPReceived(String messageBody)
        Pattern pattern = Pattern.compile(SMSReceiver.OTP_REGEX);
        Matcher matcher = pattern.matcher(messageBody);
        String otp = HkpConstants.EMPTY;
        while (matcher.find())
            otp =;
Adding constants here

public static final String OTP_REGEX = "[0-9]{1,6}";

For SMS listener one can follow the below class

public class SMSReceiver extends BroadcastReceiver
    public static final String SMS_BUNDLE = "pdus";
    public static final String OTP_REGEX = "[0-9]{1,6}";
    private static final String FORMAT = "format";

    private OnOTPSMSReceivedListener otpSMSListener;

    public SMSReceiver(OnOTPSMSReceivedListener listener)
        otpSMSListener = listener;

    public void onReceive(Context context, Intent intent)
        Bundle intentExtras = intent.getExtras();
        if (intentExtras != null)
            Object[] sms_bundle = (Object[]) intentExtras.get(SMS_BUNDLE);
            String format = intent.getStringExtra(FORMAT);
            if (sms_bundle != null)
                otpSMSListener.onOTPSMSReceived(format, sms_bundle);
            else {
                // do nothing

    public interface OnOTPSMSReceivedListener
        void onOTPSMSReceived(@Nullable String format, Object... smsBundle);

    public void onOTPSMSReceived(@Nullable String format, Object... smsBundle)
        for (Object aSmsBundle : smsBundle)
            SmsMessage smsMessage = getIncomingMessage(format, aSmsBundle);
            String sender = smsMessage.getDisplayOriginatingAddress();
            if (sender.toLowerCase().contains(ONEMG))
            } else
                // do nothing

    private SmsMessage getIncomingMessage(@Nullable String format, Object aObject)
        SmsMessage currentSMS;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && format != null)
            currentSMS = SmsMessage.createFromPdu((byte[]) aObject, format);
        } else
            currentSMS = SmsMessage.createFromPdu((byte[]) aObject);

        return currentSMS;

android EditText - finished typing event

I personally prefer automatic submit after end of typing. Here's how you can detect this event.

Declarations and initialization:

private Timer timer = new Timer();
private final long DELAY = 1000; // in ms

Listener in e.g. onCreate()

EditText editTextStop = (EditText) findViewById(;
    editTextStop.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        public void onTextChanged(final CharSequence s, int start, int before,
                int count) {
            if(timer != null)
        public void afterTextChanged(final Editable s) {
            //avoid triggering event when text is too short
            if (s.length() >= 3) {              

                timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        // TODO: do what you need here (refresh list)
                        // you will probably need to use
                        // runOnUiThread(Runnable action) for some specific
                        // actions

                }, DELAY);

So, when text is changed the timer is starting to wait for any next changes to happen. When they occure timer is cancelled and then started once again.

Oracle date function for the previous month

The trunc() function truncates a date to the specified time period; so trunc(sysdate,'mm') would return the beginning of the current month. You can then use the add_months() function to get the beginning of the previous month, something like this:

select count(distinct switch_id)   
  from [email protected]  
 where dealer_name =  'XXXX'    
   and creation_date >= add_months(trunc(sysdate,'mm'),-1) 
   and creation_date < trunc(sysdate, 'mm')

As a little side not you're not explicitly converting to a date in your original query. Always do this, either using a date literal, e.g. DATE 2012-08-31, or the to_date() function, for example to_date('2012-08-31','YYYY-MM-DD'). If you don't then you are bound to get this wrong at some point.

You would not use sysdate - 15 as this would provide the date 15 days before the current date, which does not seem to be what you are after. It would also include a time component as you are not using trunc().

Just as a little demonstration of what trunc(<date>,'mm') does:

select sysdate
     , case when trunc(sysdate,'mm') > to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as gt
     , case when trunc(sysdate,'mm') < to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as lt
     , case when trunc(sysdate,'mm') = to_date('20120901 00:00:00','yyyymmdd hh24:mi:ss')
             then 1 end as eq
  from dual

SYSDATE                   GT         LT         EQ
----------------- ---------- ---------- ----------
20120911 19:58:51                                1

RegEx match open tags except XHTML self-contained tags

While the answers that you can't parse HTML with regexes are correct, they don't apply here. The OP just wants to parse one HTML tag with regexes, and that is something that can be done with a regular expression.

The suggested regex is wrong, though:

<([a-z]+) *[^/]*?>

If you add something to the regex, by backtracking it can be forced to match silly things like <a >>, [^/] is too permissive. Also note that <space>*[^/]* is redundant, because the [^/]* can also match spaces.

My suggestion would be


Where (?<! ... ) is (in Perl regexes) the negative look-behind. It reads "a <, then a word, then anything that's not a >, the last of which may not be a /, followed by >".

Note that this allows things like <a/ > (just like the original regex), so if you want something more restrictive, you need to build a regex to match attribute pairs separated by spaces.

Move existing, uncommitted work to a new branch in Git

I used @Robin answer & listing all that I did,

git status                               <-- review/list uncommitted changes
git stash                                <-- stash uncommitted changes
git stash branch <new-branch> stash@{1}  <-- create a branch from stash
git add .                                <-- add local changes
git status                               <-- review the status; ready to commit
git commit -m "local changes ..."        <-- commit the changes
git branch --list                        <-- see list of branches incl the one created above
git status                               <-- nothing to commit, working tree (new-branch) is clean
git checkout <old-branch>                <-- switch back

! If the repo has more than one stash, see which one to apply to the new-branch:

git stash list  
  stash@{0}: WIP on ...  
  stash@{1}: WIP on ...

and inspect the individual stash by,

git stash show stash@{1}

Or inspect all stashes at once:

git stash list -p

How do I time a method's execution in Java?

Performance measurements on my machine

  • System.nanoTime() : 750ns
  • System.currentTimeMillis() : 18ns

As mentioned, System.nanoTime() is thought to measure elapsed time. Just be aware of the cost if used inside a loop or the like.

How to use ClassLoader.getResources() correctly?

Here is code based on bestsss' answer:

    Enumeration<URL> en = getClass().getClassLoader().getResources(
    List<String> profiles = new ArrayList<>();
    while (en.hasMoreElements()) {
        URL url = en.nextElement();
        JarURLConnection urlcon = (JarURLConnection) (url.openConnection());
        try (JarFile jar = urlcon.getJarFile();) {
            Enumeration<JarEntry> entries = jar.entries();
            while (entries.hasMoreElements()) {
                String entry = entries.nextElement().getName();

How to specify different Debug/Release output directories in QMake .pro file

The short answer is: you don't.

You should run qmake followed by make in whatever build directory you want to build in. So, run it once in a debug directory, once in a release directory.

That's how anyone building your project would expect it to work, and that's how Qt itself is set up to build, that's also how Qt Creator expects your .pro file to behave: it simply starts qmake and then make in the build folder for your target's chosen configuration.

If you wish to create these folders and perform the two (or more) builds in them, you'll need a top-level makefile, possibly created from a top-level project file via qmake.

It's not uncommon to have more than two build configurations, so you're unnecessarily committing yourself to only differentiating between a build and a release; you might have builds with different optimization levels, etc. The debug/release dichotomy is best left to rest in peace.

Django check for any exists for a query

Use count():


if sc.count() > 0:

The advantage over e.g. len() is, that the QuerySet is not yet evaluated:

count() performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result.

Having this in mind, When QuerySets are evaluated can be worth reading.

If you use get(), e.g. scorm.objects.get(pk=someid), and the object does not exists, an ObjectDoesNotExist exception is raised:

from django.core.exceptions import ObjectDoesNotExist
    sc = scorm.objects.get(pk=someid)
except ObjectDoesNotExist:
    print ...

Update: it's also possible to use exists():

if scorm.objects.filter(

Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.

Extracting hours from a DateTime (SQL Server 2005)

Try this one too:


New features in java 7

New Feature of Java Standard Edition (JSE 7)

  1. Decorate Components with the JLayer Class:

    The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at The JLayer class was initially based on the JXLayer project, but its API evolved separately.

  2. Strings in switch Statement:

    In the JDK 7 , we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

  3. Type Inference for Generic Instance:

    We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

    List<String> l = new ArrayList<>();
    l.addAll(new ArrayList<>());

    In comparison, the following example compiles:

    List<? extends String> list2 = new ArrayList<>();
  4. Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:

    In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:

    catch (IOException e) {
        throw e;
    catch (SQLException e) {
        throw e;

    In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:

    catch (IOException|SQLException e) {
        throw e;

    The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

  5. The java.nio.file package

    The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.


web.xml is missing and <failOnMissingWebXml> is set to true

You can also do this which is less verbose


DECODE( ) function in SQL Server

join this "literal table",

    t.c.value('@c', 'varchar(30)') code,
    t.c.value('@v', 'varchar(30)') val
from (select convert(xml, '<x c="CODE001" v="Value One" /><x c="CODE002" v="Value Two" />') aXmlCol) z
cross apply aXmlCol.nodes('/x') t(c)

Python convert csv to xlsx

With my library pyexcel,

 $ pip install pyexcel pyexcel-xlsx

you can do it in one command line:

from pyexcel.cookbook import merge_all_to_a_book
# import pyexcel.ext.xlsx # no longer required if you use pyexcel >= 0.2.2 
import glob

merge_all_to_a_book(glob.glob("your_csv_directory/*.csv"), "output.xlsx")

Each csv will have its own sheet and the name will be their file name.

Why are Python's 'private' methods not actually private?

Similar behavior exists when module attribute names begin with a single underscore (e.g. _foo).

Module attributes named as such will not be copied into an importing module when using the from* method, e.g.:

from bar import *

However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation. Access denied (

Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy file (path is as in the reply of Petey B)

permission "your folder path", "write"

In your case it would be

permission "S:/PDSPopulatingProgram/-", "write"

Here /- means any files or sub-folders inside this folder.

Warning: But by doing this, you are inviting some security risk.

Are multi-line strings allowed in JSON?

Unfortunately many of the answers here address the question of how to put a newline character in the string data. The question is how to make the code look nicer by splitting the string value across multiple lines of code. (And even the answers that recognize this provide "solutions" that assume one is free to change the data representation, which in many cases one is not.)

And the worse news is, there is no good answer.

In many programming languages, even if they don't explicitly support splitting strings across lines, you can still use string concatenation to get the desired effect; and as long as the compiler isn't awful this is fine.

But json is not a programming language; it's just a data representation. You can't tell it to concatenate strings. Nor does its (fairly small) grammar include any facility for representing a string on multiple lines.

Short of devising a pre-processor of some kind (and I, for one, don't feel like effectively making up my own language to solve this issue), there isn't a general solution to this problem. IF you can change the data format, then you can substitute an array of strings. Otherwise, this is one of the numerous ways that json isn't designed for human-readability.

How to round up the result of integer division?

The following should do rounding better than the above solutions, but at the expense of performance (due to floating point calculation of 0.5*rctDenominator):

uint64_t integerDivide( const uint64_t& rctNumerator, const uint64_t& rctDenominator )
  // Ensure .5 upwards is rounded up (otherwise integer division just truncates - ie gives no remainder)
  return (rctDenominator == 0) ? 0 : (rctNumerator + (int)(0.5*rctDenominator)) / rctDenominator;

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

It is an abbreviation for 'optional' , used for optional software in some distros.

missing private key in the distribution certificate on keychain

At the Menu > Visual Studio (mac) > Preferences > Publishing > Apple Developer Accounts > [Select your apple id] > View Details > Create Certificate

To delete unused/invalid certificates, go to website:

delete any unwanted certificate there

Next is to create App ID (identifiers), go to website:

Next, go to website to create provisioning profiles:

use the certificate to bind with your app id.

Next is to download the profiles:
At your mac > At the Menu > Visual Studio (mac) > Preferences > Publishing > Apple Developer Accounts > [Select your apple id] > View Details > Download All Profiles

Difference between View and ViewGroup in Android

ViewGroup is itself a View that works as a container for other views. It extends the functionality of View class in order to provide efficient ways to layout the child views.

For example, LinearLayout is a ViewGroup that lets you define the orientation in which you want child views to be laid, that's all you need to do and LinearLayout will take care of the rest.

Click a button programmatically - JS

window.onload = function() {
    var userImage = document.getElementById('imageOtherUser');
    var hangoutButton = document.getElementById("hangoutButtonId");
    userImage.onclick = function() {; // this will trigger the click event

this will do the trick

JSON Array iteration in Android/Java

You are using the same Cast object for every entry. On each iteration you just changed the same object instead creating a new one.

This code should fix it:

JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();

for (int i=0; i < jCastArr.length(); i++) {
    Cast person = new Cast();  // create a new object here
    JSONObject jpersonObj = jCastArr.getJSONObject(i);

    person.castId = (String) jpersonObj.getString("id");
    person.castFullName = (String) jpersonObj.getString("name");

details.castList = castList;

String array initialization in Java

You mean like:

String names[] = {"Ankit","Bohra","Xyz"};

But you can only do this in the same statement when you declare it

Count number of columns in a table row

Why not use reduce so that we can take colspan into account? :)

function getColumns(table) {
    var cellsArray = [];
    var cells = table.rows[0].cells;

    // Cast the cells to an array
    // (there are *cooler* ways of doing this, but this is the fastest by far)
    // Taken from
    for(var i=-1, l=cells.length; ++i!==l; cellsArray[i]=cells[i]);

    return cellsArray.reduce(
        (cols, cell) =>
            // Check if the cell is visible and add it / ignore it
            (cell.offsetParent !== null) ? cols += cell.colSpan : cols,

The action or event has been blocked by Disabled Mode

Try and see if this works:

  1. Click on 'External Data' tab
  2. There should be a Security Warning that states "Certain content in the database has been disabled"
  3. Click the 'Options' button
  4. Select 'Enable this content' and click the OK button

Change value of input and submit form in JavaScript

You could do something like this instead:

<form name="myform" action="action.php" onsubmit="DoSubmit();">
    <input type="hidden" name="myinput" value="0" />
    <input type="text" name="message" value="" />
    <input type="submit" name="submit" />

And then modify your DoSubmit function to just return true, indicating that "it's OK, now you can submit the form" to the browser:

function DoSubmit(){
  document.myform.myinput.value = '1';
  return true;

I'd also be wary of using onclick events on a submit button; the order of events isn't immediately obvious, and your callback won't get called if the user submits by, for example, hitting return in a textbox.

How to search a Git repository by commit message?

git log --grep="Build 0051"

should do the trick

div with dynamic min-height based on browser window height

It's hard to do this.

There is a min-height: css style, but it doesn't work in all browsers. You can use it, but the biggest problem is that you will need to set it to something like 90% or numbers like that (percents), but the top and bottom divs use fixed pixel sizes, and you won't be able to reconcile them.

 var minHeight = $(window).height() -
                 $('#a').outerHeight(true) -

if($('#b').height() < minHeight) $('#b').height(minHeight);

I know a and c have fixed heights, but I rather measure them in case they change later.

Also, I am measuring the height of b (I don't want to make is smaller after all), but if there is an image in there that did not load the height can change, so watch out for things like that.

It may be safer to do:

$('#b').prepend('<div style="float: left; width: 1px; height: ' + minHeight + 'px;">&nbsp;</div>');

Which simply adds an element into that div with the correct height - that effectively acts as min-height even for browsers that don't have it. (You may want to add the element into your markup, and then just control the height of it via javascript instead of also adding it that way, that way you can take it into account when designing the layout.)

MySQL: can't access root account

This worked for me:

Step 1: Stop MySQL daemon if it is currently running

  ps -ef | grep mysql      - checks if mysql/mysqld is one of the running processes.

  pkill mysqld             - kills the daemon, if it is running.

Step 2: Run MySQL safe daemon with skipping grant tables

  mysqld_safe --skip-grant-tables &

  mysql -u root mysql

Step 3: Login to MySQL as root with no password

  mysql -u root mysql

Step 4: Run UPDATE query to reset the root password

  UPDATE user SET password=PASSWORD("value=42") WHERE user="root";

In MySQL 5.7, the 'password' field was removed, now the field name is 'authentication_string':

  UPDATE user SET authentication_string=PASSWORD("42") WHERE 

Step 5: Stop MySQL safe daemon

Step 6: Start MySQL daemon

WebDriver - wait for element using Java

You can use Explicit wait or Fluent Wait

Example of Explicit Wait -

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated("about_me")));     

Example of Fluent Wait -

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
.withTimeout(20, TimeUnit.SECONDS)          
.pollingEvery(5, TimeUnit.SECONDS)          

  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement("about_me"));     

Check this TUTORIAL for more details.

Get the distance between two geo points

Just use the following method, pass it lat and long and get distance in meter:

private static double distance_in_meter(final double lat1, final double lon1, final double lat2, final double lon2) {
    double R = 6371000f; // Radius of the earth in m
    double dLat = (lat1 - lat2) * Math.PI / 180f;
    double dLon = (lon1 - lon2) * Math.PI / 180f;
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(latlong1.latitude * Math.PI / 180f) * Math.cos(latlong2.latitude * Math.PI / 180f) *
                    Math.sin(dLon/2) * Math.sin(dLon/2);
    double c = 2f * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double d = R * c;
    return d;

Is it safe to delete the "InetPub" folder?

If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.

Change IIS7 Inetpub path

  • Open %windir%\system32\inetsrv\config\applicationhost.config and search for


  • Change the path.

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

The problem is the ssl certificate on server side. Either something is interfering or the certificate doesn't match the service. For instance when a site has a ssl cert for while the service you use runs on That is a different machine.

How to remove all callbacks from a Handler?

Please note that one should define a Handler and a Runnable in class scope, so that it is created once.removeCallbacks(Runnable) works correctly unless one defines them multiple times. Please look at following examples for better understanding:

Incorrect way :

    public class FooActivity extends Activity {
           private void handleSomething(){
                Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                   public void run() {
                  //doIt() works after 3 seconds.
                  handler.postDelayed(runnable, 3000);
              } else {

          public void onClick(View v){

If you call onClick(..) method, you never stop doIt() method calling before it call. Because each time creates new Handler and new Runnable instances. In this way, you lost necessary references which belong to handler and runnable instances.

Correct way :

 public class FooActivity extends Activity {
        Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            public void run() {
        private void handleSomething(){
                //doIt() works after 3 seconds.
                handler.postDelayed(runnable, 3000);
            } else {

       public void onClick(View v){

In this way, you don't lost actual references and removeCallbacks(runnable) works successfully.

Key sentence is that 'define them as global in your Activity or Fragment what you use'.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

use this code

  while ($rows = mysql_fetch_array($query)):

   $name = $rows['Name'];
   $address = $rows['Address'];
   $email = $rows['Email'];
   $subject = $rows['Subject'];
   $comment = $rows['Comment'];

   echo "$name<br>$address<br>$email<br>$subject<br>$comment<br><br>";



How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach

How can I add new keys to a dictionary?

I feel like consolidating info about Python dictionaries:

Creating an empty dictionary

data = {}
# OR
data = dict()

Creating a dictionary with initial values

data = {'a': 1, 'b': 2, 'c': 3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1), ('b',2), ('c',3))}

Inserting/Updating a single value

data['a'] = 1  # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a': 1})
# OR
# OR

Inserting/Updating multiple values

data.update({'c':3,'d':4})  # Updates 'c' and adds 'd'

Python 3.9+:

The update operator |= now works for dictionaries:

data |= {'c':3,'d':4}

Creating a merged dictionary without modifying originals

data3 = {}
data3.update(data)  # Modifies data3, not data
data3.update(data2)  # Modifies data3, not data2

Python 3.5+:

This uses a new feature called dictionary unpacking.

data = {**data1, **data2, **data3}

Python 3.9+:

The merge operator | now works for dictionaries:

data = data1 | {'c':3,'d':4}

Deleting items in dictionary

del data[key]  # Removes specific element in a dictionary
data.pop(key)  # Removes the key & returns the value
data.clear()  # Clears entire dictionary

Check if a key is already in dictionary

key in data

Iterate through pairs in a dictionary

for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys

Create a dictionary from two lists

data = dict(zip(list_with_keys, list_with_values))

Transfer files to/from session I'm logged in with PuTTY

If you have to do private key validation; at Command Prompt(cmd), run


set PATH=C:\PuttySetupLocation


pscp -i C:/MyPrivateKeyFile.ppk C:/MySourceFile.jar [email protected]:/home/ubuntu

Also, if you need extra options look at the following link.

Using Enum values as String literals

As Benny Neugebauer mentions, you could overwrite the toString(). However instead overwriting the toString for each enum field I like more something like this:

public enum Country{

    private String value;

    Country(final String value) {
        this.value = value;

    public String getValue() {
        return value;

    public String toString() {
        return this.getValue();

You could also add a static method to retrieve all the fields, to print them all, etc. Simply call getValue to obtain the string associated to each Enum item

Failed to load AppCompat ActionBar with unknown error in android studio

Open preview mode

follow the below link to fix the issue

Fix - Rendering Problems The Following classes could not be found :

goto appTheme ----> select Holo Theme ---> refresh

Xcode Project vs. Xcode Workspace - Differences

In brief

  • Xcode 3 introduced subproject, which is parent-child relationship, meaning that parent can reference its child target, but no vice versa
  • Xcode 4 introduced workspace, which is sibling relationship, meaning that any project can reference projects in the same workspace

Python: How to check a string for substrings from a list?

Try this test:

any(substring in string for substring in substring_list)

It will return True if any of the substrings in substring_list is contained in string.

Note that there is a Python analogue of Marc Gravell's answer in the linked question:

from itertools import imap
any(imap(string.__contains__, substring_list)) 

In Python 3, you can use map directly instead:

any(map(string.__contains__, substring_list))

Probably the above version using a generator expression is more clear though.

How to Define Callbacks in Android?

Example to implement callback method using interface.

Define the interface,

package javaapplication1;

public interface NewInterface {
    void callback();

Create a new class, It will call the callback method in main class.

package javaapplication1;

public class NewClass {

    private NewInterface mainClass;

    public NewClass(NewInterface mClass){
        mainClass = mClass;

    public void calledFromMain(){
        //Do somthing...

        //call back main

The main class,, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.

package javaapplication1;
public class JavaApplication1 implements NewInterface{

    NewClass newClass;

    public static void main(String[] args) {


        JavaApplication1 myApplication = new JavaApplication1();


    private void doSomething(){
        newClass = new NewClass(this);

    public void callback() {


When increasing the size of VARCHAR column on a large table could there be any problems?

In my case alter column was not working so one can use 'Modify' command, like:

alter table [table_name] MODIFY column [column_name] varchar(1200);

Collapsing Sidebar with Bootstrap

Bootstrap 3

Yes, it's possible. This "off-canvas" example should help to get you started.

Basically you need to wrap the layout in an outer div, and use media queries to toggle the layout on smaller screens.

/* collapsed sidebar styles */
@media screen and (max-width: 767px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
  .sidebar-offcanvas {
    right: -41.6%;

  .sidebar-offcanvas {
    left: -41.6%;
  } {
    right: 41.6%;
  } {
    left: 41.6%;
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
    width: 41.6%;
  #sidebar {

Also, there are several more Bootstrap sidebar examples here

Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?

Copy multiple files from one directory to another from Linux shell

I guess you are looking for brace expansion:

cp /home/ankur/folder/{file1,file2} /home/ankur/dest

take a look here, it would be helpful for you if you want to handle multiple files once :

tab completion with zsh...

enter image description here

Custom designing EditText

// background add in layout

Combine multiple results in a subquery into a single comma-separated value

In MySQL there is a group_concat function that will return what you're asking for.

SELECT TableA.ID, TableA.Name, group_concat(TableB.SomeColumn) 
as SomColumnGroup FROM TableA LEFT JOIN TableB ON 
TableB.TableA_ID = TableA.ID

shuffling/permutating a DataFrame in pandas

Here is a work around I found if you want to only shuffle a subset of the DataFrame:

shuffle_to_index = 20
df = pd.concat([df.iloc[np.random.permutation(range(shuffle_to_index))], df.iloc[shuffle_to_index:]])

Using an array as needles in strpos

str_replace is considerably faster.

$find_letters = array('a', 'c', 'd');
$string = 'abcdefg';
$match = (str_replace($find_letters, '', $string) != $string);

How to fill 100% of remaining height?

This can be done with tables:

<table cellpadding="0" cellspacing="0" width="100%" height="100%">
    <tr height="0%"><td>
        <div id="full">
            <!--contents of 1 -->
        <div id="someid">
            <!--contents of 2 -->

Then apply css to make someid fill the remaining space:

#someid {
    height: 100%;

Now, I can just hear the angry shouts from the crowd, "Oh noes, he's using tables! Feed him to the lions!" Please hear me out.

Unlike the accepted answer which accomplishes nothing aside from making the container div the full height of the page, this solution makes div #2 fill the remaining space as requested in the question. If you need that second div to fill the full height allotted to it, this is currently the only way to do it.

But feel free to prove me wrong, of course! CSS is always better.

"psql: could not connect to server: Connection refused" Error when connecting to remote database

I had the exact same problem, with my configuration files correct. In my case the issue comes from the Eduroam wifi I used : when I connect via another wifi everything works. It seems that Eduroam blocks port 5432, at least in my university.

How to get row count in an Excel file using POI library?

getLastRowNum() return index of last row.

So if you wants to know total number of row = getLastRowNum() +1.

I hope this will work.

int rowTotal = sheet.getLastRowNum() +1;

Is it possible to log all HTTP request headers with Apache?

mod_log_forensic is what you want, but it may not be included/available with your Apache install by default.

Here is how to use it.

LoadModule log_forensic_module /usr/lib64/httpd/modules/ 
<IfModule log_forensic_module> 
ForensicLog /var/log/httpd/forensic_log 

Send json post using php

Beware that file_get_contents solution doesn't close the connection as it should when a server returns Connection: close in the HTTP header.

CURL solution, on the other hand, terminates the connection so the PHP script is not blocked by waiting for a response.

Describe table structure

sp_help tablename in sql server -- sp_help [ [ @objname = ] 'name' ]

desc tablename in oracle -- DESCRIBE { table-Name | view-Name }

IntelliJ show JavaDocs tooltip on mouse over


Check "Show quick doc on mouse"

Now when you put the mouse over a method a tooltip with the documentation will appear. Sometimes the tooltip size is too small and you will have to resize it moving the mouse down to the bottom of the tooltip.

malloc an array of struct pointers

There's a lot of typedef going on here. Personally I'm against "hiding the asterisk", i.e. typedef:ing pointer types into something that doesn't look like a pointer. In C, pointers are quite important and really affect the code, there's a lot of difference between foo and foo *.

Many of the answers are also confused about this, I think.

Your allocation of an array of Chess values, which are pointers to values of type chess (again, a very confusing nomenclature that I really can't recommend) should be like this:

Chess *array = malloc(n * sizeof *array);

Then, you need to initialize the actual instances, by looping:

for(i = 0; i < n; ++i)
  array[i] = NULL;

This assumes you don't want to allocate any memory for the instances, you just want an array of pointers with all pointers initially pointing at nothing.

If you wanted to allocate space, the simplest form would be:

for(i = 0; i < n; ++i)
  array[i] = malloc(sizeof *array[i]);

See how the sizeof usage is 100% consistent, and never starts to mention explicit types. Use the type information inherent in your variables, and let the compiler worry about which type is which. Don't repeat yourself.

Of course, the above does a needlessly large amount of calls to malloc(); depending on usage patterns it might be possible to do all of the above with just one call to malloc(), after computing the total size needed. Then you'd still need to go through and initialize the array[i] pointers to point into the large block, of course.

Python: instance has no attribute

Your class doesn't have a __init__(), so by the time it's instantiated, the attribute atoms is not present. You'd have to do C.setdata('something') so C.atoms becomes available.

>>> C = Residues()
>>> C.atoms.append('thing')

Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
AttributeError: Residues instance has no attribute 'atoms'

>>> C.setdata('something')
>>> C.atoms.append('thing')   # now it works

Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.

To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms list you could add a constructor:

def __init__(self):
    self.atoms = []

Intercept page exit event

I have users who have not been completing all required data.

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
<cfif q.myData eq "">
    <cfset unloadCheck=1>
        verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
        if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
        else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
    window.onbeforeunload = confirmExit;
    function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}

Redirect stderr to stdout in C shell

The csh shell has never been known for its extensive ability to manipulate file handles in the redirection process.

You can redirect both standard output and error to a file with:

xxx >& filename

but that's not quite what you were after, redirecting standard error to the current standard output.

However, if your underlying operating system exposes the standard output of a process in the file system (as Linux does with /dev/stdout), you can use that method as follows:

xxx >& /dev/stdout

This will force both standard output and standard error to go to the same place as the current standard output, effectively what you have with the bash redirection, 2>&1.

Just keep in mind this isn't a csh feature. If you run on an operating system that doesn't expose standard output as a file, you can't use this method.

However, there is another method. You can combine the two streams into one if you send it to a pipeline with |&, then all you need to do is find a pipeline component that writes its standard input to its standard output. In case you're unaware of such a thing, that's exactly what cat does if you don't give it any arguments. Hence, you can achieve your ends in this specific case with:

xxx |& cat

Of course, there's also nothing stopping you from running bash (assuming it's on the system somewhere) within a csh script to give you the added capabilities. Then you can use the rich redirections of that shell for the more complex cases where csh may struggle.

Let's explore this in more detail. First, create an executable echo_err that will write a string to stderr:

#include <stdio.h>
int main (int argc, char *argv[]) {
    fprintf (stderr, "stderr (%s)\n", (argc > 1) ? argv[1] : "?");
    return 0;

Then a control script test.csh which will show it in action:


ps -ef ; echo ; echo $$ ; echo

echo 'stdout (csh)'
./echo_err csh

bash -c "( echo 'stdout (bash)' ; ./echo_err bash ) 2>&1"

The echo of the PID and ps are simply so you can ensure it's csh running this script. When you run this script with:

./test.csh >test.out 2>test.err

(the initial redirection is set up by bash before csh starts running the script), and examine the out/err files, you see:

    UID     PID    PPID  TTY        STIME     COMMAND
    pax    5708    5364  cons0      11:31:14  /usr/bin/ps
    pax    5364    7364  cons0      11:31:13  /usr/bin/tcsh
    pax    7364       1  cons0      10:44:30  /usr/bin/bash


    stdout (csh)
    stdout (bash)
    stderr (bash)

    stderr (csh)

You can see there that the test.csh process is running in the C shell, and that calling bash from within there gives you the full bash power of redirection.

The 2>&1 in the bash command quite easily lets you redirect standard error to the current standard output (as desired) without prior knowledge of where standard output is currently going.

Python: printing a file to stdout

Sure. Assuming you have a string with the file's name called fname, the following does the trick.

with open(fname, 'r') as fin:

Can I use CASE statement in a JOIN condition?

Try this:

...JOIN sys.allocation_units a ON 
  (a.type=2 AND a.container_id = p.partition_id)
  OR (a.type IN (1, 3) AND a.container_id = p.hobt_id)

Get average color of image via Javascript

As pointed out in other answers, often what you really want the dominant color as opposed to the average color which tends to be brown. I wrote a script that gets the most common color and posted it on this gist

Most efficient way to convert an HTMLCollection to an Array

not sure if this is the most efficient, but a concise ES6 syntax might be:

let arry = [...htmlCollection] 

Edit: Another one, from Chris_F comment:

let arry = Array.from(htmlCollection)

javascript functions to show and hide divs

    function show() { 
        if(document.getElementById('benefits').style.display=='none') { 
        return false;
    function hide() { 
        if(document.getElementById('benefits').style.display=='block') { 
        return false;

 <div id="opener"><a href="#1" name="1" onclick="return show();">click here</a></div> 
    <div id="benefits" style="display:none;">some input in here plus the close button 
           <div id="upbutton"><a onclick="return hide();">click here</a></div> 

PDOException SQLSTATE[HY000] [2002] No such file or directory

The answer from @stuyam solved the "No such file or directory" issue for me

Short answer: Change "host" in the /app/config/database.php file from "localhost" to ""

But then I had a "Connection refused" error. If anyone had the same issue, my solution for this was to update the app/config/local/database.php file so the port is 8889:

'mysql' => array(
        'driver'    => 'mysql',
        'host'      => '',
        'port'      => '8889',
        'database'  => 'databaseName',
        'username'  => 'root',
        'password'  => 'root',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',

Different between parseInt() and valueOf() in java?

If you check the Integer class you will find that valueof call parseInt method. The big difference is caching when you call valueof API . It cache if the value is between -128 to 127 Please find below the link for more information

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

How to pass parameters to $http in angularjs?

Build URL '/search' as string. Like


Actually I didn't use

 `$http({method:'GET', url:'/search', params:{fname: fname, lname: lname}})` 

but I'm sure "params" should be JSON.stringify like for POST

var jsonData = JSON.stringify(
        fname: fname,
        lname: lname 


  params: jsonData

How to get a substring of text?

If you have your text in your_text variable, you can use:


Overriding the java equals() method - not working?


Object obj = new Book();
// Oh noes! What happens now? Can't call it with a String that isn't a Book...

How to import keras from tf.keras in Tensorflow?

Update for everybody coming to check why tensorflow.keras is not visible in PyCharm.

Starting from TensorFlow 2.0, only PyCharm versions > 2019.3 are able to recognise tensorflow and keras inside tensorflow (tensorflow.keras) properly.

Also, it is recommended(by Francois Chollet) that everybody switches to tensorflow.keras in place of plain keras.

How to check if a subclass is an instance of a class at runtime?

It's the other way around: B.class.isInstance(view)

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.


Paste MS Excel data to SQL Server

The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement. Then copy these insert into a text file and then execute on the SQL. The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.

how to select first N rows from a table in T-SQL?

You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.

FROM (SELECT row_number() over (order by UserID) AS line_no, * 
      FROM dbo.User) as users
WHERE users.line_no < 10
OR users.line_no BETWEEN 34 and 67

You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.

Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.

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

+[] evaluates to 0 [...] then summing (+ operation) it with anything converts array content to its string representation consisting of elements joined with comma.

Anything other like taking index of array (have grater priority than + operation) is ordinal and is nothing interesting.

Angular 5 Scroll to top on every Route click

There are some solutions, make sure to check them all :)

The router outlet will emit the activate event any time a new component is being instantiated, so we could use (activate) to scroll (for example) to the top:


<router-outlet (activate)="onActivate($event)" ></router-outlet>


onActivate(event) {
    //or document.body.scrollTop = 0;
    //or document.querySelector('body').scrollTo(0,0)

Use, for exemple, this solution for a smooth scroll:

    onActivate(event) {
        let scrollToTop = window.setInterval(() => {
            let pos = window.pageYOffset;
            if (pos > 0) {
                window.scrollTo(0, pos - 20); // how far to scroll on each step
            } else {
        }, 16);

If you wish to be selective, say not every component should trigger the scrolling, you can check it in an if statement like this:

onActivate(e) {
    if ("login"{ // for example

Since Angular6.1, we can also use { scrollPositionRestoration: 'enabled' } on eagerly loaded modules and it will be applied to all routes:

RouterModule.forRoot(appRoutes, { scrollPositionRestoration: 'enabled' })

It will also do the smooth scrolling, already. However this has the inconvenient for doing it on every routing.

An other solution is to do the top scrolling on router animation. Add this in every transition where you want to scroll to the top:

query(':enter, :leave', style({ position: 'fixed' }), { optional: true }) 

How can I one hot encode in Python?

Approach 1: You can use pandas' pd.get_dummies.

Example 1:

import pandas as pd
s = pd.Series(list('abca'))
     a    b    c
0  1.0  0.0  0.0
1  0.0  1.0  0.0
2  0.0  0.0  1.0
3  1.0  0.0  0.0

Example 2:

The following will transform a given column into one hot. Use prefix to have multiple dummies.

import pandas as pd
df = pd.DataFrame({
   A  B
0  a  b
1  b  a
2  a  c

# Get one hot encoding of columns B
one_hot = pd.get_dummies(df['B'])
# Drop column B as it is now encoded
df = df.drop('B',axis = 1)
# Join the encoded df
df = df.join(one_hot)
       A  a  b  c
    0  a  0  1  0
    1  b  1  0  0
    2  a  0  0  1

Approach 2: Use Scikit-learn

Using a OneHotEncoder has the advantage of being able to fit on some training data and then transform on some other data using the same instance. We also have handle_unknown to further control what the encoder does with unseen data.

Given a dataset with three features and four samples, we let the encoder find the maximum value per feature and transform the data to a binary one-hot encoding.

>>> from sklearn.preprocessing import OneHotEncoder
>>> enc = OneHotEncoder()
>>>[[0, 0, 3], [1, 1, 0], [0, 2, 1], [1, 0, 2]])   
OneHotEncoder(categorical_features='all', dtype=<class 'numpy.float64'>,
   handle_unknown='error', n_values='auto', sparse=True)
>>> enc.n_values_
array([2, 3, 4])
>>> enc.feature_indices_
array([0, 2, 5, 9], dtype=int32)
>>> enc.transform([[0, 1, 1]]).toarray()
array([[ 1.,  0.,  0.,  1.,  0.,  0.,  1.,  0.,  0.]])

Here is the link for this example:

Can't create handler inside thread that has not called Looper.prepare()

This is because Toast.makeText() is calling from a worker thread. It should be call from main UI thread like this

runOnUiThread(new Runnable() {
      public void run() {
        Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

Image, saved to sdcard, doesn't appear in Android's Gallery app

Use this after saving the image

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));

How to end C++ code

If your if statement is in Loop You can use


If you want to escape some code & continue to loop Use :


If your if statement not in Loop You can use :

 return 0;



Easy way to use variables of enum types as string in C?

I thought that a solution like Boost.Fusion one for adapting structs and classes would be nice, they even had it at some point, to use enums as a fusion sequence.

So I made just some small macros to generate the code to print the enums. This is not perfect and has nothing to see with Boost.Fusion generated boilerplate code, but can be used like the Boost Fusion macros. I want to really do generate the types needed by Boost.Fusion to integrate in this infrastructure which allows to print names of struct members, but this will happen later, for now this is just macros :


#include <swissarmyknife/detail/config.hpp>

#include <string>
#include <ostream>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>

    R, unused, ENUMERATION_ENTRY)                                               \
    case ENUMERATION_ENTRY:                                                     \
      return BOOST_PP_STRINGIZE(ENUMERATION_ENTRY);                             \

 * \brief Adapts ENUM to reflectable types.
 * \param ENUM_TYPE To be adapted
 * \param ENUMERATION_SEQ Sequence of enum states
    inline std::string to_string(const ENUM_TYPE& enum_value) {                 \
      switch (enum_value) {                                                     \
      BOOST_PP_SEQ_FOR_EACH(                                                    \
          unused, ENUMERATION_SEQ)                                              \
        default:                                                                \
          return BOOST_PP_STRINGIZE(ENUM_TYPE);                                 \
      }                                                                         \
    }                                                                           \
    inline std::ostream& operator<<(std::ostream& os, const ENUM_TYPE& value) { \
      os << to_string(value);                                                   \
      return os;                                                                \


The old answer below is pretty bad, please don't use that. :)

Old answer:

I've been searching a way which solves this problem without changing too much the enums declaration syntax. I came to a solution which uses the preprocessor to retrieve a string from a stringified enum declaration.

I'm able to define non-sparse enums like this :

    enum State {

And I can interact with them in different ways:

// With a stringstream
std::stringstream ss;
ss << State::FAULT;
std::string myEnumStr = ss.str();

//Directly to stdout
std::cout << State::FAULT << std::endl;

//to a string
std::string myStr = State::to_string(State::FAULT);

//from a string
State::State myEnumVal = State::from_string(State::FAULT);

Based on the following definitions :

#define SMART_ENUM(enumTypeArg, ...)                                                     \
namespace enumTypeArg {                                                                  \
    __VA_ARGS__;                                                                         \
    std::ostream& operator<<(std::ostream& os, const enumTypeArg& val) {                 \
            os << swissarmyknife::enums::to_string(#__VA_ARGS__, val);                   \
            return os;                                                                   \
    }                                                                                    \
    std::string to_string(const enumTypeArg& val) {                                      \
            return swissarmyknife::enums::to_string(#__VA_ARGS__, val);                  \
    }                                                                                    \
    enumTypeArg from_string(const std::string &str) {                                    \
            return swissarmyknife::enums::from_string<enumTypeArg>(#__VA_ARGS__, str);   \
    }                                                                                    \
}                                                                                        \

namespace swissarmyknife { namespace enums {

    static inline std::string to_string(const std::string completeEnumDeclaration, size_t enumVal) throw (std::runtime_error) {
        size_t begin = completeEnumDeclaration.find_first_of('{');
        size_t end = completeEnumDeclaration.find_last_of('}');
        const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );

        size_t count = 0;
        size_t found = 0;
        do {
            found = identifiers.find_first_of(",}", found+1);

            if (enumVal == count) {
                std::string identifiersSubset = identifiers.substr(0, found);
                size_t beginId = identifiersSubset.find_last_of("{,");
                identifiersSubset = identifiersSubset.substr(beginId+1);
                return identifiersSubset;

        } while (found != std::string::npos);

        throw std::runtime_error("The enum declaration provided doesn't contains this state.");

    template <typename EnumType>
    static inline EnumType from_string(const std::string completeEnumDeclaration, const std::string &enumStr) throw (std::runtime_error) {
        size_t begin = completeEnumDeclaration.find_first_of('{');
        size_t end = completeEnumDeclaration.find_last_of('}');
        const std::string identifiers = completeEnumDeclaration.substr(begin + 1, end );

        size_t count = 0;
        size_t found = 0;
        do {
            found = identifiers.find_first_of(",}", found+1);

            std::string identifiersSubset = identifiers.substr(0, found);
            size_t beginId = identifiersSubset.find_last_of("{,");
            identifiersSubset = identifiersSubset.substr(beginId+1);

            if (identifiersSubset == enumStr) {
                return static_cast<EnumType>(count);

        } while (found != std::string::npos);

        throw std::runtime_error("No valid enum value for the provided string");


When I'll need support for sparse enum and when I'll have more time I'll improve the to_string and from_string implementations with boost::xpressive, but this will costs in compilation time because of the important templating performed and the executable generated is likely to be really bigger. But this has the advantage that it will be more readable and maintanable than this ugly manual string manipulation code. :D

Otherwise I always used boost::bimap to perform such mappings between enums value and string, but it has to be maintained manually.

How to use Google Translate API in my Java application?

Generate your own API key here. Check out the documentation here.

You may need to set up a billing account when you try to enable the Google Cloud Translation API in your account.

Below is a quick start example which translates two English strings to Spanish:

import java.util.Arrays;


public class QuickstartSample
    public static void main(String[] arguments) throws IOException, GeneralSecurityException
        Translate t = new Translate.Builder(
                , GsonFactory.getDefaultInstance(), null)
                // Set your application name
        Translate.Translations.List list = Translations().list(
                        // Pass in list of strings to be translated
                        "Hello World",
                        "How to use Google Translate from Java"),
                // Target language

        // TODO: Set your API-Key from
        TranslationsListResponse response = list.execute();
        for (TranslationsResource translationsResource : response.getTranslations())

Required maven dependencies for the code snippet:



Select row with most recent date per user

Possibly you can do group by user and then order by time desc. Something like as below

  SELECT * FROM lms_attendance group by user order by time desc;

Array.push() and unique items

Yep, it's a small mistake.

if(this.items.indexOf(item) === -1) {

How to access cookies in AngularJS?

AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.

We need to add angular-cookies.min.js file to use cookie feature.

Here is some method of AngularJS Cookie.

  • get(key); // This method returns the value of given cookie key.

  • getObject(key); //This method returns the deserialized value of given cookie key.

  • getAll(); //This method returns a key value object with all the cookies.

  • put(key, value, [options]); //This method sets a value for given cookie key.

  • remove(key, [options]); //This method remove given cookie.



<!DOCTYPE html>
<html ng-app="myApp">
<script src="//"></script>
<script src="//"></script>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.


var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);

I have Taken reference from

Apache SSL Configuration Error (SSL Connection Error)

Step to enable SSL correctly.

sudo a2enmod ssl  
sudo apt-get install openssl

Configure the path of SSL certificates in your SSL config file (default-ssl.conf) that might be located in /etc/apache2/sites-available. I have stored certificates under /etc/apache2/ssl/

SSLEngine On
SSLCertificateFile /etc/apache2/ssl/certificate.crt
SSLCertificateChainFile /etc/apache2/ssl/ca_bundle.crt
SSLCertificateKeyFile /etc/apache2/ssl/private.key

Enable SSL config file

sudo a2ensite default-ssl.conf

Chrome:The website uses HSTS. Network errors...this page will probably work later

One very quick way around this is, when you're viewing the "Your connection is not private" screen:

type badidea

type thisisunsafe (credit to The Java Guy for finding the new passphrase)

That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.

This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.

Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.

Edit: as of 30 Jan 2018 this passphrase appears to no longer work.

If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:

How to create a self-signed certificate with openssl?

Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.

Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea passphrase no longer works.

Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).

The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).

The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:

Wikipedia: List of Internet Top Level Domains: Special Use Domains

These top-level domains seem to be exempt from the new https-only restrictions:

  • .local
  • .localhost
  • .test
  • (any custom/non-standard top-level domain)

See the answer and link from codinghands to the original question for more information:

answer from codinghands

How to convert HH:mm:ss.SSS to milliseconds?

Using JODA:

PeriodFormatter periodFormat = new PeriodFormatterBuilder()
  .appendHour() // 2 digits minimum
  .appendMinute() // 2 digits minimum
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();

How to join entries in a set into one string?

Set's do not have an order - so you may lose your order when you convert your list into a set, i.e.:

>>> orderedVars = ['0', '1', '2', '3']
>>> setVars = set(orderedVars)
>>> print setVars
('4', '2', '3', '1')

Generally the order will remain, but for large sets it almost certainly won't.

Finally, just incase people are wondering, you don't need a ', ' in the join.

Just: ''.join(set)


Making authenticated POST requests with Spring RestTemplate for Android

Very useful I had a slightly different scenario where I the request xml was itself the body of the POST and not a param. For that the following code can be used - Posting as an answer just in case anyone else having similar issue will benefit.

    final HttpHeaders headers = new HttpHeaders();
    headers.add("header1", "9998");
    headers.add("username", "xxxxx");
    headers.add("password", "xxxxx");
    headers.add("header2", "yyyyyy");
    headers.add("header3", "zzzzz");
    final HttpEntity<MyXmlbeansRequestDocument> httpEntity = new HttpEntity<MyXmlbeansRequestDocument>(
            MyXmlbeansRequestDocument.Factory.parse(request), headers);
    final ResponseEntity<MyXmlbeansResponseDocument> responseEntity =, HttpMethod.POST, httpEntity,MyXmlbeansResponseDocument.class);;

Is it possible to insert multiple rows at a time in an SQLite database?

If you are using bash shell you can use this:

time bash -c $'
sqlite3 $FILE "create table if not exists tab(id int);"
sqlite3 $FILE "insert into tab values (1),(2)"
for i in 1 2 3 4; do sqlite3 $FILE "INSERT INTO tab (id) select (*abs(random()%1e7) from tab a, tab b, tab c limit 5e5"; done; 
sqlite3 $FILE "select count(*) from tab;"'

Or if you are in sqlite CLI, then you need to do this:

create table if not exists tab(id int);"
insert into tab values (1),(2);
INSERT INTO tab (id) select (*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
INSERT INTO tab (id) select (*abs(random()%1e7) from tab a, tab b, tab c limit 5e5;
select count(*) from tab;

How does it work? It makes use of that if table tab:

id int

then select, from tab a, tab b returns int | int
    1    | 1
    2    | 1
    1    | 2
    2    | 2

and so on. After first execution we insert 2 rows, then 2^3=8. (three because we have tab a, tab b, tab c)

After second execution we insert additional (2+8)^3=1000 rows

Aftern thrid we insert about max(1000^3, 5e5)=500000 rows and so on...

This is the fastest known for me method of populating SQLite database.

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

In Android Q (Android 10) you can't enable/disable wifi programmatically anymore. Use Settings Panel to toggle wifi connectivity:

    val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
    startActivityForResult(panelIntent, 0)
} else {
    // use previous solution, add appropriate permissions to AndroidManifest file (see answers above)
    (this.context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }

Adding item to Dictionary within loop

In your current code, what Dictionary.update() does is that it updates (update means the value is overwritten from the value for same key in passed in dictionary) the keys in current dictionary with the values from the dictionary passed in as the parameter to it (adding any new key:value pairs if existing) . A single flat dictionary does not satisfy your requirement , you either need a list of dictionaries or a dictionary with nested dictionaries.

If you want a list of dictionaries (where each element in the list would be a diciotnary of a entry) then you can make case_list as a list and then append case to it (instead of update) .

Example -

case_list = []
for entry in entries_list:
    case = {'key1': entry[0], 'key2': entry[1], 'key3':entry[2] }

Or you can also have a dictionary of dictionaries with the key of each element in the dictionary being entry1 or entry2 , etc and the value being the corresponding dictionary for that entry.

case_list = {}
for entry in entries_list:
    case = {'key1': value, 'key2': value, 'key3':value }
    case_list[entryname] = case  #you will need to come up with the logic to get the entryname.

Generating (pseudo)random alpha-numeric strings

You can use the following code. It is similar to existing functions except that you can force special character count:

function random_string() {
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_sets = [
        ["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
        ["count" => 1, "characters" => "0123456789"]
    $temp_array = array();
    foreach ($character_sets as $character_set) {
        for ($i = 0; $i < $character_set["count"]; $i++) {
            $random = random_int(0, strlen($character_set["characters"]) - 1);
            $temp_array[] = $character_set["characters"][$random];
    return implode("", $temp_array);

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/ In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

How do I use Maven through a proxy?

Just to add my own experiences with this: my company's proxy is For maven to work via this proxy, the settings have to be exactly like this


Unlike some other proxy-configuration files, the protocol here describes how to connect to the proxy server, not which kinds of protocol should be proxied. The http part of the target has to be split off from the hostname, else it won't work.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

Theoretically, the application in DOS Prompt has its own clipboard and shortcuts. To import text from Windows clipboard is "extra". However you can use Alt-Space to open system menu of Prompt window, then press E, P to select Edit, Paste menu. However, MS could provide shortcut using Win-key. There is no chance to be used in DOS application.

Creating a blurring overlay view

I think the easiest solution to this is to override UIToolbar, which blurs everything behind it in iOS 7. It's quite sneaky, but it's very simple for you to implement, and fast!

You can do it with any view, just make it a subclass of UIToolbar instead of UIView. You can even do it with a UIViewController's view property, for example...

1) create a new class that is a "Subclass of" UIViewController and check the box for "With XIB for user interface".

2) Select the View and go to the identity inspector in the right-hand panel (alt-command-3). Change the "Class" to UIToolbar. Now go to the attributes inspector (alt-command-4) and change the "Background" color to "Clear Color".

3) Add a subview to the main view and hook it up to an IBOutlet in your interface. Call it backgroundColorView. It will look something like this, as a private category in the implementation (.m) file.

@interface BlurExampleViewController ()
@property (weak, nonatomic) IBOutlet UIView *backgroundColorView;

4) Go to the view controller implementation (.m) file and change the -viewDidLoad method, to look as follows:

- (void)viewDidLoad
    [super viewDidLoad];
    self.view.barStyle = UIBarStyleBlack; // this will give a black blur as in the original post
    self.backgroundColorView.opaque = NO;
    self.backgroundColorView.alpha = 0.5;
    self.backgroundColorView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:1];

This will give you a dark gray view, which blurs everything behind it. No funny business, no slow core image blurring, using everything that is at your fingertips provided by the OS/SDK.

You can add this view controller's view to another view, as follows:

[self addChildViewController:self.blurViewController];
[self.view addSubview:self.blurViewController.view];
[self.blurViewController didMoveToParentViewController:self];

// animate the self.blurViewController into view

Let me know if anything is unclear, I'll be happy to help!


UIToolbar has been changed in 7.0.3 to give possibly-undesirable effect when using a coloured blur.

We used to be able to set the colour using barTintColor, but if you were doing this before, you will need to set the alpha component to less than 1. Otherwise your UIToolbar will be completely opaque colour - with no blur.

This can be achieved as follows: (bearing in mind self is a subclass of UIToolbar)

UIColor *color = [UIColor blueColor]; // for example
self.barTintColor = [color colorWithAlphaComponent:0.5];

This will give a blue-ish tint to the blurred view.

Browse and display files in a git repo without cloning

if you know the remote branch you want to check, you can find out the latest via:

git ls-tree -r <remote_branch> --name-only

How to convert a file into a dictionary?

This will leave the key as a string:

with open('infile.txt') as f:
  d = dict(x.rstrip().split(None, 1) for x in f)

TimePicker Dialog from clicking EditText

I extended the nice reusable solution of @Sumoanand to support both focus change and click listeners when changing the time multiple times. Also updating the picker calendar to remember the last selected time + formatting HH:mm

public class TimeSetter implements View.OnFocusChangeListener, TimePickerDialog.OnTimeSetListener, View.OnClickListener {

    private EditText mEditText;
    private Calendar mCalendar;
    private SimpleDateFormat mFormat;

    public TimeSetter(EditText editText){
       this.mEditText = editText;

    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus){

    public void onClick(View view) {

    private void showPicker(View view) {
        if (mCalendar == null)
            mCalendar = Calendar.getInstance();

        int hour = mCalendar.get(Calendar.HOUR_OF_DAY);
        int minute = mCalendar.get(Calendar.MINUTE);

        new TimePickerDialog(view.getContext(), this, hour, minute, true).show();

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        mCalendar.set(Calendar.MINUTE, minute);

        if (mFormat == null)
            mFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());



Usage from onCreate:

EditText timeEditText = (EditText) rootView.findViewById(;
new TimeSetter(timeEditText);

SQL Server 2005 Setting a variable to the result of a select query

You could use:

declare @foo as nvarchar(25)

select @foo = 'bar'

select @foo

UPDATE with CASE and IN - Oracle

Use to_number to convert budgpost to a number:

when to_number(budgpost,99999) in (1001,1012,50055) THEN 'BP_GR_A' 

EDIT: Make sure there are enough 9's in to_number to match to largest budget post.

If there are non-numeric budget posts, you could filter them out with a where clause at then end of the query:

where regexp_like(budgpost, '^-?[[:digit:],.]+$')

Sql Server : How to use an aggregate function like MAX in a WHERE clause

SELECT rest.field1
FROM mastertable as m
INNER JOIN table1 at t1 on t1.field1 = m.field
INNER JOIN table2 at t2 on t2.field = t1.field
WHERE t1.field3 = (SELECT MAX(field3) FROM table1)

Installing mysql-python on Centos

You probably did not install MySQL via yum? The version of MySQLDB in the repository is tied to the version of MySQL in the repository. The versions need to match.

Your choices are:

  1. Install the RPM version of MySQL.
  2. Compile MySQLDB to your version of MySQL.

Notepad++ Regular expression find and delete a line

Combining the best from all the answers

enter image description here

Make xargs handle filenames that contain spaces


find . -name \*.mp3 -print0 | xargs -0 mplayer

instead of

ls | grep mp3 

How to delete files older than X hours

You could to this trick: create a file 1 hour ago, and use the -newer file argument.

(Or use touch -t to create such a file).

What is LDAP used for?

LDAP stands for Lightweight Directory Access Protocol. As the name suggests, it is a lightweight protocol for accessing directory services, specifically X.500-based directory services. LDAP runs over TCP/IP or other connection oriented transfer services. The nitty-gritty details of LDAP are defined in RFC2251 "The Lightweight Directory Access Protocol (v3)" and other documents comprising the technical specification RFC3377. This section gives an overview of LDAP from a user's perspective.

What kind of information can be stored in the directory? The LDAP information model is based on entries. An entry is a collection of attributes that has a globally-unique Distinguished Name (DN). The DN is used to refer to the entry unambiguously. Each of the entry's attributes has a type and one or more values. The types are typically mnemonic strings, like cn for common name, or mail for email address. The syntax of values depend on the attribute type. For example, a cn attribute might contain the value Babs Jensen. A mail attribute might contain the value [email protected]. A jpegPhoto attribute would contain a photograph in the JPEG (binary) format.

How is the information arranged? In LDAP, directory entries are arranged in a hierarchical tree-like structure.

enter image description here

vagrant login as root by default

This works if you are on ubuntu/trusty64 box:

vagrant ssh

Once you are in the ubuntu box:

sudo su

Now you are root user. You can update root password as shown below:

sudo -i

Now edit the below line in the file /etc/ssh/sshd_config

PermitRootLogin yes

Also, it is convenient to create your own alternate username:

adduser johndoe

Wait until it asks for password.

Call Jquery function

calling a function is simple ..


so your code will be something like..

         myFuntion();  //this will call your function

     $('#elementID').click( myFuntion );


or with some condition

   myFunction();  //this will call your function

Explicitly calling return in a function or not

return can increase code readability:

foo <- function() {
    if (a) return(a)       

How to add colored border on cardview?

Start From the material design update, it support app:strokeColor and also app:strokeWidth. see more

to use material design update. add following code to build.gradle(:app)

dependencies {
    // ...
    implementation ''
    // ...

and Change CardView to MaterialCardView

how to hide the content of the div in css

Best way to hide in html/css using display:none;


<div id="divSample" class="hideClass">hi..</div>

Saving data to a file in C#

One liner:

System.IO.File.WriteAllText(@"D:\file.txt", content);

It creates the file if it doesn't exist and overwrites it if it exists. Make sure you have appropriate privileges to write to the location, otherwise you will get an exception.

Write string to text file and ensure it always overwrites the existing content.

How to switch activity without animation in Android?

Try this code,

this.startActivity(new Intent(v.getContext(), newactivity.class).addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION));

Getting the location from an IP address

I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.

I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".

postgresql - sql - count of `true` values

Cast the Boolean to an integer and sum.

SELECT count(*),sum(myCol::int);

You get 6,3.

Bash script - variable content as a command to run

In the case where you have multiple variables containing the arguments for a command you're running, and not just a single string, you should not use eval directly, as it will fail in the following case:

function echo_arguments() {
  echo "Argument 1: $1"
  echo "Argument 2: $2"
  echo "Argument 3: $3"
  echo "Argument 4: $4"

# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"


Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg

Note that even though "Some arg" was passed as a single argument, eval read it as two.

Instead, you can just use the string as the command itself:

# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {

Note the difference between the output of eval and the new eval_command function:

eval_command echo_arguments arg1 arg2 "Some arg"


Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:

SQL Server: combining multiple rows into one row

declare @maxColumnCount int=0;
 declare @Query varchar(max)='';
 declare @DynamicColumnName nvarchar(MAX)='';

-- table type variable that store all values of column row no
 DECLARE @TotalRows TABLE( row_count int)
 INSERT INTO @TotalRows (row_count)
 SELECT (ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc)) as row_no FROM tblExportPartProforma

-- Get the MAX value from @TotalRows table
 set @maxColumnCount= (select max(row_count) from @TotalRows)
-- loop to create Dynamic max/case and store it into local variable 
 DECLARE @cnt INT = 1;
 WHILE @cnt <= @maxColumnCount
   set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then InvoiceType end )as InvoiceType'+cast(@cnt as varchar)+''
      set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then BankRefno end )as BankRefno'+cast(@cnt as varchar)+''
            set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceived end )as AmountReceived'+cast(@cnt as varchar)+''

      set @DynamicColumnName= @DynamicColumnName + ', Max(case when row_no= '+cast(@cnt as varchar)+' then AmountReceivedDate end )as AmountReceivedDate'+cast(@cnt as varchar)+''

   SET @cnt = @cnt + 1;

-- Create dynamic CTE and store it into local variable @query 
  set @Query='
     with CTE_tbl as
       SELECT InvoiceNo,InvoiceType,BankRefno,AmountReceived,AmountReceivedDate,
       ROW_NUMBER() OVER(PARTITION BY InvoiceNo order by InvoiceNo Desc) as row_no
       FROM tblExportPartProforma
     FROM CTE_tbl
     group By InvoiceNo'

-- Execute the Query
 execute (@Query)

ng-repeat: access key and value for each object in array of objects

seems like in Angular 1.3.12 you do not need the inner ng-repeat anymore, the outer loop returns the values of the collection is a single map entry

Rename a dictionary key

Other answers are pretty good.But in python3.6, regular dict also has order. So it's hard to keep key's position in normal case.

def rename(old_dict,old_name,new_name):
    new_dict = {}
    for key,value in zip(old_dict.keys(),old_dict.values()):
        new_key = key if key != old_name else new_name
        new_dict[new_key] = old_dict[key]
    return new_dict

Output in a table format in Java's System.out

Check this out. The author provides a simple but elegant solution which doesn't require any 3rd party library.

An example of the TableBuilder and sample output

hash function for string

Wikipedia shows a nice string hash function called Jenkins One At A Time Hash. It also quotes improved versions of this hash.

uint32_t jenkins_one_at_a_time_hash(char *key, size_t len)
    uint32_t hash, i;
    for(hash = i = 0; i < len; ++i)
        hash += key[i];
        hash += (hash << 10);
        hash ^= (hash >> 6);
    hash += (hash << 3);
    hash ^= (hash >> 11);
    hash += (hash << 15);
    return hash;

Fade Effect on Link Hover?

You can do this with JQueryUI:

    color: '#ff0000'
  }, 1000);
    color: '#000000'
  }, 1000);

How to write a simple Html.DropDownListFor()?

@using (Html.BeginForm()) {
    <p>Do you like pizza?
        @Html.DropDownListFor(x => x.likesPizza, new[] {
            new SelectListItem() {Text = "Yes", Value = bool.TrueString},
            new SelectListItem() {Text = "No", Value = bool.FalseString}
        }, "Choose an option") 
    <input type = "submit" value = "Submit my answer" />

I think this answer is similar to Berat's, in that you put all the code for your DropDownList directly in the view. But I think this is an efficient way of creating a y/n (boolean) drop down list, so I wanted to share it.

Some notes for beginners:

  • Don't worry about what 'x' is called - it is created here, for the first time, and doesn't link to anything else anywhere else in the MVC app, so you can call it what you want - 'x', 'model', 'm' etc.
  • The placeholder that users will see in the dropdown list is "Choose an option", so you can change this if you want.
  • There's a bit of text preceding the drop down which says "Do you like pizza?"
  • This should be complete text for a form, including a submit button, I think

Hope this helps someone,

Beautiful way to remove GET-variables with PHP?

How about:

preg_replace('/\\?.*/', '', $str)

Explain the different tiers of 2 tier & 3 tier architecture?

In a modern two-tier architecture, the server holds both the application and the data. The application resides on the server rather than the client, probably because the server will have more processing power and disk space than the PC.

In a three-tier architecture, the data and applications are split onto seperate servers, with the server-side distributed between a database server and an application server. The client is a front end, simply requesting and displaying data. Reason being that each server will be dedicated to processing either data or application requests, hence a more manageable system and less contention for resources will occur.

You can refer to Difference between three tier vs. n-tier

Convert int to string?

string myString = myInt.ToString();

Invalid shorthand property initializer

Because it's an object, the way to assign value to its properties is using :.

Change the = to : to fix the error.

var options = {
  host: 'localhost',
  port: 8080,
  path: '/',
  method: 'POST'

Doctrine2: Best way to handle many-to-many with extra columns in reference table

Unidirectional. Just add the inversedBy:(Foreign Column Name) to make it Bidirectional.

# config/yaml/ProductStore.dcm.yml
  type: entity
      associationKey: true
      associationKey: true
      type: integer(1)
      type: datetime
      type: datetime
      targetEntity: Product
        name: product_id
        referencedColumnName: id
      targetEntity: Store
        name: store_id
        referencedColumnName: id

I hope it helps. See you.

How to use JavaScript regex over multiple lines?

[.\n] does not work because . has no special meaning inside of [], it just means a literal .. (.|\n) would be a way to specify "any character, including a newline". If you want to match all newlines, you would need to add \r as well to include Windows and classic Mac OS style line endings: (.|[\r\n]).

That turns out to be somewhat cumbersome, as well as slow, (see KrisWebDev's answer for details), so a better approach would be to match all whitespace characters and all non-whitespace characters, with [\s\S], which will match everything, and is faster and simpler.

In general, you shouldn't try to use a regexp to match the actual HTML tags. See, for instance, these questions for more information on why.

Instead, try actually searching the DOM for the tag you need (using jQuery makes this easier, but you can always do document.getElementsByTagName("pre") with the standard DOM), and then search the text content of those results with a regexp if you need to match against the contents.

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:

Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True

Now it works fine.

How can I select all options of multi-select select box on click?

I'm able to make it in a native way @ jsfiddle. Hope it will help.

Post improved answer when it work, and help others.

$(function () { 

                checkAllText : 'Select All',
            uncheckAllText : 'Deselect All',
            selectedText: function(numChecked, numTotal, checkedItems){
              return numChecked + ' of ' + numTotal + ' checked';
            minWidth: 325


How can I use grep to show just filenames on Linux?

For a simple file search you could use grep's -l and -r options:

grep -rl "mystring"

All the search is done by grep. Of course, if you need to select files on some other parameter, find is the correct solution:

find . -iname "*.php" -execdir grep -l "mystring" {} +

The execdir option builds each grep command per each directory, and concatenates filenames into only one command (+).

@Autowired - No qualifying bean of type found for dependency

If you are testing your controller. Don't forget to use @WebAppConfiguration on your test class.

SQLite table constraint - unique on multiple columns

Put the UNIQUE declaration within the column definition section; working example:

    i INT,
    j INT,

Get last n lines of a file, similar to tail

Assumes a unix-like system on Python 2 you can do:

import os
def tail(f, n, offset=0):
  stdin,stdout = os.popen2("tail -n "+n+offset+" "+f)
  lines = stdout.readlines(); stdout.close()
  return lines[:,-offset]

For python 3 you may do:

import subprocess
def tail(f, n, offset=0):
    proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE)
    lines = proc.stdout.readlines()
    return lines[:, -offset]

How to get ID of button user just clicked?

You can also try this simple one-liner code. Just call the alert method on onclick attribute.

<button id="some_id1" onclick="alert("></button>

Check if a string has white space

With additions to the language it is much easier, plus you can take advantage of early return:

// Use includes method on string
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return whitespaceChars.some(char => s.includes(char));

// Use character comparison
function hasWhiteSpace(s) {
  const whitespaceChars = [' ', '\t', '\n'];
  return Array.from(s).some(char => whitespaceChars.includes(char));

const withSpace = "Hello World!";
const noSpace = "HelloWorld!";



I did not run performance benchmark but these should be faster than regex but for small text snippets there won't be that much difference anyway.

ReactJS - How to use comments?

JSX Comments Syntax: You can use

  your comment 
  in multiple lines
  for documentation 


  your comment 
  in multiple lines

for multiple lines comment. And also,

  //your comment 

for single line comment.

Note: The syntax:

{ //your comment } 

doesn't work. You need to type braces in new lines.

Curly braces are used to distinguish between JSX and JavaScript in a React component. Inside curly braces, we use JavaScript comment syntax.

Reference: click here

mysqldump Error 1045 Access denied despite correct passwords etc

I just ran into this after a fresh install of MySQL 5.6.16.

Oddly, it works without the password specified or flagged:

mysqldump -u root myschema mytable > dump.sql

How to make a transparent HTML button?

Make a div and use your image ( png with transparent background ) as the background of the div, then you can apply any text within that div to hover over the button. Something like this:

<div class="button" onclick="yourbuttonclickfunction();" >
Your Button Label Here


.button {
background: url("yourimage.png");

How to get duplicate items from a list using LINQ?

I was trying to solve the same with a list of objects and was having issues because I was trying to repack the list of groups into the original list. So I came up with looping through the groups to repack the original List with items that have duplicates.

public List<MediaFileInfo> GetDuplicatePictures()
    List<MediaFileInfo> dupes = new List<MediaFileInfo>();
    var grpDupes = from f in _fileRepo
                   group f by f.Length into grps
                   where grps.Count() >1
                   select grps;
    foreach (var item in grpDupes)
        foreach (var thing in item)
    return dupes;

Alternative to iFrames with HTML5

This also does seem to work, although W3C specifies it is not intended "for an external (typically non-HTML) application or interactive content"

<embed src="" width=200 height=200 />

More info:

Reset input value in angular 2

Working with Angular 7 I needed to create a file upload with a description of the file.


File Description: <input type="text" (change)="updateFileDescription($" #fileDescription />

<input type="file" accept="*" capture (change)="handleFileInput($" #fileInput /> <button class="btn btn-light" (click)="uploadFileToActivity()">Upload</button>

Here is the Component file

  @ViewChild('fileDescription') fileDescriptionInput: ElementRef;
  @ViewChild('fileInput') fileInput: ElementRef;

        this.fileDescriptionInput.nativeElement.value = '';
        this.fileInput.nativeElement.value = '';

This will do the trick.

Click toggle with jQuery

jQuery: Best Way, delegate the actions to jQuery (jQuery = jQuery).

$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
    return !val;

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

Datatables - Setting column width

My way to do it

    processing: true,
    serverSide: true,
    ajax: 'customer/data',
    columns: [
        { data: 'id', name: 'id' , width: '50px', class: 'text-right' },
        { data: 'name', name: 'name' width: '50px', class: 'text-right' }

How to add minutes to current time in swift

Swift 3:

let minutes: TimeInterval = 1 * 60
let nowPlusOne = Date() + minutes

CSS vertical-align: text-bottom;

To use vertical-align properly, you should do it on table tag. But there is a way to make other html tags to behave as a table by assigning them a css of display:table to your parent, and display:table-cell on your child. Then vertical-align:bottom will work on that child.


??????<div class="parent">
    <div class="child">
        This text is vertically aligned to bottom.    


?.parent {
    width: 300px;
    height: 50px;
    display:? table;
    border: 1px solid red;
.child { 
    display: table-cell;
    vertical-align: bottom;

Here is a live example: link demo

Storing JSON in database vs. having a new column for each key

Updated 4 June 2017

Given that this question/answer have gained some popularity, I figured it was worth an update.

When this question was originally posted, MySQL had no support for JSON data types and the support in PostgreSQL was in its infancy. Since 5.7, MySQL now supports a JSON data type (in a binary storage format), and PostgreSQL JSONB has matured significantly. Both products provide performant JSON types that can store arbitrary documents, including support for indexing specific keys of the JSON object.

However, I still stand by my original statement that your default preference, when using a relational database, should still be column-per-value. Relational databases are still built on the assumption of that the data within them will be fairly well normalized. The query planner has better optimization information when looking at columns than when looking at keys in a JSON document. Foreign keys can be created between columns (but not between keys in JSON documents). Importantly: if the majority of your schema is volatile enough to justify using JSON, you might want to at least consider if a relational database is the right choice.

That said, few applications are perfectly relational or document-oriented. Most applications have some mix of both. Here are some examples where I personally have found JSON useful in a relational database:

  • When storing email addresses and phone numbers for a contact, where storing them as values in a JSON array is much easier to manage than multiple separate tables

  • Saving arbitrary key/value user preferences (where the value can be boolean, textual, or numeric, and you don't want to have separate columns for different data types)

  • Storing configuration data that has no defined schema (if you're building Zapier, or IFTTT and need to store configuration data for each integration)

I'm sure there are others as well, but these are just a few quick examples.

Original Answer

If you really want to be able to add as many fields as you want with no limitation (other than an arbitrary document size limit), consider a NoSQL solution such as MongoDB.

For relational databases: use one column per value. Putting a JSON blob in a column makes it virtually impossible to query (and painfully slow when you actually find a query that works).

Relational databases take advantage of data types when indexing, and are intended to be implemented with a normalized structure.

As a side note: this isn't to say you should never store JSON in a relational database. If you're adding true metadata, or if your JSON is describing information that does not need to be queried and is only used for display, it may be overkill to create a separate column for all of the data points.

How do I Merge two Arrays in VBA?

Try this:

arr3 = Split(Join(arr1, ",") & "," & Join(arr2, ","), ",") 

mysql count group by having


SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

although that would not be the sum of all the movies, just how many have 4 genre's.

So maybe you want

    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total

What is a void pointer in C++?

A void* can point to anything (it's a raw pointer without any type info).

Access parent URL from iframe

Try it:


When you change you are in a iframe your host is "referrer".

Reset/remove CSS styles for element only

If you happen to be using sass in a build system, one way to do this that will work in all the major browsers is to wrap all your style imports with a :not() selector like so...

:not(.disable-all-styles) {
  @import 'my-sass-file';
  @import 'my-other-sass-file';

Then you can use the disable class on a container and the sub-content won't have any of your styles.

<div class="disable-all-styles">
  <p>Nothing in this div is affected by my sass styles.</p>

Of course all your styles will now be prepended with the :not() selector, so it's a little fugly, but works well.

A valid provisioning profile for this executable was not found... (again)

If none of above stated works then check for your device date, make sure your device date doesn't exceed profile expiry date i.e. not set to far future.

Is there a query language for JSON?

Here's some simple javascript libraries that will also do the trick:

  • Dollar Q is a nice lightweight library. It has a familiar feel to the chaining syntax made popular by jQuery and is only 373 SLOC.
  • SpahQL is a fully featured query language with a syntax similar to XPath (Homepage, Github
  • jFunk is an in progress query language, with a syntax similar to CSS/jQuery selectors. It looked promising, but hasn't had any development beyond its in initial commit.

  • (added 2014): the jq command line tool has a neat syntax, but unfortunately it is a c library. Example usage:

    < package.json jq '.dependencies | to_entries | .[] | select(.value | startswith("git")) | .key'

How to concatenate text from multiple rows into a single text string in SQL server?

To avoid null values you can use CONCAT()

SELECT @names = CONCAT(@names, ' ', name) 
FROM Names
select @names

Moment.js - tomorrow, today and yesterday


  • When the date is further away, use the standard moment().fromNow() functionality.
  • When the date is closer, show "today", "yesterday", "tomorrow", etc.


// call this function, passing-in your date
function dateToFromNowDaily( myDate ) {

    // get from-now for this date
    var fromNow = moment( myDate ).fromNow();

    // ensure the date is displayed with today and yesterday
    return moment( myDate ).calendar( null, {
        // when the date is closer, specify custom values
        lastWeek: '[Last] dddd',
        lastDay:  '[Yesterday]',
        sameDay:  '[Today]',
        nextDay:  '[Tomorrow]',
        nextWeek: 'dddd',
        // when the date is further away, use from-now functionality             
        sameElse: function () {
            return "[" + fromNow + "]";

NB: From version 2.14.0, the formats argument to the calendar function can be a callback, see

In OS X Lion, LANG is not set to UTF-8, how to fix it?

if you have zsh installed you can also update ~/.zprofile with

if [[ -z "$LC_ALL" ]]; then
  export LC_ALL='en_US.UTF-8'

and check the output using the locale cmd as show above

? locale                                                                                                                                           

Could not create work tree dir ''.: Permission denied

Change ownership and permissions folder

sudo chown -R username.www-data /var/www

sudo chmod -R +rwx /var/www

How do you join on the same table, twice, in mysql?

you'd use another join, something along these lines:

SELECT toD.dom_url AS ToURL, 
    fromD.dom_url AS FromUrl, 

FROM reviews AS rvw

LEFT JOIN domain AS toD 
    ON toD.Dom_ID = rvw.rev_dom_for

LEFT JOIN domain AS fromD 
    ON fromD.Dom_ID = rvw.rev_dom_from


All you're doing is joining in the table multiple times. Look at the query in the post: it selects the values from the Reviews tables (aliased as rvw), that table provides you 2 references to the Domain table (a FOR and a FROM).

At this point it's a simple matter to left join the Domain table to the Reviews table. Once (aliased as toD) for the FOR, and a second time (aliased as fromD) for the FROM.

Then in the SELECT list, you will select the DOM_URL fields from both LEFT JOINS of the DOMAIN table, referencing them by the table alias for each joined in reference to the Domains table, and alias them as the ToURL and FromUrl.

For more info about aliasing in SQL, read here.